Example #1
0
        private List <Point> Unclip(List <PointF> box, float unclip_ratio)
        {
            List <IntPoint> theCliperPts = new List <IntPoint>();

            foreach (PointF pt in box)
            {
                IntPoint a1 = new IntPoint((int)pt.X, (int)pt.Y);
                theCliperPts.Add(a1);
            }

            float  area     = Math.Abs(SignedPolygonArea(box.ToArray <PointF>()));
            double length   = LengthOfPoints(box);
            double distance = area * unclip_ratio / length;

            ClipperOffset co = new ClipperOffset();

            co.AddPath(theCliperPts, JoinType.jtRound, EndType.etClosedPolygon);
            List <List <IntPoint> > solution = new List <List <IntPoint> >();

            co.Execute(ref solution, distance);
            if (solution.Count == 0)
            {
                return(null);
            }

            List <Point> retPts = new List <Point>();

            foreach (IntPoint ip in solution[0])
            {
                retPts.Add(new Point((int)ip.X, (int)ip.Y));
            }

            return(retPts);
        }
Example #2
0
        public static bool addSteinerPointsAtOffset(ref Polygon _polygon, ref ClipperOffset co, float offset, int seglenBigInt)
        {
            PolyTree resPolytree = new AXClipperLib.PolyTree();

            co.Execute(ref resPolytree, (double)(-offset * AXGeometryTools.Utilities.IntPointPrecision));
            Paths paths = Clipper.PolyTreeToPaths(resPolytree);

            if (paths != null && paths.Count > 0 && paths[0] != null && paths[0].Count > 0)
            {
                foreach (Path path in paths)
                {
                    if (path != null && path.Count > 0)
                    {
                        Path ppp = Pather.segmentPath(path, seglenBigInt);
                        if (ppp != null && ppp.Count > 0)
                        {
                            foreach (IntPoint ip in ppp)
                            {
                                _polygon.AddSteinerPoint(new TriangulationPoint((double)ip.X / (double)AXGeometryTools.Utilities.IntPointPrecision, (double)ip.Y / (double)AXGeometryTools.Utilities.IntPointPrecision));
                            }
                        }
                    }
                }


                return(true);
            }
            return(false);
        }
Example #3
0
        // Rough shape only used in Inspector for quick preview.
        internal static List <Vector2> GetOutlinePath(Vector3[] shapePath, float offsetDistance)
        {
            const float     kClipperScale = 10000.0f;
            List <IntPoint> path          = new List <IntPoint>();
            List <Vector2>  output        = new List <Vector2>();

            for (var i = 0; i < shapePath.Length; ++i)
            {
                var newPoint = new Vector2(shapePath[i].x, shapePath[i].y) * kClipperScale;
                path.Add(new IntPoint((System.Int64)(newPoint.x), (System.Int64)(newPoint.y)));
            }
            List <List <IntPoint> > solution   = new List <List <IntPoint> >();
            ClipperOffset           clipOffset = new ClipperOffset(2048.0f);

            clipOffset.AddPath(path, JoinType.jtRound, EndType.etClosedPolygon);
            clipOffset.Execute(ref solution, kClipperScale * offsetDistance, path.Count);
            if (solution.Count > 0)
            {
                for (int i = 0; i < solution[0].Count; ++i)
                {
                    output.Add(new Vector2(solution[0][i].X / kClipperScale, solution[0][i].Y / kClipperScale));
                }
            }
            return(output);
        }
Example #4
0
        public static List <GeneralPolygon2d> ComputeOffsetPolygon(GeneralPolygon2d poly, double fOffset, bool bMiter = false)
        {
            double nIntScale = GetIntScale(poly);

            CPolygonList clipper_polys = new CPolygonList();

            clipper_polys.Add(ClipperUtil.ConvertToClipper(poly.Outer, nIntScale));
            foreach (Polygon2d hole in poly.Holes)
            {
                clipper_polys.Add(ClipperUtil.ConvertToClipper(hole, nIntScale));
            }

            CPolygonList dilate_solution = new CPolygonList();

            try {
                ClipperOffset co = new ClipperOffset();
                if (bMiter)
                {
                    co.AddPaths(clipper_polys, JoinType.jtMiter, EndType.etClosedPolygon);
                }
                else
                {
                    co.AddPaths(clipper_polys, JoinType.jtRound, EndType.etClosedPolygon);
                }
                co.Execute(ref dilate_solution, fOffset * nIntScale);
            } catch /*( Exception e )*/ {
                //System.Diagnostics.Debug.WriteLine("ClipperUtil.ComputeOffsetPolygon: Clipper threw exception: " + e.Message);
                return(new List <GeneralPolygon2d>());
            }

            List <GeneralPolygon2d> polys = ClipperUtil.ConvertFromClipper(dilate_solution, nIntScale);

            return(polys);
        }
Example #5
0
            private IEnumerable <HPGLLine> OffsetLine(double offset, HPGLLine line)
            {
                var newlines = new List <HPGLLine> {
                    line
                };

                var co        = new ClipperOffset();
                var solution  = new List <List <IntPoint> >();
                var solution2 = new List <List <IntPoint> >();

                solution.Add(line.Commands.Select(x => new IntPoint(_scale * x.PointFrom.X0, _scale * x.PointFrom.Y0)).ToList());
                co.AddPaths(solution, JoinType.jtRound, EndType.etClosedPolygon);
                co.Execute(ref solution2, offset);
                var existingline = line;

                foreach (var polygon in solution2)
                {
                    var         newcmds = new List <HPGLCommand>();
                    HPGLCommand last    = null;

                    foreach (var pt in polygon)
                    {
                        var from = new Point3D {
                            X = pt.X / _scale, Y = pt.Y / _scale
                        };
                        var hpgl = new HPGLCommand {
                            PointFrom = from, CommandType = HPGLCommand.HPGLCommandType.PenDown
                        };
                        newcmds.Add(hpgl);
                        if (last != null)
                        {
                            last.PointTo = from;
                        }
                        last = hpgl;
                    }
                    last.PointTo = newcmds.First().PointFrom;

                    if (existingline == null)
                    {
                        // add new line
                        existingline = new HPGLLine
                        {
                            PreCommands = new List <HPGLCommand>
                            {
                                new HPGLCommand {
                                    CommandType = HPGLCommand.HPGLCommandType.PenUp
                                }
                            },
                            PostCommands = new List <HPGLCommand>(),
                            ParentLine   = line.ParentLine
                        };
                        newlines.Add(existingline);
                    }

                    existingline.Commands = newcmds;
                    existingline.PreCommands.Last(l => l.IsPenCommand).PointTo = newcmds.First().PointFrom;
                    existingline = null;
                }
                return(newlines);
            }
        public static IPolygon Offset(this IPolygon p, double offset)
        {
            if (p.IsEmpty)
            {
                return(Polygon.Empty);
            }

            var    boundingBox     = p.BoundingBox().Offset(Math.Max(offset, 0));
            double scale           = Math.Max(boundingBox.Width, boundingBox.Height);
            var    fixedPointRange = new Box2(boundingBox.MinCorner, new Vector2(scale, scale));

            var fixedP = ConvertToFixedPoint(p, fixedPointRange);

            try
            {
                var offsetter = new ClipperOffset();
                offsetter.AddPaths(fixedP, JoinType.jtMiter, EndType.etClosedPolygon);

                var fixedAnswer = new ClipperPolygon();
                offsetter.Execute(ref fixedAnswer, offset * _fixedPointRange / scale);

                return(ConvertToFloatingPoint(fixedAnswer, fixedPointRange));
            }
            catch (Exception e)
            {
                Console.WriteLine("EXCEPTION: {0}", e);
                return(p);
            }
        }
        protected internal virtual Path FilterStrokePath(Path path, Matrix ctm, float lineWidth, int lineCapStyle,
                                                         int lineJoinStyle, float miterLimit, LineDashPattern lineDashPattern)
        {
            JoinType joinType = GetJoinType(lineJoinStyle);
            EndType  endType  = GetEndType(lineCapStyle);

            if (lineDashPattern != null)
            {
                if (IsZeroDash(lineDashPattern))
                {
                    return(new Path());
                }

                if (!IsSolid(lineDashPattern))
                {
                    path = ApplyDashPattern(path, lineDashPattern);
                }
            }

            ClipperOffset offset = new ClipperOffset(miterLimit, PdfCleanUpProcessor.ArcTolerance * PdfCleanUpProcessor.FloatMultiplier);

            AddPath(offset, path, joinType, endType);

            PolyTree resultTree = new PolyTree();

            offset.Execute(ref resultTree, lineWidth * PdfCleanUpProcessor.FloatMultiplier / 2);

            return(FilterFillPath(ConvertToPath(resultTree), ctm, PathPaintingRenderInfo.NONZERO_WINDING_RULE));
        }
Example #8
0
    public static Vector2[] Extend(this Vector2[] points, float radius)
    {
        if (Mathf.Approximately(radius, 0))
        {
            return(points);
        }

        Path polygon = points.ToList().ConvertAll(p => new IntPoint(p.x, p.y));

        Paths solution = new Paths();

        ClipperOffset c = new ClipperOffset();

        c.AddPath(polygon, JoinType.jtRound, EndType.etClosedPolygon);
        c.Execute(ref solution, radius);

        var r = solution.Count > 0 ? solution[0].ConvertAll(p => new Vector2(p.X, p.Y)) : new List <Vector2>();

        if (r.Count > 0)
        {
            r.Add(r[0]);
        }

        return(r.ToArray());
    }
Example #9
0
        /// <summary>
        /// Offset this polyline by the specified amount.
        /// </summary>
        /// <param name="offset">The amount to offset.</param>
        /// <param name="endType">The closure type to use on the offset polygon.</param>
        /// <param name="tolerance">An optional tolerance.</param>
        /// <returns>A new closed Polygon offset in all directions by offset from the polyline.</returns>
        public virtual Polygon[] Offset(double offset, EndType endType, double tolerance = Vector3.EPSILON)
        {
            var clipperScale = 1.0 / tolerance;
            var path         = this.ToClipperPath(tolerance);

            var solution = new List <List <IntPoint> >();
            var co       = new ClipperOffset();

            ClipperLib.EndType clEndType;
            switch (endType)
            {
            case EndType.Butt:
                clEndType = ClipperLib.EndType.etOpenButt;
                break;

            case EndType.ClosedPolygon:
                clEndType = ClipperLib.EndType.etClosedPolygon;
                break;

            case EndType.Square:
            default:
                clEndType = ClipperLib.EndType.etOpenSquare;
                break;
            }
            co.AddPath(path, JoinType.jtMiter, clEndType);
            co.Execute(ref solution, offset * clipperScale);  // important, scale also used here

            var result = new Polygon[solution.Count];

            for (var i = 0; i < result.Length; i++)
            {
                result[i] = solution[i].ToPolygon(tolerance);
            }
            return(result);
        }
Example #10
0
        public void GenerateCollision()
        {
            //List<List<Vector2>> polygons = new List<List<Vector2>>();

            List <List <Vector2> > unitedPolygons = new List <List <Vector2> >();
            Clipper clipper = new Clipper();

            int scalingFactor = 10000;

            for (int x = 0; x < layer.chunkSize_x; x++)
            {
                for (int y = 0; y < layer.chunkSize_y; y++)
                {
                    if (grid[x, y] != null && grid[x, y].colider)
                    {
                        Path newPoligons = new Path(4);

                        newPoligons.Add(new IntPoint(Mathf.Floor((0 + x) * scalingFactor), Mathf.Floor((0 + y) * scalingFactor)));
                        newPoligons.Add(new IntPoint(Mathf.Floor((0 + x) * scalingFactor), Mathf.Floor((1 + y) * scalingFactor)));
                        newPoligons.Add(new IntPoint(Mathf.Floor((1 + x) * scalingFactor), Mathf.Floor((1 + y) * scalingFactor)));
                        newPoligons.Add(new IntPoint(Mathf.Floor((1 + x) * scalingFactor), Mathf.Floor((0 + y) * scalingFactor)));

                        clipper.AddPath(newPoligons, PolyType.ptSubject, true);
                    }
                }
            }

            Paths solution = new Paths();

            clipper.Execute(ClipType.ctUnion, solution);

            ClipperOffset offset = new ClipperOffset();

            offset.AddPaths(solution, JoinType.jtMiter, EndType.etClosedPolygon);
            offset.Execute(ref solution, 5f);

            foreach (Path path in solution)
            {
                List <Vector2> unitedPolygon = new List <Vector2>();
                foreach (IntPoint point in path)
                {
                    unitedPolygon.Add(new Vector2(point.X / (float)scalingFactor, point.Y / (float)scalingFactor));
                }
                unitedPolygons.Add(unitedPolygon);
            }

            unitedPolygons = TileMap.RemoveClosePointsInPolygons(unitedPolygons);

            PolygonCollider2D collider = layer.map.gameObject.GetComponent <PolygonCollider2D>();

            collider.pathCount = unitedPolygons.Count;

            for (int i = 0; i < unitedPolygons.Count; i++)
            {
                Vector2[] points = unitedPolygons[i].ToArray();

                collider.SetPath(i, points);
            }
        }
Example #11
0
    //this function takes a list of polygons as a parameter, this list of polygons represent all the polygons that constitute collision in your level.
    public List <List <Vector2> > UniteCollisionPolygons(List <List <Vector2> > polygons)
    {
        //this is going to be the result of the method
        List <List <Vector2> > unitedPolygons = new List <List <Vector2> >();
        Clipper clipper = new Clipper();

        //clipper only works with ints, so if we're working with floats, we need to multiply all our floats by
        //a scaling factor, and when we're done, divide by the same scaling factor again
        int scalingFactor = 10000;

        //this loop will convert our List<List<Vector2>> to what Clipper works with, which is "Path" and "IntPoint"
        //and then add all the Paths to the clipper object so we can process them
        for (int i = 0; i < polygons.Count; i++)
        {
            Path allPolygonsPath = new Path(polygons[i].Count);

            for (int j = 0; j < polygons[i].Count; j++)
            {
                allPolygonsPath.Add(new IntPoint(Mathf.Floor(polygons[i][j].x * scalingFactor), Mathf.Floor(polygons[i][j].y * scalingFactor)));
                //print(new IntPoint(Mathf.Floor(polygons[i][j].x * scalingFactor), Mathf.Floor(polygons[i][j].y * scalingFactor)).X + ", " + new IntPoint(Mathf.Floor(polygons[i][j].x * scalingFactor), Mathf.Floor(polygons[i][j].y * scalingFactor)).Y);
            }
            clipper.AddPath(allPolygonsPath, PolyType.ptSubject, true);
        }

        //this will be the result
        Paths solution = new Paths();

        //having added all the Paths added to the clipper object, we tell clipper to execute an union
        clipper.Execute(ClipType.ctUnion, solution);


        //the union may not end perfectly, so we're gonna do an offset in our polygons, that is, expand them outside a little bit
        ClipperOffset offset = new ClipperOffset();

        offset.AddPaths(solution, JoinType.jtMiter, EndType.etClosedPolygon);
        //5 is the amount of offset
        offset.Execute(ref solution, 0.1f);


        //now we just need to convert it into a List<List<Vector2>> while removing the scaling
        foreach (Path path in solution)
        {
            List <Vector2> unitedPolygon = new List <Vector2>();
            foreach (IntPoint point in path)
            {
                unitedPolygon.Add(new Vector2(point.X / (float)scalingFactor, point.Y / (float)scalingFactor));
            }
            unitedPolygons.Add(unitedPolygon);
        }


        //this removes some redundant vertices in the polygons when they are too close from each other
        //may be useful to clean things up a little if your initial collisions don't match perfectly from tile to tile
        unitedPolygons = RemoveClosePointsInPolygons(unitedPolygons);

        //everything done
        return(unitedPolygons);
    }
Example #12
0
        /// <summary>
        /// Gets a parallel <see cref="Loxy"/> with offset
        /// </summary>
        /// <param name="JT">Jointype</param>
        /// <param name="ET">Endtype</param>
        /// <param name="Offset">Offset</param>
        /// <returns></returns>
        public Loxy GetOffset(JoinType JT, EndType ET, double Offset)
        {
            ClipperOffset           co       = new ClipperOffset();
            List <List <IntPoint> > Solution = new List <List <IntPoint> >();

            co.AddPaths(ToClipperPoly(this), (ClipperLib.JoinType)JT, (ClipperLib.EndType)ET);
            co.Execute(ref Solution, (long)(ToInt * Offset));
            return(FromClipperLoxy(Solution));
        }
Example #13
0
        public static void generateOutlineSegments()
        {
            Logger.logProgress("Generating outline segments");

            //Check if there should be at least one shell
            if (Global.Values.shellThickness < 1)
            {
                return;
            }

            //We need to got through every layercomponent
            //for (ushort i = 0; i < Global.Values.layerCount; i++)
            foreach (LayerComponent layer in Global.Values.layerComponentList)
            {
                Logger.logProgress("Outline: " + layer.layerNumber);

                //And every island inside the list
                foreach (Island island in layer.islandList)
                {
                    if (island.outlinePolygons.Count < 1)
                    {
                        continue;
                    }

                    //The first outline will be one that is half an extrusion thinner than the sliced outline, ths is sothat the dimensions
                    //do not change once extruded
                    Polygons      outline = new Polygons();
                    ClipperOffset offset  = new ClipperOffset();
                    offset.AddPaths(island.outlinePolygons, JoinType.jtMiter, EndType.etClosedPolygon);
                    offset.Execute(ref outline, -Global.Values.nozzleWidth / 2);

                    for (ushort j = 0; j < Global.Values.shellThickness; j++)
                    {
                        //Place the newly created outline in its own segment
                        LayerSegment outlineSegment = new LayerSegment(SegmentType.OutlineSegment);
                        outlineSegment.segmentType     = SegmentType.OutlineSegment;
                        outlineSegment.segmentSpeed    = layer.layerSpeed;
                        outlineSegment.outlinePolygons = new Polygons(outline);

                        island.segmentList.Add(outlineSegment);

                        var distance = (-Global.Values.nozzleWidth / 2) - Global.Values.nozzleWidth * (j + 1);

                        //We now shrink the outline with one extrusion width for the next shell if any
                        offset = new ClipperOffset();
                        offset.AddPaths(island.outlinePolygons, JoinType.jtMiter, EndType.etClosedPolygon);
                        offset.Execute(ref outline, distance);
                    }

                    //We now need to store the smallest outline as the new layer outline for infill trimming purposes
                    //the current outline though is just half an extrusion width to small
                    offset = new ClipperOffset();
                    offset.AddPaths(outline, JoinType.jtMiter, EndType.etClosedPolygon);
                    offset.Execute(ref island.outlinePolygons, Global.Values.nozzleWidth);
                }
            }
        }
Example #14
0
        static public ClipperPolygons Buffer(this ClipperPolygons polygons, double distance)
        {
            ClipperPolygons result = new ClipperPolygons();

            ClipperOffset co = new ClipperOffset();
            co.AddPaths(polygons, JoinType.jtRound, EndType.etClosedPolygon);
            co.Execute(ref result, distance * Acc);

            return result;
        }
        /// <summary>
        /// Simplifies an list INTPolygons using expand and shrink technique.
        /// </summary>
        /// <param name="polygons">The INTPolygons.</param>
        /// <param name="value">The value used for expand and shrink.</param>
        /// <returns>INTPolygons.</returns>
        public INTPolygons SimplifyINTPolygons(INTPolygons polygons, double value)
        {
            double        simplificationFactor = Math.Pow(10.0, this.PolygonalBooleanPrecision) * UnitConversion.Convert(value, Length_Unit_Types.FEET, UnitType);
            ClipperOffset clipperOffset        = new ClipperOffset();

            clipperOffset.AddPaths(polygons, ClipperLib.JoinType.jtMiter, EndType.etClosedPolygon);
            INTPolygons shrink = new INTPolygons();

            clipperOffset.Execute(ref shrink, -simplificationFactor);
            //expanding to return the polygons to their original position
            clipperOffset.Clear();
            clipperOffset.AddPaths(shrink, ClipperLib.JoinType.jtMiter, EndType.etClosedPolygon);
            INTPolygons expand = new INTPolygons();

            clipperOffset.Execute(ref expand, simplificationFactor);
            shrink        = null;
            clipperOffset = null;
            return(expand);
        }
Example #16
0
        public static Polygons Offset(this Polygons polygons, int distance)
        {
            ClipperOffset offseter = new ClipperOffset();

            offseter.AddPaths(polygons, JoinType.jtMiter, EndType.etClosedPolygon);
            Paths solution = new Polygons();

            offseter.Execute(ref solution, distance);
            return(solution);
        }
Example #17
0
        public static void calculateSupportSegments()
        {
            Logger.logProgress("Calculating support segments");

            if (!Global.Values.shouldSupportMaterial || Global.Values.supportMaterialDesnity <= 0)
            {
                return;
            }

            //To calculate the support segments we will keep a union of the above layers and perform a difference with them and the current layer
            Polygons topUnion = new Polygons();

            for (int i = Global.Values.layerCount - 1; i > -1; i--)
            {
                Polygons layerPolygons = new Polygons();

                foreach (Island island in Global.Values.layerComponentList[i].islandList)
                {
                    Polygons offsetResult = new Polygons();

                    ClipperOffset offset = new ClipperOffset();
                    offset.AddPaths(island.outlinePolygons, JoinType.jtMiter, EndType.etClosedPolygon);
                    offset.Execute(ref offsetResult, Global.Values.shellThickness * Global.Values.nozzleWidth);

                    Clipper clipper = new Clipper();
                    clipper.AddPaths(offsetResult, PolyType.ptClip, true);
                    clipper.AddPaths(layerPolygons, PolyType.ptSubject, true);
                    clipper.Execute(ClipType.ctUnion, layerPolygons);
                }

                Polygons supportOutline = new Polygons();
                Clipper  supportClipper = new Clipper();
                supportClipper.AddPaths(topUnion, PolyType.ptSubject, true);
                supportClipper.AddPaths(layerPolygons, PolyType.ptClip, true);
                supportClipper.Execute(ClipType.ctDifference, supportOutline);

                //We should just offset the support slightly so that it does not touch the rest of the model
                ClipperOffset clipperOffset = new ClipperOffset();
                clipperOffset.AddPaths(supportOutline, JoinType.jtMiter, EndType.etClosedPolygon);
                clipperOffset.Execute(ref supportOutline, -Global.Values.nozzleWidth);

                Island       supportIsland = new Island();
                LayerSegment segment       = new LayerSegment(SegmentType.SupportSegment);
                segment.segmentSpeed          = Global.Values.layerComponentList[i].supportSpeed;
                segment.outlinePolygons       = supportOutline;
                supportIsland.outlinePolygons = supportOutline;
                supportIsland.segmentList.Add(segment);
                Global.Values.layerComponentList[i].islandList.Add(supportIsland);

                Clipper unionClipper = new Clipper();
                unionClipper.AddPaths(topUnion, PolyType.ptClip, true);
                unionClipper.AddPaths(layerPolygons, PolyType.ptSubject, true);
                unionClipper.Execute(ClipType.ctUnion, topUnion);
            }
        }
Example #18
0
        /*
         *
         * Geometry features (Offset)
         *
         */

        public Polygon OffsetPolygon(float offset)
        {
            // Calculate Polygon-Clipper scale.
            float maximum = Mathf.Max(bounds.width, bounds.height) + offset * 2.0f + offset;
            float scale   = (float)Int32.MaxValue / maximum;

            // Convert to Clipper.
            Paths paths = new Paths();

            {
                Path path = new Path();
                EnumeratePoints((Vector2 eachPoint) =>
                {
                    path.Add(new IntPoint(eachPoint.x * scale, eachPoint.y * scale));
                });
                paths.Add(path);
            }
            foreach (Polygon eachPolygon in polygons)
            {
                Path path = new Path();
                eachPolygon.EnumeratePoints((Vector2 eachPoint) =>
                {
                    path.Add(new IntPoint(eachPoint.x * scale, eachPoint.y * scale));
                });
                paths.Add(path);
            }

            // Clipper offset.
            Paths         solutionPaths = new Paths();
            ClipperOffset clipperOffset = new ClipperOffset();

            clipperOffset.AddPaths(paths, JoinType.jtMiter, EndType.etClosedPolygon);
            clipperOffset.Execute(ref solutionPaths, (double)offset * scale);

            // Convert from Cipper.
            Polygon offsetPolygon = null;

            for (int index = 0; index < solutionPaths.Count; index++)
            {
                Path    eachSolutionPath    = solutionPaths[index];
                Polygon eachSolutionPolygon = PolygonFromClipperPath(eachSolutionPath, scale);

                if (index == 0)
                {
                    offsetPolygon = Polygon.PolygonWithPoints(eachSolutionPolygon.points);                     // Copy
                }
                else
                {
                    offsetPolygon.AddPolygon(eachSolutionPolygon);
                }
            }

            // Back to Polygon.
            return(offsetPolygon);
        }
Example #19
0
        private static Vector2[][] GenerateOpaqueOutline(Sprite sprite, float detail, byte alphaTolerance)
        {
            Vector2[][]             paths              = GenerateTransparentOutline(sprite, 1, alphaTolerance, true);
            List <List <IntPoint> > intPointList       = ConvertToIntPointList(paths, detail);
            List <List <IntPoint> > offsetIntPointList = new List <List <IntPoint> >();
            ClipperOffset           offset             = new ClipperOffset();

            offset.AddPaths(intPointList, JoinType.jtMiter, EndType.etClosedPolygon);
            offset.Execute(ref offsetIntPointList, -32);//TODO: magic number!
            return(ConvertToVector2Array(offsetIntPointList));
        }
Example #20
0
        public Paths offset(int distance)
        {
            Paths         solution2 = new Paths();
            ClipperOffset co        = new ClipperOffset();

            co.AddPaths(polygons, JoinType.jtRound, EndType.etClosedPolygon);
            //偏置时,偏置量需要先扩大Scale倍
            //co.MiterLimit = 2.0;
            co.Execute(ref solution2, distance);
            return(solution2);
        }
Example #21
0
        public override List <List <IntPoint> > GetCopyOfClipperPolygon(double relativeWidth, List <List <IntPoint> > outerPolygon)
        {
            var delta   = (-2 * relativeWidth) * ClosedSymbolBase.ClipperScalingInt;
            var clipper = new ClipperOffset();

            clipper.AddPaths(outerPolygon, JoinType.jtMiter, EndType.etClosedPolygon);
            var result = new List <List <IntPoint> >();

            clipper.Execute(ref result, delta);
            return(result);
        }
Example #22
0
        List <List <IntPoint> > Offset(List <List <IntPoint> > polygons, double delta)
        {
            var result = new List <List <IntPoint> >();

            var clipper = new ClipperOffset();

            clipper.AddPaths(polygons, JoinType.jtSquare, EndType.etClosedPolygon);
            clipper.Execute(ref result, delta);

            return(result);
        }
Example #23
0
        public Polygons Offset(Polygons polygons, double distance)
        {
            var offseter = new ClipperOffset();

            offseter.AddPaths(polygons, JoinType.jtRound, EndType.etClosedPolygon);

            var solution = new Polygons();

            offseter.Execute(ref solution, distance);

            return(solution);
        }
Example #24
0
        private void AddCharacterMeshes(string currentText, TypeFacePrinter printer)
        {
            int            newIndex = asyncMeshGroups.Count;
            StyledTypeFace typeFace = printer.TypeFaceStyle;

            for (int i = 0; i < currentText.Length; i++)
            {
                string          letter        = currentText[i].ToString();
                TypeFacePrinter letterPrinter = new TypeFacePrinter(letter, typeFace);

                if (CharacterHasMesh(letterPrinter, letter))
                {
#if true
                    Mesh textMesh = VertexSourceToMesh.Extrude(letterPrinter, unscaledLetterHeight / 2);
#else
                    Mesh textMesh = VertexSourceToMesh.Extrude(letterPrinter, unscaledLetterHeight / 2);
                    // this is the code to make rounded tops
                    // convert the letterPrinter to clipper polygons
                    List <List <IntPoint> > insetPoly = VertexSourceToPolygon.CreatePolygons(letterPrinter);
                    // inset them
                    ClipperOffset clipper = new ClipperOffset();
                    clipper.AddPaths(insetPoly, JoinType.jtMiter, EndType.etClosedPolygon);
                    List <List <IntPoint> > solution = new List <List <IntPoint> >();
                    clipper.Execute(solution, 5.0);
                    // convert them back into a vertex source
                    // merge both the inset and original vertex sources together
                    // convert the new vertex source into a mesh (trianglulate them)
                    // offset the inner loop in z
                    // create the polygons from the inner loop to a center point so that there is the rest of an approximation of the bubble
                    // make the mesh for the bottom
                    // add the top and bottom together
                    // done
#endif

                    asyncMeshGroups.Add(new MeshGroup(textMesh));

                    PlatingMeshGroupData newMeshInfo = new PlatingMeshGroupData();

                    newMeshInfo.spacing = printer.GetOffsetLeftOfCharacterIndex(i);
                    asyncPlatingDatas.Add(newMeshInfo);
                    asyncMeshGroupTransforms.Add(ScaleRotateTranslate.Identity());

                    PlatingHelper.CreateITraceableForMeshGroup(asyncPlatingDatas, asyncMeshGroups, newIndex, null);
                    ScaleRotateTranslate moved = asyncMeshGroupTransforms[newIndex];
                    moved.translation *= Matrix4X4.CreateTranslation(new Vector3(0, 0, unscaledLetterHeight / 2));
                    asyncMeshGroupTransforms[newIndex] = moved;

                    newIndex++;
                }

                processingProgressControl.PercentComplete = ((i + 1) * 95 / currentText.Length);
            }
        }
Example #25
0
        } /// <summary>

        /// 线两侧偏移后为矩形,偏移距离须与点的放大倍数一致
        /// </summary>
        public static Paths Offset(this Path _Path, double _offset, double magnification, EndType endType)
        {
            Paths         solution = new Paths();
            ClipperOffset _Co      = new ClipperOffset();

            _Co.MiterLimit = 3;
            _Co.AddPath(_Path, JoinType.jtMiter, endType);
            _Co.Execute(ref solution, _offset * magnification);
            //solution = Clipper.CleanPolygons(solution, Precision_.clipperMultiple * (0.003));
            //solution = Clipper.SimplifyPolygons(solution);
            return(solution);
        }
Example #26
0
        public static List <List <Vector2> > Outline(List <Vector2> polygon, FillMode fillMode, bool closed, StrokeStyle strokeStyle, float strokeWidth, out PolyTree tree)
        {
            List <List <Vector2> > simplified = Clipper.SimplifyPolygon(polygon, fillMode.ToPolyFillType());

            Offsetter.Clear();
            Offsetter.MiterLimit = strokeStyle.MiterLimit;
            Offsetter.AddPaths(simplified, (JoinType)strokeStyle.LineJoin, closed ? EndType.etClosedLine : strokeStyle.CapStyle.ToEndType());

            tree = new PolyTree();
            Offsetter.Execute(ref tree, strokeWidth / 2);
            return(Clipper.ClosedPathsFromPolyTree(tree));
        }
Example #27
0
        private void InsetPath()
        {
            var path = this.Children.OfType <IPathObject>().FirstOrDefault();

            if (path == null)
            {
                // clear our existing data
                VertexSource = new VertexStorage();
                return;
            }

            var aPolys = path.VertexSource.CreatePolygons();

            var offseter = new ClipperOffset();

            var outlineWidth = OutlineWidth.Value(this);
            var ratio        = Ratio.Value(this);

            offseter.AddPaths(aPolys, InflatePathObject3D.GetJoinType(OuterStyle), EndType.etClosedPolygon);
            var outerLoops = new List <List <IntPoint> >();

            offseter.Execute(ref outerLoops, outlineWidth * ratio * 1000);
            Clipper.CleanPolygons(outerLoops);

            offseter.AddPaths(aPolys, InflatePathObject3D.GetJoinType(InnerStyle), EndType.etClosedPolygon);
            var innerLoops = new List <List <IntPoint> >();

            offseter.Execute(ref innerLoops, -outlineWidth * (1 - ratio) * 1000);
            Clipper.CleanPolygons(innerLoops);

            var allLoops = outerLoops;

            allLoops.AddRange(innerLoops);

            VertexSource = allLoops.CreateVertexStorage();

            (VertexSource as VertexStorage).Add(0, 0, ShapePath.FlagsAndCommand.Stop);
        }
Example #28
0
        public static List <NestPath> polygonOffset(NestPath polygon, double offset)
        {
            List <NestPath> result = new List <NestPath>();

            if (offset == 0 || GeometryUtil.almostEqual(offset, 0))
            {
                /**
                 * return EmptyResult
                 */
                return(result);
            }
            Path p = new Path();

            foreach (Segment s in polygon.getSegments())
            {
                ClipperCoor cc = toClipperCoor(s.getX(), s.getY());
                p.Add(new IntPoint(cc.getX(), cc.getY()));
            }

            int           miterLimit = 2;
            ClipperOffset co         = new ClipperOffset(miterLimit, Config.CURVE_TOLERANCE * Config.CLIIPER_SCALE);

            co.AddPath(p, JoinType.jtRound, EndType.etClosedPolygon);

            Paths newpaths = new Paths();

            co.Execute(ref newpaths, offset * Config.CLIIPER_SCALE);


            /**
             * 这里的length是1的话就是我们想要的
             */
            for (int i = 0; i < newpaths.Count; i++)
            {
                result.Add(CommonUtil.clipperToNestPath(newpaths[i]));
            }

            if (offset > 0)
            {
                NestPath from = result[0];
                if (GeometryUtil.polygonArea(from) > 0)
                {
                    from.reverse();
                }
                from.add(from.get(0)); from.getSegments().RemoveAt(0);
            }


            return(result);
        }
Example #29
0
        public List <GameObject> CreateStreets(List <List <Vector3> > streetsPoly)
        {
            List <GameObject> streets = new List <GameObject> ();

            for (int i = 0; i < streetsPoly.Count; i++)
            {
                GameObject street = new GameObject("street" + i, typeof(MeshRenderer), typeof(MeshFilter));
                street.transform.parent = this.transform;
                street.GetComponent <MeshRenderer> ().material = (Material)Resources.Load("StreetMat");

                List <List <IntPoint> > solution = new List <List <IntPoint> > ();
                //transform vertices of each mesh in points for clipper
                List <IntPoint> intPoint = FromVecToIntPoint(streetsPoly [i].ToArray());
                //offset each mesh
                ClipperOffset co = new ClipperOffset();
                co.AddPath(intPoint, JoinType.jtRound, EndType.etOpenRound);
                co.Execute(ref solution, 700.0);

                List <Vector2> vertices2D = new List <Vector2> ();
                for (int j = 0; j < solution.Count; j++)
                {
                    vertices2D = vertices2D.Concat(FromIntPointToVec(solution [j])).ToList();
                }

                // Use the triangulator to get indices for creating triangles
                Triangulator tr      = new Triangulator(vertices2D.ToArray());
                int[]        indices = tr.Triangulate();

                // Create the Vector3 vertices
                Vector3[] vertices = new Vector3[vertices2D.Count];
                for (int k = 0; k < vertices.Length; k++)
                {
                    vertices [k] = new Vector3(vertices2D [k].x, 0f, vertices2D [k].y);
                }
                // Create the mesh
                Mesh msh = new Mesh();
                msh.vertices  = vertices;
                msh.triangles = indices;
                msh.RecalculateNormals();
                msh.RecalculateBounds();

                // Set up game object with mesh;
                street.GetComponent <MeshFilter> ().mesh = msh;
                street.AddComponent <MeshCollider> ();
                street.transform.position = new Vector3(street.transform.position.x, 0.02f, street.transform.position.z);
                streets.Add(street);
            }
            DrawStreetLineMesh(streetsPoly, streets);
            return(streets);
        }
Example #30
0
        private Polygons GetOffsetPolugon(Polygons source, double offset)
        {
            if (offset != 0)
            {
                Polygons solution2 = new Polygons();

                ClipperOffset co = new ClipperOffset();
                co.AddPaths(source, JoinType.jtRound, EndType.etClosedPolygon);
                co.Execute(ref solution2, offset);
                return(solution2);
            }

            return(new Polygons(source));
        }
        protected internal virtual Path FilterStrokePath(Path path, Matrix ctm, float lineWidth, int lineCapStyle,
                                                int lineJoinStyle, float miterLimit, LineDashPattern lineDashPattern) {
            JoinType joinType = GetJoinType(lineJoinStyle);
            EndType endType = GetEndType(lineCapStyle);

            if (lineDashPattern != null) {
                if (IsZeroDash(lineDashPattern)) {
                    return new Path();
                }
                
                if (!IsSolid(lineDashPattern)) {
                    path = ApplyDashPattern(path, lineDashPattern);
                }
            }

            ClipperOffset offset = new ClipperOffset(miterLimit, PdfCleanUpProcessor.ArcTolerance * PdfCleanUpProcessor.FloatMultiplier);
            AddPath(offset, path, joinType, endType);

            PolyTree resultTree = new PolyTree();
            offset.Execute(ref resultTree, lineWidth * PdfCleanUpProcessor.FloatMultiplier / 2);

            return FilterFillPath(ConvertToPath(resultTree), ctm, PathPaintingRenderInfo.NONZERO_WINDING_RULE);
        }
Example #32
0
 public static Polygons Offset(this Polygons polygons, int distance)
 {
     ClipperOffset offseter = new ClipperOffset();
     offseter.AddPaths(polygons, JoinType.jtMiter, EndType.etClosedPolygon);
     Paths solution = new Polygons();
     offseter.Execute(ref solution, distance);
     return solution;
 }
Example #33
0
        protected internal Path FilterStrokePath(Path sourcePath, Matrix ctm, float lineWidth, int lineCapStyle,
                                int lineJoinStyle, float miterLimit, LineDashPattern lineDashPattern) {
            Path path = sourcePath;
            JoinType joinType = GetJoinType(lineJoinStyle);
            EndType endType = GetEndType(lineCapStyle);

            if (lineDashPattern != null && !lineDashPattern.IsSolid()) {
                path = ApplyDashPattern(path, lineDashPattern);
            }

            ClipperOffset offset = new ClipperOffset(miterLimit, PdfCleanUpProcessor.ArcTolerance * PdfCleanUpProcessor.FloatMultiplier);
            IList<Subpath> degenerateSubpaths = AddPath(offset, path, joinType, endType);

            PolyTree resultTree = new PolyTree();
            offset.Execute(ref resultTree, lineWidth * PdfCleanUpProcessor.FloatMultiplier / 2);
            Path offsetedPath = ConvertToPath(resultTree);

            if (degenerateSubpaths.Count > 0) {
                if (endType == EndType.etOpenRound) {
                    IList<Subpath> circles = ConvertToCircles(degenerateSubpaths, lineWidth / 2);
                    offsetedPath.AddSubpaths(circles);
                } else if (endType == EndType.etOpenSquare && lineDashPattern != null) {
                    IList<Subpath> squares = ConvertToSquares(degenerateSubpaths, lineWidth, sourcePath);
                    offsetedPath.AddSubpaths(squares);
                }
            }

            return FilterFillPath(offsetedPath, ctm, PathPaintingRenderInfo.NONZERO_WINDING_RULE);
        }