private List <VectorTile> GetNeighbors(VectorTile tile, List <VectorTile> tiles) { List <VectorTile> neighbors = new List <VectorTile>(); // Creates the box to check all the neighbors RectInt.PositionEnumerator positions = new RectInt(tile.Position.x - 1, tile.Position.y - 1, 3, 3).allPositionsWithin; while (positions.MoveNext()) { // Skip to next tile if it is the original tile. if (positions.Current == tile.Position) { continue; } // Checks the VectorTile list to see if there is a tile with the current position. VectorTile neighborTile = tiles.Find(t => t.Position == positions.Current); // If tile was found, add it to the neighbors list if (neighborTile != default(VectorTile)) { neighbors.Add(neighborTile); } } return(neighbors); }
public void LazyDecoding(string fileName) { string fullFileName = Path.Combine(fixturesPath, fileName); Assert.True(File.Exists(fullFileName), "Vector tile exists"); byte[] data = File.ReadAllBytes(fullFileName); VectorTile vt = new VectorTile(data); foreach (var layerName in vt.LayerNames()) { VectorTileLayer layer = vt.GetLayer(layerName); for (int i = 0; i < layer.FeatureCount(); i++) { VectorTileFeature feat = layer.GetFeature(i); var properties = feat.GetProperties(); foreach (var prop in properties) { Assert.AreEqual(prop.Value, feat.GetValue(prop.Key), "Property values match"); } foreach (var geomPart in feat.Geometry <int>()) { foreach (var coord in geomPart) { //TODO add Assert } } } } string geojson = vt.ToGeoJson(0, 0, 0); Assert.GreaterOrEqual(geojson.Length, 30, "geojson >= 30 chars"); }
public void SetVectorData(VectorTile vectorTile) { if (VectorDataState != TilePropertyState.Unregistered) { VectorData = vectorTile; } }
/// <summary> /// Writes a layer of the tile to the given stream. /// </summary> /// <param name="tile">The vector tile.</param> /// <param name="stream">The stream to write to.</param> public static void Write(this VectorTile tile, Stream stream) { var featureCollection = new FeatureCollection(); foreach (var layer in tile.Layers) { if (layer == null) { continue; } foreach (var feature in layer.Features) { featureCollection.Add(feature); } } if (featureCollection.Count == 0) { return; } var streamWriter = new StreamWriter(stream, Encoding.Default, 1024, true); Serializer.Serialize(streamWriter, featureCollection); streamWriter.Flush(); }
internal static VectorTile GetVectorTile(this HeatMap heatMap, ulong tileId, uint resolution) { var tile = new Tile(tileId); var tgt = new TileGeometryTransform(tile, resolution); var vectorTile = new VectorTile() { TileId = tileId, Layers = { new Layer() { Name = "heatmap" } } }; foreach (var(x, y, value) in heatMap.GetValues(tileId, resolution)) { if (value == 0) { continue; } var coordinate = tgt.TransformTo(x, y); vectorTile.Layers[0].Features.Add(new Feature( new Point(new Coordinate(coordinate.longitude, coordinate.latitude)), new AttributesTable { { "cost", value } })); } return(vectorTile); }
internal override void OnRegistered(UnityTile tile) { var vectorTile = new VectorTile(); tile.AddTile(vectorTile); Progress++; vectorTile.Initialize(_fileSource, tile.CanonicalTileId, _mapId, () => { if (vectorTile.HasError) { tile.VectorDataState = TilePropertyState.Error; Progress--; return; } _cachedData.Add(tile, vectorTile); // FIXME: we can make the request BEFORE getting a response from these! if (tile.HeightDataState == TilePropertyState.Loading || tile.RasterDataState == TilePropertyState.Loading) { tile.OnHeightDataChanged += DataChangedHandler; tile.OnRasterDataChanged += DataChangedHandler; } else { CreateMeshes(tile); } }); }
private void Update() { // To prevent enemy drifting _rigidbody.velocity = Vector2.zero; var currentField = _vectorFieldPathing.CurrentField; // Checks to seee if the enemy is within range to reduce computation. if (Vector2.Distance(currentField.Key, transform.position) > 20) { return; } // Finds the tile with the same position as the enemy. VectorTile tile = currentField.Value.Find(v => v.Position == Vector2Int.FloorToInt(transform.position)); if (tile == null) { return; } // Moves itself based on the tile's direction. _rigidbody.MovePosition((Vector2)transform.position + tile.Direction * (_speed / 32f) * Time.deltaTime); var direcetion = (currentField.Key - (Vector2)transform.position).normalized; transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direcetion.y, direcetion.x) * Mathf.Rad2Deg + 90); }
public void VectorTile_Init_WidithHeight() { VectorTile v = new VectorTile(0, 0, 0, 512, 512); Assert.AreEqual(512, v.Width()); Assert.AreEqual(512, v.Height()); }
public void AtLeastOneLayer(string fileName) { string fullFileName = Path.Combine(fixturesPath, fileName); Assert.True(File.Exists(fullFileName), "Vector tile exists"); byte[] data = File.ReadAllBytes(fullFileName); VectorTile vt = new VectorTile(data); Assert.GreaterOrEqual(vt.LayerNames().Count, 1, "At least one layer"); string geojson = vt.ToGeoJson(0, 0, 0); Assert.GreaterOrEqual(geojson.Length, 30, "geojson >= 30 chars"); foreach (var lyrName in vt.LayerNames()) { VectorTileLayer lyr = vt.GetLayer(lyrName); for (int i = 0; i < lyr.FeatureCount(); i++) { Debug.WriteLine("{0} lyr:{1} feat:{2}", fileName, lyr.Name, i); VectorTileFeature feat = lyr.GetFeature(i); long extent = (long)lyr.Extent; foreach (var part in feat.Geometry <long>()) { foreach (var geom in part) { if (geom.X < 0 || geom.Y < 0 || geom.X > extent || geom.Y > extent) { Debug.WriteLine("{0} lyr:{1} feat:{2} x:{3} y:{4}", fileName, lyr.Name, i, geom.X, geom.Y); } } } } } }
public void Clipping(string fileName) { string fullFileName = Path.Combine(fixturesPath, fileName); Assert.True(File.Exists(fullFileName), "Vector tile exists"); byte[] data = File.ReadAllBytes(fullFileName); VectorTile vt = new VectorTile(data); foreach (var lyrName in vt.LayerNames()) { VectorTileLayer lyr = vt.GetLayer(lyrName); for (int i = 0; i < lyr.FeatureCount(); i++) { VectorTileFeature feat = lyr.GetFeature(i); //skip features with unknown geometry type if (feat.GeometryType == GeomType.UNKNOWN) { continue; } List <List <Point2d <long> > > geomRaw = feat.Geometry <long>(); List <List <Point2d <long> > > geomClipped = feat.Geometry <long>(0); for (int j = 0; j < geomRaw.Count; j++) { List <Point2d <long> > part = geomRaw[j]; List <Point2d <long> > partClipped = geomClipped[j]; // Workaround to compare parts as clipping may or may not change the order of vertices // This only works if no actual clipping is done Assert.False(part.Except(partClipped).Any(), $"{fileName}, feature[{i}], geometry part[{j}]: geometry parts don't match after clipping"); } } } }
public override void FetchData(DataFetcherParameters parameters) { if (!(parameters is BuildingMeshFetcherParameters fetcherParameters)) { return; } var vectorTile = new VectorTile(); vectorTile.Initialize(_fileSource, fetcherParameters.canonicalTileId, fetcherParameters.tilesetId, () => { if (fetcherParameters.canonicalTileId != vectorTile.Id) { return; } if (vectorTile.HasError) { UnityEngine.Debug.LogError("Vector Tile Error!"); } else { dataReceived(fetcherParameters.cTile, vectorTile); } }); }
public void Scaling(string fileName) { float[] scales = new float[] { 1.5f, 2.25f, 5.75f, 197.3f }; string fullFileName = Path.Combine(fixturesPath, fileName); byte[] data = File.ReadAllBytes(fullFileName); VectorTile vt = new VectorTile(data); foreach (var lyrName in vt.LayerNames()) { VectorTileLayer lyr = vt.GetLayer(lyrName); int featCnt = lyr.FeatureCount(); for (int idxFeat = 0; idxFeat < featCnt; idxFeat++) { VectorTileFeature feat = lyr.GetFeature(idxFeat); List <List <Point2d <int> > > rawParts = feat.Geometry <int>(); for (int idxPart = 0; idxPart < rawParts.Count; idxPart++) { List <Point2d <int> > rawGeom = rawParts[idxPart]; foreach (var scale in scales) { List <List <Point2d <float> > > scaledParts = feat.Geometry <float>(null, scale); List <Point2d <float> > scaledGeom = scaledParts[idxPart]; for (int idxVertex = 0; idxVertex < rawGeom.Count; idxVertex++) { Point2d <int> rawVertex = rawGeom[idxVertex]; Point2d <float> scaledVertex = scaledGeom[idxVertex]; Assert.AreEqual(scale * (float)rawVertex.X, scaledVertex.X, $"{fileName}, feature[{idxFeat}], geometry part[{idxPart}], vertex[{idxVertex}], scale[{scale}]: X does not match"); Assert.AreEqual(scale * (float)rawVertex.Y, scaledVertex.Y, $"{fileName}, feature[{idxFeat}], geometry part[{idxPart}], vertex[{idxVertex}], scale[{scale}]: Y does not match"); } } } } } }
public void VectorTile_GeoJSON() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "geojson.input")); string json = @"{""type"":""FeatureCollection"",""name"":""layer"",""features"":[{""type"":""Feature"",""geometry"":{""type"":""Point"",""coordinates"":[-121.9921875,47.9899216674142]},""properties"":{""name"":""geojson data""}}]}"; VectorTile v = new VectorTile(0, 0, 0); v.AddGeoJSON(json, "layer"); byte[] bytes = v.GetData(); Assert.AreEqual(53, bytes.Length); Assert.IsFalse(v.Empty()); Assert.IsTrue(v.Painted()); CollectionAssert.AreEquivalent(new List <string>() { "layer" }, v.Names().ToList()); //ToGeoJSON dynamic expected = JObject.Parse(json); var results = new List <JObject>() { JObject.Parse(v.ToGeoJSON("layer")), JObject.Parse(v.ToGeoJSON(0)) }; foreach (dynamic actual in results) { Assert.AreEqual(expected.FeatureCollection, actual.FeatureCollection); Assert.AreEqual(expected.features[0].properties.name, actual.features[0].properties.name); Assert.AreEqual(expected.features[0].geometry.type, actual.features[0].geometry.type); Assert.AreEqual(expected.features[0].geometry.coordinates[0], actual.features[0].geometry.coordinates[0]); Assert.AreEqual(expected.features[0].geometry.coordinates[1], actual.features[0].geometry.coordinates[1]); } }
public override IEnumerator ParseTileData(object m, Coordinates tilecenter, int zoom, GOLayer[] layers, bool delayedLoad, List <string> layerNames) { if (mapData == null) { Debug.LogWarning("Map Data is null!"); #if !UNITY_WEBPLAYER FileHandler.Remove(gameObject.name); #endif yield break; } var decompressed = Compression.Decompress((byte[])mapData); vt = new VectorTile(decompressed, false); foreach (GOLayer layer in layers) { string[] lyrs = GetLayersStrings(layer).Split(','); foreach (string l in lyrs) { VectorTileLayer lyr = vt.GetLayer(l); if (lyr != null) { yield return(StartCoroutine(BuildLayer(lyr, layer, delayedLoad))); } } } }
/// <summary> /// Reads a Vector Tile stream. /// </summary> /// <param name="stream">Vector tile stream.</param> /// <param name="tileDefinition">Tile information.</param> /// <param name="idAttributeName">Optional. Specifies the name of the attribute that the vector tile feature's ID should be stored in the NetTopologySuite Features AttributeTable.</param> /// <returns></returns> public VectorTile Read(Stream stream, Tiles.Tile tileDefinition, string idAttributeName) { // Deserialize the tile var tile = ProtoBuf.Serializer.Deserialize <Mapbox.Tile>(stream); var vectorTile = new VectorTile { TileId = tileDefinition.Id }; foreach (var mbTileLayer in tile.Layers) { Debug.Assert(mbTileLayer.Version == 2U); var tgs = new TileGeometryTransform(tileDefinition, mbTileLayer.Extent); var layer = new Layer { Name = mbTileLayer.Name }; foreach (var mbTileFeature in mbTileLayer.Features) { var feature = ReadFeature(tgs, mbTileLayer, mbTileFeature, idAttributeName); layer.Features.Add(feature); } vectorTile.Layers.Add(layer); } return(vectorTile); }
public void ClipHardAtTileBoundary(string fileName) { string fullFileName = Path.Combine(fixturesPath, fileName); Assert.True(File.Exists(fullFileName), "Vector tile exists"); byte[] data = File.ReadAllBytes(fullFileName); VectorTile vt = new VectorTile(data); Assert.GreaterOrEqual(vt.LayerNames().Count, 1, "At least one layer"); string geojson = vt.ToGeoJson(0, 0, 0); Assert.GreaterOrEqual(geojson.Length, 30, "geojson >= 30 chars"); foreach (var lyrName in vt.LayerNames()) { VectorTileLayer lyr = vt.GetLayer(lyrName); for (int i = 0; i < lyr.FeatureCount(); i++) { Debug.WriteLine("{0} lyr:{1} feat:{2}", fileName, lyr.Name, i); VectorTileFeature feat = lyr.GetFeature(i, 0); long extent = (long)lyr.Extent; foreach (var part in feat.Geometry <int>()) { foreach (var geom in part) { Assert.GreaterOrEqual(geom.X, 0, "geom.X equal or greater 0"); Assert.GreaterOrEqual(geom.Y, 0, "geom.Y eqaul or greater 0"); Assert.LessOrEqual(geom.X, extent, "geom.X less or equal extent"); Assert.LessOrEqual(geom.Y, extent, "geom.Y less or equal extent"); } } } } }
public void VectorTile_Overzoom_Render() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); m.ZoomToBox(-20037508.34, -20037508.34, 20037508.34, 20037508.34); VectorTile v1 = new VectorTile(0, 0, 0, 256, 256); m.Render(v1); m.ZoomToBox(-20037508.34, 0, 0, 20037508.34); VectorTile v2 = new VectorTile(1, 0, 0, 256, 256); m.Render(v2); Map renderMap = new Map(256, 256); renderMap.Load(@".\data\style.xml"); Image i1 = new Image(256, 256); Image i2 = new Image(256, 256); Dictionary <string, object> options = new Dictionary <string, object>(); options["Z"] = 1; v1.Render(renderMap, i1, options); v2.Render(renderMap, i2); //Small diff showing up between images Assert.IsTrue(i1.Compare(i2) - 500 < 0); }
public void VectorTile_SimpleComposite() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); m.ZoomAll(); VectorTile v1 = new VectorTile(0, 0, 0, 256, 256); m.Render(v1); int v1before = v1.GetData().Length; VectorTile v2 = new VectorTile(0, 0, 0, 256, 256); m.Render(v2); v1.Composite(new List <VectorTile>() { v2 }); int v1after = v1.GetData().Length; Assert.AreEqual(v1before * 2, v1after); }
public void VectorTile_OverzoomComposite() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); VectorTile v1 = new VectorTile(1, 0, 0, 256, 256); m.ZoomToBox(-20037508.34, 0, 0, 20037508.34); m.Render(v1); int v1before = v1.GetData().Length; VectorTile v2 = new VectorTile(0, 0, 0, 256, 256); m.ZoomToBox(-20037508.34, -20037508.34, 20037508.34, 20037508.34); m.Render(v2); v1.Composite(new List <VectorTile>() { v2 }); int v1after = v1.GetData().Length; //composite bytes will actually be a little bit bigger than 2* original //Assert.AreEqual(v1before * 2, v1after); }
public static bool IsNull(this VectorTile tile) { if (tile == null) { return(true); } return(false); }
protected override void ThreadFunction() { if (goTile.useElevation) { goTile.elevatedTerrainMesh(); } tT = DateTime.Now; var decompressed = Mapbox.Utils.Compression.Decompress(goTile.getVectorData()); VectorTile vt = new VectorTile(decompressed, false); ////DEBUG TO GEOJSON //string debug = vt.ToGeoJson((ulong)goTile.zoomLevel, (ulong)goTile.tileCoordinates.x, (ulong)goTile.tileCoordinates.y, 0); //FileHandler.SaveText("DEBUG_TILE", debug); //DEBUG LAYERS //foreach (string lyr in vt.LayerNames()) //{ // Debug.Log(lyr); //} list = new List <GOParsedLayer> (); //Sort layers so that the order is right for dropping environment Array.Sort(layers, (GOLayer a, GOLayer b) => GOLayer.LayerTypeToIndex(a.layerType).CompareTo(GOLayer.LayerTypeToIndex(b.layerType))); foreach (GOLayer layer in layers) { if (layer.disabled) { continue; } ParseGOLayerToList(list, vt, layer); } tF = DateTime.Now; if (tile.map.pois != null && (tile.map.pois.renderingOptions.Length > 0 && !tile.map.pois.disabled)) { ParsePOILayerToList(list, vt, tile.map.pois); } tP = DateTime.Now; if (tile.map.labels != null && !tile.map.labels.disabled) { ParseLabelLayerToList(list, vt, tile.map.labels); } tL = DateTime.Now; if (tile.map.customMapboxTilesets != null && tile.map.customMapboxTilesets.Length > 0) { ParseTilesetsToList(list, vt, tile.map.customMapboxTilesets); } tTS = DateTime.Now; }
private void ParseLabelLayerToList(List <GOParsedLayer> list, VectorTile vt, GOLabelsLayer layer) { string[] lyrs = tile.GetLabelsStrings().Split(','); // string kindKey = tile.GetPoisKindKey(); foreach (string l in lyrs) { VectorTileLayer lyr = vt.GetLayer(l); if (lyr != null) { int featureCount = lyr.FeatureCount(); if (featureCount == 0) { continue; } GOParsedLayer pl = new GOParsedLayer(); pl.name = lyr.Name; pl.labelsLayer = layer; pl.goFeatures = new List <GOFeature> (); for (int i = 0; i < featureCount; i++) { VectorTileFeature vtf = lyr.GetFeature(i); IDictionary properties = vtf.GetProperties(); List <List <LatLng> > geomWgs = vtf.GeometryAsWgs84((ulong)goTile.zoomLevel, (ulong)goTile.tileCoordinates.x, (ulong)goTile.tileCoordinates.y, 0); if (geomWgs.Count == 0 || geomWgs[0].Count <= 1) { continue; } GOFeature gf = new GOFeature(); gf.properties = properties; gf.goFeatureType = vtf.GOFeatureType(geomWgs); gf.labelsLayer = layer; gf.featureIndex = (Int64)i + vt.LayerNames().IndexOf(lyr.Name); gf.goTile = goTile; gf = tile.EditLabelData(gf); gf.goFeatureType = GOFeatureType.Label; gf.ConvertAttributes(); if (geomWgs.Count > 0) { gf.geometry = geomWgs[0]; gf.ConvertGeometries(); gf.preloadedLabelData = GOSegment.FindTheLongestStreightSegment(gf.convertedGeometry, 0); AddFatureToList(gf, pl.goFeatures); } } list.Add(pl); } } }
public void VectorTile_Init() { VectorTile v = new VectorTile(0, 0, 0); Assert.AreEqual(256, v.Width()); Assert.AreEqual(256, v.Height()); Assert.IsFalse(v.Painted()); Assert.AreEqual("", v.IsSolid()); Assert.IsTrue(v.Empty()); Assert.AreEqual(0, v.GetData().Length); }
public void VectorTile_Names() { VectorTile v = new VectorTile(9, 112, 195); v.SetData(File.ReadAllBytes(@".\data\9.112.195.pbf")); CollectionAssert.AreEquivalent(new List <string>() { "world" }, v.Names().ToList()); }
private List <VectorTile> VectorFieldAlgorithm(Vector2Int startPosition) { VectorTile current = new VectorTile(Vector2Int.zero); // Locks and selects all the tiles within a 20 // unit distance in the VectorTile pool // while reseting the values for all tiles in the pool. var tiles = new List <VectorTile>(); lock (_vectorTilesPool) { tiles = _vectorTilesPool.Where(t => { t.Reset(); if (t.Position == startPosition) { current = t; } return(Vector2.Distance(startPosition, t.Position) < 10f); }).Select(t => new VectorTile(t)).ToList(); } var open = new HashSet <VectorTile>() { current }; var close = new HashSet <VectorTile>(); // Modified version of Djistra's Algorithm. while (open.Count != 0) { current = open.Aggregate((a, b) => a.Distance < b.Distance ? a : b); open.Remove(current); close.Add(current); // Loops through every neighbor of the current tile. foreach (var neighbor in GetNeighbors(current, tiles)) { if (close.Contains(neighbor)) { continue; } // Sets neighbor's distance and direction and adds it to the open list. if (!open.Contains(neighbor)) { neighbor.Distance = current.Distance + Vector2.Distance(neighbor.Position, current.Position); neighbor.Direction = current.Position - neighbor.Position; open.Add(neighbor); } } } return(tiles); }
private void BuildVectorTile() { // Define which features from the vector tile will be made into game objects var builderDictionary = new Dictionary <string, MeshBuilder>() { { "building", new MeshBuilder() { Modifiers = new List <MeshModifier>() { new PolygonMeshModifier(), new UvModifier(), new HeightModifier() } } }, // Not using these for now. //{ // "road", new MeshBuilder() // { // Modifiers = new List<MeshModifier>() // { // new LineMeshModifier(), // new UvModifier(), // new HeightModifier() // } // } //} }; var parameters = new Tile.Parameters { Fs = _fileSource, Id = new CanonicalTileId(zoomLevel, (int)tileCoordinate.x, (int)tileCoordinate.y) }; // Use VectorTile class for vector tiles. Requests mapbox.mapbox-streets-v7 mapid by default. var vectorTile = new VectorTile(); vectorTile.Initialize(parameters, () => { if (vectorTile.Error != null) { Debug.Log(vectorTile.Error); return; } foreach (var builder in builderDictionary) { var layer = vectorTile.GetLayer(builder.Key); builder.Value.Create(layer, tileRect, heightData, tileObject.transform, parameters); } }); }
public void VectorTile_GetSetData() { VectorTile v = new VectorTile(9, 112, 195); byte[] bytes = File.ReadAllBytes(@".\data\9.112.195.pbf"); v.SetData(bytes); Assert.IsFalse(v.Empty()); Assert.IsTrue(v.Painted()); byte[] actual = v.GetData(); CollectionAssert.AreEquivalent(bytes, actual); }
// Start is called before the first frame update void Start() { PlayerData pd = StateManager.GetController().pdata; for (int i = 0; i < pd.VectorLocals.Length; i++) { if (pd.VectorLocals[i]) { VectorTile.Create(pd.VectorLocals[i], Vector2.zero, transform); } } }
private static async Task <VectorTile> baseTileToVector(object baseTile) { var tile = baseTile as Mapbox.VectorTile.VectorTile; var result = new VectorTile(); foreach (var lyrName in tile.LayerNames()) { Mapbox.VectorTile.VectorTileLayer lyr = tile.GetLayer(lyrName); var vectorLayer = new VectorTileLayer(); vectorLayer.Name = lyrName; for (int i = 0; i < lyr.FeatureCount(); i++) { Mapbox.VectorTile.VectorTileFeature feat = lyr.GetFeature(i); var vectorFeature = new VectorTileFeature(); vectorFeature.Extent = 1; vectorFeature.GeometryType = convertGeometryType(feat.GeometryType); vectorFeature.Attributes = feat.GetProperties(); var vectorGeometry = new List <List <Point> >(); foreach (var points in feat.Geometry <int>()) { var vectorPoints = new List <Point>(); foreach (var coordinate in points) { var dX = (double)coordinate.X / (double)lyr.Extent; var dY = (double)coordinate.Y / (double)lyr.Extent; vectorPoints.Add(new Point(dX, dY)); //var newX = Utils.ConvertRange(dX, extent.Left, extent.Right, 0, vectorFeature.Extent); //var newY = Utils.ConvertRange(dY, extent.Top, extent.Bottom, 0, vectorFeature.Extent); //vectorPoints.Add(new Point(newX, newY)); } vectorGeometry.Add(vectorPoints); } vectorFeature.Geometry = vectorGeometry; vectorLayer.Features.Add(vectorFeature); } result.Layers.Add(vectorLayer); } return(result); }
public void VectorTile_IsSolid() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); m.Extent = new double[] { -11271098.442818949, 4696291.017841229, -11192826.925854929, 4774562.534805249 }; VectorTile v = new VectorTile(9, 112, 195); m.Render(v); Assert.IsTrue(v.Painted()); Assert.AreEqual("world", v.IsSolid()); }
public void VectorTile_SimpleComposite() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); m.ZoomAll(); VectorTile v1 = new VectorTile(0, 0, 0, 256, 256); m.Render(v1); int v1before = v1.GetData().Length; VectorTile v2 = new VectorTile(0, 0, 0, 256, 256); m.Render(v2); v1.Composite(new List<VectorTile>() { v2 }); int v1after = v1.GetData().Length; Assert.AreEqual(v1before * 2, v1after); }
public void VectorTile_OverzoomComposite() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); VectorTile v1 = new VectorTile(1, 0, 0, 256, 256); m.ZoomToBox(-20037508.34, 0, 0, 20037508.34); m.Render(v1); int v1before = v1.GetData().Length; VectorTile v2 = new VectorTile(0, 0, 0, 256, 256); m.ZoomToBox(-20037508.34, -20037508.34, 20037508.34, 20037508.34); m.Render(v2); v1.Composite(new List<VectorTile>() { v2 }); int v1after = v1.GetData().Length; //composite bytes will actually be a little bit bigger than 2* original //Assert.AreEqual(v1before * 2, v1after); }
public void VectorTile_GeoJSON() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "geojson.input")); string json = @"{""type"":""FeatureCollection"",""name"":""layer"",""features"":[{""type"":""Feature"",""geometry"":{""type"":""Point"",""coordinates"":[-121.9921875,47.9899216674142]},""properties"":{""name"":""geojson data""}}]}"; VectorTile v = new VectorTile(0, 0, 0); v.AddGeoJSON(json, "layer"); byte[] bytes = v.GetData(); Assert.AreEqual(53, bytes.Length); Assert.IsFalse(v.Empty()); Assert.IsTrue(v.Painted()); CollectionAssert.AreEquivalent(new List<string>() { "layer" }, v.Names().ToList()); //ToGeoJSON dynamic expected = JObject.Parse(json); var results = new List<JObject>() { JObject.Parse(v.ToGeoJSON("layer")), JObject.Parse(v.ToGeoJSON(0)) }; foreach (dynamic actual in results) { Assert.AreEqual(expected.FeatureCollection, actual.FeatureCollection); Assert.AreEqual(expected.features[0].properties.name, actual.features[0].properties.name); Assert.AreEqual(expected.features[0].geometry.type, actual.features[0].geometry.type); Assert.AreEqual(expected.features[0].geometry.coordinates[0], actual.features[0].geometry.coordinates[0]); Assert.AreEqual(expected.features[0].geometry.coordinates[1], actual.features[0].geometry.coordinates[1]); } }
public void VectorTile_Clear() { VectorTile v = new VectorTile(9,112,195); byte[] bytes = File.ReadAllBytes(@".\data\9.112.195.pbf"); v.SetData(bytes); Assert.IsFalse(v.Empty()); Assert.IsTrue(v.Painted()); CollectionAssert.AreEquivalent(new List<string>() { "world" }, v.Names().ToList()); byte[] actual = v.GetData(); Assert.AreEqual(bytes.Length, actual.Length); v.Clear(); Assert.IsTrue(v.Empty()); Assert.IsFalse(v.Painted()); Assert.AreEqual("",v.IsSolid()); CollectionAssert.AreEquivalent(new List<string>(), v.Names().ToList()); actual = v.GetData(); Assert.AreEqual(0, actual.Length); }
public void VectorTile_Query() { VectorTile v = new VectorTile(9, 112, 195); byte[] bytes = File.ReadAllBytes(@".\data\9.112.195.pbf"); v.SetData(bytes); IEnumerable<VectorQueryResult> results = v.Query(-100.8576, 39.1181); VectorQueryResult result = results.ToList()[0]; Assert.AreEqual("world", result.Layer); Assert.AreEqual(0, result.Distance); Assert.AreEqual(207, result.Feature.Id()); IDictionary<string, object> attributes = result.Feature.Attributes(); Assert.AreEqual("United States", (string)attributes["NAME"]); }
public void VectorTile_ToJSON() { VectorTile v = new VectorTile(9, 112, 195); byte[] bytes = File.ReadAllBytes(@".\data\9.112.195.pbf"); v.SetData(bytes); IEnumerable<VectorTileLayer> vtJSON = v.ToJSON(); string json = JsonConvert.SerializeObject( vtJSON, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); string expected = @"[{""Features"":[{""Properties"":{""AREA"":915896,""FIPS"":""US"",""ISO2"":""US"",""ISO3"":""USA"",""LAT"":39.622,""LON"":-98.606,""NAME"":""United States"",""POP2005"":299846449,""REGION"":19,""SUBREGION"":21,""UN"":840},""Geometry"":[9,8192,0,58,0,0,0,8192,0,8191,0,8192,0,0,8191,0,0,8191,15],""Type"":3,""Id"":207}],""Version"":1,""Extent"":4096,""Name"":""world""}]"; Assert.AreEqual(expected, json); }
public void VectorTile_Render_Image() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); m.Extent = new double[] { -20037508.34, 0, 0, 20037508.34 }; VectorTile v = new VectorTile(1, 0, 0); m.Render(v); VectorTile v2 = new VectorTile(1, 0, 0); v2.SetData(v.GetData()); Map m2 = new Map(256, 256); m2.Load(@".\data\style.xml"); Image i = new Image(256, 256); v2.Render(m2, i); Assert.AreEqual(0,i.Compare(Image.Open(@".\data\world_1.0.0.png"))); }
public void VectorTile_Render_Grid() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); m.Extent = new double[] { -20037508.34, 0, 0, 20037508.34 }; VectorTile v = new VectorTile(1, 0, 0); m.Render(v); VectorTile v2 = new VectorTile(1, 0, 0); v2.SetData(v.GetData()); Map m2 = new Map(256, 256); m2.Load(@".\data\style.xml"); Grid g = new Grid(256, 256); var options = new Dictionary<string, object>() { {"Fields", new List<string>() { "FIPS" } }, {"Layer", "world" } }; v2.Render(m2, g, options); Dictionary<string, object > grid = g.Encode(); Assert.AreEqual(grid.Keys.Count, 3); //Test for keys List<string> keyList = (List<string>)grid["keys"]; Assert.AreNotEqual(keyList.Count, 0); //Test for data Dictionary<string, object> dataDict = (Dictionary<string, object>)grid["data"]; Assert.AreNotEqual(dataDict.Count, 0); //data count should equal keys + 1 Assert.AreEqual(keyList.Count, dataDict.Count + 1); }
public void VectorTile_Overzoom_Render() { Mapnik.RegisterDatasource(Path.Combine(Mapnik.Paths["InputPlugins"], "shape.input")); Map m = new Map(256, 256); m.Load(@".\data\layer.xml"); m.ZoomToBox(-20037508.34, -20037508.34, 20037508.34, 20037508.34); VectorTile v1 = new VectorTile(0, 0, 0, 256, 256); m.Render(v1); m.ZoomToBox(-20037508.34, 0, 0, 20037508.34); VectorTile v2 = new VectorTile(1, 0, 0, 256, 256); m.Render(v2); Map renderMap = new Map(256, 256); renderMap.Load(@".\data\style.xml"); Image i1 = new Image(256, 256); Image i2 = new Image(256, 256); Dictionary<string, object> options = new Dictionary<string, object>(); options["Z"] = 1; v1.Render(renderMap, i1, options); v2.Render(renderMap, i2); //Small diff showing up between images Assert.IsTrue(i1.Compare(i2)-500 < 0); }
public void VectorTile_GetSetData() { VectorTile v = new VectorTile(9,112,195); byte[] bytes = File.ReadAllBytes(@".\data\9.112.195.pbf"); v.SetData(bytes); Assert.IsFalse(v.Empty()); Assert.IsTrue(v.Painted()); byte[] actual = v.GetData(); CollectionAssert.AreEquivalent(bytes, actual); }
public byte[] Render(Envelope envelope, string format, int tileWidth, int tileHeight) { // Lock map object for rendering // TO DO: better strategy is to create a pool of map objects lock (mapLock) { _map.Width = Convert.ToUInt32(tileWidth); _map.Height = Convert.ToUInt32(tileHeight); _map.ZoomToBox(envelope.Minx, envelope.Miny, envelope.Maxx, envelope.Maxy); format = format.ToLower(); // Render Image if (format == "png" || format == "jpg") { Image img = new Image(Convert.ToInt32(_map.Width), Convert.ToInt32(_map.Height)); _map.Render(img); if (format == "png") { format = this._pngOptions; } if (format == "jpg") { format = this._jpegOptions; } return img.Encode(format); } // Render UTFGrid else if (format == "json") { NETMapnik.Grid grd = new NETMapnik.Grid(_map.Width, _map.Height); _map.Render(grd, Convert.ToUInt32(this._gridLayerIndex), this._gridFields); string json = JsonConvert.SerializeObject(grd.Encode("utf", true, Convert.ToUInt32(this._gridResolution))); return Encoding.UTF8.GetBytes(json); } // Render vector tile else if (format == "pbf") { //tile coord (i.e., 0/0/0 not needed for pbf rendering VectorTile vTile = new VectorTile(0,0,0, _map.Width,_map.Height); _map.Render(vTile); byte[] bytes = vTile.GetBytes(); //compress vector tile bytes if (bytes.Length > 0) { bytes = Compress(bytes); } return bytes; } // Format not expected so throw exception throw new InvalidTileFormatException( string.Format("Invalid tile FORMAT {0}", format) ); } }
public void VectorTile_Names() { VectorTile v = new VectorTile(9,112,195); v.SetData(File.ReadAllBytes(@".\data\9.112.195.pbf")); CollectionAssert.AreEquivalent(new List<string>() { "world" }, v.Names().ToList()); }
public byte[] Render(Coord coord, string format, int tileWidth, int tileHeight) { byte[] tileBytes = this._tileSource.GetTile(coord, "pbf"); // Uncompress bytes if (tileBytes.Length > 0) { tileBytes = Decompress(tileBytes); } // Set vector tile bytes // mapnik vector tile assumes top left origin int y = coord.Y; if (!coord.TopOrigin) y = this._tileSource.GridSet.GridHeight(coord.Z) - coord.Y - 1; VectorTile vTile = new VectorTile(coord.Z, coord.X, y, Convert.ToUInt32(tileWidth), Convert.ToUInt32(tileHeight)); vTile.SetBytes(tileBytes); // Get coord envelope Envelope envelope = this._tileSource.GridSet.CoordToEnvelope(coord); // Lock map object for rendering // TO DO: better strategy is to create a pool of map objects lock (mapLock) { _map.Width = Convert.ToUInt32(tileWidth); _map.Height = Convert.ToUInt32(tileHeight); _map.ZoomToBox(envelope.Minx, envelope.Miny, envelope.Maxx, envelope.Maxy); Image img = new Image(Convert.ToInt32(_map.Width), Convert.ToInt32(_map.Height)); vTile.Render(_map, img); format = format.ToLower(); if (format == "png" || format == "jpg") { if (format == "png") { format = this._pngOptions; } if (format == "jpg") { format = this._jpegOptions; } return img.Encode(format); } // Format not expected so throw exception throw new InvalidTileFormatException( string.Format("Invalid tile FORMAT {0}", format) ); } }
public void VectorTile_AddImage() { VectorTile v = new VectorTile(1, 0, 0); byte[] bytes = File.ReadAllBytes(@".\data\world_1.0.0.png"); v.AddImage(bytes, "raster"); Assert.IsFalse(v.Empty()); Assert.IsTrue(v.Painted()); CollectionAssert.AreEquivalent(new List<string>() { "raster" }, v.Names().ToList()); Map m = new Map(256, 256); m.Load(@".\data\raster_style.xml"); Image i = new Image(256, 256); v.Render(m, i); Assert.AreEqual(0,i.Compare(Image.FromBytes(bytes))); }