Пример #1
0
    private void Shooting()
    {
        float sqrDist    = Vector2.SqrMagnitude((Vector2)grasp.position - hookedPos);
        float hookedDist = Mathf.Pow(Time.deltaTime * shotSpeed, 2);

        if (sqrDist > hookedDist) //훅이 날아가는 중
        {
            hookedRot = Quaternion.Euler(0, 0, Math2D.LookAt2D(player.position, hookedPos)).eulerAngles.z;

            grasp.position   += ((Vector3)hookedPos - grasp.position).normalized * Time.deltaTime * shotSpeed;
            grasp.eulerAngles = new Vector3(0, 0, hookedRot);
        }
        else
        {
            if (hookedTr != null)
            {
                state             = HookState.Hooked;
                grasp.position    = hookedPos;
                grasp.eulerAngles = new Vector3(0, 0, hookedRot);
                nowChainDistance  = Vector2.Distance(player.position, grasp.position);

                Player.instance.SwingStart(hookedPos);
                chainCtrl.ChainConnect(chainStart, chainEnd);
            }
            else
            {
                state = HookState.Returning;
            }
        }
    }
Пример #2
0
 public void MakeClockwise()
 {
     if (Math2D.IsClockwise(vertices.ToArray()))
     {
         vertices.Reverse();
     }
 }
Пример #3
0
        private static Tuple <double, Point[]> GetPercentCovered(Point[] polygon, Rect rect)
        {
            // Figure out the intersected polygon
            Point[] intersection = Math2D.GetIntersection_Polygon_Polygon(
                polygon,
                new Point[] { rect.TopLeft, rect.TopRight, rect.BottomRight, rect.BottomLeft });

            if (intersection == null || intersection.Length == 0)
            {
                return(null);
            }

            // Calculate the area of the polygon
            double areaPolygon = Math2D.GetAreaPolygon(intersection);

            double areaRect = rect.Width * rect.Height;

            if (areaPolygon > areaRect)
            {
                if (areaPolygon > areaRect * 1.01)
                {
                    throw new ApplicationException(string.Format("Area of intersected polygon is larger than the rectangle that clipped it: polygon={0}, rectangle={1}", areaPolygon.ToString(), areaRect.ToString()));
                }
                areaPolygon = areaRect;
            }

            return(Tuple.Create(areaPolygon / areaRect, intersection));
        }
    static public void LinearSliceJoints(Pair2D slice)
    {
        foreach (Joint2D joint in Joint2D.GetJointsConnected())
        {
            Vector2 localPosA = joint.anchoredJoint2D.connectedAnchor;
            Vector2 worldPosA = joint.anchoredJoint2D.connectedBody.transform.TransformPoint(localPosA);
            Vector2 localPosB = joint.anchoredJoint2D.anchor;
            Vector2 worldPosB = joint.anchoredJoint2D.transform.TransformPoint(localPosB);

            switch (joint.jointType)
            {
            case Joint2D.Type.HingeJoint2D:
                worldPosA = joint.anchoredJoint2D.connectedBody.transform.position;
                break;

            default:
                break;
            }

            Pair2D jointLine = new Pair2D(worldPosA, worldPosB);

            if (Math2D.LineIntersectLine(slice, jointLine))
            {
                UnityEngine.Object.Destroy(joint.anchoredJoint2D);
            }
        }
    }
Пример #5
0
        private void ShowNearbySketches(SketchSample[] nearby, Point3D center3D, RayHitTestParameters cameraRay, Point center2D)
        {
            // Get a plane that is perpendicular to the look ray
            ITriangle plane = Math3D.GetPlane(center3D, cameraRay.Direction);

            // Project the points onto that plane
            var nearbyOnPlane = nearby.
                                Select(o => new { Sketch = o, PlanePoint = Math3D.GetClosestPoint_Plane_Point(plane, o.Position) }).
                                ToArray();

            RotateTransform3D rotate = new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRotation(new DoubleVector(cameraRay.Direction, _camera.UpDirection), new DoubleVector(new Vector3D(0, 0, -1), new Vector3D(0, 1, 0)))));

            // Lay these images down along the directions of the projected points
            // nearby is sorted by distance from the center image

            #region Attempt1

            double halfLarge = SKETCHSIZE_LARGE / 2;
            double halfSmall = SKETCHSIZE_SMALL / 2;

            double stepDist = SKETCHSIZE_SMALL * .05;

            int startIncrement = Convert.ToInt32(Math.Floor((halfSmall + halfLarge) / stepDist));

            List <Rect> existing = new List <Rect>();
            existing.Add(new Rect(center2D.X - halfLarge, center2D.Y - halfLarge, SKETCHSIZE_LARGE, SKETCHSIZE_LARGE));

            foreach (var nextSketch in nearbyOnPlane)
            {
                Vector direction = rotate.Transform(nextSketch.PlanePoint - center3D).ToVector2D();

                Vector dirUnit = direction.ToUnit();
                if (Math2D.IsInvalid(dirUnit))
                {
                    dirUnit = Math3D.GetRandomVector_Circular_Shell(1).ToVector2D();
                }
                dirUnit = new Vector(dirUnit.X, -dirUnit.Y);

                Point point = new Point();
                Rect  rect  = new Rect();

                for (int cntr = startIncrement; cntr < 1000; cntr++)
                {
                    point = center2D + (dirUnit * (stepDist * cntr));
                    rect  = new Rect(point.X - halfSmall, point.Y - halfSmall, SKETCHSIZE_SMALL, SKETCHSIZE_SMALL);

                    if (!existing.Any(o => o.IntersectsWith(rect)))
                    {
                        break;
                    }
                }

                existing.Add(rect);

                //ShowImage(nextSketch.Sketch, center2D + (dirUnit * 100), false);
                ShowImage(nextSketch.Sketch, point, false);
            }

            #endregion
        }
Пример #6
0
 public void Test(Rect _r)
 {
     if (Math2D.Intersects(mPA, mPB, _r))
     {
         gameObject.SetActive(false);
     }
 }
Пример #7
0
    void Update()
    {
        Polygon2D cameraPolygon = Polygon2D.CreateFromCamera(Camera.main);

        cameraPolygon = cameraPolygon.ToRotation(Camera.main.transform.rotation.eulerAngles.z * Mathf.Deg2Rad);
        cameraPolygon = cameraPolygon.ToOffset(new Vector2D(Camera.main.transform.position));

        foreach (Slicer2D slicer in Slicer2D.GetListCopy())
        {
            if (Math2D.PolyCollidePoly(slicer.shape.GetLocal(), cameraPolygon) == false)
            {
                if (slicer.enabled == true)
                {
                    lives--;
                    if (lives >= 0)
                    {
                        SpriteRenderer sr = livesObjects[lives].GetComponent <SpriteRenderer>();
                        sr.color = Color.white;
                    }
                    else
                    {
                        Debug.Log("lose");
                    }
                }
                Destroy(slicer.gameObject);
            }
        }

        scoreText.text = score.ToString();
    }
Пример #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FailureMechanismSection"/> class.
        /// </summary>
        /// <param name="name">The name of the section.</param>
        /// <param name="geometryPoints">The geometry points of the section.</param>
        /// <exception cref="ArgumentNullException">Thrown when:<list type="bullet">
        /// <item><paramref name="name"/> is <c>null</c>.</item>
        /// <item><paramref name="geometryPoints"/> is <c>null</c>.</item> </list></exception>
        /// <exception cref="ArgumentException">Thrown when:<list type="bullet">
        /// <item><paramref name="geometryPoints"/> does not have at least one geometry point.</item>
        /// <item>One or more <paramref name="geometryPoints"/> elements are <c>null</c>.</item>
        /// </list></exception>
        public FailureMechanismSection(string name, IEnumerable <Point2D> geometryPoints)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (geometryPoints == null)
            {
                throw new ArgumentNullException(nameof(geometryPoints));
            }

            if (!geometryPoints.Any())
            {
                throw new ArgumentException(Resources.FailureMechanismSection_Section_must_have_at_least_1_geometry_point, nameof(geometryPoints));
            }

            if (geometryPoints.Any(p => p == null))
            {
                throw new ArgumentException(@"One or multiple elements are null.", nameof(geometryPoints));
            }

            Name       = name;
            Points     = geometryPoints;
            StartPoint = geometryPoints.First();
            EndPoint   = geometryPoints.Last();
            Length     = Math2D.Length(geometryPoints);
        }
Пример #9
0
        /// <summary>
        /// Gets the height of the projected <see cref="MechanismSurfaceLineBase"/> at a L=<paramref name="l"/>.
        /// </summary>
        /// <param name="l">The L coordinate from where to take the height of the <see cref="MechanismSurfaceLineBase"/>.</param>
        /// <returns>The height of the <see cref="MechanismSurfaceLineBase"/> at L=<paramref name="l"/>.</returns>
        /// <exception cref="MechanismSurfaceLineException">Thrown when the <see cref="MechanismSurfaceLineBase"/>
        /// intersection point at <paramref name="l"/> have a significant difference in their y coordinate.</exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="l"/> is not in range of the LZ-projected <see cref="Points"/>.</exception>
        /// <exception cref="InvalidOperationException">Thrown when <see cref="Points"/> is empty.</exception>
        public double GetZAtL(RoundedDouble l)
        {
            ValidateHasPoints();

            if (!ValidateInRange(l))
            {
                var    localRangeL       = new Range <double>(LocalGeometry.First().X, LocalGeometry.Last().X);
                string outOfRangeMessage = string.Format(Resources.MechanismSurfaceLineBase_0_L_needs_to_be_in_Range_1_,
                                                         Resources.MechanismSurfaceLineBase_GetZAtL_Cannot_determine_height,
                                                         localRangeL.ToString(FormattableConstants.ShowAtLeastOneDecimal, CultureInfo.CurrentCulture));
                throw new ArgumentOutOfRangeException(null, outOfRangeMessage);
            }

            var segments = new Collection <Segment2D>();

            for (var i = 1; i < LocalGeometry.Count(); i++)
            {
                segments.Add(new Segment2D(LocalGeometry.ElementAt(i - 1), LocalGeometry.ElementAt(i)));
            }

            IEnumerable <Point2D> intersectionPoints = Math2D.SegmentsIntersectionWithVerticalLine(segments, l).OrderBy(p => p.Y).ToArray();

            const double intersectionTolerance = 1e-2;
            bool         equalIntersections    = Math.Abs(intersectionPoints.First().Y - intersectionPoints.Last().Y) < intersectionTolerance;

            if (equalIntersections)
            {
                return(intersectionPoints.First().Y);
            }

            string message = string.Format(Resources.MechanismSurfaceLineBase_Cannot_determine_reliable_z_when_surface_line_is_vertical_in_l, l);

            throw new MechanismSurfaceLineException(message);
        }
        private static bool DoesHydraulicBoundaryLocationMatchWithDuneLocation(HydraulicBoundaryLocation hydraulicBoundaryLocation,
                                                                               ReadDuneLocation readDuneLocation)
        {
            if (!Math2D.AreEqualPoints(hydraulicBoundaryLocation.Location, readDuneLocation.Location))
            {
                return(false);
            }

            // Regex to search for a pattern like "<Some text without white spaces>_<integer>_<decimal>"
            // Only the last number is captured in a group called "Offset"
            // The last number can also contain decimals.
            var   regex = new Regex(@"^(?:\S+)_(?:\d+)_(?<Offset>(?:\d+\.)?\d+$)");
            Match match = regex.Match(hydraulicBoundaryLocation.Name);

            if (!match.Success)
            {
                log.ErrorFormat(Resources.DuneErosionDataSynchronizationService_SetDuneLocations_Location_0_is_dune_location_but_name_is_not_according_format,
                                hydraulicBoundaryLocation.Name);
                return(false);
            }

            string duneLocationOffset = readDuneLocation.Offset.ToString(DuneErosionDataResources.DuneLocation_Offset_format,
                                                                         CultureInfo.InvariantCulture);

            return(match.Groups["Offset"].Value == duneLocationOffset);
        }
Пример #11
0
        public void IsStructureIntersectionWithReferenceLineInSection_StructureDoesNotIntersectReferenceLine_ReturnsFalse()
        {
            // Setup
            var structure     = new TestStructure(new Point2D(0.0, 0.0));
            var referenceLine = new ReferenceLine();

            referenceLine.SetGeometry(new[]
            {
                new Point2D(10.0, 0.0),
                new Point2D(20.0, 0.0)
            });

            var calculation = new TestStructuresCalculationScenario
            {
                InputParameters =
                {
                    Structure = structure
                }
            };

            IEnumerable <Segment2D> lineSegments = Math2D.ConvertPointsToLineSegments(referenceLine.Points);

            // Call
            bool intersects = calculation.IsStructureIntersectionWithReferenceLineInSection(lineSegments);

            // Assert
            Assert.IsFalse(intersects);
        }
Пример #12
0
        /// <summary>
        /// Returns the index of a scatter point that is closest to the location <c>hitpoint</c>
        /// </summary>
        /// <param name="layer">The layer in which this plot item is drawn into.</param>
        /// <param name="hitpoint">The point where the mouse is pressed.</param>
        /// <returns>The information about the point that is nearest to the location, or null if it can not be determined.</returns>
        public XYZScatterPointInformation GetNearestPlotPoint(IPlotArea layer, HitTestPointData hitpoint)
        {
            Processed3DPlotData pdata;

            if (null != (pdata = _cachedPlotDataUsedForPainting))
            {
                PlotRangeList rangeList         = pdata.RangeList;
                var           ptArray           = pdata.PlotPointsInAbsoluteLayerCoordinates;
                double        mindistance       = double.MaxValue;
                int           minindex          = -1;
                var           hitTransformation = hitpoint.HitTransformation;
                var           lineStart         = hitTransformation.Transform(ptArray[0]).PointD2DWithoutZ;
                for (int i = 1; i < ptArray.Length; i++)
                {
                    var    lineEnd  = hitTransformation.Transform(ptArray[i]).PointD2DWithoutZ;
                    double distance = Math2D.SquareDistanceLineToPoint(PointD2D.Empty, lineStart, lineEnd);
                    if (distance < mindistance)
                    {
                        mindistance = distance;
                        minindex    = Math2D.Distance(lineStart, PointD2D.Empty) < Math2D.Distance(lineEnd, PointD2D.Empty) ? i - 1 : i;
                    }
                    lineStart = lineEnd;
                }
                // ok, minindex is the point we are looking for
                // so we have a look in the rangeList, what row it belongs to
                int rowindex = rangeList.GetRowIndexForPlotIndex(minindex);

                return(new XYZScatterPointInformation(ptArray[minindex], rowindex, minindex));
            }

            return(null);
        }
Пример #13
0
        private static ReferenceLineIntersectionResult GetReferenceLineIntersectionsResult(IEnumerable <Segment2D> surfaceLineSegments,
                                                                                           IEnumerable <Segment2D> referenceLineSegments)
        {
            Point2D intersectionPoint = null;

            foreach (Segment2D surfaceLineSegment in surfaceLineSegments)
            {
                foreach (Segment2D referenceLineSegment in referenceLineSegments)
                {
                    Segment2DIntersectSegment2DResult result = Math2D.GetIntersectionBetweenSegments(surfaceLineSegment, referenceLineSegment);

                    if (result.IntersectionType == Intersection2DType.Intersects)
                    {
                        Point2D resultIntersectionPoint = result.IntersectionPoints[0];
                        if (intersectionPoint != null && !intersectionPoint.Equals(resultIntersectionPoint))
                        {
                            // Early exit as multiple intersections is a return result:
                            return(ReferenceLineIntersectionResult.CreateMultipleIntersectionsOrOverlapResult());
                        }

                        intersectionPoint = resultIntersectionPoint;
                    }

                    if (result.IntersectionType == Intersection2DType.Overlaps)
                    {
                        // Early exit as overlap is a return result:
                        return(ReferenceLineIntersectionResult.CreateMultipleIntersectionsOrOverlapResult());
                    }
                }
            }

            return(intersectionPoint != null
                       ? ReferenceLineIntersectionResult.CreateIntersectionResult(intersectionPoint)
                       : ReferenceLineIntersectionResult.CreateNoSingleIntersectionResult());
        }
Пример #14
0
        private static ReferenceLineIntersectionResult GetReferenceLineIntersections(ReferenceLine referenceLine, SurfaceLine surfaceLine)
        {
            IEnumerable <Segment2D> surfaceLineSegments   = Math2D.ConvertPointsToLineSegments(surfaceLine.Points.Select(p => new Point2D(p.X, p.Y))).ToArray();
            IEnumerable <Segment2D> referenceLineSegments = Math2D.ConvertPointsToLineSegments(referenceLine.Points).ToArray();

            return(GetReferenceLineIntersectionsResult(surfaceLineSegments, referenceLineSegments));
        }
Пример #15
0
        // Linear Slice
        static public Slice2D Slice(Polygon2D polygon, Pair2D slice)
        {
            Slice2D result = Slice2D.Create(null, slice);

            if (slice == null)
            {
                return(result);
            }

            // Normalize into clockwise
            polygon.Normalize();

            // Optimization
            // Skip slicing polygons that are not overlapping with slice
            Rect sliceRect   = Math2D.GetBounds(slice);
            Rect polygonRect = polygon.GetBounds();

            if (sliceRect.Overlaps(polygonRect) == false)
            {
                return(result);
            }

            result = MultipleSlice(polygon, slice);

            return(result);
        }
Пример #16
0
        /// <summary>
        /// Returns the index of a scatter point that is nearest to the location <c>hitpoint</c>
        /// </summary>
        /// <param name="layer">The layer in which this plot item is drawn into.</param>
        /// <param name="hitpoint">The point where the mouse is pressed.</param>
        /// <returns>The information about the point that is nearest to the location, or null if it can not be determined.</returns>
        public XYScatterPointInformation GetNearestPlotPoint(IPlotArea layer, PointD2D hitpoint)
        {
            Processed2DPlotData pdata;

            if (null != (pdata = _cachedPlotDataUsedForPainting))
            {
                PlotRangeList rangeList   = pdata.RangeList;
                PointF[]      ptArray     = pdata.PlotPointsInAbsoluteLayerCoordinates;
                double        mindistance = double.MaxValue;
                int           minindex    = -1;
                for (int i = 1; i < ptArray.Length; i++)
                {
                    double distance = Math2D.SquareDistanceLineToPoint(hitpoint, ptArray[i - 1], ptArray[i]);
                    if (distance < mindistance)
                    {
                        mindistance = distance;
                        minindex    = Math2D.Distance(ptArray[i - 1], hitpoint) < Math2D.Distance(ptArray[i], hitpoint) ? i - 1 : i;
                    }
                }
                // ok, minindex is the point we are looking for
                // so we have a look in the rangeList, what row it belongs to
                int rowindex = rangeList.GetRowIndexForPlotIndex(minindex);

                return(new XYScatterPointInformation(ptArray[minindex], rowindex, minindex));
            }

            return(null);
        }
Пример #17
0
    static public void SetupLocation(LightingBuffer2D buffer, LightingTilemapCollider2D id)
    {
        Vector3 rot = Math2D.GetPitchYawRollRad(id.transform.rotation);

        float rotationYScale = Mathf.Sin(rot.x + Mathf.PI / 2);
        float rotationXScale = Mathf.Sin(rot.y + Mathf.PI / 2);

        scale.x = id.transform.lossyScale.x * rotationXScale * id.cellSize.x;
        scale.y = id.transform.lossyScale.y * rotationYScale * id.cellSize.y;

        sizeInt = LightTilemapSize(id, buffer);

        LightTilemapOffset(id, scale, buffer);

        offset.x = -buffer.lightSource.transform.position.x;
        offset.y = -buffer.lightSource.transform.position.y;

        tilemapOffset.x = id.transform.position.x + id.area.position.x + id.cellAnchor.x;
        tilemapOffset.y = id.transform.position.y + id.area.position.y + id.cellAnchor.y;

        if (id.mapType == LightingTilemapCollider2D.MapType.SuperTilemapEditor)
        {
            tilemapOffset.x -= id.area.size.x / 2;
            tilemapOffset.y -= id.area.size.y / 2;
        }

        tileSize.x = scale.x / id.cellSize.x;
        tileSize.y = scale.y / id.cellSize.y;
    }
Пример #18
0
    public Vector2D GetPoint(DoublePair2D pair)
    {
        float rotA = (float)Vector2D.Atan2(pair.B, pair.A);
        float rotC = (float)Vector2D.Atan2(pair.B, pair.C);

        Vector2D pairA = new Vector2D(pair.A);

        pairA.Push(rotA - Mathf.PI / 2, lineWidth);
        pairA.Push(rotA, -100f);

        Vector2D pairC = new Vector2D(pair.C);

        pairC.Push(rotC + Mathf.PI / 2, lineWidth);
        pairC.Push(rotC, -100f);

        Vector2D vecA = new Vector2D(pair.B);

        vecA.Push(rotA - Mathf.PI / 2, lineWidth);
        vecA.Push(rotA, 100f);

        Vector2D vecC = new Vector2D(pair.B);

        vecC.Push(rotC + Mathf.PI / 2, lineWidth);
        vecC.Push(rotC, 100f);

        return(Math2D.GetPointLineIntersectLine(new Pair2D(pairA, vecA), new Pair2D(pairC, vecC)));
    }
Пример #19
0
        private bool Update_InitialChecks(out Point?currentPoint, double elapsedTime)
        {
            // Get the current point from either the mouse if they are human, or from the plate if npc
            currentPoint = GetCurrentPoint();
            if (currentPoint == null)
            {
                StopRamming();
                return(false);
            }

            if (_pointHistory.Count == 0)
            {
                StopRamming();      // this is probably unnecessary
                _pointHistory.Add(currentPoint.Value);
                return(false);
            }

            // Compare this current point to the previous point
            Point prevPoint = _pointHistory[_pointHistory.Count - 1];

            if (Math2D.IsNearValue(prevPoint, currentPoint.Value))
            {
                _probationCount++;
                if (_probationCount > MAXPROBATION)
                {
                    // They are the same point.  Reset
                    StopRamming();      // this is probably unnecessary
                    _pointHistory.Add(currentPoint.Value);
                }
                return(false);
            }

            return(true);
        }
Пример #20
0
        private void ShowNearbySketches(Dot[] nearby, Point3D center3D, RayHitTestParameters cameraRay, Point center2D)
        {
            // Get a plane that is perpendicular to the look ray
            ITriangle plane = Math3D.GetPlane(center3D, cameraRay.Direction);

            // Project the points onto that plane
            var nearbyOnPlane = nearby.
                                Select(o => new { Sketch = o, PlanePoint = Math3D.GetClosestPoint_Plane_Point(plane, o.Position) }).
                                ToArray();

            RotateTransform3D rotate = new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRotation(new DoubleVector(cameraRay.Direction, _camera.UpDirection), new DoubleVector(new Vector3D(0, 0, -1), new Vector3D(0, 1, 0)))));

            // Lay these images down along the directions of the projected points
            // nearby is sorted by distance from the center image

            double halfLarge = SKETCHSIZE_LARGE / 2;
            double halfSmall = SKETCHSIZE_SMALL / 2;

            double stepDist = SKETCHSIZE_SMALL * .05;

            // Don't start counter at a distance of zero, that's just wasted steps.  Figure out what cntr to use that is the distance of the two images touching
            int startIncrement = Convert.ToInt32(Math.Floor((halfSmall + halfLarge) / stepDist));

            // Remember the locations of each image rect
            List <Rect> existing = new List <Rect>();

            existing.Add(new Rect(center2D.X - halfLarge, center2D.Y - halfLarge, SKETCHSIZE_LARGE, SKETCHSIZE_LARGE));

            foreach (var nextSketch in nearbyOnPlane)
            {
                // Get the 2D direction this sketch is from the main
                Vector direction = rotate.Transform(nextSketch.PlanePoint - center3D).ToVector2D();

                Vector dirUnit = direction.ToUnit(true);
                if (Math2D.IsInvalid(dirUnit))
                {
                    dirUnit = Math3D.GetRandomVector_Circular_Shell(1).ToVector2D();        // sitting on top of each other, just push it in a random direction
                }
                dirUnit = new Vector(dirUnit.X, -dirUnit.Y);

                Point point = new Point();
                Rect  rect  = new Rect();

                // Keep walking along that direction until the rectangle doesn't intersect any existing sketches
                for (int cntr = startIncrement; cntr < 1000; cntr++)
                {
                    point = center2D + (dirUnit * (stepDist * cntr));
                    rect  = new Rect(point.X - halfSmall, point.Y - halfSmall, SKETCHSIZE_SMALL, SKETCHSIZE_SMALL);

                    if (!existing.Any(o => o.IntersectsWith(rect)))
                    {
                        break;
                    }
                }

                existing.Add(rect);

                ShowImage(nextSketch.Sketch, point, false);
            }
        }
Пример #21
0
    public bool ItersectsWithMap()
    {
        Polygon2D edges = GetEdges().ToWorldSpace(gameObject.transform);

        bool intersect = false;

        foreach (Slicer2D slicer in Slicer2D.GetList())
        {
            Polygon2D polyB = slicer.GetPolygon().ToWorldSpace(slicer.gameObject.transform);

            if (Math2D.SliceIntersectPoly(edges.pointsList, polyB))
            {
                intersect = true;
            }

            foreach (Vector2D p in edges.pointsList)
            {
                if (Math2D.PointInPoly(p, polyB))
                {
                    return(true);
                }
            }
        }
        return(intersect);
    }
Пример #22
0
            /// <summary>
            /// Bilinear interpolation
            /// </summary>
            /// <remarks>
            /// http://en.wikipedia.org/wiki/Bilinear_interpolation
            /// </remarks>
            /// <param name="ul">Upper Left</param>
            /// <param name="ur">Upper Right</param>
            /// <param name="bl">Bottom Left</param>
            /// <param name="br">Bottom Right</param>
            /// <param name="pos">The position within the box (values are always between 0 and 1)</param>
            private static Vector LERP(Vector ul, Vector ur, Vector bl, Vector br, double percentX, double percentY)
            {
                Vector upper  = Math2D.LERP(ul, ur, percentX);
                Vector bottom = Math2D.LERP(bl, br, percentX);

                return(Math2D.LERP(upper, bottom, percentY));
            }
Пример #23
0
        /// <summary>
        /// Creates a new instance of <see cref="SerializableFailureMechanismSection"/>.
        /// </summary>
        /// <param name="id">The unique assembly ID.</param>
        /// <param name="failureMechanismSectionCollection">The failure mechanism sections object the section belong to.</param>
        /// <param name="startDistance">The distance over the reference line where this section starts in meters.</param>
        /// <param name="endDistance">The distance over the reference line where this section ends in meters.</param>
        /// <param name="geometry">The geometry of the section.</param>
        /// <param name="sectionType">The type of the section.</param>
        /// <param name="assemblyMethod">The assembly method used to create this section.</param>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="failureMechanismSectionCollection"/>,
        /// or <paramref name="geometry"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">Thrown when:
        /// <list type="bullet">
        /// <item><paramref name="geometry"/> contains no elements.</item>
        /// <item><paramref name="id"/> is invalid.</item>
        /// </list>
        /// </exception>
        public SerializableFailureMechanismSection(string id,
                                                   SerializableFailureMechanismSectionCollection failureMechanismSectionCollection,
                                                   double startDistance,
                                                   double endDistance,
                                                   IEnumerable <Point2D> geometry,
                                                   SerializableFailureMechanismSectionType sectionType,
                                                   SerializableAssemblyMethod?assemblyMethod = null)
        {
            SerializableIdValidator.ThrowIfInvalid(id);

            if (failureMechanismSectionCollection == null)
            {
                throw new ArgumentNullException(nameof(failureMechanismSectionCollection));
            }

            if (geometry == null)
            {
                throw new ArgumentNullException(nameof(geometry));
            }

            Id            = id;
            StartDistance = new SerializableMeasure(startDistance);
            EndDistance   = new SerializableMeasure(endDistance);
            FailureMechanismSectionCollectionId = failureMechanismSectionCollection.Id;
            Geometry       = new SerializableLine(geometry);
            Length         = new SerializableMeasure(Math2D.Length(geometry));
            AssemblyMethod = assemblyMethod;
            FailureMechanismSectionType = sectionType;
        }
Пример #24
0
        public static void Test_FloodFill_01()
        {
            int[][] field = new int[][]
            {
                new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
                new int[] { 1, 1, 1, 1, 1, 0, 1, 1, 1, 1 },
                new int[] { 1, 1, 1, 1, 0, 0, 0, 1, 1, 1 },
                new int[] { 1, 1, 0, 0, 0, 0, 1, 1, 1, 1 },
                new int[] { 1, 1, 0, 0, 0, 1, 1, 1, 1, 1 },
                new int[] { 1, 0, 1, 1, 0, 0, 1, 1, 1, 1 },
                new int[] { 1, 1, 0, 1, 0, 0, 0, 0, 1, 1 },
                new int[] { 1, 1, 0, 1, 1, 1, 1, 0, 0, 1 },
                new int[] { 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
                new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
            };

            int pixelsWith0 = 0;

            Math2D.FloodFill_4Neighbour(
                5,
                5,
                (x, y) => field[y][x] == 0, (x, y) => ++ pixelsWith0,
                0, 0, 10, 10
                );

            Assert.AreEqual(19, pixelsWith0);
        }
Пример #25
0
        /// <summary>
        /// This creates solid colored blobs with areas proportional to the number of items contained.  When the user
        /// mouses over a blob, the caller can show examples of the items as tooltips
        /// </summary>
        public static void ShowResults2D_Blobs(Border border, SOMResult result, Func <SOMNode, Color> getNodeColor, BlobEvents events = null)
        {
            #region validate
#if DEBUG
            if (!result.Nodes.All(o => o.Position.Size == 2))
            {
                throw new ArgumentException("Node positions need to be 2D");
            }
#endif
            #endregion

            Point[] points = result.Nodes.
                             Select(o => new Point(o.Position[0], o.Position[1])).
                             ToArray();

            VoronoiResult2D voronoi = Math2D.GetVoronoi(points, true);
            voronoi = Math2D.CapVoronoiCircle(voronoi);

            Color[] colors = result.Nodes.
                             Select(o => getNodeColor(o)).
                             ToArray();

            //ISOMInput[][] inputsByNode = UtilityCore.ConvertJaggedArray<ISOMInput>(result.InputsByNode);

            Vector size   = new Vector(border.ActualWidth - border.Padding.Left - border.Padding.Right, border.ActualHeight - border.Padding.Top - border.Padding.Bottom);
            Canvas canvas = DrawVoronoi_Blobs(voronoi, colors, result.Nodes, result.InputsByNode, size.X.ToInt_Floor(), size.Y.ToInt_Floor(), events);

            border.Child = canvas;
        }
Пример #26
0
        public static void Test_PolygonArea02_Nothing()
        {
            var testPoints = new PointD2D[0];
            var area       = Math2D.PolygonArea(testPoints);

            Assert.AreEqual(0, area);
        }
Пример #27
0
    public bool IsSelfIntersecting()
    {
        int nexti;
        int nextj;

        for (int i = 0; i < vertices.Count; i++)
        {
            nexti = (i + 1) % vertices.Count;

            for (int j = 0; j < vertices.Count; j++)
            {
                nextj = (j + 1) % vertices.Count;
                if (nextj >= vertices.Count)
                {
                    nextj -= vertices.Count;
                }

                if (i == j || nexti == j || i == nextj)
                {
                    continue;
                }

                if (Math2D.SegmentSegmentIntersection(
                        vertices[i].Position2D,
                        vertices[nexti].Position2D,
                        vertices[j].Position2D,
                        vertices[nextj].Position2D))
                {
                    //Debug.Log("Polygon is SelfIntersecting");
                    return(true);
                }
            }
        }
        return(false);
    }
Пример #28
0
    private void ComplexSliceJoints(List <Vector2D> slice)
    {
        foreach (Joint2D joint in Joint2D.GetJointsConnected())
        {
            Vector2 localPosA = joint.anchoredJoint2D.connectedAnchor;
            Vector2 worldPosA = joint.anchoredJoint2D.connectedBody.transform.TransformPoint(localPosA);
            Vector2 localPosB = joint.anchoredJoint2D.anchor;
            Vector2 worldPosB = joint.anchoredJoint2D.transform.TransformPoint(localPosB);

            switch (joint.jointType)
            {
            case Joint2D.Type.HingeJoint2D:
                worldPosA = joint.anchoredJoint2D.connectedBody.transform.position;
                break;

            default:
                break;
            }

            Pair2D jointLine = new Pair2D(worldPosA, worldPosB);

            foreach (Pair2D pair in Pair2D.GetList(slice, false))
            {
                if (Math2D.LineIntersectLine(pair, jointLine))
                {
                    Destroy(joint.anchoredJoint2D);
                }
            }
        }
    }
        private static bool DoesSoilModelGeometryIntersectWithSurfaceLineGeometry(PipingStochasticSoilModel stochasticSoilModel,
                                                                                  Segment2D[] surfaceLineSegments)
        {
            IEnumerable <Segment2D> soilProfileGeometrySegments = Math2D.ConvertPointsToLineSegments(stochasticSoilModel.Geometry);

            return(soilProfileGeometrySegments.Any(s => DoesSegmentIntersectWithSegmentArray(s, surfaceLineSegments)));
        }
Пример #30
0
        public void CreateReferenceLineFeatures_GivenReferenceLine_ReturnsReferenceLineFeature()
        {
            // Setup
            const string id   = "1";
            const string name = "Traject 1";

            var points = new[]
            {
                new Point2D(1.2, 2.3),
                new Point2D(2.7, 2.0)
            };
            var referenceLine = new ReferenceLine();

            referenceLine.SetGeometry(points);

            // Call
            IEnumerable <MapFeature> features = RiskeerMapDataFeaturesFactory.CreateReferenceLineFeatures(referenceLine, id, name);

            // Assert
            MapFeature mapFeature = features.Single();

            Assert.AreEqual(3, mapFeature.MetaData.Keys.Count);
            Assert.AreEqual(id, mapFeature.MetaData["ID"]);
            Assert.AreEqual(name, mapFeature.MetaData["Naam"]);

            var expectedLength = new RoundedDouble(2, Math2D.Length(points));

            Assert.AreEqual(expectedLength, (RoundedDouble)mapFeature.MetaData["Lengte*"], expectedLength.GetAccuracy());
            AssertEqualPointCollections(points, mapFeature.MapGeometries.ElementAt(0));
        }