Esempio n. 1
0
    private static IEnumerator TryLoadFromResources(OnlineMapsTile tile)
    {
        ResourceRequest resourceRequest = Resources.LoadAsync(tile.resourcesPath);

        yield return(resourceRequest);

        if (tile.map == null)
        {
            tile.MarkError();
            yield break;
        }

        Texture2D texture = resourceRequest.asset as Texture2D;

        if (texture != null)
        {
            texture.wrapMode = TextureWrapMode.Clamp;
            if (tile.map.control.resultIsTexture)
            {
                (tile as OnlineMapsRasterTile).ApplyTexture(texture);
                tile.map.buffer.ApplyTile(tile);
                OnlineMapsUtils.Destroy(texture);
            }
            else
            {
                tile.texture = texture;
                tile.status  = OnlineMapsTileStatus.loaded;
            }
            tile.MarkLoaded();
            tile.loadedFromResources = true;
            tile.map.Redraw();
        }
        else if (tile.map.source == OnlineMapsSource.Resources)
        {
            tile.MarkError();
        }
    }
Esempio n. 2
0
    private void OnGeocodeComplete(OnlineMapsWWW www)
    {
        if (www.hasError)
        {
            Debug.Log(www.error);
            return;
        }

        OnlineMapsJSONItem json      = OnlineMapsJSON.Parse(www.text);
        OnlineMapsJSONItem firstItem = json["candidates/0"];

        if (firstItem == null)
        {
            return;
        }

        OnlineMapsVector2d center = firstItem["location"].Deserialize <OnlineMapsVector2d>();

        OnlineMapsJSONItem extent = firstItem["extent"];
        double             xmin   = extent.V <double>("xmin"),
                           ymin = extent.V <double>("ymin"),
                           xmax = extent.V <double>("xmax"),
                           ymax = extent.V <double>("ymax");

        Vector2[] points =
        {
            new Vector2((float)xmin, (float)ymin),
            new Vector2((float)xmax, (float)ymax),
        };

        Vector2 c;
        int     zoom;

        OnlineMapsUtils.GetCenterPointAndZoom(points, out c, out zoom);

        OnlineMaps.instance.SetPositionAndZoom(center.x, center.y, zoom);
    }
    protected OnlineMapsGooglePlacesAutocomplete(string input, string key, string types, int offset, Vector2 lnglat, int radius, string language, string components)
    {
        _status = OnlineMapsQueryStatus.downloading;

        StringBuilder url = new StringBuilder("https://maps.googleapis.com/maps/api/place/autocomplete/xml?sensor=false");

        url.Append("&input=").Append(OnlineMapsWWW.EscapeURL(input));
        url.Append("&key=").Append(key);

        if (lnglat != default(Vector2))
        {
            url.AppendFormat("&location={0},{1}", lnglat.y, lnglat.x);
        }
        if (radius != -1)
        {
            url.Append("&radius=").Append(radius);
        }
        if (offset != -1)
        {
            url.Append("&offset=").Append(offset);
        }
        if (!string.IsNullOrEmpty(types))
        {
            url.Append("&types=").Append(types);
        }
        if (!string.IsNullOrEmpty(components))
        {
            url.Append("&components=").Append(components);
        }
        if (!string.IsNullOrEmpty(language))
        {
            url.Append("&language=").Append(language);
        }

        www             = OnlineMapsUtils.GetWWW(url);
        www.OnComplete += OnRequestComplete;
    }
Esempio n. 4
0
        private void OnUpdateLate()
        {
            OnlineMapsMarkerBase tooltipMarker = OnlineMapsTooltipDrawerBase.tooltipMarker;

            if (tooltipMarker == marker)
            {
                if (tooltip == null)
                {
                    tooltip = Instantiate(tooltipPrefab) as GameObject;
                    (tooltip.transform as RectTransform).SetParent(container.transform);
                }
                Vector2 screenPosition = OnlineMapsControlBase.instance.GetScreenPosition(marker.position);
                screenPosition.y += marker.height;
                Vector2 point;
                RectTransformUtility.ScreenPointToLocalPointInRectangle(container.transform as RectTransform, screenPosition, null, out point);
                (tooltip.transform as RectTransform).localPosition = point;
                tooltip.GetComponentInChildren <Text>().text       = marker.label;
            }
            else if (tooltip != null)
            {
                OnlineMapsUtils.Destroy(tooltip);
                tooltip = null;
            }
        }
    private OnlineMapsFindAutocomplete(string input, string key, string types, int offset, Vector2 latlng, int radius, string language, string components)
    {
        _status = OnlineMapsQueryStatus.downloading;

        string url = "https://maps.googleapis.com/maps/api/place/autocomplete/xml?sensor=false";

        url += "&input=" + input.Replace(" ", "+");
        url += "&key=" + key;

        if (latlng != default(Vector2))
        {
            url += string.Format("&location={0},{1}", latlng.y, latlng.x);
        }
        if (radius != -1)
        {
            url += "&radius=" + radius;
        }
        if (offset != -1)
        {
            url += "&offset=" + offset;
        }
        if (!string.IsNullOrEmpty(types))
        {
            url += "&types=" + types;
        }
        if (!string.IsNullOrEmpty(components))
        {
            url += "&components=" + components;
        }
        if (!string.IsNullOrEmpty(language))
        {
            url += "&language=" + language;
        }

        www = OnlineMapsUtils.GetWWW(url);
    }
Esempio n. 6
0
    private void ApplyNewTiles()
    {
        if (newTiles == null || newTiles.Count == 0)
        {
            return;
        }

        lock (newTiles)
        {
            foreach (OnlineMapsTile tile in newTiles)
            {
                if (disposed)
                {
                    return;
                }
                if (tile.status == OnlineMapsTileStatus.disposed)
                {
                    continue;
                }

#if !UNITY_WEBGL
                int counter = 20;
                while (tile.colors.Length < OnlineMapsUtils.sqrTileSize && counter > 0)
                {
                    OnlineMapsUtils.ThreadSleep(1);
                    counter--;
                }
#endif
                tile.ApplyColorsToChilds();
            }
            if (newTiles.Count > 0)
            {
                newTiles.Clear();
            }
        }
    }
    private void StartNextAction()
    {
#if !UNITY_WEBGL
        while (isAlive)
        {
            bool actionInvoked = false;
            lock (threadActions)
            {
                if (threadActions.Count > 0)
                {
                    Action action = threadActions[0];
                    threadActions.RemoveAt(0);
                    action();
                    actionInvoked = true;
                }
            }
            if (!actionInvoked)
            {
                OnlineMapsUtils.ThreadSleep(1);
            }
        }
        threadActions = null;
#endif
    }
Esempio n. 8
0
    void OnDistanceChange(Vector2 userPoint)
    {
        if (currentData == null)
        {
            return;
        }

        Vector2 markerCoordinates = new Vector2((float)currentData.Longitude_User, (float)currentData.Latitude_User);
        Vector2 userCoordinares   = userPoint;

        // Calculate the distance in km between locations.
        distanceBetweenPOI = OnlineMapsUtils.DistanceBetweenPoints(userCoordinares, markerCoordinates).magnitude * 1000;

        if (distanceBetweenPOI > 1000)
        {
            GoadRange.text = string.Format("距離 {0} km", (distanceBetweenPOI / 1000).ToString("0.00"));
        }
        else
        {
            GoadRange.text = string.Format("距離 {0} m", distanceBetweenPOI.ToString("0.0"));
        }

        //GoadRange.text = "距離 " + distanceBetweenPOI.ToString("0.0") + " m";
    }
Esempio n. 9
0
    public OnlineMapsTile(int x, int y, int zoom, OnlineMaps api, bool isMapTile = true)
    {
        int maxX = 2 << (zoom - 1);

        if (x < 0)
        {
            x += maxX;
        }
        else if (x >= maxX)
        {
            x -= maxX;
        }

        this.x    = x;
        this.y    = y;
        this.zoom = zoom;

        OnlineMapsTile.api = api;
        this.isMapTile     = isMapTile;

        provider = api.provider;
        type     = api.type;
        labels   = api.labels;
        language = api.language;

        topLeft        = OnlineMapsUtils.TileToLatLong(x, y, zoom);
        bottomRight    = OnlineMapsUtils.TileToLatLong(x + 1, y + 1, zoom);
        globalPosition = Vector2.Lerp(topLeft, bottomRight, 0.5f);

        trafficURL = String.Format("https://mts0.google.com/vt?pb=!1m4!1m3!1i{0}!2i{1}!3i{2}!2m3!1e0!2sm!3i301114286!2m6!1e2!2straffic!4m2!1soffset_polylines!2s0!5i1!2m12!1e2!2spsm!4m2!1sgid!2sl0t0vMkIqfb3hBb090479A!4m2!1ssp!2s1!5i1!8m2!13m1!14b1!3m25!2sru-RU!3sUS!5e18!12m1!1e50!12m3!1e37!2m1!1ssmartmaps!12m5!1e14!2m1!1ssolid!2m1!1soffset_polylines!12m4!1e52!2m2!1sentity_class!2s0S!12m4!1e26!2m2!1sstyles!2zcy5lOmx8cC52Om9mZixzLnQ6MXxwLnY6b2ZmLHMudDozfHAudjpvZmY!4e0", zoom, x, y);

        if (isMapTile)
        {
            tiles.Add(this);
        }
    }
Esempio n. 10
0
    /// <summary>
    /// Initializes this object.
    /// </summary>
    /// <param name="parent">
    /// The parent transform.
    /// </param>
    public void Init(Transform parent)
    {
        if (instance != null)
        {
            OnlineMapsUtils.Destroy(instance);
        }

        if (prefab == null)
        {
            instance = GameObject.CreatePrimitive(PrimitiveType.Cube);
            instance.transform.localScale = Vector3.one;
        }
        else
        {
            instance = Object.Instantiate(prefab) as GameObject;
        }

        _prefab = prefab;

        instance.transform.parent        = parent;
        instance.transform.localRotation = Quaternion.Euler(0, _rotationY, 0);

        instance.layer = parent.gameObject.layer;
        instance.AddComponent <OnlineMapsMarker3DInstance>().marker = this;
        visible = false;
        inited  = true;

        control = map.control as OnlineMapsControlBase3D;

        Update();

        if (OnInitComplete != null)
        {
            OnInitComplete(this);
        }
    }
Esempio n. 11
0
        /// <summary>
        /// This method is called when a response is received.
        /// </summary>
        /// <param name="s">Response string</param>
        private void OnComplete(string s)
        {
            // Trying to get an array of results.
            OnlineMapsGooglePlacesResult[] results = OnlineMapsGooglePlaces.GetResults(s);

            // If there is no result
            if (results == null)
            {
                Debug.Log("Error");
                Debug.Log(s);
                return;
            }

            List <OnlineMapsMarker> markers = new List <OnlineMapsMarker>();

            foreach (OnlineMapsGooglePlacesResult result in results)
            {
                // Log name and location of each result.
                Debug.Log(result.name);
                Debug.Log(result.location);

                // Create a marker at the location of the result.
                OnlineMapsMarker marker = OnlineMaps.instance.AddMarker(result.location, result.name);
                markers.Add(marker);
            }

            // Get center point and best zoom for markers
            Vector2 center;
            int     zoom;

            OnlineMapsUtils.GetCenterPointAndZoom(markers.ToArray(), out center, out zoom);

            // Set map position and zoom.
            OnlineMaps.instance.position = center;
            OnlineMaps.instance.zoom     = zoom + 1;
        }
Esempio n. 12
0
    private void SetMarkerToBuffer(OnlineMapsMarker marker, OnlineMapsVector2i bufferPosition, int bufferZoom, OnlineMapsVector2i frontBufferPosition, double sx, double sy, double ex, double ey)
    {
        const int s = OnlineMapsUtils.tileSize;

        double mx, my;

        marker.GetPosition(out mx, out my);

        int maxX = 1 << bufferZoom;

        bool isEntireWorld       = map.buffer.renderState.width == maxX * s;
        bool isBiggestThatBuffer = map.buffer.renderState.width + 512 == maxX * s;

        if (isEntireWorld || isBiggestThatBuffer)
        {
        }
        else if (!(((mx > sx && mx < ex) || (mx + 360 > sx && mx + 360 < ex) || (mx - 360 > sx && mx - 360 < ex)) &&
                   my < sy && my > ey))
        {
            return;
        }

#if !UNITY_WEBGL
        int maxCount = 20;
        while (marker.locked && maxCount > 0)
        {
            OnlineMapsUtils.ThreadSleep(1);
            maxCount--;
        }
#endif

        marker.locked = true;

        double px, py;
        map.projection.CoordinatesToTile(mx, my, bufferZoom, out px, out py);
        px -= bufferPosition.x;
        py -= bufferPosition.y;

        if (isEntireWorld)
        {
            double tx, ty;
            map.projection.CoordinatesToTile(map.buffer.renderState.longitude, map.buffer.renderState.latitude, bufferZoom, out tx, out ty);
            tx -= map.buffer.renderState.width / s / 2;

            if (px < tx)
            {
                px += maxX;
            }
        }
        else
        {
            if (px < 0)
            {
                px += maxX;
            }
            else if (px > maxX)
            {
                px -= maxX;
            }
        }

        float zoomCoof = map.buffer.renderState.zoomCoof;

        px *= s;
        py *= s;

        int ipx = (int)((px - frontBufferPosition.x) / zoomCoof);
        int ipy = (int)((py - frontBufferPosition.y) / zoomCoof);

        OnlineMapsVector2i ip = marker.GetAlignedPosition(ipx, ipy);

        Color32[] markerColors = marker.colors;
        if (markerColors == null || markerColors.Length == 0)
        {
            return;
        }

        int markerWidth  = marker.width;
        int markerHeight = marker.height;

        OnlineMapsBuffer buffer = map.buffer;

        for (int y = 0; y < marker.height; y++)
        {
            if (ip.y + y < 0 || ip.y + y >= map.height)
            {
                continue;
            }

            int cy = (markerHeight - y - 1) * markerWidth;

            for (int x = 0; x < marker.width; x++)
            {
                if (ip.x + x < 0 || ip.x + x >= map.buffer.renderState.width)
                {
                    continue;
                }

                try
                {
                    buffer.SetColorToBuffer(markerColors[cy + x], ip, y, x);
                }
                catch
                {
                }
            }
        }

        if (isEntireWorld)
        {
            ip.x -= (int)(buffer.renderState.width / zoomCoof);
            for (int y = 0; y < marker.height; y++)
            {
                if (ip.y + y < 0 || ip.y + y >= map.height)
                {
                    continue;
                }

                int cy = (markerHeight - y - 1) * markerWidth;

                for (int x = 0; x < marker.width; x++)
                {
                    if (ip.x + x < 0 || ip.x + x >= map.buffer.renderState.width)
                    {
                        continue;
                    }

                    try
                    {
                        buffer.SetColorToBuffer(markerColors[cy + x], ip, y, x);
                    }
                    catch
                    {
                    }
                }
            }

            ip.x += (int)(buffer.renderState.width * 2 / zoomCoof);
            for (int y = 0; y < marker.height; y++)
            {
                if (ip.y + y < 0 || ip.y + y >= map.height)
                {
                    continue;
                }

                int cy = (markerHeight - y - 1) * markerWidth;

                for (int x = 0; x < marker.width; x++)
                {
                    if (ip.x + x < 0 || ip.x + x >= map.buffer.renderState.width)
                    {
                        continue;
                    }

                    try
                    {
                        buffer.SetColorToBuffer(markerColors[cy + x], ip, y, x);
                    }
                    catch
                    {
                    }
                }
            }
        }

        marker.locked = false;
    }
    protected void FillPoly(Color32[] buffer, Vector2 bufferPosition, int bufferWidth, int bufferHeight, float zoom, IEnumerable points, Color32 color, bool invertY)
    {
        if (color.a == 0)
        {
            return;
        }
        float alpha = color.a / 255f;

        double minX, maxX, minY, maxY;

        double[] bufferPoints = GetBufferPoints(bufferPosition, zoom, points, out minX, out maxX, out minY, out maxY);

        if (maxX < 0 || minX > bufferWidth || maxY < 0 || minY > bufferHeight)
        {
            return;
        }

        double stX = minX;

        if (stX < 0)
        {
            stX = 0;
        }
        else if (stX > bufferWidth)
        {
            stX = bufferWidth;
        }

        double stY = minY;

        if (stY < 0)
        {
            stY = 0;
        }
        else if (stY > bufferHeight)
        {
            stY = bufferHeight;
        }

        double endX = maxX;

        if (endX < 0)
        {
            stX = 0;
        }
        else if (endX > bufferWidth)
        {
            endX = bufferWidth;
        }

        double endY = maxY;

        if (endY < 0)
        {
            endY = 0;
        }
        else if (endY > bufferHeight)
        {
            endY = bufferHeight;
        }

        int lengthX = (int)Math.Round(endX - stX);
        int lengthY = (int)Math.Round(endY - stY);

        Color32 clr = new Color32(color.r, color.g, color.b, 255);

        const int blockSize   = 5;
        int       blockCountX = lengthX / blockSize + (lengthX % blockSize == 0 ? 0 : 1);
        int       blockCountY = lengthY / blockSize + (lengthY % blockSize == 0 ? 0 : 1);

        byte clrR = clr.r;
        byte clrG = clr.g;
        byte clrB = clr.b;

        int istx = (int)Math.Round(stX);
        int isty = (int)Math.Round(stY);

        for (int by = 0; by < blockCountY; by++)
        {
            int    byp     = by * blockSize;
            double bufferY = byp + stY;
            int    iby     = byp + isty;

            for (int bx = 0; bx < blockCountX; bx++)
            {
                int    bxp     = bx * blockSize;
                double bufferX = bxp + stX;
                int    ibx     = bxp + istx;

                bool p1 = OnlineMapsUtils.IsPointInPolygon(bufferPoints, bufferX, bufferY);
                bool p2 = OnlineMapsUtils.IsPointInPolygon(bufferPoints, bufferX + blockSize - 1, bufferY);
                bool p3 = OnlineMapsUtils.IsPointInPolygon(bufferPoints, bufferX + blockSize - 1, bufferY + blockSize - 1);
                bool p4 = OnlineMapsUtils.IsPointInPolygon(bufferPoints, bufferX, bufferY + blockSize - 1);

                if (p1 && p2 && p3 && p4)
                {
                    for (int y = 0; y < blockSize; y++)
                    {
                        if (byp + y >= lengthY)
                        {
                            break;
                        }
                        int cby = iby + y;
                        if (!invertY)
                        {
                            cby = bufferHeight - cby - 1;
                        }
                        int byi = cby * bufferWidth + ibx;

                        for (int x = 0; x < blockSize; x++)
                        {
                            if (bxp + x >= lengthX)
                            {
                                break;
                            }

                            int bufferIndex = byi + x;

                            Color32 a = buffer[bufferIndex];
                            a.r = (byte)(a.r + (clrR - a.r) * alpha);
                            a.g = (byte)(a.g + (clrG - a.g) * alpha);
                            a.b = (byte)(a.b + (clrB - a.b) * alpha);
                            a.a = (byte)(a.a + (255 - a.a) * alpha);
                            buffer[bufferIndex] = a;
                        }
                    }
                }
                else if (!p1 && !p2 && !p3 && !p4)
                {
                }
                else
                {
                    for (int y = 0; y < blockSize; y++)
                    {
                        if (byp + y >= lengthY)
                        {
                            break;
                        }
                        int cby = iby + y;
                        if (!invertY)
                        {
                            cby = bufferHeight - cby - 1;
                        }
                        int byi = cby * bufferWidth + ibx;

                        for (int x = 0; x < blockSize; x++)
                        {
                            if (bxp + x >= lengthX)
                            {
                                break;
                            }

                            if (OnlineMapsUtils.IsPointInPolygon(bufferPoints, bufferX + x, bufferY + y))
                            {
                                int     bufferIndex = byi + x;
                                Color32 a           = buffer[bufferIndex];
                                a.r = (byte)(a.r + (clrR - a.r) * alpha);
                                a.g = (byte)(a.g + (clrG - a.g) * alpha);
                                a.b = (byte)(a.b + (clrB - a.b) * alpha);
                                a.a = (byte)(a.a + (255 - a.a) * alpha);
                                buffer[bufferIndex] = a;
                            }
                        }
                    }
                }
            }
        }
    }
    /// <summary>
    /// Updates billboard markers.
    /// </summary>
    protected void UpdateMarkersBillboard()
    {
        if (markersGameObject == null)
        {
            InitMarkersMesh();
        }
        if (markerBillboards == null)
        {
            markerBillboards = new Dictionary <int, OnlineMapsMarkerBillboard>();
        }

        double tlx, tly, brx, bry;

        api.GetTopLeftPosition(out tlx, out tly);
        api.GetBottomRightPosition(out brx, out bry);
        if (brx < tlx)
        {
            brx += 360;
        }

        int maxX = (2 << api.buffer.apiZoom) / 2;

        double px, py;

        OnlineMapsUtils.LatLongToTiled(tlx, tly, api.zoom, out px, out py);

        float yScale = GetBestElevationYScale(tlx, tly, brx, bry);

        Bounds  mapBounds      = cl.bounds;
        Vector3 positionOffset = transform.position - mapBounds.min;
        Vector3 size           = mapBounds.size;

        size = transform.rotation * size;
        if (api.target == OnlineMapsTarget.tileset)
        {
            positionOffset.x -= size.x;
        }

        foreach (KeyValuePair <int, OnlineMapsMarkerBillboard> billboard in markerBillboards)
        {
            billboard.Value.used = false;
        }

        foreach (OnlineMapsMarker marker in api.markers)
        {
            if (!marker.enabled || !marker.range.InRange(api.zoom))
            {
                continue;
            }
            float mx = marker.position.x;
            if (!(((mx > tlx && mx < brx) || (mx + 360 > tlx && mx + 360 < brx) ||
                   (mx - 360 > tlx && mx - 360 < brx)) &&
                  marker.position.y < tly && marker.position.y > bry))
            {
                continue;
            }

            int markerHashCode = marker.GetHashCode();
            OnlineMapsMarkerBillboard markerBillboard = null;

            if (!markerBillboards.ContainsKey(markerHashCode))
            {
                markerBillboard = OnlineMapsMarkerBillboard.Create(marker);
                markerBillboard.transform.parent = markersGameObject.transform;

                markerBillboards.Add(markerHashCode, markerBillboard);
            }
            else
            {
                markerBillboard = markerBillboards[markerHashCode];
            }

            float sx = size.x / api.width * marker2DSize * marker.scale;
            float sz = size.z / api.height * marker2DSize * marker.scale;
            float s  = Mathf.Max(sx, sz);
            markerBillboard.transform.localScale = new Vector3(-s, s, s);

            Vector2 p = OnlineMapsUtils.LatLongToTilef(marker.position, api.buffer.apiZoom);

            p.x  = Mathf.Repeat(p.x - (float)px, maxX);
            p.y -= (float)py;

            float x = -p.x / api.width * OnlineMapsUtils.tileSize * size.x + positionOffset.x;
            float z = p.y / api.height * OnlineMapsUtils.tileSize * size.z - positionOffset.z;

            float y = GetElevationValue(x, z, yScale, tlx, tly, brx, bry);

            markerBillboard.transform.localPosition = transform.rotation * new Vector3(x, y, z);
            markerBillboard.used = true;
        }

        List <int> keysForRemove = new List <int>();

        foreach (KeyValuePair <int, OnlineMapsMarkerBillboard> billboard in markerBillboards)
        {
            if (!billboard.Value.used)
            {
                billboard.Value.Dispose();
                keysForRemove.Add(billboard.Key);
            }
        }

        foreach (int key in keysForRemove)
        {
            markerBillboards.Remove(key);
        }
    }
 private OnlineMapsWhat3Words(StringBuilder url)
 {
     _status         = OnlineMapsQueryStatus.downloading;
     www             = OnlineMapsUtils.GetWWW(url);
     www.OnComplete += OnRequestComplete;
 }
 public static List <Vector2> DecodePolylinePoints(string encodedPoints)
 {
     return(OnlineMapsUtils.DecodePolylinePoints(encodedPoints));
 }
    public override void DrawOnTileset(OnlineMapsTileSetControl control, int index)
    {
        base.DrawOnTileset(control, index);

        if (!visible)
        {
            active = false;
            return;
        }

        InitMesh(control, "Poly", borderColor, backgroundColor);
        InitLineMesh(points, control, ref vertices, ref normals, ref triangles, ref uv, borderWidth, true, false);

        mesh.Clear();

        if (vertices.Count < 4)
        {
            return;
        }

        active = true;

        Vector3 v1 = (vertices[0] + vertices[3]) / 2;
        Vector3 v2 = (vertices[vertices.Count - 3] + vertices[vertices.Count - 2]) / 2;

        if (Math.Abs((v1 - v2).magnitude) < float.Epsilon)
        {
            vertices[0] = vertices[vertices.Count - 3] = (vertices[0] + vertices[vertices.Count - 3]) / 2;
            vertices[3] = vertices[vertices.Count - 2] = (vertices[3] + vertices[vertices.Count - 2]) / 2;
        }

        int[] fillTriangles = null;

        if (!checkMapBoundaries && backgroundColor.a > 0 && vertices.Count > 0)
        {
            float l1 = 0;
            float l2 = 0;

            for (int i = 0; i < vertices.Count / 4 - 1; i++)
            {
                Vector3 p11 = vertices[i * 4];
                Vector3 p12 = vertices[(i + 1) * 4];

                Vector3 p21 = vertices[i * 4 + 3];
                Vector3 p22 = vertices[(i + 1) * 4 + 3];

                l1 += (p11 - p12).magnitude;
                l2 += (p21 - p22).magnitude;
            }

            bool side = l2 < l1;
            int  off1 = side ? 3 : 0;
            int  off2 = side ? 2 : 1;

            Vector2        lastPoint       = Vector2.zero;
            List <int>     internalIndices = new List <int>(vertices.Count / 4);
            List <Vector2> internalPoints  = new List <Vector2>(vertices.Count / 4);
            for (int i = 0; i < vertices.Count / 4; i++)
            {
                Vector3 p  = vertices[i * 4 + off1];
                Vector2 p2 = new Vector2(p.x, p.z);
                if (i > 0)
                {
                    if ((lastPoint - p2).magnitude > borderWidth / 2)
                    {
                        internalIndices.Add(i * 4 + off1);
                        internalPoints.Add(p2);
                        lastPoint = p2;
                    }
                }
                else
                {
                    internalIndices.Add(i * 4 + off1);
                    internalPoints.Add(p2);
                    lastPoint = p2;
                }
                p  = vertices[i * 4 + off2];
                p2 = new Vector2(p.x, p.z);
                if ((lastPoint - p2).magnitude > borderWidth / 2)
                {
                    internalIndices.Add(i * 4 + off2);
                    internalPoints.Add(p2);
                    lastPoint = p2;
                }
            }

            if (internalPoints[0] == internalPoints[internalPoints.Count - 1])
            {
                internalPoints.RemoveAt(internalPoints.Count - 1);
            }

            fillTriangles = OnlineMapsUtils.Triangulate(internalPoints).ToArray();

            if (fillTriangles.Length > 2)
            {
                for (int i = 0; i < fillTriangles.Length; i++)
                {
                    fillTriangles[i] = internalIndices[fillTriangles[i]];
                }

                Vector3 side1 = vertices[fillTriangles[1]] - vertices[fillTriangles[0]];
                Vector3 side2 = vertices[fillTriangles[2]] - vertices[fillTriangles[0]];
                Vector3 perp  = Vector3.Cross(side1, side2);

                bool reversed = perp.y < 0;
                if (reversed)
                {
                    fillTriangles = fillTriangles.Reverse().ToArray();
                }
            }
            else
            {
                fillTriangles = null;
            }
        }

        mesh.subMeshCount = 2;

#if UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1
        mesh.vertices = vertices.ToArray();
        mesh.normals  = normals.ToArray();
        mesh.uv       = uv.ToArray();
#else
        mesh.SetVertices(vertices);
        mesh.SetNormals(normals);
        mesh.SetUVs(0, uv);
#endif

        mesh.SetTriangles(triangles.ToArray(), 0);
        if (fillTriangles != null)
        {
            mesh.SetTriangles(fillTriangles.ToArray(), 1);
        }

        UpdateMaterialsQuote(control, index);
    }
    private OnlineMapsGoogleDirections(Params p)
    {
        _status = OnlineMapsQueryStatus.downloading;

        StringBuilder url = new StringBuilder();

        url.Append("https://maps.googleapis.com/maps/api/directions/xml?sensor=false");
        url.Append("&origin=");

        if (p.origin is string)
        {
            url.Append(OnlineMapsWWW.EscapeURL(p.origin as string));
        }
        else if (p.origin is Vector2)
        {
            Vector2 o = (Vector2)p.origin;
            url.Append(o.y).Append(",").Append(o.x);
        }
        else
        {
            throw new Exception("Origin must be string or Vector2.");
        }

        url.Append("&destination=");

        if (p.destination is string)
        {
            url.Append(OnlineMapsWWW.EscapeURL(p.destination as string));
        }
        else if (p.destination is Vector2)
        {
            Vector2 d = (Vector2)p.destination;
            url.Append(d.y).Append(",").Append(d.x);
        }
        else
        {
            throw new Exception("Destination must be string or Vector2.");
        }

        if (p.mode.HasValue && p.mode.Value != Mode.driving)
        {
            url.Append("&mode=").Append(Enum.GetName(typeof(Mode), p.mode.Value));
        }
        if (p.waypoints != null)
        {
            StringBuilder waypointStr    = new StringBuilder();
            bool          isFirst        = true;
            int           countWaypoints = 0;
            foreach (object w in p.waypoints)
            {
                if (countWaypoints >= 8)
                {
                    Debug.LogWarning("The maximum number of waypoints is 8.");
                    break;
                }

                if (!isFirst)
                {
                    waypointStr = waypointStr.Append("|");
                }

                if (w is string)
                {
                    waypointStr.Append(OnlineMapsWWW.EscapeURL(w as string));
                }
                else if (w is Vector2)
                {
                    Vector2 v = (Vector2)w;
                    waypointStr.Append(v.y).Append(",").Append(v.x);
                }
                else
                {
                    throw new Exception("Waypoints must be string or Vector2.");
                }

                countWaypoints++;

                isFirst = false;
            }

            if (countWaypoints > 0)
            {
                url.Append("&waypoints=optimize:true|").Append(waypointStr);
            }
        }
        if (p.alternatives)
        {
            url.Append("&alternatives=true");
        }
        if (p.avoid.HasValue && p.avoid.Value != Avoid.none)
        {
            url.Append("&avoid=").Append(Enum.GetName(typeof(Avoid), p.avoid.Value));
        }
        if (p.units.HasValue && p.units.Value != Units.metric)
        {
            url.Append("&units=").Append(Enum.GetName(typeof(Units), p.units.Value));
        }
        if (!string.IsNullOrEmpty(p.region))
        {
            url.Append("&region=").Append(p.region);
        }
        if (p.departure_time != null)
        {
            url.Append("&departure_time=").Append(p.departure_time);
        }
        if (p.arrival_time.HasValue && p.arrival_time.Value > 0)
        {
            url.Append("&arrival_time=").Append(p.arrival_time.Value);
        }
        if (!string.IsNullOrEmpty(p.language))
        {
            url.Append("&language=").Append(p.language);
        }
        if (!string.IsNullOrEmpty(p.key))
        {
            url.Append("&key=").Append(p.key);
        }
        if (p.traffic_model.HasValue && p.traffic_model.Value != TrafficModel.bestGuess)
        {
            url.Append("&traffic_model=").Append(Enum.GetName(typeof(TrafficModel), p.traffic_model.Value));
        }
        if (p.transit_mode.HasValue)
        {
            OnlineMapsUtils.GetValuesFromEnum(url, "transit_mode", typeof(TransitMode), (int)p.transit_mode.Value);
        }
        if (p.transit_routing_preference.HasValue)
        {
            url.Append("&transit_routing_preference=").Append(Enum.GetName(typeof(TransitRoutingPreference), p.transit_routing_preference.Value));
        }

        www             = OnlineMapsUtils.GetWWW(url);
        www.OnComplete += OnRequestComplete;
    }
    /// <summary>
    /// Updates billboard markers.
    /// </summary>
    protected void UpdateMarkersBillboard()
    {
        if (markersGameObjects == null)
        {
            InitMarkersMesh(0);
        }
        if (markerBillboards == null)
        {
            markerBillboards = new Dictionary <int, OnlineMapsMarkerBillboard>();
        }
        //  Debug.Log("update " + markerBillboards.Count());
        double tlx, tly, brx, bry;

        map.GetCorners(out tlx, out tly, out brx, out bry);
        if (brx < tlx)
        {
            brx += 360;
        }

        int maxX = (2 << map.buffer.apiZoom) / 2;

        double px, py;

        map.projection.CoordinatesToTile(tlx, tly, map.zoom, out px, out py);

        float yScale = GetBestElevationYScale(tlx, tly, brx, bry);

        Bounds  mapBounds      = cl.bounds;
        Vector3 positionOffset = transform.position - mapBounds.min;
        Vector3 size           = mapBounds.size;

        size = transform.rotation * size;
        if (map.target == OnlineMapsTarget.tileset)
        {
            positionOffset.x -= size.x;
        }

        foreach (KeyValuePair <int, OnlineMapsMarkerBillboard> billboard in markerBillboards)
        {
            billboard.Value.used = false;
        }

        foreach (OnlineMapsMarker marker in map.markers)
        {
            //   Debug.Log("mảk");
            if (!marker.enabled || !marker.range.InRange(map.zoom))
            {
                continue;
            }
            //    Debug.Log("mảk enable");
            double mx, my;
            marker.GetPosition(out mx, out my);

            if (!(((mx > tlx && mx < brx) || (mx + 360 > tlx && mx + 360 < brx) ||
                   (mx - 360 > tlx && mx - 360 < brx)) &&
                  my < tly && my > bry))
            {
                continue;
            }

            int markerHashCode = marker.GetHashCode();
            OnlineMapsMarkerBillboard markerBillboard;

            if (!markerBillboards.ContainsKey(markerHashCode))
            {
                //  Debug.Log("mảk hashcode");
                markerBillboard = OnlineMapsMarkerBillboard.Create(marker);
                markerBillboard.transform.parent = markersGameObjects[0].transform;
                markerBillboard.gameObject.layer = markersGameObjects[0].layer;

                markerBillboards.Add(markerHashCode, markerBillboard);
            }
            else
            {
                markerBillboard = markerBillboards[markerHashCode];
            }

            if (markerBillboard == null)
            {
                continue;
            }

            float sx = size.x / map.width * marker2DSize * marker.scale;
            float sz = size.z / map.height * marker2DSize * marker.scale;
            float s  = Mathf.Max(sx, sz);

#if !UNITY_4_6 && !UNITY_4_7 && !UNITY_5_0 && !UNITY_5_1 && !UNITY_5_2
            markerBillboard.transform.localScale = new Vector3(s, s, s);
#else
            markerBillboard.transform.localScale = new Vector3(-s, s, s);
#endif

            double mpx, mpy;
            map.projection.CoordinatesToTile(mx, my, map.buffer.apiZoom, out mpx, out mpy);

            mpx  = OnlineMapsUtils.Repeat(mpx - px, 0, maxX);
            mpy -= py;

            float x = (float)(-mpx / map.width * OnlineMapsUtils.tileSize * size.x + positionOffset.x);
            float z = (float)(mpy / map.height * OnlineMapsUtils.tileSize * size.z - positionOffset.z);

            float y = GetElevationValue(x, z, yScale, tlx, tly, brx, bry);

            markerBillboard.transform.localPosition = transform.rotation * new Vector3(x, y, z);
            markerBillboard.used = true;
        }

        List <int> keysForRemove = new List <int>();

        foreach (KeyValuePair <int, OnlineMapsMarkerBillboard> billboard in markerBillboards)
        {
            if (!billboard.Value.used)
            {
                billboard.Value.Dispose();
                keysForRemove.Add(billboard.Key);
            }
        }

        foreach (int key in keysForRemove)
        {
            markerBillboards.Remove(key);
        }
    }
Esempio n. 20
0
    private void Destroy()
    {
        lock (tiles)
        {
            tiles.Remove(this);
        }

        if (texture != null)
        {
            OnlineMapsUtils.DestroyImmediate(texture);
        }
        if (trafficTexture != null)
        {
            OnlineMapsUtils.DestroyImmediate(trafficTexture);
        }
        if (overlayBackTexture != null)
        {
            OnlineMapsUtils.DestroyImmediate(overlayBackTexture);
        }
        if (overlayFrontTexture != null)
        {
            OnlineMapsUtils.DestroyImmediate(overlayFrontTexture);
        }

        texture             = null;
        trafficTexture      = null;
        overlayBackTexture  = null;
        overlayFrontTexture = null;
        customData          = null;

        _colors     = null;
        _url        = null;
        labelData   = null;
        labelColors = null;
        data        = null;

        OnSetColor = null;
        if (hasChilds)
        {
            foreach (OnlineMapsTile child in childs)
            {
                if (child != null)
                {
                    child.parent = null;
                }
            }
        }
        if (parent != null)
        {
            if (parent.childs != null)
            {
                for (int i = 0; i < 4; i++)
                {
                    if (parent.childs[i] == this)
                    {
                        parent.childs[i] = null;
                        break;
                    }
                }
            }
        }
        parent    = null;
        childs    = null;
        hasChilds = false;
        hasColors = false;

        OnDisposed = null;
        OnSetColor = null;
    }
Esempio n. 21
0
        private void GroupMarkers()
        {
            List <MarkerGroup> groups = new List <MarkerGroup>();

            for (int zoom = OnlineMaps.MAXZOOM; zoom >= OnlineMaps.MINZOOM; zoom--)
            {
                List <OnlineMapsMarker> ms = markers.Select(m => m).ToList();

                for (int j = 0; j < ms.Count - 1; j++)
                {
                    OnlineMapsMarker marker = ms[j];
                    MarkerGroup      group = null;
                    double           px, py;
                    marker.GetPosition(out px, out py);
                    OnlineMaps.instance.projection.CoordinatesToTile(px, py, zoom, out px, out py);

                    int k = j + 1;

                    while (k < ms.Count)
                    {
                        OnlineMapsMarker marker2 = ms[k];

                        double p2x, p2y;
                        marker2.GetPosition(out p2x, out p2y);
                        OnlineMaps.instance.projection.CoordinatesToTile(p2x, p2y, zoom, out p2x, out p2y);

                        if (OnlineMapsUtils.Magnitude(px, py, p2x, p2y) < distance)
                        {
                            if (group == null)
                            {
                                group = new MarkerGroup(zoom, groupTexture);
                                groups.Add(group);
                                group.Add(marker);
                                if (Math.Abs(marker.range.min - OnlineMaps.MINZOOM) < float.Epsilon)
                                {
                                    marker.range.min = zoom + 1;
                                }
                            }

                            group.Add(marker2);
                            if (Math.Abs(marker2.range.min - OnlineMaps.MINZOOM) < float.Epsilon)
                            {
                                marker2.range.min = zoom + 1;
                            }
                            ms.RemoveAt(k);
                            px = group.tilePositionX;
                            py = group.tilePositionY;
                        }
                        else
                        {
                            k++;
                        }
                    }
                }
            }

            foreach (MarkerGroup g in groups)
            {
                g.Apply(font);
            }
        }
Esempio n. 22
0
    /// <summary>
    /// Creates a new building, based on Open Street Map.
    /// </summary>
    /// <param name="container">Reference to OnlineMapsBuildings.</param>
    /// <param name="way">Way of building.</param>
    /// <param name="nodes">Nodes obtained from Open Street Maps.</param>
    /// <returns>Building instance.</returns>
    public static OnlineMapsBuildingBase Create(OnlineMapsBuildings container, OnlineMapsOSMWay way, Dictionary <string, OnlineMapsOSMNode> nodes)
    {
        if (CheckIgnoredBuildings(way))
        {
            return(null);
        }

        if (usedNodes == null)
        {
            usedNodes = new List <OnlineMapsOSMNode>(30);
        }
        else
        {
            usedNodes.Clear();
        }

        way.GetNodes(nodes, usedNodes);
        List <Vector3> points = GetLocalPoints(usedNodes);

        if (points.Count < 3)
        {
            return(null);
        }
        if (points[0] == points[points.Count - 1])
        {
            points.RemoveAt(points.Count - 1);
        }
        if (points.Count < 3)
        {
            return(null);
        }

        for (int i = 0; i < points.Count; i++)
        {
            int prev = i - 1;
            if (prev < 0)
            {
                prev = points.Count - 1;
            }

            int next = i + 1;
            if (next >= points.Count)
            {
                next = 0;
            }

            float a1 = OnlineMapsUtils.Angle2D(points[prev], points[i]);
            float a2 = OnlineMapsUtils.Angle2D(points[i], points[next]);

            if (Mathf.Abs(a1 - a2) < 5)
            {
                points.RemoveAt(i);
                i--;
            }
        }

        if (points.Count < 3)
        {
            return(null);
        }

        Vector4 cp = new Vector4(float.MaxValue, float.MaxValue, float.MinValue, float.MinValue);

        for (int i = 0; i < points.Count; i++)
        {
            Vector3 point = points[i];
            if (point.x < cp.x)
            {
                cp.x = point.x;
            }
            if (point.z < cp.y)
            {
                cp.y = point.z;
            }
            if (point.x > cp.z)
            {
                cp.z = point.x;
            }
            if (point.z > cp.w)
            {
                cp.w = point.z;
            }
        }

        Vector3 centerPoint = new Vector3((cp.z + cp.x) / 2, 0, (cp.y + cp.w) / 2);

        for (int i = 0; i < points.Count; i++)
        {
            points[i] -= centerPoint;
        }

        bool generateWall = true;

        if (way.HasTagKey("building"))
        {
            string buildingType = way.GetTagValue("building");
            if (buildingType == "roof")
            {
                generateWall = false;
            }
        }

        float baseHeight = 15;
        float roofHeight = 0;

        OnlineMapsBuildingMaterial material = GetRandomMaterial(container);
        Material wallMaterial;
        Material roofMaterial;
        Vector2  scale = Vector2.one;

        if (defaultShader == null)
        {
            defaultShader = Shader.Find("Diffuse");
        }

        if (material != null)
        {
            if (material.wall != null)
            {
                wallMaterial = Instantiate(material.wall) as Material;
            }
            else
            {
                wallMaterial = new Material(defaultShader);
            }

            if (material.roof != null)
            {
                roofMaterial = Instantiate(material.roof) as Material;
            }
            else
            {
                roofMaterial = new Material(defaultShader);
            }

            scale = material.scale;
        }
        else
        {
            if (defaultWallMaterial == null)
            {
                defaultWallMaterial = new Material(defaultShader);
            }
            if (defaultRoofMaterial == null)
            {
                defaultRoofMaterial = new Material(defaultShader);
            }
            wallMaterial = Instantiate(defaultWallMaterial) as Material;
            roofMaterial = Instantiate(defaultRoofMaterial) as Material;
        }

        RoofType roofType = RoofType.flat;

        AnalizeHouseTags(way, ref wallMaterial, ref roofMaterial, ref baseHeight);
        AnalizeHouseRoofType(way, ref baseHeight, ref roofType, ref roofHeight);

        GameObject   houseGO    = CreateGameObject(way.id);
        MeshRenderer renderer   = houseGO.AddComponent <MeshRenderer>();
        MeshFilter   meshFilter = houseGO.AddComponent <MeshFilter>();

        Mesh mesh = new Mesh {
            name = way.id
        };

        meshFilter.sharedMesh    = mesh;
        renderer.sharedMaterials = new []
        {
            wallMaterial,
            roofMaterial
        };

        OnlineMapsBuildingBuiltIn building = houseGO.AddComponent <OnlineMapsBuildingBuiltIn>();

        building.way   = way;
        building.nodes = usedNodes;
        houseGO.transform.localPosition = centerPoint;
        houseGO.transform.localRotation = Quaternion.Euler(Vector3.zero);
        houseGO.transform.localScale    = Vector3.one;

        Vector2 centerCoords = Vector2.zero;
        float   minCX = float.MaxValue, minCY = float.MaxValue, maxCX = float.MinValue, maxCY = float.MinValue;

        foreach (OnlineMapsOSMNode node in usedNodes)
        {
            Vector2 nodeCoords = node;
            centerCoords += nodeCoords;
            if (nodeCoords.x < minCX)
            {
                minCX = nodeCoords.x;
            }
            if (nodeCoords.y < minCY)
            {
                minCY = nodeCoords.y;
            }
            if (nodeCoords.x > maxCX)
            {
                maxCX = nodeCoords.x;
            }
            if (nodeCoords.y > maxCY)
            {
                maxCY = nodeCoords.y;
            }
        }

        building.id                = way.id;
        building.initialZoom       = OnlineMaps.instance.zoom;
        building.centerCoordinates = new Vector2((maxCX + minCX) / 2, (maxCY + minCY) / 2);
        building.boundsCoords      = new Bounds(building.centerCoordinates, new Vector3(maxCX - minCX, maxCY - minCY));

        int wallVerticesCount = (points.Count + 1) * 2;
        int roofVerticesCount = points.Count;
        int verticesCount     = wallVerticesCount + roofVerticesCount;
        int countTriangles    = wallVerticesCount * 3;

        if (vertices == null)
        {
            vertices = new List <Vector3>(verticesCount);
        }
        else
        {
            vertices.Clear();
        }

        if (uvs == null)
        {
            uvs = new List <Vector2>(verticesCount);
        }
        else
        {
            uvs.Clear();
        }

        if (wallTriangles == null)
        {
            wallTriangles = new List <int>(countTriangles);
        }
        else
        {
            wallTriangles.Clear();
        }

        if (roofTriangles == null)
        {
            roofTriangles = new List <int>();
        }
        else
        {
            roofTriangles.Clear();
        }

        if (generateWall)
        {
            building.CreateHouseWall(points, baseHeight, wallMaterial, scale);
        }
        building.CreateHouseRoof(points, baseHeight, roofHeight, roofType);

        if (building.hasErrors)
        {
            OnlineMapsUtils.DestroyImmediate(building.gameObject);
            return(null);
        }

        mesh.vertices     = vertices.ToArray();
        mesh.uv           = uvs.ToArray();
        mesh.subMeshCount = 2;
        mesh.SetTriangles(wallTriangles.ToArray(), 0);
        mesh.SetTriangles(roofTriangles.ToArray(), 1);

        mesh.RecalculateBounds();
        mesh.RecalculateNormals();

        building.buildingCollider = houseGO.AddComponent <MeshCollider>();
        (building.buildingCollider as MeshCollider).sharedMesh = mesh;

        return(building);
    }
Esempio n. 23
0
        private string GetURL(OnlineMapsTile tile, string url, bool labels)
        {
            url = Regex.Replace(url, @"{\w+}", delegate(Match match)
            {
                string v = match.Value.ToLower().Trim('{', '}');

                if (OnlineMapsTile.OnReplaceURLToken != null)
                {
                    string ret = OnlineMapsTile.OnReplaceURLToken(tile, v);
                    if (ret != null)
                    {
                        return(ret);
                    }
                }

                if (v == "zoom")
                {
                    return(tile.zoom.ToString());
                }
                if (v == "z")
                {
                    return(tile.zoom.ToString());
                }
                if (v == "x")
                {
                    return(tile.x.ToString());
                }
                if (v == "y")
                {
                    return(tile.y.ToString());
                }
                if (v == "quad")
                {
                    return(OnlineMapsUtils.TileToQuadKey(tile.x, tile.y, tile.zoom));
                }
                if (v == "lng")
                {
                    return(tile.language);
                }
                if (v == "ext")
                {
                    return(ext);
                }
                if (v == "prop")
                {
                    return(labels ? propWithLabels : propWithoutLabels);
                }
                if (v == "variant")
                {
                    return(labels ? variantWithLabels : variantWithoutLabels);
                }
                if (TryUseExtraFields(ref v))
                {
                    return(v);
                }
                return(v);
            });
            url = Regex.Replace(url, @"{rnd(\d+)-(\d+)}", delegate(Match match)
            {
                int v1 = int.Parse(match.Groups[1].Value);
                int v2 = int.Parse(match.Groups[2].Value);
                return(Random.Range(v1, v2 + 1).ToString());
            });
            if (logUrl)
            {
                Debug.Log(url);
            }
            return(url);
        }
Esempio n. 24
0
    private bool CreateHouseWallVerticles(float baseHeight, List <Vector3> baseVertices, List <Vector3> vertices, List <Vector2> uvs)
    {
        float topPoint = baseHeight * OnlineMapsBuildings.instance.heightScale;

        int     baseVerticesCount = baseVertices.Count;
        Vector3 pp  = Vector3.zero;
        Vector3 ptv = Vector3.zero;

        for (int i = 0; i <= baseVerticesCount; i++)
        {
            int j = i;
            if (j >= baseVerticesCount)
            {
                j -= baseVerticesCount;
            }

            Vector3 p  = baseVertices[j];
            Vector3 tv = new Vector3(p.x, topPoint, p.z);

            if (i > 0)
            {
                vertices.Add(pp);
                vertices.Add(ptv);

                vertices.Add(p);
                vertices.Add(tv);
            }

            pp  = p;
            ptv = tv;
        }

        float currentDistance     = 0;
        int   countVertices       = vertices.Count;
        int   fourthVerticesCount = countVertices / 4;

        perimeter = 0;

        for (int i = 0; i < fourthVerticesCount; i++)
        {
            int i1 = i * 4;
            int i2 = i * 4 + 2;

            float magnitude = (vertices[i1] - vertices[i2]).magnitude;
            perimeter += magnitude;
        }

        float prevDistance = 0;

        for (int i = 0; i < fourthVerticesCount; i++)
        {
            int i1 = i * 4;
            int i2 = i * 4 + 2;

            float magnitude = (vertices[i1] - vertices[i2]).magnitude;

            float prevU = prevDistance / perimeter;

            currentDistance += magnitude;
            prevDistance     = currentDistance;

            float curU = currentDistance / perimeter;
            uvs.Add(new Vector2(prevU, 0));
            uvs.Add(new Vector2(prevU, 1));
            uvs.Add(new Vector2(curU, 0));
            uvs.Add(new Vector2(curU, 1));
        }

        int   southIndex = -1;
        float southZ     = float.MaxValue;

        for (int i = 0; i < baseVerticesCount; i++)
        {
            if (baseVertices[i].z < southZ)
            {
                southZ     = baseVertices[i].z;
                southIndex = i;
            }
        }

        int prevIndex = southIndex - 1;

        if (prevIndex < 0)
        {
            prevIndex = baseVerticesCount - 1;
        }

        int nextIndex = southIndex + 1;

        if (nextIndex >= baseVerticesCount)
        {
            nextIndex = 0;
        }

        float angle1 = OnlineMapsUtils.Angle2D(baseVertices[southIndex], baseVertices[nextIndex]);
        float angle2 = OnlineMapsUtils.Angle2D(baseVertices[southIndex], baseVertices[prevIndex]);

        return(angle1 < angle2);
    }
Esempio n. 25
0
        private void Update()
        {
            if (pointIndex == -1)
            {
                return;
            }

            // Start point
            OnlineMapsVector2d p1 = points[pointIndex];

            // End point
            OnlineMapsVector2d p2 = points[pointIndex + 1];

            // Total step distance
            double dx, dy;

            OnlineMapsUtils.DistanceBetweenPoints(p1.x, p1.y, p2.x, p2.y, out dx, out dy);
            double stepDistance = Math.Sqrt(dx * dx + dy * dy);

            // Total step time
            double totalTime = stepDistance / speed * 3600;

            // Current step progress
            progress += Time.deltaTime / totalTime;

            OnlineMapsVector2d position;

            if (progress < 1)
            {
                position = OnlineMapsVector2d.Lerp(p1, p2, progress);
                marker.SetPosition(position.x, position.y);

                // Orient marker
                if (orientMarkerOnNextPoint)
                {
                    marker.rotation = 1.25f - OnlineMapsUtils.Angle2D((Vector2)p1, (Vector2)p2) / 360f;
                }
            }
            else
            {
                position = p2;
                marker.SetPosition(position.x, position.y);
                pointIndex++;
                progress = 0;
                if (pointIndex >= points.Length - 1)
                {
                    Debug.Log("Finish");
                    pointIndex = -1;
                }
                else
                {
                    // Orient marker
                    if (orientMarkerOnNextPoint)
                    {
                        marker.rotation = 1.25f - OnlineMapsUtils.Angle2D(p2, points[pointIndex + 1]) / 360;
                    }
                }
            }

            if (lookToMarker)
            {
                OnlineMaps.instance.SetPosition(position.x, position.y);
            }
            OnlineMaps.instance.Redraw();
        }
Esempio n. 26
0
        private void UpdateLine()
        {
            _size = size;

            float   totalDistance = 0;
            Vector3 lastPosition  = Vector3.zero;

            List <Vector3> vertices  = new List <Vector3>();
            List <Vector2> uvs       = new List <Vector2>();
            List <Vector3> normals   = new List <Vector3>();
            List <int>     triangles = new List <int>();

            List <Vector3> positions = new List <Vector3>();

            for (int i = 0; i < coords.Length; i++)
            {
                // Get world position by coordinates
                Vector3 position = OnlineMapsTileSetControl.instance.GetWorldPosition(coords[i]);
                positions.Add(position);

                if (i != 0)
                {
                    // Calculate angle between coordinates.
                    float a = OnlineMapsUtils.Angle2DRad(lastPosition, position, 90);

                    // Calculate offset
                    Vector3 off = new Vector3(Mathf.Cos(a) * size, 0, Mathf.Sin(a) * size);

                    // Init vertices, normals and triangles.
                    int vCount = vertices.Count;

                    vertices.Add(lastPosition + off);
                    vertices.Add(lastPosition - off);
                    vertices.Add(position + off);
                    vertices.Add(position - off);

                    normals.Add(Vector3.up);
                    normals.Add(Vector3.up);
                    normals.Add(Vector3.up);
                    normals.Add(Vector3.up);

                    triangles.Add(vCount);
                    triangles.Add(vCount + 3);
                    triangles.Add(vCount + 1);
                    triangles.Add(vCount);
                    triangles.Add(vCount + 2);
                    triangles.Add(vCount + 3);

                    totalDistance += (lastPosition - position).magnitude;
                }

                lastPosition = position;
            }

            float tDistance = 0;

            for (int i = 1; i < positions.Count; i++)
            {
                float distance = (positions[i - 1] - positions[i]).magnitude;

                // Updates UV
                uvs.Add(new Vector2(tDistance / totalDistance, 0));
                uvs.Add(new Vector2(tDistance / totalDistance, 1));

                tDistance += distance;

                uvs.Add(new Vector2(tDistance / totalDistance, 0));
                uvs.Add(new Vector2(tDistance / totalDistance, 1));
            }

            // Update mesh
            mesh.vertices  = vertices.ToArray();
            mesh.normals   = normals.ToArray();
            mesh.uv        = uvs.ToArray();
            mesh.triangles = triangles.ToArray();
            mesh.RecalculateBounds();

            // Scale texture
            Vector2 scale = new Vector2(totalDistance / size, 1);

            scale.Scale(uvScale);
            meshRenderer.material.mainTextureScale = scale;
        }
Esempio n. 27
0
    public new static OnlineMapsFindPlaceDetailsResult GetResult(string response)
    {
        OnlineMapsGooglePlaceDetailsResult results = OnlineMapsGooglePlaceDetails.GetResult(response);

        return(OnlineMapsUtils.DeepCopy <OnlineMapsFindPlaceDetailsResult>(results));
    }
Esempio n. 28
0
    public override void Update(double tlx, double tly, double brx, double bry, int zoom)
    {
        if (instance == null)
        {
            Debug.Log("No instance");
            return;
        }

        if (!range.InRange(zoom))
        {
            enabled = false;
        }
        else if (position.y > tly || position.y < bry)
        {
            enabled = false;
        }
        else if (tlx < brx && (position.x < tlx || position.x > brx))
        {
            enabled = false;
        }
        else if (tlx > brx && position.x < tlx && position.x > brx)
        {
            enabled = false;
        }
        else
        {
            enabled = true;
        }

        if (!enabled)
        {
            return;
        }

        if (_prefab != prefab)
        {
            Reinit(tlx, tly, brx, bry, zoom);
        }

        double mx, my;

        OnlineMapsUtils.LatLongToTiled(position.x, position.y, zoom, out mx, out my);

        double ttlx, ttly, tbrx, tbry;

        OnlineMapsUtils.LatLongToTiled(tlx, tly, zoom, out ttlx, out ttly);
        OnlineMapsUtils.LatLongToTiled(brx, bry, zoom, out tbrx, out tbry);

        int maxX = (2 << zoom) / 2;

        OnlineMaps api    = OnlineMaps.instance;
        Bounds     bounds = api.GetComponent <Collider>().bounds;

        double sx = tbrx - ttlx;

        if (sx < 0)
        {
            sx += maxX;
        }

        double mpx = mx - ttlx;

        if (mpx < 0)
        {
            mpx += maxX;
        }

        double px = mpx / sx;
        double pz = (ttly - my) / (ttly - tbry);

        _relativePosition = new Vector3((float)px, 0, (float)pz);

        if (OnlineMapsControlBase.instance is OnlineMapsTileSetControl)
        {
            px = -api.tilesetSize.x / 2 - (px - 0.5) * api.tilesetSize.x;
            pz = api.tilesetSize.y / 2 + (pz - 0.5) * api.tilesetSize.y;
        }
        else
        {
            Vector3 center = bounds.center;
            Vector3 size   = bounds.size;
            px = center.x - (px - 0.5) * size.x - api.transform.position.x;
            pz = center.z + (pz - 0.5) * size.z - api.transform.position.z;
        }

        Vector3 oldPosition = instance.transform.localPosition;
        float   y           = 0;

        if (OnlineMapsControlBase.instance is OnlineMapsTileSetControl)
        {
            OnlineMapsTileSetControl control = OnlineMapsTileSetControl.instance;
            y = control.GetElevationValue((float)px, (float)pz, control.GetBestElevationYScale(tlx, tly, brx, bry), tlx, tly, brx, bry);
        }

        Vector3 newPosition = new Vector3((float)px, y, (float)pz);

        instance.transform.localPosition = newPosition;
        if (oldPosition != newPosition && OnPositionChanged != null)
        {
            OnPositionChanged(this);
        }
    }
    public override bool HitTest(Vector2 positionLngLat, int zoom)
    {
        if (points == null)
        {
            return(false);
        }

        double cx, cy;
        OnlineMapsProjection projection = api.projection;

        projection.CoordinatesToTile(positionLngLat.x, positionLngLat.y, zoom, out cx, out cy);

        int valueType = -1; // 0 - Vector2, 1 - float, 2 - double, 3 - OnlineMapsVector2d

        object v1 = null;
        object v2 = null;
        object v3 = null;
        int    i  = 0;

        float w    = hitTestWidth.HasValue ? hitTestWidth.Value : width;
        float sqrW = w * w;

        foreach (object p in points)
        {
            if (valueType == -1)
            {
                if (p is Vector2)
                {
                    valueType = 0;
                }
                else if (p is float)
                {
                    valueType = 1;
                }
                else if (p is double)
                {
                    valueType = 2;
                }
                else if (p is OnlineMapsVector2d)
                {
                    valueType = 3;
                }
            }

            object v4 = v3;
            v3 = v2;
            v2 = v1;
            v1 = p;

            double p1tx = 0, p1ty = 0, p2tx = 0, p2ty = 0;
            bool   drawPart = false;

            if (valueType == 0)
            {
                if (i > 0)
                {
                    Vector2 p1 = (Vector2)v2;
                    Vector2 p2 = (Vector2)v1;

                    projection.CoordinatesToTile(p1.x, p1.y, zoom, out p1tx, out p1ty);
                    projection.CoordinatesToTile(p2.x, p2.y, zoom, out p2tx, out p2ty);
                    drawPart = true;
                }
            }
            else if (valueType == 3)
            {
                if (i > 0)
                {
                    OnlineMapsVector2d p1 = (OnlineMapsVector2d)v2;
                    OnlineMapsVector2d p2 = (OnlineMapsVector2d)v1;

                    projection.CoordinatesToTile(p1.x, p1.y, zoom, out p1tx, out p1ty);
                    projection.CoordinatesToTile(p2.x, p2.y, zoom, out p2tx, out p2ty);
                    drawPart = true;
                }
            }
            else if (i > 2 && i % 2 == 1)
            {
                if (valueType == 1)
                {
                    projection.CoordinatesToTile((float)v4, (float)v3, zoom, out p1tx, out p1ty);
                    projection.CoordinatesToTile((float)v2, (float)v1, zoom, out p2tx, out p2ty);
                }
                else if (valueType == 2)
                {
                    projection.CoordinatesToTile((double)v4, (double)v3, zoom, out p1tx, out p1ty);
                    projection.CoordinatesToTile((double)v2, (double)v1, zoom, out p2tx, out p2ty);
                }
                drawPart = true;
            }

            if (drawPart)
            {
                double nx, ny;
                OnlineMapsUtils.NearestPointStrict(cx, cy, p1tx, p1ty, p2tx, p2ty, out nx, out ny);
                double dx = (cx - nx) * OnlineMapsUtils.tileSize;
                double dy = (cy - ny) * OnlineMapsUtils.tileSize;
                double d  = dx * dx + dy * dy;
                if (d < sqrW)
                {
                    return(true);
                }
            }

            i++;
        }

        return(false);
    }
Esempio n. 30
0
 public override bool HitTest(Vector2 positionLngLat, int zoom)
 {
     return(OnlineMapsUtils.IsPointInPolygon(points, positionLngLat.x, positionLngLat.y));
 }