/// <summary> /// Constructor from grid header /// </summary> /// <param name="h">header</param> public OffSet(MapWinGIS.GridHeader h) { // origin (taken as column zero and row zero) is at the top left of the grid this.origin = new MapWinGIS.Point(); this.origin.x = h.XllCenter - (h.dX / 2); this.origin.y = h.YllCenter - (h.dY / 2) + h.dY * h.NumberRows; this.dX = h.dX; this.dY = h.dY; this.unitArea = (double)this.dX * this.dY; }
private bool Multipoint2Grid(MapWinGIS.Shapefile MultipointSf, int FldID, MapWinGIS.Grid Newgrd, MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback) { //count the number of shapes int s, p; MapWinGIS.Shape shp; MapWinGIS.Point pt; ArrayList pixels = new ArrayList(); object val; GridPixel px; int nShps = MultipointSf.NumShapes; int nPts = 0; int perc = 1; int shpsPerc = NumPercentShapes(perc, nShps); //percent of progress for (s = 0; s < nShps; ++s) { //get the shape shp = MultipointSf.get_Shape(s); //exclude shapes which are completely outside of the grid extents if (!IsGridContainsShape(shp, header)) { continue; } //get the shape's value val = GetCellValue(MultipointSf, FldID, s, header.NodataValue); nPts = shp.numPoints; for (p = 0; p < nPts; ++p) { //write pixel values pt = shp.get_Point(p); Newgrd.ProjToCell(pt.x, pt.y, out px.col, out px.row); pixels.Add(px); writePxList(Newgrd, grType, pixels, val, cback); } //report the progress if (s >= shpsPerc) { reportProgress(shpsPerc, nShps, "shapefile to grid", cback); perc = (int)((s * 100) / nShps); shpsPerc = NumPercentShapes(perc + 1, nShps); } } return(true); }
/// <summary> /// convert point shapefile to grid /// </summary> private bool Point2Grid(MapWinGIS.Shapefile PointSf, int FldID, MapWinGIS.Grid Newgrd, MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback) { //count the number of shapes int s; MapWinGIS.Shape shp; MapWinGIS.Point pt = new MapWinGIS.Point(); object val; GridPixel px; int nShps = PointSf.NumShapes; int perc = 1; int shpsPerc = NumPercentShapes(perc, nShps); //percent of progress for (s = 0; s < nShps; ++s) { //get the point shp = PointSf.get_Shape(s); //exclude shapes which are completely outside of the grid extents if (!IsGridContainsShape(shp, header)) { continue; } if (shp.numPoints > 0) { pt = shp.get_Point(0); if (pt != null) { //return the shape's value and write the pixel val = GetCellValue(PointSf, FldID, s, header.NodataValue); Newgrd.ProjToCell(pt.x, pt.y, out px.col, out px.row); writePx(Newgrd, grType, px, val, cback); } } //report the progress if (s >= shpsPerc) { perc = (int)((s * 100) / nShps); shpsPerc = NumPercentShapes(perc + 1, nShps); reportProgress(shpsPerc, nShps, "shapefile to grid", cback); } } return(true); }
/// <summary> /// populate all the grid cells between two consecutive intersections with shape's value /// </summary> private bool ScanLine(ArrayList vettore, double xref, ArrayList pixels, MapWinGIS.GridHeader header, object value, MapWinGIS.ICallback cback) { bool result = false; bool control; double xll, yll, ystart, yend, ycellstart; double dx, dy; int nrows; int c, r, v; r = 0; GridPixel curPx; control = false; xll = header.XllCenter; yll = header.YllCenter; dx = header.dX; dy = header.dY; nrows = header.NumberRows; ystart = 0; for (v = vettore.Count - 1; v >= 0; --v) { if (control == false) { ystart = (double)vettore[v]; control = true; } else { yend = (double)vettore[v]; ycellstart = FirstLineXY(ystart, yll, dy, -1); do { Globals.ProjToCell(xref, ycellstart, out c, out r, xll, yll, dx, dy, nrows); curPx.col = c; curPx.row = r; pixels.Add(curPx); ycellstart = ycellstart - dy; }while (ycellstart >= yend); control = false; } } return(result); }
/// <summary> /// determine if the shape is partially inside grid extents /// </summary> /// <param name="shp"></param> /// <param name="hdr"></param> /// <returns>false, if the shape is completely outside grid extents /// true, if it's at least partially inside</returns> private bool IsGridContainsShape(MapWinGIS.Shape shp, MapWinGIS.GridHeader hdr) { double gridXmin = hdr.XllCenter; double gridYmin = hdr.YllCenter; double gridXmax = gridXmin + (hdr.NumberCols * hdr.dX); double gridYmax = gridYmin + (hdr.NumberRows * hdr.dY); MapWinGIS.Extents ext = shp.Extents; if (ext.xMin > gridXmax || ext.yMin > gridYmax || ext.xMax < gridXmin || ext.yMax < gridYmin) { return(false); } else { return(true); } }
/// <summary> /// 'Copyright (C) 2008 Enrico Antonio Chiaradia, UNIMI ///'This program is free software; you can redistribute it and/or ///'modify it under the terms of the GNU General Public License ///'version 2, 1991 as published by the Free Software Foundation. ///'This program is distributed in the hope that it will be useful, ///'but WITHOUT ANY WARRANTY; without even the implied warranty of ///'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ///'GNU General Public License for more details. ///'A copy of the full GNU General Public License is available at: ///'http://www.gnu.org/copyleft/gpl.html ///'or from: ///'The Free Software Foundation, Inc., 59 Temple Place - Suite 330, ///'Boston, MA 02111-1307, USA. ///'If you wish to use or incorporate this program (or parts of it) into ///'other software that does not meet the GNU General Public License ///'conditions contact the author to request permission. ///'If you have any question or suggestion, please contact the author. ///'Enrico A. Chiaradia ///'University of Milan ///'Ist. di Idraulica Agraria ///'via Celoria 2 ///'20133, Milan, Italy ///'email: [email protected] /// </summary> /// <param name="sfPath">the name of the shapefile</param> /// <param name="resultGridPath">the name of the new grid</param> /// <param name="gridFileType">file type of the new grid</param> /// <param name="gridDataType">data format of the new grid</param> /// <param name="sfValueField">the name of the field that contains data</param> /// <param name="resultGridHeader">contains information about dimension of the new grid</param> /// <param name="callback">(optional) reports progress and error messages</param> /// <returns></returns> public bool ShapefileToGrid2(string SfNm, string GrdName, MapWinGIS.GridFileType GrdFileType, MapWinGIS.GridDataType GrdDataType, string Fldname, MapWinGIS.GridHeader GrdHd, MapWinGIS.ICallback cback) { int i; bool flg; string projStr; //open the shapefile MapWinGIS.Shapefile MySf = new MapWinGIS.Shapefile(); flg = MySf.Open(SfNm, cback); if (flg == false) { reportError("ERROR in opening shapefile: " + SfNm, cback); MySf.Close(); return(false); } //get the handle for the field MapWinGIS.Field field; int FldId = -1; int LayFldNum = MySf.NumFields; i = 0; for (i = 0; i < LayFldNum; ++i) { field = MySf.get_Field(i); if (field.Name.ToLower() == Fldname.ToLower()) { FldId = i; break; } } if (FldId < 0) { reportError("The shapefile " + SfNm + " doesn't have a field " + Fldname, cback); MySf.Close(); return(false); } //copy shapefile projection projStr = MySf.Projection; if (!MapWinUtility.Strings.IsEmpty(projStr)) { GrdHd.Projection = projStr; } //create a new grid and a new gridheader MapWinGIS.Grid NewGrd = new MapWinGIS.Grid(); flg = NewGrd.CreateNew(GrdName, GrdHd, GrdDataType, GrdHd.NodataValue, false, GrdFileType, cback); if (flg == false) { reportError("ERROR in grid initialization: " + GrdName, cback); NewGrd.Close(); MySf.Close(); } //verify the type of shapefile and call rasterization function MapWinGIS.ShpfileType SfType = new MapWinGIS.ShpfileType(); SfType = MySf.ShapefileType; switch (SfType) { case ShpfileType.SHP_POLYGON: case ShpfileType.SHP_POLYGONM: case ShpfileType.SHP_POLYGONZ: flg = Poly2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback); break; case ShpfileType.SHP_POLYLINE: case ShpfileType.SHP_POLYLINEM: case ShpfileType.SHP_POLYLINEZ: flg = Line2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback); break; case ShpfileType.SHP_POINT: case ShpfileType.SHP_POINTM: case ShpfileType.SHP_POINTZ: flg = Point2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback); break; case ShpfileType.SHP_MULTIPOINT: case ShpfileType.SHP_MULTIPOINTM: case ShpfileType.SHP_MULTIPOINTZ: flg = Multipoint2Grid(MySf, FldId, NewGrd, GrdHd, GrdDataType, cback); break; default: reportError("The shapefile type " + SfType.ToString() + "is not supported.", cback); NewGrd.Close(); MySf.Close(); flg = false; break; } //save and close the grid, close shapefile NewGrd.Save(GrdName, GrdFileType, cback); NewGrd.Close(); MySf.Close(); return(flg); }
/// <summary> /// converts a Line shapefile to grid using Bresenham algorithm /// </summary> /// <param name="PolySf">Polygon shapefile object</param> /// <param name="FldID">Field index</param> /// <param name="Newgrd">New grid object</param> /// <param name="header">Grid header</param> /// <param name="nodatavalue"></param> /// <param name="cback">optional, for reporting progress</param> /// <returns>true if successful</returns> private bool Line2Grid(MapWinGIS.Shapefile LineSf, int FldID, MapWinGIS.Grid Newgrd, MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback) { int numParts, numPoints; int curPartStart, curPartEnd, vertexCol, vertexRow, lastCol, lastRow; int nShps = LineSf.NumShapes; int perc = 1; int shpsPerc = NumPercentShapes(perc, nShps); //percent of progress int s = 0; //shape number int p = 0; //part number int k = 0; //point number MapWinGIS.Shape LineShp = new MapWinGIS.Shape(); MapWinGIS.Point curPoint; //Rasterization ras = new Rasterization(); //rasterization class, contains the code of //lineToGrid methods independent on MapWinGIS functions ArrayList vertices = new ArrayList(); //list of line vertex points ArrayList pixels = new ArrayList(); //list of calculated pixels on the line GridPixel px; object val; //the shape's value for (s = 0; s < nShps; ++s) { LineShp = LineSf.get_Shape(s); numParts = LineShp.NumParts; numPoints = LineShp.numPoints; //exclude shapes which are completely outside of the grid extents if (!IsGridContainsShape(LineShp, header)) { continue; } //get the shape's value val = GetCellValue(LineSf, FldID, s, header.NodataValue); //process each part of the polyline curPartStart = 0; for (p = 0; p < numParts; ++p) { vertices.Clear(); pixels.Clear(); curPartStart = LineShp.get_Part(p); // check for multi-part lines if (p < numParts - 1) { curPartEnd = LineShp.get_Part(p + 1) - 1; } else { curPartEnd = numPoints - 1; } //go to next part if there's zero points if (numPoints <= 0) { continue; } // add all points of current part to rasterization list // always add the first point of the part (convert its coordinates to // grid row and column) curPoint = LineShp.get_Point(curPartStart); Newgrd.ProjToCell(curPoint.x, curPoint.y, out vertexCol, out vertexRow); px.col = vertexCol; px.row = vertexRow; vertices.Add(px); lastCol = vertexCol; lastRow = vertexRow; // add all other points with different grid coordinates for (k = curPartStart + 1; k <= curPartEnd; ++k) { // (check if it has a different row or column than the previous point) curPoint = LineShp.get_Point(k); Newgrd.ProjToCell(curPoint.x, curPoint.y, out vertexCol, out vertexRow); if (vertexCol != lastCol || vertexRow != lastRow) { px.col = vertexCol; px.row = vertexRow; vertices.Add(px); lastCol = vertexCol; lastRow = vertexRow; } } // convert the polyline and write pixels to grid LineBresenham(vertices, pixels); writePxList(Newgrd, grType, pixels, val, cback); } //report the progress if (s >= shpsPerc) { reportProgress(shpsPerc, nShps, "shapefile to grid", cback); perc = (int)((s * 100) / nShps); shpsPerc = NumPercentShapes(perc + 1, nShps); } } return(true); }
/// <summary> /// populate all the grid cells between two consecutive intersections with shape's value /// </summary> private bool ScanLine2(System.Collections.ArrayList vettore, double xref, ref System.Collections.ArrayList pixels, ref MapWinGIS.Grid gr, MapWinGIS.GridHeader header, object value, MapWinGIS.ICallback cback) { bool result = false; bool control; double yll, ystart, yend, ycellstart; double pxsize; int c, r, v; r = 0; GridPixel curPx; control = false; yll = header.YllCenter; pxsize = header.dX; ystart = 0; for (v = vettore.Count - 1; v >= 0; --v) { if (control == false) { ystart = (double)vettore[v]; control = true; } else { yend = (double)vettore[v]; ycellstart = FirstLineXY(ystart, yll, pxsize, -1); do { gr.ProjToCell(xref, ycellstart, out c, out r); curPx.col = c; curPx.row = r; pixels.Add(curPx); ycellstart = ycellstart - pxsize; }while (ycellstart >= yend); control = false; } } return(result); }
/// <summary> /// This function converts a polygon shapefile to grid. It implements the line-scan algorithm. /// <param name="PolySf">The polygon shapefile</param> /// <param name="FldID">The field index</param> /// <param name="Newgrd">File name of the new grid</param> /// <param name="header">Header object of the new grid</param> /// <param name="writePxDeleg">Delegate function for writing the grid pixels</param> /// <param name="nodatavalue">'no data' value</param> /// <param name="cback">can be used to report progress (optional)</param> /// <returns>true if successful</returns> // // AUTHOR NAME: Enrico A. Chiaradia // FROM: University of Milan (Italy) // e.mail: [email protected] // // For details about the line-scan algorithm, // please refer to http://www.profc.udec.cl/~gabriel/tutoriales/giswb/vol1/cp3/cp3-6.htm // // for each shape in PolySf // 0) get the shape value (in the shapefile table) // 1) load all the borders in a matrix composed by x(startpoint), x(endpoint), slope and share // 2) define x of first scan line // for each scan lines // 3) calculate intersections with polygon border // 4) sort intersections from lower Y to the higther // 5) convert line space between two consecutive intersection to raster private bool Poly2Grid(MapWinGIS.Shapefile PolySf, int FldID, MapWinGIS.Grid Newgrd, MapWinGIS.GridHeader header, MapWinGIS.GridDataType grType, MapWinGIS.ICallback cback) { double xMin, xMax; double x0, x1, x2, y0, y1, y2, m, q; int nShps, nVs, i, s, nP, p, tempn, v, b; object val; bool flg; bord brd; //struct to keep a border System.Collections.ArrayList bordi2; //list of borders int perc = 1; //percent shapes done int shpsPerc; MapWinGIS.Shape PolyShp; //the polygon shape //count the number of shapes nShps = PolySf.NumShapes; shpsPerc = NumPercentShapes(perc, nShps); //percent of progress for (s = 0; s < nShps; ++s) { //for each shape, determine the extent and the number of parts i = 0; PolyShp = PolySf.get_Shape(s); nP = PolyShp.NumParts; xMin = PolyShp.Extents.xMin; //yMin = PolyShp.Extents.yMin; xMax = PolyShp.Extents.xMax; //yMax = PolyShp.Extents.yMax; //exclude shapes which are completely outside of the grid extents if (!IsGridContainsShape(PolyShp, header)) { continue; } //return the shape's value val = GetCellValue(PolySf, FldID, s, header.NodataValue); //load polygon borders nVs = PolyShp.numPoints - 1; bordi2 = new System.Collections.ArrayList(nVs + 1); b = -1; tempn = 0; for (p = 0; p < nP; ++p) { x0 = PolyShp.get_Point(tempn).x; y0 = PolyShp.get_Point(tempn).y; for (v = tempn; v < nVs; ++v) { x1 = PolyShp.get_Point(v).x; x2 = PolyShp.get_Point(v + 1).x; y1 = PolyShp.get_Point(v).y; y2 = PolyShp.get_Point(v + 1).y; if (x1 != x2) // no vertical lines { m = (y2 - y1) / (x2 - x1); q = y1 - (m * x1); //add border to the list b = b + 1; brd = new bord(); brd.x1 = x1; brd.x2 = x2; brd.m = m; brd.q = q; bordi2.Add(brd); } //in case of multi-parts polygon if ((x2 == x0) && (y2 == y0)) { tempn = v + 2; break; } } //Next v } // next p //define the first line-scan double xstart; // 20 nov 07 added by Enrico A. Chiaradia //necessary if grid extentions differ from shapefile extentions if (xMin >= header.XllCenter) { xstart = FirstLineXY(xMin, header.XllCenter, header.dX, 1); } else { xstart = FirstLineXY(xMin, header.XllCenter, header.dX, -1); } // the list of intersection y-values System.Collections.ArrayList y_int = new System.Collections.ArrayList(); System.Collections.ArrayList pixels = new System.Collections.ArrayList(); do { flg = Interseca(bordi2, y_int, xstart); flg = SortArray(y_int); flg = ScanLine2(y_int, xstart, ref pixels, ref Newgrd, header, val, cback); xstart = xstart + header.dX; }while (xstart <= xMax); writePxList(Newgrd, grType, pixels, val, cback); //report the progress if (s >= shpsPerc) { reportProgress(shpsPerc, nShps, "shapefile to grid", cback); perc = (int)((s * 100) / nShps); shpsPerc = NumPercentShapes(perc + 1, nShps); } } // next shape reportProgress(100, 100, "shapefile to grid", cback); //100 % shapes done return(true); }
/// <summary> /// Constructor, making an empty dictionary, and setting offset /// from header. /// </summary> public ManhattanShapes(MapWinGIS.GridHeader h) { ShapesTable = new Dictionary <int, Data>(); offset = new OffSet(h); }
/// <summary> /// Converts grid to a shapefile, removing any existing shapefile. /// Assumed to be an integer grid. Adds attribute headed id with the grid values, and /// attribute headed "Area" with the area for each polygon. /// </summary> /// <param name="gridName">Path of input grid</param> /// <param name="shapeName">Path of output shapefile</param> /// <param name="id">String to use for name of grid values attribute</param> /// <param name="cb">Callback for reporting errors</param> /// <returns>null if any errors, else shapefile</returns> public static MapWinGIS.Shapefile GridToShapeManhattan(string gridName, string shapeName, string id, MapWinGIS.ICallback cb) { if (!System.IO.File.Exists(gridName)) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.nogrid + gridName); } return(null); } MapWinGIS.Grid grid = new MapWinGIS.GridClass(); if (!grid.Open(gridName, GridDataType.UnknownDataType, true, GridFileType.UseExtension, null)) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noopengrid + gridName); } return(null); } MapWinGIS.GridHeader header = grid.Header; int numRows = header.NumberRows; int numCols = header.NumberCols; MapWinGeoProc.DataManagement.DeleteShapefile(ref shapeName); string oldProj = System.IO.Path.ChangeExtension(gridName, ".prj"); string newProj = System.IO.Path.ChangeExtension(shapeName, ".prj"); if (System.IO.File.Exists(oldProj) && !oldProj.Equals(newProj)) { System.IO.File.Copy(oldProj, newProj); } MapWinGIS.Shapefile shapeFile = new MapWinGIS.Shapefile(); bool success = shapeFile.CreateNew(shapeName, ShpfileType.SHP_POLYGON); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.nocreateshapefile + shapeName); } return(null); } success = shapeFile.StartEditingShapes(true, null); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditshapefile + shapeName); } return(null); } ManhattanShapes shapes = new ManhattanShapes(header); for (int i = 0; i < numRows; i++) { shapes.addGridRow(grid, i, numCols); } if (!shapes.lastError.Equals("")) { if (cb != null) { cb.Error("GridToShapeManhattan", shapes.lastError); } return(null); } grid.Close(); shapes.FinishShapes(); MapWinGIS.Field idField = new MapWinGIS.Field(); idField.Name = id; idField.Type = FieldType.INTEGER_FIELD; int idIndex = 0; success = shapeFile.EditInsertField(idField, ref idIndex, null); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noaddfield + shapeName); } shapeFile.Close(); return(null); } MapWinGIS.Field areaField = new MapWinGIS.Field(); areaField.Name = "Area"; areaField.Type = FieldType.DOUBLE_FIELD; int areaIndex = 1; success = shapeFile.EditInsertField(areaField, ref areaIndex, null); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noaddfield + shapeName); } shapeFile.Close(); return(null); } int shapeIndex = 0; foreach (int k in shapes.ShapesTable.Keys) { success = shapes.InsertShape(shapeFile, k, ref shapeIndex); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noaddshape + shapeName); } shapeFile.Close(); return(null); } success = shapeFile.EditCellValue(idIndex, shapeIndex, k); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditcell + shapeName); } shapeFile.Close(); return(null); } double area = shapes.Area(k); success = shapeFile.EditCellValue(areaIndex, shapeIndex, area); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditcell + shapeName); } shapeFile.Close(); return(null); } } success = shapeFile.StopEditingShapes(true, true, null); if (!success) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.noeditshapefile + shapeName); } shapeFile.Close(); return(null); } if (!shapeFile.Close()) { if (cb != null) { cb.Error("GridToShapeManhattan", clsUtils.ManhattanShapes.nocloseshapefile + shapeName); } return(null); } return(shapeFile); }
private MapWinGIS.Extents GetMaxExtents(MapWinGIS.Extents ex, MapWinGIS.GridHeader header) { MapWinGIS.Extents extents = new MapWinGIS.ExtentsClass(); double xMin = 0, xMax = 0, yMin = 0, yMax = 0; double newXMin = 0, newXMax = 0, newYMin = 0, newYMax = 0; //find the grid Max and Min extents xMin = header.XllCenter; yMin = header.YllCenter; xMax = header.XllCenter + header.dX * header.NumberCols; yMax = header.YllCenter + header.dY * header.NumberRows; if (ex == null) { return(null); } else if (ex.xMax < xMin || ex.yMax < yMin || ex.xMin > xMax || ex.yMin > yMax) { //out of bounds return nothing return(null); } else { //check to make sure the selected bounds are within the grid if (ex.xMin < xMin) { newXMin = xMin; } else { newXMin = ex.xMin; } if (ex.yMin < yMin) { newYMin = yMin; } else { newYMin = ex.yMin; } if (ex.xMax > xMax) { newXMax = xMax; } else { newXMax = ex.xMax; } if (ex.yMax > yMax) { newYMax = yMax; } else { newYMax = ex.yMax; } extents.SetBounds(newXMin, newYMin, 0, newXMax, newYMax, 0); } return(extents); }