// This must be called in order for rotation and position offset to by applied public void RenderPoints(SuperTile tile, GridOrientation orientation, Vector2 gridSize) { if (orientation == GridOrientation.Isometric) { m_Position = IsometricTransform(m_Position, tile, gridSize); m_Position.x += gridSize.x * 0.5f; for (int i = 0; i < m_Points.Length; i++) { m_Points[i] = IsometricTransform(m_Points[i], tile, gridSize); } // Also, we are forced to use polygon colliders for isometric projection if (m_CollisionShapeType == CollisionShapeType.Ellipse || m_CollisionShapeType == CollisionShapeType.Rectangle) { m_CollisionShapeType = CollisionShapeType.Polygon; } } // Burn rotation into our points ApplyRotationToPoints(); // Burn translation into our points m_Points = m_Points.Select(p => p + m_Position).ToArray(); // Transform all points so that they wrt the bottom-left of the tile // This should make calculations later easier since Tiled treats the bottom-left corner of a tile as the local origin m_Points = m_Points.Select(p => LocalTransform(p, tile)).ToArray(); m_Position = LocalTransform(m_Position, tile); }
public static void SwitchGridOrientation() { if (m_isGridActive) { m_gridOrientation = MyUtils.GetNextOrPreviousEnumValue(m_gridOrientation, true); } }
IEnumerator undoMove() { if (OnUndoStart != null) { OnUndoStart(); } woodBlockManager.SetBlockKinemactics(true); BlockUndoModule.UndoAllBlocks(); yield return(waitUndo); yield return(new WaitForSeconds(undoWaitExtra)); undoWaitExtra = 0.0f; Vector3 targetVector; GridOrientation currentOrientation = LastMoves.Pop(); if (currentOrientation == GridOrientation.Left) { targetVector = new Vector3(0, 0, -90); currentOrientation = GridOrientation.Right; } else { targetVector = new Vector3(0, 0, 90); } theTween = targetRotation.DORotate(targetVector, rotationTime).SetEase(Ease.OutSine).OnComplete(OnUndoTweenComplete).SetRelative(); }
public void Paint(DimensionHierarchy hierarchy, GridPosition startPosition, GridOrientation orientation) { var placement = new ZigZagPlacement(startPosition, orientation); for (int level = 0; level < hierarchy.LevelCount; ++level) { var previousMeasurement = new object(); var currentItem = default(UIElement); for (int keyIndex = 0; keyIndex < hierarchy.KeyCount; ++keyIndex) { var measurement = hierarchy.Keys[keyIndex].Measurements[level]; if (!Equals(previousMeasurement, measurement)) { currentItem = _itemFactory.CreateHeaderItem(measurement); _grid.Children.Add(currentItem); if (keyIndex > 0) { placement.NextSlot(); } placement.ApplySlot(currentItem); } else { placement.ExtendSlot(); placement.ApplySlot(currentItem); } previousMeasurement = measurement; } placement.NextLevel(); } }
public static void LoadData() { m_gridStepMode = MyFakes.MWBUILDER ? GridStep.STEP_LEVEL_4 : GridStep.STEP_LEVEL_3; m_gridOrientation = GridOrientation.ORIENTATION_XY; m_gridColor = MyEditorConstants.COLOR_WHITE; m_isGridVisible = false; m_gridStepInMeters = GetGridStepInMeters(); }
public Grid(IPoint origin, int tileSizeX, int tileSizeY, double dpi, GridOrientation orientation) { _origin = origin; _tileSizeX = tileSizeX; _tileSizeY = tileSizeY; _dpi = dpi; _orientation = orientation; }
void DrawLines(GridOrientation orientation) { int viewportHeight = this.Height - (int)this.MarginTop; int viewportHeightFactor = 200; int viewportWidth = this.Width - (int)this.MarginRight; int horizontalStart = (int)MarginLeft; int verticalStart = (int)MarginBottom; using (Pen p = new Pen(Color.FromArgb(this.GridOpacity, this.GridColor), this.GridPenWidth)) { p.DashStyle = DashStyle.Dash; int incrementAmount = 0; if (orientation == GridOrientation.Horizontal) { incrementAmount = GridSpacingHorizontal; int verticalHalfWayPoint = DetermineMiddlePoint(0, viewportHeight, incrementAmount); for (int i = verticalStart; i < viewportHeight; i += incrementAmount) { //if (i == verticalHalfWayPoint) //{ // // Draw the center line // using (var p2 = new Pen(Color.FromArgb(100, Color.Green), 2)) // { // Graphics?.DrawLine(p2, 0, i, viewportWidth, i); // } //} //else //{ Graphics?.DrawLine(p, horizontalStart, i, viewportWidth, i); //} } } else if (orientation == GridOrientation.Vertical) { incrementAmount = this.GridSpacingHorizontal; int horizontalHalfWayPoint = DetermineMiddlePoint(0, viewportWidth, incrementAmount); for (int i = horizontalStart; i < viewportWidth; i += incrementAmount) { //if (i == horizontalHalfWayPoint) //{ // // Draw the center line // using (var p2 = new Pen(Color.FromArgb(100, Color.Green), 2)) // { // Graphics?.DrawLine(p2, i, 0, i, viewportHeight); // } //} //else //{ Graphics?.DrawLine(p, i, verticalStart, i, viewportHeight); //} } } } }
private void btnPreRender_Click(object sender, EventArgs e) { _preRenderScales.Clear(); foreach (ListViewItem item in lstScales.Items) { if (item.Checked) { _preRenderScales.Add(double.Parse(item.Text.Replace(",", "."), _nhi)); } } _maxParallelRequests = (int)numMaxParallelRequest.Value; switch (cmbImageFormat.SelectedItem.ToString().ToLower()) { case "image/png": _imgExt = ".png"; break; case "image/jpeg": _imgExt = ".jpg"; break; } switch (cmbOrigin.SelectedItem.ToString().ToLower()) { case "upper left": _orientation = GridOrientation.UpperLeft; break; case "lower left": _orientation = GridOrientation.LowerLeft; break; } _selectedEpsg = (int)cmbEpsg.SelectedItem; if (chkUseExtent.Checked == true) { _bounds = this.CurrentExtent; } else { _bounds = null; } _cacheFormat = cmbCacheFormat.SelectedItem.ToString().ToLower(); Thread thread = new Thread(new ThreadStart(this.Run)); FormProgress dlg = new FormProgress(this, thread); dlg.ShowDialog(); }
public TileRenderer(TileServiceMetadata metadata, int epsg, GridOrientation orientation = GridOrientation.UpperLeft, string cacheFormat = "compact", string imageFormat = ".png", IEnvelope bbox = null, IEnumerable<double> preRenderScales = null, int maxParallelRequests = 1) { _metadata = metadata; _epsg = epsg; _orientation = orientation; _cacheFormat = cacheFormat; _imageFormat = imageFormat; _bbox = bbox; _preRenderScales = preRenderScales; _maxParallelRequests = maxParallelRequests; }
private void GetTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation, bool renderOnTheFly) { if (!metadata.EPSGCodes.Contains(epsg)) { throw new ArgumentException("Wrong epsg argument"); } //if (!metadata.Scales.Contains(scale)) // throw new ArgumentException("Wrong scale argument"); scale = metadata.Scales.GetScale(scale); if (scale <= 0.0) { throw new ArgumentException("Wrong scale argument"); } //IEnvelope bounds = metadata.GetEPSGEnvelope(epsg); //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0) // throw new Exception("No bounds defined for EPSG:" + epsg); format = format.ToLower(); if (format != ".png" && format != ".jpg") { throw new Exception("Unsupported image format"); } if (format == ".png" && metadata.FormatPng == false) { throw new Exception("Format image/png not supported"); } if (format == ".jpg" && metadata.FormatJpg == false) { throw new Exception("Format image/jpeg no supported"); } string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" + TileServiceMetadata.TilePath(orientation, epsg, scale, row, col) + format; if ((orientation == GridOrientation.UpperLeft && metadata.UpperLeftCacheTiles) || (orientation == GridOrientation.LowerLeft && metadata.LowerLeftCacheTiles)) { FileInfo fi = new FileInfo(path); if (fi.Exists) { context.ServiceRequest.Response = fi.FullName; return; } else if (!renderOnTheFly && !metadata.RenderTilesOnTheFly) { return; // Empty } if (!fi.Directory.Exists) { fi.Directory.Create(); } } else { path = _mapServer.OutputPath + @"\tile_" + Guid.NewGuid().ToString("N").ToLower() + format; } ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg); using (IServiceMap map = context.ServiceMap) { map.Display.SpatialReference = sRef; map.Display.dpi = metadata.Dpi; map.Display.iWidth = metadata.TileWidth; map.Display.iHeight = metadata.TileHeight; double res = (double)scale / (metadata.Dpi / 0.0254); if (map.Display.MapUnits != GeoUnits.Meters) { GeoUnitConverter converter = new GeoUnitConverter(); res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits); } var origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg); double H = metadata.TileHeight * res; double y = (orientation == GridOrientation.UpperLeft ? origin.Y - H * (row + 1) : origin.Y + H * row); double W = metadata.TileWidth * res; //if (map.Display.MapUnits == GeoUnits.DecimalDegrees) //{ // double phi = (2 * y + H) / 2.0; // W /= Math.Cos(phi / 180.0 * Math.PI); //} double x = origin.X + W * col; map.Display.ZoomTo(new Envelope(x, y, x + W, y + H)); map.Render(); bool maketrans = map.Display.MakeTransparent; map.Display.MakeTransparent = true; map.SaveImage(path, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png); map.Display.MakeTransparent = maketrans; context.ServiceRequest.Response = path; _mapServer.Log("CreateTile:", loggingMethod.request_detail, path); } }
public ZigZagPlacement(GridPosition startPosition, GridOrientation orientation) { _orientation = orientation; _levelStartPosition = startPosition; _currentSlot = new GridArea(startPosition, startPosition); }
static int Main(string[] args) { try { PlugInManager.InitSilent = true; Action action = Action.None; string server = String.Empty, service = String.Empty, cacheFormat = "normal"; int epsg = 0, maxParallelRequests = 1; GridOrientation orientation = GridOrientation.UpperLeft; IEnvelope bbox = null; List <int> scales = new List <int>(); for (int i = 0; i < args.Length; i++) { if (args[i] == "-server") { server = args[++i]; } if (args[i] == "-service") { service = args[++i]; } if (args[i] == "-info") { action = Action.Info; } if (args[i] == "-render") { action = Action.Render; } if (args[i] == "-compact") { cacheFormat = "compact"; } if (args[i] == "-epsg") { epsg = int.Parse(args[++i]); } if (args[i] == "-orientation") { switch (args[++i].ToLower()) { case "ul": case "upperleft": orientation = GridOrientation.UpperLeft; break; case "ll": case "lowerleft": orientation = GridOrientation.LowerLeft; break; } } if (args[i] == "-bbox") { bbox = Envelope.FromBBox(args[++i]); } if (args[i] == "-scales") { scales.AddRange(args[++i].Split(',').Select(v => int.Parse(v))); } if (args[i] == "-threads") { maxParallelRequests = int.Parse(args[++i]); } } if (action == Action.None || String.IsNullOrWhiteSpace(server) || String.IsNullOrWhiteSpace(service)) { Console.WriteLine("USAGE:"); Console.WriteLine("gView.Cmd.RenderTileCache <-info|-render> -server <server> -service <service>"); Console.WriteLine(" optional paramters: -epsg <epsg-code> [default: first]"); Console.WriteLine(" -compact ... create a compact tile cache"); Console.WriteLine(" -orientation <ul|ll|upperleft|lowerleft> [default: upperleft]"); Console.WriteLine(" -bbox <minx,miny,maxx,maxy> [default: fullextent]"); Console.WriteLine(" -scales <scale1,scale2,...> [default: empty => all scales"); Console.WriteLine(" -threads <max-parallel-requests> [default: 1]"); return(1); } #region Read Metadata var metadata = new TileServiceMetadata().FromService(server, service); if (metadata == null) { throw new Exception("Can't read metadata from server. Are you sure taht ervice is a gView WMTS service?"); } #endregion if (action == Action.Info) { #region TileSize Console.WriteLine($"TileSize [Pixel]: { metadata.TileWidth } x { metadata.TileHeight }"); #endregion #region ImageFormat Console.Write("ImageFormats:"); Console.Write(metadata.FormatJpg ? " jpg" : ""); Console.Write(metadata.FormatPng ? " png" : ""); Console.WriteLine(); #endregion #region Scales Console.WriteLine("Scales:"); if (metadata.Scales != null) { foreach (var scale in metadata.Scales) { Console.WriteLine($" 1 : { scale }"); } } #endregion #region Origin Console.Write("Origin:"); Console.Write(metadata.UpperLeft ? " upperleft" : ""); Console.Write(metadata.LowerLeft ? " lowerleft" : ""); Console.WriteLine(); if (metadata.EPSGCodes != null) { foreach (var epsgCode in metadata.EPSGCodes) { if (metadata.UpperLeft) { var ul = metadata.GetOriginUpperLeft(epsgCode); Console.WriteLine($" EPSG:{ epsgCode } upperleft: { ul.X }, { ul.Y }"); } if (metadata.LowerLeft) { var ll = metadata.GetOriginUpperLeft(epsgCode); Console.WriteLine($" EPSG:{ epsgCode } lowerleft: { ll.X }, { ll.Y }"); } } } #endregion #region Extents Console.WriteLine("BBox:"); if (metadata.EPSGCodes != null) { foreach (var epsgCode in metadata.EPSGCodes) { var envelope = metadata.GetEPSGEnvelope(epsgCode); if (envelope != null) { Console.WriteLine($" EPSG:{ epsgCode }: { envelope.minx }, { envelope.miny }, { envelope.maxx }, { envelope.maxy }"); } } } #endregion } else if (action == Action.Render) { var startTime = DateTime.Now; List <double> preRenderScales = new List <double>(); if (scales.Count > 0) { preRenderScales.AddRange(scales.Where(s => metadata.Scales.Contains(s)).Select(s => (double)s)); } var tileRender = new TileRenderer(metadata, epsg > 0 ? epsg : metadata.EPSGCodes.First(), cacheFormat: cacheFormat, orientation: orientation, bbox: bbox, preRenderScales: preRenderScales.Count > 0 ? preRenderScales : null, maxParallelRequests: maxParallelRequests); tileRender.Renderer(server, service); Console.WriteLine(); Console.WriteLine($"Finished: { Math.Round((DateTime.Now - startTime).TotalSeconds) }sec"); } return(0); } catch (Exception ex) { Console.WriteLine("Exception:"); Console.WriteLine(ex.Message); return(1); } }
public static void UpdateGridOrientation(Camera camera) { if (camera == null) { return; } var camera_position = camera.cameraToWorldMatrix.MultiplyPoint(MathConstants.zeroVector3); var camera_forward = camera.cameraToWorldMatrix.MultiplyVector(MathConstants.forwardVector3); gridOrientation = new GridOrientation(); gridOrientation.gridCamera = camera; gridOrientation.gridCameraPosition = camera_position; if (Tools.pivotRotation == PivotRotation.Local) { var activeTransform = Selection.activeTransform; if (activeTransform != null) { var parentCenter = MathConstants.zeroVector3; var parent = activeTransform.parent; if (parent != null) { parentCenter = parent.position; } gridOrientation.gridRotation = Tools.handleRotation; gridOrientation.gridCenter = parentCenter; } } gridOrientation.gridOrthoXVisible = false; gridOrientation.gridOrthoYVisible = false; gridOrientation.gridOrthoZVisible = false; gridOrientation.gridOrtho = false; gridOrientation.gridOrthoXAlpha = 0.0f; gridOrientation.gridOrthoYAlpha = 0.0f; gridOrientation.gridOrthoZAlpha = 0.0f; gridOrientation.gridWorkCenter = gridOrientation.gridCenter; gridOrientation.gridWorkRotation = gridOrientation.gridRotation; if (camera.orthographic) { gridOrientation.gridOrtho = true; Vector3 dots = new Vector3( Mathf.Clamp01(Mathf.Abs(Vector3.Dot(camera_forward, gridOrientation.gridRotation * MathConstants.rightVector3)) - 0.6f), Mathf.Clamp01(Mathf.Abs(Vector3.Dot(camera_forward, gridOrientation.gridRotation * MathConstants.upVector3)) - 0.3f), Mathf.Clamp01(Mathf.Abs(Vector3.Dot(camera_forward, gridOrientation.gridRotation * MathConstants.forwardVector3)) - 0.6f) ).normalized; dots.x *= dots.x; dots.y *= dots.y; dots.z *= dots.z; if (dots.x > 0.5f) { Quaternion rotation = Quaternion.AngleAxis(90.0f, MathConstants.forwardVector3); gridOrientation.gridOrthoXRotation = gridOrientation.gridRotation * rotation; gridOrientation.gridOrthoXVisible = true; gridOrientation.gridOrthoXAlpha = dots.x; } if (dots.y > 0.5f) { gridOrientation.gridOrthoYRotation = gridOrientation.gridRotation; gridOrientation.gridOrthoYVisible = true; gridOrientation.gridOrthoYAlpha = dots.y; } if (dots.z > 0.5f) { Quaternion rotation = Quaternion.AngleAxis(90.0f, MathConstants.leftVector3); gridOrientation.gridOrthoZRotation = gridOrientation.gridRotation * rotation; gridOrientation.gridOrthoZVisible = true; gridOrientation.gridOrthoZAlpha = dots.z; } if (dots.y > dots.z) { if (dots.y > dots.x) { gridOrientation.gridWorkRotation = gridOrientation.gridOrthoYRotation; } else { gridOrientation.gridWorkRotation = gridOrientation.gridOrthoXRotation; } } else { if (dots.z > dots.x) { gridOrientation.gridWorkRotation = gridOrientation.gridOrthoZRotation; } else { gridOrientation.gridWorkRotation = gridOrientation.gridOrthoXRotation; } } gridOrientation.gridPlane = new CSGPlane(gridOrientation.gridWorkRotation, gridOrientation.gridWorkCenter); } else { gridOrientation.gridPlane = new CSGPlane(gridOrientation.gridWorkRotation, gridOrientation.gridWorkCenter); if (ForceGrid) { gridOrientation.gridWorkCenter = ForcedGridCenter; gridOrientation.gridWorkRotation = ForcedGridRotation; } } gridOrientation.gridWorkInvRotation = Quaternion.Inverse(gridOrientation.gridWorkRotation); // find point on the plane that is nearest to camera var normal = gridOrientation.gridWorkRotation * MathConstants.upVector3; var d = Vector3.Dot(normal, gridOrientation.gridCenter); var position = (new CSGPlane(normal, d)).Project(gridOrientation.gridCameraPosition); gridOrientation.gridCameraSnapped = position; gridOrientation.gridWorkPlane = new CSGPlane(normal, position); var euler = gridOrientation.gridWorkInvRotation.eulerAngles; euler.x = Mathf.Round(euler.x / 90) * 90; euler.y = Mathf.Round(euler.y / 90) * 90; euler.z = Mathf.Round(euler.z / 90) * 90; gridOrientation.gridSnapVector = Quaternion.Euler(euler) * RealtimeCSG.CSGSettings.SnapVector; var snap_scale = Quaternion.Euler(euler) * new Vector3(RealtimeCSG.CSGSettings.LockAxisX ? 0 : 1, RealtimeCSG.CSGSettings.LockAxisY ? 0 : 1, RealtimeCSG.CSGSettings.LockAxisZ ? 0 : 1); snap_scale.x = Mathf.Abs(snap_scale.x); snap_scale.y = Mathf.Abs(snap_scale.y); snap_scale.z = Mathf.Abs(snap_scale.z); gridOrientation.gridSnapScale = snap_scale; }
private byte[] GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation) { if (!metadata.EPSGCodes.Contains(epsg)) { throw new ArgumentException("Wrong epsg argument"); } if (orientation != GridOrientation.UpperLeft) { throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!"); } scale = metadata.Scales.GetScale(scale); if (scale <= 0.0) { throw new ArgumentException("Wrong scale argument"); } //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg); //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0) // throw new Exception("No bounds defined for EPSG:" + epsg); IPoint origin = metadata.GetOriginUpperLeft(epsg); if (origin == null) { throw new Exception("No origin defined for EPSG:" + epsg); } format = format.ToLower(); if (format != ".png" && format != ".jpg") { throw new Exception("Unsupported image format"); } if (format == ".png" && metadata.FormatPng == false) { throw new Exception("Format image/png not supported"); } if (format == ".jpg" && metadata.FormatJpg == false) { throw new Exception("Format image/jpeg no supported"); } string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" + TileServiceMetadata.ScalePath(orientation, epsg, scale); string compactTileName = CompactTileName(row, col); string bundleFilename = path + @"\" + compactTileName + ".tilebundle"; string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done"; string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc"; if (new FileInfo(bundleFilename).Exists) { return(GetCompactTileBytes(context, path, row, col, format)); } if (IsDirectoryEmpty(path)) { #region On The Fly using (IServiceMap map = context.ServiceMap) { ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg); map.Display.SpatialReference = sRef; map.Display.dpi = metadata.Dpi; map.Display.iWidth = metadata.TileWidth; map.Display.iHeight = metadata.TileHeight; double res = (double)scale / (metadata.Dpi / 0.0254); if (map.Display.MapUnits != GeoUnits.Meters) { GeoUnitConverter converter = new GeoUnitConverter(); res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits); } origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg); double H = metadata.TileHeight * res; double y = (orientation == GridOrientation.UpperLeft ? origin.Y - H * (row + 1) : origin.Y + H * row); double W = metadata.TileWidth * res; double x = origin.X + W * col; map.Display.ZoomTo(new Envelope(x, y, x + W, y + H)); map.Render(); bool maketrans = map.Display.MakeTransparent; map.Display.MakeTransparent = true; MemoryStream ms = new MemoryStream(); map.SaveImage(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png); map.Display.MakeTransparent = maketrans; return(ms.ToArray()); } #endregion #region Tile from Existing UpLevel Tiles (Vorteil Resampling wird nicht von Browser erledigt, ist meistens Fast -> hier Nearstneigbor) int level2 = metadata.Scales.IndexOf(scale); if (level2 <= 0) { return(null); } using (IServiceMap map = context.ServiceMap) { double res = (double)scale / (metadata.Dpi / 0.0254); if (map.Display.MapUnits != GeoUnits.Meters) { GeoUnitConverter converter = new GeoUnitConverter(); res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits); } double H = metadata.TileHeight * res; double y = origin.Y - H * (row + 1); double W = metadata.TileWidth * res; double x = origin.X + W * col; while (true) { if (level2 <= 0) { break; } double scale2 = metadata.Scales[level2 - 1]; string path2 = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" + TileServiceMetadata.ScalePath(orientation, epsg, scale2); if (IsDirectoryEmpty(path2)) { level2--; continue; } double res2 = scale2 / (metadata.Dpi / 0.0254); double W2 = metadata.TileWidth * res2; double H2 = metadata.TileHeight * res2; int col2_0 = (int)Math.Floor((x - origin.X) / W2); int row2_0 = (int)Math.Floor((origin.Y - (y + H)) / H2); int col2_1 = (int)Math.Floor((x + W - origin.X) / W2); int row2_1 = (int)Math.Floor((origin.Y - y) / H2); double x2_0 = origin.X + W2 * col2_0, y2_0 = origin.Y - H2 * (row2_1 + 1); double W20 = Math.Abs(col2_1 - col2_0 + 1) * W2, H20 = Math.Abs(row2_1 - row2_0 + 1) * H2; using (Bitmap bm = new Bitmap(Math.Abs(col2_1 - col2_0 + 1) * metadata.TileWidth, Math.Abs(row2_1 - row2_0 + 1) * metadata.TileHeight)) using (Graphics gr = Graphics.FromImage(bm)) { for (int r2 = row2_0; r2 <= row2_1; r2++) { for (int c2 = col2_0; c2 <= col2_1; c2++) { byte[] buffer = GetCompactTileBytes(context, path2, r2, c2, format); if (buffer != null && buffer.Length > 0) { MemoryStream ms = new MemoryStream(buffer); var tileImage = Image.FromStream(ms); gr.DrawImage(tileImage, new PointF((c2 - col2_0) * metadata.TileWidth, (r2 - row2_0) * metadata.TileHeight)); } } } float imageX = (float)((x - x2_0) / W20 * (double)bm.Width); float imageY = bm.Height - (float)((y - y2_0) / H20 * (double)bm.Height); float imageW = (float)((double)metadata.TileWidth * res / res2); float imageH = (float)((double)metadata.TileHeight * res / res2); using (Bitmap outputBm = new Bitmap(metadata.TileWidth, metadata.TileHeight)) using (Graphics outputGr = Graphics.FromImage(outputBm)) { outputGr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; outputGr.DrawImage(bm, new RectangleF(-.5f, -.5f, (float)outputBm.Width + 1f, (float)outputBm.Height + 1f), new RectangleF(imageX, imageY - imageH, imageW, imageH), GraphicsUnit.Pixel); MemoryStream output = new MemoryStream(); outputBm.Save(output, format == ".png" ? ImageFormat.Png : ImageFormat.Jpeg); return(output.ToArray()); } } } } #endregion } return(null); }
private byte[] GetTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation) { if (!metadata.EPSGCodes.Contains(epsg)) { throw new ArgumentException("Wrong epsg argument"); } //if (!metadata.Scales.Contains(scale)) // throw new ArgumentException("Wrong scale argument"); scale = metadata.Scales.GetScale(scale); if (scale <= 0.0) { throw new ArgumentException("Wrong scale argument"); } //IEnvelope bounds = metadata.GetEPSGEnvelope(epsg); //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0) // throw new Exception("No bounds defined for EPSG:" + epsg); format = format.ToLower(); if (format != ".png" && format != ".jpg") { throw new Exception("Unsupported image format"); } if (format == ".png" && metadata.FormatPng == false) { throw new Exception("Format image/png not supported"); } if (format == ".jpg" && metadata.FormatJpg == false) { throw new Exception("Format image/jpeg no supported"); } string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" + TileServiceMetadata.TilePath(orientation, epsg, scale, row, col) + format; if ((orientation == GridOrientation.UpperLeft && metadata.UpperLeftCacheTiles) || (orientation == GridOrientation.LowerLeft && metadata.LowerLeftCacheTiles)) { FileInfo fi = new FileInfo(path); if (fi.Exists) { //context.ServiceRequest.Response = fi.FullName; using (FileStream fs = File.Open(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) //new FileStream(bundleFilename, FileMode.Open, FileAccess.Read)) { byte[] data = new byte[fi.Length]; fs.Read(data, 0, data.Length); return(data); } } } return(null); }
private bool HasOrientation(GridOrientation orient) { return((orient & Orientation) > 0); }
private byte[] GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation) { if (!metadata.EPSGCodes.Contains(epsg)) { throw new ArgumentException("Wrong epsg argument"); } if (orientation != GridOrientation.UpperLeft) { throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!"); } scale = metadata.Scales.GetScale(scale); if (scale <= 0.0) { throw new ArgumentException("Wrong scale argument"); } //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg); //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0) // throw new Exception("No bounds defined for EPSG:" + epsg); IPoint origin = metadata.GetOriginUpperLeft(epsg); if (origin == null) { throw new Exception("No origin defined for EPSG:" + epsg); } format = format.ToLower(); if (format != ".png" && format != ".jpg") { throw new Exception("Unsupported image format"); } if (format == ".png" && metadata.FormatPng == false) { throw new Exception("Format image/png not supported"); } if (format == ".jpg" && metadata.FormatJpg == false) { throw new Exception("Format image/jpeg no supported"); } string path = _mapServer.TileCachePath + @"\" + MapName(context) + @"\_alllayers\compact\" + TileServiceMetadata.ScalePath(orientation, epsg, scale); string compactTileName = CompactTileName(row, col); string bundleFilename = path + @"\" + compactTileName + ".tilebundle"; string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done"; string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc"; if (new FileInfo(bundleFilename).Exists) { return(GetCompactTileBytes(context, path, row, col, format)); } if (IsDirectoryEmpty(path)) { #region On The Fly using (IServiceMap map = context.CreateServiceMapInstance()) { ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg); map.Display.SpatialReference = sRef; map.Display.dpi = metadata.Dpi; map.Display.iWidth = metadata.TileWidth; map.Display.iHeight = metadata.TileHeight; double res = (double)scale / (metadata.Dpi / 0.0254); if (map.Display.MapUnits != GeoUnits.Meters) { GeoUnitConverter converter = new GeoUnitConverter(); res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits); } origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg); double H = metadata.TileHeight * res; double y = (orientation == GridOrientation.UpperLeft ? origin.Y - H * (row + 1) : origin.Y + H * row); double W = metadata.TileWidth * res; double x = origin.X + W * col; map.Display.ZoomTo(new Envelope(x, y, x + W, y + H)); map.Render(); bool maketrans = map.Display.MakeTransparent; map.Display.MakeTransparent = true; MemoryStream ms = new MemoryStream(); map.SaveImage(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png); map.Display.MakeTransparent = maketrans; return(ms.ToArray()); } #endregion } return(null); }
public static string ScalePath(GridOrientation orientation, int epsg, double scale) { return ((orientation == GridOrientation.UpperLeft ? "ul" : "ll") + @"/" + epsg + @"/" + (int)Math.Round(scale) + @"/"); }
private void GetCompactTile(IServiceRequestContext context, TileServiceMetadata metadata, int epsg, double scale, int row, int col, string format, GridOrientation orientation, BoundingTiles boundingTiles, bool renderOnTheFly) { if (!metadata.EPSGCodes.Contains(epsg)) { throw new ArgumentException("Wrong epsg argument"); } if (orientation != GridOrientation.UpperLeft) { throw new ArgumentException("Compact Tiles Orientation must bei Upper Left!"); } scale = metadata.Scales.GetScale(scale); if (scale <= 0.0) { throw new ArgumentException("Wrong scale argument"); } //IEnvelope bounds = metadata.GetEGPSEnvelope(epsg); //if (bounds == null || bounds.Width == 0.0 || bounds.Height == 0.0) // throw new Exception("No bounds defined for EPSG:" + epsg); IPoint origin = metadata.GetOriginUpperLeft(epsg); if (origin == null) { throw new Exception("No origin defined for EPSG:" + epsg); } format = format.ToLower(); if (format != ".png" && format != ".jpg") { throw new Exception("Unsupported image format"); } if (format == ".png" && metadata.FormatPng == false) { throw new Exception("Format image/png not supported"); } if (format == ".jpg" && metadata.FormatJpg == false) { throw new Exception("Format image/jpeg no supported"); } string path = _mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\compact\" + TileServiceMetadata.ScalePath(orientation, epsg, scale); string compactTileName = CompactTileName(row, col); string bundleFilename = path + @"\" + compactTileName + ".tilebundle"; string bundleDoneFilename = path + @"\" + compactTileName + ".tilebundle.done"; string bundleCalcFilename = path + @"\" + compactTileName + ".tilebundle.calc"; if (new FileInfo(bundleFilename).Exists) { GetCompactTileBytes(context, path, row, col); return; } else if (!renderOnTheFly || new FileInfo(bundleDoneFilename).Exists || new FileInfo(bundleCalcFilename).Exists /* && !metadata.RenderTilesOnTheFly*/) { return; // Empty } DirectoryInfo di = new DirectoryInfo(path); if (!di.Exists) { di.Create(); } try { File.Delete(bundleFilename); } catch { } //temp //string pathTemp = path + @"\temp"; //DirectoryInfo diTemp = new DirectoryInfo(pathTemp); //if (!diTemp.Exists) // diTemp.Create(); File.WriteAllText(bundleCalcFilename, "calc..."); CompactTilesIndexBuilder indexBuilder = new CompactTilesIndexBuilder(); int startRow = CompactTileStart(row), startCol = CompactTileStart(col); ISpatialReference sRef = SpatialReference.FromID("epsg:" + epsg); using (IServiceMap map = context.ServiceMap) { map.Display.SpatialReference = sRef; map.Display.dpi = metadata.Dpi; double res = (double)scale / (metadata.Dpi / 0.0254); if (map.Display.MapUnits != GeoUnits.Meters) { GeoUnitConverter converter = new GeoUnitConverter(); res = converter.Convert(res, GeoUnits.Meters, map.Display.MapUnits); } string bundleTempFilename = path + @"\" + compactTileName + "." + Guid.NewGuid().ToString("N").ToLower() + ".tilebundle"; string bundleIndexFilename = path + @"\" + compactTileName + ".tilebundlx"; File.WriteAllBytes(bundleTempFilename, new byte[0]); int bundlePos = 0; int tileMatrixWidth = 8, tileMatrixHeight = 8; map.Display.iWidth = metadata.TileWidth * tileMatrixWidth; map.Display.iHeight = metadata.TileHeight * tileMatrixHeight; for (int r = 0; r < 128; r += 8) { File.WriteAllText(bundleCalcFilename, "calc...row" + r); for (int c = 0; c < 128; c += 8) { int currentRow = r + startRow, currentCol = c + startCol; if (boundingTiles != null) { if (!boundingTiles.Check(currentRow, currentCol, 8, 8)) { continue; } } double H = metadata.TileHeight * res; double y = origin.Y - H * (currentRow + tileMatrixHeight); double W = metadata.TileWidth * res; double x = origin.X + W * currentCol; map.Display.ZoomTo(new Envelope(x, y, x + W * tileMatrixWidth, y + H * tileMatrixHeight)); if (format != ".jpg") // Make PNG Transparent { map.Display.BackgroundColor = System.Drawing.Color.Transparent; } map.ReleaseImage(); // Delete old Image !!! Because there is no map.SaveImage()!!!! map.Render(); if (IsEmptyBitmap(map.MapImage, map.Display.BackgroundColor)) { continue; } // Temp //map.MapImage.Save(pathTemp + @"\matrix_" + (startRow + r) + "_" + (startCol + c) + ".png", ImageFormat.Png); for (int j = 0; j < tileMatrixHeight; j++) { for (int i = 0; i < tileMatrixWidth; i++) { int tileRow = currentRow + j, tileCol = currentCol + i; if (boundingTiles != null) { if (!boundingTiles.Check(tileRow, tileCol, 8, 8)) { continue; } } using (Bitmap bm = new Bitmap(metadata.TileWidth, metadata.TileHeight, map.MapImage.PixelFormat)) using (Graphics gr = Graphics.FromImage(bm)) { gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; gr.DrawImage(map.MapImage, new RectangleF(0f, 0f, (float)bm.Width, (float)bm.Height), new RectangleF(-0.5f + (float)(i * metadata.TileWidth), -0.5f + (float)(j * metadata.TileHeight), (float)metadata.TileWidth, (float)metadata.TileHeight), GraphicsUnit.Pixel); //for (int py = 0, to_py = bm.Height; py < to_py; py++) //{ // for (int px = 0, to_px = bm.Width; px < to_px; px++) // { // var pCol = map.MapImage.GetPixel(px + i * metadata.TileHeight, py + j * metadata.TileHeight); // bm.SetPixel(px, py, pCol); // } //} if (IsEmptyBitmap(bm, map.Display.BackgroundColor)) { continue; } // Temp //bm.Save(pathTemp + @"\tile_" + tileRow + "_" + tileCol + ".png", ImageFormat.Png); //try //{ // if (format != ".jpg" && map.Display.BackgroundColor.A > 0) // Make PNG Transparent // bm.MakeTransparent(map.Display.BackgroundColor); //} //catch { } MemoryStream ms = new MemoryStream(); bm.Save(ms, format == ".jpg" ? System.Drawing.Imaging.ImageFormat.Jpeg : System.Drawing.Imaging.ImageFormat.Png); byte[] imageBytes = ms.ToArray(); using (var stream = new FileStream(bundleTempFilename, FileMode.Append)) { stream.Write(imageBytes, 0, imageBytes.Length); } indexBuilder.SetValue(r + j, c + i, bundlePos, imageBytes.Length); bundlePos += imageBytes.Length; } } } } map.ReleaseImage(); GC.Collect(); } try { File.Delete(bundleFilename); } catch { } if (bundlePos == 0) { File.Delete(bundleTempFilename); File.WriteAllText(bundleDoneFilename, ""); } else { File.Move(bundleTempFilename, bundleFilename); indexBuilder.Save(bundleIndexFilename); } try { File.Delete(bundleCalcFilename); } catch { } } GC.Collect(); }
public static string EpsgPath(GridOrientation orientation, int epsg) { return ((orientation == GridOrientation.UpperLeft ? "ul" : "ll") + @"/" + epsg + @"/"); }
private void WriteConfFile(IServiceRequestContext context, TileServiceMetadata metadata, string cacheFormat, int epsg, string format, GridOrientation orientation) { FileInfo configFileInfo = new FileInfo(_mapServer.TileCachePath + @"\" + context.ServiceMap.Name + @"\_alllayers\" + cacheFormat + @"\" + TileServiceMetadata.EpsgPath(orientation, epsg) + @"\conf.json"); IPoint origin = orientation == GridOrientation.UpperLeft ? metadata.GetOriginUpperLeft(epsg) : metadata.GetOriginLowerLeft(epsg); IEnvelope bounds = metadata.GetEPSGEnvelope(epsg); if (origin == null || bounds == null) { return; } List <CompactTileConfig.LevelConfig> levels = new List <CompactTileConfig.LevelConfig>(); for (int i = 0; i < metadata.Scales.Count; i++) { levels.Add(new CompactTileConfig.LevelConfig() { Level = i, Scale = metadata.Scales[i] }); } CompactTileConfig config = new CompactTileConfig() { Epsg = epsg, Dpi = metadata.Dpi, Origin = new double[] { origin.X, origin.Y }, Extent = new double[] { bounds.minx, bounds.miny, bounds.maxx, bounds.maxy }, TileSize = new int[] { metadata.TileWidth, metadata.TileHeight }, Format = format, Orientation = orientation.ToString(), Levels = levels.ToArray() }; if (configFileInfo.Exists) { configFileInfo.Delete(); } if (!configFileInfo.Directory.Exists) { configFileInfo.Directory.Create(); } File.WriteAllText(configFileInfo.FullName, JsonConvert.SerializeObject(config, Formatting.Indented)); }
public static string TilePath(GridOrientation orientation, int epsg, double scale, int row, int col) { return ((orientation == GridOrientation.UpperLeft ? "ul" : "ll") + @"\" + epsg + @"\" + (int)Math.Round(scale) + @"\" + row + @"\" + col); }