public static bool TestHelper(string wkt) { PrecisionModel pm = new PrecisionModel(1, 0, 0); GeometryFactory fact = new GeometryFactory(pm, 0); //read wkt Geometry a = new GeometryWKTReader(fact).Create(wkt); //write wkb FileStream fs = new FileStream("TestFile.wkb", FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); GeometryWKBWriter bWriter = new GeometryWKBWriter(bw, fact); bWriter.Write(a, WKBByteOrder.Ndr); bw.Close(); fs.Close(); //read wkb fs = new FileStream("TestFile.wkb", FileMode.Open); byte[] bytes = new byte[fs.Length]; for(int i = 0; i < fs.Length; i++) { bytes[i] = (byte)fs.ReadByte(); } GeometryWKBReader bReader = new GeometryWKBReader(fact); Geometry geom = bReader.Create(bytes); fs.Close(); //write to wkt & compare with original text. bool results = ( Compare.WktStrings(wkt,a.toText())); return results; }
/// <summary> /// Initializes a new instance of the <see cref="ShapefileReader">ShapefileReader</see> class with the given parameters. /// </summary> /// <param name="filename">The filename of the shape file to read (with .shp).</param> /// <param name="factory">The <b>GeometryFactory</b> to use when creating Geometry objects.</param> public ShapefileReader(string filename, GeometryFactory factory) { if (filename == null) { throw new ArgumentNullException("filename"); } if (factory == null) { throw new ArgumentNullException("geometryFactory"); } _filename = filename; Trace.WriteLineIf(Shapefile.TraceSwitch.Enabled,"Reading filename:"+filename); _geometryFactory = factory; // read header information. note, we open the file, read the header information and then // close the file. This means the file is not opened again until GetEnumerator() is requested. // For each call to GetEnumerator() a new BinaryReader is created. using (BigEndianBinaryReader shpBinaryReader = new BigEndianBinaryReader(File.OpenRead(filename))) { _mainHeader = new ShapefileHeader(shpBinaryReader); } }
public Avalon(GeometryFactory Segments, Activation Attach, Activation Detach, ManipulationDeltaEventHandler Router,byte definition , bool Real = false) { if (!Real) { this.definition = definition; Data = Segments.Pattern(); ManipulationMode = Windows.UI.Xaml.Input.ManipulationModes.All; RenderTransform = new CompositeTransform(); RenderTransformOrigin = new Windows.Foundation.Point(0.5, 0.5); Fill = new SolidColorBrush(new Color { A = 0, R = 0, G = 0, B = 0 }); this.Attach = Attach; this.Detach = Detach; this.Router = Router; Tapped += Avalon_Tapped; Holding += Avalon_Holding; Loaded += Avalon_Loaded; Unloaded += Avalon_Unloaded; ManipulationDelta += Avalon_ManipulationDelta; this.Real = new Avalon(Segments, Attach, Detach, null, definition,true); this.Real.RenderTransform = RenderTransform; this.Real.RenderTransformOrigin = RenderTransformOrigin; this.Real.Data = Segments.Pattern(); this.Real.Fill = new SolidColorBrush(Colors.RosyBrown); Canvas.SetZIndex(this, 2); Canvas.SetZIndex(this.Real, 0); Avalon_Holding(null, null); } }
/// <summary> /// Creates a <see cref="ShapefileDataWriter"/> that appends to a shapefile instead of creating a new one. /// </summary> /// <param name="filename">The filename to append to.</param> /// <param name="factory">The Geometry factory to use.</param> public ShapefileDataWriter(string filename, GeometryFactory factory) { // appends _filename = filename; _shpWriter = new ShapefileWriter(filename, factory,true); _dbfWriter = new DbaseFileWriter(GetDbasefilename(_filename),true); }
public QueryableShapefileReader(string path, GeometryFactory factory) { _path = path; _factory = factory; this.Initialize(); }
/// <summary> /// Creates a <see cref="GeometryWKTReader">GeometryWKTReader</see> that creates objects using the given <b>GeometryFactory</b>. /// </summary> /// <param name="factory">The <b>GeometryFactory</b> used to create geometries.</param> public GeometryWKTReader(GeometryFactory factory) { if (factory == null) { throw new ArgumentNullException("factory"); } _factory = factory; _precisionModel = factory.getPrecisionModel(); }
/// <summary> /// Initializes a new instance of the <see cref="ShapefileDataWriter">ShapefileDataWriter</see> class. /// </summary> /// <param name="filename">The name of the file to write.</param> /// <param name="factory">The <b>GeometryFactory</b> to use.</param> /// <param name="fields">An <see cref="DbaseFieldDescriptor">DbaseFieldDescriptor[]</see> containing the data column definitions.</param> /// <remarks> /// The <see cref="ShapefileDataWriter.Close">Close</see> method must be called in order to update /// the underlying file headers. If <see cref="ShapefileDataWriter.Close">Close</see> is not called /// the underlying files may be in an invalid state. /// </remarks> public ShapefileDataWriter(string filename, GeometryFactory factory, DbaseFieldDescriptor[] fields) { _filename = filename; // This may need to have more logic to it to ensure we end up with the proper paths.... _shpWriter = new ShapefileWriter(_filename, factory); _dbfWriter = new DbaseFileWriter(GetDbasefilename(_filename)); for (int i = 0; i < fields.Length; i++) { _dbfWriter.AddColumn(fields[i]); } }
/// <summary> /// Reads a stream and converts the shapefile record to an equilivent geometry object. /// </summary> /// <param name="reader">The stream to read.</param> /// <param name="factory">The geometry factory to use when making the object.</param> /// <returns>The Geometry object that represents the shape file record.</returns> public override Geometry Read(BigEndianBinaryReader reader, GeometryFactory factory) { if (this.GetShapeType(reader) != ShapeType.Point) { throw new ShapefileException("Attempting to load a non-point as point."); } Coordinate coord = new Coordinate(reader.ReadDouble(), reader.ReadDouble()); factory.getPrecisionModel().makePrecise(coord); return factory.createPoint(coord); }
/// <summary> /// Reads a stream and converts the shapefile record to an equilivent geometry object. /// </summary> /// <param name="reader">The stream to read.</param> /// <param name="factory">The geometry factory to use when making the object.</param> /// <returns>The Geometry object that represents the shape file record.</returns> public override Geometry Read(BigEndianBinaryReader reader, GeometryFactory factory) { int shapeTypeNum = reader.ReadInt32(); ShapeType shapeType = (ShapeType)Enum.Parse(typeof(ShapeType),shapeTypeNum.ToString()); if (shapeType != ShapeType.Arc) { throw new ShapefileException("Attempting to load a non-arc as arc."); } //read and for now ignore bounds. double[] box = new double[4]; for (int i = 0; i < 4; i++) { double d= reader.ReadDouble(); box[i] =d; } int numParts = reader.ReadInt32(); int numPoints = reader.ReadInt32(); int[] partOffsets = new int[numParts]; for (int i = 0; i < numParts; i++) { partOffsets[i] = reader.ReadInt32(); } LineString[] lines = new LineString[numParts]; int start, finish, length; for (int part = 0; part < numParts; part++) { start = partOffsets[part]; if (part == numParts - 1) { finish = numPoints; } else { finish = partOffsets[part + 1]; } length = finish - start; Coordinate[] coords = new Coordinate[length]; for (int i = 0; i < length; i++) { Coordinate coord = new Coordinate(reader.ReadDouble(), reader.ReadDouble()); factory.getPrecisionModel().makePrecise(coord); coords[i] = coord; } lines[part] = factory.createLineString(new PackedCoordinateSequence.Float(coords, 2)); } return factory.createMultiLineString(lines); }
public void Test2() { string wkt = " "; GeometryFactory factory = new GeometryFactory(); try { Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Assertion.Fail("ArgumentException should have been thrown."); } catch(ParseException) { } }
public void Test1() { string wkt = null; GeometryFactory factory = new GeometryFactory(); try { Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Assertion.Fail("parse exception"); } catch(ArgumentNullException) { } }
/// <summary> /// Initializes a new instance of the <see cref="ShapefileWriter">ShapefileWriter</see> class with the specified filename and factory . /// </summary> /// <param name="filename">The name of the file to write.</param> /// <param name="factory">The <b>GeometryFactory</b> to use.</param> /// <exception cref="ArgumentNullException">The factory is a null reference (Nothing in Visual Basic).</exception> public ShapefileWriter(string filename, GeometryFactory factory) : this(filename,factory, false) { /*if (factory == null) { throw new ArgumentNullException("factory"); } _shpWriter = new BigEndianBinaryWriter(File.Open(filename, FileMode.CreateNew)); _shxWriter = new BigEndianBinaryWriter(File.Open(Path.Combine(Path.GetDirectoryName(filename), Path.GetFileNameWithoutExtension(filename) + ".shx"), FileMode.CreateNew)); _factory = factory; // Write dummy headers as place holders this.WriteHeader(_shpWriter,0); this.WriteHeader(_shxWriter,0);*/ }
/// <summary> /// Returns a byte[] containing the supplied <b>Geometry</b> object's Well-known binary representation. /// </summary> /// <param name="geometry">The <b>Geometry</b> object.</param> /// <param name="factory">The <b>GeometryFactory</b>.</param> /// <param name="byteOrder">The desired <see cref="WKBByteOrder">WKBByteOrder</see>.</param> /// <returns>A byte[] containing the supplied <b>Geometry</b> object's Well-known binary representation.</returns> public static byte[] GetBytes(Geometry geometry, GeometryFactory factory, WKBByteOrder byteOrder) { if (geometry == null) { throw new ArgumentNullException("geometry"); } using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(ms)) { new GeometryWKBWriter(writer, factory).WriteGeometry(geometry, byteOrder); return ms.ToArray(); } } }
/// <summary> /// This method returns a FeatureDataTable containing all the rows from the shapefile that intersect the testGeometry. /// The ShapeFile.ExecuteIntersectionQuery method only tests bounding boxes so we use the FilterDelegate property to add a true /// intersection test using NetTopologySuite /// </summary> /// <param name="pathToShapefile">The path to the shapefile</param> /// <param name="testGeometry">The geometry that we want to test against</param> /// <returns></returns> public FeatureDataTable GetIntersectingFeaturesUsingFilterDelegate(string pathToShapefile, SMGeometry testGeometry) { //create a new shapefile provider using (ShapeFile shapefile = new ShapeFile(pathToShapefile)) { //create an nts GeometryFactory GeometryFactory geometryFactory = new GeometryFactory(); //convert the testGeometry into the equivalent NTS geometry GeoAPI.Geometries.IGeometry testGeometryAsNtsGeom = GeometryConverter.ToNTSGeometry(testGeometry, geometryFactory); SMGeometry check = GeometryConverter.ToSharpMapGeometry(testGeometryAsNtsGeom); if (!check.Equals(testGeometry)) throw new ApplicationException("conversion error"); //set the shapefile providers' FilterDelegate property to a new anonymous method //this delegate method will be called for each potential row shapefile.FilterDelegate = delegate(FeatureDataRow featureDataRow) { //get the geometry from the featureDataRow SMGeometry rowGeometry = featureDataRow.Geometry; //convert it to the equivalent NTS geometry GeoAPI.Geometries.IGeometry compareGeometryAsNtsGeometry = GeometryConverter.ToNTSGeometry(rowGeometry, geometryFactory); //do the test. Note that the testGeometryAsNtsGeometry is available here because it is //declared in the same scope as the anonymous method. bool intersects = testGeometryAsNtsGeom.Intersects(compareGeometryAsNtsGeometry); //return the result return intersects; }; //create a new FeatureDataSet FeatureDataSet featureDataSet = new FeatureDataSet(); //open the shapefile shapefile.Open(); //call ExecuteIntersectionQuery. The FilterDelegate will be used to limit the result set shapefile.ExecuteIntersectionQuery(testGeometry, featureDataSet); //close the shapefile shapefile.Close(); //return the populated FeatureDataTable return featureDataSet.Tables[0]; } }
/// <summary> /// Test getting and setting the properties /// </summary> public void Test_MultipleRead() { PrecisionModel pm = new PrecisionModel(1,0,0); GeometryFactory geometryFactory = new GeometryFactory(pm,-1); string filename= Global.GetUnitTestRootDirectory()+@"\IO\Shapefile\Testfiles\statepop.shp"; // tests two readers reading the file as the same time. Geotools.IO.ShapefileReader shpFile = new Geotools.IO.ShapefileReader(filename, geometryFactory); Geotools.IO.ShapefileReader shpFile2 = new Geotools.IO.ShapefileReader(filename, geometryFactory); foreach(object row in shpFile) { Assertion.AssertNotNull(row); foreach(object row2 in shpFile2) { Assertion.AssertNotNull(row2); } } }
public void Test_DataGrid() { PrecisionModel pm = new PrecisionModel(100000,0,0); GeometryFactory geometryFactory = new GeometryFactory(pm,-1); string filename= Global.GetUnitTestRootDirectory()+@"\IO\Shapefile\Testfiles\statepop"; ShapefileDataReader shpDataReader = Geotools.IO.Shapefile.CreateDataReader(filename, geometryFactory); // make sure the datagrid gets the column headings. DataGrid grid = new DataGrid(); grid.DataSource = shpDataReader; grid.DataBind(); TextWriter tempWriter = new StringWriter(); grid.RenderControl(new HtmlTextWriter(tempWriter)); string html = tempWriter.ToString(); bool same = Compare.CompareAgainstString(Global.GetUnitTestRootDirectory()+@"\IO\Shapefile\Testfiles\ExpectedDataGridDataReader.txt",html); Assertion.AssertEquals("Datagrid properties",true,same); }
/// <summary> /// Initializes a new instance of the ShapefileDataReader class. /// </summary> /// <param name="filename">The shapefile to read (minus the .shp extension)</param> ///<param name="geometryFactory">The GeometryFactory to use.</param> public ShapefileDataReader(string filename, GeometryFactory geometryFactory) { if (filename==null) { throw new ArgumentNullException("filename"); } if (geometryFactory==null) { throw new ArgumentNullException("geometryFactory"); } _geometryFactory = geometryFactory; _open=true; if (filename.ToLower().EndsWith(".shp")) { filename = filename.ToLower().Replace(".shp",""); } _dbfReader = new DbaseFileReader(filename+".dbf"); _shpReader = new ShapefileReader(filename+".shp", geometryFactory); _dbfHeader = _dbfReader.GetHeader(); _recordCount = _dbfHeader.NumRecords; // _wkbWriter = new GeometryWKBWriter(_geometryFactory); // copy dbase fields to our own array. Insert into the first position, the shape column _dbaseFields = new DbaseFieldDescriptor[_dbfHeader.Fields.Length + 1]; _dbaseFields[0] = DbaseFieldDescriptor.ShapeField(); //_dbaseFields[1] = DbaseFieldDescriptor.IdField(); for(int i=0; i < _dbfHeader.Fields.Length; i++) { _dbaseFields[i+1] = _dbfHeader.Fields[i]; } _shpHeader = _shpReader.Header; _dbfEnumerator = _dbfReader.GetEnumerator(); _shpEnumerator = _shpReader.GetEnumerator(); _moreRecords = true; }
private static IMultiParts ToGeneralMultiPart(MultiPartShapeBuffer multiPart, GeometryType geometryType) { IMultiParts multiParts; if (geometryType == GeometryType.Polyline) { multiParts = new GeometryFactory().CreatePolyline(); } else { multiParts = new GeometryFactory().CreatePolygon(); } var rings = multiParts.Parts; for (var i = 0; i < multiPart.NumParts; i++) { var partStart = multiPart.Parts[i]; int partEnd; if (i + 1 < multiPart.NumParts) { partEnd = multiPart.Parts[i + 1]; } else { partEnd = multiPart.NumPoints - 1; } var linearRing = new GeometryFactory().CreateLineString(); var points = linearRing.Vertices; for (var j = partStart; j <= partEnd; j++) { var mapPoint = new GeometryFactory().CreatePoint(multiPart.Points[i].x, multiPart.Points[i].y); points.Add(mapPoint); } rings.Add(linearRing); } return multiParts; }
/// <summary> /// Reads and parses the geometry with ID 'oid' from the ShapeFile /// </summary> /// <remarks><see cref="FilterDelegate">Filtering</see> is not applied to this method</remarks> /// <param name="oid">Object ID</param> /// <returns>geometry</returns> private IGeometry ReadGeometry(uint oid) { brShapeFile.BaseStream.Seek(GetShapeIndex(oid) + 8, 0); //Skip record number and content length ShapeType type = (ShapeType)brShapeFile.ReadInt32(); //Shape type if (type == ShapeType.Null) { return(null); } if (_ShapeType == ShapeType.Point || _ShapeType == ShapeType.PointM || _ShapeType == ShapeType.PointZ) { //SharpMap.Geometries.Point tempFeature = new SharpMap.Geometries.Point(); return(GeometryFactory.CreatePoint(brShapeFile.ReadDouble(), brShapeFile.ReadDouble())); } else if (_ShapeType == ShapeType.Multipoint || _ShapeType == ShapeType.MultiPointM || _ShapeType == ShapeType.MultiPointZ) { brShapeFile.BaseStream.Seek(32 + brShapeFile.BaseStream.Position, 0); //skip min/max box List <IPoint> feature = new List <IPoint>(); //SharpMap.Geometries.MultiPoint feature = new SharpMap.Geometries.MultiPoint(); int nPoints = brShapeFile.ReadInt32(); // get the number of points if (nPoints == 0) { return(null); } for (int i = 0; i < nPoints; i++) { feature.Add(GeometryFactory.CreatePoint(brShapeFile.ReadDouble(), brShapeFile.ReadDouble())); } return(GeometryFactory.CreateMultiPoint(feature.ToArray())); } else if (_ShapeType == ShapeType.PolyLine || _ShapeType == ShapeType.Polygon || _ShapeType == ShapeType.PolyLineM || _ShapeType == ShapeType.PolygonM || _ShapeType == ShapeType.PolyLineZ || _ShapeType == ShapeType.PolygonZ) { brShapeFile.BaseStream.Seek(32 + brShapeFile.BaseStream.Position, 0); //skip min/max box int nParts = brShapeFile.ReadInt32(); // get number of parts (segments) if (nParts == 0) { return(null); } int nPoints = brShapeFile.ReadInt32(); // get number of points int[] segments = new int[nParts + 1]; //Read in the segment indexes for (int b = 0; b < nParts; b++) { segments[b] = brShapeFile.ReadInt32(); } //add end point segments[nParts] = nPoints; if ((int)_ShapeType % 10 == 3) { //SharpMap.Geometries.MultiLineString mline = new SharpMap.Geometries.MultiLineString(); List <ILineString> mline = new List <ILineString>(); for (int LineID = 0; LineID < nParts; LineID++) { //SharpMap.Geometries.LineString line = new SharpMap.Geometries.LineString(); List <ICoordinate> line = new List <ICoordinate>(); for (int i = segments[LineID]; i < segments[LineID + 1]; i++) { line.Add(GeometryFactory.CreateCoordinate(brShapeFile.ReadDouble(), brShapeFile.ReadDouble())); } //line.Vertices.Add(new SharpMap.Geometries.Point( mline.Add(GeometryFactory.CreateLineString(line.ToArray())); } if (mline.Count == 1) { return(mline[0]); } return(GeometryFactory.CreateMultiLineString(mline.ToArray())); } else //(_ShapeType == ShapeType.Polygon etc...) { //First read all the rings //List<SharpMap.Geometries.LinearRing> rings = new List<SharpMap.Geometries.LinearRing>(); List <ILinearRing> rings = new List <ILinearRing>(); for (int RingID = 0; RingID < nParts; RingID++) { //SharpMap.Geometries.LinearRing ring = new SharpMap.Geometries.LinearRing(); List <ICoordinate> ring = new List <ICoordinate>(); for (int i = segments[RingID]; i < segments[RingID + 1]; i++) { ring.Add(GeometryFactory.CreateCoordinate(brShapeFile.ReadDouble(), brShapeFile.ReadDouble())); } //ring.Vertices.Add(new SharpMap.Geometries.Point rings.Add(GeometryFactory.CreateLinearRing(ring.ToArray())); } bool[] IsCounterClockWise = new bool[rings.Count]; int PolygonCount = 0; for (int i = 0; i < rings.Count; i++) { IsCounterClockWise[i] = GeometryFactory.IsCCW(rings[i].Coordinates); if (!IsCounterClockWise[i]) { PolygonCount++; } } if (PolygonCount == 1) //We only have one polygon { ILinearRing shell = rings[0]; List <ILinearRing> holes = new List <ILinearRing>(); if (rings.Count > 1) { for (int i = 1; i < rings.Count; i++) { holes.Add(rings[i]); } } return(GeometryFactory.CreatePolygon(shell, holes.ToArray())); } else { List <IPolygon> polys = new List <IPolygon>(); ILinearRing shell = rings[0]; List <ILinearRing> holes = new List <ILinearRing>(); for (int i = 1; i < rings.Count; i++) { if (!IsCounterClockWise[i]) { polys.Add(GeometryFactory.CreatePolygon(shell, null)); shell = rings[i]; } else { holes.Add(rings[i]); } } polys.Add(GeometryFactory.CreatePolygon(shell, holes.ToArray())); return(GeometryFactory.CreateMultiPolygon(polys.ToArray())); } } } else { throw (new ApplicationException("Shapefile type " + _ShapeType.ToString() + " not supported")); } }
/// <summary> /// /// </summary> /// <param name="shell"></param> /// <param name="holes"></param> /// <param name="factory"></param> /// <param name="tolerance"></param> public CurvePolygon(LinearRing shell, LinearRing[] holes, GeometryFactory factory, double tolerance) : base(shell, holes, factory) { this.tolerance = tolerance; }
public void Insert_with_non_key_default_value() { using var testStore = SqlServerTestStore.CreateInitialized(DatabaseName); using (var context = new BlogContextNonKeyDefaultValue(testStore.Name)) { context.Database.EnsureCreatedResiliently(); var blogs = new List <Blog> { new() { Name = "One Unicorn" }, new() { Name = "Two Unicorns", CreatedOn = new DateTime(1969, 8, 3, 0, 10, 0), NeedsConverter = new NeedsConverter(111), GeometryCollection = GeometryFactory.CreateGeometryCollection( new Geometry[] { GeometryFactory.CreatePoint(new Coordinate(1, 3)) }) } }; context.AddRange(blogs); context.SaveChanges(); Assert.NotEqual(new DateTime(), blogs[0].CreatedOn); Assert.NotEqual(new DateTime(), blogs[1].CreatedOn); Assert.Equal(111, blogs[1].NeedsConverter.Value); var point = ((Point)blogs[1].GeometryCollection.Geometries[0]); Assert.Equal(1, point.X); Assert.Equal(3, point.Y); } using (var context = new BlogContextNonKeyDefaultValue(testStore.Name)) { var blogs = context.Blogs.OrderBy(e => e.Name).ToList(); Assert.Equal(3, blogs.Count); Assert.NotEqual(new DateTime(), blogs[0].CreatedOn); Assert.Equal(new DateTime(1969, 8, 3, 0, 10, 0), blogs[1].CreatedOn); Assert.Equal(new DateTime(1974, 8, 3, 0, 10, 0), blogs[2].CreatedOn); var point1 = ((Point)blogs[1].GeometryCollection.Geometries[0]); Assert.Equal(1, point1.X); Assert.Equal(3, point1.Y); var point2 = ((Point)blogs[2].GeometryCollection.Geometries[0]); Assert.Equal(1, point2.X); Assert.Equal(2, point2.Y); blogs[0].CreatedOn = new DateTime(1973, 9, 3, 0, 10, 0); blogs[1].Name = "X Unicorns"; blogs[1].NeedsConverter = new NeedsConverter(222); blogs[1].GeometryCollection.Geometries[0] = GeometryFactory.CreatePoint(new Coordinate(1, 11)); blogs[2].Name = "Y Unicorns"; blogs[2].NeedsConverter = new NeedsConverter(333); blogs[2].GeometryCollection.Geometries[0] = GeometryFactory.CreatePoint(new Coordinate(1, 22)); context.SaveChanges(); } using (var context = new BlogContextNonKeyDefaultValue(testStore.Name)) { var blogs = context.Blogs.OrderBy(e => e.Name).ToList(); Assert.Equal(3, blogs.Count); Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 0), blogs[0].CreatedOn); Assert.Equal(new DateTime(1969, 8, 3, 0, 10, 0), blogs[1].CreatedOn); Assert.Equal(222, blogs[1].NeedsConverter.Value); Assert.Equal(new DateTime(1974, 8, 3, 0, 10, 0), blogs[2].CreatedOn); Assert.Equal(333, blogs[2].NeedsConverter.Value); var point1 = ((Point)blogs[1].GeometryCollection.Geometries[0]); Assert.Equal(1, point1.X); Assert.Equal(11, point1.Y); var point2 = ((Point)blogs[2].GeometryCollection.Geometries[0]); Assert.Equal(1, point2.X); Assert.Equal(22, point2.Y); } }
private void MapImage_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if (_Map != null) { if (MouseUp != null) { MouseUp(this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)), e); } if (e.Button == MouseButtons.Left) { if (this.ActiveTool == Tools.ZoomOut) { double scale = 0.5; if (!mousedragging) { _Map.Center = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); if (MapCenterChanged != null) { MapCenterChanged(_Map.Center); } } else { if (e.Y - mousedrag.Y < 0) //Zoom out { scale = (float)Math.Pow(1 / (float)(mousedrag.Y - e.Y), 0.5); } else //Zoom in { scale = 1 + (e.Y - mousedrag.Y) * 0.1; } } _Map.Zoom *= 1 / scale; if (MapZoomChanged != null) { MapZoomChanged(_Map.Zoom); } Refresh(); } else if (this.ActiveTool == Tools.ZoomIn) { double scale = 2; if (!mousedragging) { _Map.Center = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); if (MapCenterChanged != null) { MapCenterChanged(_Map.Center); } } else { if (e.Y - mousedrag.Y < 0) //Zoom out { scale = (float)Math.Pow(1 / (float)(mousedrag.Y - e.Y), 0.5); } else //Zoom in { scale = 1 + (e.Y - mousedrag.Y) * 0.1; } } _Map.Zoom *= 1 / scale; if (MapZoomChanged != null) { MapZoomChanged(_Map.Zoom); } Refresh(); } else if (this.ActiveTool == Tools.Pan) { if (mousedragging) { System.Drawing.Point pnt = new System.Drawing.Point(this.Width / 2 + (mousedrag.X - e.Location.X), this.Height / 2 + (mousedrag.Y - e.Location.Y)); _Map.Center = this._Map.ImageToWorld(pnt); if (MapCenterChanged != null) { MapCenterChanged(_Map.Center); } } else { _Map.Center = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); if (MapCenterChanged != null) { MapCenterChanged(_Map.Center); } } Refresh(); } else if (this.ActiveTool == Tools.Query) { if (_Map.Layers.Count > _queryLayerIndex && _queryLayerIndex > -1) { if (_Map.Layers[_queryLayerIndex].GetType() == typeof(SharpMap.Layers.VectorLayer)) { SharpMap.Layers.VectorLayer layer = _Map.Layers[_queryLayerIndex] as SharpMap.Layers.VectorLayer; IEnvelope bbox = GeometryFactory.CreatePoint(this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y))).EnvelopeInternal; bbox.ExpandBy(_Map.PixelSize * 5); SharpMap.Data.FeatureDataSet ds = new SharpMap.Data.FeatureDataSet(); layer.DataSource.Open(); layer.DataSource.ExecuteIntersectionQuery(bbox, ds); layer.DataSource.Close(); if (ds.Tables.Count > 0) { if (MapQueried != null) { MapQueried(ds.Tables[0]); } else if (MapQueried != null) { MapQueried(new SharpMap.Data.FeatureDataTable()); } } } } else { MessageBox.Show("No active layer to query"); } } } if (mousedragImg != null) { mousedragImg.Dispose(); mousedragImg = null; } mousedragging = false; } }
/// <summary> /// /// </summary> /// <param name="op"></param> /// <param name="geometryFactory"></param> /// <param name="ptLocator"></param> public LineBuilder(OverlayOp op, GeometryFactory geometryFactory, PointLocator ptLocator) { _op = op; _geometryFactory = geometryFactory; _ptLocator = ptLocator; }
private static IPolycurve GetOriginalGeometry( [NotNull] IFeature feature, [CanBeNull] FeatureVertexInfo featureVertexInfo) { bool isPolygon = feature.Shape.GeometryType == esriGeometryType.esriGeometryPolygon; if (featureVertexInfo == null) { return(GeometryFactory.CreatePolyline(feature.Shape)); } featureVertexInfo.SimplifyCrackPoints(); if (_msg.IsVerboseDebugEnabled) { _msg.VerboseDebugFormat( "Cutting input geometry with protected points. Generalization Info: {0}", featureVertexInfo.ToString(true)); } IPolyline originalGeometry = featureVertexInfo.OriginalClippedPolyline; if (featureVertexInfo.CrackPointCollection == null || featureVertexInfo.CrackPointCollection.PointCount == 0) { return(originalGeometry); } // TODO: consider consolidating points equal in XY: get average Z (or Z from non-editable feature) // to really make coincident! IPointCollection protectedPoints = featureVertexInfo.CrackPointCollection; IGeometryCollection splittedResult = null; foreach (IPath path in GeometryUtils.GetPaths(originalGeometry)) { bool splitHappenedAtFrom; double cutOffDistance = GeometryUtils.GetXyTolerance(originalGeometry); const bool projectPointsOntoPathToSplit = true; IGeometryCollection splittedPaths = GeometryUtils.SplitPath( path, protectedPoints, projectPointsOntoPathToSplit, cutOffDistance, out splitHappenedAtFrom); if (isPolygon && path.IsClosed && !splitHappenedAtFrom && splittedPaths.GeometryCount > 1) { MergeLastWithFirstPart(splittedPaths); } if (splittedResult == null) { splittedResult = splittedPaths; } else { splittedResult.AddGeometryCollection(splittedPaths); } } if (_msg.IsVerboseDebugEnabled) { _msg.VerboseDebugFormat("Original feature {0} splitted by protected points: {1}", GdbObjectUtils.ToString(feature), GeometryUtils.ToString((IGeometry)splittedResult)); } return(splittedResult as IPolycurve); }
/// <summary> /// Constructor /// </summary> /// <param name="geometryFactory"></param> public GpxLoopsSplitterExecutor(GeometryFactory geometryFactory) { _geometryFactory = geometryFactory; }
/// <summary> /// Initializes a new instance of the BufferOp class. /// </summary> /// <param name="g0"></param> public BufferOp(Geometry g0) : base(g0) { _graph = new PlanarGraph(new OverlayNodeFactory()); _geomFact = new GeometryFactory(g0.PrecisionModel, g0.GetSRID()); }
public void TestKNearestNeighbors() { int topK = 1000; int totalRecords = 10000; var geometryFactory = new GeometryFactory(); var coordinate = new Coordinate(10.1, -10.1); var queryCenter = geometryFactory.CreatePoint(coordinate); int valueRange = 1000; var testDataset = new List <Geometry>(); var correctData = new List <Geometry>(); var random = new Random(); var distanceComparator = new GeometryDistanceComparer(queryCenter, true); /* * Generate the random test data set */ for (int i = 0; i < totalRecords; i++) { coordinate = new Coordinate(-100 + random.Next(valueRange) * 1.1, random.Next(valueRange) * (-5.1)); var spatialObject = geometryFactory.CreatePoint(coordinate); testDataset.Add(spatialObject); } /* * Sort the original data set and make sure the elements are sorted in an ascending order */ testDataset.Sort(distanceComparator); /* * Get the correct top K */ for (int i = 0; i < topK; i++) { correctData.Add(testDataset[i]); } var strtree = new STRtree <Geometry>(); for (int i = 0; i < totalRecords; i++) { strtree.Insert(testDataset[i].EnvelopeInternal, testDataset[i]); } /* * Shoot a random query to make sure the STR-Tree is built. */ strtree.Query(new Envelope(1 + 0.1, 1 + 0.1, 2 + 0.1, 2 + 0.1)); /* * Issue the KNN query. */ var testTopK = strtree.NearestNeighbour(queryCenter.EnvelopeInternal, queryCenter, new GeometryItemDistance(), topK); var topKList = new List <Geometry>(testTopK); topKList.Sort(distanceComparator); /* * Check the difference between correct result and test result. The difference should be 0. */ int difference = 0; for (int i = 0; i < topK; i++) { if (distanceComparator.Compare(correctData[i], topKList[i]) != 0) { difference++; } } Assert.That(difference, Is.Zero); }
public void TestWktReadMultiPoint2() { string wkt = "MULTIPOINT EMPTY"; GeometryFactory factory = new GeometryFactory(); Geometry geometry = new GeometryWKTReader(factory).Create(wkt); GeometryCollection multipoint = (GeometryCollection)geometry; Assertion.AssertEquals("empty",true,multipoint.isEmpty()); string wkt2 = new GeometryWKTWriter().Write(multipoint); Assertion.AssertEquals("wkt",true,Compare.WktStrings(wkt,wkt2)); }
private List <BaseLabel> CreateLabelDefinitions(Graphics g, MapViewport map, FeatureDataTable features) { var labels = new List <BaseLabel>(); var factory = new GeometryFactory(); for (int i = 0; i < features.Count; i++) { var feature = features[i]; LabelStyle style; if (Theme != null) //If thematics is enabled, lets override the style { style = Theme.GetStyle(feature) as LabelStyle; } else { style = Style; } // Do we need to render at all? if (!style.Enabled) { continue; } // Rotation float rotationStyle = style != null ? style.Rotation : 0f; float rotationColumn = 0f; if (!String.IsNullOrEmpty(RotationColumn)) { Single.TryParse(feature[RotationColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs, out rotationColumn); } float rotation = rotationStyle + rotationColumn; // Priority int priority = Priority; if (_getPriorityMethod != null) { priority = _getPriorityMethod(feature); } else if (!String.IsNullOrEmpty(PriorityColumn)) { Int32.TryParse(feature[PriorityColumn].ToString(), NumberStyles.Any, Map.NumberFormatEnUs, out priority); } // Text string text; if (_getLabelMethod != null) { text = _getLabelMethod(feature); } else { text = feature[LabelColumn].ToString(); } if (String.IsNullOrEmpty(text)) { continue; } // Geometry feature.Geometry = ToTarget(feature.Geometry); // for lineal geometries, clip to ensure proper labeling if (feature.Geometry is ILineal) { feature.Geometry = ClipLinealGeomToViewExtents(map, feature.Geometry); } if (feature.Geometry is IPolygonal) { // TO CONSIDER clip to ViewExtents? // This will ensure that polygons only partly in view will be labelled // but perhaps need complexity threshold (eg Pts < 500) so as not to impact rendering // or new prop bool PartialPolygonalLabel } if (feature.Geometry is IGeometryCollection geoms) { if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.All) { for (int j = 0; j < geoms.Count; j++) { var lbl = CreateLabelDefinition(feature, geoms.GetGeometryN(j), text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.CommonCenter) { if (geoms.NumGeometries > 0) { var pt = geoms.Centroid; double closest = double.MaxValue; int idxOfClosest = 0; for (int j = 0; j < geoms.NumGeometries; j++) { var geom = geoms.GetGeometryN(j); double dist = geom.Distance(pt); if (dist < closest) { closest = dist; idxOfClosest = j; } } var lbl = CreateLabelDefinition(feature, geoms.GetGeometryN(idxOfClosest), text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.First) { if (geoms.NumGeometries > 0) { var lbl = CreateLabelDefinition(feature, geoms.GetGeometryN(0), text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } else if (MultipartGeometryBehaviour == MultipartGeometryBehaviourEnum.Largest) { if (geoms.NumGeometries > 0) { double largestVal = 0d; int idxOfLargest = 0; for (var j = 0; j < geoms.NumGeometries; j++) { var geom = geoms.GetGeometryN(j); if (geom is ILineString lineString && lineString.Length > largestVal) { largestVal = lineString.Length; idxOfLargest = j; } if (geom is IMultiLineString multiLineString && multiLineString.Length > largestVal) { largestVal = multiLineString.Length; idxOfLargest = j; } if (geom is IPolygon polygon && polygon.Area > largestVal) { largestVal = polygon.Area; idxOfLargest = j; } if (geom is IMultiPolygon multiPolygon && multiPolygon.Area > largestVal) { largestVal = multiPolygon.Area; idxOfLargest = j; } } var lbl = CreateLabelDefinition(feature, geoms.GetGeometryN(idxOfLargest), text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } } else { BaseLabel lbl = CreateLabelDefinition(feature, feature.Geometry, text, rotation, priority, style, map, g, _getLocationMethod); if (lbl != null) { labels.Add(lbl); } } } return(labels); }
/// <summary> /// Initializes a new instance of the <see cref="GeometryWKBWriter">GeometryWKBWriter</see> class. /// </summary> /// <param name="writer">The <b>GeometryFactory</b> used when writing geometries.</param> /// <param name="factory">The <b>GeometryFactory</b> used when writing geometries.</param> public GeometryWKBWriter(BinaryWriter writer, GeometryFactory factory) { _writer = writer; _factory = factory; }
public void Test3() { string wkt = "MULTIPOINT EMPTY2 "; GeometryFactory factory = new GeometryFactory(); try { Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Assertion.Fail("EMPTY2 is not valid."); } catch(ParseException) { } }
public void TestWktReadPoint1() { string wkt = "POINT ( 3 4 )"; GeometryFactory factory = new GeometryFactory(); Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Point point = (Point)geometry; Assertion.AssertEquals("empty",false,point.isEmpty()); Assertion.AssertEquals("x",3.0,point.getX()); Assertion.AssertEquals("y",4.0,point.getY()); string wkt2 = new GeometryWKTWriter().Write(point); Assertion.AssertEquals("wkt",true,Compare.WktStrings(wkt,wkt2)); }
protected BaseSamples(GeometryFactory factory, WKTReader reader) { Factory = factory; Reader = reader; }
public EdgeRing(GeometryFactory factory) { deList = new ArrayList(); this.factory = factory; }
static void Main(string[] args) { // Load up the sample farm/field/cropzone information var treeData = (JArray)(JObject.Parse(File.ReadAllText("tree.json"))["Results"]); // Load up the field/cropzone boundaries var boundaryData = (JArray)(JObject.Parse(File.ReadAllText("boundaries.json"))["Results"]); // Initialize a Well-Known-Text (WKT) reader for handling the sample boundary data GeometryFactory geometryFactory = new GeometryFactory(); NetTopologySuite.IO.WKTReader wktReader = new NetTopologySuite.IO.WKTReader(geometryFactory); // In this console app the ADMPlugin is included as a NuGet package so the ADMPlugin.dll is always // copied directly in to the executable directory. That's why we tell the PluginFactory to look there // for the ADMPlugin. string applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); // The PluginFactory looks at all the DLLs in the target directory to find any that implement the IPlugin interface. var pluginFactory = new PluginFactory(applicationPath); // We're only interested in the ADMPlugin here, so I address it directly instead of looking through all the // available plugins that the PluginFactory found. var admPlugin = pluginFactory.GetPlugin("ADMPlugin"); // The ADMPlugin doesn't require any initialization parameters. admPlugin.Initialize(); // The ApplicationDataModel is the root object in ADAPT ApplicationDataModel export = new ApplicationDataModel(); // The Catalog object (inside the ApplicationDataModel) holds all the items you would expect to find in a "pick list". // Alternatively, you could think of it as the place you put everything used "by reference" in any of the Documents // you are trying to send. export.Catalog = new Catalog(); // The Documents object (inside the ApplicationDataModel) holds all the Plans, Recommendations, WorkOrders, and // WorkRecords (and their component parts). We won't be using this in this example. export.Documents = new Documents(); // Create a "crop year" TimeScope to tag objects with. TimeScope cropYear = new TimeScope(); cropYear.Description = "2017"; cropYear.DateContext = DateContextEnum.CropSeason; export.Catalog.TimeScopes.Add(cropYear); // Create the Grower object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. Grower adaptGrower = new Grower(); // Associate your internal, unique identifier to the Grower object by creating a UniqueId object // and adding it to the Grower object's CompoundIdentifier. UniqueId ourId = new UniqueId(); ourId.Id = "7d2253f0-fce6-4740-b3c3-f9c8ab92bfaa"; // Notice the available IdTypeEnum choices. Not everybody uses the same way of identifying things in their // system. As a result, we must support a number of identification schemes. ourId.IdType = IdTypeEnum.UUID; // Almost as important as the identifier is knowing who created it (or where it came from). ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; // Each CompoundIdentifier that is used in ADAPT can have multiple unique identifiers associated with it. // Consider the possibilites here, not only can your identifier for something be peristed but also the // identifiers that your trading partner assigns to the same object. PLEASE CONSIDER PERSISTING AND RETURNING // IDENTIFIERS PASSED TO YOU IN THIS FASHION. This has the potential to result in a "frictionless" conversation // once the initial mapping is done, buy this benefit will only emerge if we all are "good neighbors". adaptGrower.Id.UniqueIds.Add(ourId); // You may notice that many of the objects in ADAPT have a minimal number of properties. Don't panic if you // can't find a place to put all your data. It may be in an associated object or intended to be expressed // as a ContextItem. adaptGrower.Name = "Ponderosa Farms"; // Add the Grower object to the Catalog. export.Catalog.Growers.Add(adaptGrower); // Pull the farm objects out of the sample JSON test data var farms = (from c in treeData where ((string)c["type"] == "farm") select c).ToList(); // Iterate over each farm foreach (var farm in farms) { // Create the Farm object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. Farm adaptFarm = new Farm(); ourId = new UniqueId(); ourId.Id = (string)farm["id"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptFarm.Id.UniqueIds.Add(ourId); adaptFarm.Description = (string)farm["text"]; // Here we link this farm object to the grower. Note that this is the integer (ReferenceId) in the // Grower's CompountIdentifier object. adaptFarm.GrowerId = adaptGrower.Id.ReferenceId; // Add the Farm object to the Catalog. export.Catalog.Farms.Add(adaptFarm); // Pull the field objects out of the sample JSON test data that are part of this iteration's farm var fields = (from c in treeData where (((string)c["type"] == "field") && ((string)c["parent"] == (string)farm["id"])) select c).ToList(); // Iterate over each field foreach (var field in fields) { // Create the Field object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. Field adaptField = new Field(); ourId = new UniqueId(); ourId.Id = (string)field["id"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptField.Id.UniqueIds.Add(ourId); adaptField.Description = (string)field["text"]; // Here we link this field object to the farm. Note that this is the integer (ReferenceId) in the // Farm's CompountIdentifier object. adaptField.FarmId = adaptFarm.Id.ReferenceId; // Pull the boundary object out of the sample JSON test data (if it exists) var fieldBoundary = (from c in boundaryData where (((string)c["FieldId"] == (string)field["id"]) && ((string)c["CropZoneId"] == null)) select c).FirstOrDefault(); if (fieldBoundary != null) { // This sample data has boundaries expressed as MultiPolygons in WKT so we need to transform that into the correlary ADAPT objects. // Your data may use a different geometry (instead of MultiPolygon) to describe your boundaries so your code may differ at this point. var boundary = wktReader.Read((string)fieldBoundary["MapData"]) as NetTopologySuite.Geometries.MultiPolygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon adaptMultiPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon(); adaptMultiPolygon.Polygons = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon>(); foreach (var geometry in boundary.Geometries) { var polygon = geometry as NetTopologySuite.Geometries.Polygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon adaptPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon(); adaptPolygon.ExteriorRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptPolygon.InteriorRings = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing>(); foreach (var coordinate in polygon.ExteriorRing.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptPolygon.ExteriorRing.Points.Add(adaptPoint); } foreach (var ring in polygon.InteriorRings) { var adaptRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptRing.Points = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Point>(); foreach (var coordinate in ring.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptRing.Points.Add(adaptPoint); } adaptPolygon.InteriorRings.Add(adaptRing); } adaptMultiPolygon.Polygons.Add(adaptPolygon); } // Unlike the CropZone object (which holds its geomertry internally) a Field's boundary is held in a separate FieldBoundary object. // Create the FieldBoundary object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. FieldBoundary adaptBoundary = new FieldBoundary(); // The FieldBoundary.SpatialData property is an ADAPT Shape object (which is an abastract class). What you actually attach here // is one of the child classes of Shape (Polygon, MultiPolygon, etc.). adaptBoundary.SpatialData = adaptMultiPolygon; // Here we link this field boundary object to the field. Note that this is the integer (ReferenceId) in the // Field's CompountIdentifier object. adaptBoundary.FieldId = adaptField.Id.ReferenceId; // Add the FieldBoundary object to the Catalog. export.Catalog.FieldBoundaries.Add(adaptBoundary); // It is possible for a given Field to have multiple FieldBounday objects associated with it, but we need to be able // to indicate which one should be used by "default". adaptField.ActiveBoundaryId = adaptBoundary.Id.ReferenceId; } // Add the Field object to the Catalog. *Note: We are adding this to the Catalog here so that we don't have to go // back and fetch the object to set the ActiveBoundaryId property. Not required, just convenient. export.Catalog.Fields.Add(adaptField); // We're defining a CropZone as a spatial area within a field grown to a crop during a specific window of time. // This is fundamentally different from the concept of a management zone (that might vary by plant population or soil type). // Pull the cropzone objects out of the sample JSON test data that are part of this iteration's field var cropzones = (from c in treeData where (((string)c["type"] == "cropzone") && ((string)c["parent"] == (string)field["id"])) select c).ToList(); // Iterate over each cropzone foreach (var cropzone in cropzones) { // It's entirely possible that we have already added this Crop to the Catalog during a previous iteration. We need to check // the Crop list in Catalog first and reuse that object if it exists. Crop adaptCrop = null; var crops = export.Catalog.Crops.Where(x => (x.Name == (string)cropzone["li_attr"]["CropName"])).ToList(); if (crops.Count > 0) { adaptCrop = crops[0]; } else { // Create the Crop object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. adaptCrop = new Crop(); ourId = new UniqueId(); ourId.Id = (string)cropzone["li_attr"]["CropId"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptCrop.Id.UniqueIds.Add(ourId); adaptCrop.Name = (string)cropzone["li_attr"]["CropName"]; // Add EPPO code as ContextItem at some point in the future // Add the Crop object to the Catalog. export.Catalog.Crops.Add(adaptCrop); } // Create the CropZone object. The constructor will automatically create the Id property and assign the // next available ReferenceId integer. CropZone adaptCropZone = new CropZone(); ourId = new UniqueId(); ourId.Id = (string)cropzone["id"]; ourId.IdType = IdTypeEnum.UUID; ourId.Source = "www.agconnections.com"; ourId.SourceType = IdSourceTypeEnum.URI; adaptCropZone.Id.UniqueIds.Add(ourId); adaptCropZone.Description = (string)cropzone["text"]; // Here we link this cropzone object to the field. Note that this is the integer (ReferenceId) in the // Field's CompountIdentifier object. adaptCropZone.FieldId = adaptField.Id.ReferenceId; // Here we link this cropzone object to the crop. Note that this is the integer (ReferenceId) in the // Crop's CompountIdentifier object. adaptCropZone.CropId = adaptCrop.Id.ReferenceId; // Here we link this cropzone object to the crop year TimeScope. Note that the TimeScope is used BY VALUE // instead of BY REFERENCE (like the field and crop above). adaptCropZone.TimeScopes.Add(cropYear); string areaString = (string)cropzone["li_attr"]["AreaValue"]; if (!string.IsNullOrEmpty(areaString)) { double area = Convert.ToDouble(areaString); adaptCropZone.Area = new NumericRepresentationValue(RepresentationInstanceList.vrReportedFieldArea.ToModelRepresentation(), new NumericValue(UnitSystemManager.GetUnitOfMeasure("ac1"), area)); } // As mentioned before, the CropZone (unlike Field) holds its boundary internally. Also unlike field, a CropZone is only expected // to have a single boundary due to its scope in crop & time. var czBoundary = (from c in boundaryData where ((string)c["CropZoneId"] == (string)cropzone["id"]) select c).FirstOrDefault(); if (czBoundary != null) { var boundary = wktReader.Read((string)czBoundary["MapData"]) as NetTopologySuite.Geometries.MultiPolygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon adaptMultiPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.MultiPolygon(); adaptMultiPolygon.Polygons = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon>(); foreach (var geometry in boundary.Geometries) { var polygon = geometry as NetTopologySuite.Geometries.Polygon; AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon adaptPolygon = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Polygon(); adaptPolygon.ExteriorRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptPolygon.InteriorRings = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing>(); foreach (var coordinate in polygon.ExteriorRing.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptPolygon.ExteriorRing.Points.Add(adaptPoint); } foreach (var ring in polygon.InteriorRings) { var adaptRing = new AgGateway.ADAPT.ApplicationDataModel.Shapes.LinearRing(); adaptRing.Points = new List <AgGateway.ADAPT.ApplicationDataModel.Shapes.Point>(); foreach (var coordinate in ring.Coordinates) { var adaptPoint = new AgGateway.ADAPT.ApplicationDataModel.Shapes.Point(); adaptPoint.X = coordinate.X; adaptPoint.Y = coordinate.Y; adaptRing.Points.Add(adaptPoint); } adaptPolygon.InteriorRings.Add(adaptRing); } adaptMultiPolygon.Polygons.Add(adaptPolygon); } adaptCropZone.BoundingRegion = adaptMultiPolygon; } // Add the CropZone object to the Catalog. export.Catalog.CropZones.Add(adaptCropZone); } } } // At this point we have added all the Grower/Farm/Field objects to the Catalog and are ready to export. // Create an output path string outputPath = applicationPath + @"\Output"; if (Directory.Exists(outputPath)) { Directory.Delete(outputPath, true); } if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } // Export to a local directory using the ADMPlugin admPlugin.Export(export, outputPath); // The ADMPlugin creates an "adm" subdirectory in the indicated local directory that contains the following items: // An additional "documents" subdirectory that contains the protobuf-encoded document files. // An AdmVersion.info file that contains version information. // A ProprietaryValues.adm file // A Catalog.adm file that contains the zipped JSON serialization of the ApplicationDataModel.Catalog object. // We've added logic here to zip that "adm" subdirectory into a single file, in case you want to email it to someone. string zipPath = applicationPath + @"\Zip"; if (Directory.Exists(zipPath)) { Directory.Delete(zipPath, true); } if (!Directory.Exists(zipPath)) { Directory.CreateDirectory(zipPath); } // Delete the file if it already exists string zipFile = zipPath + @"\tree.zip"; if (File.Exists(zipFile)) { File.Delete(zipFile); } ZipFile.CreateFromDirectory(outputPath, zipFile); // This is logic to import the same data from the "adm" subdirectory we just created so you can compare it // in the debugger if you want. var pluginFactory2 = new PluginFactory(applicationPath); var admPlugin2 = pluginFactory.GetPlugin("ADMPlugin"); admPlugin2.Initialize(); // Note that when a plugin imports, the returned object is a list of ApplicationDataModel objects. var imports = admPlugin2.Import(outputPath); }
/// <summary> /// Gets the cells in the Voronoi diagram for this triangulation. /// The cells are returned as a <see cref="IGeometryCollection" /> of <see cref="IPolygon"/>s /// </summary> /// <remarks> /// The userData of each polygon is set to be the <see cref="Coordinate" /> /// of the cell site. This allows easily associating external /// data associated with the sites to the cells. /// </remarks> /// <param name="geomFact">a geometry factory</param> /// <returns>a GeometryCollection of Polygons</returns> public IGeometryCollection GetVoronoiDiagram(IGeometryFactory geomFact) { var vorCells = GetVoronoiCellPolygons(geomFact); return(geomFact.CreateGeometryCollection(GeometryFactory.ToGeometryArray(vorCells))); }
public void TestWktReadPoint2() { string wkt = "POINT ( 3 , 4 )"; GeometryFactory factory = new GeometryFactory(); try { Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Assertion.Fail("Should fail because of the comma."); } catch(ParseException) { } }
/// <summary> /// Reads a stream and converts the shapefile record to an equilivant geometry object. /// </summary> /// <param name="file">The stream to read.</param> /// <param name="totalRecordLength">Total length of the record we are about to read</param> /// <param name="factory">The geometry factory to use when making the object.</param> /// <returns>The Geometry object that represents the shape file record.</returns> public override Geometry Read(BigEndianBinaryReader file, int totalRecordLength, GeometryFactory factory) { int totalRead = 0; int shapeTypeNum = ReadInt32(file, totalRecordLength, ref totalRead); var type = (ShapeGeometryType)EnumUtility.Parse(typeof(ShapeGeometryType), shapeTypeNum.ToString()); if (type == ShapeGeometryType.NullShape) { return(factory.CreateMultiPoint()); } if (type != ShapeType) { throw new ShapefileException(string.Format("Encountered a '{0}' instead of a '{1}'", type, ShapeType)); } // Read and for now ignore bounds. int bblength = GetBoundingBoxLength(); boundingBox = new double[bblength]; for (; boundingBoxIndex < 4; boundingBoxIndex++) { double d = ReadDouble(file, totalRecordLength, ref totalRead); boundingBox[boundingBoxIndex] = d; } // Read points int numPoints = ReadInt32(file, totalRecordLength, ref totalRead); var buffer = new CoordinateBuffer(numPoints, NoDataBorderValue, true); var points = new Point[numPoints]; var pm = factory.PrecisionModel; for (int i = 0; i < numPoints; i++) { double x = pm.MakePrecise(ReadDouble(file, totalRecordLength, ref totalRead)); double y = pm.MakePrecise(ReadDouble(file, totalRecordLength, ref totalRead)); buffer.AddCoordinate(x, y); buffer.AddMarker(); } // Trond Benum: We have now read all the points, let's read optional Z and M values GetZMValues(file, totalRecordLength, ref totalRead, buffer); var sequences = buffer.ToSequences(factory.CoordinateSequenceFactory); for (int i = 0; i < numPoints; i++) { points[i] = factory.CreatePoint(sequences[i]); } geom = factory.CreateMultiPoint(points); return(geom); }
public PointInAreaStressTester(GeometryFactory geomFactory, Geometry area) { _geomFactory = geomFactory; _area = area; }
public void TestPolygon2() { string wkt = "POLYGON( ( 1 1, 10 1, 10 10, 1 10, 1 1),(4 4, 5 4, 5 5, 4 5, 4 4 ))"; GeometryFactory factory = new GeometryFactory(); Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Polygon polygon = (Polygon)geometry; string wkt2 = new GeometryWKTWriter().Write(polygon); Assertion.AssertEquals("wkt",true,Compare.WktStrings(wkt,wkt2)); }
private Polygon Poly2() { Coordinates coords = new Coordinates(); Coordinate coord = new Coordinate(10, 13); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(11, 13); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(12, 13); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(13, 14); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(14, 15); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(15, 16); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(15, 17); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(15, 18); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(14, 19); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(13, 20); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(12, 21); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(11, 21); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(10, 21); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(9, 20); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(8, 19); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(7, 18); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(7, 17); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(7, 16); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(8, 15); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(9, 14); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(10, 13); _coords2.Add(coord); coords.Add(coord); _gf = new GeometryFactory(_precMod, _sRID); _exterior2 = _gf.CreateLinearRing(coords); coords = new Coordinates(); coord = new Coordinate(10, 16); _coords2.Add(coord); coords.Add(coord); coord = new Coordinate(11, 17); coords.Add(coord); _coords2.Add(coord); coord = new Coordinate(10, 18); coords.Add(coord); _coords2.Add(coord); coord = new Coordinate(9, 17); coords.Add(coord); _coords2.Add(coord); coord = new Coordinate(10, 16); coords.Add(coord); _coords2.Add(coord); _interior2 = _gf.CreateLinearRing(coords); LinearRing[] linearRings = new LinearRing[1]; linearRings[0] = _interior2; _gf = new GeometryFactory(); Polygon polygon = _gf.CreatePolygon(_exterior2, linearRings); return(polygon); }
public void CanReshapeVerticalSquareRingInMultipatch() { ISpatialReference lv95 = SpatialReferenceUtils.CreateSpatialReference( WellKnownHorizontalCS.LV95); //IRing ring = GeometryFactory.CreateRing( // GeometryFactory.CreatePath()) var points = new WKSPointZ[5]; points[0] = new WKSPointZ { X = 2600000, Y = 1200000, Z = 500 }; points[1] = new WKSPointZ { X = 2600100, Y = 1200000, Z = 500 }; points[2] = new WKSPointZ { X = 2600100, Y = 1200000, Z = 1000 }; points[3] = new WKSPointZ { X = 2600000, Y = 1200000, Z = 1000 }; points[4] = new WKSPointZ { X = 2600000, Y = 1200000, Z = 500 }; IRing ring = new RingClass(); ((IGeometry)ring).SpatialReference = lv95; GeometryUtils.MakeZAware(ring); GeometryUtils.SetWKSPointZs((IPointCollection4)ring, points); IMultiPatch multipatch = new MultiPatchClass(); ((IGeometry)multipatch).SpatialReference = lv95; GeometryUtils.MakeZAware(multipatch); GeometryUtils.MakeMAware(multipatch); GeometryUtils.MakePointIDAware(multipatch); GeometryFactory.AddRingToMultiPatch(ring, multipatch, esriMultiPatchRingType .esriMultiPatchOuterRing); var unReshaped = (IRing)((IGeometryCollection)multipatch).Geometry[0]; int originalPointCount = ((IPointCollection)unReshaped).PointCount; // Left reshape is slightly larger -> vertical reshape side is determined by size only IPolyline cutLine = GeometryFactory.CreateLine( GeometryFactory.CreatePoint(2600051, 1200000 - 100, 222), GeometryFactory.CreatePoint(2600051, 1200000 + 100, 222)); cutLine.SpatialReference = lv95; GeometryUtils.MakeZAware(cutLine); var reshapePath = (IPath)((IGeometryCollection)cutLine).Geometry[0]; Assert.IsTrue(((ICurve3D)unReshaped).IsClosed3D); var reshapeInfo = new ReshapeInfo(multipatch, reshapePath, null) { NonPlanar = true }; IList <ReshapeInfo> singleReshapes; ReshapeUtils.ReshapeAllGeometryParts(reshapeInfo, reshapePath, out singleReshapes); var reshapedRing = (IRing)((IGeometryCollection)multipatch).Geometry[0]; Assert.AreEqual(originalPointCount, ((IPointCollection)reshapedRing).PointCount); Assert.IsTrue(((ICurve3D)reshapedRing).IsClosed3D); Assert.AreEqual(2 * 500 + 2 * 51, ((ICurve3D)reshapedRing).Length3D); var newPoints = new WKSPointZ[5]; GeometryUtils.QueryWKSPointZs((IPointCollection4)reshapedRing, newPoints); // first, fourth and last Assert.IsTrue(GeometryUtils.IsSamePoint(points[0], newPoints[0], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(points[3], newPoints[3], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(points[4], newPoints[4], 0, 0)); // the new cut points Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600051, Y = 1200000, Z = 500 }, newPoints[1], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600051, Y = 1200000, Z = 1000 }, newPoints[2], 0, 0)); }
/// <summary> /// /// </summary> /// <param name="shell"></param> /// <param name="holes"></param> /// <param name="factory"></param> /// <param name="tolerance"></param> public CurvePolygon(LinearRing shell, List <LinearRing> holes, GeometryFactory factory, double tolerance) : base(shell, holes.ToArray(), factory) { this.tolerance = tolerance; }
/// <summary> /// This method takes a pre-populated FeatureDataTable and removes rows that do not truly intersect testGeometry /// </summary> /// <param name="featureDataTable">The FeatureDataTable instance to filter</param> /// <param name="testGeometry">the geometry to compare against</param> public void PostFilterExistingFeatureDataTable(FeatureDataTable featureDataTable, SMGeometry testGeometry) { //first we create a new GeometryFactory. var geometryFactory = new GeometryFactory(); //then we convert the testGeometry into the equivalent NTS geometry GeoAPI.Geometries.IGeometry testGeometryAsNtsGeom = GeometryConverter.ToNTSGeometry(testGeometry, geometryFactory); //now we loop backwards through the FeatureDataTable for (int i = featureDataTable.Rows.Count - 1; i > -1; i--) { //we get each row FeatureDataRow featureDataRow = featureDataTable.Rows[i] as FeatureDataRow; //and get the rows' geometry SMGeometry compareGeometry = featureDataRow.Geometry; //convert the rows' geometry into the equivalent NTS geometry GeoAPI.Geometries.IGeometry compareGeometryAsNts = GeometryConverter.ToNTSGeometry(compareGeometry, geometryFactory); //now test for intesection (note other operations such as Contains, Within, Disjoint etc can all be done the same way) bool intersects = testGeometryAsNtsGeom.Intersects(compareGeometryAsNts); //if it doesn't intersect remove the row. if (!intersects) featureDataTable.Rows.RemoveAt(i); } }
/// <summary> /// I think this is correct /// </summary> /// <param name="coords"></param> /// <param name="factory"></param> public CurvePolygon(CoordinateSequence coords, GeometryFactory factory) : base(factory.CreateLinearRing(coords), factory) { }
/// <summary> /// Writes to the given stream the equilivent shape file record given a <b>Geometry</b> object. /// </summary> /// <param name="geometry">The <b>Geometry</b> object to write.</param> /// <param name="writer">The stream writeer.</param> /// <param name="geometryFactory">The <b>GeometryFactory</b> to use.</param> public abstract void Write(Geometry geometry, BinaryWriter writer, GeometryFactory geometryFactory);
private bool CutFeature([NotNull] IFeature feature, [NotNull] IPolyline cutPolyline, ChangeAlongZSource?zSource = null) { IGeometry selectedGeometry = feature.Shape; if (GeometryUtils.Disjoint(cutPolyline, selectedGeometry)) { return(false); } if (FeatureToCutPredicate != null && !FeatureToCutPredicate(selectedGeometry, cutPolyline)) { return(false); } _msg.DebugFormat("Cutting feature {0}", GdbObjectUtils.ToString(feature)); IGeometry geometryToCut = GeometryFactory.Clone(selectedGeometry); CutPolyline usedCutLine = null; if (ProcessedCutLines != null) { usedCutLine = new CutPolyline(feature.OID); ProcessedCutLines.Add(usedCutLine); } IList <IGeometry> resultGeometries; switch (geometryToCut.GeometryType) { case esriGeometryType.esriGeometryPolygon: resultGeometries = CutGeometryUtils.TryCut( (IPolygon)geometryToCut, cutPolyline, zSource ?? DetermineZSource(feature)); break; case esriGeometryType.esriGeometryPolyline: resultGeometries = _networkFeatureCutter?.IsNetworkEdge(feature) == true ? GetNetworkSplitPoints(cutPolyline, geometryToCut) : CutGeometryUtils.TryCut((IPolyline)geometryToCut, cutPolyline); break; case esriGeometryType.esriGeometryMultiPatch: resultGeometries = CutGeometryUtils.TryCut((IMultiPatch)geometryToCut, cutPolyline, zSource ?? DetermineZSource(feature), usedCutLine, DegenerateMultipatchFootprintAction) .Values.Cast <IGeometry>() .ToList(); break; default: throw new InvalidOperationException( $"Unsupported geometry type: {geometryToCut.GeometryType}"); } if (resultGeometries != null && resultGeometries.Count > 0) { IList <IGeometry> previousResults; if (ResultGeometriesByFeature.TryGetValue(feature, out previousResults)) { foreach (IGeometry resultGeometry in resultGeometries) { previousResults.Add(resultGeometry); } } else { ResultGeometriesByFeature.Add(feature, resultGeometries); } } return(resultGeometries != null && resultGeometries.Count > 0); }
public void TestPolygon1() { string wkt = "POLYGON( ( 50 31, 54 31, 54 29, 50 29, 50 31) )"; GeometryFactory factory = new GeometryFactory(); Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Polygon polygon = (Polygon)geometry; string wkt2 = new GeometryWKTWriter().Write(polygon); Assertion.AssertEquals("wkt",true,Compare.WktStrings(wkt,wkt2)); }
protected BaseSamples(GeometryFactory factory) : this(factory, new WKTReader(factory)) { }
/// <summary> /// Generic low-level reprojection. Used by the other methods /// </summary> /// <typeparam name="TGeometry"></typeparam> /// <param name="geometry"></param> /// <param name="operation"></param> /// <param name="factory"></param> /// <returns></returns> public static TGeometry Reproject <TGeometry>(this TGeometry geometry, CoordinateTransform operation, GeometryFactory factory) where TGeometry : Geometry { if (geometry is null) { throw new ArgumentNullException(nameof(geometry)); } else if (operation is null) { throw new ArgumentNullException(nameof(operation)); } else if (factory is null) { throw new ArgumentNullException(nameof(factory)); } return(SridRegister.ReProject(geometry, factory, sq => factory.CoordinateSequenceFactory.Create(sq.ToPPoints().Select(x => operation.Apply(x)).ToCoordinates().ToArray()))); }
public AutoMapperProfiles(GeometryFactory geometryFactory) { CreateMap <IdentityUser, UsuarioDTO>(); //Comercio CreateMap <Usuario, ComercioDTO>().ReverseMap(); CreateMap <ComercioCreacionDTO, Usuario>(); CreateMap <Usuario, ComercioDetallesDTO>().ReverseMap(); // .ForMember(x => x.Categorias, options => options.MapFrom(MapperComercios.MapUsuariosCategorias)); /* .ForMember(x => x.Clientes, options => options.MapFrom(MapUsuariosClientes)) * .ForMember(x => x.Compras, options => options.MapFrom(MapUsuariosCompras)) * .ForMember(x => x.Productos, options => options.MapFrom(MapUsuariosProductos)) * .ForMember(x => x.Proveedors, options => options.MapFrom(MapUsuariosProveedors)) * .ForMember(x => x.SubCategoria, options => options.MapFrom(MapUsuariosSubCategoria)) * .ForMember(x => x.SubUsuarios, options => options.MapFrom(MapUsuariosSubUsuarios)) * .ForMember(x => x.Venta, options => options.MapFrom(MapUsuariosVenta));*/ //Tipo de comercio CreateMap <TipoComercio, TipoComercioDTO>().ReverseMap(); CreateMap <TipoComercioCreacionDTO, TipoComercio>(); //Direccion CreateMap <Direccion, DireccionDTO>() .ForMember(x => x.Latitud, x => x.MapFrom(y => y.Ubicacion.Y)) .ForMember(x => x.Longitud, x => x.MapFrom(y => y.Ubicacion.X)); CreateMap <DireccionDTO, Direccion>() .ForMember(x => x.Ubicacion, x => x.MapFrom(y => geometryFactory.CreatePoint(new Coordinate(y.Longitud, y.Latitud)))); CreateMap <DireccionCreacionDTO, Direccion>() .ForMember(x => x.Ubicacion, x => x.MapFrom(y => geometryFactory.CreatePoint(new Coordinate(y.Longitud, y.Latitud)))); //Sub Usuario CreateMap <SubUsuario, SubUsuarioDTO>().ReverseMap(); CreateMap <SubUsuarioCreacionDTO, SubUsuario>(); //Categoria CreateMap <Categorium, CategoriaDTO>().ReverseMap(); CreateMap <CategoriaCreacionDTO, Categorium>(); //SubCategoria CreateMap <SubCategorium, SubCategoriaDTO>().ReverseMap(); CreateMap <SubCategoriaCreacionDTO, SubCategorium>(); //Productos CreateMap <Producto, ProductoDTO>().ReverseMap(); CreateMap <ProductoCreacionDTO, Producto>(); //Clientes CreateMap <Cliente, ClienteDTO>().ReverseMap(); CreateMap <ClienteCreacionDTO, Cliente>(); //Ventas CreateMap <Ventum, VentaDTO>().ReverseMap(); CreateMap <VentaCreacionDTO, Ventum>(); //DetalleVentas CreateMap <DetalleVentum, DetalleVentaDTO>().ReverseMap(); CreateMap <DetalleVentaCreacionDTO, DetalleVentum>(); //DeudaClientes CreateMap <DeudaCliente, DeudaClienteDTO>().ReverseMap(); CreateMap <DeudaClienteCreacionDTO, DeudaCliente>(); //Proveedores CreateMap <Proveedor, ProveedorDTO>().ReverseMap(); CreateMap <ProveedorCreacionDTO, Proveedor>(); //Compras CreateMap <Compra, CompraDTO>().ReverseMap(); CreateMap <CompraCreacionDTO, Compra>(); //.ForMember(x => x.CompraProveedores, options => options.MapFrom(MapCompraProveedores)); //DetalleCompras CreateMap <DetalleCompra, DetalleCompraDTO>().ReverseMap(); CreateMap <DetalleCompraCreacionDTO, DetalleCompra>(); }
/// <summary> /// 加载动态树骨骼动画 /// </summary> private void LoadXFileTrees() { { string fileName = (strMediaPath + @"\x\Trees\tree.X"); if (skinMeshTree == null) { // 构造ModelPoint IGeometryFactory gf = new GeometryFactory(); IModelPoint mp = gf.CreateGeometry(gviGeometryType.gviGeometryModelPoint, gviVertexAttribute.gviVertexAttributeZ) as IModelPoint; mp.ModelName = fileName; mp.SpatialCRS = datasetCRS; // 设置位置 IMatrix matrix = new Matrix(); matrix.MakeIdentity(); v3.Set(treeX, treeY, treeZ); matrix.SetTranslate(v3); mp.FromMatrix(matrix); mp.SelfScale(0.75, 0.75, 0.75); // 创建骨骼动画 skinMeshTree = CommonUnity.RenderHelper.ObjectManager.CreateSkinnedMesh(mp, rootId); if (skinMeshTree == null) { MessageBox.Show("骨骼动画创建失败!"); return; } skinMeshTree.Duration = 4; skinMeshTree.Loop = true; skinMeshTree.Play(); skinMeshTree.MaxVisibleDistance = 1000; } } { string fileName = (strMediaPath + @"\x\Trees\tree1.X"); if (skinMeshTree1 == null) { // 构造ModelPoint IGeometryFactory gf = new GeometryFactory(); IModelPoint mp = gf.CreateGeometry(gviGeometryType.gviGeometryModelPoint, gviVertexAttribute.gviVertexAttributeZ) as IModelPoint; mp.ModelName = fileName; mp.SpatialCRS = datasetCRS; // 设置位置 IMatrix matrix = new Matrix(); matrix.MakeIdentity(); v3.Set(tree1X, tree1Y, tree1Z); matrix.SetTranslate(v3); mp.FromMatrix(matrix); mp.SelfScale(0.5, 0.5, 0.5); // 创建骨骼动画 skinMeshTree1 = CommonUnity.RenderHelper.ObjectManager.CreateSkinnedMesh(mp, rootId); if (skinMeshTree == null) { MessageBox.Show("骨骼动画创建失败!"); return; } skinMeshTree1.Duration = 3; skinMeshTree1.Loop = true; skinMeshTree1.Play(); skinMeshTree1.MaxVisibleDistance = 1000; } } { string fileName = (strMediaPath + @"\x\Trees\tree2.X"); if (skinMeshTree2 == null) { // 构造ModelPoint IGeometryFactory gf = new GeometryFactory(); IModelPoint mp = gf.CreateGeometry(gviGeometryType.gviGeometryModelPoint, gviVertexAttribute.gviVertexAttributeZ) as IModelPoint; mp.ModelName = fileName; mp.SpatialCRS = datasetCRS; // 设置位置 IMatrix matrix = new Matrix(); matrix.MakeIdentity(); v3.Set(tree2X, tree2Y, tree2Z); matrix.SetTranslate(v3); mp.FromMatrix(matrix); mp.SelfScale(0.25, 0.25, 0.25); // 创建骨骼动画 skinMeshTree2 = CommonUnity.RenderHelper.ObjectManager.CreateSkinnedMesh(mp, rootId); if (skinMeshTree2 == null) { MessageBox.Show("骨骼动画创建失败!"); return; } skinMeshTree2.Loop = true; skinMeshTree2.Play(); skinMeshTree2.MaxVisibleDistance = 1000; } } }
/// <summary> /// Initializes a new instance of the <see cref="NtsProvider"/> class /// using the given <paramref name="precisionModel"/>. /// </summary> /// <param name="precisionModel"> /// The <see cref="NetTopologySuite.Geometries.PrecisionModel"/> /// to use for define the precision of the geometry operations. /// </param> /// <seealso cref="NetTopologySuite.Geometries.PrecisionModel"/> /// <seealso cref="NetTopologySuite.Geometries.GeometryFactory"/> protected internal NtsProvider(PrecisionModel precisionModel) { _geometryFactory = new GeometryFactory(precisionModel); }
protected AbstractIOFixture(GeometryFactory factory) { RandomGeometryHelper = new RandomGeometryHelper(factory); }
public void CanReshapeVerticalTriangularRingInMultipatch() { ISpatialReference lv95 = SpatialReferenceUtils.CreateSpatialReference( WellKnownHorizontalCS.LV95); //IRing ring = GeometryFactory.CreateRing( // GeometryFactory.CreatePath()) var points = new WKSPointZ[4]; points[0] = new WKSPointZ { X = 2600000, Y = 1200000, Z = 500 }; points[1] = new WKSPointZ { X = 2600100, Y = 1200000, Z = 500 }; points[2] = new WKSPointZ { X = 2600050, Y = 1200000, Z = 1000 }; points[3] = new WKSPointZ { X = 2600000, Y = 1200000, Z = 500 }; IRing ring = new RingClass(); ((IGeometry)ring).SpatialReference = lv95; GeometryUtils.MakeZAware(ring); GeometryUtils.SetWKSPointZs((IPointCollection4)ring, points); IMultiPatch multipatch = new MultiPatchClass(); ((IGeometry)multipatch).SpatialReference = lv95; GeometryUtils.MakeZAware(multipatch); GeometryUtils.MakeMAware(multipatch); GeometryUtils.MakePointIDAware(multipatch); GeometryFactory.AddRingToMultiPatch(ring, multipatch, esriMultiPatchRingType .esriMultiPatchOuterRing); var unReshaped = (IRing)((IGeometryCollection)multipatch).Geometry[0]; int originalPointCount = ((IPointCollection)unReshaped).PointCount; IPolyline cutLine = GeometryFactory.CreateLine( GeometryFactory.CreatePoint(2600075, 1200000 - 100, 222), GeometryFactory.CreatePoint(2600075, 1200000 + 100, 222)); cutLine.SpatialReference = lv95; GeometryUtils.MakeZAware(cutLine); var reshapePath = (IPath)((IGeometryCollection)cutLine).Geometry[0]; Assert.IsTrue(((ICurve3D)unReshaped).IsClosed3D); var reshapeInfo = new ReshapeInfo(multipatch, reshapePath, null) { NonPlanar = true }; IList <ReshapeInfo> singleReshapes; ReshapeUtils.ReshapeAllGeometryParts(reshapeInfo, reshapePath, out singleReshapes); var reshapedRing = (IRing)((IGeometryCollection)multipatch).Geometry[0]; Assert.AreEqual(originalPointCount + 1, ((IPointCollection)reshapedRing).PointCount); Assert.IsTrue(((ICurve3D)reshapedRing).IsClosed3D); double expectedLength = Math.Sqrt(50 * 50 + 500 * 500) * 1.5 + 75 + 250; Assert.AreEqual(expectedLength, ((ICurve3D)reshapedRing).Length3D, 0.001); var newPoints = new WKSPointZ[5]; GeometryUtils.QueryWKSPointZs((IPointCollection4)reshapedRing, newPoints); // first, fourth and last Assert.IsTrue(GeometryUtils.IsSamePoint(points[0], newPoints[0], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(points[2], newPoints[3], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(points[3], newPoints[4], 0, 0)); // the new cut points Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600075, Y = 1200000, Z = 500 }, newPoints[1], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600075, Y = 1200000, Z = 750 }, newPoints[2], 0, 0)); // And now reshape right through the vertex at the top, this time reshape the left cutLine = GeometryFactory.CreateLine( GeometryFactory.CreatePoint(2600050, 1200000 - 100, 222), GeometryFactory.CreatePoint(2600050, 1200000 + 100, 222)); cutLine.SpatialReference = lv95; GeometryUtils.MakeZAware(cutLine); reshapePath = (IPath)((IGeometryCollection)cutLine).Geometry[0]; reshapeInfo = new ReshapeInfo(multipatch, reshapePath, null) { NonPlanar = true }; // keep the right (small part) reshapeInfo.RingReshapeSide = RingReshapeSideOfLine.Right; ReshapeUtils.ReshapeAllGeometryParts(reshapeInfo, reshapePath, out singleReshapes); reshapedRing = (IRing)((IGeometryCollection)multipatch).Geometry[0]; Assert.AreEqual(5, ((IPointCollection)reshapedRing).PointCount); Assert.IsTrue(((ICurve3D)reshapedRing).IsClosed3D); expectedLength = Math.Sqrt(50 * 50 + 500 * 500) * 0.5 + 25 + 500 + 250; Assert.AreEqual(expectedLength, ((ICurve3D)reshapedRing).Length3D, 0.001); newPoints = new WKSPointZ[5]; GeometryUtils.QueryWKSPointZs((IPointCollection4)reshapedRing, newPoints); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600050, Y = 1200000, Z = 500 }, newPoints[0], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600075, Y = 1200000, Z = 500 }, newPoints[1], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600075, Y = 1200000, Z = 750 }, newPoints[2], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600050, Y = 1200000, Z = 1000 }, newPoints[3], 0, 0)); }
public void TestWktReadPoint3() { string wkt = "POINT EMPTY"; GeometryFactory factory = new GeometryFactory(); Geometry geometry = new GeometryWKTReader(factory).Create(wkt); Point point = (Point)geometry; Assertion.AssertEquals("empty",true,point.isEmpty()); string wkt2 = ((Point)point).toText(); Assertion.AssertEquals("wkt",true,Compare.WktStrings(wkt,wkt2)); }
/// <summary> /// Reads a stream and converts the shapefile record to an equilivent <b>Geometry</b> object. /// </summary> /// <param name="reader">The stream reader.</param> /// <param name="geometryFactory">The <b>GeometryFactory</b> to use when making the object.</param> /// <returns>The <b>Geometry</b> object that represents the shape file record.</returns> public abstract Geometry Read(BigEndianBinaryReader reader, GeometryFactory geometryFactory);
public void CanReshapeVerticalRingWithMutipleReshapeLineCrossings() { ISpatialReference lv95 = SpatialReferenceUtils.CreateSpatialReference( WellKnownHorizontalCS.LV95); // Vertical triangle, oriented towards the south: var points = new WKSPointZ[4]; points[0] = new WKSPointZ { X = 2600000, Y = 1200000, Z = 500 }; points[1] = new WKSPointZ { X = 2600100, Y = 1200000, Z = 500 }; points[2] = new WKSPointZ { X = 2600050, Y = 1200000, Z = 1000 }; points[3] = new WKSPointZ { X = 2600000, Y = 1200000, Z = 500 }; IRing ring = new RingClass(); ((IGeometry)ring).SpatialReference = lv95; GeometryUtils.MakeZAware(ring); GeometryUtils.SetWKSPointZs((IPointCollection4)ring, points); IMultiPatch multipatch = new MultiPatchClass(); ((IGeometry)multipatch).SpatialReference = lv95; GeometryUtils.MakeZAware(multipatch); GeometryUtils.MakeMAware(multipatch); GeometryUtils.MakePointIDAware(multipatch); GeometryFactory.AddRingToMultiPatch(ring, multipatch, esriMultiPatchRingType .esriMultiPatchOuterRing); var unReshaped = (IRing)((IGeometryCollection)multipatch).Geometry[0]; IPolyline cutLine = GeometryFactory.CreateLine( GeometryFactory.CreatePoint(2600075, 1200000 - 100, 222), GeometryFactory.CreatePoint(2600075, 1200000 + 100, 222), GeometryFactory.CreatePoint(2600025, 1200000 + 100, 222), GeometryFactory.CreatePoint(2600025, 1200000 - 100, 222)); cutLine.SpatialReference = lv95; GeometryUtils.MakeZAware(cutLine); var reshapePath = (IPath)((IGeometryCollection)cutLine).Geometry[0]; Assert.IsTrue(((ICurve3D)unReshaped).IsClosed3D); var reshapeInfo = new ReshapeInfo(multipatch, reshapePath, null); IList <IPath> verticalPaths; Assert.IsTrue(reshapeInfo.IsVerticalRingReshape(0, out verticalPaths)); Assert.AreEqual(2, verticalPaths.Count); // Currently it is the caller's responsability to make 2 different reshapes using the desired side... // We want the middle part: // verticalPaths[0] is the one at X=2600025 var reshape1 = new ReshapeInfo(multipatch, verticalPaths[0], null); reshape1.RingReshapeSide = RingReshapeSideOfLine.Right; reshape1.NonPlanar = true; ReshapeUtils.ReshapeGeometry(reshape1, verticalPaths[0]); // verticalPaths[1] is the one at X=2600075 var reshape2 = new ReshapeInfo(multipatch, verticalPaths[1], null); reshape2.RingReshapeSide = RingReshapeSideOfLine.Left; reshape2.NonPlanar = true; ReshapeUtils.ReshapeGeometry(reshape2, verticalPaths[1]); var reshapedRing = (IRing)((IGeometryCollection)multipatch).Geometry[0]; Assert.AreEqual(6, ((IPointCollection)reshapedRing).PointCount); Assert.IsTrue(((ICurve3D)reshapedRing).IsClosed3D); double expectedLength = Math.Sqrt(50 * 50 + 500 * 500) * 1.0 + 50 + 2 * 250; Assert.AreEqual(expectedLength, ((ICurve3D)reshapedRing).Length3D, 0.001); var newPoints = new WKSPointZ[6]; GeometryUtils.QueryWKSPointZs((IPointCollection4)reshapedRing, newPoints); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600025, Y = 1200000, Z = 500 }, newPoints[0], 0, 0)); // the new cut points Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600075, Y = 1200000, Z = 500 }, newPoints[1], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600075, Y = 1200000, Z = 750 }, newPoints[2], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600050, Y = 1200000, Z = 1000 }, newPoints[3], 0, 0)); Assert.IsTrue(GeometryUtils.IsSamePoint(new WKSPointZ { X = 2600025, Y = 1200000, Z = 750 }, newPoints[4], 0, 0)); }
public void CanCalculateDifferenceInHugeLockergestein() { string filePath = TestData.GetHugeLockergesteinPolygonPath(); var poly1 = (IPolygon)ReadGeometryFromXML(filePath); Console.WriteLine(@"{0}: {1}", @"Intersection Tests with 'Huge Lockergestein'", GetVertexString(poly1)); IPolygon poly2 = GeometryFactory.Clone(poly1); var watch = new Stopwatch(); watch.Start(); IPolyline result = ReshapeUtils.GetZOnlyDifference( GeometryFactory.CreatePolyline(poly1), GeometryFactory.CreatePolyline(poly2)); watch.Stop(); Console.WriteLine( @"Calculated Z difference in huge Lockergestein (no difference) in {0} ms", watch.ElapsedMilliseconds); Assert.IsNull(result); // Change few points in Z IPoint point7 = ((IPointCollection)poly2).get_Point(7); point7.Z += 0.01; ((IPointCollection)poly2).UpdatePoint(7, point7); IPoint point8 = ((IPointCollection)poly2).get_Point(8); point8.Z += 0.01; ((IPointCollection)poly2).UpdatePoint(8, point8); watch.Reset(); watch.Start(); result = ReshapeUtils.GetZOnlyDifference( GeometryFactory.CreatePolyline(poly1), GeometryFactory.CreatePolyline(poly2), 0.0); watch.Stop(); Console.WriteLine( @"Calculated Z difference in huge Lockergestein (2 different) in {0} ms", watch.ElapsedMilliseconds); Assert.IsNotNull(result); Assert.IsFalse(result.IsEmpty); double changedLength = ((ISegmentCollection)poly2).Segment[6].Length + ((ISegmentCollection)poly2).Segment[7].Length + ((ISegmentCollection)poly2).Segment[8].Length; Assert.AreEqual(Math.Round(changedLength, 5), Math.Round(result.Length, 5)); GeometryUtils.MoveGeometry(poly2, 0, 0, 0.5); watch.Reset(); watch.Start(); result = ReshapeUtils.GetZOnlyDifference( GeometryFactory.CreatePolyline(poly1), GeometryFactory.CreatePolyline(poly2)); watch.Stop(); Console.WriteLine( @"Calculated Z difference in huge Lockergestein (all different) in {0} ms", watch.ElapsedMilliseconds); Assert.IsNotNull(result); Assert.IsFalse(result.IsEmpty); Assert.AreEqual(Math.Round(poly2.Length, 5), Math.Round(result.Length, 5)); }
public void CannotPerformVerticalReshapeOnFlatRing() { // Originally this geometry resulted in an endless loop because // IntersectionUtils.IntersectNonPlanar returned the incorrect result ISpatialReference lv95 = SpatialReferenceUtils.CreateSpatialReference( WellKnownHorizontalCS.LV95, WellKnownVerticalCS.LHN95); // The problem cannot be reproduced with standard resolution var srResolution = (ISpatialReferenceResolution)lv95; srResolution.set_XYResolution(true, 0.001); var srTolerance = (ISpatialReferenceTolerance)lv95; srTolerance.XYTolerance = 0.01; // Vertical triangle, oriented towards the south: var points = new WKSPointZ[6]; points[0] = new WKSPointZ { X = 2578309.3000000007, Y = 1183264.3999999985, Z = 619.14500000000407 }; points[1] = new WKSPointZ { X = 2578295.6829999983, Y = 1183260.568, Z = 619.14500000000407 }; points[2] = new WKSPointZ { X = 2578293.9990000017, Y = 1183266.5500000007, Z = 619.14500000000407 }; points[3] = new WKSPointZ { X = 2578295.9070000015, Y = 1183267.1559999995, Z = 619.14500000000407 }; points[4] = new WKSPointZ { X = 2578307.5989999995, Y = 1183270.4450000003, Z = 619.14500000000407 }; points[5] = new WKSPointZ { X = 2578309.3000000007, Y = 1183264.3999999985, Z = 619.14500000000407 }; IRing ring = new RingClass(); ((IGeometry)ring).SpatialReference = lv95; GeometryUtils.MakeZAware(ring); GeometryUtils.SetWKSPointZs((IPointCollection4)ring, points); IMultiPatch multipatch = new MultiPatchClass(); ((IGeometry)multipatch).SpatialReference = lv95; GeometryUtils.MakeZAware(multipatch); GeometryUtils.MakeMAware(multipatch); GeometryUtils.MakePointIDAware(multipatch); GeometryFactory.AddRingToMultiPatch(ring, multipatch, esriMultiPatchRingType .esriMultiPatchOuterRing); var unReshaped = (IRing)((IGeometryCollection)multipatch).Geometry[0]; IPolyline cutLine = GeometryFactory.CreateLine( GeometryFactory.CreatePoint(2578314.9090000018, 1183246.2400000021), GeometryFactory.CreatePoint(2578307.4299999997, 1183270.4310000017)); cutLine.SpatialReference = lv95; //GeometryUtils.MakeZAware(cutLine); var reshapePath = (IPath)((IGeometryCollection)cutLine).Geometry[0]; Assert.IsTrue(((ICurve3D)unReshaped).IsClosed3D); var reshapeInfo = new ReshapeInfo(multipatch, reshapePath, null); IList <IPath> verticalPaths; Assert.IsFalse(reshapeInfo.IsVerticalRingReshape(0, out verticalPaths)); Assert.AreEqual(0, verticalPaths.Count); Assert.IsTrue(ReshapeUtils.ReshapeGeometry(reshapeInfo, reshapePath)); var reshapedRing = (IRing)((IGeometryCollection)multipatch).Geometry[0]; Assert.AreEqual(6, ((IPointCollection)reshapedRing).PointCount); Assert.IsTrue(((ICurve3D)reshapedRing).IsClosed3D); }