/// <summary> /// Releases com objects /// </summary> /// <param name="disposeManagedResources"></param> protected virtual void Dispose(bool disposeManagedResources) { // process only if mananged and unmanaged resources have // not been disposed of. if (!m_Disposed) { //Trace.WriteLine("GridWrapper: Resources not disposed"); if (disposeManagedResources) { } // dispose unmanaged resources //Trace.WriteLine("GridWrapper: Disposing unmanaged resouces"); if (m_Grid != null) { //Trace.WriteLine("GridWrapper: Disposing of grid COM object"); m_Grid.Close(); while (Marshal.ReleaseComObject(m_Grid) != 0) { ; } m_Grid = null; } m_Disposed = true; } else { } }
protected virtual void Dispose(bool disposeManagedResources) { // process only if mananged and unmanaged resources have // not been disposed of. if (!this.disposed) { //Trace.WriteLine("GridWrapper: Resources not disposed"); if (disposeManagedResources) { //Trace.WriteLine("GridWrapper: Disposing managed resources"); // dispose managed resources gErrorMsg = null; } // dispose unmanaged resources //Trace.WriteLine("GridWrapper: Disposing unmanaged resouces"); if (grid != null) { //Trace.WriteLine("GridWrapper: Disposing of grid COM object"); grid.Close(); while (Marshal.ReleaseComObject(grid) != 0) { ; } grid = null; } disposed = true; } else { Trace.WriteLine("GridWrapper: Resources already disposed"); } }
/// <summary> /// This function copies a two dimensional array of float values to the appropriate space in the grid. /// </summary> /// <param name="OutputArray">The two dimensional array of floats to save to the grid</param> /// <param name="mwGrid">The MapWinGIS.grid to save the float values to</param> /// <param name="ICallBack">A MapWinGIS.ICallback for status messages</param> public void SaveArrayToWindow(float[][] OutputArray, MapWinGIS.Grid mwGrid, MapWinGIS.ICallback ICallBack) { // Write values to the grid int numCols = this.Rectangle.Width; int numRows = this.Rectangle.Height; float[] Temp = new float[numCols * numRows]; //Organize the OutputArray into a single window if (ICallBack != null) { ICallBack.Progress("Status", 0, "Copying value to 1-D array."); } for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { Temp[numCols * row + col] = OutputArray[row][col]; } } if (ICallBack != null) { ICallBack.Progress("Status", 0, "Saving window to grid"); } mwGrid.PutFloatWindow(this.Rectangle.Y, this.Rectangle.Bottom - 1, this.Rectangle.X, this.Rectangle.Right - 1, ref Temp[0]); return; }
public bool RunAutoSnap(string outletPath, string newOutletPath, string d8Result, string streamShapeResult, double snapThreshod) { MapWinGIS.Grid g = new MapWinGIS.Grid(); g.Open(d8Result); double dx = g.Header.dX; g.Close(); return(MapWinGeoProc.Utils.SnapPointsToLines(outletPath, streamShapeResult, snapThreshod, dx / 2, newOutletPath, true, null)); }
/// <summary> /// Querying a property from a null parameter will cause an error. /// Therefore, this checks for the null case. /// Returns a filename if the grid exists, and "null" otherwise. /// </summary> /// <param name="mwGrid">A MapWinGIS.Grid to obtain the filename for.</param> public static string ParamName(MapWinGIS.Grid mwGrid) { string filename = "null"; if (mwGrid == null) { filename = mwGrid.Filename; } return(filename); }
/// <summary> /// Er... Changes a grid format? /// </summary> /// <param name="origFilename">Original Grid Filename</param> /// <param name="newFilename">Output Grid Filename</param> /// <param name="newFileType">Specifies the original file format of the grid</param> /// <param name="newFileFormat">Specifies the new file format</param> /// <param name="multFactor">Like Extrusion, this multiplies the Z value</param> /// <returns>Boolean, false if there was an error</returns> public static bool ChangeGridFormat(string origFilename, string newFilename, MapWinGIS.GridFileType newFileType, MapWinGIS.GridDataType newFileFormat, float multFactor) { bool Errors = false; MapWinGIS.Grid tGrd = new MapWinGIS.Grid(); tGrd.Open(origFilename, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null); Logger.Status("Writing Grid to New Format"); //If we're multiplying by a factor, must //create the new grid and actually do it ourselves. //Otherwise, can save directly //Jiri Kadlec 1-28-2009 we still neet to create a new grid when the data or file type is different. if (multFactor == 1 && newFileFormat == tGrd.DataType) { Logger.Dbg("Saving directly to new format"); tGrd.Save(newFilename, newFileType, null); // ProgressForm) } else { Logger.Dbg("Saving to new format with mult. factor: " + multFactor.ToString()); MapWinGIS.GridHeader hdr = new MapWinGIS.GridHeader(); hdr.CopyFrom(tGrd.Header); MapWinGIS.Grid newgrid = new MapWinGIS.Grid(); if (!newgrid.CreateNew(newFilename, hdr, newFileFormat, hdr.NodataValue, true, newFileType, null)) { Logger.Message("Unable to create new grid!", "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.DialogResult.OK); Errors = true; } else { int ncols = tGrd.Header.NumberCols; int nrows = tGrd.Header.NumberRows; float[] oneRow = new float[ncols + 1]; for (int i = 0; i <= nrows - 1; i++) { tGrd.GetFloatWindow(i, i, 0, ncols, ref oneRow[0]); for (int z = 0; z <= ncols - 1; z++) { oneRow[z] *= multFactor; } newgrid.PutFloatWindow(i, i, 0, ncols, ref oneRow[0]); } newgrid.Save(newFilename, newFileType, null); newgrid.Close(); } } return(!Errors); }
private void InitThread() { try { m_Grid = new MapWinGIS.Grid(); } catch (Exception ex) { MapWinGIS.Utility.Logger.Message(ex.ToString()); } finally { m_Ready = true; } }
/// <summary> /// 创建一个新的LayerSource类实例 /// </summary> public LayerSource(object obj) { if (obj is MapWinGIS.Shapefile) { m_shapefile = obj as MapWinGIS.Shapefile; } else if (obj is MapWinGIS.Image) { m_image = obj as MapWinGIS.Image; } else if (obj is MapWinGIS.Grid) { m_grid = obj as MapWinGIS.Grid; } }
}//End Write_Vertical #endregion #region Array - Grid Handling /// <summary> /// Converts a region of a grid into a 2D array of float values /// </summary> /// <param name="mwSourceGrid">The grid to read</param> /// <param name="ICallBack">A MapWinGIS.ICallback for status messages</param> /// <returns>float[][] the values from the grid</returns> public float[][] GetArrayFromWindow(MapWinGIS.Grid mwSourceGrid, MapWinGIS.ICallback ICallBack) { if (mwSourceGrid == null) { if (ICallBack != null) { ICallBack.Error("Error", "SourceGrid cannot be null."); } throw new ArgumentException("SourceGrid cannot be null."); } int numRows = this.Rectangle.Height; int numCols = this.Rectangle.Width; // Populate the Array by directly reading values from the grid float[][] SourceArray = new float[numRows][]; float[] Temp = new float[numRows * numCols]; // Read from the ocx once, rather than calling several times if (ICallBack != null) { ICallBack.Progress("Status", 0, " Loading Values"); } mwSourceGrid.GetFloatWindow(this.Rectangle.Y, this.Rectangle.Bottom - 1, this.Rectangle.X, this.Rectangle.Right - 1, ref Temp[0]); if (ICallBack != null) { ICallBack.Progress("Status", 0, "Copying Values"); } for (int row = 0; row < numRows; row++) { SourceArray[row] = new float[numCols]; // for (int col = 0; col < numCols; col++) { // copy the values into a 2D style array because it improves // handling speeds for some reason SourceArray[row][col] = Temp[row * numCols + col]; } } if (ICallBack != null) { ICallBack.Progress("Status", 0, "Finished copying values from grid."); } return(SourceArray); }// End GetArrayFromWindow
private static void CreateGridFromExtents(MapWinGIS.Extents InExtents, double CellSize, String Projection, double NoDataValue, string OutGridPath, out MapWinGIS.Grid OutGrid) { double height = Math.Abs(InExtents.yMax - InExtents.yMin); double width = Math.Abs(InExtents.xMax - InExtents.xMin); OutGrid = new MapWinGIS.Grid(); MapWinGIS.GridHeader hdr = new MapWinGIS.GridHeader(); hdr.dX = CellSize; hdr.dY = CellSize; hdr.NodataValue = NoDataValue; hdr.NumberRows = int.Parse(Math.Ceiling(height / CellSize).ToString()); hdr.NumberCols = int.Parse(Math.Ceiling(width / CellSize).ToString()); hdr.Projection = Projection; hdr.XllCenter = InExtents.xMin + 0.5 * CellSize; hdr.YllCenter = InExtents.yMin + 0.5 * CellSize; OutGrid.CreateNew(OutGridPath, hdr, MapWinGIS.GridDataType.DoubleDataType, NoDataValue, true, MapWinGIS.GridFileType.UseExtension, null); }
public bool SetSoilPath(string soilPath) { string soilFileName = System.IO.Path.GetFileName(soilPath); string temp = prjPath + @"\Source\soil\" + soilFileName; if (System.IO.File.Exists(temp) == false) { System.IO.File.Copy(soilPath, temp); } // copy .prj file if any string prjsource = System.IO.Path.ChangeExtension(soilFileName, ".prj"); string prjtarget = System.IO.Path.ChangeExtension(temp, ".prj"); if (System.IO.File.Exists(prjsource) && (!System.IO.File.Exists(prjtarget))) { System.IO.File.Copy(prjsource, prjtarget); } hruGlobals.soilPath = temp; soilLayer = new MapWinGIS.Grid(); soilLayer.Open(soilPath); return(true); }
/// <summary> /// This creates a new shapefile that has Z values and follows along the same line segments. /// The boundaries for grid cells are marked with vertices and the segment is given a Z value /// that corresponds to the grid elevation it intersects. /// </summary> /// <param name="ElevGrid">A string filename for the grid that contains the elevations.</param> /// <param name="PolyLine">A string filename for a polyline shapefile that shows the pathways of the cross sections in the X-Y direction.</param> /// <param name="OutFileName">A string containing the full path of the desired output shapefile. The extension should be *.shp</param> /// <param name="CrossSectionType">Clarifies the type of output</param> /// <param name="ICallBack">A MapWinGIS.ICallback for progress messages. [Optional]</param> /// <remarks>This function throws Argument or Application exceptions on errors, so it's recommended that coders enclose it in a try catch block.</remarks> public static void GetCrossSection(string ElevGrid, string PolyLine, string OutFileName, CrossSectionTypes CrossSectionType, MapWinGIS.ICallback ICallBack) { bool res; // Load the grid if (ElevGrid == null) { throw new ArgumentException("ElevGrid cannot be null."); } if (System.IO.File.Exists(ElevGrid) == false) { throw new ArgumentException("The file " + ElevGrid + " does not exist."); } MapWinGIS.Grid mwGrid = new MapWinGIS.Grid(); res = mwGrid.Open(ElevGrid, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { throw new ApplicationException(mwGrid.get_ErrorMsg(mwGrid.LastErrorCode)); } // Load the Shapefile if (PolyLine == null) { throw new ArgumentException("PolyLine cannot be null."); } if (System.IO.File.Exists(PolyLine) == false) { throw new ArgumentException("The file " + PolyLine + " does not exist."); } MapWinGIS.Shapefile mwPolyLine = new MapWinGIS.Shapefile(); res = mwPolyLine.Open(PolyLine, ICallBack); if (res == false) { throw new ApplicationException(mwPolyLine.get_ErrorMsg(mwPolyLine.LastErrorCode)); } GetCrossSection(mwGrid, mwPolyLine, OutFileName, CrossSectionType, ICallBack); }
/// <summary> /// adds the new grid as a new layer to the map /// </summary> private void DisplayGrid(string grFileName) { MapWindow.Interfaces.Layer newLayer; MapWinGIS.GridColorScheme cS = new MapWinGIS.GridColorScheme(); try { newLayer = m_MapWin.Layers.Add(grFileName); MapWinGIS.Grid gr = newLayer.GetGridObject; cS = (MapWinGIS.GridColorScheme)newLayer.ColoringScheme; int i; for (i = 0; i < cS.NumBreaks; ++i) { cS.get_Break(i).ColoringType = MapWinGIS.ColoringType.Gradient; } m_MapWin.Layers.RebuildGridLayer(newLayer.Handle, gr, cS); } catch (Exception ex) { MapWinUtility.Logger.Msg("ERROR adding grid to the map. " + ex.Message); } }
/// <summary> /// 关闭图层. 设置未定义的图层类型 /// </summary> public void Close() { m_error = LayerSourceError.None; switch (this.Type) { case LayerSourceType.Shapefile: m_shapefile.Close(); m_shapefile = null; break; case LayerSourceType.Image: m_image.Close(); m_image = null; break; case LayerSourceType.Grid: m_grid.Close(); m_grid = null; break; default: break; } }
/// <summary> /// This is the core algorithm to fill the depressions in an image /// This concept is masterminded by the self proclaimed genius Ted Dunsford /// and is being prepared for publication. /// </summary> /// <param name="mwSourceGrid">The MapWinGIS.Grid to read the actual elevation values from</param> /// <param name="mwDestGrid">The MapWinGIS.Grid to write the elevations to</param> /// <param name="SpawnPoints">A list of points on the edges where the algorithm will start </param> /// <param name="myFrame">The current sub-division of the overall grid</param> /// <param name="DepsExist">A list of booleans for each direction indicating if dependencies were found in neighboring frames</param> /// <param name="myProgress">A Dialogs.ProgressDialog indicating the current progress of the algorithm.</param> /// <returns>TimeSpan indicating the time the function took to run the algorithm</returns> public static System.TimeSpan FloodDependencies(MapWinGIS.Grid mwSourceGrid, MapWinGIS.Grid mwDestGrid, List <Frame.Loc> SpawnPoints, Frame myFrame, bool[] DepsExist, Dialogs.ProgressDialog myProgress) { string strSpawnPoints = "null"; string strFrame = "null"; int Prog = 0; int OldProg = 0; if (SpawnPoints != null) { strSpawnPoints = SpawnPoints.Count.ToString(); } if (myFrame != null) { strFrame = "Frame [" + myFrame.Width.ToString() + " x " + myFrame.Height.ToString() + "]"; } MapWinUtility.Logger.Dbg("FloodDependencies(mwSourceGrid: " + Macro.ParamName(mwSourceGrid) + ",\n" + " mwDestGrid: " + Macro.ParamName(mwDestGrid) + ",\n" + " SpawnPoints: " + strSpawnPoints + " Locations,\n" + " myFrame: " + strSpawnPoints + ",\n" + " DepsExist: " + DepsExist.ToString() + " ProgressDialog)"); if (mwSourceGrid == null) { MapWinUtility.Logger.Dbg("Argument Exception: mwSourceGrid cannot be null."); throw new ArgumentException("mwSourceGrid cannot be null."); } if (mwDestGrid == null) { MapWinUtility.Logger.Dbg("Argument Exception: mwDestGrid cannot be null."); throw new ArgumentException("mwDestGrid cannot be null."); } if (SpawnPoints == null) { MapWinUtility.Logger.Dbg("Argument Exception: SpawnPoints cannot be null."); throw new ArgumentException("SpawnPoints cannot be null."); } if (myFrame == null) { MapWinUtility.Logger.Dbg("Argument Exception: myFrame cannot be null."); throw new ArgumentException("myFrame cannot be null."); } System.Drawing.Rectangle Window = myFrame.Rectangle; float[][] Source; float[][] Dest; int numRows = Window.Height; int numCols = Window.Width; mPoint pt; Frame.Loc ptStart; List <mPoint> DryCells = new List <mPoint>(); List <mPoint> WetCells = new List <mPoint>(); float[] Top = new float[numCols]; float[] Bottom = new float[numCols]; float[] Left = new float[numRows]; float[] Right = new float[numRows]; // Since we are evaluating this frame, we can clear its dependencies myFrame.Set_HasDependencies(UP, false); myFrame.Set_HasDependencies(DOWN, false); myFrame.Set_HasDependencies(LEFT, false); myFrame.Set_HasDependencies(RIGHT, false); myProgress.WriteMessage("Loading File..."); MapWinUtility.Logger.Progress("Loading File...", Prog, OldProg); Source = myFrame.GetArrayFromWindow(mwSourceGrid, myProgress.ICallBack); // Initialize first time around. We will be writing over the "copy" with // any changes we make, but this should save some time in file handling if (myFrame.Parent.First_Time(myFrame.X, myFrame.Y) == true) { if (myFrame.Parent.numCols * myFrame.Parent.numRows > 64000000) { // in the case where we copied the file, we need the middle cells to be set // to the float maximum for the algorithm to work. Dest = myFrame.GetBorders(mwSourceGrid, mwDestGrid, myProgress.ICallBack); myFrame.Parent.set_First_Time(myFrame.X, myFrame.Y, false); } else { Dest = myFrame.GetArrayFromWindow(mwDestGrid, myProgress.ICallBack); } } else { Dest = myFrame.GetArrayFromWindow(mwDestGrid, myProgress.ICallBack); } DateTime AlgStart = new DateTime(); AlgStart = DateTime.Now; for (int iPoint = 0; iPoint < SpawnPoints.Count; iPoint++) { ptStart = SpawnPoints[iPoint]; pt = new mPoint(ptStart.Y, ptStart.X, Dest[ptStart.Y][ptStart.X]); if (Dest[ptStart.Y][ptStart.X] == Source[ptStart.Y][ptStart.X]) { DryCells.Add(pt); } else { WetCells.Add(pt); } } // Even though we have specific dependency locations for our source, we can potentially // effect any other cells on the perimeter for (int col = 0; col < numCols; col++) { Top[col] = Dest[0][col]; Bottom[col] = Dest[numRows - 1][col]; } for (int row = 0; row < numRows; row++) { Left[row] = Dest[row][0]; Right[row] = Dest[row][numCols - 1]; } if (DryCells.Count > 0) { WetCells.AddRange(DryUpward(Source, ref Dest, numRows, numCols, DryCells, myProgress.ICallBack)); } FloodFill(Source, ref Dest, numRows, numCols, WetCells, myProgress.ICallBack); TimeSpan AlgTime = DateTime.Now - AlgStart; myProgress.WriteMessage("Saving Array to File..."); MapWinUtility.Logger.Progress("Saving Array to File...", Prog, OldProg); myFrame.SaveArrayToWindow(Dest, mwDestGrid, myProgress.ICallBack); myProgress.WriteMessage("Done.\n"); MapWinUtility.Logger.Progress("", Prog, OldProg); byte[][] Dependencies = new byte[5][]; Dependencies[UP] = new byte[numCols]; Dependencies[DOWN] = new byte[numCols]; DepsExist[UP] = false; DepsExist[DOWN] = false; for (int col = 0; col < numCols; col++) { if (Top[col] != Dest[0][col]) { DepsExist[UP] = true; Dependencies[UP][col] = (byte)DOWN; //if (Dest[0][col] < Minima[UP]) Minima[UP] = Dest[0][col]; } else { Dependencies[UP][col] = (byte)0; } if (Bottom[col] != Dest[numRows - 1][col]) { DepsExist[DOWN] = true; Dependencies[DOWN][col] = (byte)UP; //if (Dest[numRows - 1][col] < Minima[DOWN]) Minima[DOWN] = Dest[numRows - 1][col]; } else { Dependencies[DOWN][col] = (byte)0; } } // Save Dependencies to the files myFrame.Write_Dependencies(Dependencies[UP], UP); myFrame.Write_Dependencies(Dependencies[DOWN], DOWN); Dependencies[LEFT] = new byte[numRows]; Dependencies[RIGHT] = new byte[numRows]; DepsExist[LEFT] = false; DepsExist[RIGHT] = false; for (int row = 0; row < numRows; row++) { if (Left[row] != Dest[row][0]) { DepsExist[LEFT] = true; Dependencies[LEFT][row] = (byte)RIGHT; //if (Dest[row][0] < Minima[LEFT]) Minima[LEFT] = Dest[row][0]; } else { Dependencies[LEFT][row] = (byte)0; } if (Right[row] != Dest[row][numCols - 1]) { DepsExist[RIGHT] = true; Dependencies[RIGHT][row] = (byte)LEFT; //if (Dest[row][numCols - 1] < Minima[RIGHT]) Minima[RIGHT] = Dest[row][numCols - 1]; } else { Dependencies[RIGHT][row] = (byte)0; } } // Save Vertical Dependencies to the file myFrame.Write_Dependencies(Dependencies[LEFT], LEFT); myFrame.Write_Dependencies(Dependencies[RIGHT], RIGHT); // Update the status of the neighbors myFrame.Update_Neighbor_Status(DepsExist); MapWinUtility.Logger.Dbg("Finished FloodDependencies"); return(AlgTime); }
private bool m_Disposed; // For handling disposal /// <summary> /// Creates a new instance of the Raster wrapper for the grid /// </summary> Raster() { m_Grid = new MapWinGIS.Grid(); }
/// <summary> /// 创建一个新的LayerSource类实例(Grid) /// </summary> public LayerSource(MapWinGIS.Grid grid) { m_grid = grid; }
/// <summary> /// Creates a Raster from a specific instance of an m_Grid /// </summary> /// <param name="MapWinGIS_Grid">MapWinGIS.Grid to create a Raster from</param> Raster(MapWinGIS.Grid MapWinGIS_Grid) { m_Grid = MapWinGIS_Grid; }
/// <summary> /// 打开指定数据源的图层 /// </summary> /// <param name="filename">文件名</param> /// <param name="callback"></param> /// <returns></returns> public bool Open(string filename, MapWinGIS.ICallback callback) { this.Close(); if (filename.ToLower().EndsWith(".shp")) { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); if (sf.Open(filename, callback)) { // 检查dbf是否存在 bool error = false; if (!File.Exists(Path.ChangeExtension(sf.Filename, ".dbf"))) { m_error = LayerSourceError.DbfIsMissing; error = true; } // 检查DBF记录数相匹配的形状的数量。 MapWinGIS.Table table = new MapWinGIS.Table(); table.Open(Path.ChangeExtension(sf.Filename, ".dbf"), null); if (sf.NumShapes != table.NumRows) { m_error = LayerSourceError.DbfRecordCountMismatch; error = true; } table.Close(); if (error) { sf.Close(); } else { m_shapefile = sf; } return(!error); } else { m_error = LayerSourceError.OcxBased; m_ErrorString = sf.get_ErrorMsg(sf.LastErrorCode); } } else { bool asGrid = true; if (filename.ToLower().EndsWith(".tif")) { asGrid = false; } // TODO: 可能更聪明的选择是在grid/image中使用应用程序设置 if (asGrid) { MapWinGIS.Grid grid = new MapWinGIS.Grid(); if (grid.Open(filename, MapWinGIS.GridDataType.UnknownDataType, false, MapWinGIS.GridFileType.UseExtension, callback)) { m_grid = grid; return(true); } } // 尝试image MapWinGIS.Image image = new MapWinGIS.Image(); if (image.Open(filename, MapWinGIS.ImageType.USE_FILE_EXTENSION, false, callback)) { m_image = image; return(true); } else { m_error = LayerSourceError.OcxBased; m_ErrorString = image.get_ErrorMsg(image.LastErrorCode); } } return(false); }
/// <summary> /// This overload calculates the difference between files. THe number of rows and columns should be the same. /// </summary> /// <param name="SourceFile1">String filename of one grid to compare</param> /// <param name="SourceFile2">String filename of another grid to compare</param> /// <param name="DestFile">String filename of the output difference file</param> /// <param name="Overwrite">Boolean, true if you wish to overwrite an existing output /// file and delete the associated .bmp file. False raises a messagebox if the files exist.</param> /// <param name="ICallBack">A MapWinGIS.ICallBack for status messages</param> public static void Difference(string SourceFile1, string SourceFile2, string DestFile, bool Overwrite, MapWinGIS.ICallback ICallBack) { MapWinGIS.Grid Source1 = new MapWinGIS.Grid(); MapWinGIS.Grid Source2 = new MapWinGIS.Grid(); MapWinGIS.Grid Dest = new MapWinGIS.Grid(); bool res; // Open the source grids if (ICallBack != null) { ICallBack.Progress("Status", 0, "Opening Files..."); } res = Source1.Open(SourceFile1, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { MapWinUtility.Logger.Dbg("Argument Exception: " + Source1.get_ErrorMsg(Source1.LastErrorCode)); throw new ArgumentException(Source1.get_ErrorMsg(Source1.LastErrorCode)); } res = Source2.Open(SourceFile2, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { throw new ArgumentException(Source2.get_ErrorMsg(Source2.LastErrorCode)); } // Delete any existing files for our output grid if (System.IO.File.Exists(DestFile)) { string bmp = System.IO.Path.ChangeExtension(DestFile, "bmp"); string bpw = System.IO.Path.ChangeExtension(DestFile, "bpw"); string prj = System.IO.Path.ChangeExtension(DestFile, "prj"); string mwleg = System.IO.Path.ChangeExtension(DestFile, "mwleg"); if (Overwrite == false) { if (System.IO.File.Exists(bmp) || System.IO.File.Exists(bpw) || System.IO.File.Exists(prj) || System.IO.File.Exists(mwleg)) { if (MapWinUtility.Logger.Message("The output file exists, or associated files of the same name exist. Do you wish to delete the existing files?\n", "Output Files Exist", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning, System.Windows.Forms.DialogResult.No) == System.Windows.Forms.DialogResult.No) { return; } // This ensures mapwindow will recognize the new image as a new file. if (System.IO.File.Exists(bmp)) { System.IO.File.Delete(bmp); } if (System.IO.File.Exists(bpw)) { System.IO.File.Delete(bpw); } if (System.IO.File.Exists(prj)) { System.IO.File.Delete(prj); } if (System.IO.File.Exists(mwleg)) { System.IO.File.Delete(mwleg); } } else { if (MapWinUtility.Logger.Message("The output file already exists. Do you wish to delete it?", "Destination File Already Exists", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning, System.Windows.Forms.DialogResult.No) == System.Windows.Forms.DialogResult.No) { return; } } } else { if (System.IO.File.Exists(bmp)) { System.IO.File.Delete(bmp); } if (System.IO.File.Exists(bpw)) { System.IO.File.Delete(bpw); } if (System.IO.File.Exists(prj)) { System.IO.File.Delete(prj); } if (System.IO.File.Exists(mwleg)) { System.IO.File.Delete(mwleg); } } System.IO.File.Delete(DestFile); } // Create a new output grid MapWinGIS.GridHeader newHeader = new MapWinGIS.GridHeader(); newHeader.CopyFrom(Source1.Header); if (ICallBack != null) { MapWinUtility.Logger.Dbg("Creating Output File..."); ICallBack.Progress("Status", 0, "Creating Output File..."); } res = Dest.CreateNew(DestFile, newHeader, Source1.DataType, 0, true, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { MapWinUtility.Logger.Dbg("Argument Exception: " + Dest.get_ErrorMsg(Dest.LastErrorCode)); throw new ArgumentException(Dest.get_ErrorMsg(Dest.LastErrorCode)); } // Calculate the differences Difference(Source1, Source2, Dest, ICallBack); // Close Source grids Source1.Close(); Source2.Close(); // Save and close the output grid res = Dest.Save(DestFile, MapWinGIS.GridFileType.UseExtension, ICallBack); if (res == false) { MapWinUtility.Logger.Dbg("Application Exception: " + Dest.get_ErrorMsg(Dest.LastErrorCode)); throw new ArgumentException(Dest.get_ErrorMsg(Dest.LastErrorCode)); } Dest.Close(); MapWinUtility.Logger.Dbg("Finished Difference"); }
// This is not a full fledged map algebra function! This cannot deal with // images of different sizes or cell spacings. This is only a quick function // that can tell if, for instance, a pitfilled image is different from the // version created in Arcview. It simply takes each cell and finds the difference // in values. #region "Difference" /// <summary> /// Calculates the difference values and stores them in the Dest grid. This only works if the grids /// have the same number of rows and columns. /// </summary> /// <param name="Source1">MapWinGIS.Grid representing one source grid</param> /// <param name="Source2">MapWinGIS.Grid to compare Source1 against</param> /// <param name="Dest">MapWinGIS.Grid where the output is to be saved</param> /// <param name="ICallBack">A MapWinGIS.ICallBack</param> /// <remarks>Uses ArgumentExceptions if the grids are different sizes</remarks> public static void Difference(MapWinGIS.Grid Source1, MapWinGIS.Grid Source2, MapWinGIS.Grid Dest, MapWinGIS.ICallback ICallBack) { // Log entrance as best as possible while preventing errors from a null reference string Source1File = "null"; string Source2File = "null"; string DestFile = "null"; if (Source1 != null) { Source1File = Source1.Filename; if (Source1File == null) { Source1File = "Unnamed"; } } if (Source2 != null) { Source2File = Source2.Filename; if (Source2File == null) { Source2File = "Unnamed"; } } if (Dest != null) { DestFile = Dest.Filename; if (DestFile == null) { DestFile = "Unnamed"; } } MapWinUtility.Logger.Dbg("Difference(Source1: " + Source1File + ",\n" + " Source2: " + Source2File + ",\n" + " Dest: " + DestFile + ",\n" + " ICallback"); if (Source1 == null) { MapWinUtility.Logger.Dbg("Argument Exception: Source1 cannot be null."); throw new ArgumentException("Source1 cannot be null."); } if (Source2 == null) { MapWinUtility.Logger.Dbg("Argument Exception: Source2 cannot be null."); throw new ArgumentException("Source2 cannot be null."); } if (Dest == null) { MapWinUtility.Logger.Dbg("Argument Exception: Dest cannot be null."); throw new ArgumentException("Dest cannot be null."); } int nX, nY; nX = Source1.Header.NumberCols; nY = Source1.Header.NumberRows; if (Source2.Header.NumberRows != nY) { MapWinUtility.Logger.Dbg("Argument Exception: The grids are not the same height."); throw new ArgumentException("The grids are not the same height."); } if (Source2.Header.NumberCols != nX) { MapWinUtility.Logger.Dbg("Argument Exception: The grids are not the same width!"); throw new ArgumentException("The grids are not the same width!"); } if (Dest.Header.NumberRows != nY) { MapWinUtility.Logger.Dbg("Argument Exception: The output grid is not the same height!"); throw new ArgumentException("The output grid is not the same height!"); } if (Dest.Header.NumberCols != nX) { MapWinUtility.Logger.Dbg("Argument Exception: The output grid is not the same width!"); throw new ArgumentException("The output grid is not the same width!"); } int OldProg = 0; int Prog = 0; if (ICallBack != null) { ICallBack.Progress("Status", 0, "Difference...0% Complete"); } MapWinUtility.Logger.Progress("Difference...0% Complete", Prog, OldProg); if (Source1.DataType != MapWinGIS.GridDataType.FloatDataType) { switch (Source1.DataType) { case MapWinGIS.GridDataType.DoubleDataType: for (int Y = 0; Y < nY; Y++) { for (int X = 0; X < nX; X++) { double val = (double)Source1.get_Value(X, Y) - (double)Source2.get_Value(X, Y); Dest.set_Value(X, Y, val); } if (ICallBack != null) { Prog = (int)(Y * 100 / nY); if (Prog > OldProg) { ICallBack.Progress("Status", Prog, "Difference..." + Prog.ToString() + "% Complete"); MapWinUtility.Logger.Progress("Difference..." + Prog.ToString() + "% Complete", Prog, OldProg); OldProg = Prog; } } } break; case MapWinGIS.GridDataType.UnknownDataType: for (int Y = 0; Y < nY; Y++) { for (int X = 0; X < nX; X++) { double val = (double)Source1.get_Value(X, Y) - (double)Source2.get_Value(X, Y); Dest.set_Value(X, Y, val); } if (ICallBack != null) { Prog = (int)(Y * 100 / nY); if (Prog > OldProg) { ICallBack.Progress("Status", Prog, "Difference..." + Prog.ToString() + "% Complete"); MapWinUtility.Logger.Progress("Difference..." + Prog.ToString() + "% Complete", Prog, OldProg); OldProg = Prog; } } } break; case MapWinGIS.GridDataType.LongDataType: for (int Y = 0; Y < nY; Y++) { for (int X = 0; X < nX; X++) { long val = (long)Source1.get_Value(X, Y) - (long)Source2.get_Value(X, Y); Dest.set_Value(X, Y, val); } if (ICallBack != null) { Prog = (int)(Y * 100 / nY); if (Prog > OldProg) { MapWinUtility.Logger.Progress("Difference..." + Prog.ToString() + "% Complete", Prog, OldProg); ICallBack.Progress("Status", Prog, "Difference..." + Prog.ToString() + "% Complete"); OldProg = Prog; } } } break; case MapWinGIS.GridDataType.ShortDataType: for (int Y = 0; Y < nY; Y++) { for (int X = 0; X < nX; X++) { int val = (int)Source1.get_Value(X, Y) - (int)Source2.get_Value(X, Y); Dest.set_Value(X, Y, val); } if (ICallBack != null) { Prog = (int)(Y * 100 / nY); if (Prog > OldProg) { MapWinUtility.Logger.Progress("Difference..." + Prog.ToString() + "% Complete", Prog, OldProg); ICallBack.Progress("Status", Prog, "Difference..." + Prog.ToString() + "% Complete"); OldProg = Prog; } } } break; default: MapWinUtility.Logger.Progress("The Datatype was not a valid numeric type.", Prog, OldProg); throw new ArgumentException("The Datatype was not a valid numeric type."); } } else { for (int Y = 0; Y < nY; Y++) { float[] Vals1 = new float[nX]; float[] Vals2 = new float[nX]; float[] Diff = new float[nX]; Source1.GetRow(Y, ref Vals1[0]); Source2.GetRow(Y, ref Vals2[0]); for (int X = 0; X < nX; X++) { Diff[X] = Vals1[X] - Vals2[X]; } Dest.PutRow(Y, ref Diff[0]); if (ICallBack != null) { Prog = (int)(Y * 100 / nY); if (Prog > OldProg) { MapWinUtility.Logger.Progress("Difference..." + Prog.ToString() + "% Complete", Prog, OldProg); ICallBack.Progress("Status", Prog, "Difference..." + Prog.ToString() + "% Complete"); OldProg = Prog; } } } } MapWinUtility.Logger.Dbg("Finished Difference"); if (ICallBack != null) { ICallBack.Progress("Status", 0, "Done."); } }
private void cmdIdentify_Click(object sender, EventArgs e) { if (m_MapWin.View.SelectedShapes.NumSelected == 0) { MapWinUtility.Logger.Msg(resMan.GetString("msgZeroShapesSelected.Text"), resMan.GetString("titleSelectShapes.Text")); return; } if (cmbIdentFrom.SelectedIndex == -1) { MapWinUtility.Logger.Msg(resMan.GetString("msgIdentFromNotSelected.Text"), resMan.GetString("titleSpecifyLayer.Text")); return; } if (cmbIdentWith.SelectedIndex == -1) { MapWinUtility.Logger.Msg(resMan.GetString("msgIdentWithNotSelected.Text"), resMan.GetString("titleSpecifyLayer.Text")); return; } if (m_MapWin.View.SelectedShapes.NumSelected == 0) { return; } // If it's a polygon layer we're identifying, call SelectByPolygon // If it's a grid, extract by mask // ...then, open that temporary file (not Add to Map, just "Open"), and summarize all data within that // file. int fromLayerHandle = -1; int maskLayerHandle = -1; if (cmbIdentFrom.SelectedIndex != -1) { string s = cmbIdentFrom.Items[cmbIdentFrom.SelectedIndex].ToString(); if (s.Contains(")")) { s = s.Substring(0, s.IndexOf(")")); } s = s.Replace("(", ""); if (!int.TryParse(s, out fromLayerHandle)) { return; } if (fromLayerHandle == -1) { return; } } if (cmbIdentWith.SelectedIndex != -1) { string s = cmbIdentWith.Items[cmbIdentWith.SelectedIndex].ToString(); if (s.Contains(")")) { s = s.Substring(0, s.IndexOf(")")); } s = s.Replace("(", ""); if (!int.TryParse(s, out maskLayerHandle)) { return; } if (maskLayerHandle == -1) { return; } } string TempPath = System.IO.Path.GetTempFileName(); System.IO.File.Delete(TempPath); MapWinGIS.Shape IdentifyBy; MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)m_MapWin.Layers[m_MapWin.Layers.CurrentLayer].GetObject(); if (m_MapWin.View.SelectedShapes.NumSelected > 1) { // Get 0 and 1 first to initialize IdentifyBy MapWinGIS.Shape shp1 = sf.get_Shape(m_MapWin.View.SelectedShapes[0].ShapeIndex); MapWinGIS.Shape shp2 = sf.get_Shape(m_MapWin.View.SelectedShapes[1].ShapeIndex); MapWinGeoProc.SpatialOperations.MergeShapes(ref shp1, ref shp2, out IdentifyBy); // ...now, the rest if (m_MapWin.View.SelectedShapes.NumSelected > 2) { for (int i = 2; i < m_MapWin.View.SelectedShapes.NumSelected; i++) { MapWinGIS.Shape tmpResultShp; MapWinGIS.Shape shp3 = sf.get_Shape(m_MapWin.View.SelectedShapes[i].ShapeIndex); MapWinGeoProc.SpatialOperations.MergeShapes(ref IdentifyBy, ref shp3, out tmpResultShp); IdentifyBy = tmpResultShp; tmpResultShp = null; } } // Ready to identify based on a single shape now regardless of multiple selected } else { IdentifyBy = sf.get_Shape(m_MapWin.View.SelectedShapes[0].ShapeIndex); } MapWindow.Interfaces.eLayerType layerType = m_MapWin.Layers[fromLayerHandle].LayerType; if (layerType == MapWindow.Interfaces.eLayerType.Grid) { // Grid TempPath = System.IO.Path.ChangeExtension(TempPath, ".bgd"); string fn = m_MapWin.Layers[fromLayerHandle].FileName; MapWinGeoProc.SpatialOperations.ClipGridWithPolygon(ref fn, ref IdentifyBy, ref TempPath, chbJustToExtents.Checked); MapWinGIS.Grid grd = new MapWinGIS.Grid(); grd.Open(TempPath, MapWinGIS.GridDataType.UnknownDataType, true, MapWinGIS.GridFileType.UseExtension, null); if (grd == null || grd.Header == null) { MapWinUtility.Logger.Msg(resMan.GetString("msgNoGridValues.Text"), resMan.GetString("titleNoGridValues.Text")); return; } m_Plugin.ActivateNoLoad(); m_Plugin.LoadLayerAlternate(layerType, m_MapWin.Layers[fromLayerHandle].Name); MapWinGIS.Extents exts = new MapWinGIS.Extents(); exts.SetBounds(grd.Header.XllCenter, grd.Header.YllCenter + grd.Header.NumberRows * grd.Header.dY, 0, grd.Header.XllCenter + grd.Header.NumberCols * grd.Header.dX, grd.Header.YllCenter, 0); m_MapWin.Layers.CurrentLayer = fromLayerHandle; m_Plugin.m_GridPropfrm.PopulateForm(!m_Plugin.m_HavePanel, grd, m_MapWin.Layers[fromLayerHandle].Name, exts, fromLayerHandle); this.Close(); } else { // SF if (!chbJustToExtents.Checked) { string fn = m_MapWin.Layers[fromLayerHandle].FileName; // 2/14/2008 jk the results ArrayList cannot be null, // when it was null it caused an exception in SpatialOperations.SelectWithPolygon method //System.Collections.ArrayList results = null; System.Collections.ArrayList results = new System.Collections.ArrayList(); MapWinGeoProc.SpatialOperations.SelectWithPolygon(ref fn, ref IdentifyBy, ref results); // Switch current layer over to the one we're identifying so that the shapes // can be reselected for visual effect m_MapWin.Layers.CurrentLayer = fromLayerHandle; m_Plugin.ActivateNoLoad(); m_Plugin.LoadLayerAlternate(layerType, m_MapWin.Layers[fromLayerHandle].Name); int[] iresults = new int[results.Count]; for (int i = 0; i < results.Count; i++) { iresults[i] = (int)results[i]; m_MapWin.View.SelectedShapes.AddByIndex((int)results[i], m_MapWin.View.SelectColor); } m_Plugin.m_shpFilePropfrm.PopulateForm(!m_Plugin.m_HavePanel, (MapWinGIS.Shapefile)m_MapWin.Layers[fromLayerHandle].GetObject(), iresults, m_MapWin.Layers[fromLayerHandle].Name, false); this.Close(); } else { object rslt = null; m_MapWin.Layers.CurrentLayer = fromLayerHandle; MapWinGIS.Shapefile DestSF = (MapWinGIS.Shapefile)m_MapWin.Layers[fromLayerHandle].GetObject(); DestSF.SelectShapes(IdentifyBy.Extents, 0.1, MapWinGIS.SelectMode.INTERSECTION, ref rslt); m_Plugin.ActivateNoLoad(); m_Plugin.LoadLayerAlternate(layerType, m_MapWin.Layers[fromLayerHandle].Name); int[] results = (int[])rslt; for (int i = 0; i < results.Length; i++) { m_MapWin.View.SelectedShapes.AddByIndex((int)results[i], m_MapWin.View.SelectColor); } m_Plugin.m_shpFilePropfrm.PopulateForm(!m_Plugin.m_HavePanel, DestSF, results, m_MapWin.Layers[fromLayerHandle].Name, false); this.Close(); } } }
public bool LabelBasins(string watershedShpPath, string streamNetShpPath, string oiShpPath, string extraOiShpPath) { SetProjection(); MapWinGIS.Grid dem = new MapWinGIS.Grid(); dem.Open(basedem); //MapWindow.Interfaces.Layer demLayer = (MapWindow.Interfaces.Layer)dem; wshd = new MapWinGIS.Shapefile(); wshd.Open(watershedShpPath); //MapWindow.Interfaces.Layer wshdLayer = (MapWindow.Interfaces.Layer)wshd; net = new MapWinGIS.Shapefile(); net.Open(streamNetShpPath); // MapWindow.Interfaces.Layer netLayer = (MapWindow.Interfaces.Layer)net; oiFile = new MapWinGIS.Shapefile(); oiFile.Open(oiShpPath); //MapWindow.Interfaces.Layer oiFileLayer = (MapWindow.Interfaces.Layer)oiFile; if (extraOiShpPath != "") { extraOiFile = new MapWinGIS.Shapefile(); extraOiFile.Open(extraOiShpPath); } //MapWindow.Interfaces.Layer extraOiFileLayer = (MapWindow.Interfaces.Layer)extraOiFile; //hruGlobals.populateLinkToBasin(demLayer, wshdLayer, netLayer, oiFileLayer, extraOiFileLayer); //Passing, exception,, cannot convert UTM to LatLong hruGlobals.populateLinkToBasin(dem, wshd, net, oiFile, extraOiFile); //Passing, exception,, cannot convert UTM to LatLong hruGlobals.clearCentroids(); int numFields = wshd.NumFields; // Find index for PolygonID field int polyidField = -1; for (int i = 0; i < numFields; i++) { if (wshd.Field[i].Name.Equals("PolygonID", System.StringComparison.InvariantCultureIgnoreCase)) { polyidField = i; break; } } ////////////////////////////////////////////////////////////////////////// int numShapes = wshd.NumShapes; for (int i = 0; i < numShapes; i++) { MapWinGIS.Shape shape = wshd.Shape[i]; MapWinGIS.Point centroid = MapWinGeoProc.Utils.Centroid(ref shape); int link = Convert.ToInt32(wshd.CellValue[polyidField, i]); if (hruGlobals.linkToBasin.ContainsKey(link) == false) { //MessageBox.Show(strings_vb.nobasinforlink & link.ToString() & _ //strings_vb.tryrestart, MWSWATName, _ //MessageBoxButtons.OK, MessageBoxIcon.Error) return(false); } int basin = hruGlobals.linkToBasin[link]; hruGlobals.setCentroid(basin, centroid); if (hruGlobals.basinToSWATBasin.ContainsKey(basin)) { int SWATBasin = hruGlobals.basinToSWATBasin[basin]; //wshdLayer.AddLabel(SWATBasin.ToString(), System.Drawing.Color.Black, centroid.x, centroid.y, MapWinGIS.tkHJustification.hjCenter) } } return(true); }
}// End GetArrayFromWindow /// <summary> /// Returns jagged array where the borders are read from the destination file but the central /// portion is set to be the maximum float value. /// </summary> /// <param name="mwSourceGrid">A MapWinGIS.Grid to read the frame borders that are on the very outside of the image</param> /// <param name="mwDestGrid">A MapWinGIS.Grid to read the frame borders on the interior edges already processed </param> /// <param name="ICallBack">A MapWinGIS.ICallback for messages (optional)</param> /// <returns>A float[][] array representing the destination values for an entire frame</returns> public float[][] GetBorders(MapWinGIS.Grid mwSourceGrid, MapWinGIS.Grid mwDestGrid, MapWinGIS.ICallback ICallBack) { if (mwSourceGrid == null || mwDestGrid == null) { if (ICallBack != null) { ICallBack.Error("Error", "SourceGrid cannot be null."); } throw new ArgumentException("SourceGrid cannot be null."); } int numRows = this.Rectangle.Height; int numCols = this.Rectangle.Width; // Populate the Array by directly reading values from the grid float[][] SourceArray = new float[numRows][]; // Read from the ocx once, rather than calling several times // Initialize the array to max values for (int row = 0; row < numRows; row++) { SourceArray[row] = new float[numCols]; for (int col = 0; col < numCols; col++) { SourceArray[row][col] = float.MaxValue; } } // If we need a dependency in a given direction, read it from the file. if (Y == 0) { mwSourceGrid.GetFloatWindow(this.Rectangle.Y, this.Rectangle.Y, this.Rectangle.X, this.Rectangle.Right - 1, ref SourceArray[0][0]); } else if (Parent.First_Time(X, Y - 1) == false) { mwDestGrid.GetFloatWindow(this.Rectangle.Y, this.Rectangle.Y, this.Rectangle.X, this.Rectangle.Right - 1, ref SourceArray[0][0]); } if (Y == Parent.NumFramesTall - 1) { mwSourceGrid.GetFloatWindow(this.Rectangle.Bottom - 1, this.Rectangle.Bottom - 1, this.Rectangle.X, this.Rectangle.Right - 1, ref SourceArray[numRows - 1][0]); } else if (Parent.First_Time(X, Y + 1) == false) { mwDestGrid.GetFloatWindow(this.Rectangle.Bottom - 1, this.Rectangle.Bottom - 1, this.Rectangle.X, this.Rectangle.Right - 1, ref SourceArray[numRows - 1][0]); } if (X == 0) { float[] Temp = new float[numRows]; mwSourceGrid.GetFloatWindow(this.Rectangle.Y, this.Rectangle.Bottom - 1, this.Rectangle.X, this.Rectangle.X, ref Temp[0]); for (int row = 0; row < numRows; row++) { SourceArray[row][0] = Temp[row]; } } else if (Parent.First_Time(X - 1, Y) == false) { float[] Temp = new float[numRows]; mwDestGrid.GetFloatWindow(this.Rectangle.Y, this.Rectangle.Bottom - 1, this.Rectangle.X, this.Rectangle.X, ref Temp[0]); for (int row = 0; row < numRows; row++) { SourceArray[row][0] = Temp[row]; } } if (X == Parent.NumFramesWide - 1) { float[] Temp = new float[numRows]; mwSourceGrid.GetFloatWindow(this.Rectangle.Y, this.Rectangle.Bottom - 1, this.Rectangle.Right - 1, this.Rectangle.Right - 1, ref Temp[0]); for (int row = 0; row < numRows; row++) { SourceArray[row][numCols - 1] = Temp[row]; } } else if (Parent.First_Time(X + 1, Y) == false) { float[] Temp = new float[numRows]; mwDestGrid.GetFloatWindow(this.Rectangle.Y, this.Rectangle.Bottom - 1, this.Rectangle.Right - 1, this.Rectangle.Right - 1, ref Temp[0]); for (int row = 0; row < numRows; row++) { SourceArray[row][numCols - 1] = Temp[row]; } } if (ICallBack != null) { ICallBack.Progress("Status", 0, "Finished copying values from grid."); } return(SourceArray); }
// displays the grid extent! private void cmbExtent_SelectedIndexChanged(object sender, EventArgs e) { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); MapWindow.Interfaces.Layer curLayer; MapWinGIS.Grid grd = new MapWinGIS.Grid(); MapWinGIS.Extents extents; double cellSize = m_DefaultCellSize; //get the cell size to value from textbox Utils.string2double(txtCellSize.Text, out cellSize); //handle the "as specified below" option if (cmbExtent.Text == msgSpecifiedBelow) { txtMinX.Enabled = true; txtMinY.Enabled = true; txtMaxX.Enabled = true; txtMaxY.Enabled = true; return; } else { txtMinX.Enabled = false; txtMinY.Enabled = false; txtMaxX.Enabled = false; txtMaxY.Enabled = false; } //handle the case when shapefile loaded from disk and selected if (cmbExtent.Text == msgSameAs + m_ShortName) { if (sf.Open(m_ShpFileName,null)) { extents = calcShapefileExtent(sf); UpdateExtentBox(extents); } sf.Close(); } for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i) { //an existing layer is used to determine the extent curLayer = m_MapWin.Layers[i]; if (curLayer != null) { if (msgSameAs + curLayer.Name == cmbExtent.Text) { switch (curLayer.LayerType) { //same extention as an existing grid case MapWindow.Interfaces.eLayerType.Grid: grd = curLayer.GetGridObject; UpdateExtentBox(grd.Header); break; //same extention as an existing shapefile case MapWindow.Interfaces.eLayerType.LineShapefile: case MapWindow.Interfaces.eLayerType.PolygonShapefile: case MapWindow.Interfaces.eLayerType.PointShapefile: sf = (MapWinGIS.Shapefile)curLayer.GetObject(); extents = calcShapefileExtent(sf); UpdateExtentBox(extents); break; default: break; } } } } }
/// <summary> /// This creates a new shapefile that has Z values and follows along the same line segments. /// The boundaries for grid cells are marked with vertices and the segment is given a Z value /// that corresponds to the grid elevation it intersects. /// </summary> /// <param name="mwElevGrid">A MapWinGIS Grid that contains the elevations.</param> /// <param name="mwPolyLine">A MapWinGIS Shapefile that shows the pathways of the cross sections in the X-Y direction.</param> /// <param name="OutFileName">A string containing the full path of the desired output shapefile. The extension should be *.shp</param> /// <param name="CrossSectionType">Clarifies the type of output</param> /// <remarks>This function throws Argument or Application exceptions on errors, so it's recommended that coders enclose it in a try catch block.</remarks> public static void GetCrossSection(MapWinGIS.Grid mwElevGrid, MapWinGIS.Shapefile mwPolyLine, string OutFileName, CrossSectionTypes CrossSectionType) { GetCrossSection(mwElevGrid, mwPolyLine, OutFileName, CrossSectionType, null); }
public GridWrapper() { grid = new MapWinGIS.GridClass(); }
/// <summary> /// This creates a new shapefile that has Z values and follows along the same line segments. /// The boundaries for grid cells are marked with vertices and the segment is given a Z value /// that corresponds to the grid elevation it intersects. /// </summary> /// <param name="mwElevGrid">A MapWinGIS Grid that contains the elevations.</param> /// <param name="mwPolyLine">A MapWinGIS Shapefile that shows the pathways of the cross sections in the X-Y direction.</param> /// <param name="OutFileName">A string containing the full path of the desired output shapefile. The extension should be *.shp</param> /// <param name="CrossSectionType">Clarifies the type of output. default = PolyLineWithZ</param> /// <param name="ICallBack">A MapWinGIS.ICallback for progress messages. [Optional]</param> /// <remarks>This function throws Argument or Application exceptions on errors, so it's recommended that coders enclose it in a try catch block.</remarks> public static void GetCrossSection(MapWinGIS.Grid mwElevGrid, MapWinGIS.Shapefile mwPolyLine, string OutFileName, CrossSectionTypes CrossSectionType, MapWinGIS.ICallback ICallBack) { MapWinUtility.Logger.Dbg("GetCrossSection(mwElevGrid: " + Macro.ParamName(mwElevGrid) + ",\n" + " mwPolyLine: " + Macro.ParamName(mwPolyLine) + ",\n" + " OutFileName: " + OutFileName + ",\n" + " CrossSectionType: " + CrossSectionType.ToString() + ",\n" + " ICallback)"); bool res; int Prog = 0; int OldProg = 0; double dS, dX, dY, XllCenter, YllCenter; int NumRows, NumCols, ElevField, IDField; ElevField = 1; IDField = 0; // Test to be sure that the elevation grid and shapefile are not null if (mwElevGrid == null) { MapWinUtility.Logger.Dbg("Argument Exception: Elevation grid mwElevGrid can't be null."); throw new ArgumentException("Elevation grid mwElevGrid can't be null."); } if (mwPolyLine == null) { MapWinUtility.Logger.Dbg("Argument Exception: The shapefile of input cross sections mwPolyLine can't be null."); throw new ArgumentException("The shapefile of input cross sections mwPolyLine can't be null."); } // Clear any existing shapefile output filenames that might cause problems if they exist. string fn; if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(OutFileName)) == false) { System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(OutFileName)); } if (System.IO.File.Exists(OutFileName)) { System.IO.File.Delete(OutFileName); } fn = System.IO.Path.ChangeExtension(OutFileName, ".dbf"); if (System.IO.File.Exists(fn)) { System.IO.File.Delete(fn); } fn = System.IO.Path.ChangeExtension(OutFileName, ".shx"); if (System.IO.File.Exists(fn)) { System.IO.File.Delete(fn); } fn = System.IO.Path.ChangeExtension(OutFileName, ".prj"); if (System.IO.File.Exists(fn)) { System.IO.File.Delete(fn); } // Since we are given the lower left coordinate, just make sure dX and dY are positive dX = Math.Abs(mwElevGrid.Header.dX); if (dX == 0) { throw new ApplicationException("mwElevGrid.Header.dX cannot be 0."); } dY = Math.Abs(mwElevGrid.Header.dY); if (dY == 0) { throw new ApplicationException("mwElevGrid.Header.dY cannot be 0."); } // Determine the stepping distance from the grid coordintes dS = dX / 2; if (dY < dX) { dS = dY / 2; } XllCenter = mwElevGrid.Header.XllCenter; YllCenter = mwElevGrid.Header.YllCenter; NumRows = mwElevGrid.Header.NumberRows; NumCols = mwElevGrid.Header.NumberCols; // Test for intersection between the entire shapefile and the grid double left, right, top, bottom; left = XllCenter - dX / 2; right = XllCenter + NumCols * dX - dX / 2; bottom = YllCenter - dY / 2; top = YllCenter + NumRows * dY - dY / 2; MapWinGeoProc.Topology2D.Envelope gExt = new MapWinGeoProc.Topology2D.Envelope(left, right, bottom, top); MapWinGeoProc.Topology2D.Envelope pExt = new MapWinGeoProc.Topology2D.Envelope(mwPolyLine.Extents); if (gExt.Intersects(pExt) == false) { MapWinUtility.Logger.Dbg("Application Exception: The shapefile doesn't overlap the grid, so no cross sections were found."); throw new ApplicationException("The shapefile doesn't overlap the grid, so no cross sections were found."); } // Setup the output shapefile and the basic shape objects MapWinGIS.Shape mwShape; MapWinGIS.Shapefile sfOut = new MapWinGIS.Shapefile(); sfOut.Projection = mwPolyLine.Projection; if (CrossSectionType == CrossSectionTypes.PointsWithZAndElevField) { res = sfOut.CreateNew(OutFileName, MapWinGIS.ShpfileType.SHP_POINTZ); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } res = sfOut.StartEditingShapes(true, ICallBack); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } MapWinGIS.Field ID = new MapWinGIS.Field(); ID.Name = "ID"; ID.Type = MapWinGIS.FieldType.INTEGER_FIELD; res = sfOut.EditInsertField(ID, ref IDField, ICallBack); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } MapWinGIS.Field Elev = new MapWinGIS.Field(); Elev.Name = "Elevation"; Elev.Type = MapWinGIS.FieldType.DOUBLE_FIELD; res = sfOut.EditInsertField(Elev, ref ElevField, ICallBack); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } } else { res = sfOut.CreateNew(OutFileName, MapWinGIS.ShpfileType.SHP_POLYLINEZ); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } res = sfOut.StartEditingShapes(true, ICallBack); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } MapWinGIS.Field ID = new MapWinGIS.Field(); ID.Name = "ID"; ID.Type = MapWinGIS.FieldType.INTEGER_FIELD; res = sfOut.EditInsertField(ID, ref IDField, ICallBack); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } } MapWinGIS.Shape mwOutShape; // Loop through all the shapes in the polyline shapefile int shIndx = -1; for (int shp = 0; shp < mwPolyLine.NumShapes; shp++) { mwShape = mwPolyLine.get_Shape(shp); // By turning multi-part polylines into multiple linestrings, we avoid the annoying multi-part logic MultiLineString MLS = GeometryFactory.CreateMultiLineString(mwShape); for (int ls = 0; ls < MLS.NumGeometries; ls++) { LineString lsSource = MLS.GeometryN[ls] as LineString; for (int pt = 0; pt < lsSource.Coordinates.Count - 1; pt++) { Coordinate start = lsSource.Coordinates[pt]; Coordinate end = lsSource.Coordinates[pt + 1]; // Crop the parts of each segment that do not overlap with the grid. if (start.X < left) { if (end.X < left) { // this segment is outside the grid continue; } // crop this segment to only the portion on the grid start.X = left; } if (end.X < left) { // crop this segment to only the portion on the grid end.X = left; } if (start.X > right) { if (end.X > right) { // this segment is outside the grid continue; } // crop to grid start.X = right; } if (end.X > right) { // crop to the grid end.X = right; } double length = Math.Sqrt((end.X - start.X) * (end.X - start.X) + (end.Y - start.Y) * (end.Y - start.Y)); int NumSteps = (int)Math.Floor(length / dS); double segDx = (end.X - start.X) / NumSteps; double segDy = (end.Y - start.Y) / NumSteps; mwOutShape = new MapWinGIS.Shape(); if (CrossSectionType == CrossSectionTypes.PolyLineWithZ) { mwOutShape.Create(MapWinGIS.ShpfileType.SHP_POLYLINEZ); } // step by dS and get the grid value at that point at each step int p = 0; for (int I = 0; I < NumSteps; I++) { int row, col; object Elev; double X = start.X + segDx * I; double Y = start.Y + segDy * I; mwElevGrid.ProjToCell(X, Y, out col, out row); Elev = mwElevGrid.get_Value(col, row); MapWinGIS.Point pnt = new MapWinGIS.Point(); pnt.x = X; pnt.y = Y; pnt.Z = (double)Elev; if (CrossSectionType == CrossSectionTypes.PointsWithZAndElevField) { p = 0; mwOutShape = new MapWinGIS.Shape(); mwOutShape.Create(MapWinGIS.ShpfileType.SHP_POINTZ); res = mwOutShape.InsertPoint(pnt, ref p); if (res == false) { throw new ApplicationException(mwOutShape.get_ErrorMsg(mwOutShape.LastErrorCode)); } res = sfOut.EditInsertShape(mwOutShape, ref shIndx); if (res != true) { throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } res = sfOut.EditCellValue(IDField, shIndx, shIndx); if (res != true) { throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } res = sfOut.EditCellValue(ElevField, shIndx, Elev); if (res != true) { throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } shIndx++; } else { res = mwOutShape.InsertPoint(pnt, ref p); p++; if (res == false) { throw new ApplicationException(mwOutShape.get_ErrorMsg(mwOutShape.LastErrorCode)); } } } if (CrossSectionType == CrossSectionTypes.PolyLineWithZ) { if (mwOutShape.numPoints > 0) { res = sfOut.EditInsertShape(mwOutShape, ref shIndx); if (res != true) { throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } res = sfOut.EditCellValue(IDField, shIndx, shIndx); if (res != true) { throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } shIndx++; } } } } Prog = Convert.ToInt32(shp * 100 / mwPolyLine.NumShapes); if (Prog > OldProg) { MapWinUtility.Logger.Progress("Evaluating Cross Section..." + Prog.ToString() + "% Complete.", Prog, OldProg); OldProg = Prog; } } res = sfOut.StopEditingShapes(true, true, ICallBack); if (res != true) { MapWinUtility.Logger.Dbg("Application Exception: " + sfOut.get_ErrorMsg(sfOut.LastErrorCode)); throw new ApplicationException(sfOut.get_ErrorMsg(sfOut.LastErrorCode)); } }
/// <summary> /// 将图层颜色设置输出到一个指定路径 /// </summary> public static bool ExportScheme(Interfaces.Layer lyr, string path) { XmlDocument doc = new XmlDocument(); XmlElement mainScheme; XmlElement root; XmlAttribute schemeType; root = doc.CreateElement("ColoringScheme"); if (lyr == null) { return(false); } if (lyr.LayerType == Interfaces.eLayerType.LineShapefile || lyr.LayerType == Interfaces.eLayerType.PointShapefile || lyr.LayerType == Interfaces.eLayerType.PolygonShapefile) { MapWinGIS.ShapefileColorScheme sch = (MapWinGIS.ShapefileColorScheme)lyr.ColoringScheme; MapWinGIS.Shapefile sf = (MapWinGIS.Shapefile)lyr.GetObject(); XmlAttribute fldName; XmlAttribute key; if (sch == null || sch.NumBreaks() == 0) { return(false); } schemeType = doc.CreateAttribute("SchemeType"); schemeType.InnerText = "Shapefile"; root.Attributes.Append(schemeType); mainScheme = doc.CreateElement("ShapefileColoringScheme"); fldName = doc.CreateAttribute("FieldName"); key = doc.CreateAttribute("Key"); fldName.InnerText = sf.Field[sch.FieldIndex].Name; key.InnerText = sch.Key; mainScheme.Attributes.Append(fldName); mainScheme.Attributes.Append(key); root.AppendChild(mainScheme); doc.AppendChild(root); if (ExportScheme(((MapWinGIS.ShapefileColorScheme)lyr.ColoringScheme), doc, mainScheme)) { doc.Save(path); return(true); } else { MapWinGIS.Utility.Logger.Message("导出 coloring scheme 失败.", "错误"); return(false); } } else if (lyr.LayerType == Interfaces.eLayerType.Grid) { MapWinGIS.GridColorScheme sch = (MapWinGIS.GridColorScheme)lyr.ColoringScheme; MapWinGIS.Grid grd = lyr.GetGridObject; XmlAttribute AmbientIntensity; XmlAttribute Key; XmlAttribute LightSourceAzimuth; XmlAttribute LightSourceElevation; XmlAttribute LightSourceIntensity; XmlAttribute NoDataColor; XmlAttribute GridName; XmlAttribute GroupName; XmlAttribute ImageLayerFillTransparency; XmlAttribute ImageUpsamplingMethod; XmlAttribute ImageDownsamplingMethod; if (sch == null || sch.NumBreaks == 0) { return(false); } GridName = doc.CreateAttribute("GridName"); GroupName = doc.CreateAttribute("GroupName"); schemeType = doc.CreateAttribute("SchemeType"); schemeType.InnerText = "Grid"; root.Attributes.Append(schemeType); AmbientIntensity = doc.CreateAttribute("AmbientIntensity"); Key = doc.CreateAttribute("Key"); LightSourceAzimuth = doc.CreateAttribute("LightSourceAzimuth"); LightSourceElevation = doc.CreateAttribute("LightSourceElevation"); LightSourceIntensity = doc.CreateAttribute("LightSourceIntensity"); ImageLayerFillTransparency = doc.CreateAttribute("ImageLayerFillTransparency"); ImageUpsamplingMethod = doc.CreateAttribute("ImageUpsamplingMethod"); ImageDownsamplingMethod = doc.CreateAttribute("ImageDownsamplingMethod"); NoDataColor = doc.CreateAttribute("NoDataColor"); GridName.InnerText = lyr.Name; GroupName.InnerText = Program.frmMain.Legend.Groups.ItemByHandle(lyr.GroupHandle).Text; AmbientIntensity.InnerText = (sch.AmbientIntensity).ToString(); Key.InnerText = sch.Key; LightSourceAzimuth.InnerText = (sch.LightSourceAzimuth).ToString(); LightSourceElevation.InnerText = (sch.LightSourceElevation).ToString(); LightSourceIntensity.InnerText = (sch.LightSourceIntensity).ToString(); NoDataColor.InnerText = (ColorScheme.UIntToColor(sch.NoDataColor).ToArgb()).ToString(); ImageLayerFillTransparency.InnerText = ((System.Convert.ToInt32(lyr.ImageLayerFillTransparency * 100)) / 100).ToString(); MapWinGIS.Image img = new MapWinGIS.Image(); img = (MapWinGIS.Image)(Program.frmMain.MapMain.get_GetObject(lyr.Handle)); if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imBicubic) { ImageDownsamplingMethod.InnerText = "Bicubic"; } else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imBilinear) { ImageDownsamplingMethod.InnerText = "Bilinear"; } else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBicubic) { ImageDownsamplingMethod.InnerText = "HighQualityBicubic"; } else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBilinear) { ImageDownsamplingMethod.InnerText = "HighQualityBilinear"; } else if (img.DownsamplingMode == MapWinGIS.tkInterpolationMode.imNone) { ImageDownsamplingMethod.InnerText = "None"; } else { ImageDownsamplingMethod.InnerText = "None"; } if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imBicubic) { ImageUpsamplingMethod.InnerText = "Bicubic"; } else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imBilinear) { ImageUpsamplingMethod.InnerText = "Bilinear"; } else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBicubic) { ImageUpsamplingMethod.InnerText = "HighQualityBicubic"; } else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imHighQualityBilinear) { ImageUpsamplingMethod.InnerText = "HighQualityBilinear"; } else if (img.UpsamplingMode == MapWinGIS.tkInterpolationMode.imNone) { ImageUpsamplingMethod.InnerText = "None"; } else { ImageUpsamplingMethod.InnerText = "None"; } mainScheme = doc.CreateElement("GridColoringScheme"); mainScheme.Attributes.Append(AmbientIntensity); mainScheme.Attributes.Append(Key); mainScheme.Attributes.Append(LightSourceAzimuth); mainScheme.Attributes.Append(LightSourceElevation); mainScheme.Attributes.Append(LightSourceIntensity); mainScheme.Attributes.Append(NoDataColor); mainScheme.Attributes.Append(ImageLayerFillTransparency); mainScheme.Attributes.Append(ImageUpsamplingMethod); mainScheme.Attributes.Append(ImageDownsamplingMethod); root.AppendChild(mainScheme); root.Attributes.Append(GridName); root.Attributes.Append(GroupName); doc.AppendChild(root); if (ExportScheme(((MapWinGIS.GridColorScheme)lyr.ColoringScheme), doc, mainScheme)) { doc.Save(path); return(true); } else { MapWinGIS.Utility.Logger.Message("导出 coloring scheme 失败.", "错误"); return(false); } } return(false); }
// displays the grid extent! private void cmbExtent_SelectedIndexChanged(object sender, EventArgs e) { MapWinGIS.Shapefile sf = new MapWinGIS.Shapefile(); MapWindow.Interfaces.Layer curLayer; MapWinGIS.Grid grd = new MapWinGIS.Grid(); MapWinGIS.Extents extents; double cellSize = m_DefaultCellSize; //get the cell size to value from textbox Utils.string2double(txtCellSize.Text, out cellSize); //handle the "as specified below" option if (cmbExtent.Text == msgSpecifiedBelow) { txtMinX.Enabled = true; txtMinY.Enabled = true; txtMaxX.Enabled = true; txtMaxY.Enabled = true; return; } else { txtMinX.Enabled = false; txtMinY.Enabled = false; txtMaxX.Enabled = false; txtMaxY.Enabled = false; } //handle the case when shapefile loaded from disk and selected if (cmbExtent.Text == msgSameAs + m_ShortName) { if (sf.Open(m_ShpFileName, null)) { extents = calcShapefileExtent(sf); UpdateExtentBox(extents); } sf.Close(); } for (int i = 0; i < m_MapWin.Layers.NumLayers; ++i) { //an existing layer is used to determine the extent curLayer = m_MapWin.Layers[i]; if (curLayer != null) { if (msgSameAs + curLayer.Name == cmbExtent.Text) { switch (curLayer.LayerType) { //same extention as an existing grid case MapWindow.Interfaces.eLayerType.Grid: grd = curLayer.GetGridObject; UpdateExtentBox(grd.Header); break; //same extention as an existing shapefile case MapWindow.Interfaces.eLayerType.LineShapefile: case MapWindow.Interfaces.eLayerType.PolygonShapefile: case MapWindow.Interfaces.eLayerType.PointShapefile: sf = (MapWinGIS.Shapefile)curLayer.GetObject(); extents = calcShapefileExtent(sf); UpdateExtentBox(extents); break; default: break; } } } } }