Ejemplo n.º 1
0
        private void AddDataSource(PointSet pointSet, Guid guid)
        {
            List<Coordinate2D> points = new List<Coordinate2D>();

            foreach (PointSetElement point in pointSet.Data)
            {
                points.Add(new Coordinate2D(point.Longitude, point.Latitude));
            }
            PolyInfo style = PolyInfo.DefaultPolyline;
            style.LineColor = Color.Red;
            style.LineWidth = 0.5;

            string layerId = Guid.NewGuid().ToString();
            string geometryId = Guid.NewGuid().ToString();
            string dataSourceId = Guid.NewGuid().ToString();



            trajectoriesLayers.Add(new TrajectoriesLayer
            {
                DataSource = new TrajectoriesDataSource(host, pointSet),
                Guid = guid,
                GeometryID = geometryId,
                LayerID = layerId,
                DataSourceID = dataSourceId,
                IsVisible = true,
                Geometry = new PolylineGeometry(layerId, geometryId, new Polyline2(Wgs84CoordinateReferenceSystem.Instance,
                   Coordinate2DCollection.CreateUnsafe(points.ToArray())), style)
            });
            AddLayerToHost(trajectoriesLayers[trajectoriesLayers.Count - 1]);


        }
Ejemplo n.º 2
0
 private void AddDataSource(PointSet data, Guid guid)
 {
     probesLayers.Add(new ProbesLayer
     {
         Guid = guid,
         IsVisible = true,
         DataSource = new ProbesDataSource(guid, data, host),
         LayerID = Guid.NewGuid().ToString(),
         LayerName = Guid.NewGuid().ToString()
     });
     AddLayerToHost(probesLayers[probesLayers.Count - 1]);
 }
Ejemplo n.º 3
0
        private int[] mRadiusToAdd; // must be dividable by meshScale!

        #endregion Fields

        #region Constructors

        private PathFinder()
        {
            mObstructions = new List<Obstruction>();
            mBlocked = new PointSet<int>[3];
            for (int i = 0; i < 3; i++)
                mBlocked[i] = new PointSet<int>();
            GlobalValues global = GlobalValues.GetInstance();
            int meshScale = global.MeshScale;
            mRadiusToAdd= new[]{0,
              meshScale * (int)Math.Round(global.SpaceshipCollisionRadius / (float)meshScale),
              meshScale * (int)Math.Round(global.DeathStarCollisionRadius / (float)meshScale)};
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Set of points in 3D space.
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="xAxis"></param>
        /// <param name="yAxis"></param>
        /// <param name="scale">Scaling the field extent.</param>
        /// <param name="field"></param>
        public PointCloud(Plane plane, PointSet<Point> points)
        {
            this._vertexSizeBytes = 32;
            this._numVertices = points.Points.Length;
            if (_numVertices == 0)
                return;
            this._topology = PrimitiveTopology.PointList;

            // Setting up the vertex buffer.
            GenerateGeometry(plane, points);

            Debug.Assert(_cloudEffect != null);
            this._technique = _cloudEffect.GetTechniqueByName("Render");
            this._vertexLayout = new InputLayout(_device, _technique.GetPassByIndex(0).Description.Signature, new[] {
                new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0),
                new InputElement("COLOR", 0, Format.R32G32B32_Float, 16, 0),
                new InputElement("RADIUS", 0, Format.R32_Float, 28, 0)
            });
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Prints the specified part of a point set in 2D view for debugging purpose.
        /// </summary>
        public static void PrintPointSet(PointSet<int> set, int offsetX, int offsetY, int width, int height)
        {
            for (int y = offsetY; y < offsetY + height; y++)
            {
                StringBuilder builder = new StringBuilder();
                for (int x = offsetX; x < offsetX + width; x++)
                {
                    if (set.Contains(x, y))
                    {
                        builder.Append("#");
                    } else
                    {
                        builder.Append(" ");
                    }

                }
                builder.Append("|");
                Debug.WriteLine(builder.ToString());
            }
        }
Ejemplo n.º 6
0
        public PathlineLengthMapper(VectorFieldUnsteady velocity, Plane plane)
            : base(plane, velocity.Size.ToInt2())
        {
            Velocity = velocity;

            Mapping = ShowPaths;
            Plane = plane;

            int time = velocity.Size.T;
            _intersectTimeSlices = new PointSet<EndPoint>[time];
            _pathlineSegments = new LineSet[time - 1];
            _intersectTimeSlices[0] = FieldAnalysis.ValidDataPoints<EndPoint>(velocity.GetTimeSlice(0));//FieldAnalysis.SomePoints2D<EndPoint>(velocity, 100);//
            _points = new PointCloud[velocity.Size.T];
            _points[0] = new PointCloud(Plane, _intersectTimeSlices[0].ToBasicSet());
            _fieldPositionOfValidCell = new int[_intersectTimeSlices[0].Length];
            for(int i = 0; i < _fieldPositionOfValidCell.Length; ++i)
            {
                Vector3 pos = _intersectTimeSlices[0].Points[i].Position;
                _fieldPositionOfValidCell[i] = (int)(pos.X + 0.5) + (int)(pos.Y + 0.5) * Velocity.Size[0];
            }
        }
        public TrajectoriesDataSource(Host host, PointSet data)
            : base(Guid.NewGuid())
        {
            this.pointSet = data;
            this.host = host;

            if (pointSet.Metadata.ContainsKey("ProbePicture"))
                probesHelper = new ProbesHelper(pointSet.Metadata["ProbePicture"], true);
            else
                probesHelper = new ProbesHelper("ProbeSample.png", false);

            // set up the Ontology, a description of the kind of data we contain.
            // See DataSource sample for more details.
            OntologySpecification o = this.Ontology.Edit();
            o.PrimitiveTypes.Create("RasterPatch", "GeoEntity", typeof(RasterPatch2));

            this.UpdateOntology(o);

            EntitySpecification entitySpec = new EntitySpecification(this.Ontology.EntityTypes["GeoEntity"]);
            entity = this.EntityAuthorityReference.EntityAuthority.CreateEntity(true, entitySpec);

        }
Ejemplo n.º 8
0
 public GridInterpolation(PointSet pointSet)
 {
     this.mPointSet = pointSet;
 }
Ejemplo n.º 9
0
        private void InitDockLayout()
        {
            _mapForm      = new ControlMapForm();
            _mapForm.Text = "GIS地图";
            _mapForm.Show(dockPanel1, DockState.Document);
            _mapForm.CloseButton = false;
            _mapForm.UiInitAndInvoke();
            _mapForm.Activate();



            MouseMoveOperator mouseMoveOperate;
            MouseDownOperator mouseDownOperate;

            sfHandle = new ShapeFileHandle(_mapForm.Map);

            #region 加载gis地图
            string[] str = { @"D:\光纤传感监测系统\Monitor\Monitor\data\底图.shp", @"D:\光纤传感监测系统\Monitor\Monitor\data\省界WGS 84.shp", @"D:\光纤传感监测系统\Monitor\Monitor\data\海缆WGS 84.tif" };
            mapLayer        = new MapLayer();
            MainLayerHandle = mapLayer.AddLayer(_mapForm.Map, str, "底图");

            _mapForm.MainLayerHandle = MainLayerHandle;
            _mapForm.SetMainLayerHandle();
            #endregion


            //	_mapForm.Map.ZoomToMaxExtents();
            _mapForm.Map.ZoomToLayer(MainLayerHandle);



            #region  在地图上划线
            ClassLine line      = new ClassLine();
            ClassLine line_1    = new ClassLine();
            GisPoint  gisPoint  = new GisPoint();
            LineSet   lineSet   = new LineSet(tkMapColor.Yellow, 6.0f, tkDashStyle.dsSolid);
            LineSet   lineSet_1 = new LineSet(tkMapColor.Red, 5.0f, tkDashStyle.dsCustom);
            gisPoint.connectToDB("Data Source=" + new DirectoryInfo("../../../../").FullName + "Monitor\\Monitor\\data\\data.db");
            gisPoint.readData();
            gisPoint.InitLineData(line);
            line_1.startX = gisPoint.m_PointList[15].X;
            line_1.startY = gisPoint.m_PointList[15].Y;
            line_1.endX   = gisPoint.m_PointList[20].X;
            line_1.endY   = gisPoint.m_PointList[20].Y;

            drawLine = new classDrawLine(_mapForm.Map);
            drawLine.WriteLine(line, lineSet);
            drawLine.WriteLine(line_1, lineSet_1);
            #endregion

            #region   在gis地图中添加ais数据
            //1、获取数据库中数据
            SqliteData sqlite = new SqliteData("Data Source=" + new DirectoryInfo("../../../../").FullName +
                                               "Monitor\\Monitor\\data\\data.db");
            DataTable gisData = sqlite.readData("Point");

            //2、实例化AISData类
            ais           = new AISData(_mapForm.Map, gisData);
            drawPoint_Ais = new classDrawPoint(MapForm.Map);

            //3、在地图上加载ais数据
            pointSet = new PointSet("AisReal", tkDefaultPointSymbol.dpsTriangleUp, tkMapColor.Red, 16);
            drawPoint_Ais.CreatPoint(ais.point, pointSet);
            drawPoint_Ais.EditAttribute();
            sfHandle.AddMouseMoveShapeFile("Ais", drawPoint_Ais.LayerHandle);
            #endregion


            #region
            drawPoint = new classDrawPoint(_mapForm.Map);
            var pnt = new ClassPoint();
            pnt.x   = 121.907567728461;
            pnt.y   = 30.8729913928844;
            pnt.str = "图片详情";
            string path = new DirectoryInfo("../../../../").FullName + "Monitor\\Monitor\\data\\ship3.png";
            drawPoint.AddPicture(pnt, path);
            drawPoint.EditAttribute();
            sfHandle.AddMouseDownShapeFile("pic", drawPoint.LayerHandle);
            #endregion


            _mapForm.Sf_MouseMove = sfHandle.Sf_MouseMove;
            _mapForm.Sf_MouseDown = sfHandle.Sf_MouseDown;


            mouseMoveOperate = new MouseMoveOperator(Operation.AddLabel);
            mouseDownOperate = new MouseDownOperator(Operation.AddLabel);

            //传入委托
            MapForm.MouseMoveOperate = mouseMoveOperate;
            MapForm.mouseDownOperate = mouseDownOperate;

            //var point = new ClassPoint();
            //point.x = 121.907567728461;
            //point.y = 30.8739913928844;
            //addText = new classAddText(_mapForm.Map, MainLayerHandle);
            //addText.AddText(point.x, point.y);
        }
 public void OnLeftMouseDown()
 {
     Ray ray = camera.GetPickingRay(GraphicsDevice.BackBuffer.Width, GraphicsDevice.BackBuffer.Height, host.WindowsInputElement);
     pointSetWithSelection = null;
     foreach (PointSet pointSet in pointSets)
     {
         if (pointSet.SelectSphere(ray, terrainScale, terrain.Translation))
             pointSetWithSelection = pointSet;
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Helper method for GetNearestFreeNodes().
        /// </summary>
        private void MeshNodeHunt(List<Polygon> sector, Vector2 blockedPoint, ref double minDistance, SortedList<double, MeshNode> nodes, PointSet<float> nodesExist)
        {
            // We accept nodes that have a distance <= minDistance+1 to the blockedPoint
            foreach (Polygon polygon in sector)
            {
                foreach (MeshNode node in polygon.GetNodes())
                {
                    double distance = HelperMethods.EuklidDistance(node.mVector, blockedPoint);
            // ReSharper disable CompareOfFloatsByEqualityOperator
                    // I make minDistance have the largest double value by simply assigning it. Simple
                    // assignment won't introduce rounding errors -> I may use exact equality test here.
                    if (minDistance == double.MaxValue || distance <= minDistance + 1)
            // ReSharper restore CompareOfFloatsByEqualityOperator
                    {
                        // Decide if we have to add or to update a node:
                        if (nodesExist.Contains(node.mVector.X, node.mVector.Y))
                        {
                            int nodeIndex = nodes.IndexOfValue(node);
                            if (distance < nodes.Keys[nodeIndex])
                                nodes.Keys[nodeIndex] = distance;
                        }
                        else
                        {
                            nodes.Add(distance, node);
                            nodesExist.Add(node.mVector.X, node.mVector.Y);
                        }

                    }

                    // Look if we can even update minDistance and throw out nodes too far away
                    if (distance < minDistance)
                    {
                        minDistance = distance;
                        while (nodes.Keys[nodes.Count-1] > minDistance + 1)
                        {
                            MeshNode nodeToDelete = nodes.Values[nodes.Count - 1];
                            nodesExist.Remove(nodeToDelete.mVector.X, nodeToDelete.mVector.Y);
                            nodes.RemoveAt(nodes.Count - 1);
                        }
                    }

                }
            }
        }
        public static void Full_Sys_Test_Alternative_Extreme()
        {
            int dim       = 32;
            int testcases = 20;
            int dws       = 80;
            int K         = 20;
            int maxSearch = 500;
            int ntrees    = 3;

            int    nrand  = 100;
            int    ddeter = 2;
            double ratio  = .4;
            double prune  = 1.5;
            double selper = .03;

            Random random = new Random();

            PointSet ps = new PointSet("ColorHistogram.asc", 1, ' ');

            ps.NormalizePoints();

            //Indexes
            var bruteForce = new BruteForce(ps);

            var standardTree   = new KDTree(ps, false);
            var standardForest = new KDTreeForestHolder(ps, ddeter, nrand, true, false);

            //Result holders
            var standardDist   = new List <double>();
            var queryDist      = new List <double>();
            var standardDist_f = new List <double>();

            for (int i = 0; i < dws; i++)
            {
                Console.WriteLine(dim + " " + i);
                var querydw = new DimWeight(dim, selper, random);

                var queryTree = new KDTree(ps, querydw, false);

                for (int j = 0; j < testcases; j++)
                {
                    var p   = ps.Points[random.Next(ps.Points.Count())];
                    var bfd = bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw);

                    standardDist.Add(standardTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    queryDist.Add(queryTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    standardDist_f.Add(standardForest.GetANN(p, querydw, K, ntrees, ratio, prune, maxSearch).GetMeanDistance(p, querydw) / bfd - 1);
                }
            }

            var standardDist2   = new List <double>();
            var queryDist2      = new List <double>();
            var standardDist_f2 = new List <double>();

            for (int i = 0; i < standardDist.Count(); i++)
            {
                if (!Double.IsNaN(standardDist[i]) && !Double.IsInfinity(standardDist[i]))
                {
                    standardDist2.Add(standardDist[i]);
                }
                if (!Double.IsNaN(queryDist[i]) && !Double.IsInfinity(queryDist[i]))
                {
                    queryDist2.Add(queryDist[i]);
                }
                if (!Double.IsNaN(standardDist_f[i]) && !Double.IsInfinity(standardDist_f[i]))
                {
                    standardDist_f2.Add(standardDist_f[i]);
                }
            }

            Console.WriteLine(standardDist2.Average() + "," + standardDist_f2.Average() + "," + queryDist2.Average());
        }
Ejemplo n.º 13
0
        public bool CheckIntersection(LatLonAlt location)
        {
            bool hasIntersections = false;

            foreach (VisualPushpin pin in intersectedValues)
            {
                host.Geometry.RemoveGeometry(pin.Pushpin.LayerId, pin.Pushpin.Id);
            }
            intersectedValues.Clear();

            lock (meshLayers)
            {
                foreach (MeshLayer meshLayer in meshLayers)
                {
                    if (meshLayer.IsVisible)
                    {
                        if (meshLayer.ScalarField is IDataSource2D <double> )
                        {
                            //for warped grids
                            IDataSource2D <double> field = meshLayer.ScalarField as IDataSource2D <double>;

                            Coordinate2D minCoordinate = new Coordinate2D(field.Grid[0, 0].X, field.Grid[0, 0].Y);
                            Coordinate2D maxCoordinate = new Coordinate2D(field.Grid[field.Width - 1, field.Height - 1].X, field.Grid[field.Width - 1, field.Height - 1].Y);


                            for (int j = 0; j < field.Height; j++)
                            {
                                for (int i = 0; i < field.Width; i++)
                                {
                                    if (field.Grid[i, j].Y < minCoordinate.X)
                                    {
                                        minCoordinate.X = field.Grid[i, j].X;
                                    }

                                    if (field.Grid[i, j].X > maxCoordinate.X)
                                    {
                                        maxCoordinate.X = field.Grid[i, j].X;
                                    }

                                    if (field.Grid[i, j].Y < minCoordinate.Y)
                                    {
                                        minCoordinate.Y = field.Grid[i, j].Y;
                                    }

                                    if (field.Grid[i, j].Y > maxCoordinate.Y)
                                    {
                                        maxCoordinate.Y = field.Grid[i, j].Y;
                                    }
                                }
                            }

                            if (location.LatitudeDegrees > minCoordinate.Y && location.LongitudeDegrees > minCoordinate.X && location.LongitudeDegrees < maxCoordinate.X && location.LatitudeDegrees < maxCoordinate.Y)
                            {
                                for (int i = 0; i < field.Width; i++)
                                {
                                    for (int j = 0; j < field.Height; j++)
                                    {
                                        LatLonAlt gridPos = LatLonAlt.CreateUsingDegrees(field.Grid[i, j].Y, field.Grid[i, j].X, meshLayer.LayerAltitude);
                                        if (CheckEnvirons(gridPos, location, meshLayer.Step))
                                        {
                                            if (!hasIntersections)
                                            {
                                                hasIntersections = true;
                                            }

                                            intersectedValues.Add(new VisualPushpin(50, 50, field.Data[i, j].ToString(), gridPos, null, Guid.NewGuid().ToString()));
                                        }
                                    }
                                }
                            }
                        }
                        else if (meshLayer.ScalarField is PointSet)
                        {
                            PointSet pointSet = meshLayer.ScalarField as PointSet;
                            if (meshLayer.IsVisible)
                            {
                                for (int i = 0; i < pointSet.Data.Count; i++)
                                {
                                    LatLonAlt gridPos = LatLonAlt.CreateUsingDegrees(pointSet.Data[i].Latitude, pointSet.Data[i].Longitude, 0);
                                    if (CheckEnvirons(gridPos, location, 0.3))
                                    {
                                        if (!hasIntersections)
                                        {
                                            hasIntersections = true;
                                        }

                                        intersectedValues.Add(new VisualPushpin(60, 60, pointSet.Data[i].Value.ToString(), gridPos, null, Guid.NewGuid().ToString()));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(hasIntersections);
        }
        public static void Full_Sys_Test_ExtremeDRV()
        {
            int dim       = 8;
            int npoint    = 100000;
            int testcases = 10;
            int dws       = 50;
            int K         = 20;
            int maxSearch = 500;
            int ntrees    = 3;

            int    nrand  = 50;
            int    ddeter = 3;
            double ratio  = .4;
            double prune  = 1.5;
            double selper = .125;

            Random   random = new Random();
            PointSet ps     = new PointSet(dim);

            for (int i = 0; i < npoint; i++)
            {
                ps.AddPoint(new Point(dim, random));
            }

            ////garbage
            //var p2 = new Point(dim, random);
            //var querydw2 = new DimWeight(dim, 0, random);
            //var queryTree2 = new KDTree(ps, querydw2, false);
            //var tmp = queryTree2.root.GetANN(p2, K, maxSearch, querydw2);

            //Indexes
            var bruteForce = new BruteForce(ps);

            var standardTree   = new KDTree(ps, false);
            var standardForest = new KDTreeForestHolder(ps, ddeter, nrand, false, false);

            var standardTree_r   = new KDTree(ps, true);
            var standardForest_r = new KDTreeForestHolder(ps, ddeter, nrand, false, true);

            //Result holders
            var standardDist   = new List <double>();
            var queryDist      = new List <double>();
            var standardDist_f = new List <double>();

            var standardDist_r   = new List <double>();
            var queryDist_r      = new List <double>();
            var standardDist_f_r = new List <double>();

            for (int i = 0; i < dws; i++)
            {
                Console.WriteLine(i);
                var querydw = new DimWeight(dim, selper, random);

                var queryTree   = new KDTree(ps, querydw, false);
                var queryTree_r = new KDTree(ps, querydw, true);

                for (int j = 0; j < testcases; j++)
                {
                    var p   = new Point(dim, random);
                    var bfd = bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw);

                    standardDist.Add(standardTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    queryDist.Add(queryTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    standardDist_f.Add(standardForest.GetANN(p, querydw, K, ntrees, ratio, prune, maxSearch).GetMeanDistance(p, querydw) / bfd - 1);

                    standardDist_r.Add(standardTree_r.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    queryDist_r.Add(queryTree_r.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    standardDist_f_r.Add(standardForest_r.GetANN(p, querydw, K, ntrees, ratio, prune, maxSearch).GetMeanDistance(p, querydw) / bfd - 1);
                }
            }

            Console.WriteLine(standardDist.Average() + " " + standardDist_f.Average() + " " + queryDist.Average());
            Console.WriteLine(standardDist_r.Average() + " " + standardDist_f_r.Average() + " " + queryDist_r.Average());

            Console.WriteLine(stdev(standardDist) + " " + stdev(standardDist_f) + " " + stdev(queryDist));
            Console.WriteLine(stdev(standardDist_r) + " " + stdev(standardDist_f_r) + " " + stdev(queryDist_r));
        }
Ejemplo n.º 15
0
        private void method_1(ObjectId[] objectId_0)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            EntityList    entityList      = new EntityList();
            int           num             = 0;
            int           num2            = 0;
            int           num3            = 0;
            int           num4            = 0;
            MessageFilter messageFilter   = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            ProgressMeter progressMeter = new ProgressMeter();

            progressMeter.SetLimit(objectId_0.Length);
            progressMeter.Start("Serializing XML entities");
            try
            {
                CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), Conversions.GetUCS());
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    LayerTable arg_83_0 = (LayerTable)transaction.GetObject(workingDatabase.LayerTableId, (OpenMode)0);
                    for (int i = 0; i < objectId_0.Length; i++)
                    {
                        messageFilter.CheckMessageFilter((long)i, 10000);
                        progressMeter.MeterProgress();
                        Entity entity = (Entity)transaction.GetObject(objectId_0[i], (OpenMode)0);
                        string name   = ((LayerTableRecord)transaction.GetObject(entity.LayerId, (OpenMode)0)).Name;
                        Autodesk.AutoCAD.DatabaseServices.Face face = entity as Autodesk.AutoCAD.DatabaseServices.Face;
                        if (face != null)
                        {
                            Point3d vertexAt  = face.GetVertexAt(0);
                            Point3d vertexAt2 = face.GetVertexAt(1);
                            Point3d vertexAt3 = face.GetVertexAt(2);
                            Point3d vertexAt4 = face.GetVertexAt(3);
                            global::TerrainComputeC.XML.Vertex v     = new global::TerrainComputeC.XML.Vertex(vertexAt.X, vertexAt.Y, vertexAt.Z);
                            global::TerrainComputeC.XML.Vertex v2    = new global::TerrainComputeC.XML.Vertex(vertexAt2.X, vertexAt2.Y, vertexAt2.Z);
                            global::TerrainComputeC.XML.Vertex v3    = new global::TerrainComputeC.XML.Vertex(vertexAt3.X, vertexAt3.Y, vertexAt3.Z);
                            global::TerrainComputeC.XML.Vertex v4    = new global::TerrainComputeC.XML.Vertex(vertexAt4.X, vertexAt4.Y, vertexAt4.Z);
                            global::TerrainComputeC.XML.Face   face2 = new global::TerrainComputeC.XML.Face(v, v2, v3, v4);
                            face2.SetProperties(name, face.Color.ColorIndex);
                            entityList.Faces.Add(face2);
                            coordinateTransformator.Transform(face2);
                            num4++;
                        }
                        else
                        {
                            DBPoint dBPoint = entity as DBPoint;
                            if (dBPoint != null)
                            {
                                global::TerrainComputeC.XML.Point point = new global::TerrainComputeC.XML.Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                                point.SetProperties(name, dBPoint.Color.ColorIndex);
                                entityList.Points.Add(point);
                                coordinateTransformator.Transform(point);
                                num++;
                            }
                            else
                            {
                                Autodesk.AutoCAD.DatabaseServices.Line line = entity as Autodesk.AutoCAD.DatabaseServices.Line;
                                if (line != null)
                                {
                                    Point3d startPoint = line.StartPoint;
                                    Point3d endPoint   = line.EndPoint;
                                    global::TerrainComputeC.XML.Vertex startVertex = new global::TerrainComputeC.XML.Vertex(startPoint.X, startPoint.Y, startPoint.Z);
                                    global::TerrainComputeC.XML.Vertex endVertex   = new global::TerrainComputeC.XML.Vertex(endPoint.X, endPoint.Y, endPoint.Z);
                                    global::TerrainComputeC.XML.Line   line2       = new global::TerrainComputeC.XML.Line(startVertex, endVertex);
                                    line2.SetProperties(name, line.Color.ColorIndex);
                                    entityList.Lines.Add(line2);
                                    coordinateTransformator.Transform(line2);
                                    num2++;
                                }
                                else
                                {
                                    Polyline   polyline   = entity as Polyline;
                                    Polyline2d polyline2d = entity as Polyline2d;
                                    Polyline3d polyline3d = entity as Polyline3d;
                                    if (polyline != null || polyline2d != null || polyline3d != null)
                                    {
                                        short colorIndex = 256;
                                        if (polyline != null)
                                        {
                                            colorIndex = polyline.Color.ColorIndex;
                                        }
                                        if (polyline2d != null)
                                        {
                                            colorIndex = polyline2d.Color.ColorIndex;
                                        }
                                        if (polyline3d != null)
                                        {
                                            colorIndex = polyline3d.Color.ColorIndex;
                                        }
                                        PointSet pointSet = PointGeneration.SubdividePolyline(entity, transaction, 0.0);
                                        List <global::TerrainComputeC.XML.Vertex> list = new List <global::TerrainComputeC.XML.Vertex>();
                                        for (int j = 0; j < pointSet.Count; j++)
                                        {
                                            list.Add(new global::TerrainComputeC.XML.Vertex(pointSet[j].X, pointSet[j].Y, pointSet[j].Z));
                                        }
                                        PolyLine polyLine = new PolyLine(list);
                                        polyLine.SetProperties(name, colorIndex);
                                        entityList.Polylines.Add(polyLine);
                                        coordinateTransformator.Transform(polyLine);
                                        num3++;
                                    }
                                }
                            }
                        }
                    }
                }
                progressMeter.Stop();
                editor.WriteMessage("\nXML entity list created:");
                editor.WriteMessage("\nNumber of points        : " + entityList.Points.Count);
                editor.WriteMessage("\nNumber of lines         : " + entityList.Lines.Count);
                editor.WriteMessage("\nNumber of polylines     : " + entityList.Polylines.Count);
                editor.WriteMessage("\nNumber of faces         : " + entityList.Faces.Count);
                editor.WriteMessage("\nTotal number of entities: " + entityList.Count);
                editor.WriteMessage("\nWriting xml file " + IO.string_0 + "...");
                Serializer.Serialize(IO.string_0, entityList);
                editor.WriteMessage("OK\n");
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
Ejemplo n.º 16
0
        internal PointSet method_0(ObjectId[] objectId_0, double double_0)
        {
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();

            progressMeter.SetLimit(objectId_0.Length);
            if (objectId_0.Length > 1)
            {
                progressMeter.Start("Generating points...");
            }
            MessageFilter messageFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            int      num      = 0;
            PointSet pointSet = new PointSet();
            PointSet result;

            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    List <Entity> list = new List <Entity>();
                    for (int i = 0; i < objectId_0.Length; i++)
                    {
                        list.Add((Entity)transaction.GetObject(objectId_0[i], (OpenMode)0));
                    }
                    Mesh2dControl mesh2dControl = new Mesh2dControl();
                    mesh2dControl.MaxNodeSpacing = (double_0);
                    mesh2dControl.ElementShape   = (0);
                    for (int j = 0; j < objectId_0.Length; j++)
                    {
                        Brep         brep         = new Brep(list[j]);
                        Mesh2dFilter mesh2dFilter = new Mesh2dFilter();
                        mesh2dFilter.Insert(brep, mesh2dControl);
                        Mesh2d mesh2d = new Mesh2d(mesh2dFilter);
                        using (Mesh2dElement2dEnumerator enumerator = mesh2d.Element2ds.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                Element2d current = enumerator.Current;
                                messageFilter.CheckMessageFilter((long)num, 100);
                                num++;
                                using (Element2dNodeEnumerator enumerator2 = current.Nodes.GetEnumerator())
                                {
                                    while (enumerator2.MoveNext())
                                    {
                                        Node current2 = enumerator2.Current;
                                        pointSet.Add(new Point(current2.Point.X, current2.Point.Y, current2.Point.Z));
                                        current2.Dispose();
                                    }
                                }
                                current.Dispose();
                            }
                        }
                        progressMeter.MeterProgress();
                    }
                    pointSet.RemoveMultiplePoints3d();
                }
                progressMeter.Stop();
                result = pointSet;
            }
            catch
            {
                progressMeter.Stop();
                throw;
            }
            return(result);
        }
        public static void Full_Sys_Test_Nrand()
        {
            int dim       = 8;
            int npoint    = 100000;
            int testcases = 20;
            int dws       = 80;
            int K         = 20;
            int maxSearch = 500;
            int ntrees    = 3;

            var nrands = new List <int>()
            {
                20, 50, 100, 200, 400
            };
            int    ddeter = 1;
            double ratio  = .4;
            double prune  = 1.5;

            var    lines    = new List <string>();
            string filename = "resultsnrand.csv";

            Random random = new Random();

            foreach (var nrand in nrands)
            {
                PointSet ps = new PointSet(dim);

                for (int i = 0; i < npoint; i++)
                {
                    ps.AddPoint(new Point(dim, random));
                }

                //Indexes
                var bruteForce = new BruteForce(ps);

                var standardTree   = new KDTree(ps, false);
                var standardForest = new KDTreeForestHolder(ps, ddeter, nrand, false, false);

                //Result holders
                var standardDist   = new List <double>();
                var queryDist      = new List <double>();
                var standardDist_f = new List <double>();

                for (int i = 0; i < dws; i++)
                {
                    Console.WriteLine(dim + " " + i);
                    var querydw = new DimWeight(dim, random);

                    var queryTree = new KDTree(ps, querydw, false);

                    for (int j = 0; j < testcases; j++)
                    {
                        var p   = new Point(dim, random);
                        var bfd = bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw);

                        standardDist.Add(standardTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                        queryDist.Add(queryTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                        double val = standardForest.GetANN(p, querydw, K, ntrees, ratio, prune, maxSearch).GetMeanDistance(p, querydw) / bfd - 1;
                        if (!Double.IsNaN(val) && val < 1000)
                        {
                            standardDist_f.Add(val);
                        }
                    }
                }

                lines.Add(standardDist.Average() + "," + standardDist_f.Average() + "," + queryDist.Average());
            }

            System.IO.File.WriteAllLines(filename, lines);
        }
        public static void Full_Sys_Test_nSearch()
        {
            int dim        = 8;
            int npoint     = 100000;
            int testcases  = 20;
            int dws        = 80;
            int K          = 20;
            var maxSearchs = new List <int>()
            {
                50, 200, 500, 2000, 8000
            };
            int ntrees = 3;

            int    nrand  = 100;
            int    ddeter = 1;
            double ratio  = .4;
            double prune  = 1.5;

            var    lines    = new List <string>();
            string filename = "resultsnsearch.csv";

            Random random = new Random();

            PointSet ps = new PointSet(dim);

            for (int i = 0; i < npoint; i++)
            {
                ps.AddPoint(new Point(dim, random));
            }

            //Indexes
            var bruteForce = new BruteForce(ps);

            var standardTree   = new KDTree(ps, false);
            var standardForest = new KDTreeForestHolder(ps, ddeter, nrand, false, false);

            //Result holders
            var standardDist   = new List <List <double> >();
            var queryDist      = new List <List <double> >();
            var standardDist_f = new List <List <double> >();

            for (int i = 0; i < maxSearchs.Count(); i++)
            {
                standardDist.Add(new List <double>());
                queryDist.Add(new List <double>());
                standardDist_f.Add(new List <double>());
            }

            for (int i = 0; i < dws; i++)
            {
                Console.WriteLine(dim + " " + i);
                var querydw = new DimWeight(dim, random);

                var queryTree = new KDTree(ps, querydw, false);

                for (int j = 0; j < testcases; j++)
                {
                    var p   = new Point(dim, random);
                    var bfd = bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw);
                    foreach (var maxSearch in maxSearchs)
                    {
                        int indx = 0;
                        standardDist[indx].Add(standardTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                        queryDist[indx].Add(queryTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);


                        standardDist_f[indx].Add(standardForest.GetANN(p, querydw, K, ntrees, ratio, prune, maxSearch).GetMeanDistance(p, querydw) / bfd - 1);
                        indx++;
                    }
                }
            }

            for (int i = 0; i < standardDist.Count(); i++)
            {
                lines.Add(standardDist[i].Average() + "," + queryDist[i].Average() + "," + standardDist_f[i].Average());
            }

            System.IO.File.WriteAllLines(filename, lines);
        }
Ejemplo n.º 19
0
        //protected Line IntegrateCircle(float angle, float radius, out Graph2D graph, float time = 0)
        //{
        //}
        protected LineSet IntegrateCircles(float[] radii, float[] angles, out Graph2D[] graph, int time = 0)
        {
            // ~~~~~~~~~~~~~~~~~~ Initialize seed points. ~~~~~~~~~~~~~~~~~~~~ \\
            PointSet<Point> circle = new PointSet<Point>(new Point[radii.Length * angles.Length]);
            for (int a = 0; a < angles.Length; ++a)
            {
                float x = (float)(Math.Sin(angles[a] + Math.PI / 2));
                float y = (float)(Math.Cos(angles[a] + Math.PI / 2));

                for (int r = 0; r < radii.Length; ++r)
                {
                    // Take the selection as center.
                    circle[a*radii.Length + r] = new Point() { Position = new Vector3(_selection.X + x * radii[r], _selection.Y + y * radii[r], time) };
                }
            }

            // ~~~~~~~~~~~~ Integrate Pathlines and Adapt ~~~~~~~~~~~~~~~~~~~~~~~~ \\
            // Setup integrator.
            Integrator pathlineIntegrator = Integrator.CreateIntegrator(null, IntegrationType, _cores[_selectedCore], _repulsion);
            pathlineIntegrator.StepSize = StepSize;
            LineSet pathlines;

            // Count out the runs for debugging.
            int run = 0;

            // ~~~~~~~~~~~~ Integrate Pathlines  ~~~~~~~~~~~~~~~~~~~~~~~~ \\
            #region IntegratePathlines
            // Do we need to load a field first?
            if (_velocity.TimeOrigin > time || _velocity.TimeOrigin + _velocity.Size.T < time)
                LoadField(time, MemberMain);

            // Integrate first few steps.
            pathlineIntegrator.Field = _velocity;
            pathlines = pathlineIntegrator.Integrate(circle, false)[0];

            // Append integrated lines of next loaded vectorfield time slices.
            float timeLength = STEPS_IN_MEMORY * 3 - 2/*RedSea.Singleton.NumSubstepsTotal / _everyNthTimestep / 4*/ + time;
            while (_currentEndStep + 1 < timeLength)
            {
                // Don't load more steps than we need to!
                int numSteps = (int)Math.Min(timeLength - _currentEndStep, STEPS_IN_MEMORY);
                pathlineIntegrator.Field = null;
                LoadField(_currentEndStep, MemberMain, numSteps);

                // Integrate further.
                pathlineIntegrator.Field = _velocity;
                pathlineIntegrator.IntegrateFurther(pathlines);
            }
            #endregion IntegratePathlines

            // ~~~~~~~~~~~~ Get Boundary ~~~~~~~~~~~~~~~~~~~~~~~~ \\
            #region GetBoundary
            // The two needes functions.
            //Line[] distances = FieldAnalysis.GetGraph(_cores[_selectedCore], _selection, pathlines, (StepSize * _everyNthTimestep) / 24.0f, _everyNthTimestep, true);
            //Line[] angles = FieldAnalysis.GetGraph(_cores[_selectedCore], _selection, pathlines, (StepSize * _everyNthTimestep) / 24.0f, _everyNthTimestep, false);
            graph = FieldAnalysis.GetDistanceToAngle(_cores[_selectedCore], _selection, pathlines);
            //graph[0].CutGraph((float)(Math.PI * 2));
            //Array.Resize(ref pathlines[0].Positions, graph[0].Length);
            FieldAnalysis.WriteXToLinesetAttribute(pathlines, graph);

            #endregion GetBoundary
            //LineSet[] subsets = new LineSet[angles.Length];
            //for(int s = 0; s < subsets.Length; ++ s)
            //{
            //    subsets[s] = new LineSet(pathlines, s * radii.Length, radii.Length);
            //}
            //return subsets;
            return pathlines;

            //            LineSet set = new LineSet(_coreAngleGraph);
            //GeometryWriter.WriteHeightCSV(RedSea.Singleton.DonutFileName + "Angle.csv", set);
            //            GeometryWriter.WriteToFile(RedSea.Singleton.DonutFileName + ".angle", set);

            //            set = new LineSet(_coreDistanceGraph);
            //GeometryWriter.WriteHeightCSV(RedSea.Singleton.DonutFileName + "Distance.csv", set);
            //            GeometryWriter.WriteToFile(RedSea.Singleton.DonutFileName + ".distance", set);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="PS">点集</param>
 /// <param name="method">拟合方法</param>
 public ActualLine(PointSet PS, Unit.EvaluationMethod method = Unit.EvaluationMethod.Gauss)
 {
     ParasChangedEvent += Calculate;
     Points             = PS;
     EvaluationMethod   = method;
 }
Ejemplo n.º 21
0
 public PointSet AddRing(string name, PointF[] points)
 {
     PointSet ps = new PointSet(points);
     ring.Add(name, ps);
     ringList.Add(ps);
     return ps;
 }
Ejemplo n.º 22
0
    internal void method_5(ConvexHull3d convexHull3d_0)
    {
        PointSet initialPoints = convexHull3d_0.InitialPoints;

        if (initialPoints == null)
        {
            throw new InvalidOperationException("Can not compute convex hull: no point set defined.");
        }
        if (initialPoints.Count < 4)
        {
            throw new ArgumentException("Can not compute 3d convex hull for less than four points.");
        }
        if (!Class20.bool_0)
        {
            Class20.smethod_0();
        }
        PointSet pointSet = initialPoints.DeepCopy();

        pointSet.RandomPermute();
        Point center = pointSet.Center;

        int[] array = new int[4];
        array[0] = 0;
        Point point = pointSet[array[0]];

        array[1] = 1;
        Point point2 = pointSet[array[1]];

        while (Math.Abs(Predicate.Orient2d_exact(point, point2, center)) < 1E-07 | point2 == point)
        {
            array[1]++;
            if (array[1] > pointSet.Count - 1)
            {
                throw new ArithmeticException("Failed compute 3d convex hull: need at least four non-coplanar points.");
            }
            point2 = pointSet[array[1]];
        }
        array[2] = 1;
        Point point3 = pointSet[array[2]];

        while (Predicate.Orient3d_exact(point, point2, point3, center) < 1E-06 | point3 == point | point3 == point2)
        {
            array[2]++;
            if (array[2] > pointSet.Count - 1)
            {
                throw new ArithmeticException("Failed compute 3d convex hull: need at least four non-coplanar points.");
            }
            point3 = pointSet[array[2]];
        }
        array[3] = 1;
        Point point4 = pointSet[array[3]];

        while (Predicate.Orient3d_exact(point, point2, point3, point4) < 1E-06 | point4 == point | point4 == point2 | point4 == point3)
        {
            array[3]++;
            if (array[3] > pointSet.Count - 1)
            {
                throw new ArithmeticException("Failed compute 3d convex hull: need at least four non-coplanar points.");
            }
            point4 = pointSet[array[3]];
        }
        List <int> list = new List <int>();

        list.AddRange(array);
        list.Sort();
        pointSet.RemoveAt(list[3]);
        pointSet.RemoveAt(list[2]);
        pointSet.RemoveAt(list[1]);
        pointSet.RemoveAt(list[0]);
        Class25 @class = new Class25(point);
        Class25 class2 = new Class25(point2);
        Class25 class3 = new Class25(point3);
        Class25 class4 = new Class25(point4);

        @class.method_5(true);
        class2.method_5(true);
        class3.method_5(true);
        class4.method_5(true);
        this.list_1.Add(new Class13(@class, class2, class3));
        this.list_1.Add(new Class13(@class, class4, class2));
        this.list_1.Add(new Class13(@class, class3, class4));
        this.list_1.Add(new Class13(class3, class2, class4));
        this.list_1[0].method_8()[0] = this.list_1[3];
        this.list_1[0].method_8()[1] = this.list_1[2];
        this.list_1[0].method_8()[2] = this.list_1[1];
        this.list_1[1].method_8()[0] = this.list_1[3];
        this.list_1[1].method_8()[1] = this.list_1[0];
        this.list_1[1].method_8()[2] = this.list_1[2];
        this.list_1[2].method_8()[0] = this.list_1[3];
        this.list_1[2].method_8()[1] = this.list_1[1];
        this.list_1[2].method_8()[2] = this.list_1[0];
        this.list_1[3].method_8()[0] = this.list_1[1];
        this.list_1[3].method_8()[1] = this.list_1[2];
        this.list_1[3].method_8()[2] = this.list_1[0];
        for (int i = 0; i < pointSet.Count; i++)
        {
            this.list_0.Add(new Class25(pointSet[i]));
        }
        this.list_0.Add(@class);
        this.list_0.Add(class2);
        this.list_0.Add(class3);
        this.list_0.Add(class4);
        for (int j = 0; j < this.list_0.Count; j++)
        {
            convexHull3d_0.vmethod_0(null, null);
            for (int k = 0; k < this.list_1.Count; k++)
            {
                if (this.list_1[k].method_15(this.list_0[j]))
                {
                    this.list_1[k].method_10().Add(this.list_0[j]);
                    this.list_0[j].method_2().Add(this.list_1[k]);
                }
            }
        }
    }
Ejemplo n.º 23
0
        /// <summary>
        /// Removes the given polygons and recalculates the mesh
        /// inside the given bounding box. Also needs the blocked
        /// points and the mesh scale to do so.
        /// </summary>
        public void Recalculate(PointSet<int> blocked, List<Polygon> polygonsToRecalculate, Rectangle extremaBoundingBox, int scale)
        {
            GlobalValues globalValues = GlobalValues.GetInstance();

            // extremaBoundingBox is the rectangle containing all polygonsToRecalculate
            Debug.Assert(extremaBoundingBox.X >= 0 && extremaBoundingBox.Y >= 0
                && extremaBoundingBox.X + extremaBoundingBox.Width <= mWidth
                && extremaBoundingBox.Y + extremaBoundingBox.Height <= mHeight);

            // We will remove all polygons for which we want to refill the space:
            foreach (Polygon polygon in polygonsToRecalculate)
            {
                Debug.Assert(polygon.IsCovered(extremaBoundingBox, true));
                RemovePolygon(polygon);
                polygon.Delete(true);
            }

            // We also need the remaining involved polygons
            // to clean them up now and to calculate coveredByPolygonBefore, which is needed such that
            // the space of still existant polygons within extremaBoundingBox isn't invaded
            Rectangle? ofNoInterest;
            List<Polygon> remainingPolygons = FindCoveredPolygons(extremaBoundingBox, out ofNoInterest, false, true);
            PointSet<int> coveredByPolygonBefore = new PointSet<int>();
            foreach (Polygon remainingPolygon in remainingPolygons)
            {
                if (remainingPolygon.CanBeCleanedUp()) remainingPolygon.CleanUp(true);
                Rectangle coverRestriction = new Rectangle(extremaBoundingBox.X - 1, extremaBoundingBox.Y - 1,
                    extremaBoundingBox.Width + 1, extremaBoundingBox.Height + 1);
                remainingPolygon.RectRegisterCover(coveredByPolygonBefore, coverRestriction, scale);
            }
            // Get all nodes that still exist
            // (we must use these instead of creating new ones at the same position):
            List<MeshNode> createdNodes = new List<MeshNode>();
            foreach (Polygon polygon in remainingPolygons)
            {
                foreach (MeshNode node in polygon.GetNodes())
                {
                    if (HelperMethods.RectangleContains(extremaBoundingBox, node.mVector) &&
                        !createdNodes.Contains(node))
                        createdNodes.Add(node);
                }
            }

            // We don't have to adjust mBlocked because
            // that has been done by AddObstruction() / RemoveObstruction()

            CheckIntegrity(false);
            Stopwatch watch = Stopwatch.StartNew();
            if (globalValues.mShowMeshCreation) CodeTest.mMeshesToDraw.Add(this);
            // Now fill up extremaBoundingBox with new polygons:
            List<Polygon>[,] newSectors = NavigationMeshFactory.CreateInstanceFromBlockmap(blocked,
                                                                                  remainingPolygons,
                                                                                  coveredByPolygonBefore,
                                                                                  scale,
                                                                                  extremaBoundingBox,
                                                                                  createdNodes, false).GetSectors();
            if (globalValues.mShowMeshCreation) CodeTest.mMeshesToDraw.Remove(this);
            watch.Stop();
            Debug.WriteLine("CreateInstanceFromBlockmap in " + watch.ElapsedMilliseconds + " ms.");
            // Take these new polygons and add them to our mesh:
            List<Polygon>[,] mySectors = GetSectors();
            for (int y = 0; y < mSectorRows; y++)
                for (int x = 0; x < mSectorColumns; x++)
                    foreach (Polygon polygon in newSectors[x, y])
                    {
                        mySectors[x, y].Add(polygon);

                        // We don't use AddPolygon here because that would be
                        // too tedious (e.g. checking for already added polygons etc.)
                    }

            CheckIntegrity();
            Debug.WriteLine("Start WholeUnionRun...");
            // Try to unite as many polygons as possible inside extremaBoundingBox:
            WholeUnionRun(true, extremaBoundingBox);
            CheckIntegrity();
        }
Ejemplo n.º 24
0
        public static List <Edge> ToCeometricEdgeList(ObjectId[] idArray)
        {
            Database    workingDatabase = HostApplicationServices.WorkingDatabase;
            List <Edge> list            = new List <Edge>();

            using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
            {
                for (int i = 0; i < idArray.Length; i++)
                {
                    DBObject @object = transaction.GetObject(idArray[i], (OpenMode)0);
                    if (!(@object == null))
                    {
                        Autodesk.AutoCAD.DatabaseServices.Line line = @object as Autodesk.AutoCAD.DatabaseServices.Line;
                        if (line != null)
                        {
                            ngeometry.VectorGeometry.Point startPoint = Conversions.ToCeometricPoint(line.StartPoint);
                            ngeometry.VectorGeometry.Point endPoint   = Conversions.ToCeometricPoint(line.EndPoint);
                            list.Add(new Edge(startPoint, endPoint));
                        }
                        else
                        {
                            PointSet pointSet = null;
                            Polyline polyline = @object as Polyline;
                            if (polyline != null)
                            {
                                pointSet = PointGeneration.SubdivideLWPolyline(polyline, 0.0);
                                if (polyline.Closed)
                                {
                                    pointSet.Add(pointSet[0]);
                                }
                            }
                            Polyline2d polyline2d = @object as Polyline2d;
                            if (polyline2d != null)
                            {
                                pointSet = PointGeneration.SubdividePolyline2d(polyline2d, transaction, 0.0);
                                if (polyline2d.Closed)
                                {
                                    pointSet.Add(pointSet[0]);
                                }
                            }
                            Polyline3d polyline3d = @object as Polyline3d;
                            if (polyline3d != null)
                            {
                                pointSet = PointGeneration.SubdividePolyline3d(polyline3d, transaction, 0.0);
                                if (polyline3d.Closed)
                                {
                                    pointSet.Add(pointSet[0]);
                                }
                            }
                            if (pointSet != null)
                            {
                                for (int j = 0; j < pointSet.Count - 1; j++)
                                {
                                    list.Add(new Edge(pointSet[j], pointSet[j + 1]));
                                }
                            }
                        }
                    }
                }
            }
            return(list);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Returns and removes the element with the lowest heuristic value from the workingQueue.
        /// </summary>
        private AStarNode GetNextNodeFromWorkingQueue(MinHeap<AStarNode> workingQueue, PointSet<float> workingCoords)
        {
            AStarNode result = workingQueue.RemoveMin();

            workingCoords.Remove(result.mNode.mVector.X, result.mNode.mVector.Y);
            return result;
        }
 public AgentInterior()
 {
     //AddProperty("AverageValue", property); //Property that will be actualized with the AverageV from PointSet PS, cannot currently be implemented
     PS = new PointSet();
     GA = new GeneticAlgorithm(new DoubleEvaluation_Trigonometric());
 }
        public static void Test_Tree_maxSearch()
        {
            int dim       = 8;
            int npoint    = 100000;
            int testcases = 10;
            int dws       = 10;
            int K         = 20;
            int maxSearch = 200;
            int ntrees    = 3;

            Random   random = new Random();
            PointSet ps     = new PointSet(dim);

            for (int i = 0; i < npoint; i++)
            {
                ps.AddPoint(new Point(dim, random));
            }

            //Indexes
            var bruteForce   = new BruteForce(ps);
            var standardTree = new KDTree(ps, false);

            //Result holders
            var bruteforceDist = new List <double>();
            var standardDist   = new List <List <double> >();
            var queryDist      = new List <List <double> >();

            //Final Result Holder
            var finStd = new List <double>();
            var finQue = new List <double>();

            for (int i = 0; i < dws; i++)
            {
                Console.WriteLine(i);
                var querydw   = new DimWeight(dim, random);
                var queryTree = new KDTree(ps, querydw, false);

                standardDist.Clear();
                queryDist.Clear();

                for (int j = 0; j < testcases; j++)
                {
                    standardDist.Add(new List <double>());
                    queryDist.Add(new List <double>());

                    var p = new Point(dim, random);
                    //bruteforceDist.Add(bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw));
                    var bfd = bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw);

                    for (int k = maxSearch; k < 8000; k = k + 200)
                    {
                        if (j == 0 && i == 0)
                        {
                            finStd.Add(0);
                            finQue.Add(0);
                        }
                        standardDist[j].Add(standardTree.root.GetANN(p, K, k, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                        queryDist[j].Add(queryTree.root.GetANN(p, K, k, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    }
                }

                for (int k = 0; k < queryDist[0].Count(); k++)
                {
                    double sumStd = 0;
                    double sumQue = 0;
                    for (int j = 0; j < testcases; j++)
                    {
                        sumStd += standardDist[j][k];
                        sumQue += queryDist[j][k];
                    }

                    sumStd /= testcases;
                    sumQue /= testcases;

                    finStd[k] += sumStd / dws;
                    finQue[k] += sumQue / dws;
                }
            }

            FileStream   fs = new FileStream("Results2.csv", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            for (int i = 0; i < finStd.Count(); i++)
            {
                sw.WriteLine(finStd[i] + "," + finQue[i]);
            }
        }
 public AgentInterior(GeneticAlgorithm ga)
 {
     PS = new PointSet();
     GA = ga;
 }
 /// <summary>
 /// Removes a PointSet.
 /// </summary>
 /// <param name="pointSet">PointSet to remove</param>
 public void RemovePointSet(PointSet pointSet)
 {
     pointSets.Remove(pointSet);
 }
Ejemplo n.º 30
0
        public PCA(PointSet points)
        {
            //Build a matrix
            _m = Matrix <double> .Build.Dense(points.Count, points.Dimensions);

            //Add our values
            for (int r = 0; r < points.Count; r++)
            {
                for (int c = 0; c < points.Dimensions; c++)
                {
                    _m[r, c] = points[r][c];
                }
            }

            //Now Find the standard Deviation
            for (int d = 0; d < points.Dimensions; d++)
            {
                var    col  = _m.Column(d);
                double mean = col.Mean();
                double std  = col.StandardDeviation();
                for (int r = 0; r < points.Count; r++)
                {
                    _m[r, d] = (_m[r, d] - mean) / std;
                }
            }

            //Calculate Covariance matrix
            var cov = ((_m.Transpose()).Multiply(_m)).Multiply(1 / ((double)points.Count - 1));

            //Calculate EigenValue Decomposition
            var    eigen    = cov.Evd();
            double eigenSum = eigen.EigenValues.SumMagnitudes();

            _eigenPairs = new List <EigenPair>();
            for (int d = 0; d < points.Dimensions; d++)
            {
                var eVec = eigen.EigenVectors.Column(d);
                _eigenPairs.Add(new EigenPair(eigen.EigenValues[d].Magnitude, eVec));
            }

            //fast eigenVector
            //Matrix<double> mMinus = m.Subtract(mean_vec);
            //Get the Eigenvectors

            /*
             * var mT = m.Transpose();
             * Svd<double> svd = mT.Svd();
             * Matrix<double> eigenVectors = svd.U;
             */

            //Sort the list by eigenValue
            _eigenPairs.Sort((x, y) => y.Value.CompareTo(x.Value));

            //Finally Calculate the Eigenvalue contribution
            RunningTotalArr = new double[points.Dimensions];
            Contributions   = new double[points.Dimensions];
            int    n            = 0;
            double runningTotal = 0.0;

            foreach (double contribution in _eigenPairs.Select(ep => ep.Value / eigenSum))
            {
                runningTotal      += contribution;
                Contributions[n]   = contribution;
                RunningTotalArr[n] = runningTotal;
                n++;
            }
        }
Ejemplo n.º 31
0
 public void WritePointSet(PointSet pointSet)
 {
     WritePointSet(pointSet, SliceId);
 }
Ejemplo n.º 32
0
        public PointSet[] GetSetsToDraw(Point leftTopView, Point rightBottomView, Window window)//, Matrix m)
        {
            lock (world.tickLocker)
            {
                calcOtherWatch.Restart();
                calcWatch.Restart();
                PointSet[] setsToDraw =
                    world.pointsManager.getPointsSets(
                        leftTopView.X, rightBottomView.X, leftTopView.Y, rightBottomView.Y,
                        maxPartiesRendered);
                calcGetSetsTimes.Add(calcOtherWatch.ElapsedMilliseconds);

                calcOtherWatch.Restart();
                int clustersDrawed = 0;
                int totalElements  = 0;
                foreach (Cluster c in world.pointsManager.clusters)
                {
                    if (c != null && c.idX >= world.pointsManager.li && c.idX <= world.pointsManager.ri && c.idY >= world.pointsManager.ti && c.idY <= world.pointsManager.bi)
                    {
                        clustersDrawed++;
                        totalElements += c.container.Values.Count;
                    }
                }
                calcIterateClustersTimes.Add(calcOtherWatch.ElapsedMilliseconds);

                calcOtherWatch.Restart();
                int    coloredGeometrySetLength = 0;
                double foodGetTime        = 0;
                int    foodGetCount       = 0;
                double createGeometryTime = 0;
                int    geometriesCreated  = 0;
                int    geometriesRestored = 0;
                //Parallel.For(0, coloredGeometry.Length - 1, (i) =>
                for (int i = 0; i < setsToDraw.Length; i++)
                {
                    PointSet        set = setsToDraw[i];
                    ColoredGeometry cg  = new ColoredGeometry();

                    Object val     = set.linkedObjects[CacheLastHashGeometryType];
                    uint   oldHash = 0;
                    if (val != null)
                    {
                        oldHash = (uint)val;
                    }
                    uint nowHash = set.hash;
                    if (oldHash == nowHash)
                    {
                        Object val2 = set.linkedObjects[CacheColoredGeometryType];
                        if (val2 != null)
                        {
                            geometriesRestored++;
                            continue;
                        }
                    }
                    geometriesCreated++;
                    set.linkedObjects[CacheLastHashGeometryType] = nowHash;

                    switch (set.type)
                    {
                    case World.ZoaType:
                        break;

                    case World.FoodType:
                        double size  = (set.joinDist * 2);
                        double alpha =
                            (world.pointsManager.lowestPointSize * world.pointsManager.lowestPointSize * set.points.Count * 4) /     //total food area
                            (Math.PI * size * size / 4);
                        if (alpha > 1)
                        {
                            alpha = 1;
                        }
                        coloredGeometrySetLength++;

                        double fire     = 0;
                        double grass    = 0;
                        double ocean    = 0;
                        double toxicity = 0;
                        foreach (StaticPoint p in set.points)
                        {
                            Food f = (Food)p.linkedObjects[World.WorldObjectType];    //world.food[p.id];
                            fire     += f.fire;
                            grass    += f.grass;
                            ocean    += f.ocean;
                            toxicity += f.toxicity;
                        }
                        toxicity /= set.points.Count;

                        /*Geometry g = new RectangleGeometry(
                         *      new Rect(
                         *          new Point(set.x - size / 2, set.y - size / 2),
                         *          new Point(set.x + size / 2, set.y + size / 2))
                         *  );*/
                        Geometry g = new EllipseGeometry(
                            new Rect(set.x - size / 2, set.y - size / 2, size, size)
                            );
                        g.Freeze();

                        double sum = fire + grass + ocean;
                        Color  c   = Color.FromArgb(
                            (byte)(alpha * 255),            //coeff * 255),
                            (byte)(fire / sum * 255),
                            (byte)(grass / sum * 255),
                            (byte)(ocean / sum * 255));
                        cg = new ColoredGeometry(g, c, null);
                        break;
                    }
                    set.linkedObjects[CacheColoredGeometryType] = cg;
                }//);
                createGeometryTime /= coloredGeometrySetLength;
                foodGetTime        /= foodGetCount;
                foodGetTimes.Add(foodGetTime);
                createGeometryTimes.Add(createGeometryTime);
                calcGeometryTimes.Add(calcOtherWatch.ElapsedMilliseconds);

                calcTimes.Add(calcWatch.ElapsedMilliseconds);

                if (calcTimes.Count > checkTimes)
                {
                    calcTimes.RemoveAt(0);
                }
                if (calcGetSetsTimes.Count > checkTimes)
                {
                    calcGetSetsTimes.RemoveAt(0);
                }
                if (calcIterateClustersTimes.Count > checkTimes)
                {
                    calcIterateClustersTimes.RemoveAt(0);
                }
                if (calcGeometryTimes.Count > checkTimes)
                {
                    calcGeometryTimes.RemoveAt(0);
                }

                int calcTime = 0;
                foreach (double d in calcTimes)
                {
                    calcTime += (int)d;
                }
                calcTime /= calcTimes.Count;

                int calcGetSetsTime = 0;
                foreach (double d in calcGetSetsTimes)
                {
                    calcGetSetsTime += (int)d;
                }
                calcGetSetsTime /= calcGetSetsTimes.Count;

                int calcIterateClustersTime = 0;
                foreach (double d in calcIterateClustersTimes)
                {
                    calcIterateClustersTime += (int)d;
                }
                calcIterateClustersTime /= calcIterateClustersTimes.Count;

                int calcGeometryTime = 0;
                foreach (double d in calcGeometryTimes)
                {
                    calcGeometryTime += (int)d;
                }
                calcGeometryTime /= calcGeometryTimes.Count;

                int renderTime = 0;
                lock (renderTimes)
                    foreach (double d in renderTimes)
                    {
                        renderTime += (int)d;
                    }
                if (renderTimes.Count > 0)
                {
                    renderTime /= renderTimes.Count;
                }

                try
                {
                    window.Dispatcher.Invoke(() =>
                    {
                        if (window.Title != null)
                        {
                            window.Title = String.Format(
                                "Clusters: {14}x{15}x{16} isGeneratingLayer: {17}|{18}%" +
                                " ClustersDrawed: {0}/{1}, Elements(Rendered/MaxRendered/InViewedClusters/Total): {2}/{3}/{4}/{5} " +
                                //"ElapsedTime: CalcSets/CalcClusters/CalcGeometry/CalcAll {6}/{7}/{8}/{9}ms" +
                                " Render {10}/Total {11}ms Geometries(Restored/Created): {12}/{13} FixedLayer: {19}",
                                //" CacheSize(CG/Drawings): {14}/{15}",
                                clustersDrawed, world.pointsManager.clusters.Length,
                                setsToDraw.Length, maxPartiesRendered, totalElements, world.pointsManager.pointsCount,
                                calcGetSetsTime, calcIterateClustersTime, calcGeometryTime,
                                calcTime, renderTime, calcTime + renderTime,
                                geometriesRestored, geometriesCreated,
                                world.pointsManager.clusters.GetLength(0), world.pointsManager.clusters.GetLength(1), world.pointsManager.clusters.GetLength(2),
                                world.pointsManager.isGeneratingLayer, (int)(world.pointsManager.layerGeneratingProgress * 100),
                                world.pointsManager.fixedLayerId);//,
                        }
                        //geometriesCache.Count, drawingsCache.Count);
                    });
                }
                catch (Exception e) { }

                return(setsToDraw);
            }
        }
        public HexagonalSelfOrganizingMap(PointSet data, int dimension, double learningRate)
        {
            _dimension = dimension;

            //Get initial learning rate
            this.initialLearningRate = learningRate;
            this.learningRate        = learningRate;
            influence   = 0;
            itterations = 1;

            this.data = data;
            rng       = new Random();

            int numNeurons = dimension * dimension;

            //Scale each attribute from [0,1] and store the conversion matrix
            conversionMatrix = data.GetMinMaxWeights().Max.Coordinates;

            foreach (KPoint d in data.PointList)
            {
                d.Normalize(conversionMatrix);
            }

            //Here We will initialize Our Neurons
            neurons = new List <SOMNeuron>();
            KPoint zero            = KPoint.Zero(data[0].Dimensions);
            KPoint one             = KPoint.One(data[0].Dimensions);
            double halfNeuronDelta = 1 / Math.Sqrt(3.0);

            //Initialize our Quadtree for reference
            double centerX             = (dimension - 0.5) * (2 * halfNeuronDelta) / 2.0;
            double centerY             = (dimension - 1.0) / 2.0;
            QuadTreePointStruct center = new QuadTreePointStruct()
            {
                Index = -1, X = centerX, Y = centerY
            };
            QuadTreePointStruct halfDistance = new QuadTreePointStruct()
            {
                Index = -1, X = centerX + halfNeuronDelta, Y = centerY + 0.5
            };

            neuronQuadTree = new QuadTree(new QuadTreeBoundingBox()
            {
                Center = center, HalfLength = halfDistance
            });

            int neuronIndex = 0;

            for (int r = 0; r < dimension; r++)
            {
                double xPos = (r % 2 == 1) ? halfNeuronDelta : 0.0;
                for (int c = 0; c < dimension; c++)
                {
                    //Generate our neurons
                    double[]            posNeuron   = { xPos, (double)r };
                    SOMNeuron           neuron      = new SOMNeuron(zero, one, rng, new KPoint(posNeuron), neuronIndex);
                    QuadTreePointStruct neuronQTPos = new QuadTreePointStruct()
                    {
                        Index = neuronIndex,
                        X     = posNeuron[0],
                        Y     = posNeuron[1]
                    };
                    neuronQuadTree.Insert(neuronQTPos);
                    neurons.Add(neuron);
                    xPos += 2 * halfNeuronDelta;
                    neuronIndex++;
                }
            }



            //Get the max radius
            SetRadius();

            timeConstant = (double)totalItterations / Math.Log(radius);
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Helper method for this.CreateInstanceFromBlockmap():
 /// Checks if the right edge of the specified rectangle by (x,y,width,height)
 /// does not have any points in the given "blocked" set.
 /// </summary>
 /// <param name="blocked">the points that may not lie on the rectangle's right edge</param>
 /// <param name="x">defines the rectangle</param>
 /// <param name="y">defines the rectangle</param>
 /// <param name="width">defines the rectangle</param>
 /// <param name="height">defines the rectangle</param>
 /// <returns>if the rectangle doesn't touch any blocked points</returns>
 private static bool VerticalFree(PointSet<int> blocked, int x, int y, int width, int height)
 {
     for (int i = y; i <= y + height; i++)
     {
         if (blocked.Contains(x + width, i)) return false;
     }
     return true;
 }
Ejemplo n.º 35
0
        //protected Line IntegrateCircle(float angle, float radius, out Graph2D graph, float time = 0)
        //{
        //}
        protected LineSet IntegrateCircles(float[] radii, float[] angles, out Graph2D[] graph, float time = 0)
        {
            // ~~~~~~~~~~~~~~~~~~ Initialize seed points. ~~~~~~~~~~~~~~~~~~~~ \\
            PointSet<Point> circle = new PointSet<Point>(new Point[radii.Length * angles.Length * 4]);
            //float angleDiff = 2 * (float)(Math.PI / LineX);
            for (int a = 0; a < angles.Length; ++a)
            {
                float x = (float)(Math.Sin(angles[a] + Math.PI / 2));
                float y = (float)(Math.Cos(angles[a] + Math.PI / 2));

                for (int r = 0; r < radii.Length; ++r)
                {
                    // Take the selection as center.
                    circle[(a * radii.Length + r)*4 + 0] = new Point() { Position = new Vector3(_selection.X + x * radii[r] + _epsOffset, _selection.Y + y * radii[r], time) };
                    circle[(a * radii.Length + r)*4 + 1] = new Point() { Position = new Vector3(_selection.X + x * radii[r] - _epsOffset, _selection.Y + y * radii[r], time) };
                    circle[(a * radii.Length + r)*4 + 2] = new Point() { Position = new Vector3(_selection.X + x * radii[r], _selection.Y + y * radii[r] + _epsOffset, time) };
                    circle[(a * radii.Length + r)*4 + 3] = new Point() { Position = new Vector3(_selection.X + x * radii[r], _selection.Y + y * radii[r] - _epsOffset, time) };
                }
            }

            // ~~~~~~~~~~~~ Integrate Pathlines and Adapt ~~~~~~~~~~~~~~~~~~~~~~~~ \\
            // Setup integrator.
            Integrator pathlineIntegrator = Integrator.CreateIntegrator(null, IntegrationType, _cores[_selectedCore], _repulsion);
            pathlineIntegrator.StepSize = StepSize;
            LineSet pathlines;

            // Count out the runs for debugging.

            // ~~~~~~~~~~~~ Integrate Pathlines  ~~~~~~~~~~~~~~~~~~~~~~~~ \\
            #region IntegratePathlines
            // Do we need to load a field first?
            if (_velocity.TimeOrigin > SliceTimeMain || _velocity.TimeOrigin + _velocity.Size.T < SliceTimeMain)
                LoadField(SliceTimeMain, MemberMain);

            // Integrate first few steps.
            pathlineIntegrator.Field = _velocity;
            Console.WriteLine("Starting integration of {0} pathlines", circle.Length);
            pathlines = pathlineIntegrator.Integrate(circle, false, 10)[0];

            // Append integrated lines of next loaded vectorfield time slices.
            //float timeEnd = (float)(12*15) / _everyNthTimestep + SliceTimeMain;
            //while (_currentEndStep + 1 < timeEnd)
            //{
            //    // Don't load more steps than we need to!
            //    int numSteps = (int)Math.Min(timeEnd - _currentEndStep, STEPS_IN_MEMORY);
            //    pathlineIntegrator.Field = null;
            //    LoadField(_currentEndStep, MemberMain, numSteps);

            //    // Integrate further.
            //    pathlineIntegrator.Field = _velocity;
            //    pathlineIntegrator.IntegrateFurther(pathlines);
            //}
            #endregion IntegratePathlines
            Console.WriteLine("Integrated all {0} pathlines", pathlines.Length);
            graph = FieldAnalysis.ComputeFTLE2D(pathlines, new Vector3(_selection, time), angles, radii, time, IntegrationTime);

            return pathlines;

            //            LineSet set = new LineSet(_coreAngleGraph);
            //GeometryWriter.WriteHeightCSV(RedSea.Singleton.DonutFileName + "Angle.csv", set);
            //            GeometryWriter.WriteToFile(RedSea.Singleton.DonutFileName + ".angle", set);

            //            set = new LineSet(_coreDistanceGraph);
            //GeometryWriter.WriteHeightCSV(RedSea.Singleton.DonutFileName + "Distance.csv", set);
            //            GeometryWriter.WriteToFile(RedSea.Singleton.DonutFileName + ".distance", set);
        }
Ejemplo n.º 36
0
 public new void RasterizeCurrentTriangulation(PointSet raster, double defaultZ)
 {
     throw new NotImplementedException("Not implemented for conforming triangulation.");
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Add points this way to see where they will occur on the destination image
 /// </summary>
 /// <param name="name"></param>
 /// <param name="points"></param>
 /// <returns></returns>
 public PointSet AddInvisiblePolygon(string name, PointF[] points)
 {
     PointSet ps = new PointSet(points);
     ps.flags = PointFlags.Invisible;
     ring.Add(name, ps);
     ringList.Add(ps);
     return ps;
 }
Ejemplo n.º 38
0
        public RasterPatch2 GetTilePatch(PointSet pointSet, Box2 regionBox, double iconSize)
        {
            GeoRect tileBox = new GeoRect(
                regionBox.MinCoordinate.X,
                regionBox.MinCoordinate.Y,
                regionBox.MaxCoordinate.X - regionBox.MinCoordinate.X,
                regionBox.MaxCoordinate.Y - regionBox.MinCoordinate.Y);

            int width = 256;
            int height = 256;
            Bitmap resultBitmap = new Bitmap(width, height);
            Graphics graphics = Graphics.FromImage(resultBitmap);

            double minT = 0, maxT = 0, k;
            if (!Double.IsNaN(pointSet.MaxValue))
            {
                minT = pointSet.MinValue;
                maxT = pointSet.MaxValue;
                k = 1.0 / (maxT - minT);
            }
            else
                k = Double.NaN;

            ColorMatrix colorMatrix = new ColorMatrix();
            ImageAttributes imageAttributes = new ImageAttributes();


            for (int i = 0; i < pointSet.Data.Count; i++)
            {
                GeoRect workingRect = new GeoRect(
                            pointSet.Data[i].Longitude - iconSize / 2.0,
                            pointSet.Data[i].Latitude - iconSize / 2.0,
                            iconSize,
                            iconSize);

                if (GeoRect.IntersectionExist(workingRect, tileBox))
                {
                    int x0 = (int)(Math.Min(width, Math.Max(0, pointSet.Data[i].Longitude - iconSize / 2.0 - tileBox.Left) / tileBox.Width * width));
                    int y0 = (int)(Math.Min(height, Math.Max(0, tileBox.Top - pointSet.Data[i].Latitude - iconSize / 2.0) / tileBox.Height * height));

                    int x1 = (int)(Math.Min(width, Math.Max(0, pointSet.Data[i].Longitude + iconSize / 2.0 - tileBox.Left) / tileBox.Width * width));
                    int y1 = (int)(Math.Min(height, Math.Max(0, tileBox.Top - pointSet.Data[i].Latitude + iconSize / 2.0) / tileBox.Height * height));

                    double widthX = Math.Min(tileBox.Width, iconSize);
                    double heightY = Math.Min(tileBox.Height, iconSize);



                    lock (icon)
                    {
                        System.Windows.Media.Color tempColor = System.Windows.Media.Brushes.Red.Color;
                        if (!Double.IsNaN(k))
                        {
                            double hue = 270 * ((maxT - (double)pointSet.Data[i].Value) * k);
                            tempColor = new HsbColor(hue, 1, 1, 0.8).ToArgb();
                        }

                        colorMatrix.Matrix00 = (float)tempColor.R / 255f;
                        colorMatrix.Matrix11 = (float)tempColor.G / 255f;
                        colorMatrix.Matrix22 = (float)tempColor.B / 255f;


                        imageAttributes.SetColorMatrix(colorMatrix,
                                                ColorMatrixFlag.Default,
                                                ColorAdjustType.Bitmap);

                        int x2 = 0;
                        if (pointSet.Data[i].Longitude - iconSize / 2.0 < tileBox.Left)
                        {
                            x2 = icon.Width - (int)((double)(x1 - x0) * icon.Width / (widthX / tileBox.Width * width));
                        }

                        int y2 = 0;
                        if (tileBox.Top - pointSet.Data[i].Latitude - iconSize / 2.0 < 0)
                        {
                            y2 = icon.Height - (int)((double)(y1 - y0) * icon.Height / (heightY / tileBox.Height * height));
                        }

                        graphics.DrawImage(
                            icon,
                            new Rectangle(x0, y0, x1 - x0, y1 - y0),
                            x2,
                            y2,
                            (int)((double)(x1 - x0) * icon.Width / (widthX / tileBox.Width * width)),
                            (int)((double)(y1 - y0) * icon.Height / (heightY / tileBox.Height * height)),
                            GraphicsUnit.Pixel, imageAttributes);
                    }

                }
            }
            return new RasterPatch2(
                    regionBox,
                    resultBitmap,
                    Wgs84CoordinateReferenceSystem.Instance);
        }
Ejemplo n.º 39
0
 public PointSet AddIgnoredPoints(string name, PointF[] points)
 {
     PointSet ps = new PointSet(points);
     ps.flags = PointFlags.Ignored;
     ring.Add(name, ps);
     ringList.Add(ps);
     return ps;
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Needed as approximation when start / end point of desired path are blocked.
 /// </summary>
 public List<MeshNode> GetNearestFreeNodes(Vector2 blockedPoint, Type unitType)
 {
     int pointX = (int)blockedPoint.X;
     int pointY = (int) blockedPoint.Y;
     int meshIndex = DecideMeshIndex(unitType);
     NavigationMesh mesh = mMesh[meshIndex];
     int sectorX = pointX / mesh.mSectorWidth;
     int sectorY = pointY / mesh.mSectorHeight;
     int sectorXOffset = sectorX * mesh.mSectorWidth;
     int sectorYOffset = sectorY * mesh.mSectorHeight;
     int[] indexes = new int[4];
     if (pointX-sectorXOffset < mesh.mSectorWidth)
     {
         indexes[0] = sectorX-1; // Xmin
         indexes[2] = sectorX;   // Xmax
     }
     else
     {
         indexes[0] = sectorX;
         indexes[2] = sectorX+1;
     }
     if (pointY - sectorYOffset < mesh.mSectorHeight)
     {
         indexes[1] = sectorY-1; // Ymin
         indexes[3] = sectorY;   // Ymax
     }
     else
     {
         indexes[1] = sectorY;
         indexes[3] = sectorY+1;
     }
     for (int i = 0; i < 4; i+=2 )
     {
         if (indexes[i] < 0) indexes[i] = 0;
         if (indexes[i] >= mesh.mSectorColumns)
             indexes[i] = mesh.mSectorColumns - 1;
     }
     for (int i = 1; i < 4; i += 2)
     {
         if (indexes[i] < 0) indexes[i] = 0;
         if (indexes[i] >= mesh.mSectorRows)
             indexes[i] = mesh.mSectorRows - 1;
     }
     // Now go on meshnode hunt in the specified sectors:
     SortedList<double, MeshNode> nodes = new SortedList<double, MeshNode>(new MyComparer());
     PointSet<float> nodesExist = new PointSet<float>();
     double minDistance = double.MaxValue;
     for (int y = indexes[1]; y <= indexes[3]; y++)
         for (int x = indexes[0]; x <= indexes[2]; x++ )
             MeshNodeHunt(mesh.GetSectors()[x,y], blockedPoint, ref minDistance, nodes, nodesExist);
     return new List<MeshNode>(nodes.Values);
 }
Ejemplo n.º 41
0
        public List<Renderable> ComputeStatistics()
        {
            List<Renderable> result = new List<Renderable>(200);
            result.Add(new FieldPlane(Plane, Velocity.GetTimeSlice(_currentSetting.SliceTimeMain), _currentSetting.Shader, _currentSetting.Colormap));

            if (!_initialized)
                return result;

            result.Add(new LineBall(Plane, new LineSet(new Line[] { new Line() { Positions = new Vector3[] { _startSelection, _endSelection } } })));

            bool completelyNew = false;
            // ~~~~~~~~~~~~~~ Get new Start Points ~~~~~~~~~~~~~~ //
            if (_lastSetting == null ||
                SliceTimeMainChanged ||
                LineXChanged ||
                _selectionChanged)
            {
                int numPoints = _startSelection == null ? 0 : Math.Max(2, _currentSetting.LineX + 1);
                Point[] startPoints = new Point[numPoints];

                // Compute point positions (linear interpolation).
                for (int x = 0; x < numPoints; ++x)
                {
                    float t = (float)x / (numPoints - 1);
                    startPoints[x] = new Point()
                    {
                        Position = _startSelection * (1.0f - t) + _endSelection * t
                    };
                }
                _linePoints = new PointSet<Point>(startPoints);
                _values = new float[_linePoints.Length];

                completelyNew = true;
            }

            // ~~~~~~~~~~~~ Compute Selected Measure ~~~~~~~~~~~~ //
            if (completelyNew ||
                MeasureChanged ||
                FlatChanged ||
                IntegrationTimeChanged ||
                IntegrationTypeChanged ||
                StepSizeChanged)
            {
                // ~~~~~~~~~~~~~ Compute Scalar FIeld ~~~~~~~~~~~~~~~ //
                ScalarField measure = null;
                switch (_currentSetting.Measure)
                {
                    // Velocity Length / Pathline Length.
                    case RedSea.Measure.VELOCITY:
                        measure = new VectorField(Velocity.GetTimeSlice(_currentSetting.SliceTimeMain), FieldAnalysis.VFLength, 1).Scalars[0] as ScalarField;
                        break;
                    case RedSea.Measure.SURFACE_HEIGHT:
                        break;
                    case RedSea.Measure.SALINITY:
                        break;
                    case RedSea.Measure.TEMPERATURE:
                        break;
                    case RedSea.Measure.DIVERGENCE:
                        measure = new VectorField(Velocity.GetTimeSlice(_currentSetting.SliceTimeMain), FieldAnalysis.Divergence, 1).Scalars[0] as ScalarField;
                        break;
                    // Closeness of Pathline.
                    case RedSea.Measure.DIVERGENCE_2D:
                        break;
                    case RedSea.Measure.VORTICITY:
                        measure = new VectorField(Velocity.GetTimeSlice(_currentSetting.SliceTimeMain), FieldAnalysis.Vorticity, 1).Scalars[0] as ScalarField;
                        break;
                    case RedSea.Measure.SHEAR:
                        measure = new VectorField(Velocity.GetTimeSlice(_currentSetting.SliceTimeMain), FieldAnalysis.Shear, 1).Scalars[0] as ScalarField;
                        break;
                }

                // ~~~~~~~~~~~~~~~~ Sample Field ~~~~~~~~~~~~~~~~~~~ //
                switch (_currentSetting.Measure)
                {
                    // Velocity Length / Pathline Length.
                    case RedSea.Measure.VELOCITY:
                        if (_currentSetting.IntegrationTime == 0)
                        {
                            for (int index = 0; index < _values.Length; ++index)
                            {
                                _values[index] = measure.Sample(((Vec3)_linePoints.Points[index].Position).ToVec2());
                            }
                        }
                        else
                        {
                            VectorField.Integrator integrator = VectorField.Integrator.CreateIntegrator(Velocity, _currentSetting.IntegrationType);
                            integrator.Direction = Sign.POSITIVE;
                            integrator.StepSize = _currentSetting.StepSize;

                            LineSet line = integrator.Integrate(_linePoints, _currentSetting.Flat, _currentSetting.IntegrationTime)[0];
                            for (int index = 0; index < _values.Length; ++index)
                            {
                                _values[index] = line.Lines[index].LineLength;
                            }
                            result.Add(new LineBall(Plane, line));
                        }
                        break;
                    // Simply sample a field.
                    case RedSea.Measure.SURFACE_HEIGHT:
                    case RedSea.Measure.SALINITY:
                    case RedSea.Measure.TEMPERATURE:
                    case RedSea.Measure.DIVERGENCE:
                    case RedSea.Measure.VORTICITY:
                    case RedSea.Measure.SHEAR:
                        for (int index = 0; index < _values.Length; ++index)
                        {
                            _values[index] = measure.Sample(((Vec3)_linePoints.Points[index].Position).ToVec2());
                        }
                        break;
                    // Closeness of Pathline.
                    case RedSea.Measure.DIVERGENCE_2D:

                        break;
                }
                completelyNew = true;
            }

            //if (completelyNew ||
            //    AlphaStableChanged ||
            //    LineSettingChanged)
            //{
                // ~~~~~~~~~~~~~~~~ Display the Graph ~~~~~~~~~~~~~~~ //
                result.Add(FieldAnalysis.BuildGraph(Plane, _linePoints, _values, _currentSetting.AlphaStable, _currentSetting.LineSetting));
            //}
            _selectionChanged = false;
            return result;
        }
Ejemplo n.º 42
0
 /// <summary>
 /// Sets the nodes near a position as blocked (or unblocked, if given
 /// removeInstead is true).
 /// "radius = 0" will block one node = 4 squares.
 /// </summary>
 /// <param name="blocked">the list of impassable coords</param>
 /// <param name="scale">the mesh scale</param>
 /// <param name="position">the position of the obstruction</param>
 /// <param name="radius">distance limit up to which nodes are marked as blocked</param>
 /// <param name="removeInstead">if the nodes should be unblocked instead</param>
 private void BlockCircularArea(PointSet<int> blocked, int scale, Vector2 position, int radius, bool removeInstead = false)
 {
     int x = (int)(position.X) / scale;
     int y = (int)(position.Y) / scale;
     int scaledRadius = radius / scale;
     if (!removeInstead)
         for (int i = -scaledRadius; i <= scaledRadius; i++)
         {
             for (int j = (int)(-Math.Sqrt(scaledRadius * scaledRadius - i * i));
                   j <= (int)(Math.Sqrt(scaledRadius * scaledRadius - i * i)); j++)
             {
                 blocked.Add(x + i, y + j);
             }
         }
     else
     {
         for (int i = -scaledRadius; i <= scaledRadius; i++)
         {
             for (int j = (int)(-Math.Sqrt(scaledRadius * scaledRadius - i * i));
                   j <= (int)(Math.Sqrt(scaledRadius * scaledRadius - i * i)); j++)
             {
                 blocked.Remove(x + i, y + j);
             }
         }
     }
 }
Ejemplo n.º 43
0
 public void WritePointSet(PointSet pointSet)
 {
     throw new NotImplementedException();
 }
        public static void DRV_Matching_Test()
        {
            int dim       = 8;
            int npoint    = 100000;
            int testcases = 10;
            int dws       = 10;
            int K         = 20;
            int maxSearch = 500;
            int ntrees    = 3;

            Random   random = new Random();
            PointSet ps     = new PointSet(dim);

            for (int i = 0; i < npoint; i++)
            {
                ps.AddPoint(new Point(dim, random));
            }

            //Indexes
            var bruteForce = new BruteForce(ps);

            var standardTree_r = new KDTree(ps, true);
            var standardTree   = new KDTree(ps, false);

            var standardForest_r = new KDTreeForest(ntrees, ps, true);
            var standardForest   = new KDTreeForest(ntrees, ps, false);

            //Result holders
            var bruteforceDist = new List <double>();

            var standardDist = new List <double>();
            var queryDist    = new List <double>();

            var standardDist_r = new List <double>();
            var queryDist_r    = new List <double>();

            var standardDist_f = new List <double>();
            var queryDist_f    = new List <double>();

            var standardDist_r_f = new List <double>();
            var queryDist_r_f    = new List <double>();

            for (int i = 0; i < dws; i++)
            {
                Console.WriteLine(i);
                var querydw = new DimWeight(dim, random);

                var queryTree   = new KDTree(ps, querydw, false);
                var queryTree_r = new KDTree(ps, querydw, true);

                var queryForest   = new KDTreeForest(ntrees, ps, querydw, false);
                var queryForest_r = new KDTreeForest(ntrees, ps, querydw, true);

                for (int j = 0; j < testcases; j++)
                {
                    var p = new Point(dim, random);
                    //bruteforceDist.Add(bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw));
                    var bfd = bruteForce.GetKNN(p, K, querydw).GetMeanDistance(p, querydw);

                    standardDist.Add(standardTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    queryDist.Add(queryTree.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);

                    standardDist_r.Add(standardTree_r.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    queryDist_r.Add(queryTree_r.root.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);

                    //Forests

                    standardDist_f.Add(standardForest.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    queryDist_f.Add(queryForest.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);

                    standardDist_r_f.Add(standardForest_r.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                    queryDist_r_f.Add(queryForest_r.GetANN(p, K, maxSearch, querydw).GetMeanDistance(p, querydw) / bfd - 1);
                }
            }

            //Console.WriteLine(bruteforceDist.Average());
            Console.WriteLine(standardDist.Average() + " " + queryDist.Average());
            Console.WriteLine(standardDist_r.Average() + " " + queryDist_r.Average());
            Console.WriteLine(standardDist_f.Average() + " " + queryDist_f.Average());
            Console.WriteLine(standardDist_r_f.Average() + " " + queryDist_r_f.Average());

            //Console.WriteLine(standardDist.Max() + " " + queryDist.Max());
            //Console.WriteLine(standardDist_r.Max() + " " + queryDist_r.Max());
            //Console.WriteLine(standardDist_f.Max() + " " + queryDist_f.Max());
            //Console.WriteLine(standardDist_r_f.Max() + " " + queryDist_r_f.Max());
        }
Ejemplo n.º 45
0
 /// <summary>
 /// Removes all obstructions and resets the mesh(es) to null.
 /// </summary>
 public void ClearObstructions()
 {
     mObstructions.Clear();
     for (int i = 0; i < 3; i++ )
         mBlocked[i] = new PointSet<int>();
     if (mMesh != null)
     {
         Debug.WriteLine("You deleted all obstructions. The Navigation Mesh is now outdated and has been deleted.");
         mMesh = null;
     }
 }
        public static void ComputeMinAreaEnclosingRectangle(ObjectId[] idArray, CoordinateSystem actualCS)
        {
            Editor        editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database      workingDatabase = HostApplicationServices.WorkingDatabase;
            ProgressMeter progressMeter   = new ProgressMeter();
            MessageFilter value           = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(value);
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    progressMeter.SetLimit(idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        progressMeter.Start("Computing min. area rectangle...");
                    }
                    CoordinateTransformator coordinateTransformator = new CoordinateTransformator(CoordinateSystem.Global(), actualCS);
                    CoordinateTransformator inverseTransformation   = coordinateTransformator.GetInverseTransformation();
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        progressMeter.MeterProgress();
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        coordinateTransformator.Transform(point);
                        pointSet.Add(point);
                    }
                    ConvexHull2d convexHull2d = new ConvexHull2d();
                    convexHull2d.InitialPoints = pointSet;
                    convexHull2d.ComputeHull();
                    PointSet vertices = convexHull2d.Vertices;
                    double   z        = vertices[0].Z;
                    for (int j = 0; j < vertices.Count; j++)
                    {
                        vertices[j].Z = z;
                    }
                    BoundingRectangle boundingRectangle = convexHull2d.MinimumAreaEnclosingRectangle();
                    PointSet          vertices2         = boundingRectangle.GetVertices();
                    for (int k = 0; k < vertices2.Count; k++)
                    {
                        inverseTransformation.Transform(vertices2[k]);
                    }
                    Point3dCollection point3dCollection = Conversions.ToPoint3dCollection(vertices2.ToList());
                    Polyline3d        polyline3d        = new Polyline3d(0, point3dCollection, true);
                    polyline3d.LayerId = (layerId);
                    blockTableRecord.AppendEntity(polyline3d);
                    transaction.AddNewlyCreatedDBObject(polyline3d, true);
                    editor.WriteMessage("\nMinimum area enclosing rectangle properties:");
                    editor.WriteMessage("\n--------------------------------------------");
                    editor.WriteMessage("\nWidth           : " + boundingRectangle.Width.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nHeight          : " + boundingRectangle.Length.ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nArea            : " + (boundingRectangle.Length * boundingRectangle.Width).ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nPerimeter length: " + (2.0 * boundingRectangle.Length + 2.0 * boundingRectangle.Width).ToString(DBManager.GetFormatFromLUPREC()));
                    transaction.Commit();
                }
                progressMeter.Stop();
            }
            catch (System.Exception ex)
            {
                progressMeter.Stop();
                throw;
            }
        }
 /// <summary>
 /// Changes given pointset
 /// </summary>
 /// <param name="pointSet">pointset to be changed</param>
 abstract public PointSet Operate(PointSet pointSet);
Ejemplo n.º 48
0
        public void Compute3dHull(ObjectId[] idArray)
        {
            Editor   editor          = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            Database workingDatabase = HostApplicationServices.WorkingDatabase;

            DBManager.SetEpsilon();
            this.progressMeter_0 = new ProgressMeter();
            this.messageFilter_0 = new MessageFilter();
            System.Windows.Forms.Application.AddMessageFilter(this.messageFilter_0);
            this.int_0 = 0;
            try
            {
                using (Transaction transaction = workingDatabase.TransactionManager.StartTransaction())
                {
                    this.progressMeter_0.SetLimit(3 * idArray.Length);
                    if ((double)idArray.Length > 10000.0)
                    {
                        this.progressMeter_0.Start("Computing 3d hull...");
                    }
                    BlockTable       blockTable       = (BlockTable)transaction.GetObject(workingDatabase.BlockTableId, (OpenMode)1);
                    BlockTableRecord blockTableRecord = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], (OpenMode)1);
                    ObjectId         layerId          = DBManager.CurrentLayerId();
                    DBManager.CurrentLayerName();
                    PointSet pointSet = new PointSet();
                    for (int i = 0; i < idArray.Length; i++)
                    {
                        DBPoint dBPoint = (DBPoint)transaction.GetObject(idArray[i], (OpenMode)0, true);
                        Point   point   = new Point(dBPoint.Position.X, dBPoint.Position.Y, dBPoint.Position.Z);
                        pointSet.Add(point);
                        this.vmethod_0(null, null);
                    }
                    ConvexHull3d convexHull3d = new ConvexHull3d();
                    convexHull3d.PointInsertionHandler += new HullPointInsertionEventHandler(this.vmethod_0);
                    convexHull3d.InitialPoints          = pointSet;
                    convexHull3d.ComputeHull();
                    PointSet        vertices  = convexHull3d.Vertices;
                    List <Triangle> triangles = convexHull3d.Triangles;
                    for (int j = 0; j < triangles.Count; j++)
                    {
                        Point   vertex   = triangles[j].Vertex1;
                        Point   vertex2  = triangles[j].Vertex2;
                        Point   vertex3  = triangles[j].Vertex3;
                        Point3d point3d  = new Point3d(vertex.X, vertex.Y, vertex.Z);
                        Point3d point3d2 = new Point3d(vertex2.X, vertex2.Y, vertex2.Z);
                        Point3d point3d3 = new Point3d(vertex3.X, vertex3.Y, vertex3.Z);
                        Face    face     = new Face(point3d, point3d2, point3d3, true, true, true, true);
                        face.LayerId = (layerId);
                        blockTableRecord.AppendEntity(face);
                        transaction.AddNewlyCreatedDBObject(face, true);
                    }
                    editor.WriteMessage("\n3d convex hull properties:");
                    editor.WriteMessage("\n--------------------------");
                    editor.WriteMessage("\nNumber of vertices on hull: " + vertices.Count);
                    editor.WriteMessage("\nNumber of invalid vertices: " + convexHull3d.BadPoints.Count);
                    editor.WriteMessage("\nNumber of faces on hull   : " + triangles.Count);
                    editor.WriteMessage("\nNumber of degenerate faces: " + convexHull3d.NumberOfDegenerateTriangles);
                    editor.WriteMessage("\nHull surface area         : " + convexHull3d.Area().ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nHull volume               : " + convexHull3d.Volume().ToString(DBManager.GetFormatFromLUPREC()));
                    editor.WriteMessage("\nCenter of mass            : " + convexHull3d.CenterOfMass().ToString());
                    transaction.Commit();
                }
                this.progressMeter_0.Stop();
            }
            catch (System.Exception ex)
            {
                this.progressMeter_0.Stop();
                throw;
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// This does the actual work for CalculatePath(). CalculatePath() did just
        /// determine all the parameters for it.
        /// </summary>
        private Path CalculatePath2(Vector2 end, MeshNode startMeshNode, List<MeshNode> firstNeighbours, Polygon endPolygon, List<MeshNode> endNodes, bool startPassable, bool endPassable)
        {
            Debug.Assert(mMesh != null, "There is no navigation mesh! Load a map and then call PathFinder.GetInstance().LoadMeshFromObstructions().");
            // uses A* algorithm
            // !! remember to distinguish between latest costs (costs up to that point)
            // !! and heuristic costs (estimated path costs over that point to target)
            // I use AStarNode instead of MeshNode / Vector2 because I have to save
            // additional information, like predecessor and latest costs.
            // WorkingQueue should be in ascending order
            // of heuristic value. I use my own comparer to allow multiple
            // equal keys (since we may have nodes with the same heuristic value).
            MinHeap<AStarNode> workingQueue = new MinHeap<AStarNode>();
            // workingQueue doesn't support a quick check if some coords are
            // already contained, so we handle that with a corresp. structure:
            PointSet<float> workingCoords = new PointSet<float>();
            PointSet<float> exploredCoords = new PointSet<float>();

            // TODO: Evaluate First Loop iteration separately
            double startCostsToEnd = HelperMethods.EuklidDistance(startMeshNode.mVector, end);
            AStarNode current = new AStarNode(0, startCostsToEnd, startMeshNode, null);
            if (EndConditionMet(current, endPassable, endPolygon, endNodes))
                return HandleEnding(current, end, startPassable, endPassable, endPolygon);
            exploredCoords.Add(startMeshNode.mVector.X, startMeshNode.mVector.Y);
            HandleNeighbours(current, firstNeighbours, workingQueue, workingCoords, exploredCoords, end);
            // TODO: First iteration evaluation finished

            while (workingQueue.Count > 0)
            {
                //Debug.WriteLine("No. of nodes in the workingQueue: "+workingQueue.Count);
                //OutputHeuristics(workingQueue);
                current = GetNextNodeFromWorkingQueue(workingQueue, workingCoords);

                //Debug.WriteLine("Now examining "+current.mNode.mVector.X+","+current.mNode.mVector.Y);
                if (EndConditionMet(current, endPassable, endPolygon, endNodes))
                    return HandleEnding(current, end, startPassable, endPassable, endPolygon);

                // The shortest path to current has been found,
                // so we won't have to touch it ever again!
                exploredCoords.Add(current.mNode.mVector.X, current.mNode.mVector.Y);
                //Debug.WriteLine("Explored " + current.mNode.mVector.X + "," + current.mNode.mVector.Y);

                // Add all unexplored unblocked neighbours to workingQueue:
                List<MeshNode> neighbours = GetNeighbours2(current.mNode);
                HandleNeighbours(current, neighbours, workingQueue, workingCoords, exploredCoords, end);
            }

            // Working queue got empty, but we still didn't reach our target
            // -> No path found
            Debug.WriteLine("WARNING - Pathfinder: No path found!");
            return null;
        }
Ejemplo n.º 50
0
    public void Create(Func<IEnumerable<SwapsSummaryRow>> func_)
    {
      m_func = func_;
      cmbXAxis.AddItems(typeof(StatCols), true);
      cmbXAxis.Bind(m_args, "XAxis", new Validators.EnumDescValidator(StatCols.CombinedStat));
      cmbYAxis.AddItems(typeof(StatCols), true);
      cmbYAxis.Bind(m_args, "YAxis", new Validators.EnumDescValidator(StatCols.CombinedStat));

      m_args.PropertyChanged += (x, y) => ReRead();

      m_scatter = new Controls.ScatterPlot();
      m_scatter.Dock = DockStyle.Fill;
      m_scatter.SetXAxisFormat("<DATA_VALUE:##0.##>");
      m_scatter.ToolTipFormat_X = "##0.##";
      m_scatter.SetYAxisFormat("<DATA_VALUE:##0.##>");
      m_scatter.ToolTipFormat_Y = "##0.##";
      m_scatter.DontAdjustFillSceneGraph = true;
      panel1.ClientArea.Controls.Add(m_scatter);

      m_scatter.Chart.FillSceneGraph += (a, b) =>
        {
          if (Selected == null) return;

          try
          {
            var pointSet = b.SceneGraph.OfType<Primitive>().FirstOrDefault(p => p is PointSet) as PointSet;

            if (pointSet != null)
            {
              var newPoints = new List<DataPoint>();
              foreach (var point in pointSet.points)
              {
                foreach (var s in Selected)
                {
                  if (point.DataPoint.Label.Equals(s.Inst))
                  {
                    var p = new DataPoint(point.point);
                    point.PE.Fill = Color.Red;
                    newPoints.Add(p);
                    break;
                  }
                }
              }

              PointSet highValues = new PointSet(newPoints.ToArray(), Font, 'X');
              highValues.PE.Fill = Color.Red;
              highValues.icon = Infragistics.UltraChart.Shared.Styles.SymbolIcon.X;
              highValues.iconSize = Infragistics.UltraChart.Shared.Styles.SymbolIconSize.Large;

              b.SceneGraph.Add(highValues);

            }

          }
          catch (Exception ex_)
          {
            Logger.Error("Error finding selected item to highlight", typeof(StatContScatter), ex_);
          }

        };

    }
Ejemplo n.º 51
0
        /// <summary>
        /// Neighbour handling of our AStar algorithm.
        /// </summary>
        private void HandleNeighbours(AStarNode current, List<MeshNode> neighbours, MinHeap<AStarNode> workingQueue, PointSet<float> workingCoords, PointSet<float> exploredCoords, Vector2 end)
        {
            foreach (MeshNode neighbour in neighbours)
            {

                // neighbour will be added if neither in workingQueue(workingCoords) nor exploredCoords
                if (!exploredCoords.Contains(neighbour.mVector.X, neighbour.mVector.Y) && !workingCoords.Contains(neighbour.mVector.X, neighbour.mVector.Y))
                {
                    double neighbourCostsToEnd = HelperMethods.EuklidDistance(neighbour.mVector, end);
                    double neighbourLatestCosts =
                        current.mLatestCosts + HelperMethods.EuklidDistance(current.mNode.mVector, neighbour.mVector);
                    AStarNode neighbour2 = new AStarNode(neighbourLatestCosts, neighbourCostsToEnd, neighbour, current);

                    // add neighbour with its heuristic value to workingQueue:
                    workingQueue.Add(HeuristicValue(neighbour2), neighbour2);
                    workingCoords.Add(neighbour.mVector.X, neighbour.mVector.Y);
                }
            }
        }
Ejemplo n.º 52
0
        public void ReconstructSurface(ProgressMeter pm, int relevantDecimals)
        {
            Editor        arg_0F_0      = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            MessageFilter messageFilter = new MessageFilter();

            System.Windows.Forms.Application.AddMessageFilter(messageFilter);
            PointSet pointSet = new PointSet();

            for (int i = 0; i < this.Edges.Count; i++)
            {
                messageFilter.CheckMessageFilter((long)i, 10000);
                this.Edges[i].StartPoint.Round(relevantDecimals);
                this.Edges[i].EndPoint.Round(relevantDecimals);
                pointSet.Add(this.Edges[i].StartPoint);
                pointSet.Add(this.Edges[i].EndPoint);
            }
            pointSet.RemoveMultiplePoints3d();
            pointSet.Sort();
            this.Vertices = pointSet.ToList();
            List <SurfaceReconstruction.IndexedEdge> list = new List <SurfaceReconstruction.IndexedEdge>();

            for (int j = 0; j < this.Edges.Count; j++)
            {
                messageFilter.CheckMessageFilter((long)j, 10000);
                int num = this.Vertices.BinarySearch(this.Edges[j].StartPoint);
                if (num < 0)
                {
                    num = ~num;
                    int num2 = Math.Max(0, num - 1);
                    if (this.Edges[num].DistanceTo(this.Edges[j].StartPoint) > this.Edges[num2].DistanceTo(this.Edges[j].StartPoint))
                    {
                        num = num2;
                    }
                }
                int num3 = this.Vertices.BinarySearch(this.Edges[j].EndPoint);
                if (num3 < 0)
                {
                    num3 = ~num3;
                    int num4 = Math.Max(0, num3 - 1);
                    if (this.Edges[num3].DistanceTo(this.Edges[j].EndPoint) > this.Edges[num4].DistanceTo(this.Edges[j].EndPoint))
                    {
                        num3 = num4;
                    }
                }
                list.Add(new SurfaceReconstruction.IndexedEdge(num, num3));
            }
            list = SurfaceReconstruction.IndexedEdge.RemoveDuplicates(list);
            list = SurfaceReconstruction.IndexedEdge.RemoveZeros(list);
            SurfaceReconstruction.DirectedCyclicGraph directedCyclicGraph = new SurfaceReconstruction.DirectedCyclicGraph();
            for (int k = 0; k < list.Count; k++)
            {
                directedCyclicGraph.Add(list[k]);
            }
            pm.SetLimit(directedCyclicGraph.Count);
            if (directedCyclicGraph.Count > 10000)
            {
                pm.Start("Scanning for faces");
            }
            int num5 = 0;

            foreach (int current in directedCyclicGraph.Keys)
            {
                messageFilter.CheckMessageFilter((long)num5, 1000);
                if (directedCyclicGraph.Count > 10000)
                {
                    pm.MeterProgress();
                }
                num5++;
                SurfaceReconstruction.Node node = directedCyclicGraph[current];
                foreach (SurfaceReconstruction.Node current2 in node.Children)
                {
                    foreach (SurfaceReconstruction.Node current3 in current2.Children)
                    {
                        if (current3.Number != node.Number)
                        {
                            bool flag = false;
                            foreach (SurfaceReconstruction.Node current4 in current3.Children)
                            {
                                if (current4.Number != current2.Number && current4.Number == node.Number)
                                {
                                    this.Tris.Add(new SurfaceReconstruction.Tri(node.Number, current2.Number, current3.Number));
                                    flag = true;
                                    break;
                                }
                            }
                            if (!flag)
                            {
                                foreach (SurfaceReconstruction.Node current5 in current3.Children)
                                {
                                    if (current5.Number != current2.Number && !current5.Children.Contains(current2))
                                    {
                                        foreach (SurfaceReconstruction.Node current6 in current5.Children)
                                        {
                                            if (current6.Number != current3.Number && current6.Number == node.Number)
                                            {
                                                this.Quads.Add(new SurfaceReconstruction.Quad(node.Number, current2.Number, current3.Number, current5.Number));
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            SurfaceReconstruction.Tri.RemoveDuplicates(ref this.Tris);
            SurfaceReconstruction.Quad.RemoveDuplicates(ref this.Quads);
            pm.Stop();
        }
Ejemplo n.º 53
0
		public static void Triangulate(PointSet ps) {
			Triangulate(_defaultAlgorithm, ps);
		}
Ejemplo n.º 54
0
        public void CanAddNormals()
        {
            var r       = new Random();
            var storage = PointSetTests.CreateStorage();

            var ps = new V3d[10000].SetByIndex(_ => new V3d(r.NextDouble(), r.NextDouble(), r.NextDouble()));

            var pointset = PointSet
                           .Create(storage, "test", ps.ToList(), null, null, null, 5000, false, CancellationToken.None)
                           .GenerateLod(ImportConfig.Default.WithKey("lod").WithOctreeSplitLimit(5000))
            ;

            storage.Add("pss", pointset, CancellationToken.None);

            var withNormals = WithRandomNormals(pointset.Root.Value);

            storage.Add("psWithNormals", withNormals, CancellationToken.None);

            withNormals.ForEachNode(true, node =>
            {
                if (node.IsLeaf)
                {
                    Assert.IsTrue(node.HasNormals);
                    Assert.IsTrue(!node.HasLodNormals);
                    Assert.IsTrue(node.Normals.Value.Length == node.PointCount);
                }
                else
                {
                    Assert.IsTrue(!node.HasNormals);
                    Assert.IsTrue(node.HasLodNormals);
                    Assert.IsTrue(node.LodNormals.Value.Length == node.LodPointCount);
                }

                //
                var binary = node.ToBinary();
                var node2  = PointSetNode.ParseBinary(binary, storage);
                Assert.IsTrue(node.HasNormals == node2.HasNormals);
                Assert.IsTrue(node.HasLodNormals == node2.HasLodNormals);
                Assert.IsTrue(node.Normals?.Value?.Length == node2.Normals?.Value?.Length);
                Assert.IsTrue(node.LodNormals?.Value?.Length == node2.LodNormals?.Value?.Length);
            });

            PointSetNode WithRandomNormals(PointSetNode n)
            {
                var id = Guid.NewGuid();
                var ns = new V3f[n.IsLeaf ? n.PointCount : n.LodPointCount].Set(V3f.OOI);

                storage.Add(id, ns, CancellationToken.None);

                if (n.IsLeaf)
                {
                    var m = n.WithNormals(id);
                    return(m);
                }
                else
                {
                    var subnodes = n.Subnodes.Map(x => x != null ? WithRandomNormals(x.Value) : null);
                    var m        = n.WithLodNormals(id, subnodes);
                    return(m);
                }
            }
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Setting up the vertex buffer. Vertex size and number has to be known.
        /// </summary>
        /// <param name="origin"></param>
        /// <param name="xAxis"></param>
        /// <param name="yAxis"></param>
        /// <param name="scale"></param>
        protected void GenerateGeometry(Plane plane, PointSet<Point> points)
        {
            // Write poition and UV-map data.
            var stream = new DataStream(_numVertices * _vertexSizeBytes, true, true);
            Vector3 zAxis = plane.ZAxis;
            foreach(Point point in points.Points)
            {
                var test = new Vector4(plane.Origin + (plane.XAxis * point.Position[0] + plane.YAxis * point.Position[1] + zAxis * point.Position[2]), 1.0f);
                stream.Write(new Vector4(plane.Origin + (plane.XAxis * point.Position[0] + plane.YAxis * point.Position[1] + zAxis * point.Position[2]), 1.0f));
                stream.Write(point.Color);
                stream.Write(point.Radius * plane.PointSize);
            }
            stream.Position = 0;

            // Create and fill buffer.
            _vertices = new Buffer(Renderable._device, stream, new BufferDescription()
            {
                BindFlags = BindFlags.VertexBuffer,
                CpuAccessFlags = CpuAccessFlags.None,
                OptionFlags = ResourceOptionFlags.None,
                SizeInBytes = _numVertices * _vertexSizeBytes,
                Usage = ResourceUsage.Default
            });
            stream.Dispose();
        }
Ejemplo n.º 56
0
 public static void Triangulate(PointSet ps)
 {
     Triangulate(_defaultAlgorithm, ps);
 }
 public void OnLeftMouseUp()
 {
     pointSetWithSelection = null;
 }
Ejemplo n.º 58
0
        public void UserInterface()
        {
            Editor editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            this.messageFilter = new MessageFilter();
            System.Windows.Forms.Application.AddMessageFilter(this.messageFilter);
            try
            {
                PointSet   pointSet  = new PointSet();
                ObjectId[] objectIDs = CommandLineQuerries.GetObjectIDs(CommandLineQuerries.EntityType.POINT, "Select triangulation points", false);
                if (objectIDs != null)
                {
                    string text = " triangulation point";
                    if (objectIDs.Length > 1)
                    {
                        text += "s";
                    }
                    editor.WriteMessage(objectIDs.Length + text + " selected.");
                    pointSet.Add2(Conversions.ToCeometricPointSet2(objectIDs));
                }
                else
                {
                    editor.WriteMessage("No triangulation points selected.\n");
                }
                List <Constraint> list       = new List <Constraint>();
                ObjectId[]        objectIDs2 = CommandLineQuerries.GetObjectIDs(CommandLineQuerries.EntityType.LINE, "Select constraints (lines)", false);
                if (objectIDs2 != null)
                {
                    string text2 = " constraint";
                    if (objectIDs2.Length > 1)
                    {
                        text2 += "s";
                    }
                    editor.WriteMessage(objectIDs2.Length + text2 + " selected.");
                    List <Edge> list2 = Conversions.ToCeometricEdgeList(objectIDs2);
                    for (int i = 0; i < list2.Count; i++)
                    {
                        list.Add(new Constraint(list2[i], Constraint.ConstraintType.Constraint));
                    }
                }
                else
                {
                    editor.WriteMessage("No constraints selected.\n");
                }
                if (pointSet.Count == 0 && list.Count == 0)
                {
                    throw new ArgumentException("No triangulation points nor constraints.");
                }
                List <Constraint> bo  = new List <Constraint>();
                int        plCount    = 0;
                ObjectId[] objectIDs3 = CommandLineQuerries.GetObjectIDs(CommandLineQuerries.EntityType.PLINES, "Select boundaries (polylines)", false);
                if (objectIDs3 != null)
                {
                    string text3 = " boundary";
                    if (objectIDs3.Length > 1)
                    {
                        text3 += "s";
                    }
                    editor.WriteMessage(objectIDs3.Length + text3 + " selected.");
                    plCount = this.getPolylineCount(objectIDs3);
                    List <Edge> list4 = Conversions.ToCeometricEdgeList(objectIDs3);
                    for (int j = 0; j < list4.Count; j++)
                    {
                        bo.Add(new Constraint(list4[j], Constraint.ConstraintType.Boundary));
                    }
                }
                else
                {
                    editor.WriteMessage("No boundaries selected.\n");
                }
                if (list.Count > 0)
                {
                    Triangulate.int_0 = CommandLineQuerries.SpecifyInteger("Maximum feasible constraint violations", Triangulate.int_0, 0, 2147483647, false, true);
                }
                editor.WriteMessage("\nInitial triangulation:");
                editor.WriteMessage("\n----------------------");
                editor.WriteMessage("\nInitial triangulation points  : " + pointSet.Count);
                editor.WriteMessage("\nInitial constraints           : " + list.Count);
                editor.WriteMessage("\nNumber of boundary regions    : " + plCount);
                editor.WriteMessage("\nInitial boundary segments     : " + bo.Count);
                editor.WriteMessage("\n");
                this.TriangulateInternal(pointSet, list, bo, null);
            }
            catch (System.Exception ex)
            {
                editor.WriteMessage("\n" + ex.Message);
            }
            finally
            {
                try
                {
                    this.progressMeter_0.Stop();
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("feef");
                }
                try
                {
                    this.pane_0.Text    = ("");
                    this.pane_0.Visible = (false);
                    Autodesk.AutoCAD.ApplicationServices.Application.StatusBar.Update();
                    Autodesk.AutoCAD.ApplicationServices.Application.StatusBar.Panes.Remove(this.pane_0);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("efefe");
                }
                System.Windows.Forms.Application.DoEvents();
            }
        }
 /// <summary>
 /// Adds a PointSet.
 /// </summary>
 /// <param name="newPointSet">New point set</param>
 public void AddPointSet(PointSet newPointSet)
 {
     newPointSet.InitGraphicsRessource(GraphicsDevice);
     pointSets.Add(newPointSet);
 }
Ejemplo n.º 60
0
        private Edge method_3(Edge edge_0, Triangle triangle_0)
        {
            List <Edge> edges = triangle_0.Edges;
            List <Edge> list  = new List <Edge>();
            List <Edge> list2 = new List <Edge>();
            int         num   = 0;
            int         num2  = 0;
            int         num3  = 0;
            int         num4  = 0;
            int         num5  = 0;

            for (int i = 0; i < 3; i++)
            {
                double num6 = Predicate.IntersectsExact(edge_0, edges[i]);
                if (num6 == -1.0)
                {
                    num3++;
                }
                else if (num6 == 1.0)
                {
                    list.Add(edges[i]);
                }
                else if (num6 == 0.0)
                {
                    num4++;
                }
                else if (num6 == 2.0)
                {
                    num5++;
                }
                else
                {
                    if (!double.IsNaN(num6))
                    {
                        throw new NotImplementedException("Unexpected predicate return value in case C:  " + num6.ToString());
                    }
                    list2.Add(edges[i]);
                }
                num  = list.Count;
                num2 = list2.Count;
            }
            bool flag = false;

            if (num3 == 1 && num == 2)
            {
                flag = true;
            }
            else if (num == 1 && num4 == 2)
            {
                flag = true;
            }
            else if (num3 == 1 && num4 == 2)
            {
                flag = true;
            }
            else if (num2 == 1 && num3 == 2)
            {
                flag = true;
            }
            else if (num2 == 1 && num4 == 2)
            {
                flag = true;
            }
            else if (num3 == 3)
            {
                flag = true;
            }
            if (!flag)
            {
                throw new NotImplementedException(string.Concat(new string[]
                {
                    "Unexpected combination in case C:\nPredicate  -1: ",
                    num3.ToString(),
                    "\nPredicate   0: ",
                    num4.ToString(),
                    "\nPredicate   1: ",
                    num.ToString(),
                    "\nPredicate   2: ",
                    num5.ToString(),
                    "\nPredicate NaN: ",
                    num2.ToString(),
                    "\nAt triangle:\n",
                    triangle_0.ToString()
                }));
            }
            if (list.Count == 2)
            {
                try
                {
                    Point point = this.method_4(edge_0, list[0]);
                    Edge  result;
                    if (point == null)
                    {
                        result = this.method_5(edge_0, list[0]);
                        return(result);
                    }
                    Point point2 = this.method_4(edge_0, list[1]);
                    if (point2 == null)
                    {
                        result = this.method_5(edge_0, list[1]);
                        return(result);
                    }
                    result = new Edge(point, point2);
                    return(result);
                }
                catch (System.Exception ex)
                {
                    throw new ArithmeticException("Error in case C0: " + ex.Message);
                }
            }
            if (num2 == 1 && num4 == 2)
            {
                return(list2[0]);
            }
            if (list.Count == 1)
            {
                Point point3;
                try
                {
                    point3 = this.method_4(edge_0, list[0]);
                    if (point3 == null)
                    {
                        Edge result = this.method_5(edge_0, list[0]);
                        return(result);
                    }
                }
                catch (System.Exception ex)
                {
                    throw new ArithmeticException("Degenerate edge in case C2");
                }
                PointSet vertices = triangle_0.Vertices;
                for (int j = 0; j < 3; j++)
                {
                    if (Predicate.Orient2d_exact(edge_0.StartPoint, edge_0.EndPoint, vertices[j]) == 0.0)
                    {
                        return(new Edge(point3, vertices[j]));
                    }
                }
                throw new ArithmeticException("Exact arithmetic error in case C2");
            }
            return(null);
        }