/// <summary> 
        /// Create Arc from 3 given Points
        /// </summary>
        /// <param name="startPoint">Start-Point of the Arc</param>
        /// <param name="interPoint">A point anywhere the Arc</param>
        /// <param name="endPoint">End-Point of the Arc</param>
        /// <returns></returns>
        public static Arc FromDescriptorPoints(Vector2 startPoint, Vector2 interPoint, Vector2 endPoint)
        {

            const Direction calcdirection = Direction.RIGHT;

            // Calculate Rays from the 3 given Points
            var rays = RaysFromDescriptorPoints(startPoint, interPoint, endPoint, DirectionUtil.Switch(calcdirection));
            // The two Rays intercept in the Arc's Middlepoint:
            var arcCenter = rays[0].Intersect(rays[1]);
            var arcRadius = new Vector2(startPoint, arcCenter).Length;

            // Take Vectors from these Points
            var middleToStart = new Vector2(arcCenter, startPoint);
            var middleToEnd = new Vector2(arcCenter, endPoint);

            // Calculate base vector
            var vbase = middleToStart.GetOrthogonalVector(Direction.RIGHT)*-1;

            var arcAngle = middleToEnd.AngleSignedTo(middleToStart, true);

            var newArc = new Arc(
                arcRadius,
                arcAngle,
                vbase)
            {
                Location = startPoint,
                Direction = DirectionUtil.Switch(calcdirection)
            };

            return newArc;
        }
示例#2
0
文件: Program.cs 项目: KasperSK/I4SWD
 static void Main(string[] args)
 {
     Shape myShape = new Line(new Coordinate(0, 0, 0), 10);
     myShape.Render();
     myShape = new Arc(new Coordinate(1,1,1),5,20);
     myShape.Render();
 }
示例#3
0
 public void GetPoint(string cps, double radius, double offset, double angle, string expected)
 {
     var centre = cps.AsPoint();
     var arc = new Arc(centre, 0, 0, radius, false);
     var actual = arc.GetPoint(angle, offset);
     Assert.AreEqual(expected, actual.ToString("F0"));
 }
示例#4
0
 public ArcView(Arc arc)
 {
     this.SemanticNetworkId = arc.SemanticNetworkId;
     this.Text = arc.Text;
     this.ArcId = arc.ArcId;
     this.FromVertexId = arc.FromVertexId;
     this.ToVertexId = arc.ToVertexId;
 }
示例#5
0
 private void InitArcs()
 {
     arcs = new Arc [num_arcs];
     arcs [right_answer] = new Arc () { X = 0.35, Y = 0.42,  Size = 0.35, StartAngle = 215, EndAngle = 260};
     arcs[1] = new Arc () { X = 0.3, Y = 0.40, Size = 0.25, StartAngle = 215, EndAngle = 290};
     arcs[2] = new Arc () { X = 0.3, Y = 0.40, Size = 0.25, StartAngle = 215, EndAngle = 270};
     arcs[3] = new Arc () { X = 0.3, Y = 0.40, Size = 0.25, StartAngle = 215, EndAngle = 270};
 }
 public IEnumerator waitForParticles()
 {
     while (particleSystem.GetParticles(particles) < pCount) {
         yield return 0;
     }
     arcs = new Arc[maxConcurrentArcs];
     for (int i = 0; i < maxConcurrentArcs; i++) {
         arcs[i] = new Arc(particles, particlesPerArc * i, particlesPerArc);
     }
     running = true;
 }
示例#7
0
        public PointD[] IntersectionWith(Arc arc)
        {
            if (arc.Point.DistanceTo(this) > arc.Radius) return null;

            double a = Math.Pow(Slope.Value, 2) + 1;
            double b = 2 * ((Point.Y * Slope.Value) - (Point.X * Math.Pow(Slope.Value, 2)) - (arc.Point.Y * Slope.Value) - arc.Point.X);
            double c = Math.Pow(arc.Point.X, 2) - Math.Pow(arc.Radius, 2) +
                       (Math.Pow(Point.X, 2)*Math.Pow(Slope.Value, 2)) - (2*Point.X*Point.Y*Slope.Value) +
                       (2*Point.X*arc.Point.Y*Slope.Value) + Math.Pow(Point.Y, 2) - (2*Point.Y*arc.Point.Y) +
                       Math.Pow(arc.Point.Y, 2);

            double x1 = (-b + Math.Sqrt(b*b - 4*a*c))/(2*a);
            double x2 = (-b - Math.Sqrt(b*b - 4*a*c))/(2*a);
            return new PointD[] {new PointD(x1, Y(x1).Value), new PointD(x2, Y(x2).Value) };
        }
        private static Arc MakeArea(double startAngle, double endAngle, Color fillColor)
        {
            Arc arc = new Arc();
            arc.Stretch = Stretch.None;
            arc.Width = 200;
            arc.Height = 200;

            arc.StartAngle = startAngle;
            arc.EndAngle = endAngle;
            arc.ArcThickness = 20;
            arc.StrokeThickness = 0.5;
            arc.Stroke = new SolidColorBrush(Colors.Black);
            arc.Fill = new SolidColorBrush(fillColor);
            return arc;
        }
        public static void Main()
        {
            Coordinate coordinate1, coordinate2;
            coordinate1 = new Coordinate(
                new Longitude(48, 52), new Latitude(-2, -20));
            Arc arc = new Arc(new Longitude(3), new Latitude(1));

            coordinate2 = coordinate1 + arc;
            Console.WriteLine(coordinate2);

            coordinate2 = coordinate2 - arc;
            Console.WriteLine(coordinate2);

            coordinate2 += arc;
            Console.WriteLine(coordinate2);
        }
示例#10
0
        public frmMain()
        {
            InitializeComponent();
            Update = Output; //Used to support calling Output() from a different thread.

            Angle angle = new Angle(60, AngleType.Degrees);
            Line line = new Line(new PointD(0, 0), angle);
            Arc arc = new Arc(new PointD(0, 0), 2);

            PointD[] intersections = line.IntersectionWith(arc);
            foreach (var point in intersections)
            {
                Output(point.ToString());
            }

            //tm.Interval = 1000 * 1000;
            //tm.MicroTimerElapsed += Tm_MicroTimerElapsed;
            //tm.Start();
        }
示例#11
0
        internal override void OnApplyTemplateInternal()
        {
            if (Template != null)
            {
                _arc = Template.FindName(ArcName, this) as Arc;
                if (_arc == null)
                {
                    Trace.TraceWarning(ArcName + " not found.");
                }
                // NOTE: Lack of contracts: FindName is pure method
                Contract.Assume(Template != null);
                _busyBar = Template.FindName(BusyBarName, this) as Canvas;
                if (_busyBar == null)
                {
                    Trace.TraceWarning(BusyBarName +" not found.");
                }
            }

            base.OnApplyTemplateInternal();
        }
 internal IfcTrimmedCurve(DatabaseIfc db, Arc a, bool twoD, IfcCartesianPoint optStrt, out IfcCartesianPoint end)
     : base(db)
 {
     Point3d o = a.Plane.Origin, s = a.StartPoint, e = a.EndPoint;
     Vector3d x = s - o;
     mSenseAgreement = true;
     if (optStrt == null)
         optStrt = twoD ? new IfcCartesianPoint(db, new Point2d(s.X, s.Y)) : new IfcCartesianPoint(db, s);
     end = twoD ? new IfcCartesianPoint(db, new Point2d(e.X, e.Y)) : new IfcCartesianPoint(db,e);
     double angleFactor = mDatabase.mContext.UnitsInContext.getScaleSI(IfcUnitEnum.PLANEANGLEUNIT);
     if (twoD)
     {
         if (a.Plane.ZAxis.Z < 0)
         {
             mSenseAgreement = false;
             x = e - o;
             IfcAxis2Placement2D ap = new IfcAxis2Placement2D(db, new Point2d(o.X, o.Y), new Vector2d(x.X, x.Y));
             BasisCurve = new IfcCircle(ap, a.Radius);
             mTrim1 = new IfcTrimmingSelect(a.Angle / angleFactor, optStrt);
             mTrim2 = new IfcTrimmingSelect(0, end);
         }
         else
         {
             IfcAxis2Placement2D ap = new IfcAxis2Placement2D(db, new Point2d(o.X, o.Y), new Vector2d(x.X, x.Y));
             BasisCurve = new IfcCircle(ap, a.Radius);
             mTrim1 = new IfcTrimmingSelect(0, optStrt);
             mTrim2 = new IfcTrimmingSelect(a.Angle / angleFactor, end);
         }
     }
     else
     {
         Vector3d y = Vector3d.CrossProduct(a.Plane.ZAxis, x);
         Plane pl = new Plane(o, x, y);
         IfcAxis2Placement3D ap = new IfcAxis2Placement3D(db, pl);
         BasisCurve = new IfcCircle(ap, a.Radius);
         mTrim1 = new IfcTrimmingSelect(0, optStrt);
         mTrim2 = new IfcTrimmingSelect(a.Angle / angleFactor, end);
     }
     mMasterRepresentation = IfcTrimmingPreference.PARAMETER;
 }
示例#13
0
 /**<summary>Gudermann函数</summary>*/ public static complex gd(complex x)
 {
     return(Arc.tan(sinh(x)));
 }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app  = commandData.Application;
            Document      doc  = app.ActiveUIDocument.Document;
            View          view = doc.ActiveView;

            Autodesk.Revit.Creation.Application creApp = app.Application.Create;
            Autodesk.Revit.Creation.Document    creDoc = doc.Create;

            // Create a geometry line

            XYZ startPoint = new XYZ(0, 0, 0);
            XYZ endPoint   = new XYZ(10, 10, 0);

            //Line geomLine = creApp.NewLine( startPoint, endPoint, true ); // 2013

            Line geomLine = Line.CreateBound(startPoint, endPoint); // 2014

            // Create a geometry arc

            XYZ end0         = new XYZ(0, 0, 0);
            XYZ end1         = new XYZ(10, 0, 0);
            XYZ pointOnCurve = new XYZ(5, 5, 0);

            //Arc geomArc = creApp.NewArc( end0, end1, pointOnCurve ); // 2013

            Arc geomArc = Arc.Create(end0, end1, pointOnCurve); // 2014

#if NEED_PLANE
            // Create a geometry plane

            XYZ origin = new XYZ(0, 0, 0);
            XYZ normal = new XYZ(1, 1, 0);

            Plane geomPlane = creApp.NewPlane(
                normal, origin);

            // Create a sketch plane in current document

            SketchPlane sketch = creDoc.NewSketchPlane(
                geomPlane);
#endif // NEED_PLANE

            // Create a DetailLine element using the
            // newly created geometry line and sketch plane

            DetailLine line = creDoc.NewDetailCurve(
                view, geomLine) as DetailLine;

            // Create a DetailArc element using the
            // newly created geometry arc and sketch plane

            DetailArc arc = creDoc.NewDetailCurve(
                view, geomArc) as DetailArc;

            // Change detail curve colour.
            // Initially, this only affects the newly
            // created curves. However, when the view
            // is refreshed, all detail curves will
            // be updated.

            GraphicsStyle gs = arc.LineStyle as GraphicsStyle;

            gs.GraphicsStyleCategory.LineColor
                = new Color(250, 10, 10);

            return(Result.Succeeded);
        }
示例#15
0
        getNestedEntities(ObjectId idAlign, ref List <POI> pois, BlockTableRecord btrXRefDbModelSpace)
        {
            Alignment align       = (Alignment)idAlign.getEnt();
            double    alignLength = align.Length;

            string strNameStakeObject = fStake.NameStakeObject;
            string strLayerName       = strNameStakeObject + "-TEMP";

            Layer.manageLayers(strLayerName);
            Layer.manageLayer(strLayerName, 2);

            Point3d varPntBeg, varPntEnd;

            List <ObjectId> ids = new List <ObjectId>();

            foreach (ObjectId id in btrXRefDbModelSpace)
            {
                Entity ent = id.getEnt();

                int intPos = ent.Layer.IndexOf("|");

                string strLayerObj = ent.Layer.Substring(intPos + 1);

                List <string> layers = new List <string> {
                    strNameStakeObject, "CURB", "FL", "GB", "EC", "BLDG", "SEWER", "WATER", "SD-CL", "PROP-WAT"
                };

                if (layers.Contains(strLayerObj))
                {
                    switch (ent.GetType().ToString())
                    {
                    case "Line":
                        ids.Add(ent.ObjectId);
                        break;

                    case "Arc":
                        ids.Add(ent.ObjectId);
                        break;

                    case "Polyline":
                        ids.Add(ent.ObjectId);
                        break;
                    }
                }
            }

            double dblStationBeg = 0, dblStationEnd = 0;
            double dblOffsetBeg = 0, dblOffsetEnd = 0;

            color = new Color();
            color = Color.FromColorIndex(ColorMethod.ByBlock, 4);
            for (int i = 0; i < ids.Count; i++)
            {
                ObjectId id = ids[i];

                Entity ent = id.getEnt();
                id.changeProp(color, ent.Layer, LineWeight.LineWeight100);

                int intPos = ent.Layer.IndexOf("|");

                string strLayerObj = ent.Layer.Substring(intPos + 1);

                if (strLayerObj == strNameStakeObject)
                {
                    switch (ent.GetType().Name)
                    {
                    case "Arc":

                        Arc objArc = (Arc)ent;

                        varPntBeg = objArc.StartPoint;
                        varPntEnd = objArc.EndPoint;

                        align.StationOffset(varPntBeg.X, varPntBeg.Y, ref dblStationBeg, ref dblOffsetBeg);
                        align.StationOffset(varPntEnd.X, varPntEnd.Y, ref dblStationEnd, ref dblOffsetEnd);

                        break;

                    case "Line":

                        Line line = (Line)ent;

                        varPntBeg = line.StartPoint;
                        varPntEnd = line.EndPoint;

                        align.StationOffset(varPntBeg.X, varPntBeg.Y, ref dblStationBeg, ref dblOffsetBeg);
                        align.StationOffset(varPntEnd.X, varPntEnd.Y, ref dblStationEnd, ref dblOffsetEnd);

                        break;

                    case "Polyline":

                        Polyline poly = (Polyline)ent;
                        varPntBeg = poly.StartPoint;
                        varPntEnd = poly.EndPoint;

                        align.StationOffset(varPntBeg.X, varPntBeg.Y, ref dblStationBeg, ref dblOffsetBeg);
                        align.StationOffset(varPntEnd.X, varPntEnd.Y, ref dblStationEnd, ref dblOffsetEnd);

                        break;
                    }

                    if (dblStationBeg >= align.StartingStation & dblStationBeg <= align.EndingStation)
                    {
                        if (dblStationEnd >= align.StartingStation & dblStationEnd <= align.EndingStation)
                        {
                            if (System.Math.Abs(dblOffsetBeg) < 0.1)
                            {
                                POI poi = new POI();

                                poi.Station   = Math.roundDown3(dblStationBeg);
                                poi.ClassObj  = fStake.ClassObj;
                                poi.Desc0     = "TEE";
                                poi.CrossDesc = "TEE";

                                if (dblOffsetEnd > 0)
                                {
                                    poi.Side = 1;
                                }
                                else
                                {
                                    poi.Side = -1;
                                }

                                pois.Add(poi);
                            }
                            else if (System.Math.Abs(dblOffsetEnd) < 0.1)
                            {
                                POI poi = new POI();

                                poi.Station   = Math.roundDown3(dblStationEnd);
                                poi.ClassObj  = fStake.ClassObj;
                                poi.Desc0     = "TEE";
                                poi.CrossDesc = "TEE";

                                if (dblOffsetBeg > 0)
                                {
                                    poi.Side = 1;
                                }
                                else
                                {
                                    poi.Side = -1;
                                }

                                pois.Add(poi);
                            }
                        }
                    }
                }
                else
                {
                    List <Point3d> varPntInt = align.intersectWith(ent, false, extend.source);

                    try
                    {
                        for (int n = 0; n <= varPntInt.Count; n++)
                        {
                            Point3d pnt3dInt = varPntInt[i];
                            align.StationOffset(pnt3dInt.X, pnt3dInt.Y, ref dblStationBeg, ref dblOffsetBeg);

                            POI poi = new POI();

                            poi.Station   = Math.roundDown3(dblStationBeg);
                            poi.ClassObj  = fStake.ClassObj;
                            poi.Desc0     = strLayerObj;
                            poi.CrossDesc = strLayerObj;

                            if (strLayerObj.Contains("SEW") || strLayerObj.Contains("WAT") || strLayerObj.Contains("SD") || strLayerObj.Contains("WTR"))
                            {
                                poi.Type = strLayerObj;
                            }

                            pois.Add(poi);
                        }
                    }
                    catch (System.Exception)
                    {
                    }
                }
            }

            for (int i = 0; i < ids.Count; i++)
            {
                ids[i].delete();
            }
        }
示例#16
0
 /**<summary>第二種Tschebyscheff(Chebychef)函数 Un(x)=sin(n arccos x)</summary>*/
 public static complex Un(complex n, complex x)
 {
     return(sin(n * Arc.cos(x)));
 }
示例#17
0
        private static void WriteDxfFile()
        {
            DxfDocument dxf = new DxfDocument();

            //arc
            Arc arc = new Arc(new Vector3f(10, 10, 0), 10, 45, 135);

            arc.Layer             = new Layer("arc");
            arc.Layer.Color.Index = 1;
            dxf.AddEntity(arc);

            //xData sample
            XData xdata = new XData(new ApplicationRegistry("SharpDxf"));

            xdata.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with SharpDxf"));
            xdata.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionX, 0));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionY, 0));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionZ, 0));
            xdata.XDataRecord.Add(XDataRecord.CloseControlString);

            XData xdata2 = new XData(new ApplicationRegistry("other application"));

            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with SharpDxf"));
            xdata2.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "string record"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Real, 15.5));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Long, 350));
            xdata2.XDataRecord.Add(XDataRecord.CloseControlString);

            //circle
            Vector3f extrusion = new Vector3f(1, 1, 1);
            Vector3f centerWCS = new Vector3f(1, 1, 1);
            Vector3d centerOCS = MathHelper.Transform((Vector3d)centerWCS,
                                                      (Vector3d)extrusion,
                                                      MathHelper.CoordinateSystem.World,
                                                      MathHelper.CoordinateSystem.Object);

            Circle circle = new Circle((Vector3f)centerOCS, 5);

            circle.Layer       = new Layer("circle with spaces");
            circle.Layer.Color = AciColor.Yellow;
            circle.LineType    = LineType.Dashed;
            circle.Normal      = extrusion;
            circle.XData       = new Dictionary <ApplicationRegistry, XData>
            {
                { xdata.ApplicationRegistry, xdata },
                { xdata2.ApplicationRegistry, xdata2 }
            };

            dxf.AddEntity(circle);

            //points
            Point point1 = new Point(new Vector3f(-3, -3, 0));

            point1.Layer = new Layer("point");
            point1.Color = new AciColor(30);
            Point point2 = new Point(new Vector3f(1, 1, 1));

            point2.Layer             = point1.Layer;
            point2.Layer.Color.Index = 9;
            point2.Normal            = new Vector3f(1, 1, 1);
            dxf.AddEntity(point1);
            dxf.AddEntity(point2);

            //3dface
            Face3d face3D = new Face3d(new Vector3f(-5, -5, 5),
                                       new Vector3f(5, -5, 5),
                                       new Vector3f(5, 5, 5),
                                       new Vector3f(-5, 5, 5));

            face3D.Layer             = new Layer("3dface");
            face3D.Layer.Color.Index = 3;
            dxf.AddEntity(face3D);

            //polyline
            PolylineVertex        polyVertex;
            List <PolylineVertex> polyVertexes = new List <PolylineVertex>();

            polyVertex = new PolylineVertex(new Vector2f(-50, -50));
            polyVertex.BeginThickness = 2;
            polyVertexes.Add(polyVertex);
            polyVertex = new PolylineVertex(new Vector2f(50, -50));
            polyVertex.BeginThickness = 1;
            polyVertexes.Add(polyVertex);
            polyVertex       = new PolylineVertex(new Vector2f(50, 50));
            polyVertex.Bulge = 1;
            polyVertexes.Add(polyVertex);
            polyVertex = new PolylineVertex(new Vector2f(-50, 50));
            polyVertexes.Add(polyVertex);
            Polyline polyline2d = new Polyline(polyVertexes, true);

            polyline2d.Layer             = new Layer("polyline2d");
            polyline2d.Layer.Color.Index = 5;
            polyline2d.Normal            = new Vector3f(1, 1, 1);
            polyline2d.Elevation         = 100.0f;
            dxf.AddEntity(polyline2d);

            //lightweight polyline
            LightWeightPolylineVertex        lwVertex;
            List <LightWeightPolylineVertex> lwVertexes = new List <LightWeightPolylineVertex>();

            lwVertex = new LightWeightPolylineVertex(new Vector2f(-25, -25));
            lwVertex.BeginThickness = 2;
            lwVertexes.Add(lwVertex);
            lwVertex = new LightWeightPolylineVertex(new Vector2f(25, -25));
            lwVertex.BeginThickness = 1;
            lwVertexes.Add(lwVertex);
            lwVertex       = new LightWeightPolylineVertex(new Vector2f(25, 25));
            lwVertex.Bulge = 1;
            lwVertexes.Add(lwVertex);
            lwVertex = new LightWeightPolylineVertex(new Vector2f(-25, 25));
            lwVertexes.Add(lwVertex);
            LightWeightPolyline lwPolyline = new LightWeightPolyline(lwVertexes, true);

            lwPolyline.Layer             = new Layer("lwpolyline");
            lwPolyline.Layer.Color.Index = 5;
            lwPolyline.Normal            = new Vector3f(1, 1, 1);
            lwPolyline.Elevation         = 100.0f;
            dxf.AddEntity(lwPolyline);

            //line
            Line line = new Line(new Vector3f(0, 0, 0), new Vector3f(10, 10, 10));

            line.Layer             = new Layer("line");
            line.Layer.Color.Index = 6;
            dxf.AddEntity(line);

            //3d polyline
            Polyline3dVertex        vertex;
            List <Polyline3dVertex> vertexes = new List <Polyline3dVertex>();

            vertex = new Polyline3dVertex(new Vector3f(-50, -50, 0));
            vertexes.Add(vertex);
            vertex = new Polyline3dVertex(new Vector3f(50, -50, 10));
            vertexes.Add(vertex);
            vertex = new Polyline3dVertex(new Vector3f(50, 50, 25));
            vertexes.Add(vertex);
            vertex = new Polyline3dVertex(new Vector3f(-50, 50, 50));
            vertexes.Add(vertex);
            Polyline3d polyline = new Polyline3d(vertexes, true);

            polyline.Layer             = new Layer("polyline3d");
            polyline.Layer.Color.Index = 24;
            dxf.AddEntity(polyline);

            //block definition
            Block block = new Block("TestBlock");

            block.Entities.Add(new Line(new Vector3f(-5, -5, 5), new Vector3f(5, 5, 5)));
            block.Entities.Add(new Line(new Vector3f(5, -5, 5), new Vector3f(-5, 5, 5)));

            //insert
            Insert insert = new Insert(block, new Vector3f(5, 5, 5));

            insert.Layer             = new Layer("insert");
            insert.Layer.Color.Index = 4;
            dxf.AddEntity(insert);

            //text
            TextStyle style = new TextStyle("True type font", "Arial.ttf");
            Text      text  = new Text("Hello world!", Vector3f.Zero, 10.0f, style);

            text.Layer             = new Layer("text");
            text.Layer.Color.Index = 8;
            text.Alignment         = TextAlignment.TopRight;
            dxf.AddEntity(text);

            dxf.Save("AutoCad2007.dxf", DxfVersion.AutoCad2007);
            dxf.Save("AutoCad2004.dxf", DxfVersion.AutoCad2004);
            dxf.Save("AutoCad2000.dxf", DxfVersion.AutoCad2000);
            dxf.Save("AutoCad12.dxf", DxfVersion.AutoCad12);
        }
示例#18
0
        // [TODO]
        //    - we could get a better fit to the original curve if we use the ability to have separate
        //      d1 and d2 values. There is a point where d1 > 0 and d2 > 0 where we will get a best-fit.
        //
        //      if d1==0, the first arc degenerates. The second arc degenerates when d2 == 0.
        //      If either d1 or d2 go negative, then we shouldn't use that result.
        //      But it's not clear if we can directly compute the positive-d-range...
        //
        //      It does seem like if we solve the d1=d2 case, then we use [0,2*d1] as the d1 range,
        //      then maybe we are safe. And we can always discard solutions where it is negative...


        // solve biarc fit where the free parameter is automatically set so that
        // d1=d2, which is basically the 'middle' case
        void Fit()
        {
            // get inputs
            Vector2d p1 = Point1;
            Vector2d p2 = Point2;

            Vector2d t1 = Tangent1;
            Vector2d t2 = Tangent2;

            // fit biarc
            Vector2d v       = p2 - p1;
            double   vMagSqr = v.LengthSquared;

            // set d1 equal to d2
            Vector2d t       = t1 + t2;
            double   tMagSqr = t.LengthSquared;

            // original code used 0.0001 here...
            bool equalTangents = MathUtil.EpsilonEqual(tMagSqr, 4.0, Epsilon);
            //var equalTangents = IsEqualEps(tMagSqr, 4.0);

            double vDotT1 = v.Dot(t1);
            bool   perpT1 = MathUtil.EpsilonEqual(vDotT1, 0.0, Epsilon);

            if (equalTangents && perpT1)
            {
                // we have two semicircles
                //Vector2d joint = p1 + 0.5 * v;

                // d1 = d2 = infinity here...
                FitD1 = FitD2 = double.PositiveInfinity;

                // draw arcs
                double   angle   = Math.Atan2(v.y, v.x);
                Vector2d center1 = p1 + 0.25 * v;
                Vector2d center2 = p1 + 0.75 * v;
                double   radius  = Math.Sqrt(vMagSqr) * 0.25;
                double   cross   = v.x * t1.y - v.y * t1.x;

                arc1 = new Arc(center1, radius, angle, angle + Math.PI, (cross < 0));
                arc1 = new Arc(center2, radius, angle, angle + Math.PI, (cross > 0));
            }
            else
            {
                double vDotT = v.Dot(t);

                // [RMS] this was unused in original code...
                //bool perpT1 = MathUtil.EpsilonEqual(vDotT1, 0, epsilon);

                double d1 = 0;
                if (equalTangents)
                {
                    d1 = vMagSqr / (4 * vDotT1);
                }
                else
                {
                    double denominator  = 2.0 - 2.0 * t1.Dot(t2);
                    double discriminant = vDotT * vDotT + denominator * vMagSqr;
                    d1 = (Math.Sqrt(discriminant) - vDotT) / denominator;
                }
                FitD1 = FitD2 = d1;

                Vector2d joint = p1 + p2 + d1 * (t1 - t2);
                joint *= 0.5;

                // construct arcs
                SetArcFromEdge(0, p1, t1, joint, true);
                SetArcFromEdge(1, p2, t2, joint, false);
            }
        }
示例#19
0
        private void PasteObjects_Click(object sender, EventArgs e)
        {
            try
            {
                Drawing drawing = drawingHandler.GetActiveDrawing();

                if (selectedPartsArray.Count > 0)
                {
                    Tekla.Structures.Drawing.View view = new Tekla.Structures.Drawing.View(drawing.GetSheet(), v.ViewCoordinateSystem, v.DisplayCoordinateSystem, selectedPartsArray);
                    view.Insert();
                }

                if (selectedViewsArray.Count > 0)
                {
                    foreach (Tekla.Structures.Drawing.View oView in selectedViewsArray)
                    {
                        Tekla.Structures.Drawing.View view = new Tekla.Structures.Drawing.View(drawing.GetSheet(), oView.ViewCoordinateSystem, oView.DisplayCoordinateSystem, oView.RestrictionBox);
                        view = oView;
                        view.Insert();
                    }
                }

                if (selectedObjectsArray.Count > 0)
                {
                    Tekla.Structures.Drawing.UI.Picker picker = drawingHandler.GetPicker();
                    Tekla.Structures.Geometry3d.Point  point  = null;
                    ViewBase selectedView = null;
                    picker.PickPoint("Pick View", out point, out selectedView);

                    foreach (DrawingObject drawingObject in selectedObjectsArray)
                    {
                        if (drawingObject is Tekla.Structures.Drawing.Text)
                        {
                            Tekla.Structures.Drawing.Text oText = (Tekla.Structures.Drawing.Text)drawingObject;
                            Tekla.Structures.Drawing.Text text  = new Tekla.Structures.Drawing.Text(selectedView, oText.InsertionPoint, oText.TextString, oText.Attributes);

                            if (oText.Placing is Tekla.Structures.Drawing.LeaderLinePlacing)
                            {
                                Tekla.Structures.Drawing.LeaderLinePlacing l = (Tekla.Structures.Drawing.LeaderLinePlacing)oText.Placing;
                                text = new Tekla.Structures.Drawing.Text(selectedView, oText.InsertionPoint, oText.TextString, new LeaderLinePlacing(l.StartPoint), oText.Attributes);
                                text.Insert();
                            }
                            else
                            {
                                text = new Tekla.Structures.Drawing.Text(selectedView, oText.InsertionPoint, oText.TextString, oText.Attributes);
                                text.Insert();
                            }
                        }

                        if (drawingObject is Tekla.Structures.Drawing.Line)
                        {
                            Tekla.Structures.Drawing.Line oLine = (Tekla.Structures.Drawing.Line)drawingObject;
                            Tekla.Structures.Drawing.Line line  = new Tekla.Structures.Drawing.Line(selectedView, oLine.StartPoint, oLine.EndPoint, oLine.Bulge, oLine.Attributes);
                            line.Insert();
                        }

                        if (drawingObject is Tekla.Structures.Drawing.Arc)
                        {
                            Tekla.Structures.Drawing.Arc oArc = (Tekla.Structures.Drawing.Arc)drawingObject;
                            Tekla.Structures.Drawing.Arc arc  = new Arc(selectedView, oArc.StartPoint, oArc.EndPoint, oArc.Radius, oArc.Attributes);
                            arc.Insert();
                        }

                        if (drawingObject is Tekla.Structures.Drawing.Polyline)
                        {
                            Tekla.Structures.Drawing.Polyline oPolyline = (Tekla.Structures.Drawing.Polyline)drawingObject;
                            Tekla.Structures.Drawing.Polyline polyline  = new Polyline(selectedView, oPolyline.Points, oPolyline.Attributes);
                            polyline.Bulge = oPolyline.Bulge;
                            polyline.Insert();
                        }

                        if (drawingObject is Tekla.Structures.Drawing.Rectangle)
                        {
                            Tekla.Structures.Drawing.Rectangle oRectangle = (Tekla.Structures.Drawing.Rectangle)drawingObject;
                            Tekla.Structures.Drawing.Rectangle rectangle  = new Tekla.Structures.Drawing.Rectangle(selectedView, oRectangle.StartPoint, oRectangle.Width, oRectangle.Height, oRectangle.Attributes);
                            rectangle.Angle = oRectangle.Angle;
                            rectangle.Insert();
                        }

                        if (drawingObject is Tekla.Structures.Drawing.Circle)
                        {
                            Tekla.Structures.Drawing.Circle oCircle = (Tekla.Structures.Drawing.Circle)drawingObject;
                            Tekla.Structures.Drawing.Circle circle  = new Circle(selectedView, oCircle.CenterPoint, oCircle.Radius, oCircle.Attributes);
                            circle.Insert();
                        }

                        if (drawingObject is Tekla.Structures.Drawing.Polygon)
                        {
                            Tekla.Structures.Drawing.Polygon oPolygon = (Tekla.Structures.Drawing.Polygon)drawingObject;
                            Tekla.Structures.Drawing.Polygon polygon  = new Tekla.Structures.Drawing.Polygon(selectedView, oPolygon.Points, oPolygon.Attributes);;
                            polygon.Bulge = oPolygon.Bulge;
                            polygon.Insert();
                        }
                    }
                }
                statusLabel.Text = "Objects pasted in drawing " + drawing.Mark.Substring(1, drawing.Mark.Length - 2);
            }
            catch (Exception ex)
            {
                statusLabel.Text = ex.Message;
            }
        }
示例#20
0
 public void ReadEntryLengthCorrectly() => File.OpenRead(FileName).Using(stream =>
 {
     var entries = Arc.Read(stream).ToArray();
     Assert.Equal(0x3ec, entries[0].Data.Length);
     Assert.Equal(0xbc, entries[1].Data.Length);
 });
        //
        //    A \      / B
        //       \    /
        //        \  /
        //  O      \/ X
        //         /\
        //        /  \
        //     C /    \ D
        //
        // Intersection(Segment(AD), Segment(BC)) -> 2 * Angle(CXA) = Arc(A, C) + Arc(B, D),
        //                                           2 * Angle(BXD) = Arc(A, C) + Arc(B, D),
        //                                           2 * Angle(AXB) = Arc(A, B) + Arc(C, D),
        //                                           2 * Angle(CXD) = Arc(A, B) + Arc(C, D)
        //
        public static List <EdgeAggregator> InstantiateTheorem(Intersection inter, Circle circle)
        {
            List <EdgeAggregator> newGrounded = new List <EdgeAggregator>();

            // Is this intersection explicitly inside the circle? That is, the point of intersection interior?
            if (!circle.PointIsInterior(inter.intersect))
            {
                return(newGrounded);
            }

            //
            // Get the chords
            //
            Segment chord1 = circle.GetChord(inter.lhs);
            Segment chord2 = circle.GetChord(inter.rhs);

            if (chord1 == null || chord2 == null)
            {
                return(newGrounded);
            }

            //
            // Group 1
            //
            Arc   arc1   = Arc.GetFigureMinorArc(circle, chord1.Point1, chord2.Point1);
            Angle angle1 = Angle.AcquireFigureAngle(new Angle(chord1.Point1, inter.intersect, chord2.Point1));

            Arc   oppArc1   = Arc.GetFigureMinorArc(circle, chord1.Point2, chord2.Point2);
            Angle oppAngle1 = Angle.AcquireFigureAngle(new Angle(chord1.Point2, inter.intersect, chord2.Point2));

            //
            // Group 2
            //
            Arc   arc2   = Arc.GetFigureMinorArc(circle, chord1.Point1, chord2.Point2);
            Angle angle2 = Angle.AcquireFigureAngle(new Angle(chord1.Point1, inter.intersect, chord2.Point2));

            Arc   oppArc2   = Arc.GetFigureMinorArc(circle, chord1.Point2, chord2.Point1);
            Angle oppAngle2 = Angle.AcquireFigureAngle(new Angle(chord1.Point2, inter.intersect, chord2.Point1));

            //
            // Construct each of the 4 equations.
            //
            NumericValue two = new NumericValue(2);

            GeometricAngleArcEquation gaeq1 = new GeometricAngleArcEquation(new Multiplication(two, angle1), new Addition(arc1, oppArc1));
            GeometricAngleArcEquation gaeq2 = new GeometricAngleArcEquation(new Multiplication(two, oppAngle1), new Addition(arc1, oppArc1));

            GeometricAngleArcEquation gaeq3 = new GeometricAngleArcEquation(new Multiplication(two, angle2), new Addition(arc2, oppArc2));
            GeometricAngleArcEquation gaeq4 = new GeometricAngleArcEquation(new Multiplication(two, oppAngle2), new Addition(arc2, oppArc2));

            // For hypergraph
            List <GroundedClause> antecedent = new List <GroundedClause>();

            antecedent.Add(inter);
            antecedent.Add(circle);

            newGrounded.Add(new EdgeAggregator(antecedent, gaeq1, annotation));
            newGrounded.Add(new EdgeAggregator(antecedent, gaeq2, annotation));
            newGrounded.Add(new EdgeAggregator(antecedent, gaeq3, annotation));
            newGrounded.Add(new EdgeAggregator(antecedent, gaeq4, annotation));

            return(newGrounded);
        }
示例#22
0
        /// <summary>
        /// Create a cylinder to subtract from the cube.
        /// </summary>
        public BRepBuilder CreateBrepVoid()
        {
            // Naming convention for faces and edges: we
            // assume that x is to the left and pointing down,
            // y is horizontal and pointing to the right,
            // z is up.

            BRepBuilder b = new BRepBuilder(BRepType.Solid);

            // The surfaces of the four faces.
            Frame basis = new Frame(new XYZ(50, 0, 0), new XYZ(0, 1, 0), new XYZ(-1, 0, 0), new XYZ(0, 0, 1));
            CylindricalSurface cylSurf = CylindricalSurface.Create(basis, 40);
            Plane top1    = Plane.CreateByNormalAndOrigin(new XYZ(0, 0, 1), new XYZ(0, 0, 100)); // normal points outside the cylinder
            Plane bottom1 = Plane.CreateByNormalAndOrigin(new XYZ(0, 0, 1), new XYZ(0, 0, 0));   // normal points inside the cylinder

            // Add the four faces
            BRepBuilderGeometryId frontCylFaceId = b.AddFace(BRepBuilderSurfaceGeometry.Create(cylSurf, null), false);
            BRepBuilderGeometryId backCylFaceId  = b.AddFace(BRepBuilderSurfaceGeometry.Create(cylSurf, null), false);
            BRepBuilderGeometryId topFaceId      = b.AddFace(BRepBuilderSurfaceGeometry.Create(top1, null), false);
            BRepBuilderGeometryId bottomFaceId   = b.AddFace(BRepBuilderSurfaceGeometry.Create(bottom1, null), true);

            // Geometry for the four semi-circular edges and two vertical linear edges
            BRepBuilderEdgeGeometry frontEdgeBottom = BRepBuilderEdgeGeometry.Create(Arc.Create(new XYZ(10, 0, 0), new XYZ(90, 0, 0), new XYZ(50, 40, 0)));
            BRepBuilderEdgeGeometry backEdgeBottom  = BRepBuilderEdgeGeometry.Create(Arc.Create(new XYZ(90, 0, 0), new XYZ(10, 0, 0), new XYZ(50, -40, 0)));

            BRepBuilderEdgeGeometry frontEdgeTop = BRepBuilderEdgeGeometry.Create(Arc.Create(new XYZ(10, 0, 100), new XYZ(90, 0, 100), new XYZ(50, 40, 100)));
            BRepBuilderEdgeGeometry backEdgeTop  = BRepBuilderEdgeGeometry.Create(Arc.Create(new XYZ(10, 0, 100), new XYZ(90, 0, 100), new XYZ(50, -40, 100)));

            BRepBuilderEdgeGeometry linearEdgeFront = BRepBuilderEdgeGeometry.Create(new XYZ(90, 0, 0), new XYZ(90, 0, 100));
            BRepBuilderEdgeGeometry linearEdgeBack  = BRepBuilderEdgeGeometry.Create(new XYZ(10, 0, 0), new XYZ(10, 0, 100));

            // Add the six edges
            BRepBuilderGeometryId frontEdgeBottomId = b.AddEdge(frontEdgeBottom);
            BRepBuilderGeometryId frontEdgeTopId    = b.AddEdge(frontEdgeTop);
            BRepBuilderGeometryId linearEdgeFrontId = b.AddEdge(linearEdgeFront);
            BRepBuilderGeometryId linearEdgeBackId  = b.AddEdge(linearEdgeBack);
            BRepBuilderGeometryId backEdgeBottomId  = b.AddEdge(backEdgeBottom);
            BRepBuilderGeometryId backEdgeTopId     = b.AddEdge(backEdgeTop);

            // Loops of the four faces
            BRepBuilderGeometryId loopId_Top    = b.AddLoop(topFaceId);
            BRepBuilderGeometryId loopId_Bottom = b.AddLoop(bottomFaceId);
            BRepBuilderGeometryId loopId_Front  = b.AddLoop(frontCylFaceId);
            BRepBuilderGeometryId loopId_Back   = b.AddLoop(backCylFaceId);

            // Add coedges for the loop of the front face
            b.AddCoEdge(loopId_Front, linearEdgeBackId, false);
            b.AddCoEdge(loopId_Front, frontEdgeTopId, false);
            b.AddCoEdge(loopId_Front, linearEdgeFrontId, true);
            b.AddCoEdge(loopId_Front, frontEdgeBottomId, true);
            b.FinishLoop(loopId_Front);
            b.FinishFace(frontCylFaceId);

            // Add coedges for the loop of the back face
            b.AddCoEdge(loopId_Back, linearEdgeBackId, true);
            b.AddCoEdge(loopId_Back, backEdgeBottomId, true);
            b.AddCoEdge(loopId_Back, linearEdgeFrontId, false);
            b.AddCoEdge(loopId_Back, backEdgeTopId, true);
            b.FinishLoop(loopId_Back);
            b.FinishFace(backCylFaceId);

            // Add coedges for the loop of the top face
            b.AddCoEdge(loopId_Top, backEdgeTopId, false);
            b.AddCoEdge(loopId_Top, frontEdgeTopId, true);
            b.FinishLoop(loopId_Top);
            b.FinishFace(topFaceId);

            // Add coedges for the loop of the bottom face
            b.AddCoEdge(loopId_Bottom, frontEdgeBottomId, false);
            b.AddCoEdge(loopId_Bottom, backEdgeBottomId, false);
            b.FinishLoop(loopId_Bottom);
            b.FinishFace(bottomFaceId);

            b.Finish();

            return(b);
        }
        public static List <Base> ToPathList(this string pathDataText)
        {
            pathDataText = pathDataText.Trim();
            var strings = new List <string>();
            int start   = 0;

            for (int i = 1; i <= pathDataText.Length; i++)
            {
                if (i == pathDataText.Length || (char.ToLower(pathDataText[i]) != 'e' && char.IsLetter(pathDataText[i])))
                {
                    strings.Add(pathDataText.Substring(start, i - start));
                    start = i;
                }
            }

            var result = new List <PathElement.Base>();

            foreach (var str in strings)
            {
                if (string.IsNullOrWhiteSpace(str))
                {
                    continue;
                }
                var cmd = char.ToUpper(str[0]);
                switch (cmd)
                {
                case Arc.Symbol:
                    if (Arc.FromString(str) is List <Arc> arcList)
                    {
                        result.AddRange(arcList);
                    }
                    break;

                case BezierCurve.Symbol:
                    if (BezierCurve.FromString(str) is List <BezierCurve> bezierCurveList)
                    {
                        result.AddRange(bezierCurveList);
                    }
                    break;

                case ClosePath.Symbol:
                    result.Add(new ClosePath());
                    break;

                case HorzLineTo.Symbol:
                    if (HorzLineTo.FromString(str) is HorzLineTo horzLineTo)
                    {
                        result.Add(horzLineTo);
                    }
                    break;

                case LineTo.Symbol:
                    if (LineTo.FromString(str) is List <LineTo> lineList)
                    {
                        result.AddRange(lineList);
                    }
                    break;

                case MoveTo.Symbol:
                    if (MoveTo.FromString(str) is List <Base> moveAndLineList)
                    {
                        result.AddRange(moveAndLineList);
                    }
                    break;

                case QuadraticCurve.Symbol:
                    if (QuadraticCurve.FromString(str) is List <QuadraticCurve> quadraticCurveList)
                    {
                        result.AddRange(quadraticCurveList);
                    }
                    break;

                case ShortcutBezierCurve.Symbol:
                    if (ShortcutBezierCurve.FromString(str) is List <ShortcutBezierCurve> shortcutBezierCurveList)
                    {
                        result.AddRange(shortcutBezierCurveList);
                    }
                    break;

                case ShortcutQuadraticCurve.Symbol:
                    if (ShortcutQuadraticCurve.FromString(str) is List <ShortcutQuadraticCurve> shortcutQuadraticCurveList)
                    {
                        result.AddRange(shortcutQuadraticCurveList);
                    }
                    break;

                case VertLineTo.Symbol:
                    if (VertLineTo.FromString(str) is VertLineTo vertLineTo)
                    {
                        result.Add(vertLineTo);
                    }
                    break;

                default:
                    throw new Exception("Unrecognized Path Command : " + str);
                }
            }
            return(result);
        }
示例#24
0
 StreamWcs(Arc arc)
 {
     StreamCurveAsTesselatedPointsWcs(arc);
 }
示例#25
0
        /***************************************************/
        /**** Public Methods - Curves                   ****/
        /***************************************************/

        public static bool IsClosed(this Arc arc, double tolerance = Tolerance.Distance)
        {
            return((arc.Angle() - Math.PI * 2) * arc.Radius > -tolerance);
        }
示例#26
0
 public void PointersShouldHaveNullData() => File.OpenRead(FileName).Using(stream =>
 {
     var entries = Arc.Read(stream).ToArray();
     Assert.Null(entries[2].Data);
 });
        public static Fst get(Fst fst, int n, bool determinize)
        {
            if (fst == null)
            {
                return(null);
            }
            if (fst.getSemiring() == null)
            {
                return(null);
            }
            Fst fst2 = fst;

            if (determinize)
            {
                fst2 = Determinize.get(fst);
            }
            Semiring semiring = fst2.getSemiring();
            Fst      fst3     = new Fst(semiring);

            fst3.setIsyms(fst2.getIsyms());
            fst3.setOsyms(fst2.getOsyms());
            float[] array = NShortestPaths.shortestDistance(fst2);
            ExtendFinal.apply(fst2);
            int[]         array2        = new int[fst2.getNumStates()];
            PriorityQueue priorityQueue = new PriorityQueue(10, new NShortestPaths_1(array, semiring));
            HashMap       hashMap       = new HashMap(fst.getNumStates());
            HashMap       hashMap2      = new HashMap(fst.getNumStates());
            State         start         = fst2.getStart();
            Pair          pair          = new Pair(start, Float.valueOf(semiring.one()));

            priorityQueue.add(pair);
            hashMap.put(pair, null);
            while (!priorityQueue.isEmpty())
            {
                Pair  pair2  = (Pair)priorityQueue.remove();
                State state  = (State)pair2.getLeft();
                Float @float = (Float)pair2.getRight();
                State state2 = new State(state.getFinalWeight());
                fst3.addState(state2);
                hashMap2.put(pair2, state2);
                if (hashMap.get(pair2) == null)
                {
                    fst3.setStart(state2);
                }
                else
                {
                    State state3 = (State)hashMap2.get(hashMap.get(pair2));
                    State state4 = (State)((Pair)hashMap.get(pair2)).getLeft();
                    for (int i = 0; i < state4.getNumArcs(); i++)
                    {
                        Arc arc = state4.getArc(i);
                        if (arc.getNextState().equals(state))
                        {
                            state3.addArc(new Arc(arc.getIlabel(), arc.getOlabel(), arc.getWeight(), state2));
                        }
                    }
                }
                Integer integer = Integer.valueOf(state.getId());
                int[]   array3  = array2;
                int     num     = integer.intValue();
                int[]   array4  = array3;
                array4[num]++;
                if (array2[integer.intValue()] == n && state.getFinalWeight() != semiring.zero())
                {
                    break;
                }
                if (array2[integer.intValue()] <= n)
                {
                    for (int j = 0; j < state.getNumArcs(); j++)
                    {
                        Arc   arc2  = state.getArc(j);
                        float num2  = semiring.times(@float.floatValue(), arc2.getWeight());
                        Pair  pair3 = new Pair(arc2.getNextState(), Float.valueOf(num2));
                        hashMap.put(pair3, pair2);
                        priorityQueue.add(pair3);
                    }
                }
            }
            return(fst3);
        }
示例#28
0
 public void ReadCorrectAmountOfEntries() => File.OpenRead(FileName).Using(stream =>
 {
     var entries = Arc.Read(stream);
     Assert.Equal(3, entries.Count());
 });
示例#29
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += new ResolveEventHandler(Misc.LoadFromSameFolder);

            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            View active_view = doc.ActiveView;

            double tolerance = app.ShortCurveTolerance;

            ///////////////////////
            // Pick Import Instance
            ImportInstance import = null;

            try
            {
                Reference r = uidoc.Selection.PickObject(ObjectType.Element, new Util.ElementsOfClassSelectionFilter <ImportInstance>());
                import = doc.GetElement(r) as ImportInstance;
            }
            catch
            {
                return(Result.Cancelled);
            }
            if (import == null)
            {
                System.Windows.MessageBox.Show("CAD not found", "Tips");
                return(Result.Cancelled);
            }


            // Initiate the progress bar
            Views.ProgressBar pb = new Views.ProgressBar("Modeling entire building", "Initiation...", 100);
            if (pb.ProcessCancelled)
            {
                return(Result.Cancelled);
            }


            //////////////////////////////////
            // Check if the families are ready
            pb.CustomizeStatus("Checking families...", 2);
            if (pb.ProcessCancelled)
            {
                return(Result.Cancelled);
            }
            // Consider to add more customized families (in the Setting Panel)
            if (Properties.Settings.Default.name_door == null ||
                Properties.Settings.Default.name_window == null ||
                Properties.Settings.Default.name_columnRect == null ||
                Properties.Settings.Default.name_columnRound == null)
            {
                System.Windows.MessageBox.Show("Please select the column/door/window type in settings", "Tips");
                return(Result.Cancelled);
            }
            //if (!File.Exists(Properties.Settings.Default.url_door) && File.Exists(Properties.Settings.Default.url_window)
            //    && File.Exists(Properties.Settings.Default.url_column))
            //{
            //    System.Windows.MessageBox.Show("Please check the family path is solid", "Tips");
            //    return Result.Cancelled;
            //}
            //Family fColumn, fDoor, fWindow = null;
            //using (Transaction tx = new Transaction(doc, "Load necessary families"))
            //{
            //    tx.Start();
            //    if (!doc.LoadFamily(Properties.Settings.Default.url_column, out fColumn))
            //    {
            //        System.Windows.MessageBox.Show("Please check the column family path is solid", "Tips");
            //        return Result.Cancelled;
            //    }
            //    if (!doc.LoadFamily(Properties.Settings.Default.url_door, out fDoor) ||
            //        !doc.LoadFamily(Properties.Settings.Default.url_window, out fWindow))
            //    {
            //        System.Windows.MessageBox.Show("Please check the door/window family path is solid", "Tips");
            //        return Result.Cancelled;
            //    }
            //    tx.Commit();
            //}

            // Prepare a family for ViewPlan creation
            // It may be a coincidence that the 1st ViewFamilyType is for the FloorPlan
            // Uplift needed here (doomed if it happends to be a CeilingPlan)
            ViewFamilyType viewType = new FilteredElementCollector(doc)
                                      .OfClass(typeof(ViewFamilyType)).First() as ViewFamilyType;

            RoofType roofType = new FilteredElementCollector(doc)
                                .OfClass(typeof(RoofType)).FirstOrDefault <Element>() as RoofType;

            FloorType floorType = new FilteredElementCollector(doc)
                                  .OfClass(typeof(FloorType)).FirstOrDefault <Element>() as FloorType;


            ////////////////////
            // DATA PREPARATIONS
            pb.CustomizeStatus("Processing geometries...", 3);
            if (pb.ProcessCancelled)
            {
                return(Result.Cancelled);
            }
            // Prepare frames and levels
            // Cluster all geometry elements and texts into datatrees
            // Two procedures are intertwined
            List <GeometryObject> dwg_frames = Util.TeighaGeometry.ExtractElement(uidoc, import,
                                                                                  Properties.Settings.Default.layerFrame, "PolyLine"); // framework is polyline by default
            List <GeometryObject> dwg_geos = Util.TeighaGeometry.ExtractElement(uidoc, import);

            // Terminate if no geometry has been found
            if (dwg_geos == null)
            {
                System.Windows.MessageBox.Show("A drawing frame is mandantory", "Tips");
                return(Result.Failed);
            }

            List <PolyLine> closedPolys = new List <PolyLine>();
            List <PolyLine> parentPolys = new List <PolyLine>();

            Debug.Print("Number of geos acting as the framework is " + dwg_frames.Count().ToString());

            if (dwg_frames.Count > 0)
            {
                foreach (var obj in dwg_frames)
                {
                    PolyLine poly = obj as PolyLine;
                    // Draw shattered lines in case the object is a PolyLine
                    if (null != poly)
                    {
                        var vertices = poly.GetCoordinates();
                        if (vertices[0].IsAlmostEqualTo(vertices.Last()))
                        {
                            closedPolys.Add(poly);
                        }
                    }
                }

                for (int i = 0; i < closedPolys.Count(); i++)
                {
                    int judgement = 0;
                    int counter   = 0;
                    for (int j = 0; j < closedPolys.Count(); j++)
                    {
                        if (i != j)
                        {
                            if (!RegionDetect.PolyInPoly(closedPolys[i], RegionDetect.PolyLineToCurveArray(closedPolys[j], tolerance)))
                            {
                                //Debug.Print("Poly inside poly detected");
                                judgement += 1;
                            }
                            counter += 1;
                        }
                    }
                    if (judgement == counter)
                    {
                        parentPolys.Add(closedPolys[i]);
                    }
                }
            }
            else
            {
                Debug.Print("There is no returning of geometries");
            }
            Debug.Print("Got closedPolys: " + closedPolys.Count().ToString());
            Debug.Print("Got parentPolys: " + parentPolys.Count().ToString());


            string path = Util.TeighaText.GetCADPath(uidoc, import);

            Debug.Print("The path of linked CAD file is: " + path);
            List <Util.TeighaText.CADTextModel> texts = Util.TeighaText.GetCADText(path);


            int    level;
            int    levelCounter = 0;
            double floorHeight  = Misc.MmToFoot(Properties.Settings.Default.floorHeight);
            Dictionary <int, PolyLine> frameDict = new Dictionary <int, PolyLine>(); // cache drawing borders
            Dictionary <int, XYZ>      transDict = new Dictionary <int, XYZ>();
            // cache transform vector from the left-bottom corner of the drawing border to the Origin
            Dictionary <int, List <GeometryObject> > geoDict = new Dictionary <int, List <GeometryObject> >();
            // cache geometries of each floorplan
            Dictionary <int, List <Util.TeighaText.CADTextModel> > textDict = new Dictionary <int, List <Util.TeighaText.CADTextModel> >();

            // cache text info of each floorplan

            if (texts.Count > 0)
            {
                foreach (var textmodel in texts)
                {
                    level = Misc.GetLevel(textmodel.Text, "平面图");
                    Debug.Print("Got target label " + textmodel.Text);
                    if (level != -1)
                    {
                        foreach (PolyLine frame in parentPolys)
                        {
                            if (RegionDetect.PointInPoly(RegionDetect.PolyLineToCurveArray(frame, tolerance), textmodel.Location))
                            {
                                XYZ basePt   = Algorithm.BubbleSort(frame.GetCoordinates().ToList())[0];
                                XYZ transVec = XYZ.Zero - basePt;
                                Debug.Print("Add level " + level.ToString() + " with transaction (" +
                                            transVec.X.ToString() + ", " + transVec.Y.ToString() + ", " + transVec.Z.ToString() + ")");
                                if (!frameDict.Values.ToList().Contains(frame))
                                {
                                    frameDict.Add(level, frame);
                                    transDict.Add(level, transVec);
                                    levelCounter += 1;
                                }
                            }
                        }
                    }
                }
                // Too complicated using 2 iterations... uplift needed
                for (int i = 1; i <= levelCounter; i++)
                {
                    textDict.Add(i, new List <Util.TeighaText.CADTextModel>());
                    geoDict.Add(i, new List <GeometryObject>());
                    CurveArray tempPolyArray = RegionDetect.PolyLineToCurveArray(frameDict[i], tolerance);
                    foreach (var textmodel in texts)
                    {
                        if (RegionDetect.PointInPoly(tempPolyArray, textmodel.Location))
                        {
                            textDict[i].Add(textmodel);
                        }
                    }
                    foreach (GeometryObject go in dwg_geos)
                    {
                        XYZ centPt = XYZ.Zero;
                        if (go is Line)
                        {
                            //get the revit model coordinates.
                            Line go_line = go as Line;
                            centPt = (go_line.GetEndPoint(0) + go_line.GetEndPoint(1)).Divide(2);
                        }
                        else if (go is Arc)
                        {
                            Arc go_arc = go as Arc;
                            centPt = go_arc.Center;
                        }
                        else if (go is PolyLine)
                        {
                            PolyLine go_poly = go as PolyLine;
                            centPt = go_poly.GetCoordinate(0);
                        }
                        // Assignment
                        if (RegionDetect.PointInPoly(tempPolyArray, centPt) && centPt != XYZ.Zero)
                        {
                            geoDict[i].Add(go);
                        }
                    }
                }
            }
            Debug.Print("All levels: " + levelCounter.ToString());
            Debug.Print("frameDict: " + frameDict.Count().ToString());
            Debug.Print("transDict: " + transDict.Count().ToString());
            for (int i = 1; i <= levelCounter; i++)
            {
                Debug.Print("geoDict-{0}: {1}", i, geoDict[i].Count().ToString());
            }
            Debug.Print("textDict: " + textDict.Count().ToString() + " " + textDict[1].Count().ToString());


            ////////////////////
            // MAIN TRANSACTIONS

            // Prepare a family and configurations for TextNote (Put it inside transactions)

            /*
             * TextNoteType tnt = new FilteredElementCollector(doc)
             *  .OfClass(typeof(TextNoteType)).First() as TextNoteType;
             * TextNoteOptions options = new TextNoteOptions();
             * options.HorizontalAlignment = HorizontalTextAlignment.Center;
             * options.TypeId = doc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
             * BuiltInParameter paraIndex = BuiltInParameter.TEXT_SIZE;
             * Parameter textSize = tnt.get_Parameter(paraIndex);
             * textSize.Set(0.3); // in feet
             *
             * XYZ centPt = RegionDetect.PolyCentPt(frameDict[i]);
             * TextNoteOptions opts = new TextNoteOptions(tnt.Id);
             *
             * // The note may only show in the current view
             * // no matter we still need it anyway
             * TextNote txNote = TextNote.Create(doc, active_view.Id, centPt, floorView.Name, options);
             * txNote.ChangeTypeId(tnt.Id);
             *
             * // Draw model lines of frames as notation
             * Plane Geomplane = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, XYZ.Zero + transDict[i] + XYZ.BasisZ * (i - 1) * floorHeight);
             * SketchPlane sketch = SketchPlane.Create(doc, Geomplane);
             * CurveArray shatters = RegionDetect.PolyLineToCurveArray(frameDict[i], tolerance);
             * Transform alignModelLine = Transform.CreateTranslation(transDict[i] + XYZ.BasisZ * (i - 1) * floorHeight);
             * foreach (Curve shatter in shatters)
             * {
             *  Curve alignedCrv = shatter.CreateTransformed(alignModelLine);
             *  ModelCurve modelline = doc.Create.NewModelCurve(alignedCrv, sketch) as ModelCurve;
             * }
             */


            // ITERATION FLAG
            for (int i = 1; i <= levelCounter; i++)
            {
                pb.CustomizeStatus("On Floor " + i.ToString() + "... with lines", 5);
                if (pb.ProcessCancelled)
                {
                    return(Result.Cancelled);
                }

                TransactionGroup tg = new TransactionGroup(doc, "Generate on floor-" + i.ToString());
                {
                    try
                    {
                        tg.Start();

                        // MILESTONE
                        // Align the labels to the origin
                        Transform alignment = Transform.CreateTranslation(transDict[i]);
                        foreach (Util.TeighaText.CADTextModel label in textDict[i])
                        {
                            label.Location = label.Location + transDict[i];
                        }

                        // MILESTONE
                        // Sort out lines
                        List <Curve> wallCrvs   = new List <Curve>();
                        List <Curve> columnCrvs = new List <Curve>();
                        List <Curve> doorCrvs   = new List <Curve>();
                        List <Curve> windowCrvs = new List <Curve>();
                        foreach (GeometryObject go in geoDict[i])
                        {
                            var gStyle = doc.GetElement(go.GraphicsStyleId) as GraphicsStyle;
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerWall)
                            {
                                if (go.GetType().Name == "Line")
                                {
                                    Curve wallLine = go as Curve;
                                    wallCrvs.Add(wallLine.CreateTransformed(alignment) as Line);
                                }
                                if (go.GetType().Name == "PolyLine")
                                {
                                    CurveArray wallPolyLine_shattered = RegionDetect.PolyLineToCurveArray(go as PolyLine, tolerance);
                                    foreach (Curve crv in wallPolyLine_shattered)
                                    {
                                        wallCrvs.Add(crv.CreateTransformed(alignment) as Line);
                                    }
                                }
                            }
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerColumn)
                            {
                                if (go.GetType().Name == "Line")
                                {
                                    Curve columnLine = go as Curve;
                                    columnCrvs.Add(columnLine.CreateTransformed(alignment));
                                }
                                if (go.GetType().Name == "PolyLine")
                                {
                                    CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(go as PolyLine, tolerance);
                                    foreach (Curve crv in columnPolyLine_shattered)
                                    {
                                        columnCrvs.Add(crv.CreateTransformed(alignment));
                                    }
                                }
                            }
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerDoor)
                            {
                                Curve    doorCrv = go as Curve;
                                PolyLine poly    = go as PolyLine;
                                if (null != doorCrv)
                                {
                                    doorCrvs.Add(doorCrv.CreateTransformed(alignment));
                                }
                                if (null != poly)
                                {
                                    CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(poly, tolerance);
                                    foreach (Curve crv in columnPolyLine_shattered)
                                    {
                                        doorCrvs.Add(crv.CreateTransformed(alignment) as Line);
                                    }
                                }
                            }
                            if (gStyle.GraphicsStyleCategory.Name == Properties.Settings.Default.layerWindow)
                            {
                                Curve    windowCrv = go as Curve;
                                PolyLine poly      = go as PolyLine;
                                if (null != windowCrv)
                                {
                                    windowCrvs.Add(windowCrv.CreateTransformed(alignment));
                                }
                                if (null != poly)
                                {
                                    CurveArray columnPolyLine_shattered = RegionDetect.PolyLineToCurveArray(poly, tolerance);
                                    foreach (Curve crv in columnPolyLine_shattered)
                                    {
                                        windowCrvs.Add(crv.CreateTransformed(alignment) as Line);
                                    }
                                }
                            }
                        }

                        // MILESTONE
                        // Create additional levels (ignore what's present)
                        // Consider to use sub-transaction here
                        using (var t_level = new Transaction(doc))
                        {
                            t_level.Start("Create levels");
                            Level    floor     = Level.Create(doc, (i - 1) * floorHeight);
                            ViewPlan floorView = ViewPlan.Create(doc, viewType.Id, floor.Id);
                            floorView.Name = "F-" + i.ToString();
                            t_level.Commit();
                        }

                        // Grab the current building level
                        FilteredElementCollector colLevels = new FilteredElementCollector(doc)
                                                             .WhereElementIsNotElementType()
                                                             .OfCategory(BuiltInCategory.INVALID)
                                                             .OfClass(typeof(Level));
                        Level currentLevel = colLevels.LastOrDefault() as Level;
                        // The newly created level will append to the list,
                        // but this is not a safe choice

                        // Sub-transactions are packed within these functions.
                        // The family names should be defined by the user in WPF
                        // MILESTONE
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Walls", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        CreateWall.Execute(uiapp, wallCrvs, currentLevel, true);

                        // MILESTONE
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Columns", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        CreateColumn.Execute(app, doc, columnCrvs,
                                             Properties.Settings.Default.name_columnRect,
                                             Properties.Settings.Default.name_columnRound,
                                             currentLevel, true);

                        // MILESTONE
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Openings", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        CreateOpening.Execute(doc, doorCrvs, windowCrvs, wallCrvs, textDict[i],
                                              Properties.Settings.Default.name_door, Properties.Settings.Default.name_window, currentLevel, true);

                        // Create floor
                        // MILESTONE
                        var footprint = CreateRegion.Execute(doc, wallCrvs, columnCrvs, windowCrvs, doorCrvs);
                        using (var t_floor = new Transaction(doc))
                        {
                            t_floor.Start("Generate Floor");

                            Floor newFloor = doc.Create.NewFloor(footprint, floorType, currentLevel, false, XYZ.BasisZ);
                            newFloor.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM).Set(0);

                            t_floor.Commit();
                        }

                        // Generate rooms after the topology is established
                        pb.CustomizeStatus("On Floor " + i.ToString() + "... with Rooms", 90 / levelCounter / 4);
                        if (pb.ProcessCancelled)
                        {
                            return(Result.Cancelled);
                        }
                        // MILESTONE
                        using (var t_space = new Transaction(doc))
                        {
                            t_space.Start("Create rooms");

                            doc.Regenerate();

                            PlanTopology planTopology = doc.get_PlanTopology(currentLevel);
                            if (doc.ActiveView.ViewType == ViewType.FloorPlan)
                            {
                                foreach (PlanCircuit circuit in planTopology.Circuits)
                                {
                                    if (null != circuit && !circuit.IsRoomLocated)
                                    {
                                        Room room = doc.Create.NewRoom(null, circuit);
                                        room.LimitOffset = floorHeight;
                                        room.BaseOffset  = 0;
                                        string roomName = "";
                                        foreach (Util.TeighaText.CADTextModel label in textDict[i])
                                        {
                                            if (label.Layer == Properties.Settings.Default.layerSpace)
                                            {
                                                if (room.IsPointInRoom(label.Location + XYZ.BasisZ * (i - 1) * floorHeight))
                                                {
                                                    roomName += label.Text;
                                                }
                                            }
                                        }
                                        if (roomName != "")
                                        {
                                            room.Name = roomName;
                                        }
                                    }
                                }
                            }
                            t_space.Commit();
                        }



                        // Create roof when iterating to the last level
                        // MILESTONE
                        if (i == levelCounter)
                        {
                            using (var t_roof = new Transaction(doc))
                            {
                                t_roof.Start("Create roof");
                                Level    roofLevel = Level.Create(doc, i * floorHeight);
                                ViewPlan floorView = ViewPlan.Create(doc, viewType.Id, roofLevel.Id);
                                floorView.Name = "Roof";

                                ModelCurveArray footPrintToModelCurveMapping = new ModelCurveArray();
                                FootPrintRoof   footprintRoof = doc.Create.NewFootPrintRoof(footprint, roofLevel, roofType,
                                                                                            out footPrintToModelCurveMapping);

                                //ModelCurveArrayIterator iterator = footPrintToModelCurveMapping.ForwardIterator();

                                /*
                                 * iterator.Reset();
                                 * while (iterator.MoveNext())
                                 * {
                                 *  ModelCurve modelCurve = iterator.Current as ModelCurve;
                                 *  footprintRoof.set_DefinesSlope(modelCurve, true);
                                 *  footprintRoof.set_SlopeAngle(modelCurve, 0.5);
                                 * }
                                 */
                                t_roof.Commit();
                            }
                        }
                        tg.Assimilate();
                    }
                    catch
                    {
                        System.Windows.MessageBox.Show("Error", "Tips");
                        tg.RollBack();
                    }
                }
                pb.JobCompleted();
            }

            return(Result.Succeeded);
        }
示例#30
0
        /***************************************************/

        public static bool IsLinear(this Arc arc, double tolerance = Tolerance.Distance)
        {
            return(false);
        }
示例#31
0
        /***************************************************/
        /**** public Methods - Curves                  ****/
        /***************************************************/

        public static Arc Mirror(this Arc arc, Plane p)
        {
            return(new Arc {
                CoordinateSystem = arc.CoordinateSystem.Mirror(p), StartAngle = arc.StartAngle, EndAngle = arc.EndAngle, Radius = arc.Radius
            });
        }
示例#32
0
            // output the module as a Library component
            public string ToModule()
            {
                StringBuilder ret = new StringBuilder("");

                ret.Append($"  (module \"{Name}\" (layer {Layer}) {Tedit} {Tstamp}\n");
                ret.Append($"  (descr \"\")");
                ret.Append($"  (tags \"\")");
                if (Attr != "")
                {
                    ret.Append($"  (attr {Attr})\n");
                }

                foreach (var String in Strings)
                {
                    string str;

                    str = String.ToString(X, Y, Rotation);

                    if (str.Contains("fp_text reference"))
                    {
                        str = String.ToRefString(X, Y, Rotation);
                    }

                    ret.Append(str);
                }
                foreach (var Pad in Pads)
                {
                    ret.Append(Pad.ToModuleString(X, Y, Rotation));
                }
                foreach (var Line in Lines)
                {
                    ret.Append(Line.ToString(X, Y, Rotation));
                }
                // Vias in components are done as pads
                //                foreach (var Via in Vias)
                //                {
                //                    ret += Via.ToString(X, Y);
                //                }
                foreach (var Arc in Arcs)
                {
                    ret.Append(Arc.ToString(X, Y, Rotation));
                }
                foreach (var Polygon in Polygons)
                {
                    ret.Append(Polygon.ToString());
                }
                foreach (var Fill in Fills)
                {
                    ret.Append(Fill.ToString(X, Y, -Rotation));
                }
                foreach (var region in Regions)
                {
                    ret.Append(region.ToString(X, Y, -Rotation));
                }
                foreach (var ComponentBody in ComponentBodies)
                {
                    ret.Append(ComponentBody.ToString(X, Y, -Rotation));
                }
                ret.Append("  )\n");
                return(ret.ToString());
            }
示例#33
0
 public static List <Point> CurvePlanarIntersections(this Arc curve1, Line curve2, double tolerance = Tolerance.Distance)
 {
     return(curve1.CurveIntersections(curve2, tolerance));
 }
        public static IEnumerable <VertexData> GetVertexIter(this Arc arc)
        {
            // go to the start
            if (arc.UseStartEndLimit)
            {
                //---------------------------------------------------------
                VertexData vertexData = new VertexData();
                vertexData.command = VertexCmd.MoveTo;
                vertexData.x       = arc.StartX;
                vertexData.y       = arc.StartY;
                yield return(vertexData);

                //---------------------------------------------------------
                double angle = arc.StartAngle;
                vertexData.command = VertexCmd.LineTo;
                //calculate nsteps
                int calculateNSteps = arc.CalculateNSteps;

                int    n    = 0;
                double radX = arc.RadiusX;
                double radY = arc.RadiusY;
                double flatternDeltaAngle = arc.FlattenDeltaAngle;
                double orgX = arc.OriginX;
                double orgY = arc.OriginY;

                while (n < calculateNSteps - 1)
                {
                    angle       += flatternDeltaAngle;
                    vertexData.x = orgX + Math.Cos(angle) * radX;
                    vertexData.y = orgY + Math.Sin(angle) * radY;
                    yield return(vertexData);

                    n++;
                }

                //while ((angle < endAngle - flatenDeltaAngle / 4) == (((int)ArcDirection.CounterClockWise) == 1))
                //{
                //    angle += flatenDeltaAngle;
                //    vertexData.x = originX + Math.Cos(angle) * radiusX;
                //    vertexData.y = originY + Math.Sin(angle) * radiusY;

                //    yield return vertexData;
                //}
                //---------------------------------------------------------
                vertexData.x = arc.EndX;
                vertexData.y = arc.EndY;
                yield return(vertexData);

                vertexData.command = VertexCmd.NoMore;
                yield return(vertexData);
            }
            else
            {
                double     originX    = arc.OriginX;
                double     originY    = arc.OriginY;
                double     startAngle = arc.StartAngle;
                double     radX       = arc.RadiusX;
                double     radY       = arc.RadiusY;
                VertexData vertexData = new VertexData();
                vertexData.command = VertexCmd.MoveTo;
                vertexData.x       = originX + Math.Cos(startAngle) * radX;
                vertexData.y       = originY + Math.Sin(startAngle) * radY;
                yield return(vertexData);

                //---------------------------------------------------------
                double angle              = startAngle;
                double endAngle           = arc.EndY;
                double flatternDeltaAngle = arc.FlattenDeltaAngle;
                vertexData.command = VertexCmd.LineTo;
                while ((angle < endAngle - flatternDeltaAngle / 4) == (((int)Arc.ArcDirection.CounterClockWise) == 1))
                {
                    angle       += flatternDeltaAngle;
                    vertexData.x = originX + Math.Cos(angle) * radX;
                    vertexData.y = originY + Math.Sin(angle) * radY;
                    yield return(vertexData);
                }
                //---------------------------------------------------------
                vertexData.x = originX + Math.Cos(endAngle) * radX;
                vertexData.y = originY + Math.Sin(endAngle) * radY;
                yield return(vertexData);

                vertexData.command = VertexCmd.NoMore;
                yield return(vertexData);
            }
        }
示例#35
0
        public U_Geometry(Object Obentity)
        {
            if (Obentity.GetType().Name == "Line")
            {
                this.line = (Line)Obentity;

                this.Type       = this.line.GetType().Name;
                this.Length     = this.line.Length;
                this.StartPoint = this.line.StartPoint;
                this.EndPoint   = this.line.EndPoint;
                this.Layer      = this.line.Layer;

                OutputStr = GeoToString(this.Layer) +
                            GeoToString(this.Type) +
                            GeoToString(this.Length) +
                            GeoToString(this.StartPoint) +
                            GeoToString(this.EndPoint);
            }
            else if (Obentity.GetType().Name == "Arc")
            {
                this.arc = (Arc)Obentity;

                this.Type       = this.arc.GetType().Name;
                this.Length     = this.arc.Length;
                this.StartPoint = this.arc.StartPoint;
                this.EndPoint   = this.arc.EndPoint;
                this.Center     = this.arc.Center;
                this.Radius     = this.Radius;
                this.Layer      = this.arc.Layer;
                OutputStr       = GeoToString(this.Layer) +
                                  GeoToString(this.Type) +
                                  GeoToString(this.Length) +
                                  GeoToString(this.Radius) +
                                  GeoToString(this.StartPoint) +
                                  GeoToString(this.EndPoint) +
                                  GeoToString(this.Center);
            }
            else if (Obentity.GetType().Name == "Circle")
            {
                this.circle = (Circle)Obentity;

                this.Radius     = this.circle.Radius;
                this.Type       = this.circle.GetType().Name;
                this.Length     = Math.PI * this.circle.Radius * 2;
                this.StartPoint = this.circle.StartPoint;
                this.EndPoint   = this.circle.EndPoint;
                this.Center     = this.circle.Center;
                this.Layer      = this.circle.Layer;
                OutputStr       = GeoToString(this.Layer) +
                                  GeoToString(this.Type) +
                                  GeoToString(this.Length) +
                                  GeoToString(this.Radius) +
                                  GeoToString(this.StartPoint) +
                                  GeoToString(this.EndPoint) +
                                  GeoToString(this.Center);
            }
            else if (Obentity.GetType().Name == "Polyline")
            {
                this.polyline = (Polyline)Obentity;

                this.Type       = this.polyline.GetType().Name;
                this.Length     = this.polyline.Length;
                this.StartPoint = this.polyline.StartPoint;
                this.EndPoint   = this.polyline.EndPoint;
                this.Area       = this.polyline.Area;
                this.Layer      = this.polyline.Layer;
                OutputStr       = GeoToString(this.Layer) +
                                  GeoToString(this.Type) +
                                  GeoToString(this.Length) +
                                  GeoToString(this.Area) +
                                  GeoToString(this.StartPoint) +
                                  GeoToString(this.EndPoint);
            }
            else if (Obentity.GetType().Name == "MText")
            {
                this.mText = (MText)Obentity;

                this.Type       = this.mText.GetType().Name;
                this.Text       = this.mText.Text;
                this.StartPoint = this.mText.Location;
                OutputStr       = GeoToString(this.Layer) +
                                  GeoToString(this.Type) +
                                  GeoToString(this.StartPoint);
            }
            else if (Obentity.GetType().Name == "DBText")
            {
                this.dbText = (DBText)Obentity;

                this.Type       = this.dbText.GetType().Name;
                this.Text       = this.dbText.TextString;
                this.StartPoint = this.dbText.Position;
                OutputStr       = GeoToString(this.Layer) +
                                  GeoToString(this.Type) +
                                  GeoToString(this.StartPoint);
            }
        }
示例#36
0
 /**<summary>極インボリュート函数;polar involute function</summary>*/
 public static complex invr(complex x)
 {
     return(inv(Arc.sec(x)));
 }
示例#37
0
 public ArcIterator(Arc arc, float begin, float end)
 {
     this.arc   = arc;
     this.begin = begin;
     this.end   = end;
 }
示例#38
0
 /**<summary>第二種Tschebyscheff(Chebychef)多項式 U*n(x)=sin(n arccos x)/√(1-x^2)</summary>*/
 public static complex Un_a(complex n, complex x)
 {
     return(sin(n * Arc.cos(x)) / sqrt(1 - x * x));
 }
示例#39
0
            private string Traverse(Point3d from, Arc arc, GCodeConfig config)
            {
                string gcode = "";

                if (from.DistanceTo(arc.StartPoint.Add(offset)) <= config.Tolerance)
                {
                    gcode += $"G03 {config.Formatter.Format2D(arc.EndPoint.Add(offset))} " +
                             $"I{config.Formatter.Format1D(arc.StartPoint.GetVectorTo(arc.Center).X)} " +
                             $"J{config.Formatter.Format1D(arc.StartPoint.GetVectorTo(arc.Center).Y)};\n";


                    foreach (ObjectId id in Utils.SelectAroundPoint(arc.EndPoint.Add(offset), config))
                    {
                        if (objectIds.Contains(id))
                        {
                            objectIds.Remove(id);
                            foreach (Type type in config.AvailableTypes)
                            {
                                try
                                {
                                    gcode += Traverse(arc.EndPoint.Add(offset), (dynamic)Convert.ChangeType(transaction.GetObject(id, OpenMode.ForRead), type), config);
                                }
                                catch (Exception) { }
                            }
                        }
                    }

                    gcode += (!config.AdditionalArguments.Contains("--no-return")) ? $"G02 {config.Formatter.Format2D(arc.StartPoint.Add(offset))} " +
                             $"I{config.Formatter.Format1D(arc.EndPoint.GetVectorTo(arc.Center).X)} " + $"" +
                             $"J{config.Formatter.Format1D(arc.EndPoint.GetVectorTo(arc.Center).Y)};\n" : "";
                }
                else
                {
                    gcode += $"G02 {config.Formatter.Format2D(arc.StartPoint.Add(offset))} " +
                             $"I{config.Formatter.Format1D(arc.EndPoint.GetVectorTo(arc.Center).X)} " +
                             $"J{config.Formatter.Format1D(arc.EndPoint.GetVectorTo(arc.Center).Y)};\n";


                    foreach (ObjectId id in Utils.SelectAroundPoint(arc.StartPoint.Add(offset), config))
                    {
                        if (objectIds.Contains(id))
                        {
                            objectIds.Remove(id);
                            foreach (Type type in config.AvailableTypes)
                            {
                                try
                                {
                                    gcode += Traverse(arc.StartPoint.Add(offset), (dynamic)Convert.ChangeType(transaction.GetObject(id, OpenMode.ForRead), type), config);
                                }
                                catch (Exception) { }
                            }
                        }
                    }


                    gcode += (!config.AdditionalArguments.Contains("--no-return")) ? $"G03 {config.Formatter.Format2D(arc.EndPoint.Add(offset))} " +
                             $"I{config.Formatter.Format1D(arc.StartPoint.GetVectorTo(arc.Center.Add(offset)).X)} " +
                             $"J{config.Formatter.Format1D(arc.StartPoint.GetVectorTo(arc.Center.Add(offset)).Y)};\n" : "";
                }
                return(gcode);
            }
示例#40
0
        // Gh Capture
        public static SpeckleArc ToSpeckle(this Arc a)
        {
            SpeckleArc arc = new SpeckleArc(a.Plane.ToSpeckle(), a.Radius, a.StartAngle, a.EndAngle, a.Angle);

            return(arc);
        }
示例#41
0
        Stream(ArrayList data, Curve crv)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(Curve)));


            try
            {
                data.Add(new Snoop.Data.Double("Approximate length", crv.ApproximateLength));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Approximate length", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Double("Length", crv.Length));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Length", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Double("Period", crv.Period));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Period", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Bool("Is bound", crv.IsBound));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Is bound", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Bool("Is cyclic", crv.IsCyclic));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Is cyclic", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Xyz("Start point", crv.GetEndPoint(0)));
                data.Add(new Snoop.Data.Xyz("End point", crv.GetEndPoint(1)));
            }
            catch (System.Exception)
            {
                // if the curve is unbound, those don't mean anything
                data.Add(new Snoop.Data.String("Start point", "N/A"));
                data.Add(new Snoop.Data.String("End point", "N/A"));
            }

            try
            {
                data.Add(new Snoop.Data.Double("Start parameter", crv.GetEndParameter(0)));
                data.Add(new Snoop.Data.Double("End parameter", crv.GetEndParameter(1)));
            }
            catch (System.Exception)
            {
                // if the curve is unbound, those don't mean anything
                data.Add(new Snoop.Data.String("Start parameter", "N/A"));
                data.Add(new Snoop.Data.String("End parameter", "N/A"));
            }

            try
            {
                data.Add(new Snoop.Data.Object("Start point reference", crv.GetEndPointReference(0)));
                data.Add(new Snoop.Data.Object("End point reference", crv.GetEndPointReference(1)));
            }
            catch (System.Exception)
            {
                // if the curve is unbound, those don't mean anything
                data.Add(new Snoop.Data.String("Start point reference", "N/A"));
                data.Add(new Snoop.Data.String("End point reference", "N/A"));
            }

            try
            {
                data.Add(new Snoop.Data.Object("Reference", crv.Reference));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Reference", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Object("Derivative at Start", crv.ComputeDerivatives(0.0, normalized: true)));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Derivative at Start", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Object("Derivative at Center", crv.ComputeDerivatives(0.5, normalized: true)));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Derivative at Center", ex));
            }

            try
            {
                data.Add(new Snoop.Data.Object("Derivative at End", crv.ComputeDerivatives(1.0, normalized: true)));
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Derivative at End", ex));
            }

            try
            {
                data.Add(new Snoop.Data.CategorySeparator("Tesselated Points"));
            }
            catch
            {
                data.Add(new Snoop.Data.String("Tesselated Points", "N/A"));
            }

            try
            {
                System.Collections.Generic.IList <XYZ> pts = crv.Tessellate();
                int i = 0;
                foreach (XYZ pt in pts)
                {
                    data.Add(new Snoop.Data.Xyz(string.Format("PT [{0:d}]", i++), pt));
                }
            }
            catch (System.Exception ex)
            {
                data.Add(new Snoop.Data.Exception("Xyz", ex));
            }

            Line line = crv as Line;

            if (line != null)
            {
                Stream(data, line);
                return;
            }

            Arc arc = crv as Arc;

            if (arc != null)
            {
                Stream(data, arc);
                return;
            }

            Ellipse ellipse = crv as Ellipse;

            if (ellipse != null)
            {
                Stream(data, ellipse);
                return;
            }

            NurbSpline nurbSpline = crv as NurbSpline;

            if (nurbSpline != null)
            {
                Stream(data, nurbSpline);
                return;
            }

            HermiteSpline hermiteSpline = crv as HermiteSpline;

            if (hermiteSpline != null)
            {
                Stream(data, hermiteSpline);
                return;
            }
        }
 /// <summary>
 /// Create an angular dimension from a give arc
 /// </summary>
 /// <param name="arc">The start and end points of the arc are the start and endpoints of the dimension</param>
 /// <param name="offset">How far to offset the dimension location from the arc</param>
 public AngularDimension(Arc arc, double offset)
 {
   IntPtr ptr = UnsafeNativeMethods.ON_AngularDimension2_New(ref arc, offset);
   ConstructNonConstObject(ptr);
 }
示例#43
0
 /// <summary>
 /// Try to convert this curve into an Arc using a custom tolerance.
 /// </summary>
 /// <param name="plane">Plane in which the comparison is performed.</param>
 /// <param name="arc">On success, the Arc will be filled in.</param>
 /// <param name="tolerance">Tolerance to use when checking.</param>
 /// <returns>true if the curve could be converted into an arc within the given plane.</returns>
 public bool TryGetArc(Plane plane, out Arc arc, double tolerance)
 {
   arc = new Arc();
   IntPtr ptr = ConstPointer();
   return UnsafeNativeMethods.ON_Curve_IsArc(ptr, idxIgnoreNone, ref plane, ref arc, tolerance);
 }
示例#44
0
 /// <summary>
 /// Test a curve to see if it can be represented by an arc or circle within the given tolerance.
 /// </summary>
 /// <param name="tolerance">Tolerance to use when checking.</param>
 /// <returns>
 /// true if the curve can be represented by an arc or a circle within tolerance.
 /// </returns>
 public bool IsArc(double tolerance)
 {
   Arc arc = new Arc();
   Plane p = Plane.WorldXY;
   IntPtr ptr = ConstPointer();
   return UnsafeNativeMethods.ON_Curve_IsArc(ptr, idxIgnorePlaneArcOrEllipse, ref p, ref arc, tolerance);
 }
示例#45
0
 /// <summary>
 /// Try to convert this curve into an Arc using RhinoMath.ZeroTolerance.
 /// </summary>
 /// <param name="plane">Plane in which the comparison is performed.</param>
 /// <param name="arc">On success, the Arc will be filled in.</param>
 /// <returns>true if the curve could be converted into an arc within the given plane.</returns>
 public bool TryGetArc(Plane plane, out Arc arc)
 {
   return TryGetArc(plane, out arc, RhinoMath.ZeroTolerance);
 }
示例#46
0
 /// <summary>
 /// Initializes a new <see cref="ArcCurve"/> instance,
 /// copying values from another <see cref="Arc"/>.
 /// </summary>
 /// <param name="arc">Another Arc.</param>
 public ArcCurve(Arc arc)
 {
   IntPtr ptr = UnsafeNativeMethods.ON_ArcCurve_New2(ref arc);
   ConstructNonConstObject(ptr);
 }
示例#47
0
 /// <summary>
 /// Initializes a new <see cref="ArcCurve"/> instance,
 /// copying values from another <see cref="Arc"/> and specifying the 
 /// needed parametrization of the arc.
 /// <para>Arc will not be cut again at these parameterizations.</para>
 /// </summary>
 /// <param name="arc">An original arc.</param>
 /// <param name="t0">A new Domain.T0 value.</param>
 /// <param name="t1">A new Domain.T1 value.</param>
 public ArcCurve(Arc arc, double t0, double t1)
 {
   IntPtr ptr = UnsafeNativeMethods.ON_ArcCurve_New3(ref arc, t0, t1);
   ConstructNonConstObject(ptr);
 }
示例#48
0
 internal static extern bool ON_Arc_Transform(ref Arc pArc, ref Transform xf);
        /// <summary>
        /// Creates an IFC arc from a Revit arc object.
        /// </summary>
        /// <param name="exporterIFC">The exporter.</param>
        /// <param name="arc">The arc.</param>
        /// <param name="scaledPlane">The scaled plane.</param>
        /// <returns>The arc handle.</returns>
        public static IFCAnyHandle CreateArc(ExporterIFC exporterIFC, Arc arc, Plane scaledPlane)
        {
            IFCFile file = exporterIFC.GetFile();

            XYZ centerPoint = ExporterIFCUtils.TransformAndScalePoint(exporterIFC, arc.Center);

            IFCAnyHandle centerPointHandle;
            if (scaledPlane != null)
            {
                List<double> centerPointValues = ConvertPointToLocalCoordinatesCommon(scaledPlane, centerPoint);
                centerPointHandle = ExporterUtil.CreateCartesianPoint(file, centerPointValues);
            }
            else
                centerPointHandle = ExporterUtil.CreateCartesianPoint(file, centerPoint);

            XYZ xDirection = ExporterIFCUtils.TransformAndScaleVector(exporterIFC, arc.XDirection);
            IFCAnyHandle axis;
            if (scaledPlane != null)
            {
                List<double> xDirectionValues = ConvertVectorToLocalCoordinates(scaledPlane, xDirection);
                IFCAnyHandle xDirectionHandle = ExporterUtil.CreateDirection(file, xDirectionValues);
                axis = IFCInstanceExporter.CreateAxis2Placement2D(file, centerPointHandle, null, xDirectionHandle);
            }
            else
                axis = ExporterUtil.CreateAxis2Placement3D(file, centerPoint, arc.Normal, xDirection);

            double arcRadius = arc.Radius * exporterIFC.LinearScale;

            IFCAnyHandle circle = IFCInstanceExporter.CreateCircle(file, axis, arcRadius);

            IFCAnyHandle arcHandle = circle;
            if (arc.IsBound)
            {
                double endParam0 = arc.get_EndParameter(0);
                double endParam1 = arc.get_EndParameter(1);
                if (scaledPlane != null && MustFlipCurve(scaledPlane, arc))
                {
                    double oldParam0 = endParam0;
                    endParam0 = Math.PI * 2 - endParam1;
                    endParam1 = Math.PI * 2 - oldParam0;
                }
                IFCData firstParam = IFCDataUtil.CreateAsParameterValue(MathUtil.PutInRange(endParam0, Math.PI, 2 * Math.PI) * (180 / Math.PI));
                IFCData secondParam = IFCDataUtil.CreateAsParameterValue(MathUtil.PutInRange(endParam1, Math.PI, 2 * Math.PI) * (180 / Math.PI));

                // todo: check that firstParam != secondParam.
                HashSet<IFCData> trim1 = new HashSet<IFCData>();
                trim1.Add(firstParam);
                HashSet<IFCData> trim2 = new HashSet<IFCData>();
                trim2.Add(secondParam);

                arcHandle = IFCInstanceExporter.CreateTrimmedCurve(file, circle, trim1, trim2, true, IFCTrimmingPreference.Parameter);
            }
            return arcHandle;
        }
示例#50
0
 internal static extern void ON_ArcCurve_GetArc(IntPtr pConstCurve, ref Arc rc);
示例#51
0
 internal static extern Guid ONX_Model_ObjectTable_AddArc(IntPtr pModel, ref Arc pArc, IntPtr pConstAttributes);
示例#52
0
 internal static extern IntPtr ON_ArcCurve_New2(ref Arc arc);
示例#53
0
 internal static extern IntPtr ON_ArcCurve_New3(ref Arc arc, double t0, double t1);
示例#54
0
 internal static extern int ON_Arc_GetNurbForm(ref Arc pArc, IntPtr nurbs_curve);
示例#55
0
 internal static extern bool ON_PolyCurve_AppendAndMatch(IntPtr pCurve, ref Arc arc);
示例#56
0
 internal static extern bool ON_Arc_ClosestPointTo(ref Arc pArc, Point3d testPoint, ref double t);
示例#57
0
    /// <summary>
    /// Computes the fillet arc for a curve filleting operation.
    /// </summary>
    /// <param name="curve0">First curve to fillet.</param>
    /// <param name="curve1">Second curve to fillet.</param>
    /// <param name="radius">Fillet radius.</param>
    /// <param name="t0Base">Parameter on curve0 where the fillet ought to start (approximately).</param>
    /// <param name="t1Base">Parameter on curve1 where the fillet ought to end (approximately).</param>
    /// <returns>The fillet arc on success, or Arc.Unset on failure.</returns>
    public static Arc CreateFillet(Curve curve0, Curve curve1, double radius, double t0Base, double t1Base)
    {
      Arc arc = Arc.Unset;

      double t0, t1;
      Plane plane;
      if (GetFilletPoints(curve0, curve1, radius, t0Base, t1Base, out t0, out t1, out plane))
      {
        Vector3d radial0 = curve0.PointAt(t0) - plane.Origin;
        Vector3d radial1 = curve1.PointAt(t1) - plane.Origin;
        radial0.Unitize();
        radial1.Unitize();

        double angle = System.Math.Acos(radial0 * radial1);
        Plane fillet_plane = new Plane(plane.Origin, radial0, radial1);
        arc = new Arc(fillet_plane, plane.Origin, radius, angle);
      }
      return arc;
    }
        private void Stream(ArrayList data, Arc arc)
        {
            data.Add(new Snoop.Data.ClassSeparator(typeof(Arc)));

            data.Add(new Snoop.Data.Xyz("Center", arc.Center));
            data.Add(new Snoop.Data.Xyz("Normal", arc.Normal));
            data.Add(new Snoop.Data.Double("Radius", arc.Radius));
        }
示例#59
0
 public void ReadEntryContentCorrectly() => File.OpenRead(FileName).Using(stream =>
 {
     var entries = Arc.Read(stream).ToArray();
     Assert.Equal(0x42, entries[0].Data[2]);
     Assert.Equal(0x43, entries[1].Data[2]);
 });
示例#60
-1
        //Purpose: returns false if an inconsistency is found and true otherwise
        public bool AC3()
        {
            //AC3 Algorithm from the book

            //local variables: Queue of arcs, initially all the arcs in CSP
            Queue<Arc> arcQueue = new Queue<Arc>();

            //Add all the arcs into the queue
            for (int i = 0; i < boardWidthAndHeight; i++)
            {
                for (int j = 0; j < boardWidthAndHeight; j++)
                {
                    for (int k = 0; k < board[i, j].getConstraints().Count; k++)
                    {
                        Arc temp = new Arc();//used for loading arcs into the arc queue,
                        temp.setVar1Row(i);
                        temp.setVar1Column(j);

                        temp.setVar2Row(board[i, j].getConstraints()[k].getRow());
                        temp.setVar2Column(board[i, j].getConstraints()[k].getColumn());
                        arcQueue.Enqueue(temp);
                    }
                }
            }

            //while(queue is not empty) do
            while (arcQueue.Count > 0)
            {
                Arc temp = new Arc();//holds the object removed from the queue
                //(Xi, Xj) <- Remove First(queue)
                temp = arcQueue.Dequeue();

                //if (Revise(csp, Xi, Xj))
                if (revise(temp))
                {
                    //if (size of Domain == 0)
                    if (board[temp.getVar1Row(), temp.getVar1Column()].getDomain().Count == 0)
                    {
                        return false;
                    }
                    //for (each Xk in Xi, Neighbors - {Xj} do
                    for (int k = 0; k < board[temp.getVar1Row(), temp.getVar1Column()].getConstraints().Count; k++)
                    {
                        Arc temp2 = new Arc();//used for loading new arcs into the arc queue
                        //add (Xk, Xi) to the queue
                        temp2.setVar1Row(board[temp.getVar1Row(), temp.getVar1Column()].getConstraints()[k].getRow());
                        temp2.setVar1Column(board[temp.getVar1Row(), temp.getVar1Column()].getConstraints()[k].getColumn());

                        temp2.setVar2Row(temp.getVar1Row());
                        temp2.setVar2Column(temp.getVar1Column());
                        arcQueue.Enqueue(temp2);
                    }

                }

            }

            return true;
        }