public void Create()
 {
     var line = new Line2D(Point.Zero, Point.One, Color.Red);
     renderer.Add(line);
     Assert.AreEqual(Color.Red, line.Color);
     renderer.Remove(line);
 }
Esempio n. 2
0
        public void InequalityOperator(string p1s, string p2s, string p3s, string p4s, bool expected)
        {
            var l1 = new Line2D(Point2D.Parse(p1s), Point2D.Parse(p2s));
            var l2 = new Line2D(Point2D.Parse(p3s), Point2D.Parse(p4s));

            Assert.AreEqual(expected, l1 != l2);
        }
Esempio n. 3
0
        public bool FindIntersection(Line2D other, out VectorD intersection)
        {
            /* http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
             * Now there are five cases:
             * If r × s = 0 and (q − p) × r = 0, then the two lines are collinear. If in addition, either 0 ≤ (q − p) · r ≤ r · r or 0 ≤ (p − q) · s ≤ s · s, then the two lines are overlapping.
             * If r × s = 0 and (q − p) × r = 0, but neither 0 ≤ (q − p) · r ≤ r · r nor 0 ≤ (p − q) · s ≤ s · s, then the two lines are collinear but disjoint.
             * If r × s = 0 and (q − p) × r ≠ 0, then the two lines are parallel and non-intersecting.
             * If r × s ≠ 0 and 0 ≤ t ≤ 1 and 0 ≤ u ≤ 1, the two line segments meet at the point p + t r = q + u s.
             * Otherwise, the two line segments are not parallel but do not intersect.
             */

            // line1.Start = p
            // line2.Start = q

            var r = Stop - Start;
            var s = other.Stop - other.Start;
            var startPointVector = (other.Start - Start);

            var denom = r.Cross(s); // denom = r × s

            var firstScalar = startPointVector.Cross(s) / denom; // firstScalar = t
            var secondScalar = startPointVector.Cross(r) / denom; // secondScalar = u
            intersection = Start + (firstScalar * r);
            // ReSharper disable CompareOfFloatsByEqualityOperator
            return denom != 0d && firstScalar >= 0d && firstScalar <= 1d && secondScalar >= 0d && secondScalar <= 1d;
            // ReSharper restore CompareOfFloatsByEqualityOperator
        }
Esempio n. 4
0
		private static void AddRotatingLine(int num)
		{
			var line = new Line2D(Vector2D.Half, Vector2D.Half, Color.Orange);
			line.Rotation = num * 360 / 100.0f;
			line.EndPoint = line.StartPoint +
				new Vector2D(0.4f, 0).RotateAround(Vector2D.Zero, line.Rotation);
			line.Start<Rotate>();
		}
Esempio n. 5
0
		public void CreateLine()
		{
			var line = new Line2D(Vector2D.Zero, Vector2D.One, Color.Red);
			Assert.AreEqual(Vector2D.Zero, line.StartPoint);
			Assert.AreEqual(Vector2D.One, line.EndPoint);
			Assert.AreEqual(Color.Red, line.Color);
			Assert.AreEqual(2, line.Points.Count);
		}
Esempio n. 6
0
 public void CanDetermineIfLinesIntersect()
 {
     var line = new Line2D(2, 0);
     var secondLine = new Line2D(3, 1);
     var thirdLine = new Line2D(2, 3);
     Assert.IsTrue(line.IntersectsWith(secondLine));
     Assert.IsFalse(line.IntersectsWith(thirdLine));
 }
Esempio n. 7
0
 public void CanDetermineIfLinesAreParallel()
 {
     var line = new Line2D(2, 0);
     var secondLine = new Line2D(2, 3);
     var thirdLine = new Line2D(3, 1);
     Assert.IsTrue(line.IsParallelTo(secondLine));
     Assert.IsFalse(secondLine.IsParallelTo(thirdLine));
 }
Esempio n. 8
0
 public void LineAboveViewportIsHidden()
 {
     var line = new Line2D(new Vector2D(0.2f, -1.0f), new Vector2D(0.6f, -1.5f), Color.Red);
     line.Clip(Rectangle.One);
     Assert.AreEqual(new Vector2D(0.2f, -1.0f), line.StartPoint);
     Assert.AreEqual(new Vector2D(0.6f, -1.5f), line.EndPoint);
     Assert.IsFalse(line.IsVisible);
 }
 public void Render()
 {
     var line = new Line2D(Point.Zero, Point.One, Color.Red);
     renderer.Add(line);
     line.EndPosition = Point.Half;
     renderer.Run(null);
     Assert.AreEqual(2, resolver.NumberOfVerticesDrawn);
     renderer.RemoveAll();
 }
Esempio n. 10
0
        public void Constructor()
        {
            var p1 = new Point2D(0, 0);
            var p2 = new Point2D(1, 1);
            var line = new Line2D(p1, p2);

            AssertGeometry.AreEqual(p1, line.StartPoint);
            AssertGeometry.AreEqual(p2, line.EndPoint);
        }
Esempio n. 11
0
        public void LineDirection(string p1s, string p2s, string exs)
        {
            var p1 = Point2D.Parse(p1s);
            var p2 = Point2D.Parse(p2s);
            var ex = Vector2D.Parse(exs);
            var line = new Line2D(p1, p2);

            AssertGeometry.AreEqual(ex, line.Direction);
        }
Esempio n. 12
0
        public void CanDetermineIfPointIsOnLine()
        {
            var line = new Line2D(1, 0);
            Assert.IsTrue(line.IsPointOnLine(new Point2D(1, 1)));
            Assert.IsFalse(line.IsPointOnLine(new Point2D(2, 1)));

            var secondLine = new Line2D(2, 3);
            Assert.IsTrue(secondLine.IsPointOnLine(new Point2D(4, 11)));
            Assert.IsFalse(secondLine.IsPointOnLine(new Point2D(3, 2)));
        }
Esempio n. 13
0
        public void CanFindIntersectionPoint()
        {
            // 0.5x - 1
            var firstLine = new Line2D(0.5, -1);
            // -2x - 6
            var secondLine = new Line2D(-2, -6);

            var intersectionPoint = firstLine.GetIntersectionPoint(secondLine);
            Assert.AreEqual(-2, intersectionPoint.X);
            Assert.AreEqual(-2, intersectionPoint.Y);
        }
Esempio n. 14
0
 public void DrawInPixelSpace(Type resolver)
 {
     var line = new Line2D(Point.Zero, Point.Zero, Color.Red);
     Start(resolver, (Renderer r, Window window) =>
     {
         window.BackgroundColor = Color.Black;
         r.Add(line);
     }, (ScreenSpace screen) =>
     {
         line.StartPosition = screen.FromPixelSpace(Point.Zero);
         line.EndPosition = screen.FromPixelSpace(new Point(800, 600));
     });
 }
Esempio n. 15
0
 public static void CreateCam(double angle)
 {
     double dRad = angle*dPi/180;
     double dDSin1 = iCircle1Rad*Math.Sin(dRad);
     double dDCos1 = iCircle1Rad*Math.Cos(dRad);
     double dDSin2 = iCircle2Rad*Math.Sin(dRad);
     double dDCos2 = iCircle2Rad*Math.Cos(dRad);
     double dCSin = iCircleDist*Math.Sin(dRad);
     double dCCos = iCircleDist*Math.Cos(dRad);
     oCurrentSketch = oPartBody.Sketches.Add ( oPlaneYZ );
     Factory2D oFactory2D = oCurrentSketch.OpenEdition();
     double dRad1 = dRad - dPi/4;
     double dRad2 = dRad + dPi/4;
     oCurrentLine1 = oFactory2D.CreateLine( iCenterX - dDSin1, iCenterY + dDCos1, iCenterX + dCCos + dDSin2,  iCenterY - dCSin + dDCos2);
     oCurrentLine2 = oFactory2D.CreateLine( iCenterX + dDSin1, iCenterY - dDCos1, iCenterX + dCCos - dDSin2,  iCenterY - dCSin - dDCos2 );
     oCurrentCircle1 = oFactory2D.CreateCircle( iCenterX, iCenterY, iCircle1Rad,   dRad2,    dRad1);
     oCurrentCircle2 = oFactory2D.CreateCircle( iCenterX + dCCos, iCenterY + dCSin, iCircle2Rad,   dRad1,    dRad2);
     Reference oRefLine1 = oPart.CreateReferenceFromObject(oCurrentLine1);
     Reference oRefCircle1 = oPart.CreateReferenceFromObject(oCurrentCircle1);
     Reference oRefLine2 = oPart.CreateReferenceFromObject(oCurrentLine2);
     Reference oRefCircle2 = oPart.CreateReferenceFromObject(oCurrentCircle2);
     Reference oRefLine1StartPt = oPart.CreateReferenceFromObject(oCurrentLine1.StartPoint);
     Reference oRefLine1EndPt = oPart.CreateReferenceFromObject(oCurrentLine1.EndPoint);
     Reference oRefLine2StartPt = oPart.CreateReferenceFromObject(oCurrentLine2.StartPoint);
     Reference oRefLine2EndPt = oPart.CreateReferenceFromObject(oCurrentLine2.EndPoint);
     Reference oRefCircle1StartPt = oPart.CreateReferenceFromObject(oCurrentCircle1.StartPoint);
     Reference oRefCircle1EndPt = oPart.CreateReferenceFromObject(oCurrentCircle1.EndPoint);
     Reference oRefCircle2StartPt = oPart.CreateReferenceFromObject(oCurrentCircle2.StartPoint);
     Reference oRefCircle2EndPt = oPart.CreateReferenceFromObject(oCurrentCircle2.EndPoint);
     Constraints oConstraints = oCurrentSketch.Constraints;
     Constraint oConstraint = oConstraints.AddMonoEltCst(CatConstraintType.catCstTypeReference, oRefCircle1);
     oConstraint = oConstraints.AddMonoEltCst(CatConstraintType.catCstTypeReference, oRefCircle2);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeTangency, oRefLine1, oRefCircle1);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeTangency, oRefCircle2, oRefLine1);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeOn, oRefCircle1StartPt, oRefLine1StartPt);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeOn, oRefCircle2EndPt, oRefLine1EndPt);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeTangency, oRefLine2, oRefCircle1);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeTangency, oRefLine2, oRefCircle2);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeOn, oRefCircle1EndPt, oRefLine2StartPt);
     oConstraint = oConstraints.AddBiEltCst(CatConstraintType.catCstTypeOn, oRefCircle2StartPt, oRefLine2EndPt);
     oCurrentSketch.CloseEdition();
     ShapeFactory oShapeFactory = (ShapeFactory)oPart.ShapeFactory;
     Pad oPad = oShapeFactory.AddNewPad ( oCurrentSketch,  iCamThickness + iCurrentLevel );
     oPad.SecondLimit.Dimension.Value = iCurrentLevel*-1;
 }
Esempio n. 16
0
        public void LineToIgnoreEndPoints(string ptest, string exs)
        {
            var line = Line2D.Parse("1,-1", "3,-1");
            var point = Point2D.Parse(ptest);
            var expPoint = Point2D.Parse(exs);
            var expLine = new Line2D(expPoint, point);

            Assert.AreEqual(expLine, line.LineTo(point, false));
        }
Esempio n. 17
0
 public void EqualityComparisonFalseAgainstNull()
 {
     var line = new Line2D(new Point2D(), new Point2D(1,1) );
     Assert.IsFalse(line.Equals(null));
 }
Esempio n. 18
0
    // This finds the cut coordinates and splits the other poly with inner vertices
    private static void SplitOuterWithInner(LinkedListNode <EarClipVertex> start, EarClipPolygon p)
    {
        LinkedListNode <EarClipVertex> insertbefore = null;
        float    foundu   = float.MaxValue;
        Vector2D foundpos = new Vector2D();

        // Create a line from start that goes beyond the right most vertex of p
        LinkedListNode <EarClipVertex> pr = FindRightMostVertex(p);
        float  startx       = start.Value.Position.x;
        float  endx         = pr.Value.Position.x + 10.0f;
        Line2D starttoright = new Line2D(start.Value.Position, new Vector2D(endx, start.Value.Position.y));

        // Calculate a small bonus (0.1 mappixel)
        float bonus = starttoright.GetNearestOnLine(new Vector2D(start.Value.Position.x + 0.1f, start.Value.Position.y));

        // Go for all lines in the outer polygon
        LinkedListNode <EarClipVertex> v1 = p.Last;
        LinkedListNode <EarClipVertex> v2 = p.First;

        while (v2 != null)
        {
            // Check if the line goes between startx and endx
            if ((v1.Value.Position.x > startx || v2.Value.Position.x > startx) &&
                (v1.Value.Position.x < endx || v2.Value.Position.x < endx))
            {
                // Find intersection
                Line2D pl = new Line2D(v1.Value.Position, v2.Value.Position);
                float  u, ul;
                pl.GetIntersection(starttoright, out u, out ul);
                if (float.IsNaN(u))
                {
                    // We have found a line that is perfectly horizontal
                    // (parallel to the cut scan line) Check if the line
                    // is overlapping the cut scan line.
                    if (v1.Value.Position.y == start.Value.Position.y)
                    {
                        // This is an exceptional situation which causes a bit of a problem, because
                        // this could be a previously made cut, which overlaps another line from the
                        // same cut and we have to determine which of the two we will join with. If we
                        // pick the wrong one, the polygon is no longer valid and triangulation will fail.

                        // Calculate distance of each vertex in units
                        u  = starttoright.GetNearestOnLine(v1.Value.Position);
                        ul = starttoright.GetNearestOnLine(v2.Value.Position);

                        // Rule out vertices before the scan line
                        if (u < 0.0f)
                        {
                            u = float.MaxValue;
                        }
                        if (ul < 0.0f)
                        {
                            ul = float.MaxValue;
                        }

                        float    insert_u = Math.Min(u, ul);
                        Vector2D inserpos = starttoright.GetCoordinatesAt(insert_u);

                        // Check in which direction the line goes.
                        if (v1.Value.Position.x > v2.Value.Position.x)
                        {
                            // The line goes from right to left (towards our start point)
                            // so we must always insert our cut after this line.

                            // If the next line goes up, we consider this a better candidate than
                            // a horizontal line that goes from left to right (the other cut line)
                            // so we give it a small bonus.
                            LinkedListNode <EarClipVertex> v3 = v2.Next ?? v2.List.First;
                            if (v3.Value.Position.y < v2.Value.Position.y)
                            {
                                insert_u -= bonus;
                            }

                            // Remember this when it is a closer match
                            if (insert_u <= foundu)
                            {
                                insertbefore = v2.Next ?? v2.List.First;
                                foundu       = insert_u;
                                foundpos     = inserpos;
                            }
                        }
                        else
                        {
                            // The line goes from left to right (away from our start point)
                            // so we must always insert our cut before this line.

                            // If the previous line goes down, we consider this a better candidate than
                            // a horizontal line that goes from right to left (the other cut line)
                            // so we give it a small bonus.
                            LinkedListNode <EarClipVertex> v3 = v1.Previous ?? v1.List.Last;
                            if (v3.Value.Position.y > v1.Value.Position.y)
                            {
                                insert_u -= bonus;
                            }

                            // Remember this when it is a closer match
                            if (insert_u <= foundu)
                            {
                                insertbefore = v2;
                                foundu       = insert_u;
                                foundpos     = inserpos;
                            }
                        }
                    }
                }
                // Found a closer match?
                else if ((ul >= 0.0f) && (ul <= 1.0f) && (u > 0.0f) && (u <= foundu))
                {
                    // Found a closer intersection
                    insertbefore = v2;
                    foundu       = u;
                    foundpos     = starttoright.GetCoordinatesAt(u);
                }
            }

            // Next
            v1 = v2;
            v2 = v2.Next;
        }

        // Found anything?
        if (insertbefore != null)
        {
            Sidedef sd = (insertbefore.Previous == null) ? insertbefore.List.Last.Value.Sidedef : insertbefore.Previous.Value.Sidedef;

            // Find the position where we have to split the outer polygon
            EarClipVertex split = new EarClipVertex(foundpos, null);

            // Insert manual split vertices
            p.AddBefore(insertbefore, new EarClipVertex(split, sd));

            // Start inserting from the start (do I make sense this time?)
            v1 = start;
            do
            {
                // Insert inner polygon vertex
                p.AddBefore(insertbefore, new EarClipVertex(v1.Value));
                v1 = (v1.Next ?? v1.List.First);
            } while (v1 != start);

            // Insert manual split vertices
            p.AddBefore(insertbefore, new EarClipVertex(start.Value, sd));
            if (split.Position != insertbefore.Value.Position)
            {
                p.AddBefore(insertbefore, new EarClipVertex(split, sd));
            }
        }
    }
Esempio n. 19
0
		public void MoveLineViaItsEndPoints()
		{
			var line = new Line2D(Vector2D.Zero, Vector2D.Zero, Color.Red)
			{
				StartPoint = Vector2D.Half,
				EndPoint = Vector2D.One
			};
			Assert.AreEqual(Vector2D.Half, line.StartPoint);
			Assert.AreEqual(Vector2D.One, line.EndPoint);
		}
Esempio n. 20
0
        // When select button is pressed
        protected override void OnSelectBegin()
        {
            base.OnSelectBegin();
            if (mode != ModifyMode.None)
            {
                return;
            }

            // Check what grip the mouse is over
            switch (CheckMouseGrip())
            {
            // Drag main rectangle
            case Grip.Main:
                dragoffset = -mousemappos - offset;
                mode       = ModifyMode.Dragging;
                EnableAutoPanning();
                autopanning = true;
                break;

            // Scale
            case Grip.SizeH:
                // The resize vector is a unit vector in the direction of the resize.
                // We multiply this with the sign of the current size, because the
                // corners may be reversed when the selection is flipped.
                resizevector = corners[1] - corners[0];
                resizevector = resizevector.GetNormal() * Math.Sign(scale.x);

                // Make the resize axis. This is a line with the length and direction
                // of basesize used to calculate the resize percentage.
                resizeaxis = new Line2D(corners[0], corners[0] + resizevector * texture.ScaledWidth / Math.Abs(sectorinfo[0].scale.x));

                // Original axis filter
                resizefilter = new Vector2D(1.0f, 0.0f);

                mode = ModifyMode.Resizing;
                break;

            // Scale
            case Grip.SizeV:
                // See description above
                resizevector = corners[2] - corners[1];
                resizevector = resizevector.GetNormal() * Math.Sign(scale.y);
                resizeaxis   = new Line2D(corners[1], corners[1] + resizevector * texture.ScaledHeight / Math.Abs(sectorinfo[0].scale.y));
                resizefilter = new Vector2D(0.0f, 1.0f);
                mode         = ModifyMode.Resizing;
                break;

            // Rotate
            case Grip.RotateRT:
                rotationoffset = Angle2D.PIHALF;
                if (Math.Sign(scale.x * sectorinfo[0].scale.x) < 0)
                {
                    rotationoffset += Angle2D.PI;
                }
                rotationcenter = corners[0];
                mode           = ModifyMode.Rotating;
                break;

            // Rotate
            case Grip.RotateLB:
                rotationoffset = 0f;
                if (Math.Sign(scale.y * sectorinfo[0].scale.y) < 0)
                {
                    rotationoffset += Angle2D.PI;
                }
                rotationcenter = corners[0];
                mode           = ModifyMode.Rotating;
                break;

            // Outside the selection?
            default:
                // Accept and be done with it
                General.Editing.AcceptMode();
                break;
            }
        }
Esempio n. 21
0
    // This checks if a given ear is a valid (no intersections from reflex vertices)
    private static bool CheckValidEar(EarClipVertex[] t, LinkedList <EarClipVertex> reflexes)
    {
        //mxd
        Vector2D pos0 = t[0].Position;
        Vector2D pos1 = t[1].Position;
        Vector2D pos2 = t[2].Position;
        Vector2D vpos;
        LinkedListNode <EarClipVertex> p;

        // Go for all reflex vertices
        foreach (EarClipVertex rv in reflexes)
        {
            // Not one of the triangle corners?
            if ((rv.Position != pos0) && (rv.Position != pos1) && (rv.Position != pos2))
            {
                // Return false on intersection

                // This checks if a point is inside a triangle
                // When the point is on an edge of the triangle, it depends on the lines
                // adjacent to the point if it is considered inside or not
                // NOTE: vertices in t must be in clockwise order!

                // If the triangle has no area, there can never be a point inside
                if (TriangleHasArea(t))
                {
                    //mxd
                    pos0 = t[0].Position;
                    pos1 = t[1].Position;
                    pos2 = t[2].Position;
                    p    = rv.MainListNode;
                    vpos = p.Value.Position;

                    //mxd. Check bounds first...
                    if (vpos.x < Math.Min(pos0.x, Math.Min(pos1.x, pos2.x)) ||
                        vpos.x > Math.Max(pos0.x, Math.Max(pos1.x, pos2.x)) ||
                        vpos.y < Math.Min(pos0.y, Math.Min(pos1.y, pos2.y)) ||
                        vpos.y > Math.Max(pos0.y, Math.Max(pos1.y, pos2.y)))
                    {
                        continue;
                    }

                    float lineside01 = Line2D.GetSideOfLine(pos0, pos1, vpos);
                    float lineside12 = Line2D.GetSideOfLine(pos1, pos2, vpos);
                    float lineside20 = Line2D.GetSideOfLine(pos2, pos0, vpos);
                    float u_on_line  = 0.5f;

                    // If point p is on the line of an edge, find out where on the edge segment p is.
                    if (lineside01 == 0.0f)
                    {
                        u_on_line = Line2D.GetNearestOnLine(pos0, pos1, vpos);
                    }
                    else if (lineside12 == 0.0f)
                    {
                        u_on_line = Line2D.GetNearestOnLine(pos1, pos2, vpos);
                    }
                    else if (lineside20 == 0.0f)
                    {
                        u_on_line = Line2D.GetNearestOnLine(pos2, pos0, vpos);
                    }

                    // If any of the lineside results are 0 then that means the point p lies on that edge and we
                    // need to test if the lines adjacent to the point p are in the triangle or not.
                    // If the lines are intersecting the triangle, we also consider the point inside.
                    if (lineside01 == 0.0f || lineside12 == 0.0f || lineside20 == 0.0f)
                    {
                        // When the point p is outside the edge segment, then it is not inside the triangle
                        if (u_on_line < 0.0f || u_on_line > 1.0f)
                        {
                            continue;
                        }

                        // Point p is on an edge segment. We'll have to decide by it's lines if we call it inside or outside the triangle.
                        LinkedListNode <EarClipVertex> p1 = p.Previous ?? p.List.Last;
                        if (LineInsideTriangle(t, vpos, p1.Value.Position))
                        {
                            return(false);
                        }

                        LinkedListNode <EarClipVertex> p2 = p.Next ?? p.List.First;
                        if (LineInsideTriangle(t, vpos, p2.Value.Position))
                        {
                            return(false);
                        }

                        continue;
                    }

                    if (lineside01 < 0.0f && lineside12 < 0.0f && lineside20 < 0.0f)
                    {
                        return(false);
                    }
                }
            }
        }

        // Valid ear!
        return(true);
    }
 private bool IsRectangleWidth(Line2D source, Rectangle2D rec)
 {
     return((source.Length - rec.Top.Length).AreEqual(0) || (source.Length - rec.Left.Length).AreEqual(0));
 }
Esempio n. 23
0
 public bool Equals(Line2D other)
 {
     return Start.Equals(other.Start) && Stop.Equals(other.Stop);
 }
Esempio n. 24
0
 /// <summary>
 /// Recalibrates the <see cref="Line2D"/> field.
 /// </summary>
 private void SetLine2D()
 {
     _line = Line2D.FromPoints(Start, End);
 }
Esempio n. 25
0
 public OverlappingLineLineSegmentException(LineSegment2D lineSegment, Line2D line, string msg = "")
     : base(msg)
 {
     LineSegment = lineSegment;
     Line        = line;
 }
Esempio n. 26
0
 /// <summary>
 /// Returns whether a <see cref="Line2D"/> is intersecting with this segment.
 /// </summary>
 /// <param name="other">The other <see cref="Line"/></param>
 /// <returns></returns>
 public bool IsIntersectingWith(Line2D other)
 {
     return(GetIntersectionWith(other) != null);
 }
Esempio n. 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LineSegment2D"/> class.
 /// </summary>
 /// <param name="start">The starting point</param>
 /// <param name="direction">The direction of the line</param>
 /// <param name="length">The length of the line</param>
 public LineSegment2D(Vector2 start, Vector2 direction, float length)
 {
     this._start = start;
     this._end   = start + direction.normalized * length;
     _line       = Line2D.FromPoints(_start, _end);
 }
Esempio n. 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LineSegment2D"/> class.
 /// </summary>
 ///
 /// <param name="start">Segment's start point.</param>
 /// <param name="end">Segment's end point.</param>
 ///
 /// <exception cref="ArgumentException">Thrown if the two points are the same.</exception>
 ///
 public LineSegment2D(Vector2 start, Vector2 end)
 {
     _line       = Line2D.FromPoints(start, end);
     this._start = start;
     this._end   = end;
 }
Esempio n. 29
0
        //Returns the tile point that contains a certain position (x,y) on the surface
        //Using Surface's technique for information
        public Point GetPositionTile(float x, float y, ShiftModes shiftApplied)
        {
            Point tile = new Point(0, 0);            //holds the result

            ShiftModes shiftm = shiftApplied;

            //detect shifting from technique
            if (shiftApplied == ShiftModes.AutoDetect)
            {
                shiftm = this.SurfaceTechnique.DetectShiftMode();
                if (shiftm == ShiftModes.Both)
                {
                    throw new ExceptionSurface("A horizontal and a vertical shift were both found in this surface's technique. Function GetPositionHeight cannot compute surfaces with a technique that uses shifts both horisontal and vertical! Please use only one kind of shift.");
                }
            }


            //different algortitms for different shift modes, although somehow analogues
            if (shiftm == ShiftModes.None)
            {
                //NO SHIFT mode (fast computing)

                tile.X = (int)Math.Floor(x / this.SurfaceTechnique.TileSize.Width);               //the column this point is in
                tile.Y = (int)Math.Floor(y / this.SurfaceTechnique.TileSize.Height);              //the row this point is in
            }
            else if (shiftm == ShiftModes.Horizontal)
            {
                //HORIZONTAL SHIFT mode

                tile.Y = (int)Math.Floor(y / this.SurfaceTechnique.TileSize.Height);               //the row this point is in

                //lower/upper points line (projection on lower/upper points line of this tile line):
                int tileXLower, tileXUpper;                //column of the tile in which the lower/upper projection of the point is located
                tileXLower = this.GetTileForProjectedX(tile.Y, x);
                tileXUpper = this.GetTileForProjectedX(tile.Y + 1, x);

                if (tileXLower == tileXUpper)                 //it is clearly in this tile
                {
                    tile.X = tileXLower;
                }
                else                                                                                               //could be in either of these two or between them
                {
                    Vector2 pLower, pUpper;                                                                        //keep the positions of each couple of points that separate each two tiles in which the point might be
                    bool    found = false;                                                                         //changes to true when the tile is found

                    for (int i = Math.Min(tileXLower, tileXUpper) + 1; i <= Math.Max(tileXLower, tileXUpper); i++) //verify (agains the point) each line in between two consecutive tiles from the lowest possible tile to the highest one to see where the point is
                    {
                        pLower = this.GetPointRealCoordinatesXY(i, tile.Y, true);
                        pUpper = this.GetPointRealCoordinatesXY(i, tile.Y + 1, true);

                        PointF pInter = Line2D.Intersection(Line2D.FromTwoPoints(pUpper.X, pUpper.Y, pLower.X, pLower.Y), new Line2D(x, y, 0, 1));                      //gets the intersection between the determination line (the line between these two tiles) and the projection line of the point on OX

                        //the two cases when the point is to the left of the determination line (the line that separates the two tiles) which means the point belongs to the left tile -> i-1;
                        if (pUpper.X > pLower.X)
                        {
                            if (y > pInter.Y)
                            {
                                tile.X = i - 1;
                                found  = true;
                                break;
                            }
                        }
                        if (pUpper.X < pLower.X)
                        {
                            if (y < pInter.Y)
                            {
                                tile.X = i - 1;
                                found  = true;
                                break;
                            }
                        }
                    }

                    if (!found)
                    {
                        tile.X = Math.Max(tileXLower, tileXUpper);                            //is no tile is found in the left of each line that separates two lines (the determination lines) then the point is surely in the mostright tile from the series of tiles found
                    }
                }
            }
            else if (shiftm == ShiftModes.Vertical)
            {
                //VERTICAL SHIFT mode

                // !!! NEEDS DONE FOR VERTICAL SHIFT AS WELL !!!
            }

            return(tile);
        }
        //mxd. This moves the label so it stays on screen and offsets it vertically so it doesn't overlap the line
        public virtual void Move(Vector2D start, Vector2D end)
        {
            // Store before making any adjustments to start/end...
            this.start = start;
            this.end   = end;

            // Update text label
            UpdateText();

            // Check if start/end point is on screen...
            Vector2D   lt           = General.Map.Renderer2D.DisplayToMap(new Vector2D(0.0f, General.Interface.Display.Size.Height));
            Vector2D   rb           = General.Map.Renderer2D.DisplayToMap(new Vector2D(General.Interface.Display.Size.Width, 0.0f));
            RectangleF viewport     = new RectangleF((float)lt.x, (float)lt.y, (float)(rb.x - lt.x), (float)(rb.y - lt.y));
            bool       startvisible = viewport.Contains((float)start.x, (float)start.y);
            bool       endvisible   = viewport.Contains((float)end.x, (float)end.y);

            // Do this only when one point is visible, an the other isn't
            if ((!startvisible && endvisible) || (startvisible && !endvisible))
            {
                Line2D   drawnline     = new Line2D(start, end);
                Line2D[] viewportsides = new[] {
                    new Line2D(lt, rb.x, lt.y),                     // top
                    new Line2D(lt.x, rb.y, rb.x, rb.y),             // bottom
                    new Line2D(lt, lt.x, rb.y),                     // left
                    new Line2D(rb.x, lt.y, rb.x, rb.y),             // right
                };

                foreach (Line2D side in viewportsides)
                {
                    // Modify the start point so it stays on screen
                    double u;
                    if (!startvisible && side.GetIntersection(drawnline, out u))
                    {
                        start = drawnline.GetCoordinatesAt(u);
                        break;
                    }

                    // Modify the end point so it stays on screen
                    if (!endvisible && side.GetIntersection(drawnline, out u))
                    {
                        end = drawnline.GetCoordinatesAt(u);
                        break;
                    }
                }
            }

            // Update label position
            if (offsetposition)
            {
                Vector2D perpendicular = (end - start).GetPerpendicular();
                double   angle         = perpendicular.GetAngle();
                SizeF    textsize      = General.Interface.MeasureString(label.Text, label.Font);
                double   offset        = textsize.Width * Math.Abs(Math.Sin(angle)) + textsize.Height * Math.Abs(Math.Cos(angle));
                perpendicular = perpendicular.GetNormal().GetScaled(offset / 2.0f / General.Map.Renderer2D.Scale);
                start        += perpendicular;
                end          += perpendicular;
            }

            // Apply changes
            Vector2D delta = end - start;

            label.Location = new Vector2D(start.x + delta.x * 0.5f, start.y + delta.y * 0.5f);
        }
Esempio n. 31
0
 internal static HandleRef getCPtr(Line2D obj) {
   return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Esempio n. 32
0
        // This picks an object from the scene
        public VisualPickResult PickObject(Vector3D from, Vector3D to)
        {
            VisualPickResult result = new VisualPickResult();
            Line2D           ray2d  = new Line2D(from, to);
            Vector3D         delta  = to - from;

            // Setup no result
            result.picked = null;
            result.hitpos = new Vector3D();
            result.u_ray  = 1.0f;

            // Find all blocks we are intersecting
            List <VisualBlockEntry> blocks = blockmap.GetLineBlocks(from, to);

            // Make collections
            Dictionary <Linedef, Linedef>     lines     = new Dictionary <Linedef, Linedef>(blocks.Count * 10);
            Dictionary <Sector, VisualSector> sectors   = new Dictionary <Sector, VisualSector>(blocks.Count * 10);
            List <IVisualPickable>            pickables = new List <IVisualPickable>(blocks.Count * 10);

            // Add geometry from the camera sector
            if ((General.Map.VisualCamera.Sector != null) && allsectors.ContainsKey(General.Map.VisualCamera.Sector))
            {
                VisualSector vs = allsectors[General.Map.VisualCamera.Sector];
                sectors.Add(General.Map.VisualCamera.Sector, vs);
                foreach (VisualGeometry g in vs.FixedGeometry)
                {
                    pickables.Add(g);
                }
            }

            // Go for all lines to see which ones we intersect
            // We will collect geometry from the sectors and sidedefs
            foreach (VisualBlockEntry b in blocks)
            {
                foreach (Linedef ld in b.Lines)
                {
                    // Make sure we don't test a line twice
                    if (!lines.ContainsKey(ld))
                    {
                        lines.Add(ld, ld);

                        // Intersecting?
                        float u;
                        if (ld.Line.GetIntersection(ray2d, out u))
                        {
                            // Check on which side we are
                            float side = ld.SideOfLine(ray2d.v1);

                            // Calculate intersection point
                            Vector3D intersect = from + delta * u;

                            // We must add the sectors of both sides of the line
                            // If we wouldn't, then aiming at a sector that is just within range
                            // could result in an incorrect hit (because the far line of the
                            // sector may not be included in this loop)
                            if (ld.Front != null)
                            {
                                // Find the visualsector
                                if (allsectors.ContainsKey(ld.Front.Sector))
                                {
                                    VisualSector vs = allsectors[ld.Front.Sector];

                                    // Add sector if not already added
                                    if (!sectors.ContainsKey(ld.Front.Sector))
                                    {
                                        sectors.Add(ld.Front.Sector, vs);
                                        foreach (VisualGeometry g in vs.FixedGeometry)
                                        {
                                            // Must have content
                                            if (g.Triangles > 0)
                                            {
                                                pickables.Add(g);
                                            }
                                        }
                                    }

                                    // Add sidedef if on the front side
                                    if (side < 0.0f)
                                    {
                                        List <VisualGeometry> sidedefgeo = vs.GetSidedefGeometry(ld.Front);
                                        foreach (VisualGeometry g in sidedefgeo)
                                        {
                                            // Must have content
                                            if (g.Triangles > 0)
                                            {
                                                g.SetPickResults(intersect, u);
                                                pickables.Add(g);
                                            }
                                        }
                                    }
                                }
                            }

                            // Add back side also
                            if (ld.Back != null)
                            {
                                // Find the visualsector
                                if (allsectors.ContainsKey(ld.Back.Sector))
                                {
                                    VisualSector vs = allsectors[ld.Back.Sector];

                                    // Add sector if not already added
                                    if (!sectors.ContainsKey(ld.Back.Sector))
                                    {
                                        sectors.Add(ld.Back.Sector, vs);
                                        foreach (VisualGeometry g in vs.FixedGeometry)
                                        {
                                            // Must have content
                                            if (g.Triangles > 0)
                                            {
                                                pickables.Add(g);
                                            }
                                        }
                                    }

                                    // Add sidedef if on the front side
                                    if (side > 0.0f)
                                    {
                                        List <VisualGeometry> sidedefgeo = vs.GetSidedefGeometry(ld.Back);
                                        foreach (VisualGeometry g in sidedefgeo)
                                        {
                                            // Must have content
                                            if (g.Triangles > 0)
                                            {
                                                g.SetPickResults(intersect, u);
                                                pickables.Add(g);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Add all the visible things
            foreach (VisualThing vt in visiblethings)
            {
                pickables.Add(vt);
            }

            // Now we have a list of potential geometry that lies along the trace line.
            // We still don't know what geometry actually hits, but we ruled out that which doesn't get even close.
            // This is still too much for accurate intersection testing, so we do a fast reject pass first.
            Vector3D direction = to - from;

            direction = direction.GetNormal();
            List <IVisualPickable> potentialpicks = new List <IVisualPickable>(pickables.Count);

            foreach (IVisualPickable p in pickables)
            {
                if (p.PickFastReject(from, to, direction))
                {
                    potentialpicks.Add(p);
                }
            }

            // Now we do an accurate intersection test for all resulting geometry
            // We keep only the closest hit!
            foreach (IVisualPickable p in potentialpicks)
            {
                float u = result.u_ray;
                if (p.PickAccurate(from, to, direction, ref u))
                {
                    // Closer than previous find?
                    if ((u > 0.0f) && (u < result.u_ray))
                    {
                        result.u_ray  = u;
                        result.picked = p;
                    }
                }
            }

            // Setup final result
            result.hitpos = from + to * result.u_ray;

            // Done
            return(result);
        }
Esempio n. 33
0
        internal void AddVertexAt(
            Vector2D mappos, bool snaptonearest, bool snaptogrid, float stitchrange,
            List <PenVertex> points = null)
        {
            PenVertex p  = new PenVertex();
            Vector2D  vm = mappos;

            float vrange = stitchrange;

            if (vrange <= 0)
            {
                vrange = BuilderPlug.Me.StitchRange;
            }

            // Snap to nearest?
            if (snaptonearest)
            {
                if (points != null)
                {
                    // Go for all drawn points
                    foreach (PenVertex v in points)
                    {
                        if (Vector2D.DistanceSq(mappos, v.pos.vec) < (vrange * vrange))
                        {
                            p.pos        = v.pos;
                            p.stitch     = true;
                            p.stitchline = true;
                            //Logger.WriteLogLine("a");//debugcrap
                            points.Add(p);
                            return;
                        }
                    }
                    if (points.Count > 0 && Vector2D.DistanceSq(vm, points[points.Count - 1].pos.vec) < 0.001f)
                    {
                        //return points[points.Count - 1];
                        return;
                    }
                }

                // Try the nearest vertex
                Vertex nv = General.Map.Map.NearestVertexSquareRange(mappos, vrange);
                if (nv != null)
                {
                    p.pos.vec    = nv.Position;
                    p.stitch     = true;
                    p.stitchline = true;
                    //Logger.WriteLogLine("b");//debugcrap
                    points.Add(p);
                    return;
                }

                // Try the nearest linedef
                Linedef nl = General.Map.Map.NearestLinedefRange(mappos, vrange);
                if (nl != null)
                {
                    // Snap to grid?
                    if (snaptogrid)
                    {
                        // Get grid intersection coordinates
                        List <Vector2D> coords = nl.GetGridIntersections();

                        // Find nearest grid intersection
                        bool     found          = false;
                        float    found_distance = float.MaxValue;
                        Vector2D found_coord    = new Vector2D();
                        foreach (Vector2D v in coords)
                        {
                            Vector2D delta = mappos - v;
                            if (delta.GetLengthSq() < found_distance)
                            {
                                found_distance = delta.GetLengthSq();
                                found_coord    = v;
                                found          = true;
                            }
                        }

                        if (found)
                        {
                            // Align to the closest grid intersection
                            p.pos.vec    = found_coord;
                            p.stitch     = true;
                            p.stitchline = true;
                            //Logger.WriteLogLine("c");//debugcrap
                            points.Add(p);
                            return;
                        }
                    }
                    else
                    {
                        // Aligned to line
                        p.pos.vec    = nl.NearestOnLine(mappos);
                        p.stitch     = true;
                        p.stitchline = true;
                        //Logger.WriteLogLine("d");//debugcrap
                        points.Add(p);
                        return;
                    }
                }
            }
            else
            {
                // Always snap to the first drawn vertex so that the user can finish a complete sector without stitching
                if (points != null && points.Count > 0)
                {
                    if (Vector2D.DistanceSq(mappos, points[0].pos.vec) < (vrange * vrange))
                    {
                        p.pos        = points[0].pos;
                        p.stitch     = true;
                        p.stitchline = false;
                        //Logger.WriteLogLine("e");//debugcrap
                        points.Add(p);
                        return;
                    }
                }
            }

            // if the mouse cursor is outside the map bondaries check if the line between the last set point and the
            // mouse cursor intersect any of the boundary lines. If it does, set the position to this intersection
            if (points != null &&
                points.Count > 0 &&
                (mappos.x < General.Map.Config.LeftBoundary || mappos.x > General.Map.Config.RightBoundary ||
                 mappos.y > General.Map.Config.TopBoundary || mappos.y < General.Map.Config.BottomBoundary))
            {
                Line2D        dline             = new Line2D(mappos, points[points.Count - 1].pos.vec);
                bool          foundintersection = false;
                float         u      = 0.0f;
                List <Line2D> blines = new List <Line2D>();

                // lines for left, top, right and bottom bondaries
                blines.Add(new Line2D(General.Map.Config.LeftBoundary, General.Map.Config.BottomBoundary, General.Map.Config.LeftBoundary, General.Map.Config.TopBoundary));
                blines.Add(new Line2D(General.Map.Config.LeftBoundary, General.Map.Config.TopBoundary, General.Map.Config.RightBoundary, General.Map.Config.TopBoundary));
                blines.Add(new Line2D(General.Map.Config.RightBoundary, General.Map.Config.TopBoundary, General.Map.Config.RightBoundary, General.Map.Config.BottomBoundary));
                blines.Add(new Line2D(General.Map.Config.RightBoundary, General.Map.Config.BottomBoundary, General.Map.Config.LeftBoundary, General.Map.Config.BottomBoundary));

                // check for intersections with boundaries
                for (int i = 0; i < blines.Count; i++)
                {
                    if (!foundintersection)
                    {
                        // only check for intersection if the last set point is not on the
                        // line we are checking against
                        if (blines[i].GetSideOfLine(points[points.Count - 1].pos.vec) != 0.0f)
                        {
                            foundintersection = blines[i].GetIntersection(dline, out u);
                        }
                    }
                }

                // if there was no intersection set the position to the last set point
                if (!foundintersection)
                {
                    vm = points[points.Count - 1].pos.vec;
                }
                else
                {
                    vm = dline.GetCoordinatesAt(u);
                }
            }


            // Snap to grid?
            if (snaptogrid)
            {
                // Aligned to grid
                p.pos.vec = General.Map.Grid.SnappedToGrid(vm);

                // special handling
                if (p.pos.vec.x > General.Map.Config.RightBoundary)
                {
                    p.pos.vec.x = General.Map.Config.RightBoundary;
                }
                if (p.pos.vec.y < General.Map.Config.BottomBoundary)
                {
                    p.pos.vec.y = General.Map.Config.BottomBoundary;
                }
                p.stitch     = snaptonearest;
                p.stitchline = snaptonearest;
                //Logger.WriteLogLine("f");//debugcrap
                points.Add(p);
                return;
            }
            else
            {
                // Normal position
                p.pos.vec    = vm;
                p.stitch     = snaptonearest;
                p.stitchline = snaptonearest;
                //Logger.WriteLogLine("g");//debugcrap
                points.Add(p);
                return;
            }
        } // getcurrentposition
Esempio n. 34
0
        /// <summary>
        /// Deserializes the given leaf.
        /// </summary>
        /// <param name="typeModel"></param>
        /// <param name="data"></param>
        /// <param name="boxes"></param>
        /// <returns></returns>
        protected override List <Primitive2D> DeSerialize(RuntimeTypeModel typeModel,
                                                          byte[] data, out List <BoxF2D> boxes)
        {
            if (_compressed)
            { // decompress if needed.
                data = GZipStream.UncompressBuffer(data);
            }

            List <Primitive2D> dataLists = new List <Primitive2D>();

            boxes = new List <BoxF2D>();

            int scaleFactor = _scaleFactor;

            // Assume the following stuff already exists in the current scene:
            // - ZoomRanges
            // - Styles

            // deserialize the leaf data.
            SceneObjectBlock leafData = typeModel.Deserialize(
                new MemoryStream(data), null, typeof(SceneObjectBlock)) as SceneObjectBlock;

            // decode
            for (int idx = 0; idx < leafData.PointsX.Count; idx++)
            {
                leafData.PointsX[idx] = leafData.PointsX[idx] + leafData.PointsXMin;
                leafData.PointsY[idx] = leafData.PointsY[idx] + leafData.PointsYMin;
            }

            // store the next points.
            bool[] pointsStarts = new bool[leafData.PointsX.Count];
            // loop over all points.
            for (int idx = 0; idx < leafData.PointPointId.Count; idx++)
            {
                pointsStarts[leafData.PointPointId[idx]] = true;
            }
            // loop over all text-points.
            for (int idx = 0; idx < leafData.TextPointPointId.Count; idx++)
            {
                pointsStarts[leafData.TextPointPointId[idx]] = true;
            }
            // loop over all icons.
            for (int idx = 0; idx < leafData.IconPointId.Count; idx++)
            {
                pointsStarts[leafData.IconPointId[idx]] = true;
            }
            // loop over all lines.
            for (int idx = 0; idx < leafData.LinePointsId.Count; idx++)
            {
                pointsStarts[leafData.LinePointsId[idx]] = true;
            }
            // loop over all polygons.
            for (int idx = 0; idx < leafData.PolygonPointsId.Count; idx++)
            {
                pointsStarts[leafData.PolygonPointsId[idx]] = true;
            }
            // loop over all line-texts.
            for (int idx = 0; idx < leafData.LineTextPointsId.Count; idx++)
            {
                pointsStarts[leafData.LineTextPointsId[idx]] = true;
            }
            Dictionary <int, int> pointsBoundaries = new Dictionary <int, int>();
            int previous = 0;

            for (int idx = 1; idx < pointsStarts.Length; idx++)
            {
                if (pointsStarts[idx])
                { // there is a start here.
                    pointsBoundaries[previous] = idx - previous;
                    previous = idx;
                }
            }
            pointsBoundaries[previous] = pointsStarts.Length - previous;

            // loop over all points.
            for (int idx = 0; idx < leafData.PointPointId.Count; idx++)
            {
                // get properties.
                int  pointId = leafData.PointPointId[idx];
                uint styleId = leafData.PointStyleId[idx];

                // get point/style/zoomrange.
                double     x     = (double)leafData.PointsX[pointId] / (double)scaleFactor;
                double     y     = (double)leafData.PointsY[pointId] / (double)scaleFactor;
                StylePoint style = _index.PointStyles[styleId];

                // build the primitive.
                Point2D point = new Point2D(x, y, style.Color, style.Size);
                point.Layer   = style.Layer;
                point.MinZoom = style.MinZoom;
                point.MaxZoom = style.MaxZoom;

                dataLists.Add(point);
                boxes.Add(new BoxF2D(new PointF2D(x, y)));
            }

            // loop over all text-points.
            for (int idx = 0; idx < leafData.TextPointPointId.Count; idx++)
            {
                // get properties.
                int    pointId = leafData.TextPointPointId[idx];
                uint   styleId = leafData.TextPointStyleId[idx];
                string text    = leafData.TextPointText[idx];

                // get point/style/zoomrange.
                float     x     = (float)leafData.PointsX[pointId] / (float)scaleFactor;
                float     y     = (float)leafData.PointsY[pointId] / (float)scaleFactor;
                StyleText style = _index.TextStyles[styleId];

                // build the primitive.
                Text2D text2D = new Text2D(x, y, text, style.Color, style.Size);
                text2D.Layer      = style.Layer;
                text2D.HaloColor  = style.HaloColor;
                text2D.HaloRadius = style.HaloRadius;
                text2D.MinZoom    = style.MinZoom;
                text2D.MaxZoom    = style.MaxZoom;

                dataLists.Add(text2D);
                boxes.Add(new BoxF2D(new PointF2D(x, y)));
            }

            // loop over all icons.
            for (int idx = 0; idx < leafData.IconPointId.Count; idx++)
            {
                // get properties.
                int  pointId = leafData.IconPointId[idx];
                uint imageId = leafData.IconImageId[idx];

                // get point/style/zoomrange.
                double x     = (double)leafData.PointsX[pointId] / (double)scaleFactor;
                double y     = (double)leafData.PointsY[pointId] / (double)scaleFactor;
                byte[] image = _index.IconImage[(int)imageId];

                // build the primitive.
                Icon2D icon = new Icon2D(x, y, image);
                icon.Layer = 0;
                // TODO: layer and zoom level. style.MinZoom, style.MaxZoom

                dataLists.Add(icon);
                boxes.Add(new BoxF2D(new PointF2D(x, y)));
            }

            // loop over all lines.
            for (int idx = 0; idx < leafData.LinePointsId.Count; idx++)
            {
                // get properties.
                int  pointsId = leafData.LinePointsId[idx];
                uint styleId  = leafData.LineStyleId[idx];

                // get points/style/zoomrange.
                int      pointsCount = pointsBoundaries[pointsId];
                double[] x           =
                    leafData.PointsX.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                double[] y =
                    leafData.PointsY.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                StyleLine style = _index.LineStyles[styleId];

                // build the primitive.
                Line2D line = new Line2D(x, y, style.Color, style.Width, style.LineJoin, style.Dashes);
                line.Layer   = style.Layer;
                line.MinZoom = style.MinZoom;
                line.MaxZoom = style.MaxZoom;

                dataLists.Add(line);
                boxes.Add(new BoxF2D(x, y));
            }

            // loop over all polygons.
            for (int idx = 0; idx < leafData.PolygonPointsId.Count; idx++)
            {
                // get properties.
                int  pointsId = leafData.PolygonPointsId[idx];
                uint styleId  = leafData.PolygonStyleId[idx];

                // get points/style/zoomrange.
                int      pointsCount = pointsBoundaries[pointsId];
                double[] x           =
                    leafData.PointsX.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                double[] y =
                    leafData.PointsY.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                StylePolygon style = _index.PolygonStyles[styleId];

                // build the primitive.
                Polygon2D polygon = new Polygon2D(x, y, style.Color, style.Width, style.Fill);
                polygon.Layer   = style.Layer;
                polygon.MaxZoom = style.MaxZoom;
                polygon.MinZoom = style.MinZoom;

                dataLists.Add(polygon);
                boxes.Add(new BoxF2D(x, y));
            }

            // loop over all line-texts.
            for (int idx = 0; idx < leafData.LineTextPointsId.Count; idx++)
            {
                // get properties.
                int    pointsId = leafData.LineTextPointsId[idx];
                uint   styleId  = leafData.LineTextStyleId[idx];
                string text     = leafData.LineTextText[idx];

                // get points/style/zoomrange.
                int      pointsCount = pointsBoundaries[pointsId];
                double[] x           =
                    leafData.PointsX.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                double[] y =
                    leafData.PointsY.GetRange(pointsId, pointsCount).ConvertFromLongArray(scaleFactor);
                StyleText style = _index.TextStyles[styleId];

                // build the primitive.
                LineText2D lineText = new LineText2D(x, y, style.Color, style.Size, text);
                lineText.Layer      = style.Layer;
                lineText.Font       = style.Font;
                lineText.HaloColor  = style.HaloColor;
                lineText.HaloRadius = style.HaloRadius;
                lineText.MinZoom    = style.MinZoom;
                lineText.MaxZoom    = style.MaxZoom;

                dataLists.Add(lineText);
                boxes.Add(new BoxF2D(x, y));
            }
            return(dataLists);
        }
Esempio n. 35
0
 public LineBase(Line2D line2D)
 {
     Pen          = GetDefaultPen();
     SelectionPen = GetDefaultSelectionPen();
     Line2D       = line2D ?? throw new ArgumentNullException(nameof(line2D));
 }
 public static Line2D LineairRegression(vector_Coord2D tab) {
   Line2D ret = new Line2D(VisionLabPINVOKE.LineairRegression(vector_Coord2D.getCPtr(tab)), true);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Esempio n. 37
0
    // This clips a polygon and returns the triangles
    // The polygon may not have any holes or islands
    // See: http://www.geometrictools.com/Documentation/TriangulationByEarClipping.pdf
    private int DoEarClip(EarClipPolygon poly, List <Vector2D> verticeslist, List <Sidedef> sidedefslist)
    {
        LinkedList <EarClipVertex>     verts    = new LinkedList <EarClipVertex>();
        List <EarClipVertex>           convexes = new List <EarClipVertex>(poly.Count);
        LinkedList <EarClipVertex>     reflexes = new LinkedList <EarClipVertex>();
        LinkedList <EarClipVertex>     eartips  = new LinkedList <EarClipVertex>();
        LinkedListNode <EarClipVertex> n2;

        EarClipVertex[] t;
        int             countvertices = 0;

        // Go for all vertices to fill list
        foreach (EarClipVertex vec in poly)
        {
            vec.SetVertsLink(verts.AddLast(vec));
        }

        // Remove any zero-length lines, these will give problems
        LinkedListNode <EarClipVertex> n1 = verts.First;

        do
        {
            // Continue until adjacent zero-length lines are removed
            n2 = n1.Next ?? verts.First;
            Vector2D d = n1.Value.Position - n2.Value.Position;
            while ((Math.Abs(d.x) < 0.00001f) && (Math.Abs(d.y) < 0.00001f))
            {
                n2.Value.Remove();
                n2 = n1.Next ?? verts.First;
                if (n2 != null)
                {
                    d = n1.Value.Position - n2.Value.Position;
                }
                else
                {
                    break;
                }
            }

            // Next!
            n1 = n2;
        }while (n1 != verts.First);

        // Optimization: Vertices which have lines with the
        // same angle are useless. Remove them!
        n1 = verts.First;
        while (n1 != null)
        {
            // Get the next vertex
            n2 = n1.Next;

            // Get triangle for v
            t = GetTriangle(n1.Value);

            // Check if both lines have the same angle
            Line2D a = new Line2D(t[0].Position, t[1].Position);
            Line2D b = new Line2D(t[1].Position, t[2].Position);
            if (Math.Abs(Angle2D.Difference(a.GetAngle(), b.GetAngle())) < 0.00001f)
            {
                // Same angles, remove vertex
                n1.Value.Remove();
            }

            // Next!
            n1 = n2;
        }

        // Go for all vertices to determine reflex or convex
        foreach (EarClipVertex vv in verts)
        {
            // Add to reflex or convex list
            if (IsReflex(GetTriangle(vv)))
            {
                vv.AddReflex(reflexes);
            }
            else
            {
                convexes.Add(vv);
            }
        }

        // Go for all convex vertices to see if they are ear tips
        foreach (EarClipVertex cv in convexes)
        {
            // Add when this is a valid ear
            t = GetTriangle(cv);
            if (CheckValidEar(t, reflexes))
            {
                cv.AddEarTip(eartips);
            }
        }

/*#if DEBUG
 *      if (OnShowPolygon != null) OnShowPolygon(verts);
 #endif*/

        // Process ears until done
        while ((eartips.Count > 0) && (verts.Count > 2))
        {
            // Get next ear
            EarClipVertex v = eartips.First.Value;
            t = GetTriangle(v);

            // Only save this triangle when it has an area
            if (TriangleHasArea(t))
            {
                // Add ear as triangle
                AddTriangleToList(t, verticeslist, sidedefslist, (verts.Count == 3));
                countvertices += 3;
            }

            // Remove this ear from all lists
            v.Remove();
            EarClipVertex v1 = t[0];
            EarClipVertex v2 = t[2];

/*#if DEBUG
 *          if (TriangleHasArea(t))
 *          {
 *              if (OnShowEarClip != null) OnShowEarClip(t, verts);
 *          }
 #endif*/

            // Test first neighbour
            EarClipVertex[] t1 = GetTriangle(v1);
            //bool t1a = true;	//TriangleHasArea(t1);
            if (/*t1a && */ IsReflex(t1))
            {
                // List as reflex if not listed yet
                if (!v1.IsReflex)
                {
                    v1.AddReflex(reflexes);
                }
                v1.RemoveEarTip();
            }
            else
            {
                // Remove from reflexes
                v1.RemoveReflex();
            }

            // Test second neighbour
            EarClipVertex[] t2 = GetTriangle(v2);
            //bool t2a = true;	//TriangleHasArea(t2);
            if (/*t2a && */ IsReflex(t2))
            {
                // List as reflex if not listed yet
                if (!v2.IsReflex)
                {
                    v2.AddReflex(reflexes);
                }
                v2.RemoveEarTip();
            }
            else
            {
                // Remove from reflexes
                v2.RemoveReflex();
            }

            // Check if any neightbour have become a valid or invalid ear
            if (!v1.IsReflex && (/*!t1a || */ CheckValidEar(t1, reflexes)))
            {
                v1.AddEarTip(eartips);
            }
            else
            {
                v1.RemoveEarTip();
            }
            if (!v2.IsReflex && (/*!t2a || */ CheckValidEar(t2, reflexes)))
            {
                v2.AddEarTip(eartips);
            }
            else
            {
                v2.RemoveEarTip();
            }
        }

/*#if DEBUG
 *      if (OnShowRemaining != null) OnShowRemaining(verts);
 #endif*/

        // Dispose remaining vertices
        foreach (EarClipVertex ecv in verts)
        {
            ecv.Dispose();
        }

        // Return the number of vertices in the result
        return(countvertices);
    }
 public static void Line2DToCoords(Line2D line, int nrCoords, vector_Coord2D res) {
   VisionLabPINVOKE.Line2DToCoords__SWIG_3(Line2D.getCPtr(line), nrCoords, vector_Coord2D.getCPtr(res));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
 }
 public override void _Ready()
 {
     navigation2D = GetNode <Navigation2D>("Navigation2D");
     player       = GetNode <Player>("Player");
     line2D       = GetNode <Line2D>("Line2D");
 }
 public static double Distance(Line2D line, Coord2D p) {
   double ret = VisionLabPINVOKE.Distance__SWIG_0(Line2D.getCPtr(line), Coord2D.getCPtr(p));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Esempio n. 41
0
		public void MoveLineByAssigningListOfPoints()
		{
			var line = new Line2D(Vector2D.Zero, Vector2D.Zero, Color.Red);
			line.Points = new List<Vector2D> { Vector2D.Half, Vector2D.One };
			Assert.AreEqual(Vector2D.Half, line.StartPoint);
			Assert.AreEqual(Vector2D.One, line.EndPoint);
		}
 public static Line2D LongestLineBetweenCoords(vector_Coord2D tab, ref int startIndex, ref int endIndex) {
   Line2D ret = new Line2D(VisionLabPINVOKE.LongestLineBetweenCoords__SWIG_1(vector_Coord2D.getCPtr(tab), ref startIndex, ref endIndex), true);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Esempio n. 43
0
        public void Init()
        {
            RobustConsole.ClearConsole();
            RobustConsole.SetLogLevel(LogLevel.Debug);
            RobustConsole.Write(LogLevel.Debug, "RobustEngine", "Init() Intializing...");

            Timekeeper = new Clock();
            VSettings  = new VideoSettings(); //TODO import video settings here

            GameScreen = new GameWindow(800, 800, GraphicsMode.Default, "RobustWando", GameWindowFlags.Default, DisplayDevice.Default, 3, 3, GraphicsContextFlags.Debug);

            //GameScreen = new GameWindow();
            //GameScreen.Size = VSettings.Size;
            //GameScreen.WindowBorder = VSettings.Border;
            //GameScreen.Title = "Space Station 14";
            //GameScreen.Visible = true;

            // GameScreen.VSync = VSyncMode.Off;

            GameScreen.MakeCurrent(); //OPENGL CONTEXT STARTS HERE

            GLINFO += "\n\n------------------------------------------------------------------";
            GLINFO += "\n OpenGL Version: " + GL.GetString(StringName.Version);
            GLINFO += "\n Vendor: " + GL.GetString(StringName.Vendor);
            GLINFO += "\n GLSL Version: " + GL.GetString(StringName.ShadingLanguageVersion);
            GLINFO += "\n------------------------------------------------------------------\n";

            RobustConsole.Write(LogLevel.Info, this, GLINFO);
            GameScreen.RenderFrame += Render;
            GameScreen.UpdateFrame += Update;
            GL.Enable(EnableCap.Texture2D);

            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.ClearColor(0, 0, 0, 0);            //GL.Enable(EnableCap.VertexArray);

            var ImageTestFile = Path.Combine(Environment.CurrentDirectory, "Graphics", "Shaders", "ImageTest");

            CurrentShader = new Shader(ImageTestFile + ".vert", ImageTestFile + ".frag");


            //TESTING
            Texture  = new Texture2D("Devtexture_Floor.png");
            LineTest = new Line2D(0, 0, 0, 0, 1);
            //LineTest = new Line(0, 0, 1, 1, 1);

            TriangleTest = new Triangle2D(0, 0, 256, 256);
            Sprite       = new Sprite("test", Texture);
            Sprite.SetPosition(new Vector2(.4f, .4f));

            PlayerView = new View(Vector2.One, 0, 10);


            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.ClearColor(Color.DimGray);
            //  GL.Viewport(0, 0, -1500, -1500);



            //Context = new GraphicsContext(GraphicsMode.Default, GameScreen.WindowInfo,4,4,GraphicsContextFlags.Default);
            //Context.MakeCurrent(GameScreen.WindowInfo);
            //(Context as IGraphicsContextInternal).LoadAll();
            //GL.Enable(EnableCap.Blend);

            RobustConsole.Write(LogLevel.Debug, "RobustEngine", "Init() Done.");
            ReadyToRun = true;
        }
Esempio n. 44
0
 // This checks if a vertex is reflex (corner > 180 deg) or convex (corner < 180 deg)
 private static bool IsReflex(EarClipVertex[] t)
 {
     // Return true when corner is > 180 deg
     return(Line2D.GetSideOfLine(t[0].Position, t[2].Position, t[1].Position) < 0.0f);
 }
Esempio n. 45
0
        //Returns the triangle in which a given point (ray) (x,y) is located. It returns the real coordinates of points that form the triangle in which the ray (x,y) goes trough the surface
        //Using Surface's technique for information
        public Vector3[] GetPositionTriangle(float x, float y, ShiftModes shiftApplied)
        {
            ShiftModes shiftm = shiftApplied;

            //detect shifting from technique
            if (shiftApplied == ShiftModes.AutoDetect)
            {
                shiftm = this.SurfaceTechnique.DetectShiftMode();
                if (shiftm == ShiftModes.Both)
                {
                    throw new ExceptionSurface("A horizontal and a vertical shift were both found in this surface's technique. Function GetPositionHeight cannot compute surfaces with a technique that uses shifts both horisontal and vertical! Please use only one kind of shift.");
                }
            }

            //get the tile where the position is located and check if the tile obtained is within surface limits. if not, throw exception
            Point tile = this.GetPositionTile(x, y, shiftApplied);

            if (!Misc.WithinBounds(tile, this.Size, -2, -2))
            {
                throw new ExceptionSurface("The tile that contains the point (" + x + "," + y + ") is not within surface limits!");                                                       //okay, uses offsets of -2 because: for once the tile number is one less than the points in a surface, which is returned in this.size. and another thing is that the function verifies in interval [0,size] but it must not include size in our case, because from 0 to size-1 is the boundary that includes all good points
            }
            HatchingMode tileHatch = this.GetTileHatching(tile.X, tile.Y);

            //determine the triangle from this tile that contains this point
            //same algorithm for any shift mode works
            Vector3 p1, p2;            //points that determin the hatching line on this tile
            Vector3 A, B, C;           //points of the triangle that contains this point

            if (tileHatch == HatchingMode.NWSE)
            {
                p1 = this.GetPointRealCoordinatesXYHeight(tile.X, tile.Y + 1, true);
                p2 = this.GetPointRealCoordinatesXYHeight(tile.X + 1, tile.Y, true);

                PointF pInter = Line2D.Intersection(Line2D.FromTwoPoints(p1.X, p1.Y, p2.X, p2.Y), new Line2D(x, y, 0, 1)); //determine the intersection point between a vertical line that goes through the point and the one that determines the hatching. The result can help determine which triangle exacly this point belongs to

                bool leftTriangle = true;                                                                                  // consider it is the left triangle first, for faster computing

                //lines were parallel and the point is on the right triangle
                if (float.IsInfinity(pInter.Y))
                {
                    if (x > p1.X)
                    {
                        leftTriangle = false;
                    }
                }

                //lines not parallel, but the point is on the right triangle
                if (y > pInter.Y)
                {
                    leftTriangle = false;
                }

                //set the triangle (obs: one point was not calculated)
                if (leftTriangle)
                {
                    A = p1;
                    B = p2;
                    C = this.GetPointRealCoordinatesXYHeight(tile.X, tile.Y, true);
                }
                else                 //right triangle
                {
                    A = p1;
                    B = this.GetPointRealCoordinatesXYHeight(tile.X + 1, tile.Y + 1, true);
                    C = p2;
                }
            }
            else             //NESW
            {
                p1 = this.GetPointRealCoordinatesXYHeight(tile.X, tile.Y, true);
                p2 = this.GetPointRealCoordinatesXYHeight(tile.X + 1, tile.Y + 1, true);

                PointF pInter = Line2D.Intersection(Line2D.FromTwoPoints(p1.X, p1.Y, p2.X, p2.Y), new Line2D(x, y, 0, 1)); //determine the intersection point between a vertical line that goes through the point and the one that determines the hatching. The result can help determine which triangle exacly this point belongs to

                bool leftTriangle = true;                                                                                  // consider it is the left triangle first, for faster computing

                //lines were parallel and the point is on the right triangle
                if (float.IsInfinity(pInter.Y))
                {
                    if (x > p1.X)
                    {
                        leftTriangle = false;
                    }
                }

                //lines not parallel, but the point is on the right triangle
                if (y < pInter.Y)
                {
                    leftTriangle = false;
                }

                //set the triangle (obs: one point was not calculated)
                if (leftTriangle)
                {
                    A = p1;
                    B = this.GetPointRealCoordinatesXYHeight(tile.X, tile.Y + 1, true);
                    C = p2;
                }
                else                 //right triangle
                {
                    A = p1;
                    B = p2;
                    C = this.GetPointRealCoordinatesXYHeight(tile.X + 1, tile.Y, true);
                }
            }

            //returns the triangle in the form of an 3 elements array of Vector3 object. (The triangle is given clockwise, relative to the surface)
            Vector3[] triangle = new Vector3[3];
            triangle[0] = A; triangle[1] = B; triangle[2] = C;

            return(triangle);
        }
		//mxd
		public override void OnMouseMove(MouseEventArgs e)
		{
			base.OnMouseMove(e);

			// Anything to do?
			if((!selectpressed && !editpressed) || closestline == null)
			{
				hintlabel.Text = string.Empty;
				return;
			}

			// Do something...
			Vector2D perpendicular = closestline.Line.GetPerpendicular().GetNormal();
			if(panel.Distance != 0) perpendicular *= panel.Distance; // Special cases...
			Vector2D center = closestline.GetCenterPoint();
			Line2D radius = new Line2D(center, center - perpendicular);
			double u = radius.GetNearestOnLine(mousemappos - mousedownoffset);
			int dist = (panel.Distance == 0 ? 1 : panel.Distance); // Special cases...
			int offset = (int)Math.Round(dist * u - dist);
			bool updaterequired = false;

			// Clamp values?
			bool clampvalue = !General.Interface.ShiftState;

			// Change verts amount
			if(selectpressed && editpressed)
			{
				if(prevoffset != 0)
				{
					// Set new verts count without triggering the update...
					panel.SetValues(panel.Vertices + Math.Sign(prevoffset - offset), panel.Distance, panel.Angle, panel.FixedCurve, panel.FixedCurveOutwards);

					// Update hint text
					hintlabel.Text = "Vertices: " + panel.Vertices;
					updaterequired = true;
				}
			}
			// Change distance
			else if(selectpressed && !panel.FixedCurve)
			{
				if(double.IsNaN(u))
				{
					// Set new distance without triggering the update...
					panel.SetValues(panel.Vertices, 0, panel.Angle, panel.FixedCurve, panel.FixedCurveOutwards); // Special cases...
				}
				else
				{
					int newoffset;
					if(clampvalue)
						newoffset = (panel.Distance + offset) / panel.DistanceIncrement * panel.DistanceIncrement; // Clamp to 8 mu increments
					else
						newoffset = panel.Distance + offset;

					// Set new distance without triggering the update...
					panel.SetValues(panel.Vertices, newoffset, panel.Angle, panel.FixedCurve, panel.FixedCurveOutwards);
				}

				// Update hint text
				hintlabel.Text = "Distance: " + panel.Distance;
				updaterequired = true;
			}
			// Change angle
			else if(editpressed && prevoffset != 0)
			{
				int newangle = 0;
				if(panel.FixedCurve)
				{
					// Flip required?
					if(panel.Angle == 0 && (Math.Sign(offset - prevoffset) != Math.Sign(panel.Distance)))
					{
						// Set new distance without triggering the update...
						panel.SetValues(panel.Vertices, -panel.Distance, panel.Angle, panel.FixedCurve, panel.FixedCurveOutwards);

						// Recalculate affected values...
						perpendicular *= -1;
						radius.v2 = center - perpendicular;
						u = radius.GetNearestOnLine(mousemappos - mousedownoffset);
					}

					//TODO: there surely is a way to get new angle without iteration...
					double targetoffset = radius.GetLength() * u;
					double prevdiff = double.MaxValue;
					int increment = (clampvalue ? panel.AngleIncrement : 1);
					for(int i = 1; i < panel.MaximumAngle; i += increment)
					{
						// Calculate diameter for current angle...
						double ma = Angle2D.DegToRad(i);
						double d = (closestline.Length / Math.Tan(ma / 2f)) / 2;
						double D = d / Math.Cos(ma / 2f);
						double h = D - d;

						double curdiff = Math.Abs(h - targetoffset);

						// This one matches better...
						if(curdiff < prevdiff) newangle = i;
						prevdiff = curdiff;
					}

					// Clamp to 5 deg increments
					if(clampvalue) newangle = (newangle / panel.AngleIncrement) * panel.AngleIncrement; 
				}
				else
				{
					int diff = (int)Math.Round((offset - prevoffset) * renderer.Scale);
					if(panel.Angle + diff > 0)
					{
						if(clampvalue) newangle = (panel.Angle / panel.AngleIncrement + Math.Sign(diff)) * panel.AngleIncrement; // Clamp to 5 deg increments
						else newangle = panel.Angle + diff;
					}
				}

				// Set new angle without triggering the update...
				panel.SetValues(panel.Vertices, panel.Distance, newangle, panel.FixedCurve, panel.FixedCurveOutwards);

				// Update hint text
				hintlabel.Text = "Angle: " + panel.Angle;
				updaterequired = true;
			}

			// Update UI
			if(updaterequired)
			{
				// Update label position
				double labeldistance;

				if(panel.Angle == 0)
				{
					labeldistance = 0; // Special cases!
				}
				else if(panel.FixedCurve)
				{
					double ma = Angle2D.DegToRad(panel.Angle);
					double d = (closestline.Length / Math.Tan(ma / 2f)) / 2;
					double D = d / Math.Cos(ma / 2f);
					labeldistance = D - d;
				}
				else
				{
					labeldistance = Math.Abs(panel.Distance);
				}

				labeldistance += 16 / renderer.Scale;
				Vector2D labelpos = radius.GetCoordinatesAt(labeldistance / radius.GetLength());
				hintlabel.Move(labelpos, labelpos);

				// Trigger update
				OnValuesChanged(null, EventArgs.Empty);
			}

			// Store current offset
			prevoffset = offset;
		}
Esempio n. 47
0
        public void LineLength(string p1s, string p2s, double expected)
        {
            var p1 = Point2D.Parse(p1s);
            var p2 = Point2D.Parse(p2s);
            var line = new Line2D(p1, p2);
            double len = line.Length;

            Assert.AreEqual(expected, len, 1e-7);
        }
Esempio n. 48
0
        public void erstelleSkizzenElemente()
        {
            Factory2D fact2D = hsp_catiaProfil.OpenEdition();

            // Eckpunkte erstellen

            Console.Write("Vertikale Länge Außen : ");
            double dL1 = Convert.ToDouble(Console.ReadLine());

            Console.Write("Horizontale Länge Außen : ");
            double dL2 = Convert.ToDouble(Console.ReadLine());

            Point2D P1 = fact2D.CreatePoint(dL2 / 2, dL1 / 2);
            Point2D P2 = fact2D.CreatePoint(dL2 / 2, -dL1 / 2);
            Point2D P3 = fact2D.CreatePoint(-dL2 / 2, -dL1 / 2);
            Point2D P4 = fact2D.CreatePoint(-dL2 / 2, dL1 / 2);

            Line2D L1 = fact2D.CreateLine(dL2 / 2, dL1 / 2, dL2 / 2, -dL1 / 2);
            Line2D L2 = fact2D.CreateLine(dL2 / 2, -dL1 / 2, -dL2 / 2, -dL1 / 2);
            Line2D L3 = fact2D.CreateLine(-dL2 / 2, -dL1 / 2, -dL2 / 2, dL1 / 2);
            Line2D L4 = fact2D.CreateLine(-dL2 / 2, dL1 / 2, dL2 / 2, dL1 / 2);

            L1.StartPoint = P1;
            L1.EndPoint   = P2;

            L2.StartPoint = P2;
            L2.EndPoint   = P3;

            L3.StartPoint = P3;
            L3.EndPoint   = P4;

            L4.StartPoint = P4;
            L4.EndPoint   = P1;


            Console.Write("Vertikale Länge Innen : ");
            double dL3 = Convert.ToDouble(Console.ReadLine());

            Console.Write("Horizontale Länge Innen : ");
            double dL4 = Convert.ToDouble(Console.ReadLine());

            Point2D P5 = fact2D.CreatePoint(dL4 / 2, dL3 / 2);
            Point2D P6 = fact2D.CreatePoint(dL4 / 2, -dL3 / 2);
            Point2D P7 = fact2D.CreatePoint(-dL4 / 2, -dL3 / 2);
            Point2D P8 = fact2D.CreatePoint(-dL4 / 2, dL3 / 2);

            Line2D L5 = fact2D.CreateLine(dL4 / 2, dL3 / 2, dL4 / 2, -dL3 / 2);
            Line2D L6 = fact2D.CreateLine(dL4 / 2, -dL3 / 2, -dL4 / 2, -dL3 / 2);
            Line2D L7 = fact2D.CreateLine(-dL4 / 2, -dL3 / 2, -dL4 / 2, dL3 / 2);
            Line2D L8 = fact2D.CreateLine(-dL4 / 2, dL3 / 2, dL4 / 2, dL3 / 2);

            L5.StartPoint = P5;
            L5.EndPoint   = P6;

            L6.StartPoint = P6;
            L6.EndPoint   = P7;

            L7.StartPoint = P7;
            L7.EndPoint   = P8;

            L8.StartPoint = P8;
            L8.EndPoint   = P5;


            hsp_catiaProfil.CloseEdition();

            hsp_catiaPart.Part.Update();
        }
        public void Rechteck_hohl_DrawSketch(double Rechteck_hohl_Breite, double Rechteck_hohl_Hoehe, double Wandstaerke)
        {
            double b = Rechteck_hohl_Breite;
            double h = Rechteck_hohl_Hoehe;
            double t = Wandstaerke;
            double bi = b - 2 * t;
            double hi = h - 2 * t;
            double ra, ri;

            // Berechnung der Eckenradien nach DIN EN 10219-2:2006 für Hohlprofile
            if (t <= 6)
            {
                ra = 1.6 * t;
            }
            else if (t <= 10)
            {
                ra = 2 * t;
            }
            else if (t > 10)
            {
                ra = 2.4 * t;
            }
            else
            {
                ra = 2.4 * t;
            }

            ri = ra - t;

            CATIA_Rechteck_hohl_2D.set_Name("Rechteck-Hohlprofil");

            Factory2D Rechteck_hohl_Factory = CATIA_Rechteck_hohl_2D.OpenEdition();

            // Definition der Radienmittelpunkte
            Point2D Mittelpunkt1            = Rechteck_hohl_Factory.CreatePoint(ra, ra);
            Point2D Mittelpunkt2            = Rechteck_hohl_Factory.CreatePoint((b - ra), ra);
            Point2D Mittelpunkt3            = Rechteck_hohl_Factory.CreatePoint((b - ra), (h - ra));
            Point2D Mittelpunkt4            = Rechteck_hohl_Factory.CreatePoint(ra, (h - ra));

            // Definition des äußeren Rechtecks
            Point2D Konturpunkt1 = Rechteck_hohl_Factory.CreatePoint(ra, 0);
            Point2D Konturpunkt2 = Rechteck_hohl_Factory.CreatePoint((b - ra), 0);
            Point2D Konturpunkt3 = Rechteck_hohl_Factory.CreatePoint(b, ra);
            Point2D Konturpunkt4 = Rechteck_hohl_Factory.CreatePoint(b, (h - ra));
            Point2D Konturpunkt5 = Rechteck_hohl_Factory.CreatePoint((b - ra), h);
            Point2D Konturpunkt6 = Rechteck_hohl_Factory.CreatePoint(ra, h);
            Point2D Konturpunkt7 = Rechteck_hohl_Factory.CreatePoint(0, (h - ra));
            Point2D Konturpunkt8 = Rechteck_hohl_Factory.CreatePoint(0, ra);

            Line2D Linie12 = Rechteck_hohl_Factory.CreateLine(ra, 0, (b - ra), 0);

            Linie12.StartPoint = Konturpunkt1;
            Linie12.EndPoint   = Konturpunkt2;

            Line2D Linie34 = Rechteck_hohl_Factory.CreateLine(b, ra, b, (h - ra));

            Linie34.StartPoint = Konturpunkt3;
            Linie34.EndPoint   = Konturpunkt4;

            Line2D Linie56 = Rechteck_hohl_Factory.CreateLine((b - ra), h, ra, h);

            Linie56.StartPoint = Konturpunkt5;
            Linie56.EndPoint   = Konturpunkt6;

            Line2D Linie78 = Rechteck_hohl_Factory.CreateLine(0, (h - ra), 0, ra);

            Linie78.StartPoint = Konturpunkt7;
            Linie78.EndPoint   = Konturpunkt8;

            Circle2D Eckenverrundung81 = Rechteck_hohl_Factory.CreateCircle(ra, ra, ra, 0, 0);

            Eckenverrundung81.CenterPoint = Mittelpunkt1;
            Eckenverrundung81.StartPoint  = Konturpunkt8;
            Eckenverrundung81.EndPoint    = Konturpunkt1;

            Circle2D Eckenverrundung23 = Rechteck_hohl_Factory.CreateCircle(0, 0, ra, 0, 0);

            Eckenverrundung23.CenterPoint = Mittelpunkt2;
            Eckenverrundung23.StartPoint  = Konturpunkt2;
            Eckenverrundung23.EndPoint    = Konturpunkt3;

            Circle2D Eckenverrundung45 = Rechteck_hohl_Factory.CreateCircle(0, 0, ra, 0, 0);

            Eckenverrundung45.CenterPoint = Mittelpunkt3;
            Eckenverrundung45.StartPoint  = Konturpunkt4;
            Eckenverrundung45.EndPoint    = Konturpunkt5;

            Circle2D Eckenverrundung67 = Rechteck_hohl_Factory.CreateCircle(0, 0, ra, 0, 0);

            Eckenverrundung67.CenterPoint = Mittelpunkt4;
            Eckenverrundung67.StartPoint  = Konturpunkt6;
            Eckenverrundung67.EndPoint    = Konturpunkt7;

            // Definition des inneren Rechtecks
            Point2D Konturpunkt_i1 = Rechteck_hohl_Factory.CreatePoint(ra, t);
            Point2D Konturpunkt_i2 = Rechteck_hohl_Factory.CreatePoint((b - ra), t);
            Point2D Konturpunkt_i3 = Rechteck_hohl_Factory.CreatePoint((b - t), ra);
            Point2D Konturpunkt_i4 = Rechteck_hohl_Factory.CreatePoint((b - t), (h - ra));
            Point2D Konturpunkt_i5 = Rechteck_hohl_Factory.CreatePoint((b - ra), (h - t));
            Point2D Konturpunkt_i6 = Rechteck_hohl_Factory.CreatePoint(ra, (h - t));
            Point2D Konturpunkt_i7 = Rechteck_hohl_Factory.CreatePoint(t, (h - ra));
            Point2D Konturpunkt_i8 = Rechteck_hohl_Factory.CreatePoint(t, ra);

            Line2D Linie_i12 = Rechteck_hohl_Factory.CreateLine(ra, t, (b - ra), t);

            Linie_i12.StartPoint = Konturpunkt_i1;
            Linie_i12.EndPoint   = Konturpunkt_i2;

            Line2D Linie_i34 = Rechteck_hohl_Factory.CreateLine((b - t), ra, (b - t), (h - ra));

            Linie_i34.StartPoint = Konturpunkt_i3;
            Linie_i34.EndPoint   = Konturpunkt_i4;

            Line2D Linie_i56 = Rechteck_hohl_Factory.CreateLine((b - ra), (h - t), ra, (h - t));

            Linie_i56.StartPoint = Konturpunkt_i5;
            Linie_i56.EndPoint   = Konturpunkt_i6;

            Line2D Linie_i78 = Rechteck_hohl_Factory.CreateLine(t, (h - ra), t, ra);

            Linie_i78.StartPoint = Konturpunkt_i7;
            Linie_i78.EndPoint   = Konturpunkt_i8;

            Circle2D Eckenverrundung_i81 = Rechteck_hohl_Factory.CreateCircle(ra, ra, ri, 0, 0);

            Eckenverrundung_i81.CenterPoint = Mittelpunkt1;
            Eckenverrundung_i81.StartPoint  = Konturpunkt_i8;
            Eckenverrundung_i81.EndPoint    = Konturpunkt_i1;

            Circle2D Eckenverrundung_i23 = Rechteck_hohl_Factory.CreateCircle((b - ra), ra, ri, 0, 0);

            Eckenverrundung_i23.CenterPoint = Mittelpunkt2;
            Eckenverrundung_i23.StartPoint  = Konturpunkt_i2;
            Eckenverrundung_i23.EndPoint    = Konturpunkt_i3;

            Circle2D Eckenverrundung_i45 = Rechteck_hohl_Factory.CreateCircle((b - ra), (h - ra), ri, 0, 0);

            Eckenverrundung_i45.CenterPoint = Mittelpunkt3;
            Eckenverrundung_i45.StartPoint  = Konturpunkt_i4;
            Eckenverrundung_i45.EndPoint    = Konturpunkt_i5;

            Circle2D Eckenverrundung_i67 = Rechteck_hohl_Factory.CreateCircle(ra, (h - ra), ri, 0, 0);

            Eckenverrundung_i67.CenterPoint = Mittelpunkt4;
            Eckenverrundung_i67.StartPoint  = Konturpunkt_i6;
            Eckenverrundung_i67.EndPoint    = Konturpunkt_i7;


            CATIA_Rechteck_hohl_2D.CloseEdition();

            CATIA_Rechteck_hohl_Part.Part.Update();
        }
Esempio n. 50
0
        // This updates the selection
        private void Update()
        {
            // Not in any modifying mode?
            if (mode == ModifyMode.None)
            {
                Vector2D prevdragoffset = alignoffset;
                alignoffset     = new Vector2D(float.MinValue, float.MinValue);
                showalignoffset = false;

                // Check what grip the mouse is over
                // and change cursor accordingly
                Grip mousegrip = CheckMouseGrip();
                switch (mousegrip)
                {
                case Grip.Main:
                    int   closestcorner = -1;
                    float cornerdist    = float.MaxValue;
                    for (int i = 0; i < 4; i++)
                    {
                        Vector2D delta = corners[i] - mousemappos;
                        float    d     = delta.GetLengthSq();
                        if (d < cornerdist)
                        {
                            closestcorner = i;
                            cornerdist    = d;
                        }
                    }
                    switch (closestcorner)
                    {
                    // TODO:
                    case 0: alignoffset = new Vector2D(0f, 0f); break;

                    case 1: alignoffset = new Vector2D(texture.ScaledWidth, 0f); break;

                    case 2: alignoffset = new Vector2D(texture.ScaledWidth, -texture.ScaledHeight); break;

                    case 3: alignoffset = new Vector2D(0f, -texture.ScaledHeight); break;
                    }
                    showalignoffset = true;
                    General.Interface.SetCursor(Cursors.Hand);
                    break;

                case Grip.RotateLB:
                case Grip.RotateRT:
                    alignoffset     = new Vector2D(0f, 0f);
                    showalignoffset = true;
                    General.Interface.SetCursor(Cursors.Cross);
                    break;

                case Grip.SizeH:
                case Grip.SizeV:
                    alignoffset     = new Vector2D(0f, 0f);
                    showalignoffset = true;
                    // Pick the best matching cursor depending on rotation and side
                    float resizeangle = -(rotation + sectorinfo[0].rotation);
                    if (mousegrip == Grip.SizeH)
                    {
                        resizeangle += Angle2D.PIHALF;
                    }
                    resizeangle = Angle2D.Normalized(resizeangle);
                    if (resizeangle > Angle2D.PI)
                    {
                        resizeangle -= Angle2D.PI;
                    }
                    resizeangle = Math.Abs(resizeangle + Angle2D.PI / 8.000001f);
                    int cursorindex = (int)Math.Floor((resizeangle / Angle2D.PI) * 4.0f) % 4;
                    General.Interface.SetCursor(RESIZE_CURSORS[cursorindex]);
                    break;

                default:
                    General.Interface.SetCursor(Cursors.Default);
                    break;
                }

                if (prevdragoffset != alignoffset)
                {
                    General.Interface.RedrawDisplay();
                }
            }
            else
            {
                Vector2D snappedmappos = mousemappos;
                bool     dosnaptogrid  = snaptogrid;

                // Options
                snaptogrid    = General.Interface.ShiftState ^ General.Interface.SnapToGrid;
                snaptonearest = General.Interface.CtrlState ^ General.Interface.AutoMerge;

                // Change to crosshair cursor so we can clearly see around the mouse cursor
                General.Interface.SetCursor(Cursors.Cross);

                // Check what modifying mode we are in
                switch (mode)
                {
                case ModifyMode.Dragging:

                    offset = -mousemappos - dragoffset;
                    Vector2D transformedpos = TexToWorld(alignoffset);

                    // Snap to nearest vertex?
                    if (snaptonearest)
                    {
                        float vrange = BuilderPlug.Me.StitchRange / renderer.Scale;

                        // Try the nearest vertex
                        Vertex nv = MapSet.NearestVertexSquareRange(General.Map.Map.Vertices, transformedpos, vrange);
                        if (nv != null)
                        {
                            // Change offset to snap to target
                            offset      -= nv.Position - transformedpos;
                            dosnaptogrid = false;
                        }
                        else
                        {
                            // Find the nearest line within range
                            Linedef nl = MapSet.NearestLinedefRange(General.Map.Map.Linedefs, transformedpos, vrange);
                            if (nl != null)
                            {
                                // Snap to grid?
                                if (dosnaptogrid)
                                {
                                    // Get grid intersection coordinates
                                    List <Vector2D> coords = nl.GetGridIntersections();

                                    // Find nearest grid intersection
                                    float    found_distance = float.MaxValue;
                                    Vector2D found_pos      = new Vector2D(float.NaN, float.NaN);
                                    foreach (Vector2D v in coords)
                                    {
                                        Vector2D dist = transformedpos - v;
                                        if (dist.GetLengthSq() < found_distance)
                                        {
                                            // Found a better match
                                            found_distance = dist.GetLengthSq();
                                            found_pos      = v;

                                            // Do not snap to grid anymore
                                            dosnaptogrid = false;
                                        }
                                    }

                                    // Found something?
                                    if (!float.IsNaN(found_pos.x))
                                    {
                                        // Change offset to snap to target
                                        offset -= found_pos - transformedpos;
                                    }
                                }
                                else
                                {
                                    // Change offset to snap onto the line
                                    offset -= nl.NearestOnLine(transformedpos) - transformedpos;
                                }
                            }
                        }
                    }

                    // Snap to grid?
                    if (dosnaptogrid)
                    {
                        // Change offset to align to grid
                        offset -= General.Map.Grid.SnappedToGrid(transformedpos) - transformedpos;
                    }

                    break;

                case ModifyMode.Resizing:

                    // Snap to nearest vertex?
                    if (snaptonearest)
                    {
                        float vrange = BuilderPlug.Me.StitchRange / renderer.Scale;

                        // Try the nearest vertex
                        Vertex nv = MapSet.NearestVertexSquareRange(General.Map.Map.Vertices, snappedmappos, vrange);
                        if (nv != null)
                        {
                            snappedmappos = nv.Position;
                            dosnaptogrid  = false;
                        }
                    }

                    // Snap to grid?
                    if (dosnaptogrid)
                    {
                        // Aligned to grid
                        snappedmappos = General.Map.Grid.SnappedToGrid(snappedmappos);
                    }

                    float newscale = 1f / resizeaxis.GetNearestOnLine(snappedmappos);
                    if (float.IsInfinity(newscale) || float.IsNaN(newscale))
                    {
                        newscale = 99999f;
                    }
                    scale = (newscale * resizefilter) + scale * (1.0f - resizefilter);
                    if (float.IsInfinity(scale.x) || float.IsNaN(scale.x))
                    {
                        scale.x = 99999f;
                    }
                    if (float.IsInfinity(scale.y) || float.IsNaN(scale.y))
                    {
                        scale.y = 99999f;
                    }

                    // Show the extension line so that the user knows what it is aligning to
                    UpdateRectangleComponents();
                    Line2D edgeline;
                    if (resizefilter.x > resizefilter.y)
                    {
                        edgeline = new Line2D(corners[1], corners[2]);
                    }
                    else
                    {
                        edgeline = new Line2D(corners[3], corners[2]);
                    }
                    float nearestonedge = edgeline.GetNearestOnLine(snappedmappos);
                    if (nearestonedge > 0.5f)
                    {
                        extensionline = new Line2D(edgeline.v1, snappedmappos);
                    }
                    else
                    {
                        extensionline = new Line2D(edgeline.v2, snappedmappos);
                    }

                    break;

                case ModifyMode.Rotating:

                    // Snap to nearest vertex?
                    extensionline = new Line2D();
                    if (snaptonearest)
                    {
                        float vrange = BuilderPlug.Me.StitchRange / renderer.Scale;

                        // Try the nearest vertex
                        Vertex nv = MapSet.NearestVertexSquareRange(General.Map.Map.Vertices, snappedmappos, vrange);
                        if (nv != null)
                        {
                            snappedmappos = nv.Position;
                            dosnaptogrid  = false;

                            // Show the extension line so that the user knows what it is aligning to
                            extensionline = new Line2D(corners[0], snappedmappos);
                        }
                    }

                    Vector2D delta      = snappedmappos - rotationcenter;
                    float    deltaangle = -delta.GetAngle();

                    // Snap to grid?
                    if (dosnaptogrid)
                    {
                        // We make 24 vectors that the rotation can snap to
                        float    founddistance = float.MaxValue;
                        float    foundrotation = rotation;
                        Vector3D rotvec        = Vector2D.FromAngle(deltaangle + rotationoffset);

                        for (int i = 0; i < 24; i++)
                        {
                            // Make the vectors
                            float    angle   = i * Angle2D.PI * 0.08333333333f;                                //mxd. 15-degree increments
                            Vector2D gridvec = Vector2D.FromAngle(angle);

                            // Check distance
                            float dist = 2.0f - Vector2D.DotProduct(gridvec, rotvec);
                            if (dist < founddistance)
                            {
                                foundrotation = angle;
                                founddistance = dist;
                            }
                        }

                        // Keep rotation
                        rotation = foundrotation - sectorinfo[0].rotation;
                    }
                    else
                    {
                        rotation = deltaangle + rotationoffset - sectorinfo[0].rotation;
                    }
                    break;
                }

                UpdateSectors();
                General.Interface.RedrawDisplay();
            }
        }
Esempio n. 51
0
 public void AddLine(Line2D line)
 {
     Debug.WriteLine($"line added : {line.ToString()}");
     //this.GraphContainer.Children.Add(line.LineUI);
 }
Esempio n. 52
0
    // This checks if a line is inside a triangle (touching the triangle is allowed)
    // NOTE: We already know p1 is on an edge segment of the triangle
    private static bool LineInsideTriangle(EarClipVertex[] t, Vector2D p1, Vector2D p2)
    {
        float s01             = Line2D.GetSideOfLine(t[0].Position, t[1].Position, p2);
        float s12             = Line2D.GetSideOfLine(t[1].Position, t[2].Position, p2);
        float s20             = Line2D.GetSideOfLine(t[2].Position, t[0].Position, p2);
        float p2_on_edge      = 2.0f;   // somewhere outside the 0 .. 1 range
        float p1_on_same_edge = 2.0f;

        // Test if p2 is inside the triangle
        if ((s01 < 0.0f) && (s12 < 0.0f) && (s20 < 0.0f))
        {
            // Line is inside triangle, because p2 is
            return(true);
        }

        // Test if p2 is on an edge of the triangle and if it is we would
        // like to know where on the edge segment p2 is
        if (s01 == 0.0f)
        {
            p2_on_edge      = Line2D.GetNearestOnLine(t[0].Position, t[1].Position, p2);
            p1_on_same_edge = Line2D.GetSideOfLine(t[0].Position, t[1].Position, p1);
        }
        else if (s12 == 0.0f)
        {
            p2_on_edge      = Line2D.GetNearestOnLine(t[1].Position, t[2].Position, p2);
            p1_on_same_edge = Line2D.GetSideOfLine(t[1].Position, t[2].Position, p1);
        }
        else if (s20 == 0.0f)
        {
            p2_on_edge      = Line2D.GetNearestOnLine(t[2].Position, t[0].Position, p2);
            p1_on_same_edge = Line2D.GetSideOfLine(t[2].Position, t[0].Position, p1);
        }

        // Is p2 actually on the edge segment?
        if ((p2_on_edge >= 0.0f) && (p2_on_edge <= 1.0f))
        {
            // If p1 is on the same edge (or the unlimited line of that edge)
            // then the line is not inside this triangle.
            if (p1_on_same_edge == 0.0f)
            {
                return(false);
            }
        }

        // Do a complete line-triangle intersection test
        // We already know p1 is not inside the triangle (possibly on an edge)
        Line2D p = new Line2D(p1, p2);
        Line2D t01 = new Line2D(t[0].Position, t[1].Position);
        Line2D t12 = new Line2D(t[1].Position, t[2].Position);
        Line2D t20 = new Line2D(t[2].Position, t[0].Position);
        float  pu, pt;

        //mxd. Test intersections
        if (t01.GetIntersection(p, out pu, out pt))
        {
            return(true);
        }
        if (t12.GetIntersection(p, out pu, out pt))
        {
            return(true);
        }
        if (t20.GetIntersection(p, out pu, out pt))
        {
            return(true);
        }

        return(false);
    }
 public static vector_Coord2D Line2DToCoords(Line2D line, int nrCoords) {
   vector_Coord2D ret = new vector_Coord2D(VisionLabPINVOKE.Line2DToCoords__SWIG_1(Line2D.getCPtr(line), nrCoords), true);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Esempio n. 54
0
        /// <summary>
        /// 更新当前图形
        /// </summary>
        /// <param name="ms"></param>
        public override void Update()
        {
            List <Vector2D> points = new List <Vector2D>();

            if (Central != null)
            {
                if (this.central.IntersectPointStyle == 0)
                {
                    var v1 = new Vector2D(central.Point.X - 5 * KernelProperty.PixelToSize, central.Point.Y - 5 * KernelProperty.PixelToSize);
                    var v2 = new Vector2D(central.Point.X + 5 * KernelProperty.PixelToSize, central.Point.Y - 5 * KernelProperty.PixelToSize);
                    var v3 = new Vector2D(central.Point.X + 5 * KernelProperty.PixelToSize, central.Point.Y + 5 * KernelProperty.PixelToSize);
                    var v4 = new Vector2D(central.Point.X - 5 * KernelProperty.PixelToSize, central.Point.Y + 5 * KernelProperty.PixelToSize);
                    points.Add(v1);
                    points.Add(v2);
                    points.Add(v3);
                    points.Add(v4);
                    points.Add(v1);
                    base.Draw(points);
                }
                else if (this.central.IntersectPointStyle == 1)
                {
                    if (this.central.Line != null)
                    {
                        var Start  = this.central.Line.Start;
                        var End    = this.central.Line.End;
                        var Middle = central.Point;
                        //对直线矩形偏移
                        Line3D subline3d       = Line3D.Create(Vector3D.Create(Start.X, Start.Y, 0), Vector3D.Create(End.X, End.Y, 0));
                        var    offsetDirection = subline3d.Direction.Cross(Vector3D.BasisZ);
                        //获取偏移量
                        var offsetdir = Vector2D.Create(offsetDirection.X, offsetDirection.Y) * KernelProperty.PixToMM(KernelProperty.SublineOffset);

                        //冻结画笔,这样能加快绘图速度
                        DrawingContext dc = this.RenderOpen();
                        Pen.Freeze();
                        this.DashStyle      = new System.Windows.Media.DashStyle(new double[] { 5, 5 }, 10);
                        this.PenColor       = Colors.DeepSkyBlue;
                        this.Pen.EndLineCap = PenLineCap.Triangle;
                        var v1 = Start;
                        //添加偏移
                        var v2 = Start.Offset(offsetdir);
                        //绘制第一个线
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v1), KernelProperty.MMToPix(v2));
                        var v3 = Middle.Offset(offsetdir);
                        //第二个线
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v2), KernelProperty.MMToPix(v3));
                        //绘制文本
                        this.SetText(dc, Line2D.Create(v2, v3));
                        //绘制三个线竖线
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v3), KernelProperty.MMToPix(Middle));

                        var v4 = End.Offset(offsetdir);
                        //绘制第四个线
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v3), KernelProperty.MMToPix(v4));
                        this.SetText(dc, Line2D.Create(v3, v4));
                        //绘制第五个线
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v4), KernelProperty.MMToPix(End));


                        //绘制偏移的线

                        var v5 = new Vector2D(central.Point.X - 5 * KernelProperty.PixelToSize, central.Point.Y - 5 * KernelProperty.PixelToSize);
                        var v6 = new Vector2D(central.Point.X + 5 * KernelProperty.PixelToSize, central.Point.Y - 5 * KernelProperty.PixelToSize);
                        var v7 = new Vector2D(central.Point.X - 5 * KernelProperty.PixelToSize, central.Point.Y + 5 * KernelProperty.PixelToSize);
                        var v8 = new Vector2D(central.Point.X + 5 * KernelProperty.PixelToSize, central.Point.Y + 5 * KernelProperty.PixelToSize);
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v5), KernelProperty.MMToPix(v6));
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v6), KernelProperty.MMToPix(v7));
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v7), KernelProperty.MMToPix(v8));
                        dc.DrawLine(Pen, KernelProperty.MMToPix(v8), KernelProperty.MMToPix(v5));
                        dc.Close();
                    }
                }
                else if (this.central.IntersectPointStyle == 2)
                {
                    //冻结画笔,这样能加快绘图速度
                    DrawingContext dc = this.RenderOpen();
                    Pen.Freeze();
                    this.DashStyle      = new System.Windows.Media.DashStyle(new double[] { 5, 5 }, 10);
                    this.PenColor       = Colors.DeepSkyBlue;
                    this.Pen.EndLineCap = PenLineCap.Triangle;
                    if (this.central.Refences != null)
                    {
                        this.central.Refences.ForEach(x => {
                            dc.DrawLine(Pen, KernelProperty.MMToPix(x.Start), KernelProperty.MMToPix(x.End));
                        });
                    }

                    dc.Close();
                }
                else if (this.central.IntersectPointStyle == 3)
                {
                    DrawingContext dc = this.RenderOpen();
                    Pen.Freeze();
                }
            }
        }
 public static Coord2D NearestPoint(Line2D line, Coord2D p) {
   Coord2D ret = new Coord2D(VisionLabPINVOKE.NearestPoint(Line2D.getCPtr(line), Coord2D.getCPtr(p)), true);
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
Esempio n. 56
0
        /// <summary>
        /// Crop a polygon by a split line
        /// </summary>
        private static void CropPolygon(List <Vector2D> poly, Split split)
        {
            if (poly.Count == 0)
            {
                return;
            }
            Vector2D prev = poly[poly.Count - 1];

            float           side1 = (prev.y - split.pos.y) * split.delta.x - (prev.x - split.pos.x) * split.delta.y;
            List <Vector2D> newp  = new List <Vector2D>(poly.Count);

            for (int i = 0; i < poly.Count; i++)
            {
                // Fetch vertex and determine side
                Vector2D cur   = poly[i];
                float    side2 = (cur.y - split.pos.y) * split.delta.x - (cur.x - split.pos.x) * split.delta.y;

                // Front?
                if (side2 < -EPSILON)
                {
                    if (side1 > EPSILON)
                    {
                        // Split line with plane and insert the vertex
                        float u;
                        Line2D.GetIntersection(split.pos, split.pos + split.delta, prev.x, prev.y, cur.x, cur.y, out u, false);
                        Vector2D newv = prev + (cur - prev) * u;
                        newp.Add(newv);
                    }

                    newp.Add(cur);
                }
                // Back?
                else if (side2 > EPSILON)
                {
                    if (side1 < -EPSILON)
                    {
                        // Split line with plane and insert the vertex
                        float u;
                        Line2D.GetIntersection(split.pos, split.pos + split.delta, prev.x, prev.y, cur.x, cur.y, out u, false);
                        Vector2D newv = prev + (cur - prev) * u;
                        newp.Add(newv);
                    }
                }
                else
                {
                    // On the plane
                    newp.Add(cur);
                }

                // Next
                prev  = cur;
                side1 = side2;
            }
            poly.Clear();
            poly.AddRange(newp);

            // The code below would be more efficient, because it modifies the polygon in place...
            // but it has a bug, some polygons are corrupted.

            /*
             * bool prevremoved = false;
             * float prevside = (prev.y - split.pos.y) * split.delta.x - (prev.x - split.pos.x) * split.delta.y;
             * int i = 0;
             * while(i < poly.Count)
             * {
             *      Vector2D cur = poly[i];
             *      float curside = (cur.y - split.pos.y) * split.delta.x - (cur.x - split.pos.x) * split.delta.y;
             *
             *      // Point is in FRONT of the split?
             *      if(curside < -EPSILON)
             *      {
             *              if(prevside > EPSILON)
             *              {
             *                      // Previous point was BEHIND the split
             *                      // Line crosses the split, we need to add the intersection point
             *                      float u;
             *                      Line2D.GetIntersection(split.pos, split.pos + split.delta, prev.x, prev.y, cur.x, cur.y, out u);
             *                      Vector2D newv = prev + (cur - prev) * u;
             *                      poly.Insert(i, newv);
             *                      i++;
             *              }
             *              else if(prevside < -EPSILON)
             *              {
             *                      // Previous point was also in FRONT of the split
             *                      // We don't need to do anything
             *              }
             *              else
             *              {
             *                      // Previous point was ON the split
             *                      // If the previous point was removed, we have to add it again
             *                      if(prevremoved)
             *                      {
             *                              poly.Insert(i, prev);
             *                              i++;
             *                      }
             *              }
             *
             *              i++;
             *              prevremoved = false;
             *      }
             *      // Point is BEHIND the split?
             *      else if(curside > EPSILON)
             *      {
             *              if(prevside < -EPSILON)
             *              {
             *                      // Previous point was in FRONT of the split
             *                      // Line crosses the split, so we must add the intersection point
             *                      float u;
             *                      Line2D.GetIntersection(split.pos, split.pos + split.delta, prev.x, prev.y, cur.x, cur.y, out u);
             *                      Vector2D newv = prev + (cur - prev) * u;
             *                      poly.Insert(i, newv);
             *                      i++;
             *              }
             *              else if(prevside > EPSILON)
             *              {
             *                      // Previous point was also BEHIND the split
             *                      // We don't need to do anything, this point will be removed
             *              }
             *              else
             *              {
             *                      // Previous point was ON the split
             *                      // We don't need to do anything, this point will be removed
             *              }
             *
             *              poly.RemoveAt(i);
             *              prevremoved = true;
             *      }
             *      // Point is ON the split?
             *      else
             *      {
             *              if(prevside > EPSILON)
             *              {
             *                      // Previous point was BEHIND the split
             *                      // Remove this point
             *                      poly.RemoveAt(i);
             *                      prevremoved = true;
             *              }
             *              else if(prevside < -EPSILON)
             *              {
             *                      // Previous point was in FRONT of the split
             *                      // We want to keep this point
             *                      prevremoved = false;
             *                      i++;
             *              }
             *              else
             *              {
             *                      // Previous point is ON the split
             *                      // Only if the previous point was also removed, we remove this one as well
             *                      if(prevremoved)
             *                              poly.RemoveAt(i);
             *                      else
             *                              i++;
             *              }
             *      }
             *
             *      prev = cur;
             *      prevside = curside;
             * }
             */
        }
 public static int FindEdgeLine(DoubleImage image, XYCoord middle, XYCoord endLine, XYCoord endBox, int lineDistance, double outlierDistance, int nrIterations, Line2D line) {
   int ret = VisionLabPINVOKE.FindEdgeLine__SWIG_6(DoubleImage.getCPtr(image), XYCoord.getCPtr(middle), XYCoord.getCPtr(endLine), XYCoord.getCPtr(endBox), lineDistance, outlierDistance, nrIterations, Line2D.getCPtr(line));
   if (VisionLabPINVOKE.SWIGPendingException.Pending) throw VisionLabPINVOKE.SWIGPendingException.Retrieve();
   return ret;
 }
 internal static HandleRef getCPtr(Line2D obj)
 {
     return((obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr);
 }
 public StackedXYAreaRendererState([In] PlotRenderingInfo obj0)
   : base(obj0)
 {
   StackedXYAreaRenderer.StackedXYAreaRendererState areaRendererState = this;
   this.seriesArea = (Polygon) null;
   this.line = (Line2D) new Line2D.Double();
   this.lastSeriesPoints = new Stack();
   this.currentSeriesPoints = new Stack();
 }
Esempio n. 60
0
        public void RenderGeometry(DrawingContext2D drawingContext, AptContext context,
                                   Geometry shape, ItemTransform transform, Texture solidTexture)
        {
            CalculateTransform(ref transform, context);
            var matrix = transform.GeometryRotation;

            foreach (var e in shape.Entries)
            {
                switch (e)
                {
                case GeometryLines l:
                {
                    var color = l.Color.ToColorRgbaF() * transform.ColorTransform;
                    foreach (var line in l.Lines)
                    {
                        drawingContext.DrawLine(
                            Line2D.Transform(line, matrix),
                            l.Thickness,
                            color);
                    }
                    break;
                }

                case GeometrySolidTriangles st:
                {
                    var color = st.Color.ToColorRgbaF() * transform.ColorTransform;
                    foreach (var tri in st.Triangles)
                    {
                        if (solidTexture == null)
                        {
                            drawingContext.FillTriangle(
                                Triangle2D.Transform(tri, matrix),
                                color);
                        }
                        else
                        {
                            var destTri  = Triangle2D.Transform(tri, matrix);
                            var coordTri = new Triangle2D(new Vector2(tri.V0.X / 100.0f * solidTexture.Width,
                                                                      tri.V0.Y / 100.0f * solidTexture.Height),
                                                          new Vector2(tri.V1.X / 100.0f * solidTexture.Width,
                                                                      tri.V1.Y / 100.0f * solidTexture.Height),
                                                          new Vector2(tri.V2.X / 100.0f * solidTexture.Width,
                                                                      tri.V2.Y / 100.0f * solidTexture.Height));

                            drawingContext.FillTriangle(
                                solidTexture,
                                coordTri,
                                destTri,
                                new ColorRgbaF(1.0f, 1.0f, 1.0f, color.A));
                        }
                    }
                    break;
                }

                case GeometryTexturedTriangles tt:
                {
                    var coordinatesTransform = new Matrix3x2
                    {
                        M11 = tt.RotScale.M11,
                        M12 = tt.RotScale.M12,
                        M21 = tt.RotScale.M21,
                        M22 = tt.RotScale.M22,
                        M31 = tt.Translation.X,
                        M32 = tt.Translation.Y
                    };

                    foreach (var tri in tt.Triangles)
                    {
                        //if (assignment is RectangleAssignment)
                        //    throw new NotImplementedException();

                        var tex = context.GetTexture(tt.Image, shape);

                        drawingContext.FillTriangle(
                            tex,
                            Triangle2D.Transform(tri, coordinatesTransform),
                            Triangle2D.Transform(tri, matrix),
                            transform.ColorTransform);
                    }
                    break;
                }
                }
            }
        }