Пример #1
1
        public void CreateContour(BlockTableRecord btr)
        {
            if (panelBtr.ExtentsByTile.Diagonal() < endOffset)
            {
                return;
            }

            // из всех плиток отделить торцевые плитки????
            // дерево границ плиток
            TreeTiles = new RTree<Tuple<ObjectId, Extents3d>>();
            panelBtr.Tiles.ForEach(t =>
                           {
                               try
                               {
                                   var r = new Rectangle(t.Item2.MinPoint.X, t.Item2.MinPoint.Y, t.Item2.MaxPoint.X, t.Item2.MaxPoint.Y, 0, 0);
                                   TreeTiles.Add(r, t);
                               }
                               catch { }
                           });

            // Первый угол панели - левый нижний
            var pt1 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MinPoint, EnumCorner.LeftLower);
            var pt2 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MinPoint.X, panelBtr.ExtentsByTile.MaxPoint.Y, 0), EnumCorner.LeftTop);
            var pt3 = getCoordTileNoEnd(panelBtr.ExtentsByTile.MaxPoint, EnumCorner.RightTop);
            var pt4 = getCoordTileNoEnd(new Point3d(panelBtr.ExtentsByTile.MaxPoint.X, panelBtr.ExtentsByTile.MinPoint.Y, 0), EnumCorner.RightLower);

            Extents3d extNoEnd = new Extents3d(pt1, pt2);
            extNoEnd.AddPoint(pt3);
            extNoEnd.AddPoint(pt4);
            panelBtr.ExtentsNoEnd = extNoEnd;

            Point3dCollection pts = new Point3dCollection();
            pts.Add(pt1);
            pts.Add(pt2);
            pts.Add(pt3);
            pts.Add(pt4);
            using (Polyline3d poly = new Polyline3d(Poly3dType.SimplePoly, pts, true))
            {
                poly.LayerId = panelBtr.CPS.IdLayerContour;
                btr.AppendEntity(poly);
                btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(poly, true);
            }
        }
Пример #2
0
        public void TestMultithreading()
        {
            var instance = new RTree <string>();

            Parallel.For(0, 100, i => {
                instance.Add(new Rectangle(0, 0, 0, 0, 0, 0), $"Origin-{Guid.NewGuid()}");
                instance.Add(new Rectangle(1, 1, 1, 1, 1, 1), $"Box1-{Guid.NewGuid()}");

                var rect_to_delete_name = $"Box 2-3-{Guid.NewGuid()}";
                instance.Add(new Rectangle(2, 2, 3, 3, 2, 3), rect_to_delete_name);
                instance.Add(new Rectangle(2, 2, 3, 3, 2, 3), $"Box 2-3-{Guid.NewGuid()}");

                var instancelist = instance.Contains(new Rectangle(-1, -1, 2, 2, -1, 2));
                Assert.IsTrue(instancelist.Count() > 0);

                var intersectlist = instance.Intersects(new Rectangle(3, 3, 5, 5, 3, 5));
                Assert.IsTrue(intersectlist.Count() > 1);
                Assert.IsTrue(intersectlist[0].StartsWith("Box 2-3"));

                var nearestlist = instance.Nearest(new Point(5, 5, 5), 10);

                Assert.IsTrue(nearestlist[0].StartsWith("Box 2-3"));

                instance.Delete(new Rectangle(2, 2, 3, 3, 2, 3), rect_to_delete_name);

                nearestlist = instance.Nearest(new Point(5, 5, 5), 10);

                Assert.IsTrue(nearestlist.Count() > 0);

                Assert.IsTrue(nearestlist[0].StartsWith("Box 2"));
            });
        }
Пример #3
0
        private RTree <byte[]> GetAFullTree(IStorageManager storageManager)
        {
            var options = new RTreeOptions()
            {
                Dimensions               = 2,
                EnsureTightMBRs          = false,
                TreeVariant              = RTreeVariant.RStar,
                FillFactor               = 0.9,
                IndexCapacity            = 10000,
                SplitDistributionFactor  = 0.5,
                NearMinimumOverlapFactor = 2
            };

            var rand  = new Random();
            var rtree = new RTree <byte[]>(options, storageManager);

            for (int i = 0; i < 10000; ++i)
            {
                if (rand.Next() % 2 != 0)
                {
                    var randinsert = new Circle(rand.NextDouble() * 5000, rand.NextDouble() * 5000, rand.NextDouble() * 40);
                    rtree.Add(randinsert, DataHelpers.GenerateSomeBytes(rand.Next()));
                }
                else
                {
                    var coordMin = new[] { rand.NextDouble() * 5000, rand.NextDouble() * 5000 };
                    var coordMax = new[] { coordMin[0] + (rand.NextDouble() * 80), coordMin[1] + (rand.NextDouble() * 80) };

                    var regioninsert = new Region(coordMin, coordMax);
                    rtree.Add(regioninsert, DataHelpers.GenerateSomeBytes(rand.Next()));
                }
            }
            return(rtree);
        }
Пример #4
0
        private RTree <byte[]> SetupAnRTreeWithMy4Shapes()
        {
            var options = new RTreeOptions()
            {
                Dimensions      = 2,
                EnsureTightMBRs = true,
                TreeVariant     = RTreeVariant.RStar,
                FillFactor      = 0.9
            };

            var rtree   = new RTree <byte[]>(options, new ManagedMemoryStorageManager());
            var square1 = new Region(new[] { 5.0, -2.0 }, new[] { 12.0, 0.0 });
            var square2 = new Region(new[] { -2.0, -5.0 }, new[] { 7, 0.0 });
            var square3 = new Region(new[] { -5.0, 1.0 }, new[] { 0, 4.0 });
            var circle  = new Circle(new Point(new[] { 7.0, 3.0 }), 4);

            var sq1bytes = Encoding.UTF8.GetBytes("Square1");

            rtree.Add(square1, sq1bytes);

            var sq2bytes = Encoding.UTF8.GetBytes("Square2");

            rtree.Add(square2, sq2bytes);

            var sq3bytes = Encoding.UTF8.GetBytes("Square3");

            rtree.Add(square3, sq3bytes);

            var circlebytes = Encoding.UTF8.GetBytes("Circle");

            rtree.Add(circle, circlebytes);

            return(rtree);
        }
Пример #5
0
        private void runMoveEntries(UInt16 minNodeEntries, UInt16 maxNodeEntries, int numRects, int numMoves)
        {
            RTree rtree = new RTree(minNodeEntries, maxNodeEntries);

            Rectangle[] rects = new Rectangle[numRects];

            // first add the rects
            for (int i = 0; i < numRects; i++)
            {
                rects[i] = nextRect();
                rtree.Add(rects[i]);
            }

            // now move each one in turn
            for (int move = 0; move < numMoves; move++)
            {
                for (int i = 0; i < numRects; i++)
                {
                    rtree.Remove(rects[i]);
                    rects[i].set(nextRect());
                    rtree.Add(rects[i]);
                    Assert.True(rtree.checkConsistency());
                }
            }
        }
Пример #6
0
        public void RTreeSearchTest()
        {
            // empty results

            this.tree.Search(Envelope.Undefined).ShouldBeEmpty();

            for (Int32 value = 0; value < 1000; value++)
            {
                this.tree.Search(new Envelope(value, value, value, value, 0, 0)).ShouldBeEmpty();
            }

            // all results
            this.tree.Search(Envelope.Infinity).Count().ShouldBe(this.tree.NumberOfGeometries);
            this.tree.Search(Envelope.FromEnvelopes(this.geometries.Select(geometry => geometry.Envelope))).Count().ShouldBe(this.tree.NumberOfGeometries);

            // exact results

            RTree tree = new RTree();

            Coordinate[] firstShell = new Coordinate[]
            {
                new Coordinate(0, 0, 0),
                new Coordinate(0, 10, 0),
                new Coordinate(10, 10, 0),
                new Coordinate(10, 0, 0),
                new Coordinate(0, 0, 0)
            };

            Coordinate[] secondShell = new Coordinate[]
            {
                new Coordinate(0, 0, 0),
                new Coordinate(0, 15, 0),
                new Coordinate(15, 15, 0),
                new Coordinate(15, 0, 0),
                new Coordinate(0, 0, 0)
            };

            Coordinate[] thirdShell = new Coordinate[]
            {
                new Coordinate(30, 30, 0),
                new Coordinate(30, 40, 0),
                new Coordinate(40, 40, 0),
                new Coordinate(40, 30, 0),
                new Coordinate(30, 30, 0)
            };

            tree.Add(this.factory.CreatePolygon(firstShell));
            tree.Add(this.factory.CreatePolygon(secondShell));
            tree.Add(this.factory.CreatePolygon(thirdShell));

            tree.Search(Envelope.FromCoordinates(firstShell)).Count().ShouldBe(1);
            tree.Search(Envelope.FromCoordinates(secondShell)).Count().ShouldBe(2);
            tree.Search(Envelope.FromCoordinates(thirdShell)).Count().ShouldBe(1);
            tree.Search(Envelope.FromCoordinates(secondShell.Union(thirdShell))).Count().ShouldBe(3);

            // errors

            Should.Throw <ArgumentNullException>(() => this.tree.Search(null));
        }
Пример #7
0
        public void Setup()
        {
            Instance = new RTree <string>();
            Instance.Add(new Rectangle(0, 0, 0, 0, 0, 0), "Origin");
            Instance.Add(new Rectangle(1, 1, 1, 1, 1, 1), "Box1");

            Instance.Add(new Rectangle(2, 2, 3, 3, 2, 3), "Box 2-3");
        }
Пример #8
0
        public void TestAdd()
        {
            var rtree = new RTree(new Config(), null, null);

            rtree.Add(new Rectangle(1, 2, 3, 4));
            rtree.Dispose();
        }
Пример #9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // --- input

            var geometries = new List <GeometryBase>();

            if (!DA.GetDataList(0, geometries))
            {
                return;
            }

            // --- execute

            var rtree = new RTree(3, geometries.Count);

            foreach (var geometry in geometries)
            {
                var bbox = geometry.GetBoundingBox(true);
                rtree.Add(bbox.Min, bbox.Max);
            }

            rtree.Finish();
            rtree.Geometries = geometries; // FIXME: Cleaner solution

            // --- output

            DA.SetData(0, rtree);
        }
Пример #10
0
        internal void AddSegment(Segment segment)
        {
            // добавление прямоугольника сегмента в дерево, для проверки попадания любой ячейки в этот дом
            Rectangle r = GetRectangle(segment);

            tree.Add(r, segment);
        }
Пример #11
0
        internal bool Run()
        {
            if (metroGraphData.Edges.Count() == 0)
            {
                return(false);
            }

            var splittingPoints = new Dictionary <PointPair, List <Point> >();
            var treeOfVertices  = new RTree <Point>();

            foreach (var vertex in Vertices())
            {
                var r = new Rectangle(vertex.Point);
                r.Pad(ApproximateComparer.IntersectionEpsilon);
                treeOfVertices.Add(r, vertex.Point);
            }

            var treeOfEdges = RectangleNode <PointPair> .CreateRectangleNodeOnData(Edges(), e => new Rectangle(e.First, e.Second));

            RectangleNodeUtils.CrossRectangleNodes <PointPair>(treeOfEdges, treeOfEdges, (a, b) => IntersectTwoEdges(a, b, splittingPoints, treeOfVertices));

            SortInsertedPoints(splittingPoints);
            bool pointsInserted = InsertPointsIntoPolylines(splittingPoints);

            bool progress = FixPaths();

            bool pointsRemoved = RemoveUnimportantCrossings();

            return(progress || pointsInserted || pointsRemoved);
        }
Пример #12
0
        /// <summary>
        /// Finds the item(s) closest to the <paramref name="mapLocation"/> that matches the <paramref name="itemID"/>.
        /// Returns null if no result found.
        /// </summary>
        /// <param name="itemID"></param>
        /// <param name="mapLocation"></param>
        /// <returns>Returns the map location of the closest item of a specified spot.</returns>
        public static Point2D FindNearestLocation(int itemID, Point2D mapLocation, int dimension)
        {
            List <Point2D> nearestChunks = FindNearestChunks(itemID, mapLocation, dimension);

            if (nearestChunks != null)
            {
                RTree <Point2D> allNear = new RTree <Point2D>();

                Chunk chunk;
                foreach (Point2D item in nearestChunks)
                {
                    chunk = World.Data.World.GetChunk(dimension, item.X, item.Y);
                    RTree <Point2D> items  = chunk.Items[itemID];
                    List <Point2D>  result = items.Intersects(new Rectangle(0, 0, Chunk.Width, Chunk.Height));

                    foreach (Point2D it in result)
                    {
                        allNear.Add(new Rectangle(it.X, it.Y, it.X, it.Y), it);
                    }
                }

                List <Point2D> closest = allNear.Nearest(new Point(mapLocation.X, mapLocation.Y), SearchDistance);

                if (closest != null && closest.Count > 0)
                {
                    return(closest[0]);
                }
            }

            return(null);
        }
        internal RouteSimplifier(LgPathRouter pathRouter, IEnumerable <LgNodeInfo> nodes, Set <Point> fixedPoints)
        {
            _pathRouter  = pathRouter;
            _fixedPoints = fixedPoints;
            foreach (var node in nodes)
            {
                _nodesTree.Add(node.BoundaryOnLayer.BoundingBox, node);
            }


            foreach (var e in pathRouter.VisGraph.Edges)
            {
                var ss = new SymmetricSegment(e.SourcePoint, e.TargetPoint);
                _symmetricSegmentsTree.Add(new Rectangle(ss.A, ss.B), ss);
            }
        }
        public void RTreeQuery_IncrementalRectangles()
        {
            const int RectsCount = 1000;
            const int RegionSize = 1000;
            const int RectSize   = 10;
            var       rects      = new Rectangle[RectsCount];
            var       rand       = new Random(0);

            for (int i = 0; i < RectsCount; ++i)
            {
                rects[i] = new Rectangle(new Point(rand.Next(RegionSize), rand.Next(RegionSize)));
            }

            // create rTree with just the first rectangle
            var rtree = new RTree <Rectangle, Point>();

            rtree.Add(rects[0], rects[0]);

            // add remaining rectangles 10 at a time
            for (int a = 1, b = 10; b < RectsCount; a = b, b += 10)
            {
                for (int i = a; i < b; ++i)
                {
                    rtree.Add(rects[i], rects[i]);
                }
                var allLeaves = rtree.GetAllLeaves().ToArray();
                Assert.AreEqual(allLeaves.Length, b, "did we lose leaves?");
                Assert.AreEqual(rtree.GetAllIntersecting(
                                    new Rectangle(0, 0, RegionSize + RectSize, RegionSize + RectSize)).Count(), b,
                                "are all leaves inside the max range?");
                Assert.AreEqual(rtree.GetAllIntersecting(new Rectangle(-2, -2, -1, -1)).Count(), 0,
                                "should be no leaves inside this rectangle!");
                var rect      = new Rectangle(rand.Next(RegionSize), rand.Next(RegionSize), rand.Next(RegionSize), rand.Next(RegionSize));
                var checkList = (from r in rects.Take(b)
                                 where rect.Intersects(r)
                                 select r).ToList();
                var checkSet = new HashSet <string>(checkList.Select(r => r.ToString()));
                var result   = rtree.GetAllIntersecting(rect).ToList();
                Assert.AreEqual(result.Count, checkList.Count, "result and check are different sizes");
                foreach (var r in result)
                {
                    Assert.IsTrue(rect.Intersects(r), "rect doesn't intersect query: rect={1}, query={2}", r, rect);
                    Assert.IsTrue(checkSet.Contains(r.ToString()), "check set does not contain rect");
                }
            }
        }
        public User AddUser(float longitude, float latitude)
        {
            int userId      = _userStore.AddUser(longitude, latitude);
            var boundingBox = GetBoundingBox(longitude, latitude, 0);

            _userMap.Add(boundingBox, userId);
            return(_userStore.GetUser(userId));
        }
Пример #16
0
 /// <summary>
 /// Adds a row (feature) to this table
 /// </summary>
 /// <param name="feature"></param>
 public void AddRow(FdoFeature feature)
 {
     base.Rows.Add(feature);
     if (feature.BoundingBox != null)
     {
         _tree.Add(feature.BoundingBox, feature);
     }
 }
Пример #17
0
        public void RTreeAddTest()
        {
            RTree tree = new RTree(2, 3);

            // add a single geometry

            tree.Add(_geometries[0]);
            Assert.AreEqual(1, tree.Height);
            Assert.AreEqual(1, tree.NumberOfGeometries);

            tree.Add(_geometries[1]);
            Assert.AreEqual(1, tree.Height);
            Assert.AreEqual(2, tree.NumberOfGeometries);

            tree.Add(_geometries[2]);
            Assert.AreEqual(1, tree.Height);
            Assert.AreEqual(3, tree.NumberOfGeometries);

            tree.Add(_geometries[3]);
            Assert.AreEqual(2, tree.Height);
            Assert.AreEqual(4, tree.NumberOfGeometries);

            for (Int32 geometryIndex = 4; geometryIndex < _geometries.Count; geometryIndex++)
            {
                tree.Add(_geometries[geometryIndex]);
            }

            Assert.AreEqual(_geometries.Count, tree.NumberOfGeometries);
            Assert.IsTrue(tree.Height >= Math.Floor(Math.Log(_geometries.Count, 3)));
            Assert.IsTrue(tree.Height <= _geometries.Count);


            // add a complete collection

            tree = new RTree(2, 12);
            tree.Add(_geometries);

            Assert.AreEqual(_geometries.Count, tree.NumberOfGeometries);


            // errors

            Assert.Throws <ArgumentNullException>(() => tree.Add((IGeometry)null));
            Assert.Throws <ArgumentNullException>(() => tree.Add((IEnumerable <IGeometry>)null));
        }
 public void InitSegmentTree()
 {
     for (int i = 0; i < fixedSegments.Length; i++)
     {
         Segment seg  = new Segment(fixedSegments[i].A, fixedSegments[i].B);
         var     bbox = new Rectangle(seg.p1, seg.p2);
         _segmentTree.Add(bbox, seg);
     }
 }
Пример #19
0
        void AddNodeToInserted(LgNodeInfo ni)
        {
            _insertedNodes.Add(ni);

            var rect = new Rectangle(ni.Center, ni.Center);

            _insertedNodesTree.Add(rect, ni);
            _insertedNodeRectsTree.Add(rect, rect);
        }
Пример #20
0
        public void RTreeCustomShapesCanBeRecycled()
        {
            var  filename = Path.GetTempFileName();
            long indexId  = 0;

            // create the new storage manager
            using (var storageManager = new DiskStorageManager(filename))
            {
                var options = new RTreeOptions()
                {
                    Dimensions      = 2,
                    EnsureTightMBRs = true,
                    TreeVariant     = RTreeVariant.RStar,
                    FillFactor      = 0.9
                };

                storageManager.DatafileSuffix  = "data";
                storageManager.IndexfileSuffix = "index";
                storageManager.Overwrite       = true;
                storageManager.PageSize        = 1024;

                using (var rtree = new RTree <byte[]>(options, storageManager))
                {
                    rtree.Add(new Circle(new Point(0, 0), 16), DataHelpers.GenerateSomeBytes(0x123021));

                    // verify that our circle is a circle
                    var circle = rtree.IntersectsWith(new Point(0, 0));
                    Assert.Equal(1, circle.Count());
                    Assert.Equal(0, rtree.IntersectsWith(new Point(15.99, 15.99)).Count());
                    indexId = rtree.Options.IndexIdentifier;
                }
            }

            // recycle the storage manager
            using (var storageManager = new DiskStorageManager(filename))
            {
                storageManager.DatafileSuffix  = "data";
                storageManager.IndexfileSuffix = "index";
                storageManager.Overwrite       = false;
                storageManager.PageSize        = 1024;

                var options = new RTreeOptions(indexId)
                {
                    Dimensions      = 2,
                    EnsureTightMBRs = true,
                    TreeVariant     = RTreeVariant.RStar,
                    FillFactor      = 0.9
                };

                using (var rtree = new RTree <byte[]>(options, storageManager))
                {
                    // verify that our circle is a circle
                    Assert.Equal(1, rtree.IntersectsWith(new Point(0, 0)).Count());
                    Assert.Equal(0, rtree.IntersectsWith(new Point(15.5, 15.5)).Count());
                }
            }
        }
Пример #21
0
        public void ShouldAddAnElement()
        {
            var shape = Shape2DFactory.GetShape();
            var tree  = new RTree <Int32>();

            tree.Add(shape);

            Assert.AreEqual(1, tree.Count);
        }
Пример #22
0
        internal void InitNodePortEdges(IEnumerable <LgNodeInfo> nodes, IEnumerable <SymmetricSegment> segments)
        {
            NodePortEdges.Clear();
            NodeCenters.Clear();

            RTree <SymmetricSegment> rtree      = new RTree <SymmetricSegment>();
            RTree <Point>            pointRtree = new RTree <Point>();

            foreach (var seg in segments)
            {
                rtree.Add(new Rectangle(seg.A, seg.B), seg);

                pointRtree.Add(new Rectangle(seg.A), seg.A);
                pointRtree.Add(new Rectangle(seg.B), seg.B);
            }

            foreach (var node in nodes)
            {
                var bbox = node.BoundingBox.Clone();
                bbox.ScaleAroundCenter(0.9);
                NodePortEdges[node] = new List <SymmetricSegment>();
                var segInt = rtree.GetAllIntersecting(bbox).ToList();
                foreach (var seg in segInt)
                {
                    if (RectSegIntersection.Intersect(bbox, seg.A, seg.B))
                    {
                        NodePortEdges[node].Add(seg);
                    }
                    if (!(node.BoundingBox.Contains(seg.A) && node.BoundingBox.Contains(seg.B)))
                    {
                        Debug.Assert(false, "found long edge");
                    }
                }

                bbox = node.BoundingBox.Clone();
                bbox.ScaleAroundCenter(0.01);

                Point x;
                if (pointRtree.OneIntersecting(bbox, out x))
                {
                    NodeCenters[node] = x;
                }
            }
        }
        private RTree <double, Point> CreateOnRecs(List <Rectangle> rects)
        {
            var r = new RTree <double, Point>();

            foreach (var p in rects)
            {
                r.Add(p, p.Area);
            }
            return(r);
        }
Пример #24
0
        public void RTreeAddTest()
        {
            RTree tree = new RTree(2, 3);

            // add a single geometry

            tree.Add(this.geometries[0]);
            tree.Height.ShouldBe(1);
            tree.NumberOfGeometries.ShouldBe(1);

            tree.Add(this.geometries[1]);
            tree.Height.ShouldBe(1);
            tree.NumberOfGeometries.ShouldBe(2);

            tree.Add(this.geometries[2]);
            tree.Height.ShouldBe(1);
            tree.NumberOfGeometries.ShouldBe(3);

            tree.Add(this.geometries[3]);
            tree.Height.ShouldBe(2);
            tree.NumberOfGeometries.ShouldBe(4);

            for (Int32 geometryIndex = 4; geometryIndex < this.geometries.Count; geometryIndex++)
            {
                tree.Add(this.geometries[geometryIndex]);
            }

            tree.NumberOfGeometries.ShouldBe(this.geometries.Count);
            tree.Height.ShouldBeGreaterThanOrEqualTo((Int32)Math.Floor(Math.Log(this.geometries.Count, 3)));
            tree.Height.ShouldBeLessThanOrEqualTo((Int32)Math.Ceiling(Math.Log(this.geometries.Count, 2)));

            // add a complete collection

            tree = new RTree(2, 12);
            tree.Add(this.geometries);

            tree.NumberOfGeometries.ShouldBe(this.geometries.Count);

            // errors

            Should.Throw <ArgumentNullException>(() => tree.Add((IGeometry)null));
            Should.Throw <ArgumentNullException>(() => tree.Add((IEnumerable <IGeometry>)null));
        }
        public void InitCdt()
        {
            InitSegmentTree();

            for (int i = 0; i < fixedRectangles.Length; i++)
            {
                Point p    = Round(fixedRectangles[i].Center);
                var   node = new TreeNode {
                    isFixed = true, rectId = i, rect = fixedRectangles[i], sitePoint = p, type = SiteType.RectFixed
                };
                if (nodeLabelsFixed != null)
                {
                    node.label = nodeLabelsFixed[i];
                }

                pointToTreeNode[p] = node;
                _rectNodesRtree.Add(node.rect, node);
                _fixedRectanglesTree.Add(fixedRectangles[i], node);
            }

            for (int i = 0; i < moveableRectangles.Length; i++)
            {
                Point p    = Round(moveableRectangles[i].Center);
                var   node = new TreeNode {
                    isFixed = false, rectId = i, rect = moveableRectangles[i], sitePoint = p, type = SiteType.RectMoveable
                };
                if (nodeLabelsMoveable != null)
                {
                    node.label = nodeLabelsMoveable[i];
                }

                pointToTreeNode[p] = node;
                _rectNodesRtree.Add(node.rect, node);
                _moveableRectanglesTree.Add(moveableRectangles[i], node);
            }

            var sites = pointToTreeNode.Keys.ToList();

            //AddSitesForBoxSegmentOverlaps(sites);

            cdt = new Cdt(sites, null, null);
            cdt.Run();
        }
Пример #26
0
        private static RTree <BlockSectionKP> GetRtreeBs(List <BlockSectionKP> blocks)
        {
            RTree <BlockSectionKP> rtree = new RTree <BlockSectionKP>  ();

            foreach (var item in blocks)
            {
                Rectangle r = item.Rectangle;
                rtree.Add(r, item);
            }
            return(rtree);
        }
Пример #27
0
        void AddIntervalToTree(int i)
        {
            var interval = GetInterval(i);

            if (_intervalTree == null)
            {
                _intervalTree = new RTree <int, double>();
            }

            _intervalTree.Add(interval, i);
        }
Пример #28
0
 private void AddElementWsToTree(object obj, Extents3d ext, string elemName, ref RTree <object> treeElementsInWs)
 {
     try
     {
         treeElementsInWs.Add(new Rectangle(ext), obj);
     }
     catch
     {
         Inspector.AddError($"Дублирование элементов '{elemName}'", ext, Matrix3d.Identity, System.Drawing.SystemIcons.Error);
     }
 }
Пример #29
0
        void RegisterInTree(VisibilityVertex vv)
        {
            var rect = new Rectangle(vv.Point);
            VisibilityVertex treeVv;

            if (_visGraphVerticesTree.OneIntersecting(rect, out treeVv))
            {
                Debug.Assert(treeVv == vv);
                return;
            }
            _visGraphVerticesTree.Add(rect, vv);
        }
Пример #30
0
        public void RTreeRemoveTest()
        {
            // remove geometry

            Assert.IsFalse(_tree.Remove(_factory.CreatePoint(1000, 1000, 1000)));
            Assert.IsFalse(_tree.Remove(_factory.CreatePoint(Coordinate.Undefined)));

            foreach (IPoint geometry in _geometries)
            {
                Assert.IsTrue(_tree.Remove(geometry));
            }


            // remove envelope

            _tree.Add(_geometries);

            Assert.IsTrue(_tree.Remove(Envelope.Infinity));


            // remove envelope with results

            IList <IGeometry> geometries = new List <IGeometry>();

            Assert.IsFalse(_tree.Remove(Envelope.Infinity, out geometries));
            Assert.AreEqual(0, geometries.Count);

            _tree.Add(_geometries);

            Assert.IsTrue(_tree.Remove(Envelope.Infinity, out geometries));
            Assert.AreEqual(_geometries.Count, geometries.Count);


            // errors

            Assert.Throws <ArgumentNullException>(() => _tree.Remove((Envelope)null));
            Assert.Throws <ArgumentNullException>(() => _tree.Remove((IGeometry)null));
        }
Пример #31
0
        public void RTreeQuery_IncrementalRectangles()
        {
            const int RectsCount = 1000;
            const int RegionSize = 1000;
            const int RectSize   = 10;

            for (int seed = 0; seed < 1; ++seed)
            {
                var rects = new Rectangle[RectsCount];
                var rand  = new Random(seed);
                for (int i = 0; i < RectsCount; ++i)
                {
                    rects[i] = new Rectangle(new Point(rand.Next(RegionSize), rand.Next(RegionSize)));
                }

                // create rTree with just the first rectangle
                var l = new List <KeyValuePair <Rectangle, Rectangle> >
                {
                    new KeyValuePair <Rectangle, Rectangle>(rects[0], rects[0])
                };
                var queryTree = new RTree <Rectangle>(l);

                // add remaining rectangles 10 at a time
                for (int a = 1, b = 10; b < RectsCount; a = b, b += 10)
                {
                    for (int i = a; i < b; ++i)
                    {
                        queryTree.Add(rects[i], rects[i]);
                    }
                    Assert.AreEqual(queryTree.GetAllLeaves().Count(), b, "did we lose leaves?");
                    Assert.AreEqual(queryTree.GetAllIntersecting(
                                        new Rectangle(0, 0, RegionSize + RectSize, RegionSize + RectSize)).Count(), b,
                                    "are all leaves inside the max range?");
                    Assert.AreEqual(queryTree.GetAllIntersecting(new Rectangle(-2, -2, -1, -1)).Count(), 0,
                                    "should be no leaves inside this rectangle!");
                    var query     = new Rectangle(rand.Next(RegionSize), rand.Next(RegionSize), rand.Next(RegionSize), rand.Next(RegionSize));
                    var checkList = (from r in rects.Take(b)
                                     where query.Intersects(r)
                                     select r).ToList();
                    var checkSet = new HashSet <string>(checkList.Select(r => r.ToString()));
                    var result   = queryTree.GetAllIntersecting(query).ToList();
                    Assert.AreEqual(result.Count, checkList.Count, "result and check are different sizes: seed={0}", seed);
                    foreach (var r in result)
                    {
                        Assert.IsTrue(query.Intersects(r), "rect doesn't intersect query: seed={0}, rect={1}, query={2}", seed, r, query);
                        Assert.IsTrue(checkSet.Contains(r.ToString()), "check set does not contain rect: seed={0}", seed);
                    }
                }
            }
        }
        internal List<VisibilityEdge> GetAllGraphEdgesWithEndpointInInteriorOf(IEnumerable<Rectangle> rects,
            double slack = 0.01) {
            var rtree = new RTree<Rectangle>();
            foreach (var rect in rects) {
                var shrinkedRect = rect.Clone();
                shrinkedRect.ScaleAroundCenter(1 - slack);
                rtree.Add(shrinkedRect, shrinkedRect);
            }

            var edges = (from edge in PathRouter.GetAllEdgesVisibilityEdges()
                let qrect1 = new Rectangle(edge.SourcePoint, edge.SourcePoint)
                let qrect2 = new Rectangle(edge.TargetPoint, edge.TargetPoint)
                where rtree.GetAllIntersecting(qrect1).Any() || rtree.GetAllIntersecting(qrect2).Any()
                select edge).ToList();

            return edges;
        }
Пример #33
0
        private static void BuildTree()
        {
            Stopwatch watch = new Stopwatch ();
            watch.Start ();

            sensable_tree = new RTree<Sensable> (sensables.Count, sensables.Count);

            foreach (Sensable sensable in sensables) {
                var pos = sensable.transform.position;
                var rect = new Rectangle (new float[]{ pos.x, pos.y, pos.z }, new float[]{ pos.x, pos.y, pos.z });
                sensable_tree.Add (rect, sensable);
            }

            watch.Stop ();
            if (watch.Elapsed.TotalMilliseconds > 0)
                UnityEngine.Debug.Log ("BUILD TREE: " + watch.Elapsed.TotalMilliseconds.ToString ());
        }
Пример #34
0
        private RTree<int> LoadRTree(string dataPath, int maxNode)
        {
            string rex = @"\w+ (\S+) (\S+)";
            RTree<int> rtree = null;
            StreamReader streamReader = null;
            int count = 0;

            try
            {
                rtree = new RTree<int>(maxNode, 0);
                streamReader = new StreamReader(dataPath);
                for (string line = streamReader.ReadLine();
                    line != null;
                    line = streamReader.ReadLine())
                {
                    Match match = Regex.Match(line, rex);
                    if (match.Success)
                    {
                        float lat = float.Parse(match.Groups[2].Value);
                        float lon = float.Parse(match.Groups[1].Value);
                        rtree.Add(new Rectangle(lat, lon, lat, lon, 0, 0), count);
                        count++;
                    }
                }

                return rtree;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to load RTree data: " +
                    ex.Message);
                return null;
            }
            finally
            {
                if (streamReader != null) streamReader.Close();
            }
        }
        internal bool Run() {
            if (metroGraphData.Edges.Count() == 0) return false;

            var splittingPoints = new Dictionary<PointPair, List<Point>>();
            var treeOfVertices = new RTree<Point>();
            foreach (var vertex in Vertices()) {
                var r = new Rectangle(vertex.Point);
                r.Pad(ApproximateComparer.IntersectionEpsilon);
                treeOfVertices.Add(r, vertex.Point);
            }

            var treeOfEdges = RectangleNode<PointPair>.CreateRectangleNodeOnData(Edges(), e => new Rectangle(e.First, e.Second));
            RectangleNodeUtils.CrossRectangleNodes<PointPair>(treeOfEdges, treeOfEdges, (a, b) => IntersectTwoEdges(a, b, splittingPoints, treeOfVertices));

            SortInsertedPoints(splittingPoints);
            bool pointsInserted = InsertPointsIntoPolylines(splittingPoints);

            bool progress = FixPaths();

            bool pointsRemoved = RemoveUnimportantCrossings();

            return progress || pointsInserted || pointsRemoved;
        }
Пример #36
0
        public static List<FacadeFrontBlock> GetFacadeFrontBlocks(BlockTableRecord ms, List<FloorMounting> floors)
        {
            List<FacadeFrontBlock> facadeFrontBlocks = new List<FacadeFrontBlock>();
            foreach (ObjectId idEnt in ms)
            {
                var blRef = idEnt.GetObject(OpenMode.ForRead, false, true) as BlockReference;
                if (blRef == null) { continue; }
                // Если это блок обозначения стороны фасада - по имени блока
                if (string.Equals(blRef.GetEffectiveName(), Settings.Default.BlockFacadeName, StringComparison.CurrentCultureIgnoreCase))
                {
                    FacadeFrontBlock front = new FacadeFrontBlock(blRef);
                    facadeFrontBlocks.Add(front);
                }
            }
            // Найти все блоки монтажных панелей входящих в фасад
            RTree<FloorMounting> rtreeFloors = new RTree<FloorMounting>();
            foreach (var front in floors)
            {
                try
                {
                    rtreeFloors.Add(front.RectangleRTree, front);
                }
                catch { }
            }
            foreach (var front in facadeFrontBlocks)
            {
                // найти соотв обозн стороны фасада
                var frontsIntersects = rtreeFloors.Intersects(front.RectangleRTree);

                // если нет пересечений фасадов - пропускаем блок монтажки - он не входит в
                // фасады, просто так вставлен
                if (frontsIntersects.Count == 0)
                {
                    Inspector.AddError($"Для блока обозначения стороны фасада не найдены монтажные планы.", front.IdBlRef, System.Drawing.SystemIcons.Error);
                    continue;
                }
                foreach (var item in frontsIntersects)
                {
                    front.AddPanels(item);
                }
                front.DefineMinMax();
            }
            return facadeFrontBlocks;
        }
Пример #37
0
        public void RTreeQuery_IncrementalRectangles()
        {
            const int RectsCount = 1000;
            const int RegionSize = 1000;
            const int RectSize = 10;
            for (int seed = 0; seed < 1; ++seed)
            {
                var rects = new Rectangle[RectsCount];
                var rand = new Random(seed);
                for (int i = 0; i < RectsCount; ++i)
                {
                    rects[i] = new Rectangle(new Point(rand.Next(RegionSize), rand.Next(RegionSize)));
                }

                // create rTree with just the first rectangle
                var l = new List<KeyValuePair<Rectangle, Rectangle>>
                            {
                                new KeyValuePair<Rectangle, Rectangle>(rects[0], rects[0])
                            };
                var queryTree = new RTree<Rectangle>(l);

                // add remaining rectangles 10 at a time
                for (int a = 1, b = 10; b < RectsCount; a = b, b += 10)
                {
                    for (int i = a; i < b; ++i)
                    {
                        queryTree.Add(rects[i], rects[i]);
                    }
                    Assert.AreEqual(queryTree.GetAllLeaves().Count(), b, "did we lose leaves?");
                    Assert.AreEqual(queryTree.GetAllIntersecting(
                        new Rectangle(0, 0, RegionSize + RectSize, RegionSize + RectSize)).Count(), b,
                        "are all leaves inside the max range?");
                    Assert.AreEqual(queryTree.GetAllIntersecting(new Rectangle(-2, -2, -1, -1)).Count(), 0,
                        "should be no leaves inside this rectangle!");
                    var query = new Rectangle(rand.Next(RegionSize), rand.Next(RegionSize), rand.Next(RegionSize), rand.Next(RegionSize));
                    var checkList = (from r in rects.Take(b)
                                     where query.Intersects(r)
                                     select r).ToList();
                    var checkSet = new HashSet<Rectangle>(checkList);
                    var result = queryTree.GetAllIntersecting(query).ToList();
                    Assert.AreEqual(result.Count, checkList.Count, "result and check are different sizes: seed={0}", seed);
                    foreach (var r in result)
                    {
                        Assert.IsTrue(query.Intersects(r), "rect doesn't intersect query: seed={0}, rect={1}, query={2}", seed, r, query);
                        Assert.IsTrue(checkSet.Contains(r), "check set does not contain rect: seed={0}", seed);
                    }
                }
            }
        }
Пример #38
0
        static void Main(string[] args)
        {
            RTree<int> rtree1 = new RTree<int>(4, 0);
            //rtree1.Add(new Rectangle(30, 30, 30, 30, 0, 0), 101);
            //rtree1.Add(new Rectangle(12, 12, 12, 12, 0, 0), 102);
            //rtree1.Add(new Rectangle(14, 14, 14, 14, 0, 0), 103);
            //rtree1.Add(new Rectangle(16, 16, 16, 16, 0, 0), 104);
            //rtree1.Add(new Rectangle(35, 35, 35, 35, 0, 0), 105);

            rtree1.Add(new Rectangle(2, 6, 2, 6, 0, 0), 1);
            rtree1.Add(new Rectangle(2.5f, 6, 2.5f, 6, 0, 0), 2);
            rtree1.Add(new Rectangle(3, 5, 3, 5, 0, 0), 3);
            rtree1.Add(new Rectangle(3, 6, 3, 6, 0, 0), 4);
            rtree1.Add(new Rectangle(3.5f, 6, 3.5f, 6, 0, 0), 5);
            rtree1.Add(new Rectangle(4, 6, 4, 6, 0, 0), 6);
            rtree1.Add(new Rectangle(1.5f, 5.5f, 1.5f, 5.5f, 0, 0), 7);
            rtree1.Add(new Rectangle(1.5f, 5.1f, 1.5f, 5.1f, 0, 0), 8);
            rtree1.Add(new Rectangle(3.5f, 5.5f, 3.5f, 5.5f, 0, 0), 9);
            rtree1.Add(new Rectangle(4, 5.5f, 4, 5.5f, 0, 0), 10);
            rtree1.Add(new Rectangle(4.5f, 5.5f, 4.5f, 5.5f, 0, 0), 11); //k
            Console.WriteLine("End Of Program");
        }
        internal void InitNodePortEdges(IEnumerable<LgNodeInfo> nodes, IEnumerable<SymmetricSegment> segments) {
            NodePortEdges.Clear();
            NodeCenters.Clear();

            RTree<SymmetricSegment> rtree = new RTree<SymmetricSegment>();
            RTree<Point> pointRtree = new RTree<Point>();

            foreach (var seg in segments) {
                rtree.Add(new Rectangle(seg.A, seg.B), seg);

                pointRtree.Add(new Rectangle(seg.A), seg.A);
                pointRtree.Add(new Rectangle(seg.B), seg.B);
            }

            foreach (var node in nodes) {
                var bbox = node.BoundingBox.Clone();
                bbox.ScaleAroundCenter(0.9);
                NodePortEdges[node] = new List<SymmetricSegment>();
                var segInt = rtree.GetAllIntersecting(bbox).ToList();
                foreach (var seg in segInt) {
                    if (RectSegIntersection.Intersect(bbox, seg.A, seg.B)) {
                        NodePortEdges[node].Add(seg);
                    }
                    if (!(node.BoundingBox.Contains(seg.A) && node.BoundingBox.Contains(seg.B)))
                        Debug.Assert(false, "found long edge");
                }

                bbox = node.BoundingBox.Clone();
                bbox.ScaleAroundCenter(0.01);

                Point x;
                if (pointRtree.OneIntersecting(bbox, out x))
                    NodeCenters[node] = x;
            }
        }
        Point FindExistingVertexOrCreateNew(RTree<Point> tree, Point x) {
            var p = tree.RootNode.FirstHitNode(x);
            if (p != null)
                return p.UserData;

            var rect = new Rectangle(x);
            rect.Pad(ApproximateComparer.IntersectionEpsilon);
            tree.Add(rect, x);
            return x;
        }
Пример #41
0
        static void run()
        {
            ArrayList words = readinput("c:\\data\\web2.txt");
            double ec = words.Count;
            DateTime st = DateTime.Now;
            FilterTree ft = new FilterTree(words);
            TimeSpan ts = DateTime.Now - st;
            pair xx1 = ft.join(ft, 1);
            //pair xx2 = ft.join(ft, 2);
            DateTime et = DateTime.Now;
            Console.WriteLine(ts);
            Console.WriteLine(et - st);
            long c1 = (long)xx1.second;
               // long c2 = (long)xx2.second;
            Console.WriteLine(ec);
            Console.WriteLine(c1 / ec / ec);

            RTree<Node> rt = new RTree<Node>();

            foreach (Node w in ft.root.children.Values)
            {
                rt.Add(new Rectangle(w.p), w);
            }
            RTree<Node> rt1 = new RTree<Node>();
            //ArrayList leafs1 = ft.getLeafs(1);
            foreach (Node w1 in ft.root.children.Values)
            {
                rt1.Add(new Rectangle(w1.p), w1);
            }
            List<pair> a= rt.joins(rt1, 1);
            long matches = 0;
            foreach (pair p in a)
            {
                Node p1 = (Node)p.first;
                Node p2 = (Node)p.second;
                matches+=p1.words.Count * p2.words.Count;
            }
            //Console.WriteLine(c2 / ec / ec);
        }
        public int PositionAllMoveableRectsSameSize(int startInd, RTree<Rectangle> fixedRectanglesTree,
            RTree<SymmetricSegment> fixedSegmentsTree) {
            Console.WriteLine("\nRemoving overlaps");
            int i;
            if (_moveableRectangles.Length == 0) return 0;

            InitInsertRectSize(_moveableRectangles[startInd]);

            DrawFixedRectsSegments(fixedRectanglesTree, fixedSegmentsTree);

            for (i = startInd; i < _moveableRectangles.Length; i++) {
                var rect = _moveableRectangles[i];

                bool couldInsert;

                if (IsPositionFree(rect.Center)) {
                    movedRectangles[i] = rect;
                    couldInsert = true;
                }
                else {
                    Point newPos;
                    couldInsert = FindClosestFreePos(rect.Center, out newPos);
                    movedRectangles[i] = Translate(rect, newPos - rect.Center);
                }

                if (!couldInsert) {
                    return i;
                }

                fixedRectanglesTree.Add(movedRectangles[i], movedRectangles[i]);
                DrawRectDilated(movedRectangles[i]);

                if (i%10 == 0) {
                    Console.Write(".");
                }
            }
            return _moveableRectangles.Length;
        }
Пример #43
0
        private static void start()
        {
            canvas = (CanvasElement)Document.GetElementById("canvas");
            context = (CanvasRenderingContext2D)canvas.GetContext(CanvasContextId.Render2D);

            Offset = new Vector2(0, 0);

            Vector2 draggingPos = null;
            canvas.OnMousedown = @event =>
            {
                int mouseX = ((dynamic)@event).pageX;
                int mouseY = ((dynamic)@event).pageY;
                draggingPos = new Vector2(mouseX, mouseY);
            };
            canvas.OnMouseup = @event =>
            {
                /*
                                if (draggingPos == null) return;

                                int mouseX = ((dynamic)@event).pageX;
                                int mouseY = ((dynamic)@event).pageY;

                                draggingPos = new Vector2(draggingPos.X - mouseX, draggingPos.Y - mouseY);

                                Offset = new Vector2(Offset.X + draggingPos.X, Offset.Y + draggingPos.Y);
                                draw();


                */
                draggingPos = null;
            };
            Document.OnMousemove = @event =>
            {
                if (draggingPos == null) return;

                int mouseX = ((dynamic)@event).pageX;
                int mouseY = ((dynamic)@event).pageY;

                Offset = new Vector2(Offset.X + (draggingPos.X - mouseX) * 6, Offset.Y + (draggingPos.Y - mouseY) * 6);

                draggingPos = new Vector2(mouseX, mouseY);
                Draw();
            };



            canvas.Width = Document.Body.ClientWidth - 100;
            canvas.Height = Document.Body.ClientHeight - 100;
            context.Save();
            context.Font = "50px Arial";
            context.FillText("Loading...", canvas.Width / 2, canvas.Height / 2);
            context.Restore();


            Window.OnKeydown = @event =>
            {
                if (((dynamic)@event).keyCode == 17)
                {
                    drawLines = !drawLines;
                }
                Draw();
            };


        
             


            Window.SetTimeout(() =>
            {
                Console.WriteLine("Started");
                Console.Profile();

                Stopwatch sw = new Stopwatch();
                sw.Start();
                tree = new RTree<Player>();
                players = new List<Player>();
                for (int j = 0; j < numberOfPlayers; j++)
                {
                    var player = new Player(nextId());
                    player.X = rand.Next(0, gameSize);
                    player.Y = rand.Next(0, gameSize);
                    players.Add(player);
                    tree.Add(new Rectangle(player.X, player.Y), player);
                }

                buildClusters(viewRadius);

                sw.Stop();
                Console.ProfileEnd();
                Console.WriteLine(string.Format("Time {0}", sw.ElapsedMilliseconds));
                Console.WriteLine("Done");
                Draw();
            });
        }
Пример #44
0
        public ObjectId CreateContour2(BlockTableRecord btr)
        {
            if (panelBtr.ExtentsByTile.Diagonal() < endOffset)
            {
                return ObjectId.Null;
            }

            // из всех плиток отделить торцевые плитки????
            // дерево границ плиток
            TreeTiles = new RTree<Tuple<ObjectId, Extents3d>>();
            foreach (var item in panelBtr.Tiles)
            {
                try
                {
                    var r = new Rectangle(Math.Round(item.Item2.MinPoint.X, 1), Math.Round(item.Item2.MinPoint.Y, 1),
                        Math.Round(item.Item2.MaxPoint.X, 1), Math.Round(item.Item2.MaxPoint.Y, 1), 0, 0);
                    TreeTiles.Add(r, item);
                }
                catch { }
            }

            // Отфильтровать плитки - панели от торцевых.
            using (var colPlTiles = new DisposableSet<Polyline>())
            {
                //List<Polyline> colPlTile = new List<Polyline>();
                foreach (var item in panelBtr.Tiles)
                {
                    // Проверить наличие плиток справа и слева - если есть плитка с одной из сторон то это плитка панели а не торца
                    // Проверка наличия плиток слева от этой
                    double yCenter = ((Math.Round(item.Item2.MaxPoint.Y, 1) - Math.Round(item.Item2.MinPoint.Y, 1)) * 0.5);
                    var ptCenterLeft = new Point(Math.Round(item.Item2.MinPoint.X, 1), yCenter, 0);
                    var finds = TreeTiles.Nearest(ptCenterLeft, distTileMinInPanel);
                    if (!finds.Skip(1).Any())
                    {
                        // Нет плиток слева, проверка плиток справа
                        var ptCenterRight = new Point(Math.Round(item.Item2.MaxPoint.X, 1), yCenter, 0);
                        finds = TreeTiles.Nearest(ptCenterRight, distTileMinInPanel);
                        if (!finds.Skip(1).Any())
                        {
                            // Нет плиток справа
                            // Проверка - торцевые плитки могут быть только у граней панели
                            if ((item.Item2.MinPoint.X - panelBtr.ExtentsByTile.MinPoint.X) < distTileMinInPanel ||
                                panelBtr.ExtentsByTile.MaxPoint.X - item.Item2.MaxPoint.X < distTileMinInPanel ||
                                item.Item2.MinPoint.Y - panelBtr.ExtentsByTile.MinPoint.Y < distTileMinInPanel ||
                                panelBtr.ExtentsByTile.MaxPoint.Y - item.Item2.MaxPoint.Y < distTileMinInPanel)
                            {
                                continue;
                            }
                        }
                    }
                    // Плитка панели, а не торца
                    Polyline pl = item.Item2.GetPolyline();
                    colPlTiles.Add(pl);
                }

                using (var regUnion = BrepExtensions.Union(colPlTiles, null))
                {
                    var plUnion = regUnion.GetPolylines().FirstOrDefault(f => f.Value == BrepLoopType.LoopExterior);
                    //var pl3d = colPlTiles.GetExteriorContour();
                    if (plUnion.Key != null)
                    {
                        if (panelBtr.CPS != null)
                        {
                            plUnion.Key.LayerId = panelBtr.CPS.IdLayerContour;
                        }
                        btr.AppendEntity(plUnion.Key);
                        btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(plUnion.Key, true);

                        panelBtr.ExtentsNoEnd = plUnion.Key.GeometricExtents;
                        return plUnion.Key.Id;
                    }
                }
            }
            return ObjectId.Null;
        }