예제 #1
0
        /// <summary>
        /// Splits segmentToSplit in two based on iLocation.
        /// First new segment will be added to diced, and second new segment will be returned.
        /// If split doesn't happen, segmentToSplit will be returned.
        /// </summary>
        private static Segment SplitHelper(Segment segmentToSplit, Vector3D iLocation, Polygon diced, List <IntersectionPoint> iPoints)
        {
            List <Segment> split;

            if (segmentToSplit.Split(iLocation, out split))
            {
                Debug.Assert(split.Count == 2);
                diced.Segments.Add(split[0]);

                IntersectionPoint iPoint = new IntersectionPoint();
                iPoint.Location = iLocation;
                iPoint.Index    = diced.Segments.Count;
                iPoints.Add(iPoint);

                return(split[1]);
            }
            else
            {
                // We were presumably at an endpoint.
                // Add to iPoints list only if it was the starting endpoint.
                // (This will avoid duplicate entries).
                if (iLocation.Compare(segmentToSplit.P1))
                {
                    IntersectionPoint iPoint = new IntersectionPoint();
                    iPoint.Location = iLocation;
                    iPoint.Index    = diced.Segments.Count;
                    iPoints.Add(iPoint);
                }

                return(segmentToSplit);
            }
        }
예제 #2
0
        /// <inheritdoc cref="NotuiElement"/>
        public override IntersectionPoint PureHitTest(Touch touch, bool prevpos, out IntersectionPoint persistentIspoint)
        {
            var intersection = PreparePlanarShapeHitTest(touch, prevpos);
            var phit         = intersection != null;

            if (!phit)
            {
                persistentIspoint = null;
                return(null);
            }

            //TODO: Ugly as f**k, fix phase like a human being
            var uvpos = Coordinates.RectToPolar(Vector2.Transform(intersection.ElementSpace.xy(), Matrix3x2.CreateRotation((float)Math.PI)));
            var d     = uvpos.Y;

            uvpos.X = uvpos.X / (float)Math.PI;
            uvpos.Y = uvpos.Y * 4 - 1;
            intersection.SurfaceSpace = new Vector3(uvpos, 0);

            var str = Matrix4x4.CreateWorld(intersection.ElementSpace, Vector3.UnitZ,
                                            -Vector3.Normalize(intersection.ElementSpace));

            intersection.WorldSurfaceTangentTransform = str * DisplayMatrix;

            persistentIspoint = intersection;
            return(d < 0.5 ? intersection : null);
        }
 public VertexEv(IntersectionPoint I)
 {
     v     = I.P;
     edge  = I.Edge1;
     edge2 = I.Edge2;
     type  = vType.INTERSECT;
 }
예제 #4
0
        /// <summary>
        /// Determine points where an extruded line consisting of segments intersect, as well as the neighbouring pairs of those intersection points that serve as endpoints for chunks of extruded points that lie between intersections.
        /// </summary>
        /// <param name="extrudedPointList">The extruded points.</param>
        /// <param name="intersectionPoints">The intersection points.</param>
        /// <param name="chunkIntersectionEndpoints">Pairs of neighbouring intersection points, acting as chunk endpoints.</param>
        internal static void FindIntersectionPointsAndChunkEndpoints(SegmentwiseExtrudedPointListUV extrudedPointList, out List <IntersectionPoint> intersectionPoints, out List <IntersectionPointPair> chunkIntersectionEndpoints)
        {
            intersectionPoints = DetermineIntersectionPoints(extrudedPointList);

            var extrudedPoints = extrudedPointList.Points;

            chunkIntersectionEndpoints = new List <IntersectionPointPair>();
            var firstExtrudedPoint = extrudedPoints[0];
            var lastExtrudedPoint  = extrudedPoints[extrudedPoints.Count - 1];
            var firstExtrudedPointAsIntersection = new IntersectionPoint(firstExtrudedPoint, firstExtrudedPoint, firstExtrudedPoint);
            var lastExtrudedPointAsIntersection  = new IntersectionPoint(lastExtrudedPoint, lastExtrudedPoint, lastExtrudedPoint);

            if (intersectionPoints.Count > 0)
            {
                chunkIntersectionEndpoints.Add(new IntersectionPointPair(firstExtrudedPointAsIntersection, intersectionPoints[0]));
                for (int i = 0; i < intersectionPoints.Count - 1; i++)
                {
                    chunkIntersectionEndpoints.Add(new IntersectionPointPair(intersectionPoints[i], intersectionPoints[i + 1]));
                }
                chunkIntersectionEndpoints.Add(new IntersectionPointPair(intersectionPoints[intersectionPoints.Count - 1], lastExtrudedPointAsIntersection));
            }
            else
            {
                chunkIntersectionEndpoints.Add(new IntersectionPointPair(firstExtrudedPointAsIntersection, lastExtrudedPointAsIntersection));
            }
            intersectionPoints.Insert(0, firstExtrudedPointAsIntersection);
            intersectionPoints.Add(lastExtrudedPointAsIntersection);
        }
예제 #5
0
        /// <summary>
        /// given an interesect point p definition, determines the actual interpolated intersect point.
        /// </summary>
        /// <param name="p">IntersectionPoint to find interpolated intersection point for.</param>
        /// <param name="level">the relevant contour plane level.</param>
        /// <returns>actual interpolated intersect point corresponding to p.</returns>
        private static Pair <double, double> Interpolate(IntersectionPoint p, double level)
        {
            double p_x = p.Col;
            double p_y = p.Row;

            if (p.Type == IntersectionPoint.IntersectionType.Horizontal)
            {
                if (p.Col != _grid.GetLength(1) - 1)
                {
                    p_y = p.Row;
                    Debug.Assert(
                        (_grid[p.Row, p.Col] >= level && _grid[p.Row, p.Col + 1] < level) ||
                        (_grid[p.Row, p.Col] < level && _grid[p.Row, p.Col + 1] >= level));
                    double prop = (level - _grid[p.Row, p.Col]) / (_grid[p.Row, p.Col + 1] - _grid[p.Row, p.Col]);
                    p_x = p.Col + prop;
                }
            }
            else
            {
                if (p.Row != _grid.GetLength(0) - 1)
                {
                    p_x = p.Col;
                    Debug.Assert(
                        (_grid[p.Row, p.Col] >= level && _grid[p.Row + 1, p.Col] < level) ||
                        (_grid[p.Row, p.Col] < level && _grid[p.Row + 1, p.Col] >= level));
                    double prop = (level - _grid[p.Row, p.Col]) / (_grid[p.Row + 1, p.Col] - _grid[p.Row, p.Col]);
                    p_y = p.Row + prop;
                }
            }

            return(new Pair <double, double>(p_x, p_y));
        }
예제 #6
0
    /**
     * Split this triangle
     **/
    public void Split(IntersectionPoint[] intersectionPoints, out Triangle[] splitTriangles)
    {
        if (intersectionPoints[0].m_isTriangleVertex)
        {
            Vector3[] t1Vertices = new Vector3[3];
            t1Vertices[0] = intersectionPoints[0].m_point;
            t1Vertices[1] = GetCWNextVertex(intersectionPoints[0].m_edgeIndex);
            t1Vertices[2] = intersectionPoints[1].m_point;
            Triangle t1 = new Triangle(t1Vertices);

            Vector3[] t2Vertices = new Vector3[3];
            t2Vertices[0] = GetCWPreviousVertex(intersectionPoints[0].m_edgeIndex); //previous vertex
            t2Vertices[1] = intersectionPoints[0].m_point;
            t2Vertices[2] = intersectionPoints[1].m_point;
            Triangle t2 = new Triangle(t2Vertices);

            splitTriangles    = new Triangle[2];
            splitTriangles[0] = t1;
            splitTriangles[1] = t2;
        }
        else
        {
            //sort intersection points in ascending order so their edgeIndex are consecutive
            if (intersectionPoints[0].m_edgeIndex == intersectionPoints[1].m_edgeIndex + 1 || intersectionPoints[0].m_edgeIndex == 0 && intersectionPoints[1].m_edgeIndex == 2)
            {
                IntersectionPoint tmp = intersectionPoints[0];
                intersectionPoints[0] = intersectionPoints[1];
                intersectionPoints[1] = tmp;
            }

            Vector3[] t1Vertices = new Vector3[3];
            t1Vertices[0] = intersectionPoints[0].m_point;
            t1Vertices[1] = GetCWNextVertex(intersectionPoints[0].m_edgeIndex);
            t1Vertices[2] = intersectionPoints[1].m_point;
            Triangle t1 = new Triangle(t1Vertices);

            Vector3[] t2Vertices = new Vector3[3];
            t2Vertices[0] = m_points[intersectionPoints[0].m_edgeIndex];
            t2Vertices[1] = intersectionPoints[0].m_point;
            t2Vertices[2] = intersectionPoints[1].m_point;
            Triangle t2 = new Triangle(t2Vertices);

            Vector3[] t3Vertices = new Vector3[3];
            t3Vertices[0] = m_points[intersectionPoints[0].m_edgeIndex];
            t3Vertices[1] = intersectionPoints[1].m_point;
            t3Vertices[2] = GetCWNextVertex(intersectionPoints[1].m_edgeIndex);
            Triangle t3 = new Triangle(t3Vertices);

            //if (t1.IsFlat() ||
            //    t2.IsFlat() ||
            //    t3.IsFlat())
            //    Debug.Log("flat");

            splitTriangles    = new Triangle[3];
            splitTriangles[0] = t1;
            splitTriangles[1] = t2;
            splitTriangles[2] = t3;
        }
    }
예제 #7
0
 public StreetLine(IntersectionPoint a, IntersectionPoint b)
 {
     InterPointA = a;
     InterPointB = b;
     AOnRim      = false;
     BOnRim      = false;
     Length      = Vector2.Distance(a.Position, b.Position);
     Dir         = (B - A).normalized;
 }
예제 #8
0
    IntersectionPoint SplitStreetLine(StreetLine line, Vector2 point)
    {
        //replaces line with 2 lines with one shared intersection
        placed.Remove(line);
        IntersectionPoint inter = new IntersectionPoint(point);

        placed.Add((line.AOnRim) ? new StreetLine(line.A, inter) : new StreetLine(line.InterPointA, inter));
        placed.Add((line.BOnRim) ? new StreetLine(inter, line.B) : new StreetLine(inter, line.InterPointB));
        return(inter);
    }
예제 #9
0
 public void ReEnable()
 {
     _startPos = _cb.PolygonCenter;
     _endPos   = _cb.PolygonCenter;
     _intersectionPoints.Clear();
     _lastIntersectionPoint  = IntersectionPoint.zero;
     _trailrenderer.emitting = false;
     _isEnabled = true;
     _polygon   = _cb.ToArray();
 }
 public override string ToString()
 {
     return(Index.ToString()
            + ": "
            + IntersectionPoint.ToString()
            + ", Distance = "
            + DistanceToStart.ToString()
            + ", Orientation = "
            + Orientation.ToString());
 }
예제 #11
0
 /// <summary>
 /// removes the interesection point p from _horizontalInteresects or
 /// _verticalInteresects array.
 /// </summary>
 /// <param name="p">point to remove from interesects arrays</param>
 private static void ForgetPoint(IntersectionPoint p)
 {
     if (p.Type == IntersectionPoint.IntersectionType.Horizontal)
     {
         _horizontalIntersects[p.Row, p.Col] = false;
     }
     else
     {
         _verticalIntersects[p.Row, p.Col] = false;
     }
 }
예제 #12
0
    private void MoveBlade()
    {
        Vector3 position = Input.mousePosition;

        position.z         = _distanceFromCam - 0.5f;
        position           = _mainCam.ScreenToWorldPoint(position);
        transform.position = position;

        _circle.UpdatePosition(position);

        bool isOutside     = (Mathematics.PointInPolygon(position, _polygon) ? false : true);
        var  intersections = _circle.GetIntersections(_polygon);

        if (_lastIntersectionPoint != IntersectionPoint.zero &&
            Physics2D.Linecast(_lastIntersectionPoint.Pos, position, obstacleLayer) && !isOutside &&
            position != Vector3.zero)
        {
            _LM.CollidedWithObject();
            _isEnabled = false;
        }

        Touch[] touch = Input.touches;

        if (_isEnabled && Input.GetMouseButton(0) && touch.Length < 2)
        {
            _startPos   = _endPos;
            _endPos     = position;
            _currentPos = position;
            if (!_trailrenderer.emitting)
            {
                _trailrenderer.Clear();
                _trailrenderer.emitting = true;
            }


            if (_startPos != _cb.PolygonCenter && _endPos != _cb.PolygonCenter)
            {
                NewIntersections(_startPos, _endPos);
                Cut();
            }

            if (isOutside)
            {
                _lastIntersectionPoint = IntersectionPoint.zero;
            }
        }
        else
        {
            _startPos = _cb.PolygonCenter;
            _endPos   = _cb.PolygonCenter;
            _lastIntersectionPoint  = IntersectionPoint.zero;
            _trailrenderer.emitting = false;
        }
    }
예제 #13
0
        /// <inheritdoc cref="NotuiElement"/>
        public override IntersectionPoint PureHitTest(Touch touch, bool prevpos, out IntersectionPoint persistentIspoint)
        {
            touch.GetPreviousWorldPosition(Context, out var popos, out var pdir);
            var sizetr = Matrix4x4.CreateScale(Size);
            //var invsizetr = Matrix4x4.CreateScale(Vector3.One/Size);
            var scldisp = sizetr * DisplayMatrix;

            Matrix4x4.Invert(scldisp, out var invdispmat);
            var trelpos = Vector3.Transform(prevpos ? popos : touch.WorldPosition, invdispmat);
            var treldir = Vector3.TransformNormal(prevpos ? pdir : touch.ViewDir, invdispmat);

            IntersectionPoint ispoint = null;
            float             d       = float.MaxValue;

            for (int i = 0; i < 6; i++)
            {
                var pmat = Matrix4x4.CreateWorld(_planeCenters[i] * -0.5f, _planeCenters[i], _planeUps[i]);
                var hit  = Intersections.PlaneRay(trelpos, treldir, pmat, out var aispos, out var pispos);
                if (!hit)
                {
                    continue;
                }
                hit = pispos.X <= 0.5 && pispos.X >= -0.5 &&
                      pispos.Y <= 0.5 && pispos.Y >= -0.5;
                if (!hit)
                {
                    continue;
                }
                var diff = aispos - trelpos;
                if (Vector3.Dot(Vector3.Normalize(diff), treldir) < 0)
                {
                    continue;
                }
                if (diff.Length() >= d)
                {
                    continue;
                }

                var locmat = pmat * scldisp;

                //TODO: create a more analitical method for scale correction, this is dumb
                Matrix4x4.Decompose(locmat, out var locscl, out var qdummy, out var tdummy);
                var invlocscl = Vector3.One / (locscl / DisplayTransformation.Scale);

                var smat = Matrix4x4.CreateScale(invlocscl) * Matrix4x4.CreateTranslation(pispos) * locmat;
                ispoint = new IntersectionPoint(Vector3.Transform(aispos, scldisp), aispos, pispos, smat, this, touch);
                d       = diff.Length();
            }

            persistentIspoint = ispoint;
            return(ispoint);
        }
        // ToDo: Implement role to UpdateGraphicsCanExecute() execute
        public bool UpdateGraphicsCanExecute(object parameter)
        {
            IntersectionPoint intersectionPoint = parameter as IntersectionPoint;

            if (intersectionPoint != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #15
0
        /// <summary>
        /// Get a pair of intersection points.
        /// </summary>
        private static void GetPairPoints(List <IntersectionPoint> iPoints, int pair, bool increment,
                                          out IntersectionPoint iPoint1, out IntersectionPoint iPoint2)
        {
            int idx1 = pair * 2;
            int idx2 = pair * 2 + 1;

            if (!increment)
            {
                Utils.Swap <int>(ref idx1, ref idx2);
            }

            iPoint1 = iPoints[idx1];
            iPoint2 = iPoints[idx2];
        }
예제 #16
0
        /// <inheritdoc cref="NotuiElement"/>
        public override IntersectionPoint PureHitTest(Touch touch, bool prevpos, out IntersectionPoint persistentIspoint)
        {
            persistentIspoint = null;
            touch.GetPreviousWorldPosition(Context, out var popos, out var pdir);
            var invdispmat = InverseDisplayMatrix;
            var trelpos    = Vector3.Transform(prevpos ? popos : touch.WorldPosition, invdispmat);
            var treldir    = Vector3.TransformNormal(prevpos ? pdir : touch.ViewDir, invdispmat);
            var a          = Vector3.Dot(treldir, treldir);
            var b          = 2 * Vector3.Dot(treldir, trelpos);
            var c          = Vector3.Dot(trelpos, trelpos) - 1;

            if (!SolveQuadratic(a, b, c, out var t0, out var t1))
            {
                return(null);
            }

            if (t0 > t1)
            {
                var tt = t0; t0 = t1; t1 = tt;
            }

            if (t0 < 0)
            {
                t0 = t1;
                if (t0 < 0)
                {
                    return(null);
                }
            }

            var rispos = treldir * t0 + trelpos;
            var aispos = Vector3.Transform(rispos, DisplayMatrix);

            var zd = Vector3.Normalize(rispos);
            var xd = Vector3.Cross(zd, Vector3.UnitY);
            var yd = Vector3.Cross(xd, zd);

            var uvpos = Coordinates.RectToPolar(rispos.xz());

            uvpos.X = uvpos.X / (float)Math.PI - 1;
            uvpos.Y = rispos.Y;

            var ismat   = Matrix4x4.CreateWorld(aispos, -Vector3.TransformNormal(zd, DisplayMatrix), Vector3.TransformNormal(yd, DisplayMatrix));
            var ispoint = new IntersectionPoint(aispos, rispos, new Vector3(uvpos, 0), ismat, this, touch);

            persistentIspoint = ispoint;
            return(ispoint);
        }
예제 #17
0
        /// <inheritdoc cref="NotuiElement"/>
        public override IntersectionPoint PureHitTest(Touch touch, bool prevpos, out IntersectionPoint persistentIspoint)
        {
            var intersection = PreparePlanarShapeHitTest(touch, prevpos);
            var phit         = intersection != null;

            if (!phit)
            {
                persistentIspoint = null;
                return(null);
            }
            var hit = intersection.ElementSpace.X <= 0.5 && intersection.ElementSpace.X >= -0.5 &&
                      intersection.ElementSpace.Y <= 0.5 && intersection.ElementSpace.Y >= -0.5;

            persistentIspoint = intersection;
            return(hit ? intersection : null);
        }
        public static IEnumerable <List <Vector3> > Decompose(IList <Vector3> poly)
        {
            Queue <List <Vector3> > Q = new Queue <List <Vector3> >();

            Q.Enqueue(new List <Vector3>(poly));

            while (Q.Count != 0)
            {
                List <Vector3> P = Q.Dequeue();

                IntersectionPoint I = oneIntersection(P);

                if (I != null)           // decompose p into p1 and p2

                //Debug.LogWarning("INTERSECTION=" + I.P);

                {
                    List <Vector3> p1 = new List <Vector3>();
                    List <Vector3> p2 = new List <Vector3>();

                    // p1
                    for (int i = 0; i <= I.Edge1; ++i)
                    {
                        p1.Add(P[i]);
                    }
                    p1.Add(I.P);
                    for (int i = I.Edge2 + 1; i < P.Count; ++i)
                    {
                        p1.Add(P[i]);
                    }

                    //P2
                    p2.Add(I.P);
                    for (int i = I.Edge1 + 1; i <= I.Edge2; ++i)
                    {
                        p2.Add(P[i]);
                    }

                    Q.Enqueue(p1);
                    Q.Enqueue(p2);
                }
                else             // P is simple
                {
                    yield return(P);
                }
            }
        }
예제 #19
0
파일: Game.cs 프로젝트: sKanoodle/breakout
        private void Bounce(List <Tuple <LineSegment, Brick> > boundaries, Tuple <LineSegment, Brick> removedElement = null)
        {
            IntersectionPoint intersectionPoint = CalculateIntersection(boundaries);

            if (intersectionPoint == null)
            {
                return;
            }

            Tuple <LineSegment, Brick> boundary = boundaries[intersectionPoint.Index1];

            //remove the element the ball bounced on
            boundaries.RemoveAt(intersectionPoint.Index1);

            if (Ball.Kind != Ball.Kinds.Lava || intersectionPoint.Brick1 == null)
            {
                Reflect(intersectionPoint, boundary);
            }

            //delete the brick in case ball bounced off of one
            if (intersectionPoint.Brick1 != null)
            {
                if (RemoveBrickAndCheckPowerUp(intersectionPoint.Brick1, boundaries))
                {
                    boundary = null;
                }
                if (intersectionPoint.Brick2 != null)
                {
                    RemoveBrickAndCheckPowerUp(intersectionPoint.Brick2, boundaries);
                }
            }

            //ball landed directly on border, no further checks needed
            if (intersectionPoint.Distance == 0)
            {
                return;
            }

            //add removed element from last iteration in case ball would bounce twice from one wall during one movement
            if (removedElement != null)
            {
                boundaries.Add(removedElement);
            }

            Ball.Direction *= intersectionPoint.Distance;
            Bounce(boundaries, boundary);
        }
예제 #20
0
 public Intersection(IntersectionPoint interPoint, float elev, float sidewalkHeight)
 {
     Point = interPoint;
     Point.SetCorrespondingIntersection(this);
     Elevation           = elev;
     this.sidewalkHeight = sidewalkHeight;
     Corners             = new List <IntersectionCorner>();
     Position            = new Vector3(Point.Position.x, elev, Point.Position.y);
     for (int i = 0; i < Point.Corners.Count; i++)
     {
         Corners.Add(new IntersectionCorner(new Vector3(Point.Corners[i].x, elev, Point.Corners[i].y)));
     }
     if (Corners.Count != 4)
     {
         DB.Error("Invalid number of Corners in Intersection.");
     }
 }
예제 #21
0
        /// <summary>
        /// Traza el rayo con los parametros establecidos.
        /// </summary>
        /// <returns>Devuelve el cuerpo con el que impacta.</returns>
        /// <remarks>La propiedad Hit devuelve el punto de impacto exacto del rayo.</remarks>
        public Body Trace()
        {
            // Recorremos los cuerpos que esten dentro del area definida por la diagonal del rayo:
            List <Line> lines = new List <Line>();

            foreach (Body b in this.GetBodiesInArea(this.ComputeRayArea()))
            {
                // Añadimos las lineas del cuerpo a la lista a evaluar:
                lines.Add(new Line(new Vector2(b.Bounds.Left, b.Bounds.Top), new Vector2(b.Bounds.Right, b.Bounds.Top), b));
                lines.Add(new Line(new Vector2(b.Bounds.Left, b.Bounds.Top), new Vector2(b.Bounds.Left, b.Bounds.Bottom), b));
                lines.Add(new Line(new Vector2(b.Bounds.Right, b.Bounds.Top), new Vector2(b.Bounds.Right, b.Bounds.Bottom), b));
                lines.Add(new Line(new Vector2(b.Bounds.Left, b.Bounds.Bottom), new Vector2(b.Bounds.Right, b.Bounds.Bottom), b));
            }

            // Obtenemos todos los puntos de corte que haya en el trazado del rayo:
            List <IntersectionPoint> points = new List <IntersectionPoint>(); Vector2?ret;

            foreach (Line line in lines)
            {
                ret = MathTools.IntersectLines(this.Source, this.Hit, line.a, line.b);
                if (ret != null)
                {
                    points.Add(new IntersectionPoint((Vector2)ret, Vector2.Distance(this.Source, (Vector2)ret), line.hitBody));
                }
            }

            // Si existen puntos de interseccion obtenemos el mas cercano:
            if (points.Count > 0)
            {
                IntersectionPoint near = points[0];
                foreach (IntersectionPoint p in points)
                {
                    if (p.distance < near.distance)
                    {
                        near = p;
                    }
                }
                this.Hit = near.p;      // Marcamos el impacto con el punto de interseccion mas cercano.
                return(near.hitBody);   // Devolvemos el cuerpo de impacto mas cercano.
            }
            else // Si no hay puntos de corte devolvemos null y mantenemos el punto mas lejano del rayo como impacto:
            {
                return(null);
            }
        }
예제 #22
0
        private static bool intersectsProhAreaPoint(List <LineP> penaltyZones, LineP data, out bool changedState, out IntersectionPoint ip)
        {
            changedState = false;
            bool result = false;

            ip = new IntersectionPoint();
            foreach (LineP nl in penaltyZones)
            {
                IntersectionPoint ip1 = new IntersectionPoint();
                if (getIntersection(data, nl, out ip1))
                {
                    ip           = ip1;
                    result       = true;
                    changedState = !changedState;
                }
            }
            return(result);
        }
예제 #23
0
        private static bool intersectsOwnChannel(List <LineP> ownChannel, LineP data, out bool changedState, out IntersectionPoint ip)
        {
            changedState = false;
            bool result = false;

            ip = new IntersectionPoint();
            foreach (LineP nl in ownChannel)
            {
                IntersectionPoint ip1 = new IntersectionPoint();
                if (getIntersection(data, nl, out ip1))
                {
                    ip           = ip1;
                    result       = true;
                    changedState = !changedState;
                }
            }
            return(result);
        }
예제 #24
0
파일: Game.cs 프로젝트: sKanoodle/breakout
        private IntersectionPoint CalculateIntersection(List <Tuple <LineSegment, Brick> > boundaries)
        {
            Vector2 newPosition = Ball.Position + Ball.Direction;

            //perform collision checks and give out closest border
            var intersections = boundaries
                                .Select((l, i) =>
            {
                float distance;
                Vector2?point = Utils.GetIntersectionPoint(new LineSegment()
                {
                    StartPosition = newPosition, EndPosition = Ball.Position
                }, l.Item1, out distance);
                return(new IntersectionPoint(distance, point, i, l.Item2));
            })
                                .Where(i => i.Point.HasValue == true)
                                .OrderByDescending(i => i.Distance)
                                .GroupBy(i => i.Brick1)
                                .Select(g => g.First())
                                .ToArray();

            //no intersection
            if (intersections.Length < 1)
            {
                Ball.Position = newPosition;
                return(null);
            }

            IntersectionPoint firstIntersection = intersections[0];

            if (intersections.Length == 1)
            {
                return(firstIntersection);
            }

            IntersectionPoint secondIntersection = intersections[1];

            if (firstIntersection.Distance == secondIntersection.Distance)
            {
                firstIntersection.Index2 = secondIntersection.Index1;
                firstIntersection.Brick2 = secondIntersection.Brick1;
            }
            return(firstIntersection);
        }
예제 #25
0
        /// <inheritdoc cref="NotuiElement"/>
        public override IntersectionPoint PureHitTest(Touch touch, bool prevpos, out IntersectionPoint persistentIspoint)
        {
            if (Vertices.Count < 3)
            {
                persistentIspoint = null;
                return(null);
            }

            persistentIspoint = PreparePlanarShapeHitTest(touch, prevpos);
            var phit = persistentIspoint != null;

            if (!phit)
            {
                return(null);
            }

            var vold = Vertices[Vertices.Count - 1];
            var vt   = persistentIspoint.ElementSpace.xy();
            var hit  = false;

            foreach (var vnew in Vertices)
            {
                Vector2 v1, v2;
                if (vnew.X > vold.X)
                {
                    v1 = vold;
                    v2 = vnew;
                }
                else
                {
                    v1 = vnew;
                    v2 = vold;
                }

                if ((vnew.X < vt.X == vt.X <= vold.X) && (vt.Y - v1.Y) * (v2.X - v1.X) < (v2.Y - v1.Y) * (vt.X - v1.X))
                {
                    hit = !hit;
                }
                vold = vnew;
            }
            return(hit ? persistentIspoint : null);
        }
예제 #26
0
        /// <inheritdoc cref="NotuiElement"/>
        public override IntersectionPoint PureHitTest(Touch touch, bool prevpos, out IntersectionPoint persistentIspoint)
        {
            var intersection = PreparePlanarShapeHitTest(touch, prevpos);
            var phit         = intersection != null;

            if (!phit)
            {
                persistentIspoint = null;
                return(null);
            }
            //var polar = Coordinates.RectToPolar(intersection.ElementSpace.xy());
            //polar.X = (float)Math.PI + (polar.X - Phase * (float)Math.PI*2) * Math.Sign(Cycles);
            var rad  = Math.Max(HoleRadius, 1);
            var hrad = Math.Min(HoleRadius, 1);

            var uvpos = Coordinates.RectToPolar(
                Vector2.Transform(
                    intersection.ElementSpace.xy(),
                    Matrix3x2.CreateRotation((-Phase + 0.5f) * 2.0f * (float)Math.PI)
                    )
                );

            uvpos.X = Cycles > 0 ?
                      (float)VMath.Map(uvpos.X / (float)Math.PI, -1, Cycles * 2 - 1, -1, 1, TMapMode.Float) :
                      (float)VMath.Map(uvpos.X / (float)Math.PI, 1, 1 + Cycles * 2, -1, 1, TMapMode.Float);

            uvpos.Y = HoleRadius > 1 ?
                      (float)VMath.Map(uvpos.Y * 2, hrad, rad, -1, 1, TMapMode.Float) :
                      (float)VMath.Map(uvpos.Y * 2, hrad, rad, 1, -1, TMapMode.Float);
            intersection.SurfaceSpace = new Vector3(uvpos, 0);

            var str = Matrix4x4.CreateWorld(intersection.ElementSpace, Vector3.UnitZ,
                                            -Vector3.Normalize(intersection.ElementSpace));

            intersection.WorldSurfaceTangentTransform = str * DisplayMatrix;

            //var hit = polar.Y * 2 < rad && polar.Y * 2 >= hrad && (polar.X + Math.PI) % (Math.PI * 2) <= Math.Abs(Cycles * Math.PI * 2);
            var hit = uvpos.X > -1 && uvpos.X <1 && uvpos.Y> -1 && uvpos.Y < 1;

            persistentIspoint = intersection;
            return(hit ? intersection : null);
        }
예제 #27
0
        /// <summary>
        /// Generates all contour lines for a particular contour level (may be in more than
        /// one group).
        /// </summary>
        /// <param name="level">contour level to create lines for.</param>
        private static void GenerateLevel(double level)
        {
            // first index is row, second index is column.
            //
            //   ._._._.
            //   | | | |
            //
            //  horizontal intersects refer to line to right of grid point.
            //  vertical intersects refer to line to bottom of grid point.

            GenerateIntersectArrays(level);

            while (true)
            {
                IntersectionPoint p = FindUnusedIntersection(true);
                if (p == null)
                {
                    break;
                }

                _group += 1;

                Stack <IntersectionPoint> yetToFollow = new Stack <IntersectionPoint>();
                while (true)
                {
                    List <IntersectionPoint> neighbours = FindNeighbours(p);
                    foreach (IntersectionPoint pnt in neighbours)
                    {
                        yetToFollow.Push(pnt);
                    }
                    CreateLineSegments(p, neighbours, level);
                    ForgetPoint(p);

                    if (yetToFollow.Count == 0) // optimize this.
                    {
                        break;
                    }
                    p = yetToFollow.Pop();
                }
            }
        }
예제 #28
0
    private static void AddIntersectionPoints(
        List <Vector3> first,
        List <Vector3> second,
        List <IntersectionPoint> firstIntersections,
        List <IntersectionPoint> secondIntersections)
    {
        for (int i = 0; i < first.Count - 1; i++)
        {
            var a1 = first[i];
            var a2 = first[i + 1];
            for (int j = 0; j < second.Count - 1; j++)
            {
                var b1    = second[j];
                var b2    = second[j + 1];
                var point = LineIntersect(a1, a2, b1, b2);
                if (point.result > 0)
                {
                    var ind = firstIntersections.FindIndex((el) => { return(el.originalListPos == i); });
                    ind++;
                    while (!firstIntersections[ind].stable &&
                           Vector3.Magnitude(firstIntersections[ind].position - a1) > Vector3.Magnitude(point.point - a1))
                    {
                        ind++;
                    }

                    var ind2 = firstIntersections.FindIndex((el) => { return(el.originalListPos == i); });
                    ind2++;
                    while (!secondIntersections[ind2].stable &&
                           Vector3.Magnitude(secondIntersections[ind].position - b1) > Vector3.Magnitude(point.point - b1))
                    {
                        ind2++;
                    }

                    IntersectionPoint interPoint = new IntersectionPoint(point.point, true, false, -1);
                    firstIntersections.Insert(ind, interPoint);
                    secondIntersections.Insert(ind2, interPoint);
                }
            }
        }
    }
예제 #29
0
        /// <summary>
        /// Inserts values into the _lineGroupLevels and _lineGroups arrays.
        /// </summary>
        /// <param name="p1">from point</param>
        /// <param name="ps">to points</param>
        /// <param name="level">the contour level these line segments correspond to</param>
        private static void CreateLineSegments(IntersectionPoint p1, List <IntersectionPoint> ps, double level)
        {
            for (int i = 0; i < ps.Count; ++i)
            {
                IntersectionPoint     p2  = ps[i];
                Pair <double, double> p1i = Interpolate(p1, level);
                Pair <double, double> p2i = Interpolate(p2, level);
                if (_group != _lastGroup)
                {
                    _lastGroup = _group;
                    _lineGroupLevels.Add(level);
                    _lineGroups.Add(new List <LineSegment>());
                }
                else if (_lineGroups.Count == 0) // this was a quick fix, need to invsetigate why it was happening.
                {
                    _lineGroupLevels.Add(level);
                    _lineGroups.Add(new List <LineSegment>());
                }

                _lineGroups[_lineGroups.Count - 1].Add(new LineSegment(p1i.First, p1i.Second, p2i.First, p2i.Second));
            }
        }
예제 #30
0
    private bool isIntersectionLineInPolygon(IntersectionPoint tempPoint1, IntersectionPoint tempPoint2)
    {
        Vector3 point1 = tempPoint1.Pos;
        Vector3 point2 = tempPoint2.Pos;

        Vector3 center = (point1 + point2) / 2f;

        Matrix4x4 scaleMatrix = Mathematics.ScaleMatrix(0.5f);

        point1 = scaleMatrix.MultiplyPoint(point1);
        point2 = scaleMatrix.MultiplyPoint(point2);

        Vector3 scaledCenter = (point1 + point2) / 2f;

        Matrix4x4 transMatrix = Mathematics.TranslateMatrix(center - scaledCenter);

        point1 = transMatrix.MultiplyPoint(point1);
        point2 = transMatrix.MultiplyPoint(point2);

        int edgesHit = Physics2D.LinecastAll(point1, point2).Length;

        RaycastHit2D[] edgesHitUnscaled = Physics2D.LinecastAll(tempPoint1.Pos, tempPoint2.Pos);

        for (int i = 0; i < edgesHitUnscaled.Length; i++)
        {
            Vector2 hittedPoint = edgesHitUnscaled[i].point;
            if (!Mathematics.IsVectorsAproximately(tempPoint1.Pos, hittedPoint) && !Mathematics.IsVectorsAproximately(tempPoint2.Pos, hittedPoint))
            {
                edgesHit++;
            }
        }

        if (Mathematics.PointInPolygon(point1, _polygon) && Mathematics.PointInPolygon(point2, _polygon) && edgesHit == 0)
        {
            return(true);
        }

        return(false);
    }
예제 #31
0
파일: Slicer.cs 프로젝트: roice3/Honeycombs
        /// <summary>
        /// Get a pair of intersection points.
        /// </summary>
        private static void GetPairPoints( List<IntersectionPoint> iPoints, int pair, bool increment, 
			out IntersectionPoint iPoint1, out IntersectionPoint iPoint2 )
        {
            int idx1 = pair * 2;
            int idx2 = pair * 2 + 1;
            if( !increment )
                Utils.Swap<int>( ref idx1, ref idx2 );

            iPoint1 = iPoints[idx1];
            iPoint2 = iPoints[idx2];
        }
예제 #32
0
파일: Slicer.cs 프로젝트: roice3/Honeycombs
        /// <summary>
        /// Splits segmentToSplit in two based on iLocation.
        /// First new segment will be added to diced, and second new segment will be returned.
        /// If split doesn't happen, segmentToSplit will be returned.
        /// </summary>
        private static Segment SplitHelper( Segment segmentToSplit, Vector3D iLocation, Polygon diced, List<IntersectionPoint> iPoints )
        {
            List<Segment> split;
            if( segmentToSplit.Split( iLocation, out split ) )
            {
                Debug.Assert( split.Count == 2 );
                diced.Segments.Add( split[0] );

                IntersectionPoint iPoint = new IntersectionPoint();
                iPoint.Location = iLocation;
                iPoint.Index = diced.Segments.Count;
                iPoints.Add( iPoint );

                return split[1];
            }
            else
            {
                // We were presumably at an endpoint.
                // Add to iPoints list only if it was the starting endpoint.
                // (This will avoid duplicate entries).
                if( iLocation.Compare( segmentToSplit.P1 ) )
                {
                    IntersectionPoint iPoint = new IntersectionPoint();
                    iPoint.Location = iLocation;
                    iPoint.Index = diced.Segments.Count;
                    iPoints.Add( iPoint );
                }

                return segmentToSplit;
            }
        }