/// <summary>
		/// XAML creation of polygon and polyline geometries are currently not supported, so
		/// here they are created in code. Points are generated in the XAML for this sample.
		/// </summary>
		private void CreateGeometries()
		{
			var layer = mapView1.Map.Layers.OfType<GraphicsLayer>().First();
			int i = 0;
			foreach (var g in layer.Graphics)
				g.Attributes["Label"] = "Label #" + (++i).ToString();

			Polyline line = new Polyline(FromArray(-100,-30, -80,0, -60,-30, -40,0), SpatialReferences.Wgs84);
			var graphic = new Graphic(line, (Esri.ArcGISRuntime.Symbology.Symbol)Resources["OutlinedAndDashedSymbol"]);
			graphic.Attributes["Label"] = "OutlinedAndDashedSymbol";
			layer.Graphics.Add(graphic);

			Polygon polygon = new Polygon(FromArray(-30,-30, 0,-30, 0,0, -15,-10, -30,0, -30,-30), SpatialReferences.Wgs84);
			graphic = new Graphic(polygon, (Esri.ArcGISRuntime.Symbology.Symbol)Resources["VertexFillSymbol"]);
			graphic.Attributes["Label"] = "VertexFillSymbol";
			layer.Graphics.Add(graphic);

			//CIM symbols can only be created from JSON. The JSON is currently only constructed by publishing services to ArcGIS Server with advanced symbology
			string CIMSymbolJson = "{\"type\":\"CIMSymbolReference\",\"symbol\":{\"type\":\"CIMLineSymbol\",\"symbolLayers\":[{\"type\":\"CIMFilledStroke\",\"enable\":true,\"effects\":[{\"type\":\"CIMGeometricEffectArrow\",\"geometricEffectArrowType\":\"Block\",\"primitiveName\":null,\"width\":35}],\"capStyle\":\"Round\",\"pattern\":{\"type\":\"CIMSolidPattern\",\"color\":[0,0,0,255]},\"width\":2,\"lineStyle3D\":\"Strip\",\"alignment\":\"Center\",\"joinStyle\":\"Miter\",\"miterLimit\":10,\"patternFollowsStroke\":true}]},\"symbolName\":null}";
			var cimsymbol = Esri.ArcGISRuntime.Symbology.Symbol.FromJson(CIMSymbolJson);
			Polyline line2 = new Polyline(FromArray(20, -30, 30, 0, 50, -30, 70, 0), SpatialReferences.Wgs84);
			graphic = new Graphic(line2, cimsymbol);
			graphic.Attributes["Label"] = "CIM Symbol";
			layer.Graphics.Add(graphic);

			i = 0;
			foreach (var g in layer.Graphics)
			{
				g.Attributes["SymbolType"] = g.Symbol.GetType().Name;
				g.Attributes["ID"] = ++i;
			}
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			var camera = CameraPosition.FromCamera (0, -180, 3);
			var mapView = MapView.FromCamera (CGRect.Empty, camera);

			// Create a 'normal' polyline.
			var polyline = new Polyline ();
			var path = new MutablePath ();

			path.AddCoordinate (new CLLocationCoordinate2D (37.772323, -122.214897));
			path.AddCoordinate (new CLLocationCoordinate2D (21.291982, -157.821856));
			path.AddCoordinate (new CLLocationCoordinate2D (-18.142599, 178.431));
			path.AddCoordinate (new CLLocationCoordinate2D (-27.46758, 153.0278926));

			polyline.Path = path;
			polyline.StrokeColor = UIColor.Red;
			polyline.StrokeWidth = 2;
			polyline.Map = mapView;
			
			// Copy the previous polyline, change its color, and mark it as geodesic.
			polyline = (Polyline) polyline.Copy ();
			polyline.StrokeColor = UIColor.Green;
			polyline.Geodesic = true;
			polyline.Map = mapView;
			
			View = mapView;
		}
        public static double Get(bool IsLeftComp, double r, Polyline line, Point2d TheIntersectPoint, int Index, Point2d StartPoint)
        {
            double oldBulge = line.GetBulgeAt(Index - 1);
            if (oldBulge == 0)
                return 0;//这里可能不对,可能有两个交点,而默认为一个交点
            else
            {
                double delta = System.Math.Atan(System.Math.Abs(oldBulge)) * 2;

                //这里计算新的半径时,要考虑方向因素,可能新半径会更小,也可能会更大
                //取决于路径的偏移方向,以及圆心的位置
                double newRadius = line.GetPoint2dAt(Index - 1).GetDistanceTo(line.GetPoint2dAt(Index)) / 2 / System.Math.Sin(delta);//新弧的半径
                if (IsLeftComp)
                {
                    if (oldBulge < 0)
                        newRadius += r;
                    else newRadius -= r;
                }
                else
                {
                    if (oldBulge > 0)
                        newRadius += r;
                    else newRadius -= r;
                }

                double newChord = StartPoint.GetDistanceTo(TheIntersectPoint);
                double newBulge = System.Math.Tan(
                    System.Math.Asin(newChord / 2 / newRadius) / 2
                    )
                    * line.GetBulgeAt(Index - 1) / System.Math.Abs(line.GetBulgeAt(Index - 1));
                return -newBulge;
            }
        }
Example #4
0
        public void Create(BlockTableRecord btrPanel, Transaction t)
        {
            Polyline plContour = new Polyline();
             plContour.LayerId = panelBase.Service.Env.IdLayerContourPanel;

             // Определение подрезок и пустот
             defineUndercuts();

             // Outsides - части сторон панели без плитки - заходит под торец другой угловой панели
             addOutsides(btrPanel, t);

             definePtsLeftSide();
             definePtsTopSide();
             definePtsRightSide();
             definePtsBotSide();

             int i = 0;
             ptsLeftSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));
             ptsTopSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));
             ptsRightSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));
             ptsBotSide.ForEach(p => plContour.AddVertexAt(i++, p, 0, 0, 0));

             plContour.Closed = true;
             btrPanel.AppendEntity(plContour);
             t.AddNewlyCreatedDBObject(plContour, true);
        }
Example #5
0
        public void GetNodesBetweenPointsReturnPointsInCorrectOrder1()
        {
            PointGeo start = new PointGeo(1, 1);
            PointGeo middle1 = new PointGeo(1, 1.5);
            PointGeo middle2 = new PointGeo(1, 1.6);
            PointGeo middle3 = new PointGeo(1, 1.7);
            PointGeo end = new PointGeo(1, 2);
            Polyline<IPointGeo> line = new Polyline<IPointGeo>();
            line.Nodes.Add(start);
            line.Nodes.Add(middle1);
            line.Nodes.Add(middle2);
            line.Nodes.Add(middle3);
            line.Nodes.Add(end);

            var result = Topology.GetNodesBetweenPoints(new PointGeo(1, 1.1), new PointGeo(1, 1.9), line).ToList();
            Assert.Equal(3, result.Count());
            Assert.Equal(middle1, result[0]);
            Assert.Equal(middle2, result[1]);
            Assert.Equal(middle3, result[2]);

            result = Topology.GetNodesBetweenPoints(new PointGeo(1, 1.9), new PointGeo(1, 1.1), line).ToList();
            Assert.Equal(3, result.Count());
            Assert.Equal(middle3, result[0]);
            Assert.Equal(middle2, result[1]);
            Assert.Equal(middle1, result[2]);
        }
 internal static double DistanceFromPointToPolyline(Point p, Polyline poly) {
     double d = double.PositiveInfinity;
     double u;
     for (PolylinePoint pp = poly.StartPoint; pp.Next != null; pp = pp.Next)
         d = Math.Min(d, Point.DistToLineSegment(p, pp.Point, pp.Next.Point, out u));
     return d;
 }
Example #7
0
 //
 public Movil(ref ObjectId line, ref ObjectId mobile, double minSeparation, double maxSeparation, bool loopTravel)
 {
     this.line = line;
     this.mobile = mobile;
     this.dPromMin = minSeparation;
     this.dPromMax = maxSeparation;
     this.loopTravel = loopTravel;
     this.goal = false;
     this.ruta = Lab3.DBMan.OpenEnity(line) as Polyline;
     this.bloque = Lab3.DBMan.OpenEnity(mobile) as BlockReference;
     this.bloqueCentro = new Point3d((bloque.GeometricExtents.MinPoint.X +
                      bloque.GeometricExtents.MaxPoint.X) / 2,
                      (bloque.GeometricExtents.MinPoint.Y +
                      bloque.GeometricExtents.MaxPoint.Y) / 2,
                      0);
     this.numeroSegmentos = this.ruta.NumberOfVertices - 1;
     this.segmentoActualIndex = 0;
     this.segmentoActual = this.ruta.GetLineSegment2dAt(segmentoActualIndex);
     Lab3.DBMan.UpdateBlockPosition(new Point3d(this.segmentoActual.StartPoint.X, this.segmentoActual.StartPoint.Y, 0), mobile);
     //
     AttributeManager attribute = new AttributeManager(mobile);
     attribute.SetAttribute("Velocity", this.velocity+" [Kms/hr]");
     //
     this.pointActualCurve = 0;
     this.velocityScale = 0.00001f;
     this.velocity = this.UpdateDireccion();
     Lab3.DBMan.UpdateBlockRotation(new Vector2d(this.velocity.X, this.velocity.Y).Angle, this.mobile);
 }
		public async Task<RouteResult> GetRoute(IEnumerable<MapPoint> stops, CancellationToken cancellationToken)
		{
			if (stops == null)
				throw new ArgumentNullException("stops");

			List<Graphic> stopList = new List<Graphic>();
			foreach (var stop in stops)
			{
				stopList.Add(new Graphic(stop));
			}
			if (stopList.Count < 2)
				throw new ArgumentException("Not enough stops");

			//determine which route service to use. Long distance routes should use the long-route service
			Polyline line = new Polyline() { SpatialReference = SpatialReferences.Wgs84 };
			line.Paths.AddPart(stops.Select(m => m.Coordinate));
			var length = GeometryEngine.GeodesicLength(line);
			string svc = routeService;
			if (length > 200000)
				svc = longRouteService;

			//Calculate route
			RouteTask task = new OnlineRouteTask(new Uri(svc)) { HttpMessageHandler = messageHandler };
			var parameters = await task.GetDefaultParametersAsync().ConfigureAwait(false);
			parameters.Stops = new Esri.ArcGISRuntime.Tasks.NetworkAnalyst.FeaturesAsFeature(stopList);
			parameters.ReturnStops = true;
			parameters.OutputLines = OutputLine.TrueShapeWithMeasure;
			parameters.OutSpatialReference = SpatialReferences.Wgs84;
			parameters.DirectionsLengthUnit = LinearUnits.Meters;
			parameters.UseTimeWindows = false;
			parameters.RestrictionAttributeNames = new List<string>(new string[] { "OneWay " });
			return await task.SolveAsync(parameters, cancellationToken);
		}
Example #9
0
        public PolylineBuilder Add()
        {
            var polyline = new Polyline(this.Map);

            this.Map.Polylines.Add(polyline);

            return new PolylineBuilder(polyline);
        }
Example #10
0
        public void ExtrudedSolidCommand()
        {
            var document = Application.DocumentManager.MdiActiveDocument;

            if (document == null) // don't bother doing anything else
                return;

            using (var polyline = new Polyline())
            {
                var extrudedSquareInputResult = GetExtrusionInputFromUser();

                // convenience variables
                var width = extrudedSquareInputResult.Width;
                var height = extrudedSquareInputResult.Height;
                var depth = extrudedSquareInputResult.Depth;

                // Using the polyline, we add vertices based on the user's input
                polyline.AddVertexAt(0, Point2d.Origin, 0.0, 0.0, 0.0);
                polyline.AddVertexAt(1, new Point2d(width, 0.0), 0.0, 0.0, 0.0);
                polyline.AddVertexAt(2, new Point2d(width, height), 0.0, 0.0, 0.0);
                polyline.AddVertexAt(3, new Point2d(0.0, height), 0.0, 0.0, 0.0);
                polyline.Closed = true;

                // add polyline to DBObjectCollection for us in creating region from curves
                using (var dbObjectCollection = new DBObjectCollection { polyline })
                {
                    using (var regionCollection = Region.CreateFromCurves(dbObjectCollection))
                    {
                        using (var region = (Region)regionCollection[0])
                        {
                            using (var solid = new Solid3d())
                            {
                                // extrude the region to the depth the user specified
                                solid.Extrude(region, depth, 0.0);
                                using (document.LockDocument())
                                {
                                    using (var database = document.Database)
                                    {
                                        using (var transaction = database.TransactionManager.StartTransaction())
                                        {
                                            // get the current space for appending our extruded solid
                                            using (var currentSpace = (BlockTableRecord)transaction.GetObject(database.CurrentSpaceId, OpenMode.ForWrite))
                                            {
                                                currentSpace.AppendEntity(solid);
                                            }

                                            transaction.AddNewlyCreatedDBObject(solid, true);
                                            transaction.Commit();
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
Example #11
0
 /// <summary>
 /// Creates the part.
 /// </summary>
 /// <returns>
 /// UIElement
 /// </returns>
 public override UIElement CreatePart()
 {
     Lines = new Polyline();
     PointCollection pointsCollection=new PointCollection {StartPoint, StepPoint, EndPoint};
     Lines.Points = pointsCollection;
     SetBindingForStrokeandStrokeThickness(Lines);
     UiElement = Lines;
     return Lines;
 }
        internal Polygon(Polyline polyline) {
            this.polyline = polyline;
            points = new PolylinePoint[polyline.Count];
            int i = 0;
            PolylinePoint pp = polyline.StartPoint;
            for (; i < polyline.Count; i++, pp = pp.Next)
                points[i] = pp;

        }
 public static Polyline PolylineAroundClosedCurve(ICurve curve) {
     Polyline poly = new Polyline();
     foreach (Point point in PointsOnAroundPolyline(curve))
         poly.AddPoint(point);
     if (Point.GetTriangleOrientation(poly.StartPoint.Point, poly.StartPoint.Next.Point, poly.StartPoint.Next.Next.Point) == TriangleOrientation.Counterclockwise)
         poly = (Polyline)poly.Reverse();
     poly.Closed = true;
     return poly;
 }
Example #14
0
 /// <summary>
 /// Creates a new Polyline that is the result of projecting the transformed MinPoint and MaxPoint of 'extents' 
 /// parallel to 'direction' onto 'plane' and returns it.
 /// </summary>
 /// <param name="extents">The Extents3d of a transformed from World to dirPlane Polyline.</param>
 /// <param name="plane">The plane onto which the points are to be projected.</param>
 /// <param name="direction">Direction (in WCS coordinates) of the projection</param>
 /// <param name="dirPlane">The plane which origin is 0, 0, 0 and 'direction' is the normal.</param>
 /// <returns>The newly created Polyline.</returns>
 internal static Polyline ProjectExtents(Extents3d extents, Plane plane, Vector3d direction, Plane dirPlane)
 {
     Point3d pt1 = extents.MinPoint.TransformBy(Matrix3d.PlaneToWorld(dirPlane));
     Point3d pt2 = extents.MaxPoint.TransformBy(Matrix3d.PlaneToWorld(dirPlane));
     Polyline projectedPline = new Polyline(2);
     projectedPline.AddVertexAt(0, pt1.Project(plane, direction).Convert2d(), 0.0, 0.0, 0.0);
     projectedPline.AddVertexAt(1, pt2.Project(plane, direction).Convert2d(), 0.0, 0.0, 0.0);
     return projectedPline;
 }
        private static SurveyPolyline CreateSurveyPolylineFromLine(ILine line)
        {
            IPolyline polyline = new Polyline(line.Id,
                                              line.RunDirection);

            polyline.AddSegment(line);

            return new SurveyPolyline(polyline);
        }
Example #16
0
        // 만들어진 폴리라인을 가지고 선형을 만들어주는 메소드 선형뿐만아니라 그리드 뷰까지 찍어줌
        public Alignment CreateAlign(Polyline guid)
        {
            Document dc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument; // 현재 도큐먼트를 가져옴
            Database db = dc.Database; // 현재 데이터베이스를 가져옴

            CivilDocument doc = CivilApplication.ActiveDocument;
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable acBlktbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable; // 선을 그리기 위한 블럭테이블 생성
                BlockTableRecord acblkTblrec = acTrans.GetObject(acBlktbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // 어디 도면에 그릴지 선택

                PolylineOptions plops = new PolylineOptions(); // 폴리라인 옵션 지정

                plops.AddCurvesBetweenTangents = true;
                plops.EraseExistingEntities = true;
                plops.PlineId = guid.ObjectId;

                ObjectId testAlignmentID = Alignment.Create(doc, plops, "내가만든 선형", null, "0", "Proposed", "All Labels");

                Alignment oAlignment = acTrans.GetObject(testAlignmentID, OpenMode.ForRead) as Alignment;

                ObjectId layerId = oAlignment.LayerId;
                // get first surface in the document
                ObjectId surfaceId = doc.GetSurfaceIds()[0];
                // get first style in the document
                ObjectId styleId = doc.Styles.ProfileStyles[0];
                // get the first label set style in the document
                ObjectId labelSetId = doc.Styles.LabelSetStyles.ProfileLabelSetStyles[0];

                try
                {
                    ObjectId profileId = Profile.CreateFromSurface("My Profile", testAlignmentID, surfaceId, layerId, styleId, labelSetId);

                }
                catch (Autodesk.AutoCAD.Runtime.Exception e)
                {
                    ed.WriteMessage(e.Message);
                }

                PromptPointResult pPtRes;
                PromptPointOptions pPtOpts = new PromptPointOptions("종단뷰를 그릴 위치를 찍어주세요~");
                pPtRes = dc.Editor.GetPoint(pPtOpts);
                Point3d ptStart = pPtRes.Value;
                if (pPtRes.Status == PromptStatus.Cancel) return null;

                // ObjectId ProfileViewId = ProfileView.Create(alignID, ptStart);
                ObjectId pfrVBSStyleId = doc.Styles.ProfileViewBandSetStyles[8];

                ObjectId ProfileViewId2 = ProfileView.Create(doc, "My Profile", pfrVBSStyleId, testAlignmentID, ptStart);
                //doc, "My Profile View", pfrVBSStyleId, alignID, ptInsert
                acTrans.Commit();
                return oAlignment;
            }
        }
Example #17
0
 public static List<PolylineVertex> GetVertexes(Polyline pl, string name)
 {
     var res = new List<PolylineVertex>();
     for (int i = 0; i < pl.NumberOfVertices; i++)
     {
         var pt = pl.GetPoint2dAt(i);
         res.Add(new PolylineVertex(name, i, pt));
     }
     return res;
 }
Example #18
0
 public static Polyline GetPolyline(this Extents3d ext)
 {
     var pl = new Polyline();
     pl.AddVertexAt(0, ext.MinPoint.Convert2d(), 0, 0, 0);
     pl.AddVertexAt(1, new Point2d (ext.MinPoint.X, ext.MaxPoint.Y) , 0, 0, 0);
     pl.AddVertexAt(2, ext.MaxPoint.Convert2d(), 0, 0, 0);
     pl.AddVertexAt(3, new Point2d(ext.MaxPoint.X, ext.MinPoint.Y), 0, 0, 0);
     pl.Closed = true;
     return pl;
 }
Example #19
0
        public void PolylineNodesCountReturnsCorrectValue()
        {
            PointGeo p1 = new PointGeo(1, 2);
            PointGeo p2 = new PointGeo(3, 4);

            Polyline<PointGeo> target = new Polyline<PointGeo>();
            target.Nodes.Add(p1);
            target.Nodes.Add(p2);

            Assert.Equal(2, target.NodesCount);
        }
Example #20
0
        /// <summary>
        /// Creates a Polyline with default settings (layer, color, etc.) with the specified vertices. 
        /// Only the X and Y coordinates are taken into account, width is zero, and no bulges are added.
        /// </summary>
        /// <param name="vertices">Vertices that will compose the polyline.</param>
        public static Polyline CreatePolyline(Point3dCollection vertices)
        {
            Polyline polyline = new Polyline();
            polyline.SetDatabaseDefaults();

            for (int i = 0; i < vertices.Count; i++)
            {
                polyline.AddVertexAt(i, new Point2d(vertices[i].X, vertices[i].Y), 0, 0, 0);
            }

            return polyline;
        }
 internal static void Sweep(
     IEnumerable<Polyline> obstacles,
     Point direction,
     double coneAngle,
     VisibilityGraph visibilityGraph,
     Set<Point> ports,
     Polyline borderPolyline) {
  
     var cs = new LineSweeper(obstacles, direction, direction.Rotate(-coneAngle/2),
                              direction.Rotate(coneAngle/2), visibilityGraph, ports,
                              borderPolyline);
     cs.Calculate();
 }
Example #22
0
 public Sierpinski(Point3d center, Double size = 100)
 {
     Triangle = new Polyline();
     this.Size = size;
     A = new Point2d(center.X - size / 2, center.Y);
     B = new Point2d(center.X, center.Y + size);
     C = new Point2d(center.X + size / 2, center.Y);
     Triangle.AddVertexAt(0, A, 0, 0, 0);
     Triangle.AddVertexAt(1, B, 0, 0, 0);
     Triangle.AddVertexAt(2, C, 0, 0, 0);
     Triangle.Closed = true;
     depth = 0;
 }
Example #23
0
 public Sierpinski(Point2d a, Point2d b, Point2d c)
 {
     Triangle = new Polyline();
     A = a;
     B = b;
     C = c;
     this.Size = B.GetDistanceTo(A);
     Triangle.AddVertexAt(0, A, 0, 0, 0);
     Triangle.AddVertexAt(1, B, 0, 0, 0);
     Triangle.AddVertexAt(2, C, 0, 0, 0);
     Triangle.Closed = true;
     depth = 0;
 }
Example #24
0
 /// <summary>
 /// Create a visual for single Series Part
 /// </summary>
 /// <returns>
 /// UIElement
 /// </returns>
 public override UIElement CreatePart()
 {
     if (this.LinePoints.Count > 0)
     {
         LinePart = new Polyline();
         foreach (var linePoint in LinePoints)
         {
             LinePart.Points.Add(linePoint);
         }
         SetBindingForStrokeandStrokeThickness(LinePart);
     }
     return LinePart;
 }
 LineSweeper(IEnumerable<Polyline> obstacles, Point direction, Point coneRsDir, Point coneLsDir,
             VisibilityGraph visibilityGraph, Set<Point> ports, Polyline borderPolyline)
     : base(obstacles, direction) {
     this.visibilityGraph = visibilityGraph;
     ConeRightSideDirection = coneRsDir;
     ConeLeftSideDirection = coneLsDir;
     coneSideComparer = new ConeSideComparer(this);
     leftConeSides = new RbTree<ConeSide>(coneSideComparer);
     rightConeSides = new RbTree<ConeSide>(coneSideComparer);
     Ports = ports;
     BorderPolyline = borderPolyline;
     PortEdgesCreator = (a, b) => new TollFreeVisibilityEdge(a, b);
 }
Example #26
0
        public void PolylineLengthReturnsLengthOfThePolyline()
        {
            PointGeo p1 = new PointGeo(1, 2);
            PointGeo p2 = new PointGeo(3, 4);

            IPolyline<IPointGeo> target = new Polyline<IPointGeo>();
            target.Nodes.Add(p1);
            target.Nodes.Add(p2);

            double expectedLength = Calculations.GetLength(target);

            Assert.InRange(target.Length, expectedLength - Calculations.EpsLength, expectedLength + Calculations.EpsLength);
        }
        public LatLngBounds(Polyline polyline)
        {
            if (polyline.Options.Path.Count > 0)
            {
                LatLng initialPoint = polyline.Options.Path[0];
                this.SW = new LatLng(initialPoint.Lat, initialPoint.Lng);
                this.NE = new LatLng(initialPoint.Lat, initialPoint.Lng);

                foreach (LatLng point in polyline.Options.Path)
                {
                    this.Extend(point);
                }
            }
        }
        public static List<int> FindSelfIntersectPline(Polyline polyline)
        {
            List<int> resultPts = new List<int>();

            DBObjectCollection entities = new DBObjectCollection();
            polyline.Explode(entities);

            for (int i = 0; i < entities.Count; ++i)
            {
                for (int j = i + 1; j < entities.Count; ++j)
                {
                    Curve curve1 = entities[i] as Curve;
                    Curve curve2 = entities[j] as Curve;

                    Autodesk.AutoCAD.Geometry.Point3dCollection points = new Autodesk.AutoCAD.Geometry.Point3dCollection();
                    curve1.IntersectWith(
                        curve2,
                        Intersect.OnBothOperands,
                        points,
                        IntPtr.Zero,
                        IntPtr.Zero);

                    foreach (Point3d point in points)
                    {
                        // Make a check to skip the start/end points
                        // since they are connected vertices
                        if (point == curve1.StartPoint ||
                            point == curve1.EndPoint)
                        {
                            if (point == curve2.StartPoint ||
                                point == curve2.EndPoint)
                            {
                                // If two consecutive segments, then skip
                                if (j == i + 1)
                                {
                                    continue;
                                }
                            }
                        }

                        resultPts.Add(j);
                    }
                }

                // Need to be disposed explicitely
                // since entities are not DB resident
                entities[i].Dispose();
            }
            return resultPts;
        }
Example #29
0
        static bool PolylinesIntersect(Polyline c0, Polyline c1)
        {
            if(Curve.CurveCurveIntersectionOne(c0, c1, false)!=null)
                return true;
            //could be that one lies inside of another
            if(c0.Closed)
                if(Curve.PointRelativeToCurveLocation((c1 as ICurve).Start, c0)!=PointLocation.Outside)
                    return true;

            if (c1.Closed)
                if (Curve.PointRelativeToCurveLocation((c0 as ICurve).Start, c1) != PointLocation.Outside)
                    return true;

            return false;
        }
        public CustomMapPage()
        {
            InitializeComponent();
            //var c = new Coords("49.8119444444N23.9513888889E");
            //c.Name = "test point";
            //var p = new CustomPin(c)
            //{
            //    //Position = new Position(49.8119444444, 23.9513888889),
            //    //Label = "ok"
            //};
            //map.CustomPins.Add(p);

            pointsToShow = new List <Coords>();

            Polyline polyline = new Polyline
            {
                StrokeWidth = 8,
                StrokeColor = Color.FromHex("#1BA1E2"),
                //FillColor = Color.FromHex("#881BA1E2"),
                Geopath =
                {
                    //new Position(47.6368678, -122.137305),
                    //new Position(47.6368894, -122.134655),
                    new Position(47.6359424,  -122.134655),
                    new Position(47.6359496, -122.1325521),
                    new Position(47.6424124, -122.1325199),
                    new Position(47.642463,  -122.1338932),
                    new Position(47.6406414, -122.1344833),
                    new Position(47.6384943, -122.1361248),
                    new Position(47.6372943, -122.1376912)
                }
            };

            // add the polygon to the map's MapElements collection
            map.MapElements.Add(polyline);
            List <Coords> l = new List <Coords>
            {
                new Coords(Extensions.ToRad(47.6368678), Extensions.ToRad(-122.137305)),
                new Coords(Extensions.ToRad(47.6368894), Extensions.ToRad(-122.134655))
            };
            var customPolyline = new Line(l);

            map.MapElements.Add(customPolyline);


            Polygon polygon = new Polygon
            {
                StrokeWidth = 8,
                StrokeColor = Color.FromHex("#1BA1E2"),
                FillColor   = Color.FromHex("#881BA1E2"),
                Geopath     =
                {
                    new Position(47.6368678,  -122.137305),
                    new Position(47.6368894,  -122.134655),
                    new Position(47.6359424,  -122.134655),
                    new Position(47.6359496, -122.1325521),
                    new Position(47.6424124, -122.1325199),
                    new Position(47.642463,  -122.1338932),
                    new Position(47.6406414, -122.1344833),
                    new Position(47.6384943, -122.1361248),
                    new Position(47.6372943, -122.1376912)
                }
            };
        }
Example #31
0
        private void CreateInsulationPolylineAndAppendToModelSpace(Point3d[] inputPoints, int rk,
                                                                   bool drawPerimeterOfInsulation)
        {
            var inputQPoints = new Quaternion[4]; // completed after sorting

            #region sorting

            var longestDistance = 0.0;
            var indexFirstPoint = 0;
            for (var i = 1; i < 4; i++)
            {
                var currentDistance = inputPoints[i - 1].DistanceTo(inputPoints[i]);
                if (currentDistance > longestDistance)
                {
                    longestDistance = currentDistance;
                    indexFirstPoint = i - 1;
                }
            }
            if (inputPoints[3].DistanceTo(inputPoints[0]) > longestDistance)
            {
                indexFirstPoint = 3;
            }

            var tempPoints = new Point3d[4];
            for (var i = indexFirstPoint; i < 4 + indexFirstPoint; i++)
            {
                if (i < 4)
                {
                    tempPoints[i - indexFirstPoint] = inputPoints[i];
                }
                else
                {
                    tempPoints[i - indexFirstPoint] = inputPoints[i - 4];
                }
            }

            for (var i = 0; i < 4; i++)
            {
                inputPoints[i]  = tempPoints[i];
                inputQPoints[i] = new Quaternion(0.0, inputPoints[i].X, inputPoints[i].Y, inputPoints[i].Z);
            }

            #endregion

            var uCSOfInputPoints = new UCS(inputQPoints[0], inputQPoints[1], inputQPoints[2]);

            if (Math.Abs((uCSOfInputPoints.FromACS(inputQPoints[3])).GetZ()) > 0.00000254)
            {
                _editorHelper.WriteMessage("Four Points are not in the same Plane !");
                _logger.Info("User input is invalid.");
                return;
            }

            #region counterclockwise selection test

            var centerUcsOfInputPoints  = new Quaternion(0, 0, 0, 0);
            var zAxisInUscOfInputPoints = new Quaternion(0, 0, 0, 1000);
            var zAxisInAcs = uCSOfInputPoints.ToACS(zAxisInUscOfInputPoints) -
                             uCSOfInputPoints.ToACS(centerUcsOfInputPoints);
            if (zAxisInAcs.GetZ() < 0)
            {
                var tempPoint      = new Point3d();
                var tempQuaternion = new Quaternion();

                tempPoint      = inputPoints[0];
                inputPoints[0] = inputPoints[1];
                inputPoints[1] = tempPoint;

                tempQuaternion  = inputQPoints[0];
                inputQPoints[0] = inputQPoints[1];
                inputQPoints[1] = tempQuaternion;

                tempPoint      = inputPoints[2];
                inputPoints[2] = inputPoints[3];
                inputPoints[3] = tempPoint;

                tempQuaternion  = inputQPoints[2];
                inputQPoints[2] = inputQPoints[3];
                inputQPoints[3] = tempQuaternion;

                uCSOfInputPoints = new UCS(inputQPoints[0], inputQPoints[1], inputQPoints[2]);
            }

            #endregion

            var ucsPoints = new Point3d[4];
            //are coordinates in a 0.0 WCS to draw (drawing only in oXY 0,0 per WCS and transform when it is ready polyline transform)
            var ucsQPoints = new Quaternion[4];
            //are coordinates in a 0.0 WCS to draw (drawing only in oXY 0,0 per WCS and when it is ready polyline transform)

            var complexPoints   = new Complex[4];
            var sidesOffPolygon = new Complex[4];

            #region 2d prepare

            for (int i = 0; i < 4; i++)
            {
                Quaternion q = uCSOfInputPoints.FromACS(inputQPoints[i]);
                ucsQPoints[i] = new Quaternion(0, (Math.Abs(q.GetX()) > 0.00000254) ? q.GetX() : 0.0,
                                               (Math.Abs(q.GetY()) > 0.00000254) ? q.GetY() : 0.0,
                                               (Math.Abs(q.GetZ()) > 0.00000254) ? q.GetZ() : 0.0);
                ucsPoints[i]     = new Point3d(ucsQPoints[i].GetX(), ucsQPoints[i].GetY(), ucsQPoints[i].GetZ());
                complexPoints[i] = new Complex(ucsQPoints[i].GetX(), ucsQPoints[i].GetY());
                if (i > 0)
                {
                    sidesOffPolygon[i - 1] = complexPoints[i] - complexPoints[i - 1];
                }
            }
            sidesOffPolygon[3] = complexPoints[0] - complexPoints[3];

            #endregion

            #region convex check

            for (var i = 0; i < 4; i++)
            {
                if (Math.Abs(GetAngleInPointIndex(i, complexPoints)) >= Math.PI)
                {
                    break;
                }
            }

            #endregion

            var minThickness = (complexPoints[2].imag() < complexPoints[3].imag())
                                   ? complexPoints[2].imag()
                                   : complexPoints[3].imag();
            var segmentsCount = (int)Math.Ceiling((sidesOffPolygon[0].abs() / minThickness) / 0.35);

            var radius = sidesOffPolygon[0].abs() * 2 / (segmentsCount * 2);
            radius /= rk;

            var lowerLine = new List <Complex>();
            var upperLine = new List <Complex>();


            var insulationPerimeter = new Polyline();
            insulationPerimeter.SetDatabaseDefaults();
            insulationPerimeter.AddVertexAt(0, new Point2d(complexPoints[0].real(), complexPoints[0].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(1, new Point2d(complexPoints[1].real(), complexPoints[1].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(2, new Point2d(complexPoints[2].real(), complexPoints[2].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(3, new Point2d(complexPoints[3].real(), complexPoints[3].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(4, new Point2d(complexPoints[0].real(), complexPoints[0].imag()), 0, 0,
                                            0);

            var objectsCollection = insulationPerimeter.GetOffsetCurves(-radius);
            var acPolyOffset      = objectsCollection[0] as Polyline;

            var pointsFromOffset = new Complex[4];
            for (var i = 0; i < 4; i++)
            {
                var point = acPolyOffset.GetPoint3dAt(i);
                pointsFromOffset[i] = new Complex(point.X, point.Y);
            }

            var variant = 0;
            if (pointsFromOffset[3].real() < pointsFromOffset[0].real() &&
                (pointsFromOffset[3] - pointsFromOffset[0]).abs() / (radius * 2) > 1 &&
                Math.Abs(pointsFromOffset[2].real() - pointsFromOffset[1].real()) > radius * 2)
            {
                variant = 1;
                lowerLine.Add(pointsFromOffset[0]);
                var xPos = pointsFromOffset[0].real();
                do
                {
                    xPos += radius * 2.0;
                    if (xPos <= pointsFromOffset[1].real() + radius * 2 / 3)
                    {
                        lowerLine.Add(new Complex(xPos, radius));
                    }
                } while (xPos < (pointsFromOffset[0] - pointsFromOffset[1]).abs() + radius * 2 / 3);

                xPos = 0;
                var ort = (pointsFromOffset[3] - pointsFromOffset[0]) /
                          (pointsFromOffset[3] - pointsFromOffset[0]).abs();
                var k = Math.Abs(Math.Cos(ort.arg()));
                k -= 0.01;
                do
                {
                    xPos += 2 * radius / Math.Abs(k);
                    if (xPos < (pointsFromOffset[3] - pointsFromOffset[0]).abs() + radius * 2 / 3)
                    {
                        lowerLine.Insert(0, ort * xPos + pointsFromOffset[0]);
                    }
                } while (xPos < (pointsFromOffset[3] - pointsFromOffset[0]).abs() + radius * 2 / 3);
                lowerLine.RemoveAt(0);
            }

            if (pointsFromOffset[1].real() < pointsFromOffset[2].real() &&
                (pointsFromOffset[2] - pointsFromOffset[1]).abs() / (radius * 2) > 1 &&
                Math.Abs(pointsFromOffset[2].real() - pointsFromOffset[1].real()) > radius * 2)
            {
                variant = 2;
                lowerLine.Add(pointsFromOffset[1]);
                var xPos = pointsFromOffset[1].real();
                do
                {
                    xPos -= radius * 2.0;
                    if (xPos >= pointsFromOffset[0].real() - radius * 2.0 / 3.0)
                    {
                        lowerLine.Insert(0, new Complex(xPos, radius));
                    }
                } while (xPos > pointsFromOffset[0].real() - radius * 2.0 / 3.0);


                xPos = 0;
                var ort = (pointsFromOffset[2] - pointsFromOffset[1]) /
                          (pointsFromOffset[2] - pointsFromOffset[1]).abs();
                var k = Math.Abs(Math.Cos(ort.arg()));
                k -= 0.01;
                do
                {
                    xPos += 2 * radius / Math.Abs(k);
                    if (xPos < (pointsFromOffset[2] - pointsFromOffset[1]).abs() + radius * 2.0 / 3.0)
                    {
                        lowerLine.Add(ort * xPos + pointsFromOffset[1]);
                    }
                } while (xPos < (pointsFromOffset[2] - pointsFromOffset[1]).abs() + radius * 2.0 / 3.0);
            }
            if (variant == 0)
            {
                lowerLine.Add(pointsFromOffset[0]);
                var xPos = pointsFromOffset[0].real();
                do
                {
                    xPos += radius * 2.0;
                    if (xPos <= pointsFromOffset[1].real() + radius * 2.0)
                    {
                        lowerLine.Add(new Complex(xPos, radius));
                    }
                } while (xPos < (pointsFromOffset[0] - pointsFromOffset[1]).abs() + radius * 2.0);
            }

            var insulationPolyline = new Polyline();
            insulationPolyline.SetDatabaseDefaults();
            var old = new KeyValuePair <Complex, Complex>();
            for (var i = 1; i < lowerLine.Count; i++)
            {
                var hlpPoint = (lowerLine[i] + lowerLine[i - 1]) / 2.0;

                var verticalLine = new Line(new Point3d(hlpPoint.real(), hlpPoint.imag(), 0),
                                            new Point3d(hlpPoint.real(), hlpPoint.imag() + 0.01, 0));

                var pts = new Point3dCollection();
                try
                {
                    acPolyOffset.IntersectWith(verticalLine, Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero);
                }
                catch (Exception aCadRuntimeException)
                {
                    _logger.Error("Unable to Intersect 2 entities", aCadRuntimeException);
                }
                if (pts.Count != 2)
                {
                    continue;
                }
                var p  = (pts[0].Y > pts[1].Y) ? pts[0] : pts[1];
                var cc = new Complex(p.X, p.Y);
                if ((cc - hlpPoint).abs() > 2 * radius)
                {
                    upperLine.Add(new Complex(p.X, p.Y));

                    var tangentPointsTopLeftBotRight = GetTangentPointsOfCommonInternalTanget(cc, radius,
                                                                                              lowerLine[i], radius,
                                                                                              true);
                    var tangentPointsBotRightTopLeft = GetTangentPointsOfCommonInternalTanget(lowerLine[i - 1],
                                                                                              radius, cc, radius,
                                                                                              false);

                    if (i > 1)
                    {
                        double ang1 = 0;

                        ang1 =
                            ((lowerLine[i - 1] - tangentPointsBotRightTopLeft.Key) / (lowerLine[i - 1] - old.Value))
                            .arg();
                        insulationPolyline.AddVertexAt(0,
                                                       new Point2d(tangentPointsBotRightTopLeft.Key.real(),
                                                                   tangentPointsBotRightTopLeft.Key.imag()),
                                                       -Math.Tan(ang1 / 4), 0, 0);
                    }
                    else
                    {
                        insulationPolyline.AddVertexAt(0,
                                                       new Point2d(tangentPointsBotRightTopLeft.Key.real(),
                                                                   tangentPointsBotRightTopLeft.Key.imag()), 0, 0, 0);
                    }
                    double ang =
                        ((cc - tangentPointsBotRightTopLeft.Value) / (cc - tangentPointsTopLeftBotRight.Key)).arg();
                    insulationPolyline.AddVertexAt(0,
                                                   new Point2d(tangentPointsBotRightTopLeft.Value.real(),
                                                               tangentPointsBotRightTopLeft.Value.imag()), 0, 0, 0);

                    insulationPolyline.AddVertexAt(0,
                                                   new Point2d(tangentPointsTopLeftBotRight.Key.real(),
                                                               tangentPointsTopLeftBotRight.Key.imag()),
                                                   Math.Tan(ang / 4), 0, 0);
                    insulationPolyline.AddVertexAt(0,
                                                   new Point2d(tangentPointsTopLeftBotRight.Value.real(),
                                                               tangentPointsTopLeftBotRight.Value.imag()), 0, 0, 0);

                    old = tangentPointsTopLeftBotRight;
                }
                else
                {
                    if (i < lowerLine.Count / 2)
                    {
                        lowerLine.RemoveAt(i - 1);
                    }
                    else
                    {
                        lowerLine.RemoveAt(i);
                    }
                    i--;
                }
            }

            var vectorBaseLine = new Complex(inputPoints[1].X, inputPoints[1].Y) -
                                 new Complex(inputPoints[0].X, inputPoints[0].Y);

            #region transforms

            insulationPolyline.TransformBy(Matrix3d.Rotation(vectorBaseLine.arg(), new Vector3d(0, 0, 1),
                                                             Point3d.Origin));
            insulationPerimeter.TransformBy(Matrix3d.Rotation(vectorBaseLine.arg(), new Vector3d(0, 0, 1),
                                                              Point3d.Origin));

            insulationPolyline.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(inputPoints[0])));
            insulationPerimeter.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(inputPoints[0])));

            insulationPolyline.TransformBy(_editorHelper.CurrentUcs);
            insulationPerimeter.TransformBy(_editorHelper.CurrentUcs);

            #endregion

            var oldLayer = _documentHelper.Database.Clayer;

            _documentHelper.LayerManipulator.CreateLayer("3-0", System.Drawing.Color.Lime);
            insulationPolyline.Layer = "0";
            var softInsulationBlock = new BlockTableRecord();
            var nameSalt            = DateTime.Now.GetHashCode().ToString();
            softInsulationBlock.Name   = "SoftInsulation_" + nameSalt;
            softInsulationBlock.Origin = inputPoints[0];

            using (var acTrans = _documentHelper.TransactionManager.StartTransaction())
            {
                var acBlkTbl = acTrans.GetObject(_documentHelper.Database.BlockTableId, OpenMode.ForWrite) as BlockTable;
                acBlkTbl.Add(softInsulationBlock);
                acTrans.AddNewlyCreatedDBObject(softInsulationBlock, true);
                softInsulationBlock.AppendEntity(insulationPolyline);
                acTrans.AddNewlyCreatedDBObject(insulationPolyline, true);
                if (drawPerimeterOfInsulation)
                {
                    insulationPerimeter.Layer = "0";
                    softInsulationBlock.AppendEntity(insulationPerimeter);
                    acTrans.AddNewlyCreatedDBObject(insulationPerimeter, true);
                }
                var rigidInsulationRef = new BlockReference(inputPoints[0],
                                                            softInsulationBlock.ObjectId)
                {
                    Layer = "3-0"
                };
                var currentSpace =
                    (BlockTableRecord)acTrans.GetObject(_documentHelper.Database.CurrentSpaceId, OpenMode.ForWrite);
                currentSpace.AppendEntity(rigidInsulationRef);
                acTrans.AddNewlyCreatedDBObject(rigidInsulationRef, true);
                acTrans.Commit();
            }
            _documentHelper.LayerManipulator.ChangeLayer(oldLayer);
        }
Example #32
0
        private void SetupXaxis(object sender, NotifyCollectionChangedEventArgs e)
        {
            XAxis.Children.Clear();
            XLabels.Children.Clear();

            double hlineW = HorizontalStepsWidth * (HorizontalSteps - 1) + AxisThickness + GraphContentPadding + AxisOutlineLenght;

            //Adding the horizontal axis line
            xAxisLine = new Polyline();
            xAxisLine.Points.Add(new Point(AxisThickness / 2, AxisThickness));
            xAxisLine.Points.Add(new Point(hlineW, AxisThickness));
            xAxisLine.Stroke          = AxisColor;
            xAxisLine.StrokeThickness = 0.5;

            //Setting the horizontal offset for the axis units and lines points
            Double offset = AxisThickness + GraphContentPadding;

            //for each horizontal unit:
            for (int i = 0; i < HorizontalSteps; i++)
            {
                //Adding the horizontal axis units lines
                Polyline line = new Polyline();
                line.Points.Add(new Point(offset, AxisThickness / 2));
                line.Points.Add(new Point(offset, AxisThickness));
                line.Stroke          = AxisColor;
                line.Visibility      = Visibility.Visible;
                line.StrokeThickness = 0.5;
                XAxis.Children.Add(line);

                //Adding the horizontal axis units labels
                TextBlock stepLabel = new TextBlock
                {
                    Text       = HorizontalLables[i],
                    FontSize   = 10,
                    Foreground = LabelsColor
                };
                Canvas.SetBottom(stepLabel, -2 * stepLabel.FontSize);
                Canvas.SetLeft(stepLabel, offset);
                XLabels.Children.Add(stepLabel);
                offset += HorizontalStepsWidth;
            }


            //Adding the X axis name label
            Double    XPosition = hlineW + 5;
            Double    YPosition = AxisThickness / 2;
            Decorator label     = CanvasLabel(XAxisName, XPosition, YPosition, LabelsColor, 10);

            label.Width  = 50;
            label.Height = 15;
            XLabels.Children.Add(label);

            //Creating the arrow for the end of the axis line
            Polyline arrow = HorizontalArrow(new Point(hlineW, AxisThickness), 5);

            arrow.Stroke          = AxisColor;
            arrow.StrokeThickness = 1;

            //Adding the X axis line and his arrow
            XAxis.Children.Add(xAxisLine);
            XAxis.Children.Add(arrow);
            Graph.Width = hlineW + label.Width + 10;
        }
Example #33
0
        private async void CreateNewFeatureCollection()
        {
            // Create the schema for a points table (one text field to contain a name attribute)
            List <Field> pointFields = new List <Field>();
            Field        placeField  = new Field(FieldType.Text, "Place", "Place Name", 50);

            pointFields.Add(placeField);

            // Create the schema for a lines table (one text field to contain a name attribute)
            List <Field> lineFields    = new List <Field>();
            Field        boundaryField = new Field(FieldType.Text, "Boundary", "Boundary Name", 50);

            lineFields.Add(boundaryField);

            // Create the schema for a polygon table (one text field to contain a name attribute)
            List <Field> polyFields = new List <Field>();
            Field        areaField  = new Field(FieldType.Text, "AreaName", "Area Name", 50);

            polyFields.Add(areaField);

            // Instantiate FeatureCollectionTables with schema and geometry type
            FeatureCollectionTable pointsTable = new FeatureCollectionTable(pointFields, GeometryType.Point, SpatialReferences.Wgs84);
            FeatureCollectionTable linesTable  = new FeatureCollectionTable(lineFields, GeometryType.Polyline, SpatialReferences.Wgs84);
            FeatureCollectionTable polysTable  = new FeatureCollectionTable(polyFields, GeometryType.Polygon, SpatialReferences.Wgs84);

            // Set rendering for each table
            pointsTable.Renderer = CreateRenderer(GeometryType.Point);
            linesTable.Renderer  = CreateRenderer(GeometryType.Polyline);
            polysTable.Renderer  = CreateRenderer(GeometryType.Polygon);

            // Create a new point feature, provide geometry and attribute values
            Feature pointFeature = pointsTable.CreateFeature();

            pointFeature.SetAttributeValue(placeField, "Current location");
            MapPoint point1 = new MapPoint(-79.497238, 8.849289, SpatialReferences.Wgs84);

            pointFeature.Geometry = point1;

            // Create a new line feature, provide geometry and attribute values
            Feature lineFeature = linesTable.CreateFeature();

            lineFeature.SetAttributeValue(boundaryField, "AManAPlanACanalPanama");
            MapPoint point2 = new MapPoint(-80.035568, 9.432302, SpatialReferences.Wgs84);
            Polyline line   = new Polyline(new MapPoint[] { point1, point2 });

            lineFeature.Geometry = line;

            // Create a new polygon feature, provide geometry and attribute values
            Feature polyFeature = polysTable.CreateFeature();

            polyFeature.SetAttributeValue(areaField, "Restricted area");
            MapPoint point3 = new MapPoint(-79.337936, 8.638903, SpatialReferences.Wgs84);
            MapPoint point4 = new MapPoint(-79.11409, 8.895422, SpatialReferences.Wgs84);
            Polygon  poly   = new Polygon(new MapPoint[] { point1, point3, point4 });

            polyFeature.Geometry = poly;

            // Add the new features to the appropriate feature collection table
            await pointsTable.AddFeatureAsync(pointFeature);

            await linesTable.AddFeatureAsync(lineFeature);

            await polysTable.AddFeatureAsync(polyFeature);

            // Create a feature collection and add the feature collection tables
            FeatureCollection featuresCollection = new FeatureCollection();

            featuresCollection.Tables.Add(pointsTable);
            featuresCollection.Tables.Add(linesTable);
            featuresCollection.Tables.Add(polysTable);

            // Create a FeatureCollectionLayer
            FeatureCollectionLayer collectionLayer = new FeatureCollectionLayer(featuresCollection);

            // When the layer loads, zoom the map view to the extent of the feature collection
            collectionLayer.Loaded += (s, e) => _myMapView.SetViewpointAsync(new Viewpoint(collectionLayer.FullExtent));

            // Add the layer to the Map's Operational Layers collection
            _myMapView.Map.OperationalLayers.Add(collectionLayer);
        }
        private void CalcUtilizationNominalStiffness2()
        {

            Polyline pl_Mz = Col.CrossSec.CalculateStrengthCurve(Plane.WorldXY,Ls);

            BoundingBox bb = pl_Mz.BoundingBox;
            double N_Rdmin = bb.Min.X;

            if (M_Edy_NomStiff != null && M_Edz_NomStiff != null)
            {
                //Save original loads
                double N_temp = N_Ed;

                //Check is the bigger utilization when the eccentricity is in z, or y-direction and choose that
                ZorY = true;
                M_Edy_NomStiff.CalcLoading();
                M_Edz_NomStiff.CalcLoading();

                Vector3d direction = new Vector3d(M_Edz_NomStiff.M_Ed, M_Edy_NomStiff.M_Ed, 0);
                M_EdComb = direction.Length;
                bool success = Col.CrossSec.CalculateStresses(N_Ed, M_Edz_NomStiff.M_Ed, M_Edy_NomStiff.M_Ed, Name,Ls);
                if (!success)
                {
                    Utilization[ColumnCalculationMethod.NominalStiffness2] = 999;
                    return;
                }
                    

                //Plane calcPlane = new Plane(Point3d.Origin, direction,
                //    Vector3d.CrossProduct(direction, Vector3d.ZAxis));
                Plane calcPlane = LoadPlane;
                if (calcPlane.ZAxis.Z < 0) calcPlane.Flip();
                Plane testPlane = new Plane(calcPlane);
                testPlane.Transform(Transform.PlaneToPlane(Plane.WorldXY, Plane.WorldYZ));


                Polyline pl_temp = Col.CrossSec.CalculateStrengthCurve(calcPlane,Ls);
                pl_temp.Transform(Transform.PlaneToPlane(testPlane, Plane.WorldYZ));
                pl_temp.Transform(Transform.PlanarProjection(Plane.WorldZX));
                NMCurve = pl_temp;

                /*
                Curve pl_M = Col.CrossSec.CalculateStrengthCurve(calcPlane).ToNurbsCurve();

                pl_M.Transform(Transform.PlaneToPlane(testPlane, Plane.WorldYZ));
                pl_M.Transform(Transform.PlanarProjection(Plane.WorldZX));
                */
                Curve pl_M = pl_temp.ToNurbsCurve();
                BoundingBox bbox = pl_M.GetBoundingBox(false);
                double MinNormalForce = bbox.Min.X;

                double[] NormalForceRange = Enumerable.Range(0, 100).ToList().Select(o => (double)o).ToList().Select(o => o * MinNormalForce/100).ToArray();

                Polyline pl = new Polyline();

                CalcLoadPoint(NormalForceRange[0], ref pl);
                int i = 1;

                
                while (pl_M.Contains(pl[pl.Count - 1],Plane.WorldZX) ==PointContainment.Inside)
                {
                    CalcLoadPoint(NormalForceRange[i], ref pl);
                    i++;
                }

                //Save original values back
                _n_Ed = N_temp;
                M_Edy_NomStiff.CalcLoading();
                M_Edz_NomStiff.CalcLoading();

                Utilization[ColumnCalculationMethod.NominalStiffness2] = N_Ed / pl[pl.Count - 1].X;

                LoadCurve = pl;
            }
            else
                Utilization[ColumnCalculationMethod.NominalStiffness2] = 999;
        }
Example #35
0
        public static void GetProfile(ObjectId profileLine, string majorContLayer, string minorContLayer)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                List <ObjectId>                contoursId    = new List <ObjectId>();
                ObjectIdCollection             majorEnts     = SelectByLayer(majorContLayer);
                ObjectIdCollection             minorEnts     = SelectByLayer(minorContLayer);
                List <Tuple <double, double> > intersectDist = new List <Tuple <double, double> >();
                double maxElevation  = 0;
                double profileLength = 0;
                #region Combining two selection collection together into one single list
                if (majorEnts != null)
                {
                    foreach (ObjectId id in majorEnts)
                    {
                        contoursId.Add(id);
                    }
                    if (GlobalVars.majorOnly == false)
                    {
                        foreach (ObjectId id in minorEnts)
                        {
                            contoursId.Add(id);
                        }
                    }
                    #endregion
                    foreach (ObjectId id in contoursId)
                    {
                        using (DocumentLock doclock = doc.LockDocument())
                        {
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead);
                            Polyline         ent = tr.GetObject(profileLine, OpenMode.ForRead) as Polyline;
                            //Label start and end of section
                            CreateLayer("PROFILEVIEWER.PROFILE LABEL", 10);
                            DrawText(new Point2d(ent.StartPoint.X, ent.StartPoint.Y), GlobalVars.textHeight * 2, 0, "A", "PROFILEVIEWER.PROFILE LABEL", 10);
                            DrawText(new Point2d(ent.EndPoint.X, ent.EndPoint.Y), GlobalVars.textHeight * 2, 0, "A'", "PROFILEVIEWER.PROFILE LABEL", 10);
                            Polyline ent2 = tr.GetObject(id, OpenMode.ForWrite) as Polyline;
                            double   elav = ent2.Elevation; //store elevation temporary
                            ent2.Elevation = 0;

                            if (maxElevation < elav)
                            {
                                maxElevation = elav;
                            }
                            profileLength = ent.Length;

                            /// SET ELEVATION TO ZERO TEMPORARY THEN PUT IT BACk
                            Point3dCollection intersectionPoints = new Point3dCollection();
                            ent.IntersectWith(ent2, Intersect.OnBothOperands, intersectionPoints, IntPtr.Zero, IntPtr.Zero);
                            foreach (Point3d pt in intersectionPoints)
                            {
                                Point3d ptOnProfile = ent.GetClosestPointTo(pt, true);
                                double  ptParameter = ent.GetParameterAtPoint(ptOnProfile);
                                double  a           = ent.GetDistanceAtParameter(ptParameter);
                                double  b           = ent.GetDistanceAtParameter(ent.StartParam);
                                double  distance    = a - b;
                                //double distance = ent.GetDistAtPoint(pt);
                                Tuple <double, double> xsectPt = new Tuple <double, double>(distance, elav);
                                intersectDist.Add(xsectPt);
                            }
                            ent2.Elevation = elav; //set it back
                        }
                    }
                    if (intersectDist.Count > 0)
                    {
                        intersectDist.Sort(); //sort to get the start and end points
                        double profileStartY = intersectDist[0].Item2;
                        double profileEndY   = intersectDist[intersectDist.Count - 1].Item2;
                        Tuple <double, double> xsectStart = new Tuple <double, double>(0, profileStartY);           //start of profile
                        Tuple <double, double> xsectEnd   = new Tuple <double, double>(profileLength, profileEndY); //end of profile
                        intersectDist.Add(xsectStart);
                        intersectDist.Add(xsectEnd);
                        intersectDist.Sort(); //have to resort after adding new points
                        Polyline profile = new Polyline();
                        for (int i = 0; i < intersectDist.Count; i++)
                        {
                            profile.AddVertexAt(i, new Point2d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, intersectDist[i].Item2 + GlobalVars.insertionPt.Y), 0, 0, 0);
                            double  elevationGrid = DrawLine(new Point3d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, intersectDist[i].Item2 + GlobalVars.insertionPt.Y, 0), new Point3d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y, 0), "PROFILEVIEWER.GRIDLINES", 252);
                            decimal elevLabel     = Convert.ToDecimal(intersectDist[i].Item2);
                            DrawText(new Point2d(intersectDist[i].Item1 + GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y), GlobalVars.textHeight, 1.5708, elevLabel.ToString("#.##"), "PROFILEVIEWER.LABELS", 10);
                            if (i == intersectDist.Count - 1)
                            {
                                using (DocumentLock docLock = doc.LockDocument())
                                {
                                    CreateLayer("PROFILEVIEWER.PROFILE", 255);
                                    profile.Layer = "PROFILEVIEWER.PROFILE";
                                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                                    btr.AppendEntity(profile);
                                    tr.AddNewlyCreatedDBObject(profile, true);
                                }
                            }
                        }

                        double datumY = profileLength;
                        //Datum line
                        Polyline guides = new Polyline();
                        guides.AddVertexAt(0, new Point2d(GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y + profileStartY), 0, 0, 0);
                        guides.AddVertexAt(1, new Point2d(GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y), 0, 0, 0);
                        DrawText(new Point2d(GlobalVars.insertionPt.X, GlobalVars.insertionPt.Y), GlobalVars.textHeight * 2, 0, "A", "PROFILEVIEWER.DATUMLINE");
                        guides.AddVertexAt(2, new Point2d(GlobalVars.insertionPt.X + profileLength, GlobalVars.insertionPt.Y), 0, 0, 0);
                        DrawText(new Point2d(GlobalVars.insertionPt.X + profileLength, GlobalVars.insertionPt.Y), GlobalVars.textHeight * 2, 0, "A'", "PROFILEVIEWER.DATUMLINE");
                        guides.AddVertexAt(3, new Point2d(GlobalVars.insertionPt.X + profileLength, GlobalVars.insertionPt.Y + profileEndY), 0, 0, 0);
                        CreateLayer("PROFILEVIEWER.DATUMLINE", 251);
                        guides.Layer = "PROFILEVIEWER.DATUMLINE";

                        using (DocumentLock docLock = doc.LockDocument())
                        {
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            btr.AppendEntity(guides);
                            tr.AddNewlyCreatedDBObject(guides, true);
                        }
                    }
                    tr.Commit();
                    ed.WriteMessage("Successfully created profile.");
                }
                else
                {
                    ed.WriteMessage("No Polyline in selected layer");
                }
            }
        }
Example #36
0
        public List <Line> Calculate(SlopeModes slopeMode)
        {
            List <Line> slopeLines = new List <Line>();

            Polyline basePline = _baseLine.ConvertToPolyline();
            Polyline destPline = _destinationLine.ConvertToPolyline();

            if (!_startPointComplete)
            {
                _startPoint = basePline.StartPoint;
            }
            if (!_endPointComplete)
            {
                _endPoint = _startPoint;
            }

            double startDist = 0;

            startDist = basePline.GetDistAtPoint(_startPoint);
            double endDist = startDist;

            try
            {
                endDist = basePline.GetDistAtPoint(_endPoint);
            }
            catch { }

            Vector3d startVector  = _startPoint - destPline.StartPoint;
            Vector3d endVector    = _endPoint - destPline.EndPoint;
            Point3d  centralPoint = _startPoint.Add((_endPoint - _startPoint).MultiplyBy(0.5d));

            if ((centralPoint - destPline.StartPoint).Length < startVector.Length &&
                (centralPoint - destPline.EndPoint).Length < endVector.Length)
            {
                Vector3d buffVector = startVector;
                startVector = endVector;
                endVector   = startVector;
                destPline   = ((Polyline)destPline.Clone());
                destPline.ReverseCurve();
            }



            int    sign        = endDist >= startDist ? 1 : -1;
            double buffLength  = startVector.Length + endVector.Length + basePline.Length + destPline.Length;
            int    slopeNumber = 0;

            //for (double dist = startDist; dist <= endDist && dist <= basePline.Length; dist += _step)
            for (double dist = startDist; sign > 0 ? dist <= endDist : dist >= endDist; dist += _step * sign)
            {
                slopeNumber++;
                Point3d point = basePline.GetPointAtDist(dist);

                switch (slopeMode)
                {
                case SlopeModes.BothPerpendicular:
                {
                    Point3d?destPoint = destPline.GetOrthoNormalPoint(point, null, true);
                    if (destPoint.HasValue)
                    {
                        Line slope = new Line(point, destPoint.Value);
                        //if ((dist-startDist +_step) % (_step*2d) < Tolerance.Global.EqualPoint)
                        if (slopeNumber % 2d == 0d)
                        {
                            slope = new Line(slope.StartPoint, slope.StartPoint.Add((slope.EndPoint - slope.StartPoint).MultiplyBy(_smallLineLength)));
                        }
                        slopeLines.Add(slope);
                    }
                    break;
                }

                case SlopeModes.OwnPerpendicular:
                {
                    Line line = new Line(point, point.Add(_baseLine.GetPerpendicularVector(point).MultiplyBy(buffLength)));
                    Point3dCollection intersects = new Point3dCollection();

                    Point3d?destPoint = _getIntersectPoint(line, destPline);
                    if (!destPoint.HasValue)
                    {
                        break;
                    }
                    Line slope = new Line(point, destPoint.Value);
                    if (slopeNumber % 2d == 0d)
                    {
                        slope = new Line(slope.StartPoint, slope.StartPoint.Add((slope.EndPoint - slope.StartPoint).MultiplyBy(_smallLineLength)));
                    }
                    slopeLines.Add(slope);

                    break;
                }

                case SlopeModes.EqualStep:
                {
                    int count = Convert.ToInt32(Math.Floor(Math.Abs(endDist - startDist) / _step));
                    if (count == 0)
                    {
                        break;
                    }

                    Point3d?startDestPoint = destPline.GetOrthoNormalPoint(_startPoint, null, true);
                    Point3d?endDestPoint   = destPline.GetOrthoNormalPoint(point, null, true);
                    if (!startDestPoint.HasValue)
                    {
                        startDestPoint = destPline.StartPoint;
                    }
                    if (!endDestPoint.HasValue)
                    {
                        endDestPoint = destPline.EndPoint;
                    }

                    double lengthFactor = destPline.Length / basePline.Length;
                    double destDist     = dist * lengthFactor;

                    if (Math.Abs(destDist) <= Tolerance.Global.EqualPoint)
                    {
                        destDist = 0d;
                    }
                    if (Math.Abs(destDist - destPline.Length) <= Tolerance.Global.EqualPoint)
                    {
                        destDist = destPline.Length;
                    }

                    Point3d destPoint = destPline.GetPointAtDist(destDist);

                    Line slope = new Line(point, destPoint);
                    if (slopeNumber % 2d == 0d)
                    {
                        slope = new Line(slope.StartPoint, slope.StartPoint.Add((slope.EndPoint - slope.StartPoint).MultiplyBy(_smallLineLength)));
                    }
                    slopeLines.Add(slope);

                    break;
                }

                case SlopeModes.RegressBoth:
                {
                    Point3d?basePoint = _regressBaseLine.GetOrthoNormalPoint(point, null, true);
                    if (basePoint.HasValue)
                    {
                        Point3d?destPoint = _regressDestLine.GetOrthoNormalPoint(basePoint.Value, null, true);
                        if (destPoint.HasValue)
                        {
                            Line slope = new Line(basePoint.Value, destPoint.Value);
                            basePoint = _getIntersectPoint(slope, basePline);
                            if (basePoint.HasValue)
                            {
                                destPoint = _getIntersectPoint(slope, destPline);
                                if (destPoint.HasValue)
                                {
                                    slope = new Line(basePoint.Value, destPoint.Value);
                                    if (slopeNumber % 2d == 0d)
                                    {
                                        slope = new Line(slope.StartPoint, slope.StartPoint.Add((slope.EndPoint - slope.StartPoint).MultiplyBy(_smallLineLength)));
                                    }
                                    slopeLines.Add(slope);
                                }
                            }
                        }
                    }
                    break;
                }
                }
            }

            return(slopeLines);
        }
Example #37
0
        private async void Initialize()
        {
            // Configure the basemap.
            _myMapView.Map = new Map(BasemapStyle.ArcGISTopographic);

            // Create the graphics overlay.
            _graphicsOverlay = new GraphicsOverlay();

            // Add the overlay to the MapView.
            _myMapView.GraphicsOverlays.Add(_graphicsOverlay);

            // Update the selection color.
            _myMapView.SelectionProperties.Color = Color.Yellow;

            // Create the point collection that defines the polygon.
            PointCollection polygonPoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-5991501.677830, 5599295.131468),
                new MapPoint(-6928550.398185, 2087936.739807),
                new MapPoint(-3149463.800709, 1840803.011362),
                new MapPoint(-1563689.043184, 3714900.452072),
                new MapPoint(-3180355.516764, 5619889.608838)
            };

            // Create the polygon.
            Polygon polygonGeometry = new Polygon(polygonPoints);

            // Define the symbology of the polygon.
            SimpleLineSymbol polygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Green, 2);
            SimpleFillSymbol polygonFillSymbol    = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Green, polygonOutlineSymbol);

            // Create the polygon graphic and add it to the graphics overlay.
            _polygonGraphic = new Graphic(polygonGeometry, polygonFillSymbol);
            _graphicsOverlay.Graphics.Add(_polygonGraphic);

            // Create the point collection that defines the polyline.
            PointCollection polylinePoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-4354240.726880, -609939.795721),
                new MapPoint(-3427489.245210, 2139422.933233),
                new MapPoint(-2109442.693501, 4301843.057130),
                new MapPoint(-1810822.771630, 7205664.366363)
            };

            // Create the polyline.
            Polyline polylineGeometry = new Polyline(polylinePoints);

            // Create the polyline graphic and add it to the graphics overlay.
            _polylineGraphic = new Graphic(polylineGeometry, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Red, 4));
            _graphicsOverlay.Graphics.Add(_polylineGraphic);

            // Create the point geometry that defines the point graphic.
            MapPoint pointGeometry = new MapPoint(-4487263.495911, 3699176.480377, SpatialReferences.WebMercator);

            // Define the symbology for the point.
            SimpleMarkerSymbol locationMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Blue, 10);

            // Create the point graphic and add it to the graphics overlay.
            _pointGraphic = new Graphic(pointGeometry, locationMarker);
            _graphicsOverlay.Graphics.Add(_pointGraphic);

            try
            {
                // Set the viewpoint to center on the point.
                await _myMapView.SetViewpointAsync(new Viewpoint(pointGeometry, 200000000));
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
Example #38
0
        public void GetAllYDBMGemo(T model, string layerName)
        {
            if (model != null)
            {
                LayerModel lm  = new LayerModel();
                Document   doc = Application.DocumentManager.MdiActiveDocument;
                Database   db  = doc.Database;

                ObjectIdCollection ids = new ObjectIdCollection();
                lm.Name = layerName;

                PromptSelectionResult ProSset = null;
                TypedValue[]          filList = new TypedValue[1] {
                    new TypedValue((int)DxfCode.LayerName, layerName)
                };
                SelectionFilter sfilter = new SelectionFilter(filList);

                ProSset = doc.Editor.SelectAll(sfilter);
                if (ProSset.Status == PromptStatus.OK)
                {
                    using (Transaction tran = db.TransactionManager.StartTransaction())
                    {
                        SelectionSet sst  = ProSset.Value;
                        ObjectId[]   oids = sst.GetObjectIds();

                        LayerTable lt = (LayerTable)db.LayerTableId.GetObject(OpenMode.ForRead);
                        foreach (ObjectId layerId in lt)
                        {
                            LayerTableRecord ltr = (LayerTableRecord)tran.GetObject(layerId, OpenMode.ForRead);
                            if (ltr.Name == layerName)
                            {
                                lm.Color = System.Drawing.ColorTranslator.ToHtml(ltr.Color.ColorValue);
                            }
                        }

                        foreach (ObjectId lengGemo in oids)
                        {
                            DBObject            ob             = tran.GetObject(lengGemo, OpenMode.ForRead);
                            PointsPlanItemModel pointsPlanItem = new PointsPlanItemModel();
                            if (ob is Polyline)
                            {
                                Polyline aPl = ob as Polyline;
                                // 读取分图则闭合多段线内的用地代码
                                List <PointF> pfs = new List <PointF>();
                                if (aPl.Closed is true)
                                {
                                    int vn2 = aPl.NumberOfVertices;  //lwp已知的多段线
                                    for (int J = 0; J < vn2; J++)
                                    {
                                        Point2d pt = aPl.GetPoint2dAt(J);
                                        PointF  pf = new PointF((float)pt.X, (float)pt.Y);
                                        pfs.Add(pf);
                                    }
                                }
                                pointsPlanItem.Num = MethodCommand.GetAttrIndex(pfs);
                            }

                            BlockInfoModel plModel = MethodCommand.AnalysisBlcokInfo(ob);
                            pointsPlanItem.Geom = plModel;

                            if (lm.modelItemList == null)
                            {
                                lm.modelItemList = new List <object>();
                            }

                            lm.modelItemList.Add(pointsPlanItem);
                        }
                    }

                    if (model.allLines == null)
                    {
                        model.allLines = new List <LayerModel>();
                    }
                    model.allLines.Add(lm);
                }
            }
        }
        //矩形绘制按钮
        public void drawRectBtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //CommandManager.Register();
            if (!HeatSourceLayoutApp.CommandManager.RequireLock())
            {
                HeatSourceLayoutApp.CommandManager.AddCommand(CommandManager.ToolCommand.DrawBuildingRect);
                Application.DocumentManager.MdiActiveDocument.SendStringToExecute("\x1B", true, false, false);

                return;
            }
            else
            {
                changeBtnStyle(2);
            }
            Utility.SetOrthoMode(false);
            HeatSourceLayoutApp.solutionPanel.SelectOutLineLayer();
            using (DocumentLock docLock = Application.DocumentManager.MdiActiveDocument.LockDocument())
            {
                Database db = HostApplicationServices.WorkingDatabase;
                Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
                while (true)
                {
                    PromptPointOptions optPoint = new PromptPointOptions
                                                      ("\n请指定矩形的一个角点");
                    PromptPointResult resPoint = ed.GetPoint(optPoint);
                    if (HeatSourceLayoutApp.CommandManager.Status())
                    {
                        HeatSourceLayoutApp.CommandManager.ReleaseLock();
                        HeatSourceLayoutApp.CommandManager.TriggerCommand();
                        return;
                    }
                    if (resPoint.Status != PromptStatus.OK)
                    {
                        HeatSourceLayoutApp.CommandManager.ReleaseLock();
                        return;
                    }
                    Point3d pt1 = resPoint.Value;


                    Polyline polyLine2 = new Polyline();
                    for (int i = 0; i < 4; i++)
                    {
                        polyLine2.AddVertexAt(i, new Point2d(0, 0), 0, 0, 0);
                    }
                    polyLine2.Closed = true;

                    polyLine2.Color = Color.FromRgb(255, 0, 0);

                    RecJig elRecJig = new RecJig(pt1, polyLine2);

                    PromptResult resJig = ed.Drag(elRecJig);
                    if (resJig.Status == PromptStatus.OK)
                    {
                        if (elRecJig.m_PolyLine2.Area >= 1e-10)
                        {
                            ObjectId objid = AppendEntity(elRecJig.m_PolyLine2);
                            Building b     = new Building(true);
                            b.BaseObjectId = objid;
                            HeatSource.HeatSourceLayoutApp.buildings.Add(objid, b);
                            //b.AddBuildingNumber();
                            b.Save();
                        }
                    }
                }
            }
        }
Example #40
0
        private static void GrowGroupAroundLoosePolyline(Obstacle group, Polyline loosePolyline)
        {
            var points = group.VisibilityPolyline.Select(p => p).Concat(loosePolyline.Select(p => p));

            group.SetConvexHull(new OverlapConvexHull(ConvexHull.CreateConvexHullAsClosedPolyline(points), new[] { group }));
        }
        private void Initialize()
        {
            // Configure the basemap
            MyMapView.Map = new Map(BasemapStyle.ArcGISTopographic);

            // Create the graphics overlay
            _graphicsOverlay = new GraphicsOverlay();

            // Add the overlay to the MapView
            MyMapView.GraphicsOverlays.Add(_graphicsOverlay);

            // Update the selection color
            MyMapView.SelectionProperties.Color = Color.Yellow;

            // Create the point collection that defines the polygon
            PointCollection polygonPoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-5991501.677830, 5599295.131468),
                new MapPoint(-6928550.398185, 2087936.739807),
                new MapPoint(-3149463.800709, 1840803.011362),
                new MapPoint(-1563689.043184, 3714900.452072),
                new MapPoint(-3180355.516764, 5619889.608838)
            };

            // Create the polygon
            Polygon polygonGeometry = new Polygon(polygonPoints);

            // Define the symbology of the polygon
            SimpleLineSymbol polygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Green, 2);
            SimpleFillSymbol polygonFillSymbol    = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, Color.Green, polygonOutlineSymbol);

            // Create the polygon graphic and add it to the graphics overlay
            _polygonGraphic = new Graphic(polygonGeometry, polygonFillSymbol);
            _graphicsOverlay.Graphics.Add(_polygonGraphic);

            // Create the point collection that defines the polyline
            PointCollection polylinePoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-4354240.726880, -609939.795721),
                new MapPoint(-3427489.245210, 2139422.933233),
                new MapPoint(-2109442.693501, 4301843.057130),
                new MapPoint(-1810822.771630, 7205664.366363)
            };

            // Create the polyline
            Polyline polylineGeometry = new Polyline(polylinePoints);

            // Create the polyline graphic and add it to the graphics overlay
            _polylineGraphic = new Graphic(polylineGeometry, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Red, 4));
            _graphicsOverlay.Graphics.Add(_polylineGraphic);

            // Create the point geometry that defines the point graphic
            MapPoint pointGeometry = new MapPoint(-4487263.495911, 3699176.480377, SpatialReferences.WebMercator);

            // Define the symbology for the point
            SimpleMarkerSymbol locationMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Blue, 10);

            // Create the point graphic and add it to the graphics overlay
            _pointGraphic = new Graphic(pointGeometry, locationMarker);
            _graphicsOverlay.Graphics.Add(_pointGraphic);

            // Listen for taps; the spatial relationships will be updated in the handler
            MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;

            // Set the viewpoint to center on the point
            MyMapView.SetViewpointCenterAsync(pointGeometry, 200000000);
        }
Example #42
0
        /// <summary>
        /// Перерисовать дорогу
        /// </summary>
        private void ShowRoad()
        {
            if (_roadObjects != null)
            {
                foreach (var roadObject in _roadObjects)
                {
                    //   var currShape = (Shape)roadObject;
                    Map.Children.Remove(roadObject);
                }
            }

            _roadObjects = new List <Shape>();

            #region Фрагменты дороги

            for (int i = 0; i < _roadElements.Count; i++)
            {
                var currElement = _roadElements[i];

                Line line = new Line
                {
                    X1              = currElement.StartPoint.X + _deltaX,
                    Y1              = currElement.StartPoint.Y + _deltaY,
                    X2              = currElement.EndPoint.X + _deltaX,
                    Y2              = currElement.EndPoint.Y + _deltaY,
                    Stroke          = GameBrushes.RoadBrush,
                    StrokeDashArray = new DoubleCollection()
                    {
                        4, 2
                    },
                    StrokeThickness = GameSettings.RoadWidth,
                    Margin          = new Thickness(5, 5, 0, 0)
                };

                Panel.SetZIndex(line, 1);
                Map.Children.Add(line);
                _roadObjects.Add(line);

                double top     = currElement.EndPoint.Y - GameSettings.RoadWidth / 2 + _deltaY;
                double left    = currElement.EndPoint.X - GameSettings.RoadWidth / 2 + _deltaX;
                var    ellipse = new Ellipse
                {
                    Width  = GameSettings.RoadWidth,
                    Height = GameSettings.RoadWidth,
                    Fill   = GameBrushes.RoadBrush,
                    Margin = new Thickness(5, 5, 0, 0)
                };
                Panel.SetZIndex(ellipse, 1);
                Map.Children.Add(ellipse);
                Canvas.SetTop(ellipse, top);
                Canvas.SetLeft(ellipse, left);
                _roadObjects.Add(ellipse);
            }

            #endregion

            #region Дорожная разметка

            var polyLinePointCollection = new PointCollection();
            foreach (var roadElement in _roadElements)
            {
                if (polyLinePointCollection.Count == 0)
                {
                    polyLinePointCollection.Add(new Point(roadElement.StartPoint.X + 5 + _deltaX, roadElement.StartPoint.Y + _deltaY));
                }
                polyLinePointCollection.Add(new Point(roadElement.EndPoint.X + 5 + _deltaX, roadElement.EndPoint.Y + _deltaY));
            }

            var polyLine = new Polyline()
            {
                Points          = polyLinePointCollection,
                Stroke          = Brushes.White,
                StrokeDashArray = new DoubleCollection()
                {
                    6, 4
                },
                StrokeThickness = 2
            };
            Panel.SetZIndex(polyLine, 12);
            Map.Children.Add(polyLine);
            _roadObjects.Add(polyLine);

            #endregion

            #region Дорожные знаки

            for (int i = 1; i < _roadElements.Count; i++)
            {
                var prevElement = _roadElements[i - 1];
                var currElement = _roadElements[i];

                // Опасный поворот
                if (Math.Abs(currElement.Angle - prevElement.Angle) > 70 && Math.Abs(currElement.Angle - prevElement.Angle) < 290)
                {
                    var sign = new Image()
                    {
                        Width  = 40,
                        Height = 40,
                        Source = new BitmapImage(new Uri("/Images/danger.png", UriKind.Relative))
                    };
                    Panel.SetZIndex(sign, 20);
                    Map.Children.Add(sign);
                    _offRoadObjects.Add(sign);
                    Canvas.SetTop(sign, currElement.StartPoint.Y + _deltaY);
                    Canvas.SetLeft(sign, currElement.StartPoint.X + _deltaX);
                }
            }

            #endregion
        }
        /// <summary>
        /// Create a geodetic circle
        /// </summary>
        private IGeometry CreateCircle()
        {
            if (Point1 == null && Point2 == null)
            {
                return(null);
            }

            // This section including UpdateDistance serves to handle Diameter appropriately
            var polyLine = new Polyline() as IPolyline;

            polyLine.SpatialReference = Point1.SpatialReference;
            var ptCol = polyLine as IPointCollection;

            ptCol.AddPoint(Point1);
            ptCol.AddPoint(Point2);

            UpdateDistance(polyLine as IGeometry);

            try
            {
                var construct = new Polyline() as IConstructGeodetic;
                if (construct != null)
                {
                    construct.ConstructGeodesicCircle(Point1, GetLinearUnit(), Distance, esriCurveDensifyMethod.esriCurveDensifyByAngle, 0.01);
                    IDictionary <String, System.Object> circleAttributes = new Dictionary <String, System.Object>();
                    double dist = 0.0;
                    if (CircleType == CircleFromTypes.Diameter)
                    {
                        dist = Distance * 2;
                    }
                    else
                    {
                        dist = Distance;
                    }

                    //circleAttributes.Add("radius", dist);
                    //circleAttributes.Add("disttype", CircleType.ToString());
                    //circleAttributes.Add("centerx", Point1.X);
                    //circleAttributes.Add("centery", Point1.Y);
                    //circleAttributes.Add("distanceunit", LineDistanceType.ToString());
                    //var color = new RgbColorClass() { Red = 255 } as IColor;
                    //this.AddGraphicToMap(construct as IGeometry, color, attributes: circleAttributes);

                    //Construct a polygon from geodesic polyline

                    var newPoly = this.PolylineToPolygon((IPolyline)construct);
                    if (newPoly != null)
                    {
                        //Get centroid of polygon
                        var area = newPoly as IArea;


                        string unitLabel      = "";
                        int    roundingFactor = 0;
                        // If Distance Calculator is in use, use the unit from the Rate combobox
                        // to label the circle
                        if (IsDistanceCalcExpanded)
                        {
                            // Select appropriate label and number of decimal places
                            switch (RateUnit)
                            {
                            case DistanceTypes.Feet:
                            case DistanceTypes.Meters:
                            case DistanceTypes.Yards:
                                unitLabel      = RateUnit.ToString();
                                roundingFactor = 0;
                                break;

                            case DistanceTypes.Miles:
                            case DistanceTypes.Kilometers:
                                unitLabel      = RateUnit.ToString();
                                roundingFactor = 2;
                                break;

                            case DistanceTypes.NauticalMile:
                                unitLabel      = "Nautical Miles";
                                roundingFactor = 2;
                                break;

                            default:
                                break;
                            }
                        }
                        // Else Distance Calculator not in use, use the unit from the Radius / Diameter combobox
                        // to label the circle
                        else
                        {
                            // Select appropriate number of decimal places
                            switch (LineDistanceType)
                            {
                            case DistanceTypes.Feet:
                            case DistanceTypes.Meters:
                            case DistanceTypes.Yards:
                                unitLabel      = RateUnit.ToString();
                                roundingFactor = 0;
                                break;

                            case DistanceTypes.Miles:
                            case DistanceTypes.Kilometers:
                                unitLabel      = RateUnit.ToString();
                                roundingFactor = 2;
                                break;

                            case DistanceTypes.NauticalMile:
                                unitLabel      = "Nautical Miles";
                                roundingFactor = 2;
                                break;

                            default:
                                break;
                            }

                            DistanceTypes dtVal = (DistanceTypes)LineDistanceType;
                            unitLabel = dtVal.ToString();
                        }

                        double convertedDistance = Distance;
                        // Distance is storing radius not diameter, so we have to double it to get the correct value
                        // for the label
                        // Only use Diameter when Distance Calculator is not in use
                        if (!IsDistanceCalcExpanded && circleType == CircleFromTypes.Diameter)
                        {
                            convertedDistance *= 2;
                        }

                        string circleTypeLabel = circleType.ToString();
                        string distanceLabel   = "";
                        // Use the unit from Rate combobox if Distance Calculator is expanded
                        if (IsDistanceCalcExpanded)
                        {
                            convertedDistance = ConvertFromTo(LineDistanceType, RateUnit, convertedDistance);
                            distanceLabel     = (TrimPrecision(convertedDistance, RateUnit, true)).ToString("N" + roundingFactor.ToString());
                            // Always label with radius when Distance Calculator is expanded
                            circleTypeLabel = "Radius";
                        }
                        else
                        {
                            distanceLabel = (TrimPrecision(convertedDistance, LineDistanceType, false)).ToString("N" + roundingFactor.ToString());
                        }
                        dist = convertedDistance;
                        //Add text using centroid point
                        this.AddTextToMap(area.Centroid, string.Format("{0}:{1} {2}",
                                                                       circleTypeLabel,
                                                                       distanceLabel,
                                                                       unitLabel));
                    }
                    circleAttributes.Add("radius", dist);
                    circleAttributes.Add("disttype", CircleType.ToString());
                    circleAttributes.Add("centerx", Point1.X);
                    circleAttributes.Add("centery", Point1.Y);
                    if (IsDistanceCalcExpanded)
                    {
                        circleAttributes.Add("distanceunit", RateUnit.ToString());
                    }
                    else
                    {
                        circleAttributes.Add("distanceunit", LineDistanceType.ToString());
                    }
                    var color = new RgbColorClass()
                    {
                        Red = 255
                    } as IColor;
                    this.AddGraphicToMap(construct as IGeometry, color, attributes: circleAttributes);
                    Point2    = null;
                    HasPoint2 = false;
                    ResetFeedback();
                }
                return(construct as IGeometry);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }
Example #44
0
        void timer_Tick(object sender, EventArgs e)
        {
            //     stream = new IsolatedStorageFileStream("shared/transfers/634708322772702206", FileMode.Open, fileStorage);
            //BinaryReader reader = new BinaryReader(stream1);
            //long length = stream1.Length;

            //       BinaryReader reader = new BinaryReader(stream);
            //  long length = stream1.Length;
            int[] a = new int[96];

            //清空原有的图像,覆盖上新的ECG===================================
            canvas1.Children.Clear();
            for (i = 0; i <= canvas1.Height; i += 10)
            {
                Line BaseLine = new Line();
                BaseLine.Stroke = new SolidColorBrush(Colors.Orange);

                BaseLine.X1 = 0;
                BaseLine.Y1 = i;
                BaseLine.X2 = canvas1.Width;
                BaseLine.Y2 = i;
                canvas1.Children.Add(BaseLine);
            }

            for (i = 0; i <= canvas1.Width; i += 10)
            {
                Line VerLine = new Line();
                VerLine.Stroke = new SolidColorBrush(Colors.Orange);

                VerLine.X1 = i;
                VerLine.Y1 = 0;
                VerLine.X2 = i;
                VerLine.Y2 = canvas1.Height;
                canvas1.Children.Add(VerLine);
            }
            //========================================================

            Polyline Chatline = new Polyline();

            Chatline.Stroke          = new SolidColorBrush(Colors.Red);
            Chatline.StrokeThickness = 4;
            //for (i = list.Count - 1; i >= list.Count-44; i--)
            //{
            //    Chatline.Points.Add(new Point((i - 1) * 5, canvas1.Height - list[i]));

            //}
            //int i = (int)reader.ReadByte();
            //Chatline.Points.Add(new Point(10,i));
            //int j =  (int)reader.ReadByte();
            //Chatline.Points.Add(new Point(20, j));
            //   canvas1.Children.Remove(Chatline);
            try
            {
                count = count + 80;
                for (i = 0; i < 80; i++)
                {
                    a[i] = buffer[count + i];
                    if (a[i] > -1 && i % 2 == 1)
                    {
                        int j = (a[i - 1] * 256 + a[i]) / 2;

                        list.Add(j);
                        // Chatline.Points.Add(new Point((i - 1) * 5, canvas1.Height - j));
                    }
                    else if (a[i] == -1)
                    {
                        timer.Stop();
                        return;
                    }
                }

                for (i = 0; i < 384; i++)
                {
                    Chatline.Points.Add(new Point(canvas1.Width - (i) * 1.25, canvas1.Height - list[list.Count - 1 - i]));
                }
            }
            catch (Exception) {
                stream.Close();
            }


            //Polyline Chatline = new Polyline();
            //int[] a = new int[48];
            //Chatline.Stroke = new SolidColorBrush(Colors.Red);
            //canvas1.Children.Remove(Chatline);
            //if (count < totallength-48)
            //{
            //    for (int i = 0; i < 48; i++)
            //    {
            //        a[i] = (int)canvas1.Height-((int)data1[i]);
            //        Chatline.Points.Add(new Point(i * 10, a[i]));
            //        // textBlock1.Text += (int)data1[i];
            //        //if (i % 5 == 0)
            //        //{
            //        //    Chatline.Points.Add(new Point(i % 400, (int)data1[i]));

            //        //}
            //        count += 48;

            //    }

            //}

            canvas1.Children.Add(Chatline);
        }
Example #45
0
        /***************************************************/

        public static bool IsInPlane(this Polyline curve, Plane plane, double tolerance = Tolerance.Distance)
        {
            return(curve.ControlPoints.IsInPlane(plane, tolerance));
        }
Example #46
0
        void updateMyScreen()
        {
            //Polyline ChartLine = new Polyline();
            //ChartLine.Stroke = new SolidColorBrush(Colors.Red);



            for (i = 0; i <= canvas1.Height; i += 10)
            {
                Line BaseLine = new Line();
                BaseLine.Stroke = new SolidColorBrush(Colors.Orange);

                BaseLine.X1 = 0;
                BaseLine.Y1 = i;
                BaseLine.X2 = canvas1.Width;
                BaseLine.Y2 = i;
                canvas1.Children.Add(BaseLine);
            }

            for (i = 0; i <= canvas1.Width; i += 10)
            {
                Line VerLine = new Line();
                VerLine.Stroke = new SolidColorBrush(Colors.Orange);

                VerLine.X1 = i;
                VerLine.Y1 = 0;
                VerLine.X2 = i;
                VerLine.Y2 = canvas1.Height;
                canvas1.Children.Add(VerLine);
            }

            //  Stream stream1 = App.GetResourceStream(new Uri("shared/transfers/634708322772702206", UriKind.Relative)).Stream;
            //     byte[] data1;
            // data1=ReadFully(stream1);
            string filelocation = "shared/transfers/" + ECGFileName;

            stream = new IsolatedStorageFileStream(filelocation, FileMode.Open, fileStorage);
            // long longth = stream.Length;



            BinaryReader reader = new BinaryReader(stream);

            buffer = new byte[stream.Length];
            buffer = reader.ReadBytes((int)stream.Length);

            count = 0;
            int[]    a        = new int[768];
            Polyline Chatline = new Polyline();

            Chatline.Stroke          = new SolidColorBrush(Colors.Red);
            Chatline.StrokeThickness = 4;
            //for (i = 0; i < 768; i++)
            //{
            //    a[i] = reader.ReadByte();
            //    if (a[i] > -1 && i % 2 == 1)
            //    {

            //        int j = (a[i - 1] * 256 + a[i])/2;
            //        list.Add(j);
            //        Chatline.Points.Add(new Point((i - 1) * 0.625, canvas1.Height - j));
            //    }
            //}
            //canvas1.Children.Add(Chatline);



            for (i = 0; i < 768; i++)
            {
                count++;
                a[i] = buffer[i];
                if (a[i] > -1 && i % 2 == 1)
                {
                    int j = (a[i - 1] * 256 + a[i]) / 2;
                    list.Add(j);
                    Chatline.Points.Add(new Point((i - 1) * 0.625, canvas1.Height - j));
                }
            }
            canvas1.Children.Add(Chatline);



            // judge=1;

            //   DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 200);

            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();

            //    timer.Stop();
            //    timer.Stop();
            //     if()
        }
Example #47
0
        private void CrearGrafica()
        {
            const double margin = 10;
            double       xmin   = margin;
            double       xmax   = canGraph.Width - margin;
            double       ymin   = margin;
            double       ymax   = canGraph.Height - margin;
            const double step   = 10;

            // Make the X axis.
            GeometryGroup xaxis_geom = new GeometryGroup();

            xaxis_geom.Children.Add(new LineGeometry(
                                        new Point(0, ymax), new Point(canGraph.Width, ymax)));
            for (double x = xmin + step;
                 x <= canGraph.Width - step; x += step)
            {
                xaxis_geom.Children.Add(new LineGeometry(
                                            new Point(x, ymax - margin / 2),
                                            new Point(x, ymax + margin / 2)));
            }

            System.Windows.Shapes.Path xaxis_path = new System.Windows.Shapes.Path();
            xaxis_path.StrokeThickness = 1;
            xaxis_path.Stroke          = Brushes.Black;
            xaxis_path.Data            = xaxis_geom;

            canGraph.Children.Add(xaxis_path);

            // Make the Y ayis.
            GeometryGroup yaxis_geom = new GeometryGroup();

            yaxis_geom.Children.Add(new LineGeometry(
                                        new Point(xmin, 0), new Point(xmin, canGraph.Height)));
            for (double y = step; y <= canGraph.Height - step; y += step)
            {
                yaxis_geom.Children.Add(new LineGeometry(
                                            new Point(xmin - margin / 2, y),
                                            new Point(xmin + margin / 2, y)));
            }

            System.Windows.Shapes.Path yaxis_path = new System.Windows.Shapes.Path();
            yaxis_path.StrokeThickness = 1;
            yaxis_path.Stroke          = Brushes.Black;
            yaxis_path.Data            = yaxis_geom;

            canGraph.Children.Add(yaxis_path);

            // Make some data sets.
            Brush[] brushes = { Brushes.Red, Brushes.Green, Brushes.Blue };
            Random  rand    = new Random();

            for (int data_set = 0; data_set < 3; data_set++)
            {
                int last_y = rand.Next((int)ymin, (int)ymax);

                PointCollection points = new PointCollection();
                for (double x = xmin; x <= xmax; x += step)
                {
                    last_y = rand.Next(last_y - 10, last_y + 10);
                    if (last_y < ymin)
                    {
                        last_y = (int)ymin;
                    }
                    if (last_y > ymax)
                    {
                        last_y = (int)ymax;
                    }
                    points.Add(new Point(x, last_y));
                }

                Polyline polyline = new Polyline();
                polyline.StrokeThickness = 1;
                polyline.Stroke          = brushes[data_set];
                polyline.Points          = points;

                canGraph.Children.Add(polyline);
            }
        }
Example #48
0
        //selected strokes context menu functionality
        private void DrawPathSelectedStrokes(Object sender, RoutedEventArgs e)
        {
            runAllAnimationsButton.IsEnabled = false;
            //TODO We still want the canvas we just want to hide it.
            selectionCanvas.Visibility = Visibility.Collapsed;
            inkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed;
            var currentTool = inkToolbar.ActiveTool;


            inkToolbar.ActiveTool = animationPen;
            inkToolbar.Children.Add(animationPen);

            void pressed(InkUnprocessedInput i, PointerEventArgs p)
            {
                polyline = new Polyline()
                {
                    Stroke          = new SolidColorBrush(Windows.UI.Colors.ForestGreen),
                    StrokeThickness = 1.5,
                    StrokeDashArray = new DoubleCollection()
                    {
                        5, 2
                    },
                };
                polyline.Points.Add(p.CurrentPoint.Position);
                polyCanvas.Children.Add(polyline);
            }

            void moved(InkUnprocessedInput i, PointerEventArgs p)
            {
                polyline.Points.Add(p.CurrentPoint.Position);
            }

            async void released(InkUnprocessedInput i, PointerEventArgs p)
            {
                polyline.Points.Add(p.CurrentPoint.Position);
                polyline.Opacity = 0.5;
                inkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.AllowProcessing;
                inkCanvas.InkPresenter.UnprocessedInput.PointerPressed  -= pressed;
                inkCanvas.InkPresenter.UnprocessedInput.PointerMoved    -= moved;
                inkCanvas.InkPresenter.UnprocessedInput.PointerReleased -= released;
                ClearAllHandlers();
                Animation anime = new Animation();

                foreach (var stroke in inkCanvas.InkPresenter.StrokeContainer.GetStrokes())
                {
                    if (stroke.Selected)
                    {
                        anime.inkStrokes.Add(stroke);
                        anime.inkStrokesId.Add(stroke.Id);
                        anime.inkStrokesIndex.Add(inkCanvas.InkPresenter.StrokeContainer.GetStrokes().ToList().IndexOf(stroke));
                    }
                }
                anime.SetPolyline(polyline);
                addPolylineText(anime);
                inkToolbar.ActiveTool = currentTool;
                inkToolbar.Children.Remove(animationPen);
                var container = inkCanvas.InkPresenter.StrokeContainer;

                animations.Add(anime);

                await RunAnimation(anime, true);

                selectionCanvas.Visibility = Visibility.Visible;

                ClearSelection();
                runAllAnimationsButton.IsEnabled = true;
            }

            inkCanvas.InkPresenter.UnprocessedInput.PointerPressed  += pressed;
            inkCanvas.InkPresenter.UnprocessedInput.PointerMoved    += moved;
            inkCanvas.InkPresenter.UnprocessedInput.PointerReleased += released;
        }
 bool HoleSideIsVisibleFromQ(Polyline hole, PolylinePoint b)
 {
     return(Point.SignedDoubledTriangleArea(q, b.Point, hole.Next(b).Point) >= -ApproximateComparer.SquareOfDistanceEpsilon);
 }
 void UpdateDisplay()
 {
     Path = new Polyline(_order.Select(i => _cities[i]));
     Info = $"Fitness: {_currentFitness:0.0} ({++_betterCandidateCount}/{_iterations})";
 }
Example #51
0
        private void SetupYAxis()
        {
            YAxis.Children.Clear();
            YLabels.Children.Clear();

            //Adding the vertical axis line
            yAxisLine = new Polyline();
            double lineH = GraphHeight + AxisThickness + GraphContentPadding + AxisOutlineLenght;

            yAxisLine.Points.Add(new Point(AxisThickness, AxisThickness / 2));
            yAxisLine.Points.Add(new Point(AxisThickness, lineH));
            yAxisLine.Stroke          = AxisColor;
            yAxisLine.StrokeThickness = 0.5;

            //Adding the labels and the unit lines

            //Calculatin the steps height
            Double offset     = 0;
            int    n_division = 0;
            double stepHeight = GraphHeight;

            if (maxY <= (VerticalSteps - 1))
            {
                stepHeight = GraphHeight / (VerticalSteps - 1);
            }
            else
            {
                while (stepHeight > (VerticalSteps - 1))
                {
                    n_division++;
                    stepHeight = stepHeight / (VerticalSteps - 1);
                }
                //if ((stepHeight - Math.Round(stepHeight)) < 0.5) stepHeight += 0.5;
                stepHeight = Math.Round(stepHeight, MidpointRounding.AwayFromZero);
                for (int i = 0; i < n_division; i++)
                {
                    stepHeight = stepHeight * (VerticalSteps - 1);
                }
                stepHeight = stepHeight / (VerticalSteps - 1);
            }
            //Adding the lines
            for (int i = 0; i < VerticalSteps; i++)
            {
                double   verticalPosition = AxisThickness + GraphContentPadding + offset;
                Polyline line             = new Polyline();
                line.Points.Add(new Point(AxisThickness / 2, verticalPosition));
                line.Points.Add(new Point(AxisThickness, verticalPosition));
                line.Stroke          = AxisColor;
                line.StrokeThickness = 0.5;
                YAxis.Children.Add(line);

                //Adding the labels

                TextBlock stepLabel = new TextBlock
                {
                    Text       = Math.Round((i * stepHeight) * (maxY - minY) / GraphHeight + minY, 1).ToString(),
                    FontSize   = 8,
                    Foreground = LabelsColor
                };
                Canvas.SetBottom(stepLabel, verticalPosition - stepLabel.FontSize / 2);
                Canvas.SetLeft(stepLabel, -((stepLabel.Text.Length * stepLabel.FontSize) / 2));
                YLabels.Children.Add(stepLabel);

                offset += stepHeight;
                //Avoiding lines over the vertical axis arrow
                if ((verticalPosition + stepHeight) > lineH - AxisOutlineLenght)
                {
                    break;
                }
            }

            //Adding the Y axis name label
            Decorator label = CanvasLabel(YAxisName, -AxisThickness, lineH + 5, LabelsColor, 10);

            label.Width  = 50;
            label.Height = 15;
            YLabels.Children.Add(label);

            //Adding the arrow on top of the axis line
            Polyline arrow = VerticalArrow(new Point(AxisThickness, lineH), AxisThickness / 2);

            arrow.Stroke          = AxisColor;
            arrow.StrokeThickness = 1;
            YAxis.Children.Add(yAxisLine);
            YAxis.Children.Add(arrow);
            Graph.Height = lineH + label.Height + 10;
        }
Example #52
0
        protected override SamplerStatus Sampler(JigPrompts Prompts)
        {
            PromptPointResult promptPointResult = Prompts.AcquirePoint(new JigPromptPointOptions("\r\n请指定下一点:")
            {
                Cursor       = 3,
                BasePoint    = this.point3d_0,
                UseBasePoint = true
            });
            Point3d       value = promptPointResult.Value;
            SamplerStatus result;

            if (value != this.point3d_1)
            {
                Point3d point3d  = this.point3d_0;
                Point3d point3d2 = value;
                if (point3d.X > point3d2.X)
                {
                    Point3d point3d3 = point3d;
                    point3d  = point3d2;
                    point3d2 = point3d3;
                }
                else if (point3d.X == point3d2.X & point3d.Y > point3d2.Y)
                {
                    Point3d point3d4 = point3d;
                    point3d  = point3d2;
                    point3d2 = point3d4;
                }
                double   num         = point3d.GetVectorTo(point3d2).AngleOnPlane(new Plane());
                Point3d  pointAngle  = CAD.GetPointAngle(point3d, 100.0 * this.double_0, num * 180.0 / 3.1415926535897931 + 90.0);
                Point3d  pointAngle2 = CAD.GetPointAngle(point3d2, 100.0 * this.double_0, num * 180.0 / 3.1415926535897931 + 90.0);
                Point3d  pointAngle3 = CAD.GetPointAngle(point3d, 141.0 * this.double_0, num * 180.0 / 3.1415926535897931 + 45.0);
                Point3d  pointAngle4 = CAD.GetPointAngle(point3d2, 141.0 * this.double_0, num * 180.0 / 3.1415926535897931 - 225.0);
                Polyline polyline    = new Polyline();
                polyline.SetDatabaseDefaults();
                double   num2      = Math.Tan(Math.Atan(1.0) * 4.0 / 4.0);
                Polyline polyline2 = polyline;
                int      num3      = 0;
                Point2d  point2d;
                point2d..ctor(pointAngle3.get_Coordinate(0), pointAngle3.get_Coordinate(1));
                polyline2.AddVertexAt(num3, point2d, 0.0, 45.0 * this.double_0, 45.0 * this.double_0);
                Polyline polyline3 = polyline;
                int      num4      = 1;
                point2d..ctor(pointAngle.get_Coordinate(0), pointAngle.get_Coordinate(1));
                polyline3.AddVertexAt(num4, point2d, num2, 45.0 * this.double_0, 45.0 * this.double_0);
                Polyline polyline4 = polyline;
                int      num5      = 2;
                point2d..ctor(point3d.get_Coordinate(0), point3d.get_Coordinate(1));
                polyline4.AddVertexAt(num5, point2d, 0.0, 45.0 * this.double_0, 45.0 * this.double_0);
                Polyline polyline5 = polyline;
                int      num6      = 3;
                point2d..ctor(point3d2.get_Coordinate(0), point3d2.get_Coordinate(1));
                polyline5.AddVertexAt(num6, point2d, num2, 45.0 * this.double_0, 45.0 * this.double_0);
                Polyline polyline6 = polyline;
                int      num7      = 4;
                point2d..ctor(pointAngle2.get_Coordinate(0), pointAngle2.get_Coordinate(1));
                polyline6.AddVertexAt(num7, point2d, 0.0, 45.0 * this.double_0, 45.0 * this.double_0);
                Polyline polyline7 = polyline;
                int      num8      = 5;
                point2d..ctor(pointAngle4.get_Coordinate(0), pointAngle4.get_Coordinate(1));
                polyline7.AddVertexAt(num8, point2d, 0.0, 45.0 * this.double_0, 45.0 * this.double_0);
                polyline.Layer   = "正筋";
                this.entity_0[0] = polyline;
                this.point3d_1   = value;
                result           = 0;
            }
            else
            {
                result = 1;
            }
            return(result);
        }
Example #53
0
        // 2 Points, 2 Heights
        private void DrawInsulationOnTwoPointsTwoHeights(PromptPointResult firstPoint)
        {
            #region input data

            var firstPointResult  = firstPoint;
            var secondPointResult = _editorHelper.PromptForPoint("\nSelect SECOND point.", true, true,
                                                                 firstPointResult.Value);
            if (secondPointResult.Status != PromptStatus.OK)
            {
                return;
            }

            var thicknessAtFirstPointResult = _editorHelper.PromptForDouble("\nThickness at FIRST point : ",
                                                                            Settings.Default
                                                                            .SInsulationThicknessAtFirstPoint);
            if (thicknessAtFirstPointResult.Status != PromptStatus.OK)
            {
                return;
            }
            Settings.Default.SInsulationThicknessAtFirstPoint = thicknessAtFirstPointResult.Value;

            var thicknessAtSecondPointResult = _editorHelper.PromptForDouble("\nThickness at SECOND point : ",
                                                                             Settings.Default
                                                                             .SInsulationThicknessAtSecondPoint);
            if (thicknessAtSecondPointResult.Status != PromptStatus.OK)
            {
                return;
            }
            Settings.Default.SInsulationThicknessAtSecondPoint = thicknessAtSecondPointResult.Value;
            Settings.Default.Save();

            if (Math.Abs(firstPointResult.Value.Z) > 0.00001 || Math.Abs(secondPointResult.Value.Z) > 0.00001)
            {
                _editorHelper.WriteMessage("Soft Insulation should be placed in OXY plane !");
                _logger.Info("User input is invalid.");
                return;
            }
            #endregion

            #region preparation

            var minThickness = (thicknessAtFirstPointResult.Value < thicknessAtSecondPointResult.Value)
                                   ? thicknessAtFirstPointResult.Value
                                   : thicknessAtSecondPointResult.Value;
            var segmentsCount =
                (int)Math.Ceiling((firstPointResult.Value.DistanceTo(secondPointResult.Value) / minThickness) / 0.35);

            var     botLeftPoint = new Complex(0, 0);
            var     botRightPoint = new Complex(firstPointResult.Value.DistanceTo(secondPointResult.Value), 0);
            Complex topLeftPoint, topRightPoint;
            if (thicknessAtFirstPointResult.Value <= thicknessAtSecondPointResult.Value)
            {
                topLeftPoint  = new Complex(0, thicknessAtFirstPointResult.Value);
                topRightPoint = new Complex(firstPointResult.Value.DistanceTo(secondPointResult.Value),
                                            thicknessAtSecondPointResult.Value);
            }
            else
            {
                topLeftPoint  = new Complex(0, thicknessAtSecondPointResult.Value);
                topRightPoint = new Complex(firstPointResult.Value.DistanceTo(secondPointResult.Value),
                                            thicknessAtFirstPointResult.Value);
            }

            var vectorOfBaseLine = new Complex(secondPointResult.Value.X, secondPointResult.Value.Y) -
                                   new Complex(firstPointResult.Value.X, firstPointResult.Value.Y);

            var radiusBotCircle = firstPointResult.Value.DistanceTo(secondPointResult.Value) / (segmentsCount + 0.5);
            radiusBotCircle /= 2.0;

            var vectorTopEdge         = topRightPoint - topLeftPoint;
            var vectorTopEdgeOrt      = vectorTopEdge / vectorTopEdge.abs();
            var vectorNormalOfTopEdge = vectorTopEdgeOrt * (new Complex(0, 1.0));

            #endregion

            #region calculateCenterCircle

            var centersBotCircles = new List <Complex>();
            for (var i = 0; i < segmentsCount + 1; i++)
            {
                centersBotCircles.Add(new Complex(i * 2 * radiusBotCircle, radiusBotCircle));
            }

            var centersTopCircles = new List <KeyValuePair <double, Complex> >();
            var ordinate          = new Line2d(new Complex(radiusBotCircle, 0), new Complex(radiusBotCircle, 100));
            var offsetTopEdge     = new Line2d(topLeftPoint - vectorNormalOfTopEdge * radiusBotCircle,
                                               topRightPoint - vectorNormalOfTopEdge * radiusBotCircle);
            var centerFirstUpperCircle = offsetTopEdge.IntersectWitch(ordinate);
            centersTopCircles.Add(new KeyValuePair <double, Complex>(radiusBotCircle, centerFirstUpperCircle));

            if (((topRightPoint - topLeftPoint).arg()) * 180.0 / Math.PI <= 5)
            {
                for (var i = 1; i < segmentsCount + 1; i++)
                {
                    var rightVerticalEdge = new Line2d(botRightPoint, topRightPoint);
                    var lineParallelToX   = new Line2d(centersTopCircles[i - 1].Value,
                                                       centersTopCircles[i - 1].Value +
                                                       new Complex(rightVerticalEdge.A, rightVerticalEdge.B));
                    var distFromCurrentCircleToRightVertEdge =
                        Math.Abs(
                            (centersTopCircles[i - 1].Value - lineParallelToX.IntersectWitch(rightVerticalEdge)).abs() -
                            centersTopCircles[i - 1].Key);
                    var radiusTopCircle = (distFromCurrentCircleToRightVertEdge / (segmentsCount - i + 0.5)) / 2.0;

                    var rR = centersTopCircles[i - 1].Key + radiusTopCircle;
                    var dR = Math.Abs(radiusTopCircle - centersTopCircles[i - 1].Key);
                    var distBetweenCenters  = Math.Sqrt(rR * rR - dR * dR);
                    var centerNextTopCircle = centersTopCircles[i - 1].Value - vectorNormalOfTopEdge * dR +
                                              vectorTopEdgeOrt * distBetweenCenters;
                    centersTopCircles.Add(new KeyValuePair <double, Complex>(radiusTopCircle, centerNextTopCircle));
                }
            }
            else
            {
                for (var i = 1; i < segmentsCount + 1; i++)
                {
                    var tangentPoints = GetTangentPointsOfCommonExternalTanget(centersBotCircles[i], radiusBotCircle,
                                                                               centersTopCircles[i - 1].Value,
                                                                               centersTopCircles[i - 1].Key, true);
                    var vectorCommonTangent        = tangentPoints.Value - tangentPoints.Key;
                    var vectorCommonTangentOrt     = vectorCommonTangent / vectorCommonTangent.abs();
                    var vectorTranslationTopCircle = vectorCommonTangentOrt * (new Complex(0, 1.0));

                    var dL = new Line2d(tangentPoints.Value, tangentPoints.Value + vectorTranslationTopCircle * 100);
                    var rightVerticalEdge = new Line2d(botRightPoint, topRightPoint);
                    var dist            = (tangentPoints.Value - dL.IntersectWitch(rightVerticalEdge)).abs();
                    var radiusTopCircle = (dist / (segmentsCount - i + 0.5)) / 2.0;

                    var hlpLine = new Line2d(tangentPoints.Key - vectorTranslationTopCircle * radiusTopCircle,
                                             tangentPoints.Value - vectorTranslationTopCircle * radiusTopCircle);
                    var offsetTopEdgeOnRadiusTopCircle = new Line2d(
                        topLeftPoint - vectorNormalOfTopEdge * radiusTopCircle,
                        topRightPoint - vectorNormalOfTopEdge * radiusTopCircle);
                    centersTopCircles.Add(new KeyValuePair <double, Complex>(radiusTopCircle,
                                                                             offsetTopEdgeOnRadiusTopCircle
                                                                             .IntersectWitch(hlpLine)));
                }
            }

            #endregion

            #region calculatePointsForPolylineInsulation
            var insulationPolyline = new Polyline();
            insulationPolyline.SetDatabaseDefaults();
            insulationPolyline.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
            var firstPairTangentPoints = GetTangentPointsOfCommonInternalTanget(centersBotCircles[0],
                                                                                radiusBotCircle,
                                                                                centersTopCircles[0].Value,
                                                                                centersTopCircles[0].Key, false);
            var ang = ((firstPairTangentPoints.Key - centersBotCircles[0]) / -centersBotCircles[0]).arg();
            insulationPolyline.AddVertexAt(0,
                                           new Point2d(firstPairTangentPoints.Key.real(),
                                                       firstPairTangentPoints.Key.imag()), -Math.Tan(ang / 4), 0, 0);
            insulationPolyline.AddVertexAt(0,
                                           new Point2d(firstPairTangentPoints.Value.real(),
                                                       firstPairTangentPoints.Value.imag()), 0, 0, 0);
            var secondPairTangentPoints = GetTangentPointsOfCommonInternalTanget(centersBotCircles[1],
                                                                                 radiusBotCircle,
                                                                                 centersTopCircles[0].Value,
                                                                                 centersTopCircles[0].Key, true);
            ang =
                ((centersTopCircles[0].Value - firstPairTangentPoints.Value) /
                 (centersTopCircles[0].Value - secondPairTangentPoints.Value)).arg();
            insulationPolyline.AddVertexAt(0,
                                           new Point2d(secondPairTangentPoints.Value.real(),
                                                       secondPairTangentPoints.Value.imag()), Math.Tan(ang / 4), 0,
                                           0);
            insulationPolyline.AddVertexAt(0,
                                           new Point2d(secondPairTangentPoints.Key.real(),
                                                       secondPairTangentPoints.Key.imag()), 0, 0, 0);
            var oldPair = secondPairTangentPoints;
            for (var i = 1; i < segmentsCount; i++)
            {
                var pairBotRightTopLeft = GetTangentPointsOfCommonInternalTanget(centersBotCircles[i],
                                                                                 radiusBotCircle,
                                                                                 centersTopCircles[i].Value,
                                                                                 centersTopCircles[i].Key,
                                                                                 false);
                var pairTopRightBotLeft = GetTangentPointsOfCommonInternalTanget(centersBotCircles[i + 1],
                                                                                 radiusBotCircle,
                                                                                 centersTopCircles[i].Value,
                                                                                 centersTopCircles[i].Key,
                                                                                 true);
                ang = ((pairBotRightTopLeft.Key - centersBotCircles[i]) / (oldPair.Key - centersBotCircles[i])).arg();
                insulationPolyline.AddVertexAt(0,
                                               new Point2d(pairBotRightTopLeft.Key.real(),
                                                           pairBotRightTopLeft.Key.imag()),
                                               -Math.Tan(ang / 4), 0, 0);
                insulationPolyline.AddVertexAt(0,
                                               new Point2d(pairBotRightTopLeft.Value.real(),
                                                           pairBotRightTopLeft.Value.imag()), 0, 0, 0);

                ang =
                    ((centersTopCircles[i].Value - pairBotRightTopLeft.Value) /
                     (centersTopCircles[i].Value - pairTopRightBotLeft.Value)).arg();
                insulationPolyline.AddVertexAt(0,
                                               new Point2d(pairTopRightBotLeft.Value.real(),
                                                           pairTopRightBotLeft.Value.imag()),
                                               Math.Tan(ang / 4), 0, 0);
                insulationPolyline.AddVertexAt(0,
                                               new Point2d(pairTopRightBotLeft.Key.real(),
                                                           pairTopRightBotLeft.Key.imag()), 0, 0, 0);
                oldPair = pairTopRightBotLeft;
            }
            var lastPairTangentPoints = GetTangentPointsOfCommonInternalTanget(centersBotCircles[segmentsCount],
                                                                               radiusBotCircle,
                                                                               centersTopCircles[segmentsCount]
                                                                               .Value,
                                                                               centersTopCircles[segmentsCount].Key,
                                                                               false);
            ang =
                ((lastPairTangentPoints.Key - centersBotCircles[segmentsCount]) /
                 (oldPair.Key - centersBotCircles[segmentsCount])).arg();
            insulationPolyline.AddVertexAt(0,
                                           new Point2d(lastPairTangentPoints.Key.real(),
                                                       lastPairTangentPoints.Key.imag()), -Math.Tan(ang / 4), 0, 0);
            insulationPolyline.AddVertexAt(0,
                                           new Point2d(lastPairTangentPoints.Value.real(),
                                                       lastPairTangentPoints.Value.imag()), 0, 0, 0);

            var hlpPointForLastBulge = new Complex(centersTopCircles[segmentsCount].Value.real(),
                                                   centersTopCircles[segmentsCount].Value.imag() +
                                                   centersTopCircles[segmentsCount].Key);
            ang =
                ((centersTopCircles[segmentsCount].Value - lastPairTangentPoints.Value) /
                 (centersTopCircles[segmentsCount].Value - hlpPointForLastBulge)).arg();
            insulationPolyline.AddVertexAt(0, new Point2d(hlpPointForLastBulge.real(), hlpPointForLastBulge.imag()),
                                           Math.Tan(ang / 4), 0, 0);

            #endregion

            #region add contur to poly

            insulationPolyline.AddVertexAt(0, new Point2d(topRightPoint.real(), hlpPointForLastBulge.imag()), 0, 0,
                                           0);
            insulationPolyline.AddVertexAt(0, new Point2d(botRightPoint.real(), botRightPoint.imag()), 0, 0, 0);
            insulationPolyline.AddVertexAt(0, new Point2d(botLeftPoint.real(), botLeftPoint.imag()), 0, 0, 0);
            insulationPolyline.AddVertexAt(0, new Point2d(topLeftPoint.real(), topLeftPoint.imag()), 0, 0, 0);
            insulationPolyline.AddVertexAt(0, new Point2d(topRightPoint.real(), topRightPoint.imag()), 0, 0, 0);
            insulationPolyline.AddVertexAt(0, new Point2d(topRightPoint.real(), hlpPointForLastBulge.imag()), 0, 0,
                                           0);

            #endregion

            #region transforms

            if (thicknessAtFirstPointResult.Value > thicknessAtSecondPointResult.Value)
            {
                var acPtFrom = new Point3d(botRightPoint.x / 2, botRightPoint.y / 2, 0);
                var acPtTo   = new Point3d(botRightPoint.x / 2, 100, 0);
                var acLine3d = new Line3d(acPtFrom, acPtTo);
                insulationPolyline.TransformBy(Matrix3d.Mirroring(acLine3d));
            }
            insulationPolyline.TransformBy(Matrix3d.Rotation(vectorOfBaseLine.arg(), new Vector3d(0, 0, 1),
                                                             Point3d.Origin));
            insulationPolyline.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(firstPointResult.Value)));
            insulationPolyline.TransformBy(_editorHelper.CurrentUcs);

            #endregion

            var oldLayer =
                Application.DocumentManager.MdiActiveDocument.Editor.Document
                .Database.Clayer;
            _documentHelper.LayerManipulator.CreateLayer("3-0", System.Drawing.Color.Lime);

            var softInsulationBlock = new BlockTableRecord();
            var nameSalt            = DateTime.Now.GetHashCode().ToString();
            softInsulationBlock.Name   = "SoftInsulation_" + nameSalt;
            softInsulationBlock.Origin = firstPointResult.Value;

            insulationPolyline.Layer = "0";

            #region addObjectsToDataBase
            using (var acTrans = _documentHelper.TransactionManager.StartTransaction())
            {
                var blockTable =
                    acTrans.GetObject(
                        Application.DocumentManager.MdiActiveDocument.Editor
                        .Document.Database.BlockTableId, OpenMode.ForWrite) as BlockTable;

                blockTable.Add(softInsulationBlock);
                acTrans.AddNewlyCreatedDBObject(softInsulationBlock, true);

                softInsulationBlock.AppendEntity(insulationPolyline);
                acTrans.AddNewlyCreatedDBObject(insulationPolyline, true);

                var rigidInsulationRef = new BlockReference(firstPointResult.Value,
                                                            softInsulationBlock.ObjectId)
                {
                    Layer = "3-0"
                };
                var currentSpace =
                    (BlockTableRecord)
                    acTrans.GetObject(
                        Application.DocumentManager.MdiActiveDocument.Editor
                        .Document.Database.CurrentSpaceId, OpenMode.ForWrite);

                currentSpace.AppendEntity(rigidInsulationRef);
                acTrans.AddNewlyCreatedDBObject(rigidInsulationRef, true);
                acTrans.Commit();
            }
            #endregion

            _documentHelper.LayerManipulator.ChangeLayer(oldLayer);
        }
        async private Task Query()
        {
            _features.Clear();

            string where = String.IsNullOrEmpty(_where) ?
                           $"{ _featureClass.IDFieldName }>{ _lastOid }" :
                           $"{ _where } and { _featureClass.IDFieldName }>{ _lastOid }";

            var postData = $"{ _postData }&orderByFields={ _featureClass.IDFieldName }&where={ where.UrlEncodeWhereClause() }";

            var jsonFeatureResponse = await _dataset.TryPostAsync <JsonFeatureResponse>(_queryUrl, postData);

            #region Parse Field Types (eg. is Date?)

            List <string> dateColumns = new List <string>();
            if (_featureClass?.Fields != null)
            {
                foreach (var field in _featureClass.Fields.ToEnumerable())
                {
                    if (field.type == FieldType.Date)
                    {
                        dateColumns.Add(field.name);
                    }
                }
            }

            #endregion

            foreach (var jsonFeature in jsonFeatureResponse.Features)
            {
                Feature feature = new Feature();

                #region Geometry

                if (_featureClass.GeometryType == geometryType.Polyline && jsonFeature.Geometry?.Paths != null)
                {
                    Polyline polyline = new Polyline();
                    for (int p = 0, to = jsonFeature.Geometry.Paths.Length; p < to; p++)
                    {
                        Path path = new Path();

                        var pathsPointsArray       = jsonFeature.Geometry.Paths[p];
                        var dimension              = pathsPointsArray.GetLength(1); // 2D 3D 3D+M ?
                        int pathsPointsArrayLength = (pathsPointsArray.Length / dimension);

                        for (int multiArrayIndex = 0; multiArrayIndex < pathsPointsArrayLength; multiArrayIndex++)
                        {
                            path.AddPoint(ArrayToPoint(pathsPointsArray, multiArrayIndex, dimension));
                        }
                        polyline.AddPath(path);
                    }

                    feature.Shape = polyline;
                }
                else if (_featureClass.GeometryType == geometryType.Polygon && jsonFeature.Geometry?.Rings != null)
                {
                    Polygon polygon = new Polygon();
                    for (int r = 0, to = jsonFeature.Geometry.Rings.Length; r < to; r++)
                    {
                        Ring ring = new Ring();

                        var ringsPointsArray       = jsonFeature.Geometry.Rings[r];
                        var dimension              = ringsPointsArray.GetLength(1); // 2D 3D 3D+M ?
                        int ringsPointsArrayLength = (ringsPointsArray.Length / dimension);

                        for (int multiArrayIndex = 0; multiArrayIndex < ringsPointsArrayLength; multiArrayIndex++)
                        {
                            //Point point = new Point();
                            //point.X = ringsPointsArray[multiArrayIndex, 0];
                            //point.Y = ringsPointsArray[multiArrayIndex, 1];

                            ring.AddPoint(ArrayToPoint(ringsPointsArray, multiArrayIndex, dimension));
                        }
                        polygon.AddRing(ring);
                    }

                    feature.Shape = polygon;
                }
                else if (_featureClass.GeometryType == geometryType.Point &&
                         (jsonFeature.Geometry?.X != null) &&
                         (jsonFeature.Geometry?.Y != null)
                         )
                {
                    Point shape = _featureClass.HasM ? new PointM() : new Point();
                    shape.X = jsonFeature.Geometry.X.Value;
                    shape.Y = jsonFeature.Geometry.Y.Value;

                    if (_featureClass.HasZ && jsonFeature.Geometry.Z.HasValue)
                    {
                        shape.Z = jsonFeature.Geometry.Z.Value;
                    }

                    if (this._featureClass.HasM && jsonFeature.Geometry.M.HasValue)
                    {
                        ((PointM)shape).M = jsonFeature.Geometry.M.Value;
                    }

                    feature.Shape = shape;
                }
                else if (_featureClass.GeometryType == geometryType.Multipoint &&
                         jsonFeature.Geometry?.Points != null &&
                         jsonFeature.Geometry.Points.Length > 0)
                {
                    MultiPoint multiPoint = new MultiPoint();

                    for (int p = 0, pointCount = jsonFeature.Geometry.Points.Length; p < pointCount; p++)
                    {
                        var doubleArray = jsonFeature.Geometry.Points[p];
                        if (doubleArray.Length >= 2)
                        {
                            var point = new Point(doubleArray[0].Value, doubleArray[1].Value);

                            multiPoint.AddPoint(point);
                        }
                    }

                    feature.Shape = multiPoint;
                }
                else
                {
                }

                #endregion

                #region Properties

                if (jsonFeature.Attributes != null)
                {
                    var attribiutes = (IDictionary <string, object>)jsonFeature.Attributes;
                    foreach (var name in attribiutes.Keys)
                    {
                        object value = attribiutes[name];

                        if (dateColumns.Contains(name))
                        {
                            try
                            {
                                long     esriDate = Convert.ToInt64(value);
                                DateTime td       = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(esriDate);
                                feature.Fields.Add(new FieldValue(name, td));
                            }
                            catch // if date is not a long?!
                            {
                                feature.Fields.Add(new FieldValue(name, value?.ToString()));
                            }
                        }
                        else
                        {
                            //if (!filter.SuppressResolveAttributeDomains && _domains != null && _domains.ContainsKey(name))
                            //{
                            //    value = DomainValue(name, value?.ToString());
                            //}
                            feature.Fields.Add(new FieldValue(name, value?.ToString()));
                        }

                        if (name == _featureClass.IDFieldName)
                        {
                            feature.OID = int.Parse(value.ToString());
                            _lastOid    = Math.Max(_lastOid, feature.OID);
                        }
                    }
                }

                #endregion

                _features.Add(feature);
            }

            _hasMore = _lastOid > 0 && jsonFeatureResponse.ExceededTransferLimit;

            //_hasMore = false;
        }
Example #55
0
 private static bool FirstPolylineStartIsInsideSecondPolyline(Polyline first, Polyline second)
 {
     return(Curve.PointRelativeToCurveLocation(first.Start, second) != PointLocation.Outside);
 }
Example #56
0
 public void SetModel(dynamic model)
 {
     polyline = (Polyline)model;
 }
Example #57
0
        public void TcRecHatch()
        {
            int    num;
            int    num4;
            object obj;

            try
            {
IL_01:
                ProjectData.ClearProjectError();
                num = -2;
IL_09:
                int num2 = 2;
                Polyline polyline = new Polyline();
IL_11:
                num2 = 3;
                Point3d point3d_;
                Point3d point3d_2;
                Class36.smethod_33(ref point3d_, ref point3d_2);
IL_1D:
                num2     = 4;
                polyline = Class36.smethod_17(point3d_, point3d_2);
IL_28:
                num2 = 5;
                string text = Conversions.ToString(Application.GetSystemVariable("CPROFILE"));
IL_3B:
                num2 = 6;
                if (Operators.CompareString(text.ToUpper().Substring(0, 4), "TSSD", false) != 0)
                {
                    goto IL_66;
                }
IL_5B:
                num2 = 7;
                string text2 = "AN31C";
                goto IL_A0;
IL_66:
                num2 = 9;
                if (Operators.CompareString(text.ToUpper().Substring(0, 4), "TARC", false) != 0)
                {
                    goto IL_93;
                }
IL_87:
                num2  = 10;
                text2 = "钢筋混凝土";
                goto IL_A0;
IL_93:
                num2 = 12;
IL_96:
                num2  = 13;
                text2 = "ARMORED";
IL_A0:
                num2 = 15;
                Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument;
IL_AF:
                num2 = 16;
                Database database = mdiActiveDocument.Database;
IL_BB:
                num2 = 17;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    BlockTable         blockTable         = (BlockTable)transaction.GetObject(database.BlockTableId, 0);
                    BlockTableRecord   blockTableRecord   = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], 1);
                    ObjectIdCollection objectIdCollection = new ObjectIdCollection();
                    objectIdCollection.Add(polyline.ObjectId);
                    Hatch hatch = new Hatch();
                    blockTableRecord.AppendEntity(hatch);
                    transaction.AddNewlyCreatedDBObject(hatch, true);
                    hatch.SetDatabaseDefaults();
                    hatch.PatternScale = 25.0;
                    hatch.SetHatchPattern(1, text2);
                    hatch.Associative = true;
                    hatch.AppendLoop(16, objectIdCollection);
                    hatch.EvaluateHatch(true);
                    transaction.Commit();
                }
IL_184:
                num2 = 19;
                Class36.smethod_64(polyline.ObjectId);
IL_193:
                num2 = 20;
                if (Information.Err().Number <= 0)
                {
                    goto IL_1BA;
                }
IL_1A5:
                num2 = 21;
                Interaction.MsgBox(Information.Err().Description, MsgBoxStyle.OkOnly, null);
IL_1BA:
                goto IL_271;
IL_1BF:
                int num3 = num4 + 1;
                num4     = 0;
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num3);
IL_22B:
                goto IL_266;
IL_22D:
                num4 = num2;
                if (num <= -2)
                {
                    goto IL_1BF;
                }
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num);
                IL_243 :;
            }
            catch when(endfilter(obj is Exception & num != 0 & num4 == 0))
            {
                Exception ex = (Exception)obj2;

                goto IL_22D;
            }
IL_266:
            throw ProjectData.CreateProjectError(-2146828237);
IL_271:
            if (num4 != 0)
            {
                ProjectData.ClearProjectError();
            }
        }
Example #58
0
 public static bool NormalAwayFromSpace(this Polyline polyline, List <Panel> panelsAsSpace)
 {
     return(polyline.NormalAwayFromSpace(panelsAsSpace, BH.oM.Geometry.Tolerance.Distance));
 }
Example #59
0
        public void 任意多边形填充()
        {
            int    num;
            int    num10;
            object obj;

            try
            {
IL_01:
                ProjectData.ClearProjectError();
                num = -2;
IL_09:
                int num2 = 2;
                Point3d[] array = new Point3d[2];
IL_12:
                num2 = 3;
                Class36.smethod_32(ref array[0], ref array[1], "选择插入点:");
IL_2D:
                num2 = 4;
                short num3 = 1;
IL_31:
                num2 = 5;
                Polyline polyline = new Polyline();
                for (;;)
                {
IL_124:
                    num2 = 6;
                    short    num4;
                    Polyline polyline2;
                    short    num6;
                    checked
                    {
                        num3 += 1;
IL_3F:
                        num2  = 7;
                        array = (Point3d[])Utils.CopyArray((Array)array, new Point3d[(int)(num3 + 1)]);
IL_5A:
                        num2 = 10;
                        num4 = Class36.smethod_29(array[(int)(num3 - 1)], ref array[(int)num3], "选择下一点: ");
IL_7E:
                        num2 = 11;
                        if (num4 == 0)
                        {
                            break;
                        }
IL_8B:
                        num2 = 14;
IL_8E:
                        num2      = 15;
                        polyline2 = new Polyline();
IL_98:
                        num2 = 16;
                        short num5 = 0;
                        num6 = (short)Information.UBound(array, 1);
                        num4 = num5;
                    }
                    for (;;)
                    {
                        short num7 = num4;
                        short num8 = num6;
                        if (num7 > num8)
                        {
                            break;
                        }
IL_AA:
                        num2 = 17;
                        polyline2.AddVertexAt((int)num4, Class36.smethod_38(array[(int)num4]), 0.0, 0.0, 0.0);
IL_E3:
                        num2  = 18;
                        num4 += 1;
                    }
IL_F7:
                    num2             = 19;
                    polyline2.Closed = true;
IL_102:
                    num2 = 20;
                    CAD.AddEnt(polyline2);
IL_10D:
                    num2 = 21;
                    Class36.smethod_64(polyline.ObjectId);
IL_11D:
                    num2     = 22;
                    polyline = polyline2;
                }
IL_130:
                num2 = 25;
                Document mdiActiveDocument = Application.DocumentManager.MdiActiveDocument;
IL_13F:
                num2 = 26;
                Database database = mdiActiveDocument.Database;
IL_14B:
                num2 = 27;
                using (Transaction transaction = database.TransactionManager.StartTransaction())
                {
                    BlockTable         blockTable         = (BlockTable)transaction.GetObject(database.BlockTableId, 0);
                    BlockTableRecord   blockTableRecord   = (BlockTableRecord)transaction.GetObject(blockTable[BlockTableRecord.ModelSpace], 1);
                    ObjectIdCollection objectIdCollection = new ObjectIdCollection();
                    objectIdCollection.Add(polyline.ObjectId);
                    Hatch hatch = new Hatch();
                    blockTableRecord.AppendEntity(hatch);
                    transaction.AddNewlyCreatedDBObject(hatch, true);
                    hatch.SetDatabaseDefaults();
                    hatch.PatternScale = 500.0;
                    hatch.SetHatchPattern(1, "grass");
                    hatch.Associative = true;
                    hatch.AppendLoop(16, objectIdCollection);
                    hatch.EvaluateHatch(true);
                    transaction.Commit();
                }
IL_218:
                num2 = 29;
                Class36.smethod_64(polyline.ObjectId);
IL_228:
                num2 = 30;
                if (Information.Err().Number <= 0)
                {
                    goto IL_24F;
                }
IL_23A:
                num2 = 31;
                Interaction.MsgBox(Information.Err().Description, MsgBoxStyle.OkOnly, null);
IL_24F:
                goto IL_331;
IL_254:
                int num9 = num10 + 1;
                num10    = 0;
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num9);
IL_2E8:
                goto IL_326;
IL_2EA:
                num10 = num2;
                if (num <= -2)
                {
                    goto IL_254;
                }
                @switch(ICSharpCode.Decompiler.ILAst.ILLabel[], num);
                IL_303 :;
            }
            catch when(endfilter(obj is Exception & num != 0 & num10 == 0))
            {
                Exception ex = (Exception)obj2;

                goto IL_2EA;
            }
IL_326:
            throw ProjectData.CreateProjectError(-2146828237);
IL_331:
            if (num10 != 0)
            {
                ProjectData.ClearProjectError();
            }
        }
        internal OverlapConvexHull(Polyline polyline, IEnumerable<Obstacle> obstacles) {
            this.Polyline = polyline;
            this.Obstacles = obstacles.ToList();
            this.PrimaryObstacle = this.Obstacles[0];

            Obstacle.RoundVertices(this.Polyline);
        }