public RectangleD Identicon(PointD center, double size, string thingtohash, bool top = true) { size *= 2; var H = GetHash(thingtohash); Int32 r = 0; for (int i = 0; i < Math.Min(4, H.Length); i++) { r += (int)H[i] << (int)(i * 8); } for (int ix = 0; ix < 4; ix++) { for (int iy = 0; iy < 4; iy++) { int b = ix + iy * 4; bool fill = ((r >> b) & 0x1) > 0 ? true : false; if (fill) { PolyLine P1 = new PolyLine(); P1.MakePRectangle(size / 8, size / 8, (ix - 3.5) * size / 8 + center.X, (iy - 3.5) * size / 8 + center.Y); TopSilk.AddPolyLine(P1, 0.01); } } } return(new RectangleD() { X = center.X - size / 2, Y = center.Y - size / 2, Height = size, Width = size }); }
public void AddBoardHole(PointD pos, double diameter) { PolyLine PL = new PolyLine(); PL.MakeCircle(diameter / 2.0, 20, pos.X, pos.Y); Outline.AddPolyLine(PL, 0); }
public static void PolyLine() { Polygon polygon = new Polygon(bowTieNonCrossingSegments); PolyLine polyline = polygon.PolyLine(); Assert.AreEqual(bowTieNonCrossingSegments[2], polyline[2].I); }
public void Transform(PolyLine pline) { for (int i = 0; i < pline.Vertices.Count; i++) { this.Transform(pline.Vertices[i]); } }
static void Main(string[] args) { string basepath = Directory.GetCurrentDirectory(); Directory.CreateDirectory(Path.Combine(basepath, "outline")); Directory.CreateDirectory(Path.Combine(basepath, "frame")); GerberFrameWriter.FrameSettings FS = new GerberFrameWriter.FrameSettings(); PolyLine PL = new PolyLine(); FS.FrameTitle = "Test Frame"; FS.RenderSample = false; FS.margin = 3; PL.MakeRoundedRect(new PointD(10, 10), new PointD(200, 200), 7); FS.PositionAround(PL); //FS.offset = new PointD(200, 200); FS.RenderSample = true; GerberArtWriter GAW = new GerberArtWriter(); GAW.AddPolyLine(PL); GAW.Write("outline/outtestinside.gko"); GerberFrameWriter.WriteSideEdgeFrame(PL, FS, "frame/outtest"); GerberFrameWriter.MergeFrameIntoGerberSet(Path.Combine(basepath, "frame"), Path.Combine(basepath, "outline"), Path.Combine(basepath, "mergedoutput"), FS, new FrameCreatorTest(), "testframe"); GerberFrameWriter.MergeFrameIntoGerberSet(Path.Combine(basepath, "SliceFrameOutline6"), Path.Combine(basepath, "Slice6"), Path.Combine(basepath, "slice6inframe"), FS, new FrameCreatorTest(), "slice6framed"); // PNL.SaveOutlineTo("panelized.gko", "panelcombinedgko.gko"); }
protected override void OnInitializing(EventArgs e) { base.OnInitializing(e); Vector2[] innerPoints = { new Vector2(CutCornerLength, 0), new Vector2(Width - CutCornerLength, 0), new Vector2(Width, CutCornerLength), new Vector2(Width, Height - CutCornerLength), new Vector2(Width - CutCornerLength, Height), new Vector2(CutCornerLength, Height), new Vector2(0, Height - CutCornerLength), new Vector2(0, CutCornerLength) }; float innerOffset = OutlineThickness / (float)Math.Sqrt(2); Vector2[] outerPoints = { new Vector2(2 * innerOffset, innerOffset), new Vector2(Width - 2 * innerOffset, innerOffset), new Vector2(Width - innerOffset, 2 * innerOffset), new Vector2(Width - innerOffset, Height - 2 * innerOffset), new Vector2(Width - 2 * innerOffset, Height - innerOffset), new Vector2(2 * innerOffset, Height - innerOffset), new Vector2(innerOffset, Height - 2 * innerOffset), new Vector2(innerOffset, 2 * innerOffset) }; PolyLine outerShape = ToDispose(PolyLine.New(string.Format("CC.Outer.{0}", Name), Device, innerPoints, FigureBegin.Filled, FigureEnd.Closed)); PolyLine innerShape = ToDispose(PolyLine.New(string.Format("CC.Inner.{0}", Name), Device, outerPoints, FigureBegin.Filled, FigureEnd.Closed)); shape = ToDispose(GeometryGroup.New(string.Format("CC.{0}", Name), Device, FillMode.Alternate, new[] { innerShape, outerShape, })); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiApp = commandData.Application; UIDocument uiDoc = uiApp.ActiveUIDocument; Document doc = uiDoc.Document; Selection sel = uiApp.ActiveUIDocument.Selection; //pick a point List <XYZ> points = new List <XYZ>(); for (int i = 0; i < 5; i++) { XYZ point = sel.PickPoint("pick a point inside a room"); points.Add(point); } PolyLine polyline = PolyLine.Create(points); using (Transaction tx = new Transaction(doc)) { tx.Start("create wall section view"); foreach (XYZ point in points) { XYZElement e = new XYZElement(doc, point); } tx.Commit(); } return(Result.Succeeded); }
BuildCellWithIndex(List <GeoPoint> points, double[] envelope = null, double minDistanceTolerance = 1e-8) { var tysonPts = points.Select(e => new TysonGeoPoint(e)).ToList(); envelope ??= GetEnvelope(tysonPts); var polygonBuilder = new PolygonBuilder(); var result = polygonBuilder .BuildWithIndex(tysonPts, envelope, minDistanceTolerance); var polygonRes = new Dictionary <int, Polygon>(); foreach (var item in result) { var geoPoints = new List <GeoPoint>(); foreach (var tysonGeoPoint in item.Value) { geoPoints.Add(tysonGeoPoint); } PolyLine polyLine = new PolyLine(geoPoints); var polygon = new Polygon(polyLine); polygonRes.Add(item.Key, polygon); } return(polygonRes); }
public void PolyCurveDomainInPolygon2() { var pline = new PolyLine( new Vector(0, 0), new Vector(0, 10), new Vector(-20, 10), new Vector(-20, 0)); pline.Close(); var polyCrv = pline.ToPolyCurve(); var polygon = new Vertex[] { new Vertex(-10, 0), new Vertex(-0.0001, 0), new Vertex(-0.0001, -10), new Vertex(-10, -10) }; var ints = Intersect.CurveDomainInPolygonXY(polyCrv, polygon); Assert.AreEqual(1, ints.Count); Assert.AreEqual(0.875, ints[0].Start); Assert.AreEqual(0.99999875, ints[0].End); }
private void VoronoiButton_Click(object sender, RoutedEventArgs e) { Random rng = null; if (VoronoiSeedBox.Text.IsNumeric()) { int seed = int.Parse(VoronoiSeedBox.Text); rng = new Random(seed); } else { rng = new Random(); } BoundingBox box = new BoundingBox(0, 10, -10, 0, 0, 0); int size = 500; Geometry.Vector[] points = box.RandomPointsInside(rng, size); VertexCollection verts = new VertexCollection(points); MeshFaceCollection faces = Mesh.DelaunayTriangulationXY(verts, null, box, false); Dictionary <Vertex, MeshFace> voronoi = Mesh.VoronoiFromDelaunay(verts, faces); MeshFaceCollection outFaces = new MeshFaceCollection(voronoi.Values); PolyLine rect = PolyLine.Rectangle(0, -10, 10, 0); outFaces = outFaces.TrimToPolygonXY(rect.Vertices); outFaces = outFaces.TrimToPolygonXY(rect.Vertices); //Test duplicate edges VertexGeometryCollection geometry = new VertexGeometryCollection(outFaces.ExtractFaceBoundaries()); //ShapeCollection geometry = faces.ExtractFaceBoundaries(); geometry.Add(new Cloud(verts.ExtractPoints())); VoronoiCanvas.Geometry = geometry; }
private static void SmoothingLine(PolyLine line) { List <FloatDouble> Points = line.Points; List <Int16Double> Edges = line.Edges; List <int>[] adjinfo = new List <int> [Points.Count]; for (int i = 0; i < Points.Count; i++) { adjinfo[i] = new List <int>(2); } for (int i = 0; i < Edges.Count; i++) { adjinfo[Edges[i].X].Add(Edges[i].Y); adjinfo[Edges[i].Y].Add(Edges[i].X); } FloatDouble[] tempPos = new FloatDouble[Points.Count]; for (int i = 0; i < Points.Count; i++) { FloatDouble ap0 = Points[adjinfo[i][0]]; FloatDouble ap1 = Points[adjinfo[i][1]]; tempPos[i].X = (ap0.X + ap1.X) / 2.0f; tempPos[i].Y = (ap0.Y + ap1.Y) / 2.0f; } for (int i = 0; i < Points.Count; i++) { Points[i] = tempPos[i]; } }
private void WriteContained(PolyLine boundary, string outputfilename, ProgressLog log) { ExcellonFile Out = new ExcellonFile(); foreach (var T in Tools) { Out.Tools[T.Key] = new ExcellonTool() { ID = T.Value.ID, Radius = T.Value.Radius }; foreach (var d in T.Value.Drills) { if (boundary.PointInPoly(new PointD(d.X, d.Y))) { Out.Tools[T.Key].Drills.Add(d); } } foreach (var d in T.Value.Slots) { if (boundary.PointInPoly(d.Start) || boundary.PointInPoly(d.End)) { Out.Tools[T.Key].Slots.Add(d); } } } Out.Write(outputfilename, 0, 0, 0, 0); }
private bool IsPointOnCurve(PolyLine polyline, ReferencePoint point) { var coords = polyline.GetCoordinates(); for (int i = 0; i < coords.Count - 1; i++) { var start = coords[i]; var end = coords[i + 1]; var dir = end - start; var test = point.Position - start; var area = test.CrossProduct(dir); if (!area.IsZeroLength()) { continue; } var delta = Math.Abs(dir.GetLength() - test.GetLength() - (point.Position - end).GetLength()); if (delta > 1e-5) { continue; } return(true); } return(false); }
private void saveArtworkgerberToolStripMenuItem_Click(object sender, EventArgs e) { if (gerbersaveFileDialog1.ShowDialog() == DialogResult.OK) { try { GerberArtWriter GAW = new GerberArtWriter(); double S = 72.0 / 200.0; foreach (var a in ArtRender.SubDivPoly) { PolyLine PL = new PolyLine(PolyLine.PolyIDs.ArtWork); PL.Add(a.Vertices[0].x * S, (Mask.Height - a.Vertices[0].y) * S); PL.Add(a.Vertices[1].x * S, (Mask.Height - a.Vertices[1].y) * S); PL.Add(a.Vertices[2].x * S, (Mask.Height - a.Vertices[2].y) * S); PL.Add(a.Vertices[0].x * S, (Mask.Height - a.Vertices[0].y) * S); GAW.AddPolyLine(PL, 0.1); } GAW.Write(gerbersaveFileDialog1.FileName); } catch (Exception) { } } }
public static void SelfIntersectionTest() { var pline = PolyLine.Rectangle(2, 2); bool test = pline.IsSelfIntersectingXY(); Core.Print(test.ToString()); }
public void ExecuteInThread() { if (splineSys == null) { Stage = PreviewStage.Blank; return; } //line Vector3[][] points = splineSys.GetAllPoints(resPerUnit: 0.2f, minRes: 3, maxRes: 20); for (int l = 0; l < points.Length; l++) { for (int p = 0; p < points[l].Length; p++) { points[l][p] = new Vector3(points[l][p].x / worldSize.x, points[l][p].y / worldHeight, points[l][p].z / worldSize.z); } } if (polyLine == null) { polyLine = new PolyLine(0); } polyLine.SetPointsThread(points); //nodes PrepareNodesMeshArrays(); CoroutineManager.Enqueue(ApplyInMain, priority: -1000); }
public void AddPolygon(Polygon a) { PolyLine P = new PolyLine(PolyLine.PolyIDs.Outline); P.fromPolygon(a); AddPolyLine(P); }
public void Returns_A_Ruled_Surface_Between_A_Polyline_And_A_Nurbs_Curve(double u, double v, double[] pt) { // Arrange Point3 expectedPt = new Point3(pt[0], pt[1], pt[2]); List <Point3> ptsA = new List <Point3> { new Point3(0, 0, 0), new Point3(0, 0, 5), new Point3(5, 0, 5), new Point3(5, 0, 0), new Point3(10, 0, 0) }; List <Point3> ptsB = new List <Point3> { new Point3(0, 10, 0), new Point3(0, 10, 5), new Point3(5, 10, 5), new Point3(5, 10, 0), new Point3(10, 10, 0) }; PolyLine poly = new PolyLine(ptsA); NurbsCurve curveB = new NurbsCurve(ptsB, 2); // Act NurbsSurface ruledSurface = NurbsSurface.Ruled(poly, curveB); Point3 pointAt = ruledSurface.PointAt(u, v); // Assert pointAt.EpsilonEquals(expectedPt, GSharkMath.MinTolerance).Should().BeTrue(); }
/// <summary> /// 解析多点要素 /// </summary> /// <param name="recordContents"></param> /// <returns></returns> private static List <PolyLine> GetMultiPolyLineParts(byte[] recordContents) { //获取几何分了几部分,以及所有坐标点的数量 PolyRecordFields recordNums = new PolyRecordFields(recordContents); //获取记录中的所有的坐标点 var points = GetPolyPoints(recordNums.NumPoints, recordNums.NumParts, recordContents); //按照部分划分这些点 List <PolyLine> multiparts = new List <PolyLine>(); //获取每部分点的开始索引 int[] partIndex = GetRecordPartOffsets(recordNums.NumParts, recordContents); var partsNum = partIndex.Length; //循环以生成各个部分的点 for (int n = 0; n < partsNum; n++) { //判断这是不是最后一部分点,并计算本部分点共有多少个 int numPointsInPart = n < partsNum - 1 ? partIndex[n + 1] - partIndex[n] : recordNums.NumPoints - partIndex[n]; //取出当前这部分的点 var partPoints = points.Skip(partIndex[n]).Take(numPointsInPart).ToList(); PolyLine multiPoint = new PolyLine(partPoints); multiparts.Add(multiPoint); } return(multiparts); }
public static void Main(string[] args) { ColoredPoint obj = new ColoredPoint(2, 3, "black"); ColoredLine obj1 = new ColoredLine(1, 2, 3, 4, "red"); Line obj2 = new Line(1, 2, 3, 4); PolyLine obj3 = new PolyLine(1, 2, 3, 4, 5, 6, 7, 8); }
private void AddPolyLines(List <IShape> shapes) { Point p1 = new Point(2, 3); Point p2 = new Point(5, 8); Point p3 = new Point(12, 6); Point p4 = new Point(14, 1); Point p5 = new Point(0, -6); Point p6 = new Point(3, 3); Point p7 = new Point(8, -2); PolyLine pl1 = new PolyLine(new List <Point> { p1, p2, p3, p4 }); PolyLine pl2 = new PolyLine(new List <Point> { p5, p6, p7 }); shapes.Add(pl1); shapes.Add(pl2); PolyLineUsingCompositeShape plucs = new PolyLineUsingCompositeShape(new List <Point> { p1, p2, p3, p4 }); shapes.Add(plucs); }
public static List <Point3d> GetBoundaryLine2d(List <Int16Triple> regionPoints, bool smoothing, int iteration) { Box3Int box = GetBox3(regionPoints); int stx = 0, sty = 0; BitMap2d bmp_1 = GetMappedBitmap(regionPoints, box, ref stx, ref sty); // bmp_1.OutputBitMap("1.bmp"); BitMap2d bmp_2 = GetSingleRegionBitmap(bmp_1); // bmp_2.OutputBitMap("2.bmp"); bmp_1 = null; SquarSurface mc2 = new SquarSurface(bmp_2); PolyLine polyline = mc2.GenerateLine(); if (smoothing && iteration >= 1) { for (int i = 0; i < iteration; i++) { SmoothingLine(polyline); } } // PlyManager.Output2(polyline.Points,polyline.Edges,"3.ply"); List <FloatDouble> points = polyline.GetDrawablePointList(); List <Point3d> ret = new List <Point3d>(points.Count); for (int i = 0; i < points.Count; i++) { ret.Add(new Point3d(points[i].X + stx, points[i].Y + sty, 0)); } return(ret); }
public void It_Returns_The_Intersection_Points_Between_A_Polyline_And_A_Plane() { // Arrange Point3[] pts = new[] { new Point3(-1.673787, -0.235355, 14.436008), new Point3(13.145523, 6.066452, 0), new Point3(2.328185, 22.89864, 0), new Point3(18.154088, 30.745098, 7.561387), new Point3(18.154088, 12.309505, 7.561387) }; Point3[] intersectionChecks = new[] { new Point3(10, 4.728841, 3.064164), new Point3(10, 10.961005, 0), new Point3(10, 26.702314, 3.665482) }; PolyLine poly = new PolyLine(pts); Plane pl = Plane.PlaneYZ.SetOrigin(new Point3(10, 20, 5)); // Act var intersections = Intersect.PolylinePlane(poly, pl); // Assert intersections.Count.Should().Be(intersectionChecks.Length); for (int i = 0; i < intersectionChecks.Length; i++) { intersections[i].EpsilonEquals(intersectionChecks[i], GSharkMath.MaxTolerance).Should().BeTrue(); } }
/// <summary> /// 添加顶点 /// </summary> private void AddPoint() { PolyLine.AddOrSetVertexAt(PolyLine.NumberOfVertices, new Point2d(TemPoint2d.X, TemPoint2d.Y), 0, 0, 0); if (NumberOfVertices == 1 && PolyLine.ObjectId == new ObjectId()) { PolyLine.AddToModelSpace(DataBaseTools.DocumentDatabase()); } }
public void PositionAround(PolyLine pL) { var B = pL.GetBounds(); offset = new PointD(B.TopLeft.X - leftEdge - margin, B.TopLeft.Y - topEdge - margin); innerWidth = B.Width() + margin * 2; innerHeight = B.Height() + margin * 2; }
/// <summary> /// Convert a FreeBuid polyline to a netDXF one /// </summary> /// <param name="polyline"></param> /// <returns></returns> public static nDE.Polyline Convert(PolyLine polyline) { var result = new nDE.Polyline(Convert(polyline.Vertices.ExtractPoints())); result.IsClosed = polyline.Closed; SetAttributes(result, polyline.Attributes); return(result); }
/// <summary> /// Skews the specified shape to the skewing of a containing box. /// </summary> /// <param name="stationaryReferencePoint">The stationary reference point of the skew box.</param> /// <param name="skewingReferencePoint">The skewing reference point of the skew box.</param> /// <param name="magnitude">The magnitude to skew along the x-axis and y-axis.</param> /// <returns>IPathSegment.</returns> public Shape Skew( CartesianCoordinate stationaryReferencePoint, CartesianCoordinate skewingReferencePoint, CartesianOffset magnitude) { _polyline = new PolyLine(skew(stationaryReferencePoint, skewingReferencePoint, magnitude)); return(this); }
/// <summary> /// Determines whether the specified polyline forms a valid polygon. /// </summary> /// <param name="polyline">The polyline.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> /// <exception cref="ArgumentException">Invalid shape: Polygon must have at least 3 coordinates + 1 for closure = 4.</exception> public static bool CheckValidPolygon(PolyLine polyline) { if (polyline.CountPoints < 4) { throw new ArgumentException("Invalid shape: Polygon must have at least 3 coordinates + 1 for closure = 4."); } return(CheckValidShape(polyline)); }
public static dynamic GetTSObject(PolyLine dynObject) { if (dynObject is null) { return(null); } return(dynObject.teklaObject); }
void loadXML() { // DestroyObject(go); //if (done || !GetComponent<MapChunkManager>().isReady) // return; PolyLine pl = new PolyLine("TESTINGTRACER"); pl.heigth = 1; pl.width = 3; pl.material = Resources.Load("Materials/blinker") as Material; float offsetPositionX = GetComponent<MapChunkManager>().offsetX; float offsetPositionZ = GetComponent<MapChunkManager>().offsetZ; pl.SetOffset(offsetPositionX, offsetPositionZ); XmlDocument XMLFile = new XmlDocument(); XMLFile.LoadXml(gpsLog.text); XmlNodeList coords = XMLFile.GetElementsByTagName("trkpt"); List<Node> nodes = new List<Node>(); GeoUTMConverter convertor; foreach (XmlNode coord in coords) { // coord.Attributes["lat"].Value // coord.Attributes["lon"].Value Node n = new Node(); n.lat = double.Parse(coord.Attributes["lat"].Value); n.lon = double.Parse(coord.Attributes["lon"].Value); convertor = new GeoUTMConverter(); convertor.ToUTM(n.lat,n.lon); n.northing = convertor.Y; n.easthing = convertor.X; nodes.Add(n); } for (int a = 0; a < nodes.Count -1; a++) { Node n = nodes[a]; Vector3 position = new Vector3((float)(n.easthing - offsetPositionX), 99999, (float)(n.northing - offsetPositionZ)); float baseHeight = 0; RaycastHit hit; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity)) { baseHeight = hit.point.y; } n.height = baseHeight + 1f; pl.Add(n); // Debug.Log("Node is " + (float)(n.easthing - offsetPositionX) + "|" + (float)(n.northing - offsetPositionZ) + "|" + n.height); // Color random = new Color(((float)n.easthing % 255) / 255f, ((float)n.northing % 255) / 255f, ((float)n.easthing % 255) / 255f); // Debug.DrawLine(new Vector3((float)nodes[a].easthing - offsetPositionX, 200, (float)nodes[a].northing - offsetPositionZ), new Vector3((float)nodes[a + 1].easthing - offsetPositionX, 200, (float)nodes[a + 1].northing - offsetPositionZ), random,300); } // foreach (Node node in nodes) { // pl.Add (node); // } GameObject go = new GameObject(); go.transform.position = transform.position; pl.Close(go); done = true; }
private static PolyLine CreateTerrainLine(Terrain terrain) { Vector3[] lineArr = CreateLinePoints(terrain); PolyLine polyLine = new PolyLine(lineArr.Length); polyLine.SetPoints(lineArr); return(polyLine); }
public override IEnumerator Build(Way w, MapChunkLoader mcl) { //GameObject go = new GameObject(); //go.name = "Road"; GameObject road = new GameObject(); road.name = "Road - " + w.id.ToString(); road.isStatic = true; road.transform.parent = mcl.transform; string roadPath = Application.persistentDataPath + "Assets/Resources/Objs/" + road.name + ".obj"; if (!File.Exists(roadPath)) // If the file isn't cached we calculate everything and then we cache it { Debug.Log("STARTED CREATING ROAD"); PolyLine pl = new PolyLine(w.id.ToString()); pl.SetOffset(mcl.offsetPositionX, mcl.offsetPositionZ); pl.heigth = w.height; if (w.type == WayType.Footway) { pl.material = Resources.Load("Materials/Footway Material") as Material; pl.width = 1; } if (w.type == WayType.Motorway) { pl.material = Resources.Load("Materials/Road Material") as Material; pl.width = 4; pl.lanes = 2; } if (w.type == WayType.Residential) { pl.material = Resources.Load("Materials/Road Material") as Material; pl.width = 2; } if (w.type == WayType.River) { pl.material = Resources.Load("Materials/River Material") as Material; pl.width = 8; } for (int a = 0; a < w.nodes.Count; a++) { Node n = w.nodes[a]; Vector3 position = new Vector3((float)(n.easthing - mcl.offsetPositionX), 5000, (float)(n.northing - mcl.offsetPositionZ)); float baseHeight = 0; RaycastHit hit; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, mcl.layerMask)) { baseHeight = hit.point.y; } n.height = baseHeight; pl.Add(n); } //Closed road; mcl.StartCoroutine(pl.Close(road)); if (mcl.exportObjs) { while (road.GetComponent<MeshFilter>() == null) { yield return null; } MeshFilter mf = road.GetComponent<MeshFilter>(); ObjExporter oe = new ObjExporter(); oe.MeshToFile(mf, roadPath); } } else { ObjImporter oi = new ObjImporter(); mcl.StartCoroutine(oi.FileToMesh("file://" + roadPath)); while (oi._myMesh == null) { yield return null; } MeshFilter mf = road.AddComponent<MeshFilter>(); MeshRenderer mr = road.AddComponent<MeshRenderer>(); mf.sharedMesh = oi._myMesh; Debug.LogWarning("Loaded Road from cache " + roadPath); if (w.type == WayType.Footway) { mr.material = Resources.Load("Materials/Footway Material") as Material; } if (w.type == WayType.Motorway) { mr.material = Resources.Load("Materials/Road Material") as Material; } if (w.type == WayType.Residential) { mr.material = Resources.Load("Materials/Road Material") as Material; } if (w.type == WayType.River) { mr.material = Resources.Load("Materials/River Material") as Material; } } }
private void CreateRoad(Way w) { //GameObject go = new GameObject(); //go.name = "Road"; PolyLine pl = new PolyLine(w.id.ToString()); pl.SetOffset(offsetPositionX, offsetPositionZ); pl.heigth = w.height; if (w.type == WayType.Footway) { pl.material = Resources.Load("Materials/Footway Material") as Material; pl.width = 1; } if (w.type == WayType.Motorway) { pl.material = Resources.Load("Materials/Road Material") as Material; pl.width = 4; pl.lanes = 2; } if (w.type == WayType.Residential) { pl.material = Resources.Load("Materials/Road Material") as Material; pl.width = 2; } if (w.type == WayType.River) { pl.material = Resources.Load("Materials/River Material") as Material; pl.width = 8; } //Road road = go.AddComponent<Road>(); //road.groundOffset = 0.01f; //road.points.Clear(); //road.roadWidth = 0.1f;// (float)(road.roadWidth/precision); //road.mat = (Material)Resources.LoadAssetAtPath("Assets/RoadTool/Example/Texture/Materials/Road.mat", typeof(Material)); for (int a = 0; a < w.nodes.Count; a++) { Node n = w.nodes[a]; Vector3 position = new Vector3((float)(n.easthing - offsetPositionX), 5000, (float)(n.northing - offsetPositionZ)); float baseHeight = 0; RaycastHit hit; if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask)) { baseHeight = hit.point.y; } n.height = baseHeight; //Vector3 v = newn. Vector3((float)(((float)n.easthing-offsetPositionX)/precision),(float)0.0,(float)(((float)n.northing-offsetPositionZ)/precision)); //road.points.Insert(0, v); pl.Add(n); } pl.Close(transform); //go.isStatic = true; //road.Refresh(); //go.transform.parent = transform; }
public GeoJSONGeometry(PolyLine line) { type = GeoJSONGeometryType.LineString; coordinates = GeoJSONLineString(line); }
private static double[][] GeoJSONLineString(PolyLine line) { var coords = new List<double[]>(); for (int i = 0; i < line.count(); i++) coords.Add(GeoJSONPoint(line.item(i))); return coords.ToArray(); }
public void AddPolyLine(PolyLine polyLine) { polylineList.Add(polyLine); }
public static PolyLine Reverse(this PolyLine original) { List<Coordinate> points = new List<Coordinate>(); for(int i = 0; i < original.count(); i++) points.Add(original.item(i)); points.Reverse(); PolyLine result = new PolyLine(); foreach(Coordinate c in points) result.add(c); return result; }
public static PolyLine ParseLineString(string wkt) { string[] parts = wkt.Split(new char[] {'(',')'}); if (parts[0].TrimEnd(' ') != "LINESTRING") { throw new ArgumentException(string.Format("Unexpected value '{0}'", parts[0]), "wkt"); } PolyLine pl = new PolyLine(); Line l = new Line(); string[] coords = parts[1].Split(','); foreach (string coord in coords) { l.Points.Add(SplitPoint(coord)); } pl.Lines.Add(l); return pl; }
public static PolyLine ParseMultiLineString(string wkt) { PolyLine pl = new PolyLine(); wkt = wkt.ToUpper(); if (!wkt.StartsWith("MULTILINESTRING")) { throw new ArgumentException("Invalid WKT: must start with 'MULTILINESTRING'", "wkt"); } int idx = wkt.IndexOf('('); string[] lines = wkt.Substring(idx+1, wkt.Length-idx-1).Split(new string[] {"),(", "), ("}, StringSplitOptions.None); for (int ii=0; ii < lines.Length; ii++) { string linewkt = lines[ii].Trim(new char[] {'(',')'}); Line l = new Line(); string[] coords = linewkt.Split(','); foreach (string coord in coords) { l.Points.Add(SplitPoint(coord)); } pl.Lines.Add(l); } return pl; }
public void RemovePolyLine(PolyLine polyLine) { polylineList.Remove(polyLine); }
public static string CreateFromPolyLine(PolyLine polyLine) { StringBuilder sb = new StringBuilder(); sb.Append("MULTILINESTRING("); for (int ii=0; ii<polyLine.Lines.Count; ii++) { Line line = polyLine.Lines[ii]; sb.Append("("); for (int jj=0; jj <line.Points.Count; jj++) { Point point = line.Points[jj]; sb.AppendFormat("{0} {1}{2}", point.X.ToString(CultureInfo.InvariantCulture), point.Y.ToString(CultureInfo.InvariantCulture), jj <line.Points.Count-1 ? "," : string.Empty); } sb.AppendFormat("){0}", ii < polyLine.Lines.Count-1 ? "," : string.Empty); } sb.Append(")"); return sb.ToString(); }
private bool Command(List<Shape> shapes, bool analyse) { string[] cmds = new string[] { "PU", "PD", "PA", "PR", "SP" }; while (!_stream.IsEOF()) { int cmdidx = _stream.IsCommand(cmds); if (cmdidx==4) { if (_stream.IsInt()) { int coloridx = _stream.GetInt(); if (coloridx >= 1 && coloridx <= 8) _color = _pencolor[coloridx-1]; } } else if (cmdidx >= 0) { switch (cmdidx) { case 0: _IsPenUp = true; break; case 1: _IsPenUp = false; break; } while (_stream.IsInt()) { Point3D pt = GetSpaceCoordiante(cmdidx == 3); if (cmdidx == 3) // move rel { pt.X += _last.X; pt.Y += _last.Y; } _last = pt; if (!analyse) { if (_IsPenUp) { PolyLine r = new PolyLine(); r.ForgroundColor = _color; r.LineSize = 1; r.HPGLStart = r.HPGLEnd = pt; shapes.Add(r); } else { PolyLine r = (shapes.Count > 0) ? (PolyLine)shapes.Last() : null; if (r == null) { r = new PolyLine(); r.ForgroundColor = _color; r.LineSize = 1; r.HPGLStart = r.HPGLEnd = pt; shapes.Add(r); } r.Points.Add(new PolyLine.LinePoint() { HPGLPos = pt }); } } _stream.IsCommand(","); } } else { // skip command _stream.SkipEndCommand(); } } return true; }
public static void DrawPolyLine(List<Vector3> nodes, Color color, float duration, bool isClosed = false, bool isAlternating = false) { var pLine = new PolyLine(nodes, color, isClosed, isAlternating); pLine.lifeTime = duration; Camera.main.GetComponent<LineHelper>().AddPolyLine(pLine); }
private PolyLine TrianglePlaneIntersect(Face f, Plane p) { PolyLine polyLine = new PolyLine(); float epsilon = 0.01f; // TODO: Auto compute based on scale float epsilon_unit = 0.00001f; // Unit size epsilon value Vector3 f_normal = f.Normal; f_normal.Normalize(); p.normal.Normalize(); if ((f_normal - p.normal).Length < epsilon_unit || (f_normal + p.normal).Length < epsilon_unit) { // No intersection } else { Vector3 expected_direction = Vector3.Cross(f.Normal, p.normal); // Assume we're dealing with triangles only int verts = f.vertices.Count(); if (verts != 3) { throw new Exception("The number of vertices is not 3!"); } float[] d = new float[3]; for (int i = 0; i < 3; i++) { d[i] = p.Distance(f.vertices[i]); } for (int i = 0; i < 3; i++) { // Is the line on the plane? if (Math.Abs(d[i]) < epsilon && Math.Abs(d[(i + 1) % 3]) < epsilon) { polyLine.points.Add(f.vertices[i]); polyLine.points.Add(f.vertices[(i + 1) % 3]); break; } } if (polyLine.points.Count() == 0) { // Line not on a plain: might have an intersection with a point and the opposite line for (int i = 0; i < 3; i++) { float d1 = d[i]; float d2 = d[(i + 1) % 3]; float d3 = d[(i + 2) % 3]; if (Math.Abs(d[i]) < epsilon && Math.Sign(d2) != Math.Sign(d3)) { d2 = Math.Abs(d2); d3 = Math.Abs(d3); // One negative, one positive float total = d2 + d3; Vector3 result = (f.vertices[(i + 1) % 3] * d3 + f.vertices[(i + 2) % 3] * d2) / total; polyLine.points.Add(f.vertices[i]); polyLine.points.Add(result); break; } } if (polyLine.points.Count() == 0) { // No edge in plane and no point + line intersect: maybe two lines intersect? for (int i = 0; i < 3; i++) { // Intersection with an edge if (Math.Sign(d[i]) != Math.Sign(d[(i + 1) % 3])) { float d1 = Math.Abs(d[i]); float d2 = Math.Abs(d[(i + 1) % 3]); float total = d1 + d2; Vector3 result = (f.vertices[i] * d2 + f.vertices[(i + 1) % 3] * d1) / total; polyLine.points.Add(result); if (polyLine.points.Count() == 2) { break; } } } } } if (polyLine.points.Count() >= 2) { //DrawCone1(polyLine.points[0], polyLine.points[1]); Vector3 direction = polyLine.points[1] - polyLine.points[0]; if (Vector3.Dot(direction, expected_direction) < 0) { PolyLine reversed = new PolyLine(); reversed.points.Add(polyLine.points[1]); reversed.points.Add(polyLine.points[0]); polyLine = reversed; } // // // Color[] colors = new Color[] { Color.DarkRed, Color.LightGreen, Color.DarkBlue }; // int i = 0; // GL.Begin(BeginMode.LineLoop); // foreach (Vector3 v in polyLine.points) // { // GL.Color3(colors[i++]); // GL.Vertex3(v); // // } // GL.End(); // // GL.PointSize(10); // GL.Color3(Color.Orange); // GL.Begin(BeginMode.Points); // foreach (Vector3 v in polyLine.points) // { // GL.Vertex3(v); // } // GL.End(); // GL.PointSize(1); } } return polyLine; }
private void Intersctions(IList<ILine> lines, PolyLine<Line > poly ) { IList<IPoint> points;Node node2 ; Node node1; NodeLine nodeline ; foreach (ILine line in lines) { points = poly.PointsIntersects(line); if (points.Count == 2) { node1 = new Node(points[0].X, points[0].Y, points[0].Z); node2 = new Node(points[1].X, points[1].Y, points[1].Z); nodeline = new NodeLine(node1, node2); _presenter._creator.CreateBeam(nodeline); } } }
private void Slice(Plane p) { float epsilon = 0.01f; // TODO: compute proper epsilon value List<PolyLine> linePile = new List<PolyLine>(); // Pile of disconnected lines on the slice plane List<Vector3> all_points = new List<Vector3>(); foreach (Face f in this.faces) { PolyLine newLine = TrianglePlaneIntersect(f, p); // Only add lines with exactly 2 points - others are a no match or error if (newLine.points.Count() == 2 && (newLine.points[0] - newLine.points[1]).Length> epsilon) { linePile.Add(newLine); // Add the vertices to the all_points list - only need to add the first one, the tail will be the head of another point bool matched = false; foreach (Vector3 point in all_points) { if ((point - newLine.points[0]).Length < epsilon) { matched = true; break; } } if (!matched) { all_points.Add(newLine.points[0]); } } } // linePile is a unordered list of line segments. // If a line segment is oriented with point[0] on (0, 0, 0) and point[1] // somewhere on the positive Y axis, the solid object is in the direction of the positive x axis. // // p[1]xxxxxxxxxxxxxxxxxxxxxxxx // xx xx // xx <object over here> xx // xx xx // p[0]xxxxxxxxxxxxxxxxxxxxxxxx // List<PolyLine> newPolyLines = new List<PolyLine>(); for (int i = 0; i < linePile.Count(); i++) { int points = linePile[i].points.Count(); Vector3 v1 = linePile[i].points[0]; Vector3 v2 = linePile[i].points[1]; //DrawCone1(v1, v2); List<Vector3> points_on_line = new List<Vector3>(); foreach (Vector3 v in all_points) { if ((v1 - v).Length >= epsilon && (v2 - v).Length >= epsilon && DistanceToCylinder(v1, v2, v) < epsilon) { points_on_line.Add(v); } } points_on_line.Insert(0, v1); points_on_line.Add(v2); // Order from v1 to v2 var sorted = points_on_line.OrderBy(order_vec => (order_vec - v1).Length); PolyLine newPolyLine = new PolyLine(); foreach (Vector3 v in sorted) { if (newPolyLine.points.Count() == 0 || (newPolyLine.points[newPolyLine.points.Count() - 1] - v).Length > epsilon) { newPolyLine.points.Add(v); } } if (newPolyLine.points.Count() >= 2) { newPolyLines.Add(newPolyLine); } if (newPolyLine.points.Count() >= 3) { // Shouldn't get here! } } List<LinePointIndices> lpis = new List<LinePointIndices>(); List<Vector3> vertices = new List<Vector3>(); List<List<int>> v_lookup = new List<List<int>>(); foreach (PolyLine l in newPolyLines) { int lastIndex = -1; foreach (Vector3 pointVec in l.points) { int currentIndex = -1; for (int i = 0; i < vertices.Count(); i++) { float length = (vertices[i] - pointVec).Length; if (length < epsilon) { currentIndex = i; continue; } } if (currentIndex == -1) { vertices.Add(pointVec); v_lookup.Add(new List<int>()); currentIndex = vertices.Count() - 1; } if (lastIndex != -1 && lastIndex != currentIndex) { LinePointIndices line = new LinePointIndices(); bool already_matched = false; foreach (int line_index in v_lookup[lastIndex]) { LinePointIndices l2 = lpis[line_index]; if (l2.indices[1] == currentIndex) { already_matched = true; } } if (!already_matched) { line.indices.Add(lastIndex); line.indices.Add(currentIndex); lpis.Add(line); v_lookup[lastIndex].Add(lpis.Count() - 1); v_lookup[currentIndex].Add(lpis.Count() - 1); } } lastIndex = currentIndex; } } //List<Vector3> scaled = new List<Vector3>(); List<int> vector_indices_to_see = new List<int>(); foreach (Vector3 v in vertices) { //scaled.Add(v / 125); vector_indices_to_see.Add(vector_indices_to_see.Count()); } List<LinePointIndices> slices = new List<LinePointIndices>(); GL.PushMatrix(); GL.PointSize(10); List<int> seenVertices = new List<int>(); while(vector_indices_to_see.Count() > 0) { List<int> line_indices = v_lookup [vector_indices_to_see[0]]; vector_indices_to_see.RemoveAt(0); if (line_indices.Count() == 0) { continue; } LinePointIndices line = lpis[line_indices[0]]; // Only need to look at one line with this vertex LinePointIndices start_line = new LinePointIndices(); start_line.indices.Add(line.indices[0]); start_line.indices.Add(line.indices[1]); GL.Color3(Color.Green); DrawCone1(vertices[start_line.indices[0]], vertices[start_line.indices[1]]); LinePointIndices loop = FindLoop(seenVertices, p.normal, vertices, v_lookup, lpis, start_line); if (loop != null) { slices.Add(loop); GL.Color3(Color.LightBlue); GL.Begin(BeginMode.LineLoop); Vector3 add = new Vector3(0, 0, 0); foreach (int i in loop.indices) { vector_indices_to_see.RemoveAll(value => value == i); GL.Vertex3(vertices[i] + add); seenVertices.Add(i); //add += new Vector3(0, 0, 25); } GL.End(); //GL.Translate(new Vector3(0, 0, +100)); } //break; } GL.PointSize(1); GL.PopMatrix(); Vector3 normal = new Vector3(0, 0, 1); float toolRadius = 100; GL.LineWidth(1); List<IntPoint> boundingBox = new List<IntPoint>(); boundingBox.Add(new IntPoint(-1000, -1000)); boundingBox.Add(new IntPoint(3000, -1000)); boundingBox.Add(new IntPoint(3000, 3000)); boundingBox.Add(new IntPoint(-1000, 3000)); List<LineLoop> loops = new List<LineLoop>(); foreach (LinePointIndices l in slices) { LineStrip line = new LineStrip(); for (int i = 0; i < l.indices.Count (); i++) { line.Append(vertices[l.indices[i]]); } line.Append(vertices[l.indices[0]]); loops.Add(new LineLoop (line)); } if (loops.Count() > 0) { Vector3 up = new Vector3(0, 0, 1); if (Math.Abs (normal.Z) > 0.8) { up = new Vector3(1, 0, 0); } float distance = Vector3.Dot(loops[0].GetVertex(0), normal); Matrix4 transform = Matrix4.LookAt(normal * distance, normal * (distance - 1), up); Matrix4 inverseTransform = Matrix4.Invert(transform); Clipper c = new Clipper(); c.Clear(); try { // These loops go clockwise foreach (LineLoop loop in loops) { List<IntPoint> polygon = new List<IntPoint>(); foreach (Vector3 vertex in loop.Vertices) { Vector3 result = Vector3.Transform(vertex, transform); polygon.Add(new IntPoint((long)result.X, (long)result.Y)); } polygon.RemoveAt(0); c.AddPolygon(polygon, PolyType.ptClip); GL.PushMatrix(); GL.Translate(new Vector3(0, 0, 100)); //loop.Draw(); GL.PopMatrix(); } List<List<IntPoint>> union = new List<List<IntPoint>>(); bool r = c.Execute(ClipType.ctUnion, union, PolyFillType.pftNonZero, PolyFillType.pftNonZero); List<List<IntPoint>> with_offset = Clipper.OffsetPolygons(union, toolRadius, JoinType.jtSquare); List<List<IntPoint>> whatsLeft = Clipper.OffsetPolygons(with_offset, -toolRadius, JoinType.jtRound); List<LineStrip> strips = new List<LineStrip>(); foreach (List<IntPoint> polygon in with_offset) { LineStrip strip = new LineStrip(); foreach (IntPoint point in polygon) { strip.Append(Vector3.Transform(new Vector3(point.X, point.Y, 0.0f), inverseTransform)); } strip.Append(Vector3.Transform(new Vector3(polygon[0].X, polygon[0].Y, 0.0f), inverseTransform)); strips.Add(strip); //new LineLoop(strip).Draw(); } List<List<IntPoint>> removeArea = new List<List<IntPoint>>(); c.Clear(); c.AddPolygons(with_offset, PolyType.ptClip); c.AddPolygon(boundingBox, PolyType.ptSubject); List<List<IntPoint>> resultingPolygon = new List<List<IntPoint>>(); c.Execute(ClipType.ctDifference, removeArea, PolyFillType.pftNonZero, PolyFillType.pftNonZero); removeArea = Clipper.CleanPolygons(removeArea, toolRadius / 100); c.Clear(); c.AddPolygons(removeArea, PolyType.ptClip); PolyTree test = new PolyTree(); c.Execute(ClipType.ctUnion, test, PolyFillType.pftNonZero, PolyFillType.pftNonZero); //PolyNode pn = test.GetFirst(); //while (pn != null) //{ // if (pn.IsHole) // { // LineLoop l = new LineLoop(pn.Contour, inverseTransform); // l.Draw(); // } // pn = pn.GetNext(); //} List<Polygons> polys = FlattenPolyTree(test); //GL.PushMatrix(); foreach (Polygons polygons in polys) { //GL.Translate(new Vector3 (0, 0, 100)); //foreach (Polygon polygon in polygons) //{ // LineLoop l = new LineLoop(polygon, inverseTransform); // l.Draw(); //} List<Polygons> paths = ReducePolygon(polygons, toolRadius, inverseTransform); //IOrderedEnumerable<List<IntPoint>> ordered = paths.OrderBy(poly => Clipper.Area(poly)); GL.PushMatrix(); List<Polygons> paths2 = new List<Polygons>(); List<Polygons> paths3 = new List<Polygons>(); foreach (Polygons polygons2 in paths) { var newPolys = new Polygons(); foreach (Polygon poly in polygons2) { if (Clipper.Area(poly) > 0) { newPolys.Add(poly); } } paths2.Add(newPolys); //GL.Translate(new Vector3(0, 0, 100)); var newInnerPolys = new Polygons(); foreach (Polygon poly in polygons2) { if (paths3.Count() == 0) { //newInnerPoly } if (Clipper.Area(poly) < 0) { LineLoop l = new LineLoop(poly, inverseTransform); l.Draw(); } } } foreach (Polygons polygons2 in paths2) { GL.Translate(new Vector3(0, 0, 100)); foreach (Polygon poly in polygons2) { LineLoop l = new LineLoop(poly, inverseTransform); l.Draw(); } } GL.PopMatrix(); } //GL.PopMatrix(); double boundingBoxArea = Clipper.Area(boundingBox); // Outer Polygon // Inner Polygons //ReducePolygon(boundingBox, with_offset, toolRadius, inverseTransform); //strips = new List<LineStrip>(); //double area = 1; //int loopTimes = 0; //List<List<IntPoint>> cutPolygons = new List<List<IntPoint>>(); //List<Vector3> parentPoints = new List<Vector3>(); //GL.PushMatrix(); //while (removeArea.Count() > 0) //{ // List<Vector3> points = new List<Vector3>(); // foreach (List<IntPoint> polygon in removeArea) // { // double area = Clipper.Area(polygon); // // if (area > 0) // Bigger to Smaller // { // } // IntPoint[] newP = new IntPoint[polygon.Count()]; // polygon.CopyTo(newP); // cutPolygons.Add(new List<IntPoint>(newP)); // // // LineLoop l = new LineLoop(polygon, inverseTransform); // //l.Draw(); // points.AddRange(l.Vertices); // // //ReducePolygon(null, polygon, toolRadius, inverseTransform); // //area += Clipper.Area(polygon); // //LineStrip strip = new LineStrip(); // //foreach (IntPoint point in polygon) // //{ // // strip.Append(Vector3.Transform(new Vector3(point.X, point.Y, 0.0f), inverseTransform)); // //} // //strip.Append(Vector3.Transform(new Vector3(polygon[0].X, polygon[0].Y, 0.0f), inverseTransform)); // // //strips.Add(strip); // //new LineLoop(strip).Draw(); // } // // //GL.Color3(Color.Black); // //GL.Begin(BeginMode.Lines); // //foreach (Vector3 v in points) // //{ // // foreach (Vector3 v2 in parentPoints) // // { // // if ((v - v2).Length < toolRadius * 2) // // { // // GL.Vertex3(v); // // GL.Vertex3(v2); // // } // // } // //} // //GL.End(); // // parentPoints = points; // removeArea = Clipper.OffsetPolygons(removeArea, -toolRadius, JoinType.jtRound); // removeArea = Clipper.CleanPolygons(removeArea, toolRadius / 100); //} //GL.PopMatrix(); //IOrderedEnumerable<List<IntPoint>> ordered = cutPolygons.OrderBy(poly => Clipper.Area(poly)); // //GL.PushMatrix(); //foreach (List<IntPoint> poly in ordered) //{ // GL.Translate(new Vector3(0, 0, 100)); // LineLoop l = new LineLoop(poly, inverseTransform); // l.Draw(); //} //GL.PopMatrix(); ////strips = new List<LineStrip>(); //GL.Color3(Color.Red); //GL.LineWidth(2); //foreach (List<IntPoint> polygon in whatsLeft) //{ // LineStrip strip = new LineStrip(); // foreach (IntPoint point in polygon) // { // strip.Append(Vector3.Transform(new Vector3(point.X, point.Y, 0.0f), inverseTransform)); // } // strip.Append(Vector3.Transform(new Vector3(polygon[0].X, polygon[0].Y, 0.0f), inverseTransform)); // // strips.Add(strip); // new LineLoop(strip).Draw(); //} //GL.LineWidth(1); } catch (Exception e) { } } }