private static void Insert(IEnumerable<Envelope> sourceData, ISpatialIndex<object> index)
 {
     foreach (var envelope in sourceData)
     {
         index.Insert(envelope, envelope);
     }
 }
 private void Insert(IList<Envelope> sourceData, ISpatialIndex<object> index)
 {
     foreach (var envelope in sourceData)
     {
         index.Insert(envelope, envelope);
     }
 }
        /// <summary>
        /// Creates a new <c>FindOverlapsQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="closedShape">The closed shape defining the search area.</param>
        /// <param name="spatialType">The type of objects to look for.</param>
        internal FindOverlapsQuery(ISpatialIndex index, IPosition[] closedShape, SpatialType spatialType)
        {
            m_ClosedShape = new ClosedShape(closedShape);
            m_Points = new List<PointFeature>(100);
            m_Result = new List<ISpatialObject>(100);

            // If we are looking for points or lines, locate points that overlap. Note that
            // if the user does not actually want points in the result, we still do a point
            // search, since it helps with the selection of lines.
            if ((spatialType & SpatialType.Point)!=0 || (spatialType & SpatialType.Line)!=0)
            {
                index.QueryWindow(m_ClosedShape.Extent, SpatialType.Point, OnPointFound);

                // Remember the points in the result if the caller wants them
                if ((spatialType & SpatialType.Point)!=0)
                    m_Result.AddRange(m_Points.ToArray());
            }

            // Find lines (this automatically includes lines connected to the points we just found)
            if ((spatialType & SpatialType.Line)!=0)
                index.QueryWindow(m_ClosedShape.Extent, SpatialType.Line, OnLineFound);

            // Find any overlapping text
            if ((spatialType & SpatialType.Text)!=0)
                index.QueryWindow(m_ClosedShape.Extent, SpatialType.Text, OnTextFound);

            m_Result.TrimExcess();
            m_Points = null;
        }
Esempio n. 4
0
        private static void BenchmarkSearch(ISpatialIndex index, int rounds)
        {
            var query = new KnnQuery
            {
                Coordinate = new GeoCoordinate(52.3667, 4.900),
                MaxDistance = 10000,
                MaxResults = 15
            };

            Console.Write("Searching top {0} within {1} m from [{2}] .. ", query.MaxResults, query.MaxDistance, query.Coordinate);

            var total = 0L;

            var timer = new Stopwatch();

            for (int i = rounds; i > 0; i--)
            {
                timer.Restart();
                index.KnnSearch(query);
                timer.Stop();
                total += timer.ElapsedMilliseconds;
            }

            Console.WriteLine("ok ({0} ms)", total / rounds);
        }
 private void DoTest(ISpatialIndex<object> index, double queryEnvelopeExtent, IList<Envelope> sourceData)
 {
     Console.WriteLine("---------------");
     Console.WriteLine("Envelope Extent: " + queryEnvelopeExtent);
     int extraMatchCount = 0;
     int expectedMatchCount = 0;
     int actualMatchCount = 0;
     int queryCount = 0;
     for (double x = 0; x < CELL_EXTENT * CELLS_PER_GRID_SIDE; x += queryEnvelopeExtent)
     {
         for (double y = 0; y < CELL_EXTENT * CELLS_PER_GRID_SIDE; y += queryEnvelopeExtent)
         {
             Envelope queryEnvelope = new Envelope(x, x + queryEnvelopeExtent, y, y + queryEnvelopeExtent);
             var expectedMatches = IntersectingEnvelopes(queryEnvelope, sourceData);
             var actualMatches = index.Query(queryEnvelope);
             Assert.IsTrue(expectedMatches.Count <= actualMatches.Count);
             extraMatchCount += (actualMatches.Count - expectedMatches.Count);
             expectedMatchCount += expectedMatches.Count;
             actualMatchCount += actualMatches.Count;
             Compare(expectedMatches, actualMatches);
             queryCount++;
         }
     }
     Console.WriteLine("Expected Matches: " + expectedMatchCount);
     Console.WriteLine("Actual Matches: " + actualMatchCount);
     Console.WriteLine("Extra Matches: " + extraMatchCount);
     Console.WriteLine("Query Count: " + queryCount);
     Console.WriteLine("Average Expected Matches: " + (expectedMatchCount/(double)queryCount));
     Console.WriteLine("Average Actual Matches: " + (actualMatchCount/(double)queryCount));
     Console.WriteLine("Average Extra Matches: " + (extraMatchCount/(double)queryCount));
 }
Esempio n. 6
0
 /// <summary>
 /// Creates a new <c>FindPointQuery</c> (and executes it). The result of the query
 /// can then be obtained through the <c>Result</c> property.
 /// </summary>
 /// <param name="index">The spatial index to search</param>
 /// <param name="point">The position of interest</param>
 internal FindPointQuery(ISpatialIndex index, IPointGeometry p)
 {
     m_Point = p;
     m_Result = null;
     IWindow w = new Window(p, p);
     index.QueryWindow(w, SpatialType.Point, OnQueryHit);
 }
        /// <summary>
        /// Creates a new <c>FindPointContainerQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="point">The position you want the container for</param>
        internal FindPointContainerQuery(ISpatialIndex index, IPointGeometry p)
        {
            m_Point = p;
            m_Result = null;
            IWindow w = new Window(p, p);
            index.QueryWindow(w, SpatialType.Polygon, OnQueryHit);

            // If we didn't get a result, but we skipped some candidates, check them now.
            if (m_Result==null && m_Candidates!=null)
            {
                // If NONE of the polygon's islands enclose the search position, that's
                // the result we want.

                foreach (Polygon cand in m_Candidates)
                {
                    Debug.Assert(cand.HasAnyIslands);

                    if (!cand.HasIslandEnclosing(m_Point))
                    {
                        m_Result = cand;
                        return;
                    }
                }
            }
        }
        /// <summary>
        /// Creates a new <c>FindPolygonLabelQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="polygon">The polygon that needs to be associated with a label</param>
        internal FindPolygonLabelQuery(ISpatialIndex index, Polygon polygon)
        {
            m_Polygon = polygon;
            m_Result = null;

            if (!polygon.HasAnyIslands)
                index.QueryWindow(m_Polygon.Extent, SpatialType.Text, OnTextFound);
        }
        /// <summary>
        /// Creates a new <c>FindPointsOnLineQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="line">The line of interest.</param>
        /// <param name="wantEnds">Specify true if you want points coincident with the line ends.</param>
        /// <param name="tol">The search tolerance (expected to be greater than zero).</param>
        internal FindPointsOnLineQuery(ISpatialIndex index, LineGeometry line, bool wantEnds, ILength tol)
        {
            m_Line = line;
            m_Tolerance = tol.Meters;
            m_Result = new List<PointFeature>();

            IWindow w = m_Line.Extent;
            index.QueryWindow(w, SpatialType.Point, OnQueryHit);
        }
        /// <summary>
        ///
        /// </summary>
        private void BuildQuadtree()
        {
            _quadtree = new Quadtree <ILinearRing>();

            for (int i = 0; i < _rings.Count; i++)
            {
                ILinearRing ring = _rings[i];
                Envelope    env  = ring.EnvelopeInternal;
                _quadtree.Insert(env, ring);
            }
        }
        private void BuildIndex()
        {
            _index = new STRtree <LineString>();

            for (int i = 0; i < _rings.Count; i++)
            {
                var ring = (LinearRing)_rings[i];
                var env  = ring.EnvelopeInternal;
                _index.Insert(env, ring);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Detects intersections
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        private void FindIntersections(ISpatialIndex index)
        {
            // Get the window of the candidate object and add on a 2mm buffer (on the ground). This is
            // intended to help cover the fact that some circular arcs may be inaccurate by that much.
            Window  searchwin = new Window(m_Geom.Extent);
            ILength dim       = new Length(0.002);

            searchwin.Expand(dim);

            index.QueryWindow(searchwin, SpatialType.Line, OnQueryHit);
            m_Result.TrimExcess();
        }
        /// <summary>
        /// Creates a new <c>FindIntersectionsQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// <para/>
        /// Use this constructor when intersecting something that has already been added to
        /// the spatial index. This ensures that the line is not intersected with itself.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="line">The line feature to intersect.</param>
        /// <param name="wantEndEnd">Specify true if you want end-to-end intersections in the results.</param>
        internal FindIntersectionsQuery(ISpatialIndex index, LineFeature line, bool wantEndEnd)
        {
            if (index == null)
                throw new ArgumentNullException("FindIntersectionsQuery");

            m_Feature = line;
            m_Geom = GetUnsectionedLineGeometry(line.LineGeometry);
            m_WantEndEnd = wantEndEnd;
            m_Result = new List<IntersectionResult>(100);

            FindIntersections(index);
        }
Esempio n. 14
0
 /// <summary>
 /// Handles the event that occurs when the <see cref="Items"/> property is set on this element.
 /// </summary>
 /// <param name="oldItems">The old value of <see cref="Items"/>.</param>
 /// <param name="newItems">The new value of <see cref="Items"/>.</param>
 protected virtual void OnItemsChanged(ISpatialIndex oldItems, ISpatialIndex newItems)
 {
     if (oldItems != null)
     {
         oldItems.Changed -= Items_Changed;
     }
     if (newItems != null)
     {
         newItems.Changed += Items_Changed;
     }
     Items_Changed(this, EventArgs.Empty);
 }
Esempio n. 15
0
 /// <summary>
 /// Creates a new <c>DrawQuery</c> that refers to the specified feature type(s),
 /// drawing the results of the spatial query to the specified display.
 /// </summary>
 /// <param name="index">The index to query</param>
 /// <param name="display">The display to draw to</param>
 /// <param name="style">The drawing style</param>
 /// <param name="types">The type(s) of spatial feature to draw</param>
 public DrawQuery(ISpatialIndex index, ISpatialDisplay display, IDrawStyle style, SpatialType types)
 {
     m_Display = display;
     m_Style = style;
     m_DoPaint = false;
     Timer t = new Timer(500);
     t.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
     t.Start();
     index.QueryWindow(m_Display.Extent, types, OnQueryHit);
     t.Close();
     display.PaintNow();
 }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CadastralFile"/> class.
        /// </summary>
        /// <param name="name">The name of the xml file</param>
        /// <param name="data">The data that was deserialized</param>
        internal CadastralFile(string name, GeoSurveyPacketData data)
        {
            m_Name   = Path.GetFileName(name);
            m_Data   = data;
            m_Extent = new Window(m_Data.points);
            m_Points = new Dictionary <int, IPoint>(m_Data.points.Length);

            IEditSpatialIndex index = new SpatialIndex();

            foreach (Point p in m_Data.points)
            {
                index.Add(p);
                m_Points.Add(p.pointNo, p);
            }

            foreach (Plan plan in m_Data.plans)
            {
                foreach (Parcel parcel in plan.parcels)
                {
                    // Relate the parcel to it's plan
                    parcel.Plan = plan;

                    foreach (Line line in parcel.lines)
                    {
                        Debug.Assert(line.From == null && line.To == null);

                        // Relate the line to the parcel that it is part of
                        line.Parcel = parcel;

                        line.From = m_Points[line.fromPoint];
                        line.To   = m_Points[line.toPoint];

                        if (line.centerPointSpecified)
                        {
                            line.Center = m_Points[line.centerPoint];
                        }

                        index.Add(line);
                    }

                    /*
                     * foreach (LinePoint lp in parcel.linePoints)
                     * {
                     *  // Relate to the parcel it's referenced by
                     *
                     *  // Relate the associated point
                     * }
                     */
                }
            }

            m_Index = index;
        }
Esempio n. 17
0
        public void DistanceUnitTest()
        {
            Assert.Inconclusive("TODO");

            ISpatialIndex target    = CreateISpatialIndex(); // TODO: Initialize to an appropriate value
            IGeometry     geometry1 = null;                  // TODO: Initialize to an appropriate value
            IGeometry     geometry2 = null;                  // TODO: Initialize to an appropriate value
            float         expected  = 0F;                    // TODO: Initialize to an appropriate value
            float         actual;

            actual = target.Distance(geometry1, geometry2);
            Assert.AreEqual(expected, actual);
        }
Esempio n. 18
0
        public void DistanceUnitTest1()
        {
            Assert.Inconclusive("TODO");

            ISpatialIndex target        = CreateISpatialIndex(); // TODO: Initialize to an appropriate value
            AGraphElement graphElement1 = null;                  // TODO: Initialize to an appropriate value
            AGraphElement graphElement2 = null;                  // TODO: Initialize to an appropriate value
            float         expected      = 0F;                    // TODO: Initialize to an appropriate value
            float         actual;

            actual = target.Distance(graphElement1, graphElement2);
            Assert.AreEqual(expected, actual);
        }
Esempio n. 19
0
        /// <summary>
        /// Creates a new <c>DrawQuery</c> that refers to the specified feature type(s),
        /// drawing the results of the spatial query to the specified display.
        /// </summary>
        /// <param name="index">The index to query</param>
        /// <param name="display">The display to draw to</param>
        /// <param name="style">The drawing style</param>
        /// <param name="types">The type(s) of spatial feature to draw</param>
        public DrawQuery(ISpatialIndex index, ISpatialDisplay display, IDrawStyle style, SpatialType types)
        {
            m_Display = display;
            m_Style   = style;
            m_DoPaint = false;
            Timer t = new Timer(500);

            t.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
            t.Start();
            index.QueryWindow(m_Display.Extent, types, OnQueryHit);
            t.Close();
            display.PaintNow();
        }
Esempio n. 20
0
        public IEnumerable <TItem> ElementsIn(Rectangle bounds)
        {
            if (_index == null)
            {
                _index = new SpatialQuadTreeIndex <TItem> {
                    BoundsOf  = item => new Rectangle(this.GetLocation(item), this.GetSize(item)),
                    HasBounds = item => this.HasLocation(item) && this.HasSize(item)
                };
                _index.AddRange(this.changedLocations.Keys);
            }
            var result = _index.Query(bounds);

            return(result);
        }
Esempio n. 21
0
        /// <summary>
        /// Creates a new <c>FindIntersectionsQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// <para/>
        /// Use this constructor when intersecting something that has already been added to
        /// the spatial index. This ensures that the line is not intersected with itself.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="line">The line feature to intersect.</param>
        /// <param name="wantEndEnd">Specify true if you want end-to-end intersections in the results.</param>
        internal FindIntersectionsQuery(ISpatialIndex index, LineFeature line, bool wantEndEnd)
        {
            if (index == null)
            {
                throw new ArgumentNullException("FindIntersectionsQuery");
            }

            m_Feature    = line;
            m_Geom       = GetUnsectionedLineGeometry(line.LineGeometry);
            m_WantEndEnd = wantEndEnd;
            m_Result     = new List <IntersectionResult>(100);

            FindIntersections(index);
        }
Esempio n. 22
0
        /// <summary>
        /// Handles mouse-move.
        /// </summary>
        /// <param name="p">The new position of the mouse</param>
        internal override void MouseMove(IPosition p)
        {
            if (m_LastPolygon == null || !m_LastPolygon.IsEnclosing(p))
            {
                IPointGeometry pg    = PointGeometry.Create(p);
                ISpatialIndex  index = CadastralMapModel.Current.Index;
                Polygon        pol   = new FindPointContainerQuery(index, pg).Result;

                if (pol != null || (m_LastPolygon != null && pol == null))
                {
                    Controller.ActiveDisplay.RestoreLastDraw();
                    m_LastPolygon = pol;
                }
            }
        }
Esempio n. 23
0
        public void SearchRegionUnitTest()
        {
            Assert.Inconclusive("TODO");

            ISpatialIndex target = CreateISpatialIndex();             // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> result         = null; // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> resultExpected = null; // TODO: Initialize to an appropriate value
            IMBR minimalBoundedRechtangle = null;                     // TODO: Initialize to an appropriate value
            bool expected = false;                                    // TODO: Initialize to an appropriate value
            bool actual;

            actual = target.SearchRegion(out result, minimalBoundedRechtangle);
            Assert.AreEqual(resultExpected, result);
            Assert.AreEqual(expected, actual);
        }
Esempio n. 24
0
        public void OverlapUnitTest()
        {
            Assert.Inconclusive("TODO");

            ISpatialIndex target = CreateISpatialIndex();             // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> result         = null; // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> resultExpected = null; // TODO: Initialize to an appropriate value
            AGraphElement graphElement = null;                        // TODO: Initialize to an appropriate value
            bool          expected     = false;                       // TODO: Initialize to an appropriate value
            bool          actual;

            actual = target.Overlap(out result, graphElement);
            Assert.AreEqual(resultExpected, result);
            Assert.AreEqual(expected, actual);
        }
Esempio n. 25
0
        public void ContainmentUnitTest1()
        {
            Assert.Inconclusive("TODO");

            ISpatialIndex target = CreateISpatialIndex();             // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> result         = null; // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> resultExpected = null; // TODO: Initialize to an appropriate value
            IGeometry geometry = null;                                // TODO: Initialize to an appropriate value
            bool      expected = false;                               // TODO: Initialize to an appropriate value
            bool      actual;

            actual = target.Containment(out result, geometry);
            Assert.AreEqual(resultExpected, result);
            Assert.AreEqual(expected, actual);
        }
Esempio n. 26
0
        private void addRandomEntries(ISpatialIndex <IExtents, BoundedInt32> rTree)
        {
            Random rnd = new MersenneTwister();

            for (Int32 i = 0; i < 100000; i++)
            {
                Double xMin = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();
                Double xMax = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();
                Double yMin = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();
                Double yMax = rnd.NextDouble() * (rnd.Next(0, 1) == 1 ? -1 : 1) * rnd.Next();

                IExtents bounds = _factories.GeoFactory.CreateExtents2D(xMin, yMin, xMax, yMax);
                rTree.Insert(new BoundedInt32(i, bounds));
            }
        }
        /// <summary>
        /// Adds the features retrieved from cache to the receiver.
        /// </summary>
        /// <param name="processAttributes">A value indicating whether the attributes will be processed or not</param>
        /// <param name="cacheAccessor">Cache accessor instance</param>
        /// <param name="fr">An object that receives the retrieved features</param>
        /// <param name="bounds">Rectangle that defines a query region</param>
        /// <returns>Number of retrieved features</returns>
        public static int FillFromCache(IFeatureCollectionCacheAccessor cacheAccessor, IFeatureReceiver fr, BoundingRectangle bounds, bool processAttributes)
        {
            ISpatialIndex pointsIndex    = cacheAccessor.RestoreFeaturesIndex(MapAround.Mapping.FeatureType.Point);
            ISpatialIndex polylinesIndex = cacheAccessor.RestoreFeaturesIndex(MapAround.Mapping.FeatureType.Polyline);
            ISpatialIndex polygonsIndex  = cacheAccessor.RestoreFeaturesIndex(MapAround.Mapping.FeatureType.Polygon);

            BoundingRectangle b;

            if (!bounds.IsEmpty())
            {
                b = bounds.GetBoundingRectangle();
            }
            else
            {
                b = new BoundingRectangle();
                b.Join(pointsIndex.IndexedSpace);
                b.Join(polylinesIndex.IndexedSpace);
                b.Join(polygonsIndex.IndexedSpace);
            }

            List <Feature> points = new List <Feature>();

            pointsIndex.QueryObjectsInRectangle(bounds, points);

            List <Feature> polylines = new List <Feature>();

            polylinesIndex.QueryObjectsInRectangle(bounds, polylines);

            List <Feature> polygons = new List <Feature>();

            polygonsIndex.QueryObjectsInRectangle(bounds, polygons);

            points.ForEach(point => fr.AddFeature((Feature)point.Clone()));
            polylines.ForEach(polyline => fr.AddFeature((Feature)polyline.Clone()));
            polygons.ForEach(polygon => fr.AddFeature((Feature)polygon.Clone()));

            if (processAttributes)
            {
                fr.FeatureAttributeNames.Clear();
                IList <string> attributeNames = cacheAccessor.RestoreAttributeNames();
                foreach (string s in attributeNames)
                {
                    fr.FeatureAttributeNames.Add(s);
                }
            }

            return(points.Count + polylines.Count + polygons.Count);
        }
Esempio n. 28
0
        public void GetNextNeighborsUnitTest1()
        {
            Assert.Inconclusive("TODO");

            ISpatialIndex target = CreateISpatialIndex();             // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> result         = null; // TODO: Initialize to an appropriate value
            ReadOnlyCollection <AGraphElement> resultExpected = null; // TODO: Initialize to an appropriate value
            AGraphElement graphElement         = null;                // TODO: Initialize to an appropriate value
            int           countOfNextNeighbors = 0;                   // TODO: Initialize to an appropriate value
            bool          expected             = false;               // TODO: Initialize to an appropriate value
            bool          actual;

            actual = target.GetNextNeighbors(out result, graphElement, countOfNextNeighbors);
            Assert.AreEqual(resultExpected, result);
            Assert.AreEqual(expected, actual);
        }
Esempio n. 29
0
        /// <summary>
        /// 筛选要素类中,与指定图形满足一定空间关系的要素(空间筛选时添加空间索引)
        /// (参考:http://blog.csdn.net/lanpy88/article/details/7173063)
        /// </summary>
        /// <param name="featureClass">从中筛选要素的要素类(A)</param>
        /// <param name="geometry">过滤条件图形(B)</param>
        /// <param name="spatialRefEnum">空间关系类型(举例:esriSpatialRelContains表示A包含B)</param>
        /// <param name="whereClause">查询条件</param>
        /// <returns></returns>
        public static List <IFeature> FilterFeaturesEx(this IFeatureClass featureClass, IGeometry geometry, esriSpatialRelEnum spatialRefEnum, string whereClause = "")
        {
            IGeometryBag        geometryBag        = new GeometryBagClass();
            IGeometryCollection geometryCollection = (IGeometryCollection)geometryBag;

            geometryBag.SpatialReference = ((IGeoDataset)featureClass).SpatialReference; //一定要给GeometryBag赋空间参考
            geometryCollection.AddGeometry(geometry);

            //为GeometryBag生成空间索引,以提高效率
            ISpatialIndex spatialIndex = (ISpatialIndex)geometryBag;

            spatialIndex.AllowIndexing = true;
            spatialIndex.Invalidate();

            return(FilterFeatures(featureClass, geometry, spatialRefEnum, whereClause));
        }
Esempio n. 30
0
        /// <summary>
        /// Selects stuff within the current limit line. This makes a private selection
        /// over and above any previous selection.
        /// </summary>
        void SelectLimit()
        {
            // Nothing to do if there is no limit line.
            if (m_Limit == null)
            {
                return;
            }

            // Empty out the current limit selection.
            m_LimSel.Clear();

            // Nothing to do if there's only one position.
            if (m_Limit.Count <= 1)
            {
                return;
            }

            // If we have just 2 positions, select everything that
            // intersects the line. Otherwise select inside the shape.

            try
            {
                // Close the limit line.
                m_Limit.Add(m_Limit[0]);

                // Select only lines if the limit line consists of only 2 points (otherwise select
                // whatever is currently visible on the active display)
                SpatialType types = (m_Limit.Count == 2 ? SpatialType.Line : m_Controller.VisibleFeatureTypes);

                // Make the selection.
                ISpatialIndex         index = CadastralMapModel.Current.Index;
                List <ISpatialObject> res   = new FindOverlapsQuery(index, m_Limit.ToArray(), types).Result;
                m_LimSel.AddRange(res);
            }

            catch
            {
            }

            finally
            {
                // Remove the closing point.
                int lastIndex = m_Limit.Count - 1;
                m_Limit.RemoveAt(lastIndex);
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Creates a new <c>FindIslandContainerQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="island">The island you want the container for</param>
        internal FindIslandContainerQuery(ISpatialIndex index, Island island)
        {
            m_Island = island;
            m_Result = null;

            // Get the most easterly point in the island.
            IPosition ep = m_Island.GetEastPoint();

            // Shift the east point ONE MICRON further to the east, to ensure
            // we don't pick up the interior of the island!
            PointGeometry eg = PointGeometry.Create(ep);

            m_EastPoint = new PointGeometry(eg.Easting.Microns + 1, eg.Northing.Microns);
            IWindow w = new Window(m_EastPoint, m_EastPoint);

            index.QueryWindow(w, SpatialType.Polygon, OnQueryHit);
        }
Esempio n. 32
0
        public ShapeFile(string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException();
            }

            m_MapName = fileName;
            IEditSpatialIndex index = new SpatialIndex();

            ShapefileDataReader sfdr = Shapefile.CreateDataReader(fileName, new GeometryFactory());
            ShapefileHeader     hdr  = sfdr.ShapeHeader;
            Envelope            ex   = hdr.Bounds;

            m_Extent = new Window(ex.MinX, ex.MinY, ex.MaxX, ex.MaxY);

            foreach (object o in sfdr)
            {
                // You get back an instance of GisSharpBlog.NetTopologySuite.IO.RowStructure, but
                // that's internal, so cast to the interface it implements (we'll attach this to
                // the geometry we wrap).
                //ICustomTypeDescriptor row = (ICustomTypeDescriptor)o;
                AdhocPropertyList row  = CreatePropertyList(sfdr);
                NTS.Geometry      geom = sfdr.Geometry;
                geom.UserData = row;

                List <NTS.Geometry> geoms = GetBasicGeometries(geom);
                foreach (NTS.Geometry g in geoms)
                {
                    g.UserData = row;
                    if (g is NTS.Point)
                    {
                        index.Add(new PointWrapper((NTS.Point)g));
                    }
                    else
                    {
                        index.Add(new GeometryWrapper(g));
                    }
                }
            }

            // Don't permit any further additions
            m_Index = index;
        }
Esempio n. 33
0
        /// <summary>
        /// Saves a spatial index containing features to the cache.
        /// </summary>
        /// <param name="index">Spatial index</param>
        /// <param name="featureType">Type of features in index</param>
        public void SaveFeaturesIndex(ISpatialIndex index, FeatureType featureType)
        {
            List <Feature> features = new List <Feature>();

            lock (_syncRoot)
            {
                index.QueryObjectsInRectangle(index.IndexedSpace, features);

                foreach (Feature s in features)
                {
                    if (s.FeatureType != featureType)
                    {
                        throw new ArgumentException("Illegal feature type", "index");
                    }
                }

                AddOrReplaceIndex((ISpatialIndex)index.Clone(), featureType);
            }
        }
 private int DoRadius(ISpatialIndex <ILineString> index)
 {
     {
         var c = new Coordinate2D(11.343629, 48.083797);
         var r = 50;
         index.Radius(c, r);
     }
     {
         var c = new Coordinate2D(11.344827, 48.083752);
         var r = 10;
         index.Radius(c, r);
     }
     {
         var c = new Coordinate2D(11.344827, 48.083752);
         var r = 5;
         index.Radius(c, r);
     }
     return(0);
 }
Esempio n. 35
0
        private void DoTest(ISpatialIndex <object> index, double queryEnvelopeExtent, List <Envelope> sourceData)
        {
            if (Verbose)
            {
                //System.Console.WriteLine("---------------");
                //System.Console.WriteLine("Envelope Extent: " + queryEnvelopeExtent);
            }
            int extraMatchCount    = 0;
            int expectedMatchCount = 0;
            int actualMatchCount   = 0;
            int queryCount         = 0;

            for (double x = 0d; x < CellExtent * CellsPerGridSide; x += queryEnvelopeExtent)
            {
                for (double y = 0d; y < CellExtent * CellsPerGridSide; y += queryEnvelopeExtent)
                {
                    var queryEnvelope   = new Envelope(x, x + queryEnvelopeExtent, y, y + queryEnvelopeExtent);
                    var expectedMatches = IntersectingEnvelopes(queryEnvelope, sourceData);
                    var actualMatches   = index.Query(queryEnvelope);
                    // since index returns candidates only, it may return more than the expected value
                    if (expectedMatches.Count > actualMatches.Count)
                    {
                        IsSuccess = false;
                    }
                    extraMatchCount    += (actualMatches.Count - expectedMatches.Count);
                    expectedMatchCount += expectedMatches.Count;
                    actualMatchCount   += actualMatches.Count;
                    Compare(expectedMatches, actualMatches);
                    queryCount++;
                }
            }

            if (Verbose)
            {
                //System.Console.WriteLine("Expected Matches: " + expectedMatchCount);
                //System.Console.WriteLine("Actual Matches: " + actualMatchCount);
                //System.Console.WriteLine("Extra Matches: " + extraMatchCount);
                //System.Console.WriteLine("Query Count: " + queryCount);
                //System.Console.WriteLine("Average Expected Matches: " + (expectedMatchCount/(double) queryCount));
                //System.Console.WriteLine("Average Actual Matches: " + (actualMatchCount/(double) queryCount));
                //System.Console.WriteLine("Average Extra Matches: " + (extraMatchCount/(double) queryCount));
            }
        }
        private void DoTest(ISpatialIndex<object> index, double queryEnvelopeExtent, List<Envelope> sourceData)
        {
            if (Verbose)
            {
                Console.WriteLine("---------------");
                Console.WriteLine("Envelope Extent: " + queryEnvelopeExtent);
            }
            int extraMatchCount = 0;
            int expectedMatchCount = 0;
            int actualMatchCount = 0;
            int queryCount = 0;
            for (var x = 0d; x < CellExtent*CellsPerGridSide; x += queryEnvelopeExtent)
            {
                for (var y = 0d; y < CellExtent*CellsPerGridSide; y += queryEnvelopeExtent)
                {
                    var queryEnvelope = new Envelope(x, x + queryEnvelopeExtent, y, y + queryEnvelopeExtent);
                    var expectedMatches = IntersectingEnvelopes(queryEnvelope, sourceData);
                    var actualMatches = index.Query(queryEnvelope);
                    // since index returns candidates only, it may return more than the expected value
                    if (expectedMatches.Count > actualMatches.Count)
                    {
                        IsSuccess = false;
                    }
                    extraMatchCount += (actualMatches.Count - expectedMatches.Count);
                    expectedMatchCount += expectedMatches.Count;
                    actualMatchCount += actualMatches.Count;
                    Compare(expectedMatches, actualMatches);
                    queryCount++;
                }
            }

            if (Verbose)
            {
                Console.WriteLine("Expected Matches: " + expectedMatchCount);
                Console.WriteLine("Actual Matches: " + actualMatchCount);
                Console.WriteLine("Extra Matches: " + extraMatchCount);
                Console.WriteLine("Query Count: " + queryCount);
                Console.WriteLine("Average Expected Matches: " + (expectedMatchCount/(double) queryCount));
                Console.WriteLine("Average Actual Matches: " + (actualMatchCount/(double) queryCount));
                Console.WriteLine("Average Extra Matches: " + (extraMatchCount/(double) queryCount));
            }
        }
Esempio n. 37
0
        public ShapeDataReader(string shapeFilePath, ISpatialIndex <ShapeLocationInFileInfo> index, IGeometryFactory geoFactory, bool buildIndexAsync)
        {
            m_SpatialIndex = index;
            m_GeoFactory   = geoFactory;

            ValidateParameters(shapeFilePath);

            m_ShapeReader = new ShapeReader(shapeFilePath);

            if (buildIndexAsync)
            {
                m_CancellationTokenSrc = new CancellationTokenSource();
                m_IndexCreationTask    = Task.Factory.StartNew(FillSpatialIndex, m_CancellationTokenSrc.Token);
            }
            else
            {
                FillSpatialIndex();
            }

            m_DbfReader = new DbaseReader(Path.ChangeExtension(shapeFilePath, DBF_EXT));
        }
Esempio n. 38
0
	    public ShapeDataReader(string shapeFilePath, ISpatialIndex<ShapeLocationInFileInfo> index, IGeometryFactory geoFactory, bool buildIndexAsync)
		{
			m_SpatialIndex = index;
			m_GeoFactory = geoFactory;

			ValidateParameters(shapeFilePath);

			m_ShapeReader = new ShapeReader(shapeFilePath);

			if (buildIndexAsync)
			{
                m_CancellationTokenSrc = new CancellationTokenSource();
                m_IndexCreationTask = Task.Factory.StartNew(FillSpatialIndex, m_CancellationTokenSrc.Token);
			}
			else
			{
				FillSpatialIndex();
			}

			m_DbfReader = new DbaseReader(Path.ChangeExtension(shapeFilePath, DBF_EXT));			
		}
        public ShapeDataReader(IStreamProviderRegistry streamProviderRegistry, ISpatialIndex <ShapeLocationInFileInfo> index, IGeometryFactory geoFactory, bool buildIndexAsync)
        {
            m_SpatialIndex = index;
            m_GeoFactory   = geoFactory;

            ValidateParameters();

            m_ShapeReader = new ShapeReader(streamProviderRegistry);

            if (buildIndexAsync)
            {
                m_CancellationTokenSrc = new CancellationTokenSource();
                m_IndexCreationTask    = Task.Factory.StartNew(FillSpatialIndex, m_CancellationTokenSrc.Token);
            }
            else
            {
                FillSpatialIndex();
            }

            m_DbfReader = new DbaseReader(streamProviderRegistry[StreamTypes.Data]);
        }
Esempio n. 40
0
        /// <summary>
        /// Handles a mouse down event
        /// </summary>
        /// <param name="p">The position where the click occurred</param>
        /// <returns>True if the command handled the mouse down. False if it did nothing.</returns>
        internal override bool LButtonDown(IPosition p)
        {
            // Find out what polygon we need to subdivide
            IPointGeometry pg    = PointGeometry.Create(p);
            ISpatialIndex  index = CadastralMapModel.Current.Index;
            Polygon        pol   = new FindPointContainerQuery(index, pg).Result;

            if (pol == null)
            {
                MessageBox.Show("Specified position does not fall inside any polygon.");
                return(false);
            }


            PolygonSubdivisionOperation op = null;

            try
            {
                // Form the links. Return if we didn't find any links.
                PolygonSub   sub = new PolygonSub(pol);
                PointFeature start, end;
                if (!sub.GetLink(0, out start, out end))
                {
                    MessageBox.Show("Cannot locate any points to connect.");
                    return(true);
                }

                op = new PolygonSubdivisionOperation();
                op.Execute(sub);
                FinishCommand();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace, ex.Message);
                AbortCommand();
            }

            return(true);
        }
Esempio n. 41
0
        /// <summary>
        /// Creates a new <c>FindClosestQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="p">The search position.</param>
        /// <param name="radius">The search tolerance (expected to be greater than zero).</param>
        /// <param name="types">The type of objects to look for.</param>
        internal FindClosestQuery(ISpatialIndex index, IPosition p, ILength radius, SpatialType types)
        {
            if (types==0)
                throw new ArgumentNullException("Spatial type(s) not specified");

            // If the user hasn't been specific, ensure we don't search for polygons!
            SpatialType useTypes = (types==SpatialType.All ? SpatialType.Feature : types);
            Debug.Assert((useTypes & SpatialType.Polygon)==0);

            // It's important to round off to the nearest micron. Otherwise you might not
            // get the desired results in situations where the search radius is zero.
            m_Position = PositionGeometry.Create(p);

            m_Radius = radius;
            m_Types = types;
            m_Result = null;
            m_Distance = m_Radius.Meters;

            // The query will actually involve a square window, not a circle.
            IWindow x = new Window(m_Position, radius.Meters * 2.0);
            index.QueryWindow(x, useTypes, OnQueryHit);
        }
Esempio n. 42
0
		public static ClusterSet<T> CalculateClusters<T>(
			ISpatialIndex<PointInfo<T>> index,
			double epsilon,
			int minimumPointsPerCluster)
			where T : IPointData
		{
			var points = index.Search().ToList();

			var clusters = new List<Cluster<T>>();

			foreach (var p in points)
			{
				if (p.Visited) continue;

				p.Visited = true;
				var candidates = index.Search(p.Point, epsilon);

				if (candidates.Count >= minimumPointsPerCluster)
				{
					clusters.Add(
						BuildCluster(
							index,
							p,
							candidates,
							epsilon,
							minimumPointsPerCluster));
				}
			}

			return new ClusterSet<T>
			{
				Clusters = clusters,
				UnclusteredObjects = points
					.Where(p => p.Cluster == null)
					.Select(p => p.Item)
					.ToList(),
			};
		}
Esempio n. 43
0
        /// <summary>
        /// Creates a new <c>FileCheckQuery</c> and executes it.
        /// </summary>
        /// <param name="model">The model to check</param>
        /// <param name="checks">Flag bits indicating the checks of interest</param>
        /// <param name="onCheckItem">Delegate to call whenever a further item is checked (null if no
        /// callback is required)</param>
        internal FileCheckQuery(CadastralMapModel model, CheckType checks, OnCheckItem onCheckItem)
        {
            if (model == null)
            {
                throw new ArgumentNullException();
            }

            m_OnCheckItem = onCheckItem;
            m_Options     = checks;
            m_NumCheck    = 0;
            m_Result      = new List <CheckItem>(100);

            ISpatialIndex index = model.Index;

            index.QueryWindow(null, SpatialType.Line, CheckLine);
            index.QueryWindow(null, SpatialType.Text, CheckText);
            index.QueryWindow(null, SpatialType.Polygon, CheckPolygon);

            // Do any post-processing.
            PostCheck(m_Result, true);

            m_Result.TrimExcess();
        }
Esempio n. 44
0
        /// <summary>
        /// Sees whether the orientation of the new text should be altered. This
        /// occurs if the auto-orient capability is enabled, and the specified
        /// position is close to any visible lne.
        /// </summary>
        /// <param name="posn">The position to use for making the check.</param>
        /// <returns></returns>
        LineFeature GetOrientation(IPointGeometry posn)
        {
            // The ground tolerance is 2mm at the draw scale.
            ISpatialDisplay display = ActiveDisplay;
            double          tol     = 0.002 * display.MapScale;

            // If we previously selected something, see if the search point
            // lies within tolerance. If so, there's no change.
            if (m_Orient != null)
            {
                double dist = m_Orient.Distance(posn).Meters;
                if (dist < tol)
                {
                    return(m_Orient);
                }
            }

            // Get the map to find the closest line
            CadastralMapModel map   = CadastralMapModel.Current;
            ISpatialIndex     index = map.Index;

            return(index.QueryClosest(posn, new Length(tol), SpatialType.Line) as LineFeature);
        }
Esempio n. 45
0
        public ShapeFile(string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
                throw new ArgumentNullException();

            m_MapName = fileName;
            IEditSpatialIndex index = new SpatialIndex();

            ShapefileDataReader sfdr = Shapefile.CreateDataReader(fileName, new GeometryFactory());
            ShapefileHeader hdr = sfdr.ShapeHeader;
            Envelope ex = hdr.Bounds;
            m_Extent = new Window(ex.MinX, ex.MinY, ex.MaxX, ex.MaxY);

            foreach (object o in sfdr)
            {
                // You get back an instance of GisSharpBlog.NetTopologySuite.IO.RowStructure, but
                // that's internal, so cast to the interface it implements (we'll attach this to
                // the geometry we wrap).
                //ICustomTypeDescriptor row = (ICustomTypeDescriptor)o;
                AdhocPropertyList row = CreatePropertyList(sfdr);
                NTS.Geometry geom = sfdr.Geometry;
                geom.UserData = row;

                List<NTS.Geometry> geoms = GetBasicGeometries(geom);
                foreach (NTS.Geometry g in geoms)
                {
                    g.UserData = row;
                    if (g is NTS.Point)
                        index.Add(new PointWrapper((NTS.Point)g));
                    else
                        index.Add(new GeometryWrapper(g));
                }
            }

            // Don't permit any further additions
            m_Index = index;
        }
        public ShapeDataReader(IStreamProviderRegistry streamProviderRegistry , ISpatialIndex<ShapeLocationInFileInfo> index, IGeometryFactory geoFactory, bool buildIndexAsync)
        {


            m_SpatialIndex = index;
            m_GeoFactory = geoFactory;

            ValidateParameters();


            m_ShapeReader = new ShapeReader(streamProviderRegistry);

            if (buildIndexAsync)
            {
                m_CancellationTokenSrc = new CancellationTokenSource();
                m_IndexCreationTask = Task.Factory.StartNew(FillSpatialIndex, m_CancellationTokenSrc.Token);
            }
            else
            {
                FillSpatialIndex();
            }

            m_DbfReader = new DbaseReader(streamProviderRegistry[StreamTypes.Data]);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MCIndexPointSnapper"/> class.
 /// </summary>
 /// <param name="monoChains"></param>
 /// <param name="index"></param>
 public MCIndexPointSnapper(IList monoChains, ISpatialIndex index)
 {
     this.monoChains = monoChains;
     this.index = (STRtree)index;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="McIndexPointSnapper"/> class.
 /// </summary>
 /// <param name="index"></param>
 public McIndexPointSnapper(ISpatialIndex index)
 {
     _index = (StRtree)index;
 }
        private void BuildIndex()
        {
            _index = new STRtree<ILineString>();

            for (int i = 0; i < _rings.Count; i++)
            {
                var ring = (ILinearRing)_rings[i];
                var env = ring.EnvelopeInternal;
                _index.Insert(env, ring);
            }
        }
 public ShapeDataReader(IStreamProviderRegistry streamProviderRegistry, ISpatialIndex<ShapeLocationInFileInfo> index)
     : this(streamProviderRegistry, index, new GeometryFactory())
 { }
     public ShapeDataReader(IStreamProviderRegistry streamProviderRegistry, ISpatialIndex<ShapeLocationInFileInfo> index, IGeometryFactory geoFactory)
 : this(streamProviderRegistry, index, geoFactory, true)
     { }
        /// <summary>
        /// 
        /// </summary>
        private void BuildQuadtree()
        {
            _quadtree = new Quadtree<ILinearRing>();

            for (int i = 0; i < _rings.Count; i++)
            {
                ILinearRing ring = _rings[i];
                Envelope env = ring.EnvelopeInternal;
                _quadtree.Insert(env, ring);
            }
        }
        /// <summary>
        /// Creates a new <c>FindIntersectionsQuery</c> (and executes it). The result of the query
        /// can then be obtained through the <c>Result</c> property.
        /// <para/>
        /// Use this constructor when intersecting with geometry that has been created ad-hoc.
        /// Note that if you are looking to intersect a line feature (already part of
        /// the spatial index), you should use the constructor that accepts the <c>LineFeature</c>.
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        /// <param name="geom">The geometry to intersect.</param>
        /// <param name="wantEndEnd">Specify true if you want end-to-end intersections in the results.</param>
        internal FindIntersectionsQuery(ISpatialIndex index, LineGeometry geom, bool wantEndEnd)
        {
            m_Feature = null;
            m_Geom = GetUnsectionedLineGeometry(geom);
            m_WantEndEnd = wantEndEnd;
            m_Result = new List<IntersectionResult>(100);

            FindIntersections(index);
        }
	    public ShapeDataReader(string shapeFilePath, ISpatialIndex<ShapeLocationInFileInfo> index, IGeometryFactory geoFactory, bool buildIndexAsync)
            :this(new ShapefileStreamProviderRegistry(shapeFilePath, true, true), index, geoFactory, buildIndexAsync)
		{	
		}
 /// <summary>
 /// Creates a new <c>FindPointByIdQuery</c> (and executes it). The result of the query
 /// can then be obtained through the <c>Result</c> property.
 /// </summary>
 /// <param name="index">The spatial index to search</param>
 /// <param name="key">The ID of interest.</param>
 internal FindPointByIdQuery(ISpatialIndex index, string key)
 {
     m_Key = key;
     m_Result = null;
     index.QueryWindow(null, SpatialType.Point, OnQueryHit);
 }
Esempio n. 56
0
 /// <summary>
 /// Creates a new instance of the ShapefileShapeSource with the specified
 /// shapefile as the source and supplied spatial and shape indices.
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="spatialIndex"></param>
 /// <param name="shx"></param>
 protected ShapefileShapeSource(string fileName, ISpatialIndex spatialIndex, ShapefileIndexFile shx)
 {
     Filename = fileName;
     _spatialIndex = spatialIndex;
     _shx = shx;
 }
        /// <summary>
        /// Detects intersections
        /// </summary>
        /// <param name="index">The spatial index to search</param>
        private void FindIntersections(ISpatialIndex index)
        {
            // Get the window of the candidate object and add on a 2mm buffer (on the ground). This is
            // intended to help cover the fact that some circular arcs may be inaccurate by that much.
            Window searchwin = new Window(m_Geom.Extent);
            ILength dim = new Length(0.002);
            searchwin.Expand(dim);

            index.QueryWindow(searchwin, SpatialType.Line, OnQueryHit);
            m_Result.TrimExcess();
        }
        public ShapeDataReader(string shapeFilePath, ISpatialIndex<ShapeLocationInFileInfo> index, IGeometryFactory geoFactory)
			: this(shapeFilePath, index, geoFactory, true)
		{ }
 /// <summary>
 /// Creates a new instance of the LineShapefileShapeSource with the specified polygon shapefile as the source and provided indices
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="spatialIndex"></param>
 /// <param name="shx"></param>
 public LineShapefileShapeSource(string fileName, ISpatialIndex spatialIndex, ShapefileIndexFile shx)
     : base(fileName, spatialIndex, shx)
 {
 }
		public ShapeDataReader(string shapeFilePath, ISpatialIndex<ShapeLocationInFileInfo> index)
			: this(shapeFilePath, index, new GeometryFactory())
		{ }