Ejemplo n.º 1
0
        public void TestPhysicsCircleColliderCreate()
        {
            var geometry = new CircleGeometry
            {
                Center = new float2(-10.10f, 10.12f),
                Radius = 3.0f
            };

            const uint UserData = 0xDEADBEEF;

            using (var colliderBlob = PhysicsCircleCollider.Create(geometry, CollisionFilter.Default, PhysicsMaterial.Default, UserData))
            {
                ref var collider = ref colliderBlob.GetColliderRef <PhysicsCircleCollider>();

                Assert.AreEqual(ColliderType.Circle, collider.ColliderType);
                Assert.AreEqual(CollisionType.Convex, collider.CollisionType);
                Assert.AreEqual(UserData, collider.UserData);
                Assert.AreEqual(CollisionFilter.Default, collider.Filter);
                Assert.AreEqual(PhysicsMaterial.Default, collider.Material);

                Assert.AreEqual(geometry.Center, collider.Center);
                Assert.AreEqual(geometry.Center, collider.Geometry.Center);
                Assert.AreEqual(geometry.Radius, collider.Radius);
                Assert.AreEqual(geometry.Radius, collider.Geometry.Radius);
            }
Ejemplo n.º 2
0
        /// <summary>
        /// Checks whether the current data is enough to construct a circle.
        /// If so, draws it (erasing any previously drawn circle).
        /// </summary>
        void OnChange()
        {
            // Try to construct a circle based on what's been entered
            Circle c = GetCurrentCircle();

            if (c == null)
            {
                // If we didn't get anything, but we previously had a circle, ensure
                // it gets erased.
                if (m_Circle != null)
                {
                    m_Circle = null;
                    ErasePainting();
                }
            }
            else
            {
                // Just return if current circle matches what we've already got
                if (m_Circle != null && CircleGeometry.IsCoincident(m_Circle, c, Constants.XYRES))
                {
                    return;
                }

                // Draw the new circle
                m_Circle = c;
                ErasePainting();
            }
        }
Ejemplo n.º 3
0
        private void A_DrawEraseEvent(ActionEventArgs gs)
        {
            CircleGeometry line = this.action.Geometry as CircleGeometry;

            sublineGeometry.Start = line.Start;
            sublineGeometry.End   = line.End;
            sublineGeometry.Update();
            this.Tip.SetText(sublineGeometry.TextValue, sublineGeometry.TextPosition, sublineGeometry.TextAngle);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Draws a circular arc
        /// </summary>
        /// <param name="display">The display to draw to</param>
        /// <param name="arc">The circular arc</param>
        public void Render(ISpatialDisplay display, IClockwiseCircularArcGeometry arc)
        {
            ICircleGeometry circle     = arc.Circle;
            IWindow         extent     = CircleGeometry.GetExtent(circle);
            float           topLeftX   = display.EastingToDisplay(extent.Min.X);
            float           topLeftY   = display.NorthingToDisplay(extent.Max.Y);
            float           size       = 2.0f * display.LengthToDisplay(circle.Radius);
            float           startAngle = (float)(arc.StartBearingInRadians * MathConstants.RADTODEG - 90.0);
            float           sweepAngle = (float)(arc.SweepAngleInRadians * MathConstants.RADTODEG);

            display.Graphics.DrawArc(m_Pen, topLeftX, topLeftY, size, size, startAngle, sweepAngle);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Draws this object on the specified display
 /// </summary>
 /// <param name="display">The display to draw to</param>
 /// <param name="style">The drawing style</param>
 public override void Render(ISpatialDisplay display, IDrawStyle style)
 {
     // If we're dealing with a construction line, it's drawn dotted
     // regardless of the supplied style.
     if (Geometry.IsCircle && Creator.EditId == EditingActionId.NewCircle)
     {
         CircleGeometry.Render(Geometry.Circle, display, new DottedStyle(style.LineColor));
     }
     else
     {
         base.Render(display, style);
     }
 }
Ejemplo n.º 6
0
    protected override void Setup()
    {
        base.Setup();

        m_BoxGeometry = new BoxGeometry
        {
            Size   = new float2(0.01f, 120.40f),
            Center = new float2(-10.10f, 10.12f),
        };

        m_CapsuleGeometry = new CapsuleGeometry
        {
            Vertex0 = new float2(0f, 3f),
            Vertex1 = new float2(0f, -2f),
            Radius  = 1.5f
        };

        m_CircleGeometry = new CircleGeometry
        {
            Center = new float2(-10.10f, 10.12f),
            Radius = 3.0f
        };

        m_Vertices = new NativeArray <float2>(
            new float2[]
        {
            new float2(-1f, -2f),
            new float2(2f, -3f),
            new float2(4f, 5f),
            new float2(-6f, 7f)
        },
            Allocator.Persistent
            );

        m_GiftWrappedIndices = new NativeArray <int>(
            new int[]
        {
            2, 3, 0, 1
        },
            Allocator.Persistent
            );

        Assert.IsTrue(m_Vertices.Length >= 3, "Test array must contain at least 3 points.");
        Assert.AreEqual(m_Vertices.Length, m_GiftWrappedIndices.Length, "Test array lengths do not match.");

        m_PolygonGeometry = new PolygonGeometry
        {
            Vertices    = m_Vertices,
            BevelRadius = 0.0f
        };
    }
Ejemplo n.º 7
0
        public unsafe void PhysicsBodyCastColliderTest()
        {
            var geometry = new BoxGeometry
            {
                Size = new float2(1f),
            };

            using (var collider = PhysicsBoxCollider.Create(geometry))
            {
                var physicsBody = new PhysicsBody(collider);

                var queryInput = new ColliderCastInput()
                {
                    Rotation = float2x2.identity
                };
                var closestHit = new ColliderCastHit();
                var allHits    = new NativeList <ColliderCastHit>(Allocator.Temp);

                var circleGeometry = new CircleGeometry {
                    Radius = 0.5f
                };

                using (var circleBlob = PhysicsCircleCollider.Create(circleGeometry))
                {
                    queryInput.Collider = circleBlob;

                    // OK case.
                    var startOK = new float2(-10f, -10f);
                    var endOK   = new float2(10f, 10f);
                    queryInput.Start = startOK;
                    queryInput.End   = endOK;
                    Assert.IsTrue(physicsBody.CastCollider(queryInput));
                    Assert.IsTrue(physicsBody.CastCollider(queryInput, out closestHit));
                    Assert.IsTrue(physicsBody.CastCollider(queryInput, ref allHits));

                    // Fail Case.
                    var startFail = new float2(-10f, -10f);
                    var endFail   = new float2(10f, -10f);
                    queryInput.Start = startFail;
                    queryInput.End   = endFail;
                    Assert.IsFalse(physicsBody.CastCollider(queryInput));
                    Assert.IsFalse(physicsBody.CastCollider(queryInput, out closestHit));
                    Assert.IsFalse(physicsBody.CastCollider(queryInput, ref allHits));
                }

                allHits.Dispose();
            }
        }
Ejemplo n.º 8
0
        public void Render(ISpatialDisplay display, IDrawStyle style)
        {
            if (this.category == CadastralLineCategory.Radial)
            {
                style = new DottedStyle(style.LineColor);
            }

            if (m_Center == null)
            {
                style.Render(display, this.PositionArray);
            }
            else
            {
                // radius less than zero may represent a counter-clockwise direction
                bool isClockwise = (this.radius > 0.0);

                // Define a circular arc that is assumed to run clockwise.
                ICircleGeometry      circle = new CircleGeometry(m_Center.Geometry, Math.Abs(this.radius));
                ICircularArcGeometry arc    = new CircularArcGeometry(circle, m_From.Geometry, m_To.Geometry, isClockwise);

                // Assume clockwise, see what it looks like
                style.Render(display, arc);
            }

            /*
             * else
             * {
             * if (!this.arcLengthSpecified)
             *  throw new ApplicationException("Cannot determine arc direction");
             *
             * // Define a circular arc that is assumed to run clockwise.
             * CircleGeometry circle = new CircleGeometry(m_Center.Geometry, this.radius);
             * CircularArcGeometry arc = new CircularArcGeometry(circle, m_From.Geometry, m_To.Geometry, true);
             *
             * // Assume clockwise, see what it looks like
             * new DrawStyle(Color.Red).Render(display, arc);
             *
             * //double arcLength = arc.Length.Meters;
             * //double othLength = circle.Length.Meters;
             *
             * //// Get the arc length in meters (TODO: need to access file header to determine how to convert lengths)
             * //if (Math.Abs(othLength - this.arcLength) < Math.Abs(arcLength - this.arcLength))
             * //    arc.IsClockwise = false;
             * }
             */
        }
Ejemplo n.º 9
0
        public unsafe void PhysicsBodyOverlapColliderTest()
        {
            var geometry = new BoxGeometry
            {
                Size = new float2(2f),
            };

            using (var collider = PhysicsBoxCollider.Create(geometry))
            {
                var physicsBody = new PhysicsBody(collider);

                var queryInput = new OverlapColliderInput()
                {
                    Filter = CollisionFilter.Default
                };
                var closestHit = new OverlapColliderHit();
                var allHits    = new NativeList <OverlapColliderHit>(Allocator.Temp);

                var circleGeometry = new CircleGeometry {
                    Radius = 0.5f
                };
                using (var circleBlob = PhysicsCircleCollider.Create(circleGeometry))
                {
                    queryInput.Collider = circleBlob;

                    // OK case.
                    var transformOK = new PhysicsTransform(new float2(1f));
                    queryInput.Transform = transformOK;
                    Assert.IsTrue(physicsBody.OverlapCollider(queryInput));
                    Assert.IsTrue(physicsBody.OverlapCollider(queryInput, out closestHit));
                    Assert.IsTrue(physicsBody.OverlapCollider(queryInput, ref allHits));

                    // Fail Case.
                    var transformFail = new PhysicsTransform(new float2(-10f));
                    queryInput.Transform = transformFail;
                    Assert.IsFalse(physicsBody.OverlapCollider(queryInput));
                    Assert.IsFalse(physicsBody.OverlapCollider(queryInput, out closestHit));
                    Assert.IsFalse(physicsBody.OverlapCollider(queryInput, ref allHits));
                }

                allHits.Dispose();
            }
        }
Ejemplo n.º 10
0
        public unsafe void PhysicsBodyCalculateDistanceTest()
        {
            var geometry = new BoxGeometry
            {
                Size = new float2(1f),
            };

            using (var collider = PhysicsBoxCollider.Create(geometry))
            {
                var physicsBody = new PhysicsBody(collider);

                var circleGeometry = new CircleGeometry {
                    Radius = 1f
                };

                using (var circleBlob = PhysicsCircleCollider.Create(circleGeometry))
                {
                    var queryInput = new ColliderDistanceInput
                    {
                        Collider  = circleBlob,
                        Transform = new PhysicsTransform(new float2(-10f))
                    };

                    var closestHit = new DistanceHit();
                    var allHits    = new NativeList <DistanceHit>(Allocator.Temp);

                    // OK case : with enough max distance
                    queryInput.MaxDistance = 10000.0f;
                    Assert.IsTrue(physicsBody.CalculateDistance(queryInput));
                    Assert.IsTrue(physicsBody.CalculateDistance(queryInput, out closestHit));
                    Assert.IsTrue(physicsBody.CalculateDistance(queryInput, ref allHits));

                    // Fail case : not enough max distance
                    queryInput.MaxDistance = 1f;
                    Assert.IsFalse(physicsBody.CalculateDistance(queryInput));
                    Assert.IsFalse(physicsBody.CalculateDistance(queryInput, out closestHit));
                    Assert.IsFalse(physicsBody.CalculateDistance(queryInput, ref allHits));

                    allHits.Dispose();
                }
            }
        }
Ejemplo n.º 11
0
        public void PhysicsBodyCalculateAabb_CircleColliderTest()
        {
            var geometry = new CircleGeometry
            {
                Center = new float2(-10.10f, 10.12f),
                Radius = 3.0f
            };

            var collider1 = PhysicsCircleCollider.Create(geometry);
            var collider2 = PhysicsCircleCollider.Create(geometry);

            var physicsBody = new PhysicsBody(collider1);

            var aabb = physicsBody.CalculateAabb();

            Assert.IsTrue(aabb.Equals(collider2.Value.CalculateAabb()));

            collider1.Dispose();
            collider2.Dispose();
        }
Ejemplo n.º 12
0
        protected override void OnUpdate()
        {
            Entities.ForEach((UnityEngine.CircleCollider2D collider) =>
            {
                // Convert the collider if it's valid.
                if (ConversionUtilities.CanConvertCollider(collider))
                {
                    try
                    {
                        var lossyScale = new float3(collider.transform.lossyScale).xy;
                        if (math.any(!math.isfinite(lossyScale)) || math.any(lossyScale <= 0.0f))
                        {
                            throw new ArgumentException("Transform XY scale cannot be zero or Infinite/NaN.", "Transform XY scale.");
                        }

                        var localToWorld = ConversionUtilities.GetColliderLocalToWorld(collider);

                        var geometry = new CircleGeometry
                        {
                            Center = new float3(localToWorld.MultiplyPoint(collider.offset)).xy,
                            Radius = math.clamp(collider.radius * math.cmax(lossyScale), ConversionUtilities.MinRangeClamp, ConversionUtilities.MaxRangeClamp),
                        };

                        var colliderBlob = PhysicsCircleCollider.Create(
                            geometry,
                            ConversionUtilities.GetCollisionFilterFromCollider(collider),
                            ConversionUtilities.GetPhysicsMaterialFromCollider(collider)
                            );

                        // Submit the collider for conversion.
                        m_ColliderConversionSystem.SubmitCollider(collider, ref colliderBlob);
                    }
                    catch (ArgumentException exception)
                    {
                        UnityEngine.Debug.LogWarning($"{collider.name}: {exception.Message}", collider);
                    }
                }
            });
        }
Ejemplo n.º 13
0
    public static void Generate(MotionCanvas <SkiaSharpDrawingContext> canvas)
    {
        var r = new Random();
        var p = new SolidColorPaint(SKColors.Blue, 3)
        {
            IsFill = true
        };

        canvas.AddDrawableTask(p);

        for (var i = 0; i < 1000; i++)
        {
            var circle = new CircleGeometry {
                X = r.Next(15, 285), Y = r.Next(15, 285), Width = 5, Height = 5
            };

            _ = circle
                .TransitionateProperties(
                nameof(circle.X), nameof(circle.Y))
                .WithAnimation(animation =>
                               animation
                               .WithDuration(TimeSpan.FromSeconds(1))
                               .WithEasingFunction(EasingFunctions.ElasticOut))
                .CompleteCurrentTransitions();

            //circle.SetPropertiesTransitions(
            //    new Animation(EasingFunctions.ElasticOut, TimeSpan.FromSeconds(1)),
            //    nameof(circle.X), nameof(circle.Y));
            //circle.CompleteAllTransitions();

            p.AddGeometryToPaintTask(canvas, circle);

            circle.X = r.Next(15, 285);
            circle.Y = r.Next(15, 285);
        }

        canvas.Invalidate();
    }
Ejemplo n.º 14
0
        public void TestPhysicsColliderBlobOwner()
        {
            // Create the collider blob.
            var geometry = new CircleGeometry {
                Radius = 1f
            };
            var colliderBlob = PhysicsCircleCollider.Create(geometry);

            // Create the entity that owns the collider blob.
            var entity = EntityManager.CreateEntity();

            EntityManager.AddComponentData(entity, new PhysicsColliderBlob {
                Collider = colliderBlob
            });
            EntityManager.AddComponentData(entity, new PhysicsColliderBlobOwner {
                Collider = colliderBlob
            });

            // The collider blob components should be present.
            Assert.IsTrue(EntityManager.HasComponent <PhysicsColliderBlob>(entity));
            Assert.IsTrue(EntityManager.HasComponent <PhysicsColliderBlobOwner>(entity));

            // Destroy the entity.
            EntityManager.DestroyEntity(entity);

            // The collider blob component should be removed but the blob owner should be present still.
            Assert.IsFalse(EntityManager.HasComponent <PhysicsColliderBlob>(entity));
            Assert.IsTrue(EntityManager.HasComponent <PhysicsColliderBlobOwner>(entity));

            // Run the system.
            MainLoop();

            // The collider blob owner should now be removed indicating that the
            // disposal system has disposed of the blob.
            // Unfortunately I don't believe there's a way to detect the actual deallocation
            // as our instance here still assumes the blob ptr is valid.
            Assert.IsFalse(EntityManager.HasComponent <PhysicsColliderBlobOwner>(entity));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 解析指定的XML对象
        /// </summary>
        /// <param name="messageXML"></param>
        private void ParseXML(XmlReader xmlReader)
        {
            Geometry2D shape = null;

            switch (xmlReader.Name)
            {
            case "ArcGeometry":
                shape = new ArcGeometry();
                break;

            case "BeamGeometry":
                shape = new BeamGeometry();
                break;

            case "CircleGeometry":
                shape = new CircleGeometry();
                break;

            case "CSectionGeometry":
                shape = new CSectionGeometry();
                break;

            case "EllipseGeometry":
                shape = new EllipseGeometry();
                break;

            case "FloorGeometry":
                shape = new FloorGeometry();
                break;

            case "LineGeometry":
                shape = new LineGeometry();
                break;

            case "MeasureGeometry":
                shape = new MeasureGeometry();
                break;

            case "MemberGeometry":
                shape = new MemberGeometry();
                break;

            case "OSBGeometry":
                shape = new OSBGeometry();
                break;

            case "PointGeometry":
                shape = new PointGeometry();
                break;

            case "PolygonGeometry":
                shape = new PolygonGeometry();
                break;

            case "PolylineGeometry":
                shape = new PolylineGeometry();
                break;

            case "RectangleGeometry":
                shape = new RectangleGeometry();
                break;

            case "SteelBeamGeometry":
                shape = new SteelBeamGeometry();
                break;

            case "TextGeometry":
                shape = new TextGeometry();
                break;

            case "WallGeometry":
                shape = new WallGeometry();
                break;
            }

            if (shape != null)
            {
                //将信息写入数据流中
                shape.ReadXML(xmlReader);
                //将图形添加都界面上
                this.drawingKernel.AddShape(shape);
            }
        }
Ejemplo n.º 16
0
        private ArcFeature ImportArc(Ntx.Line line, Operation creator, ILength tol)
        {
            Debug.Assert(line.IsCurve);
            IEntity what = GetEntityType(line, SpatialType.Line);

            // Get positions defining the arc
            PointGeometry[] pts = GetPositions(line);

            // Ignore zero-length lines
            if (HasZeroLength(pts))
            {
                return(null);
            }

            // Add a point at the center of the circle
            Ntx.Position  pos    = line.Center;
            PointGeometry pc     = new PointGeometry(pos.Easting, pos.Northing);
            PointFeature  center = EnsurePointExists(pc, tol, creator);

            // Calculate exact positions for the arc endpoints
            double          radius = line.Radius;
            ICircleGeometry cg     = new CircleGeometry(pc, radius);
            IPosition       bc     = CircleGeometry.GetClosestPosition(cg, pts[0]);
            IPosition       ec     = CircleGeometry.GetClosestPosition(cg, pts[pts.Length - 1]);

            // Round off to nearest micron
            PointGeometry bcg = PointGeometry.Create(bc);
            PointGeometry ecg = PointGeometry.Create(ec);

            // Ensure point features exist at both ends of the line.
            PointFeature ps = GetArcEndPoint(bcg, tol, creator);
            PointFeature pe = GetArcEndPoint(ecg, tol, creator);

            // Try to find a circle that's already been added by this import.
            Circle c = EnsureCircleExists(center, radius, tol, creator);

            // Determine which way the arc is directed
            bool iscw = LineStringGeometry.IsClockwise(pts, center);

            InternalIdValue id  = CadastralMapModel.Current.WorkingSession.AllocateNextId();
            ArcFeature      arc = new ArcFeature(creator, id, what, c, ps, pe, iscw);

            // The toological status of the incoming arc may override the status that the
            // constructor derived from the entity type
            arc.SetTopology(line.IsTopologicalArc);

            #if DEBUG
            // Confirm the NTX data was valid (ensure it's consistent with what we've imported)...

            double readRad = c.Radius;
            double calcRad = BasicGeom.Distance(c.Center, ps);
            Debug.Assert(Math.Abs(readRad - calcRad) < tol.Meters);

            foreach (IPointGeometry pg in pts)
            {
                ILength check = arc.Geometry.Distance(pg);
                Debug.Assert(check.Meters < tol.Meters);
            }
            #endif

            return(arc);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Obtains the geometry for spans along this leg.
        /// </summary>
        /// <param name="bc">The position for the start of the leg.
        /// <param name="bcBearing">The bearing on entry into the leg.</param>
        /// <param name="sfac">Scale factor to apply to distances.</param>
        /// <param name="spans">Information for the spans coinciding with this leg.</param>
        /// <returns>The sections along this leg</returns>
        internal override ILineGeometry[] GetSpanSections(IPosition bc, double bcBearing, double sfac, SpanInfo[] spans)
        {
            // Can't do anything if the leg radius isn't defined
            if (m_Metrics.ObservedRadius == null)
            {
                throw new InvalidOperationException("Cannot create sections for circular leg with undefined radius");
            }

            var result = new ILineGeometry[spans.Length];

            // Use supplied stuff to derive info on the center and EC.
            IPosition center;
            IPosition ec;
            double    bearingToBC;
            double    ecBearing;

            GetPositions(bc, bcBearing, sfac, out center, out bearingToBC, out ec, out ecBearing);

            // Define the underlying circle
            ICircleGeometry circle = new CircleGeometry(PointGeometry.Create(center), BasicGeom.Distance(center, bc));

            // Handle case where the leg is a cul-de-sac with no observed spans
            if (spans.Length == 1 && spans[0].ObservedDistance == null)
            {
                result[0] = new CircularArcGeometry(circle, bc, ec, m_Metrics.IsClockwise);
                return(result);
            }

            /// Initialize scaling factor for distances in cul-de-sacs (ratio of the length calculated from
            /// the CA & Radius, versus the observed distances that were actually specified). For curves that
            /// are not cul-de-sacs, this will be 1.0
            double culFactor = 1.0;

            if (m_Metrics.IsCulDeSac)
            {
                double obsv = PrimaryFace.GetTotal();
                if (obsv > MathConstants.TINY)
                {
                    culFactor = Length.Meters / obsv;
                }
            }

            IPosition sPos        = bc;
            IPosition ePos        = null;
            bool      isClockwise = m_Metrics.IsClockwise;
            double    radius      = RadiusInMeters;
            double    edist       = 0.0;

            for (int i = 0; i < result.Length; i++, sPos = ePos)
            {
                // Add on the unscaled distance
                edist += spans[i].ObservedDistance.Meters;

                // Get the angle subtended at the center of the circle. We use
                // unscaled values here, since the scale factors would cancel out.
                // However, we DO apply any cul-de-sac scaling factor, to account
                // for the fact that the distance may be inconsistent with the
                // curve length derived from the CA and radius. For example, it
                // is possible that the calculated curve length=200, although the
                // total of the observed spans is somehow only 100. In that case,
                // if the supplied distance is 50, we actually want to use a
                // value of 50 * (200/100) = 100.

                double angle = (edist * culFactor) / radius;

                // Get the bearing of the point with respect to the center of the circle.

                double bearing;

                if (isClockwise)
                {
                    bearing = bearingToBC + angle;
                }
                else
                {
                    bearing = bearingToBC - angle;
                }

                // Calculate the position using the scaled radius.
                ePos = Geom.Polar(center, bearing, radius * sfac);

                result[i] = new CircularArcGeometry(circle, sPos, ePos, isClockwise);
            }

            return(result);
        }
Ejemplo n.º 18
0
        // Circle
        internal uint Intersect(IPointGeometry center, double radius)
        {
            ICircleGeometry circle = new CircleGeometry(center, radius);

            return(m_IntersectedObject.LineGeometry.IntersectCircle(this, circle));
        }
Ejemplo n.º 19
0
        private void listView1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                string areaName = listView1.SelectedItems[0].Text;
                SelectedIndex = listView1.SelectedItems[0].Index;
                SelectedItem  = task.Items[SelectedIndex];

                //Отрисовка превьюшки детали
                Document Doc = TFlex.Application.ActiveDocument;
                SelectedArea = Doc.GetObjectByName(areaName) as Area;
                TFlex.Drawing.Rectangle bound = SelectedArea.BoundRect;
                double Scale = 159 / Math.Max(bound.Width, bound.Height);

                Bitmap   img   = new Bitmap(160, 160);
                Graphics graph = Graphics.FromImage(img);
                Pen      pen   = new Pen(Brushes.White);
                graph.DrawRectangle(pen, new Rectangle(0, 0, 159, 159));
                pen       = new Pen(Brushes.Black);
                pen.Width = 1;
                for (int cc = 0; cc < SelectedArea.ContourCount; cc++)
                {
                    Contour cont = SelectedArea.GetContour(cc);
                    foreach (var segm in cont)
                    {
                        switch (segm.GeometryType)
                        {
                        case ObjectGeometryType.Line:
                            LineGeometry line = segm.Geometry as LineGeometry;
                            if (line != null)
                            {
                                graph.DrawLine(pen, (float)((line.X1 - bound.Left) * Scale), (float)((bound.Top - line.Y1) * Scale), (float)((line.X2 - bound.Left) * Scale), (float)((bound.Top - line.Y2) * Scale));
                            }
                            break;

                        case ObjectGeometryType.Circle:
                            CircleGeometry circle = segm.Geometry as CircleGeometry;
                            if (circle == null)
                            {
                                break;
                            }
                            double radius = (circle.Radius * Scale);
                            int    xc     = (int)((circle.CenterX - bound.Left) * Scale);
                            int    yc     = (int)((bound.Top - circle.CenterY) * Scale);

                            graph.DrawEllipse(pen, new Rectangle((int)(xc - radius), (int)(yc - radius), (int)radius * 2, (int)radius * 2));
                            break;

                        case ObjectGeometryType.CircleArc:
                            CircleArcGeometry cgeom = segm.Geometry as CircleArcGeometry;
                            if (cgeom == null)
                            {
                                break;
                            }
                            int xc1 = (int)((cgeom.CenterX - bound.Left) * Scale);
                            int yc1 = (int)((bound.Top - cgeom.CenterY) * Scale);
                            radius = (cgeom.Radius * Scale);
                            var    angles = NFUtils.GetArcAngle(cgeom);
                            double ang    = angles.Item1 * 180 / Math.PI;
                            double ang1   = angles.Item2 * 180 / Math.PI - 90;
                            graph.DrawArc(pen, (float)(xc1 - radius), (float)(yc1 - radius), (float)(radius * 2), (float)(radius * 2), (float)ang1, (float)ang);
                            break;

                        default:

                            PolylineGeometry geom = segm.Geometry as PolylineGeometry;

                            if (geom == null)
                            {
                                break;
                            }
                            for (int i = 1; i < geom.Count; i++)
                            {
                                int x1 = (int)((geom.GetX(i) - bound.Left) * Scale);
                                int y1 = (int)((bound.Top - geom.GetY(i)) * Scale);
                                int x2 = (int)((geom.GetX(i - 1) - bound.Left) * Scale);
                                int y2 = (int)((bound.Top - geom.GetY(i - 1)) * Scale);
                                graph.DrawLine(pen, (float)x1, (float)y1, (float)x2, (float)y2);
                            }
                            break;
                        }
                    }
                }

                pictureBox1.Image = img;

                //Задание параметров форме

                label10.Text = $"Размеры детали = {(int) bound.Width} x {(int) bound.Height}";
                label9.Text  = $"Количество контуров: {SelectedArea.ContourCount}";

                selectComboNum(ref comboBox2, SelectedItem.Rotation);

                selectComboNum(ref comboBox1, SelectedItem.Reflection);
                selectComboNum(ref comboBox1, SelectedItem.Reflection);

                textBox4.Text = SelectedItem.Count.ToString();
            }
        }
Ejemplo n.º 20
0
        public static NFTask GetGeometry()
        {
            Msg("[Nesting Factory] Starting collect geometry...");

            ICollection <Area> Areas = Doc.GetAreas();

            NFTask task = new NFTask();

            foreach (var area in Areas)
            {
                Rectangle BoundBox = area.BoundRect;
                double    boundX   = BoundBox.Left;
                double    boundY   = BoundBox.Top;


                NFItem item = new NFItem(area.ObjectId.ToString());

                for (int num_contour = 0; num_contour < area.ContourCount; num_contour++)
                {
                    Contour   contour = area.GetContour(num_contour);
                    NFContour cont    = new NFContour();

                    foreach (var csegment in contour)
                    {
                        switch (csegment.GeometryType)
                        {
                        case ObjectGeometryType.Line:
                            LineGeometry linegeom = csegment.Geometry as LineGeometry;
                            cont.AddPoint(new NFPoint(linegeom.X1 - boundX, boundY - linegeom.Y1, 0));
                            cont.AddPoint(new NFPoint(linegeom.X2 - boundX, boundY - linegeom.Y2, 0));
                            break;

                        case ObjectGeometryType.CircleArc:
                            CircleArcGeometry cgeom = csegment.Geometry as CircleArcGeometry;
                            cArcToDoubles(cgeom, ref cont, BoundBox, csegment.IsCounterclockwise);
                            break;

                        case ObjectGeometryType.Circle:
                            CircleGeometry cirgeom = csegment.Geometry as CircleGeometry;
                            cont.AddPoint(new NFPoint(cirgeom.CenterX + cirgeom.Radius - boundX, boundY - cirgeom.CenterY, 1));
                            cont.AddPoint(new NFPoint(cirgeom.CenterX - cirgeom.Radius - boundX, boundY - cirgeom.CenterY, 1));
                            break;

                        default:
                            PolylineGeometry polygeom = csegment.Geometry as PolylineGeometry;
                            int v_count = polygeom.Count;
                            for (int i = 0; i < v_count; i++)
                            {
                                if (v_count < 50 || i % (csegment.GeometryType == ObjectGeometryType.Ellipse ? 5 : 1) == 0 || i == v_count)
                                {
                                    cont.AddPoint(new NFPoint(polygeom.GetX(i) - boundX, boundY - polygeom.GetY(i), 0));
                                }
                            }
                            break;
                        }
                    }
                    item.AddContour(cont);
                }
                task.AddItem(item);
            }
            Msg("[Nesting Factory] Geometry collected");
            return(task);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Creates the geometry that can be used to detect intersections with the map.
        /// </summary>
        /// <returns>The geometry for the new line (null if insufficient information has been specified)</returns>
        ArcGeometry CreateIntersectGeometry()
        {
            if (m_Circles == null)
            {
                return(null);
            }

            PointFeature start = StartPoint;

            if (start == null)
            {
                return(null);
            }

            IPointGeometry end = LastMousePosition;

            if (end == null)
            {
                return(null);
            }

            ITerminal endTerm = new FloatingTerminal(end);

            // Find the circle that is closest to the end (only looking at the valid circles
            // that are within a 1mm tolerance). Return null geometry if none of the circles
            // are within reach.

            Circle bestCircle = m_Circles[0];
            double bestdist   = bestCircle.Distance(end).Meters;

            if (m_Circles.Count > 1)
            {
                // See if there is any better choice
                for (int i = 1; i < m_Circles.Count; i++)
                {
                    Circle c    = m_Circles[i];
                    double dist = c.Distance(end).Meters;
                    if (dist < bestdist)
                    {
                        bestCircle = c;
                        bestdist   = dist;
                    }
                }
            }

            // Ignore if the best circle is too far away
            double tol = CircleTolerance.Meters;

            if (bestdist > tol)
            {
                return(null);
            }

            // Project the end point ON to the circle.
            //IPointGeometry center = bestCircle.Center;
            //Turn eturn = new Turn(center, end);
            //IAngle bearing = eturn.Bearing;
            //IPosition cirend = Geom.Polar(center, bearing.Radians, bestCircle.Radius.Meters);
            IPosition cirend = CircleGeometry.GetClosestPosition(bestCircle, end);

            // Get the clockwise angle from the start to the current end point.
            IPointGeometry center = bestCircle.Center;
            Turn           sturn  = new Turn(center, start);
            double         angle  = sturn.GetAngleInRadians(cirend);

            // Figure out which direction the curve should go, depending
            // on whether the user wants the short arc or the long one.
            bool iscw = (angle < MathConstants.PI ? m_IsShortArc : !m_IsShortArc);

            // Create the required geometry
            ITerminal ec = new FloatingTerminal(cirend);

            return(new ArcGeometry(bestCircle, start, ec, iscw));
        }
Ejemplo n.º 22
0
        public static NFTask GetGeometry()
        {
            Msg("[Nesting Factory] Starting collect geometry...");

            ICollection <Area> EO       = Doc.GetAreas();
            IEnumerator <Area> GeomEnum = EO.GetEnumerator();

            GeomEnum.MoveNext();

            NFTask task = new NFTask();

            for (int area_num = 0; area_num < EO.Count; area_num++)
            {
                Area area = GeomEnum.Current;
                GeomEnum.MoveNext();
                Rectangle BoundBox = area.BoundRect;
                double    bound_x  = BoundBox.Left;
                double    bound_y  = BoundBox.Top;


                NFItem item = new NFItem(area.ObjectId.ToString());

                for (int num_contour = 0; num_contour < area.ContourCount; num_contour++)
                {
                    Contour   contour = area.GetContour(num_contour);
                    NFContour cont    = new NFContour();

                    for (int num_segment = 0; num_segment < contour.SegmentCount; num_segment++)
                    {
                        ContourSegment csegment = contour.GetSegment(num_segment);

                        switch (csegment.GeometryType)
                        {
                        case ObjectGeometryType.Line:
                            LineGeometry linegeom = csegment.Geometry as LineGeometry;
                            cont.AddPoint(new NFPoint(linegeom.X1 - bound_x, bound_y - linegeom.Y1, 0));
                            cont.AddPoint(new NFPoint(linegeom.X2 - bound_x, bound_y - linegeom.Y2, 0));
                            break;

                        /*case ObjectGeometryType.Polyline:
                         *
                         *  PolylineGeometry polygeom = csegment.Geometry as PolylineGeometry;
                         *  CircleArcGeometry[] cArcs = polygeom.GetCircleArcApproximation(2);
                         *
                         *  for (int i = 0; i < cArcs.GetLength(0); i++)
                         *  {
                         *      cArcToDoubles(cArcs[i], ref cont, BoundBox);
                         *  }
                         *  break;*/
                        case ObjectGeometryType.CircleArc:

                            CircleArcGeometry cgeom = csegment.Geometry as CircleArcGeometry;
                            cArcToDoubles(cgeom, ref cont, BoundBox, csegment.IsCounterclockwise);

                            break;

                        case ObjectGeometryType.Circle:
                            CircleGeometry cirgeom = csegment.Geometry as CircleGeometry;
                            cont.AddPoint(new NFPoint(cirgeom.CenterX + cirgeom.Radius - bound_x, bound_y - cirgeom.CenterY, 1));
                            cont.AddPoint(new NFPoint(cirgeom.CenterX - cirgeom.Radius - bound_x, bound_y - cirgeom.CenterY, 1));
                            break;

                        default:
                            PolylineGeometry polygeom = csegment.Geometry as PolylineGeometry;
                            int v_count = polygeom.Count;
                            for (int i = 0; i < v_count; i++)
                            {
                                if (v_count < 50 || i % (csegment.GeometryType == ObjectGeometryType.Ellipse ? 5 : 1) == 0 || i == v_count)
                                {
                                    cont.AddPoint(new NFPoint(polygeom.GetX(i) - bound_x, bound_y - polygeom.GetY(i), 0));
                                }
                            }
                            break;
                        }
                    }
                    item.AddContour(cont);
                }
                task.AddItem(item);
            }
            Msg("[Nesting Factory] Geometry collected");
            return(task);
        }
Ejemplo n.º 23
0
        private void listView1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems != null && listView1.SelectedItems.Count > 0)
            {
                string areaName = listView1.SelectedItems[0].Text;
                num  = listView1.SelectedItems[0].Index;
                Item = task.GetItem(num);

                //Отрисовка превьюшки детали
                Document Doc = TFlex.Application.ActiveDocument;
                select = Doc.GetObjectByName(areaName) as Area;
                TFlex.Drawing.Rectangle bound = select.BoundRect;
                double Scale = 159 / Math.Max(bound.Width, bound.Height);

                Bitmap   img   = new Bitmap(160, 160);
                Graphics graph = Graphics.FromImage(img);
                Pen      pen   = new Pen(Brushes.White);
                graph.DrawRectangle(pen, new Rectangle(0, 0, 159, 159));
                pen       = new Pen(Brushes.Black);
                pen.Width = 1;
                for (int cc = 0; cc < select.ContourCount; cc++)
                {
                    Contour cont = select.GetContour(cc);
                    for (int sc = 0; sc < cont.SegmentCount; sc++)
                    {
                        ContourSegment segm = cont.GetSegment(sc);
                        switch (segm.GeometryType)
                        {
                        case ObjectGeometryType.Line:
                            LineGeometry line = segm.Geometry as LineGeometry;
                            graph.DrawLine(pen, (float)((line.X1 - bound.Left) * Scale), (float)((bound.Top - line.Y1) * Scale), (float)((line.X2 - bound.Left) * Scale), (float)((bound.Top - line.Y2) * Scale));
                            break;

                        case ObjectGeometryType.Circle:
                            CircleGeometry circle = segm.Geometry as CircleGeometry;
                            double         radius = (circle.Radius * Scale);
                            int            xc     = (int)((circle.CenterX - bound.Left) * Scale);
                            int            yc     = (int)((bound.Top - circle.CenterY) * Scale);

                            graph.DrawEllipse(pen, new Rectangle((int)(xc - radius), (int)(yc - radius), (int)radius * 2, (int)radius * 2));
                            break;

                        case ObjectGeometryType.CircleArc:
                            CircleArcGeometry cgeom = segm.Geometry as CircleArcGeometry;
                            int xc1 = (int)((cgeom.CenterX - bound.Left) * Scale);
                            int yc1 = (int)((bound.Top - cgeom.CenterY) * Scale);
                            radius = (cgeom.Radius * Scale);
                            double[] angles = NFGetGeom.getArcAngle(cgeom, segm.IsCounterclockwise);
                            double   ang    = angles[0] * 180 / Math.PI;
                            double   ang1   = angles[1] * 180 / Math.PI - 90;
                            graph.DrawArc(pen, (float)(xc1 - radius), (float)(yc1 - radius), (float)(radius * 2), (float)(radius * 2), (float)ang1, (float)ang);
                            break;

                        default:

                            PolylineGeometry geom = segm.Geometry as PolylineGeometry;

                            if (geom != null)
                            {
                                for (int i = 1; i < geom.Count; i++)
                                {
                                    int x1 = (int)((geom.GetX(i) - bound.Left) * Scale);
                                    int y1 = (int)((bound.Top - geom.GetY(i)) * Scale);
                                    int x2 = (int)((geom.GetX(i - 1) - bound.Left) * Scale);
                                    int y2 = (int)((bound.Top - geom.GetY(i - 1)) * Scale);
                                    graph.DrawLine(pen, (float)x1, (float)y1, (float)x2, (float)y2);
                                }
                            }
                            break;
                        }
                    }
                }

                pictureBox1.Image = img;

                //Задание параметров форме

                label10.Text = "Размер квадрата детали = " + (int)(159 / Scale);
                label9.Text  = "Количество контуров: " + select.ContourCount;

                selectComboNum(ref comboBox2, Item.Rotation);

                selectComboNum(ref comboBox1, Item.Reflection);
                selectComboNum(ref comboBox1, Item.Reflection);

                textBox4.Text = Item.Count.ToString();
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Calculates intersection points.
        /// </summary>
        /// <param name="dist1">1st distance observation.</param>
        /// <param name="from1">The point the 1st distance was observed from.</param>
        /// <param name="dist2">2nd distance observation.</param>
        /// <param name="from2">The point the 2nd distance was observed from.</param>
        /// <param name="usedefault">True if the default intersection is required (the one that has the
        /// lowest bearing with respect to the 2 from points). False for the other one (if any).</param>
        /// <param name="xsect">The position of the intersection (if any).</param>
        /// <param name="xsect1">The 1st choice intersection (if any).</param>
        /// <param name="xsect2">The 2nd choice intersection (if any).</param>
        /// <returns>True if intersections were calculated. False if the distance circles
        /// don't intersect.</returns>
        internal static bool Calculate(Observation dist1, PointFeature from1, Observation dist2, PointFeature from2, bool usedefault,
                                       out IPosition xsect, out IPosition xsect1, out IPosition xsect2)
        {
            // Initialize intersection positions.
            xsect = xsect1 = xsect2 = null;

            // Get the 2 distances.
            double d1 = dist1.GetDistance(from1).Meters;
            double d2 = dist2.GetDistance(from2).Meters;

            if (d1 < Constants.TINY || d2 < Constants.TINY)
            {
                return(false);
            }

            // Form circles with radii that match the observed distances.
            ICircleGeometry circle1 = new CircleGeometry(from1, d1);
            ICircleGeometry circle2 = new CircleGeometry(from2, d2);

            // See if there is actually an intersection between the two circles.
            IPosition x1, x2;
            uint      nx = IntersectionHelper.Intersect(circle1, circle2, out x1, out x2);

            if (nx == 0)
            {
                return(false);
            }

            // If we have 2 intersections, and we need the non-default one, pick up the 2nd
            // intersection. If only 1 intersection, use that, regardless of the setting for
            // the "use default" flag.

            if (nx == 2 && !usedefault)
            {
                xsect = x2;
            }
            else
            {
                xsect = x1;
            }

            // Return if both distances are offset points.
            OffsetPoint offset1 = (dist1 as OffsetPoint);
            OffsetPoint offset2 = (dist2 as OffsetPoint);

            if (offset1 != null && offset2 != null)
            {
                xsect1 = x1;
                xsect2 = x2;
                return(true);
            }

            // Reduce observed distances to the mapping plane.
            ISpatialSystem sys = CadastralMapModel.Current.SpatialSystem;

            if (offset1 == null)
            {
                d1 = d1 * sys.GetLineScaleFactor(from1, xsect);
            }

            if (offset2 == null)
            {
                d2 = d2 * sys.GetLineScaleFactor(from2, xsect);
            }

            // And calculate the exact intersection (like above)...
            // Form circles with radii that match the observed distances.
            ICircleGeometry circle1p = new CircleGeometry(from1, d1);
            ICircleGeometry circle2p = new CircleGeometry(from2, d2);

            // See if there is still an intersection between the two circles.
            nx = IntersectionHelper.Intersect(circle1p, circle2p, out x1, out x2);
            if (nx == 0)
            {
                return(false);
            }

            // If we have 2 intersections, and we need the non-default one, pick up the 2nd
            // intersection. If only 1 intersection, use that, regardless of the setting for
            // the "use default" flag.

            if (nx == 2 && !usedefault)
            {
                xsect = x2;
            }
            else
            {
                xsect = x1;
            }

            xsect1 = x1;
            xsect2 = x2;

            return(true);
        }
 // Use this for initialization
 void Start()
 {
     geo             = new CircleGeometry(5, 32, 0, Mathf.PI * 2);
     meshFilter.mesh = geo.CreateAndGetMesh();
 }
        /// <summary>
        /// Calculates the intersection point.
        /// </summary>
        /// <param name="dir">Direction observation.</param>
        /// <param name="distance">Distance observation.</param>
        /// <param name="from">The point the distance was observed from.</param>
        /// <param name="usedefault">True if the default intersection is required (the one
        /// closer to the origin of the direction line). False for the other one (if any).</param>
        /// <param name="xsect">The position of the intersection (if any).</param>
        /// <param name="xsect1">The 1st choice intersection (if any).</param>
        /// <param name="xsect2">The 2nd choice intersection (if any).</param>
        /// <returns>True if intersections were calculated. False if the distance circles
        /// don't intersect.</returns>
        internal static bool Calculate(Direction dir, Observation distance, PointFeature from, bool usedefault,
                                       out IPosition xsect, out IPosition xsect1, out IPosition xsect2)
        {
            // Initialize intersection positions.
            xsect = xsect1 = xsect2 = null;

            // Get the distance.
            double dist = distance.GetDistance(from).Meters;

            if (dist < Constants.TINY)
            {
                return(false);
            }

            // Form circle with a radius that matches the observed distance.
            ICircleGeometry circle = new CircleGeometry(from, dist);

            // See if there is actually an intersection between the direction & the circle.
            IPosition x1, x2;
            uint      nx = dir.Intersect(circle, out x1, out x2);

            if (nx == 0)
            {
                return(false);
            }

            // If we have 2 intersections, and we need the non-default one, pick up the 2nd
            // intersection. If only 1 intersection, use that, regardless of the setting for
            // the "use default" flag.

            if (nx == 2 && !usedefault)
            {
                xsect = x2;
            }
            else
            {
                xsect = x1;
            }

            // Return if the distance is an offset point.
            OffsetPoint offset = (distance as OffsetPoint);

            if (offset != null)
            {
                xsect1 = x1;
                xsect2 = x2;
                return(true);
            }

            // Reduce observed distance to the mapping plane.
            ISpatialSystem sys = CadastralMapModel.Current.SpatialSystem;

            dist = dist * sys.GetLineScaleFactor(from, xsect);

            // And calculate the exact intersection (like above)...
            // Form circle with a radius that matches the reduced distance.
            ICircleGeometry circlep = new CircleGeometry(from, dist);

            // See if there is actually an intersection between the direction & the circle.
            nx = dir.Intersect(circlep, out x1, out x2);
            if (nx == 0)
            {
                return(false);
            }

            // If we have 2 intersections, and we need the non-default one, pick up the 2nd
            // intersection. If only 1 intersection, use that, regardless of the setting for
            // the "use default" flag.

            if (nx == 2 && !usedefault)
            {
                xsect = x2;
            }
            else
            {
                xsect = x1;
            }

            xsect1 = x1;
            xsect2 = x2;

            return(true);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Draws this object on the specified display
 /// </summary>
 /// <param name="display">The display to draw to</param>
 /// <param name="style">The drawing style</param>
 public void Render(ISpatialDisplay display, IDrawStyle style)
 {
     CircleGeometry.Render(this, display, style);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Calculates the distance from the perimeter of this circle to the specified position.
 /// </summary>
 /// <param name="point"></param>
 /// <returns></returns>
 public ILength Distance(IPosition point)
 {
     return(CircleGeometry.Distance(this, point));
 }