private int RemoveBox() { Otri otri = new Otri(); Otri otri1 = new Otri(); Otri otri2 = new Otri(); Otri otri3 = new Otri(); Otri otri4 = new Otri(); Otri otri5 = new Otri(); bool poly = !this.mesh.behavior.Poly; otri3.triangle = Mesh.dummytri; otri3.orient = 0; otri3.SymSelf(); otri3.Lprev(ref otri4); otri3.LnextSelf(); otri3.SymSelf(); otri3.Lprev(ref otri1); otri1.SymSelf(); otri3.Lnext(ref otri2); otri2.SymSelf(); if (otri2.triangle == Mesh.dummytri) { otri1.LprevSelf(); otri1.SymSelf(); } Mesh.dummytri.neighbors[0] = otri1; int num = -2; while (!otri3.Equal(otri4)) { num++; otri3.Lprev(ref otri5); otri5.SymSelf(); if (poly && otri5.triangle != Mesh.dummytri) { Vertex vertex = otri5.Org(); if (vertex.mark == 0) { vertex.mark = 1; } } otri5.Dissolve(); otri3.Lnext(ref otri); otri.Sym(ref otri3); this.mesh.TriangleDealloc(otri.triangle); if (otri3.triangle != Mesh.dummytri) { continue; } otri5.Copy(ref otri3); } this.mesh.TriangleDealloc(otri4.triangle); return(num); }
/// <summary> /// Scout the first triangle on the path from one endpoint to another, and check /// for completion (reaching the second endpoint), a collinear vertex, or the /// intersection of two segments. /// </summary> /// <param name="searchtri"></param> /// <param name="endpoint2"></param> /// <param name="newmark"></param> /// <returns> /// Returns true if the entire segment is successfully inserted, and false /// if the job must be finished by ConstrainedEdge(). /// </returns> /// <remarks> /// If the first triangle on the path has the second endpoint as its /// destination or apex, a subsegment is inserted and the job is done. /// If the first triangle on the path has a destination or apex that lies on /// the segment, a subsegment is inserted connecting the first endpoint to /// the collinear vertex, and the search is continued from the collinear /// vertex. /// If the first triangle on the path has a subsegment opposite its origin, /// then there is a segment that intersects the segment being inserted. /// Their intersection vertex is inserted, splitting the subsegment. /// </remarks> private bool ScoutSegment(ref Otri searchtri, Vertex endpoint2, ushort newmark) { Otri crosstri = default(Otri); Osub crosssubseg = default(Osub); Vertex leftvertex, rightvertex; FindDirectionResult collinear; collinear = FindDirection(ref searchtri, endpoint2); rightvertex = searchtri.Dest(); leftvertex = searchtri.Apex(); if (((leftvertex.X == endpoint2.X) && (leftvertex.Y == endpoint2.Y)) || ((rightvertex.X == endpoint2.X) && (rightvertex.Y == endpoint2.Y))) { // The segment is already an edge in the mesh. if ((leftvertex.X == endpoint2.X) && (leftvertex.Y == endpoint2.Y)) { searchtri.Lprev(); } // Insert a subsegment, if there isn't already one there. mesh.InsertSubseg(ref searchtri, newmark); return(true); } if (collinear == FindDirectionResult.Leftcollinear) { // We've collided with a vertex between the segment's endpoints. // Make the collinear vertex be the triangle's origin. searchtri.Lprev(); mesh.InsertSubseg(ref searchtri, newmark); // Insert the remainder of the segment. return(ScoutSegment(ref searchtri, endpoint2, newmark)); } if (collinear == FindDirectionResult.Rightcollinear) { // We've collided with a vertex between the segment's endpoints. mesh.InsertSubseg(ref searchtri, newmark); // Make the collinear vertex be the triangle's origin. searchtri.Lnext(); // Insert the remainder of the segment. return(ScoutSegment(ref searchtri, endpoint2, newmark)); } searchtri.Lnext(ref crosstri); crosstri.Pivot(ref crosssubseg); // Check for a crossing segment. if (crosssubseg.seg.hash == Mesh.DUMMY) { return(false); } // Insert a vertex at the intersection. SegmentIntersection(ref crosstri, ref crosssubseg, endpoint2); crosstri.Copy(ref searchtri); mesh.InsertSubseg(ref searchtri, newmark); // Insert the remainder of the segment. return(ScoutSegment(ref searchtri, endpoint2, newmark)); }
private int RemoveGhosts(ref Otri startghost) { Otri otri = new Otri(); Otri otri1 = new Otri(); Otri otri2 = new Otri(); bool poly = !this.mesh.behavior.Poly; startghost.Lprev(ref otri); otri.SymSelf(); Mesh.dummytri.neighbors[0] = otri; startghost.Copy(ref otri1); int num = 0; do { num++; otri1.Lnext(ref otri2); otri1.LprevSelf(); otri1.SymSelf(); if (poly && otri1.triangle != Mesh.dummytri) { Vertex vertex = otri1.Org(); if (vertex.mark == 0) { vertex.mark = 1; } } otri1.Dissolve(); otri2.Sym(ref otri1); this.mesh.TriangleDealloc(otri2.triangle); }while (!otri1.Equal(startghost)); return(num); }
public void TestLprev() { var triangles = CreateExampleMesh(); Otri t = default; // The center triangle. t.tri = triangles[1]; t.orient = 0; t.Lprev(); Assert.AreEqual(3, t.Org().ID); t.Lprev(); Assert.AreEqual(4, t.Org().ID); t.Lprev(); Assert.AreEqual(1, t.Org().ID); }
/// <summary> /// Removes ghost triangles. /// </summary> /// <param name="startghost"></param> /// <returns>Number of vertices on the hull.</returns> int RemoveGhosts(ref Otri startghost) { Otri searchedge = default(Otri); Otri dissolveedge = default(Otri); Otri deadtriangle = default(Otri); Vertex markorg; int hullsize; bool noPoly = !mesh.behavior.Poly; var dummytri = mesh.dummytri; // Find an edge on the convex hull to start point location from. startghost.Lprev(ref searchedge); searchedge.Sym(); dummytri.neighbors[0] = searchedge; // Remove the bounding box and count the convex hull edges. startghost.Copy(ref dissolveedge); hullsize = 0; do { hullsize++; dissolveedge.Lnext(ref deadtriangle); dissolveedge.Lprev(); dissolveedge.Sym(); // If no PSLG is involved, set the boundary markers of all the vertices // on the convex hull. If a PSLG is used, this step is done later. if (noPoly) { // Watch out for the case where all the input vertices are collinear. if (dissolveedge.tri.id != Mesh.DUMMY) { markorg = dissolveedge.Org(); if (markorg.label == 0) { markorg.label = 1; } } } // Remove a bounding triangle from a convex hull triangle. dissolveedge.Dissolve(dummytri); // Find the next bounding triangle. deadtriangle.Sym(ref dissolveedge); // Delete the bounding triangle. mesh.TriangleDealloc(deadtriangle.tri); } while (!dissolveedge.Equals(startghost)); return(hullsize); }
private void InvokePrimitive(string name) { if (name == "sym") { current.Sym(); } else if (name == "lnext") { current.Lnext(); } else if (name == "lprev") { current.Lprev(); } else if (name == "onext") { current.Onext(); } else if (name == "oprev") { current.Oprev(); } else if (name == "dnext") { current.Dnext(); } else if (name == "dprev") { current.Dprev(); } else if (name == "rnext") { current.Rnext(); } else if (name == "rprev") { current.Rprev(); } renderControl.Update(current); topoControlView.SetTriangle(current.Triangle); }
/// <summary> /// Inserts a vertex at the circumcenter of a triangle. Deletes /// the newly inserted vertex if it encroaches upon a segment. /// </summary> /// <param name="badtri"></param> private void SplitTriangle(BadTriangle badtri) { Otri badotri = default(Otri); Vertex borg, bdest, bapex; Point newloc; // Location of the new vertex double xi = 0, eta = 0; InsertVertexResult success; bool errorflag; badotri = badtri.poortri; borg = badotri.Org(); bdest = badotri.Dest(); bapex = badotri.Apex(); // Make sure that this triangle is still the same triangle it was // when it was tested and determined to be of bad quality. // Subsequent transformations may have made it a different triangle. if (!Otri.IsDead(badotri.tri) && (borg == badtri.org) && (bdest == badtri.dest) && (bapex == badtri.apex)) { errorflag = false; // Create a new vertex at the triangle's circumcenter. // Using the original (simpler) Steiner point location method // for mesh refinement. // TODO: NewLocation doesn't work for refinement. Why? Maybe // reset VertexType? if (behavior.fixedArea || behavior.VarArea) { newloc = predicates.FindCircumcenter(borg, bdest, bapex, ref xi, ref eta, behavior.offconstant); } else { newloc = newLocation.FindLocation(borg, bdest, bapex, ref xi, ref eta, true, badotri); } // Check whether the new vertex lies on a triangle vertex. if (((newloc.x == borg.x) && (newloc.y == borg.y)) || ((newloc.x == bdest.x) && (newloc.y == bdest.y)) || ((newloc.x == bapex.x) && (newloc.y == bapex.y))) { if (Log.Verbose) { logger.Warning("New vertex falls on existing vertex.", "Quality.SplitTriangle()"); errorflag = true; } } else { // The new vertex must be in the interior, and therefore is a // free vertex with a marker of zero. Vertex newvertex = new Vertex(newloc.x, newloc.y, 0 #if USE_ATTRIBS , mesh.nextras #endif ); newvertex.type = VertexType.FreeVertex; // Ensure that the handle 'badotri' does not represent the longest // edge of the triangle. This ensures that the circumcenter must // fall to the left of this edge, so point location will work. // (If the angle org-apex-dest exceeds 90 degrees, then the // circumcenter lies outside the org-dest edge, and eta is // negative. Roundoff error might prevent eta from being // negative when it should be, so I test eta against xi.) if (eta < xi) { badotri.Lprev(); } // Assign triangle for attributes interpolation. newvertex.tri.tri = newvertex_tri; // Insert the circumcenter, searching from the edge of the triangle, // and maintain the Delaunay property of the triangulation. Osub tmp = default(Osub); success = mesh.InsertVertex(newvertex, ref badotri, ref tmp, true, true); if (success == InsertVertexResult.Successful) { newvertex.hash = mesh.hash_vtx++; newvertex.id = newvertex.hash; #if USE_ATTRIBS if (mesh.nextras > 0) { Interpolation.InterpolateAttributes(newvertex, newvertex.tri.tri, mesh.nextras); } #endif #if USE_Z Interpolation.InterpolateZ(newvertex, newvertex.tri.tri); #endif mesh.vertices.Add(newvertex.hash, newvertex); if (mesh.steinerleft > 0) { mesh.steinerleft--; } } else if (success == InsertVertexResult.Encroaching) { // If the newly inserted vertex encroaches upon a subsegment, // delete the new vertex. mesh.UndoVertex(); } else if (success == InsertVertexResult.Violating) { // Failed to insert the new vertex, but some subsegment was // marked as being encroached. } else { // success == DUPLICATEVERTEX // Couldn't insert the new vertex because a vertex is already there. if (Log.Verbose) { logger.Warning("New vertex falls on existing vertex.", "Quality.SplitTriangle()"); errorflag = true; } } } if (errorflag) { logger.Error("The new vertex is at the circumcenter of triangle: This probably " + "means that I am trying to refine triangles to a smaller size than can be " + "accommodated by the finite precision of floating point arithmetic.", "Quality.SplitTriangle()"); throw new Exception("The new vertex is at the circumcenter of triangle."); } } }
public int Triangulate(Mesh mesh) { SweepLine.SweepEvent[] sweepEventArray; SweepLine.SweepEvent sweepEvent; Vertex vertex; Vertex vertex1; Vertex vertex2; Vertex vertex3; this.mesh = mesh; this.xminextreme = 10 * mesh.bounds.Xmin - 9 * mesh.bounds.Xmax; Otri otri = new Otri(); Otri otri1 = new Otri(); Otri otri2 = new Otri(); Otri otri3 = new Otri(); Otri otri4 = new Otri(); Otri otri5 = new Otri(); Otri otri6 = new Otri(); bool i = false; this.splaynodes = new List <SweepLine.SplayNode>(); SweepLine.SplayNode splayNode = null; this.CreateHeap(out sweepEventArray); int num = mesh.invertices; mesh.MakeTriangle(ref otri2); mesh.MakeTriangle(ref otri3); otri2.Bond(ref otri3); otri2.LnextSelf(); otri3.LprevSelf(); otri2.Bond(ref otri3); otri2.LnextSelf(); otri3.LprevSelf(); otri2.Bond(ref otri3); Vertex vertex4 = sweepEventArray[0].vertexEvent; this.HeapDelete(sweepEventArray, num, 0); num--; do { if (num == 0) { SimpleLog.Instance.Error("Input vertices are all identical.", "SweepLine.SweepLineDelaunay()"); throw new Exception("Input vertices are all identical."); } vertex = sweepEventArray[0].vertexEvent; this.HeapDelete(sweepEventArray, num, 0); num--; if (vertex4.x != vertex.x || vertex4.y != vertex.y) { continue; } if (Behavior.Verbose) { SimpleLog.Instance.Warning("A duplicate vertex appeared and was ignored.", "SweepLine.SweepLineDelaunay().1"); } vertex.type = VertexType.UndeadVertex; Mesh mesh1 = mesh; mesh1.undeads = mesh1.undeads + 1; }while (vertex4.x == vertex.x && vertex4.y == vertex.y); otri2.SetOrg(vertex4); otri2.SetDest(vertex); otri3.SetOrg(vertex); otri3.SetDest(vertex4); otri2.Lprev(ref otri); Vertex vertex5 = vertex; while (num > 0) { SweepLine.SweepEvent sweepEvent1 = sweepEventArray[0]; this.HeapDelete(sweepEventArray, num, 0); num--; bool flag = true; if (sweepEvent1.xkey >= mesh.bounds.Xmin) { Vertex vertex6 = sweepEvent1.vertexEvent; if (vertex6.x != vertex5.x || vertex6.y != vertex5.y) { vertex5 = vertex6; splayNode = this.FrontLocate(splayNode, otri, vertex6, ref otri1, ref i); otri.Copy(ref otri1); for (i = false; !i && this.RightOfHyperbola(ref otri1, vertex6); i = otri1.Equal(otri)) { otri1.OnextSelf(); } this.Check4DeadEvent(ref otri1, sweepEventArray, ref num); otri1.Copy(ref otri5); otri1.Sym(ref otri4); mesh.MakeTriangle(ref otri2); mesh.MakeTriangle(ref otri3); Vertex vertex7 = otri5.Dest(); otri2.SetOrg(vertex7); otri2.SetDest(vertex6); otri3.SetOrg(vertex6); otri3.SetDest(vertex7); otri2.Bond(ref otri3); otri2.LnextSelf(); otri3.LprevSelf(); otri2.Bond(ref otri3); otri2.LnextSelf(); otri3.LprevSelf(); otri2.Bond(ref otri4); otri3.Bond(ref otri5); if (!i && otri5.Equal(otri)) { otri2.Copy(ref otri); } if (this.randomnation(SweepLine.SAMPLERATE) == 0) { splayNode = this.SplayInsert(splayNode, otri2, vertex6); } else if (this.randomnation(SweepLine.SAMPLERATE) == 0) { otri3.Lnext(ref otri6); splayNode = this.SplayInsert(splayNode, otri6, vertex6); } } else { if (Behavior.Verbose) { SimpleLog.Instance.Warning("A duplicate vertex appeared and was ignored.", "SweepLine.SweepLineDelaunay().2"); } vertex6.type = VertexType.UndeadVertex; Mesh mesh2 = mesh; mesh2.undeads = mesh2.undeads + 1; flag = false; } } else { Otri otri7 = sweepEvent1.otriEvent; otri7.Oprev(ref otri4); this.Check4DeadEvent(ref otri4, sweepEventArray, ref num); otri7.Onext(ref otri5); this.Check4DeadEvent(ref otri5, sweepEventArray, ref num); if (otri4.Equal(otri)) { otri7.Lprev(ref otri); } mesh.Flip(ref otri7); otri7.SetApex(null); otri7.Lprev(ref otri2); otri7.Lnext(ref otri3); otri2.Sym(ref otri4); if (this.randomnation(SweepLine.SAMPLERATE) == 0) { otri7.SymSelf(); vertex1 = otri7.Dest(); vertex2 = otri7.Apex(); vertex3 = otri7.Org(); splayNode = this.CircleTopInsert(splayNode, otri2, vertex1, vertex2, vertex3, sweepEvent1.ykey); } } if (!flag) { continue; } vertex1 = otri4.Apex(); vertex2 = otri2.Dest(); vertex3 = otri2.Apex(); double num1 = Primitives.CounterClockwise(vertex1, vertex2, vertex3); if (num1 > 0) { sweepEvent = new SweepLine.SweepEvent() { xkey = this.xminextreme, ykey = this.CircleTop(vertex1, vertex2, vertex3, num1), otriEvent = otri2 }; this.HeapInsert(sweepEventArray, num, sweepEvent); num++; otri2.SetOrg(new SweepLine.SweepEventVertex(sweepEvent)); } vertex1 = otri3.Apex(); vertex2 = otri3.Org(); vertex3 = otri5.Apex(); double num2 = Primitives.CounterClockwise(vertex1, vertex2, vertex3); if (num2 <= 0) { continue; } sweepEvent = new SweepLine.SweepEvent() { xkey = this.xminextreme, ykey = this.CircleTop(vertex1, vertex2, vertex3, num2), otriEvent = otri5 }; this.HeapInsert(sweepEventArray, num, sweepEvent); num++; otri5.SetOrg(new SweepLine.SweepEventVertex(sweepEvent)); } this.splaynodes.Clear(); otri.LprevSelf(); return(this.RemoveGhosts(ref otri)); }
private void MergeHulls(ref Otri farleft, ref Otri innerleft, ref Otri innerright, ref Otri farright, int axis) { Vertex vertex; Vertex vertex1; Vertex vertex2; Vertex vertex3; Vertex vertex4; Vertex i; bool flag; bool flag1; Otri otri = new Otri(); Otri otri1 = new Otri(); Otri otri2 = new Otri(); Otri otri3 = new Otri(); Otri otri4 = new Otri(); Otri otri5 = new Otri(); Otri otri6 = new Otri(); Otri otri7 = new Otri(); Vertex vertex5 = innerleft.Dest(); Vertex vertex6 = innerleft.Apex(); Vertex vertex7 = innerright.Org(); Vertex vertex8 = innerright.Apex(); if (this.useDwyer && axis == 1) { vertex = farleft.Org(); vertex2 = farleft.Apex(); vertex1 = farright.Dest(); vertex3 = farright.Apex(); while (vertex2.y < vertex.y) { farleft.LnextSelf(); farleft.SymSelf(); vertex = vertex2; vertex2 = farleft.Apex(); } innerleft.Sym(ref otri6); for (i = otri6.Apex(); i.y > vertex5.y; i = otri6.Apex()) { otri6.Lnext(ref innerleft); vertex6 = vertex5; vertex5 = i; innerleft.Sym(ref otri6); } while (vertex8.y < vertex7.y) { innerright.LnextSelf(); innerright.SymSelf(); vertex7 = vertex8; vertex8 = innerright.Apex(); } farright.Sym(ref otri6); for (i = otri6.Apex(); i.y > vertex1.y; i = otri6.Apex()) { otri6.Lnext(ref farright); vertex3 = vertex1; vertex1 = i; farright.Sym(ref otri6); } } do { flag = false; if (Primitives.CounterClockwise(vertex5, vertex6, vertex7) > 0) { innerleft.LprevSelf(); innerleft.SymSelf(); vertex5 = vertex6; vertex6 = innerleft.Apex(); flag = true; } if (Primitives.CounterClockwise(vertex8, vertex7, vertex5) <= 0) { continue; } innerright.LnextSelf(); innerright.SymSelf(); vertex7 = vertex8; vertex8 = innerright.Apex(); flag = true; }while (flag); innerleft.Sym(ref otri); innerright.Sym(ref otri1); this.mesh.MakeTriangle(ref otri7); otri7.Bond(ref innerleft); otri7.LnextSelf(); otri7.Bond(ref innerright); otri7.LnextSelf(); otri7.SetOrg(vertex7); otri7.SetDest(vertex5); vertex = farleft.Org(); if (vertex5 == vertex) { otri7.Lnext(ref farleft); } vertex1 = farright.Dest(); if (vertex7 == vertex1) { otri7.Lprev(ref farright); } Vertex vertex9 = vertex5; Vertex vertex10 = vertex7; Vertex vertex11 = otri.Apex(); Vertex vertex12 = otri1.Apex(); while (true) { bool flag2 = Primitives.CounterClockwise(vertex11, vertex9, vertex10) <= 0; bool flag3 = Primitives.CounterClockwise(vertex12, vertex9, vertex10) <= 0; if (flag2 & flag3) { break; } if (!flag2) { otri.Lprev(ref otri2); otri2.SymSelf(); vertex4 = otri2.Apex(); if (vertex4 != null) { flag1 = Primitives.InCircle(vertex9, vertex10, vertex11, vertex4) > 0; while (flag1) { otri2.LnextSelf(); otri2.Sym(ref otri4); otri2.LnextSelf(); otri2.Sym(ref otri3); otri2.Bond(ref otri4); otri.Bond(ref otri3); otri.LnextSelf(); otri.Sym(ref otri5); otri2.LprevSelf(); otri2.Bond(ref otri5); otri.SetOrg(vertex9); otri.SetDest(null); otri.SetApex(vertex4); otri2.SetOrg(null); otri2.SetDest(vertex11); otri2.SetApex(vertex4); vertex11 = vertex4; otri3.Copy(ref otri2); vertex4 = otri2.Apex(); flag1 = (vertex4 == null ? false : Primitives.InCircle(vertex9, vertex10, vertex11, vertex4) > 0); } } } if (!flag3) { otri1.Lnext(ref otri2); otri2.SymSelf(); vertex4 = otri2.Apex(); if (vertex4 != null) { flag1 = Primitives.InCircle(vertex9, vertex10, vertex12, vertex4) > 0; while (flag1) { otri2.LprevSelf(); otri2.Sym(ref otri4); otri2.LprevSelf(); otri2.Sym(ref otri3); otri2.Bond(ref otri4); otri1.Bond(ref otri3); otri1.LprevSelf(); otri1.Sym(ref otri5); otri2.LnextSelf(); otri2.Bond(ref otri5); otri1.SetOrg(null); otri1.SetDest(vertex10); otri1.SetApex(vertex4); otri2.SetOrg(vertex12); otri2.SetDest(null); otri2.SetApex(vertex4); vertex12 = vertex4; otri3.Copy(ref otri2); vertex4 = otri2.Apex(); flag1 = (vertex4 == null ? false : Primitives.InCircle(vertex9, vertex10, vertex12, vertex4) > 0); } } } if (flag2 || !flag3 && Primitives.InCircle(vertex11, vertex9, vertex10, vertex12) > 0) { otri7.Bond(ref otri1); otri1.Lprev(ref otri7); otri7.SetDest(vertex9); vertex10 = vertex12; otri7.Sym(ref otri1); vertex12 = otri1.Apex(); } else { otri7.Bond(ref otri); otri.Lnext(ref otri7); otri7.SetOrg(vertex10); vertex9 = vertex11; otri7.Sym(ref otri); vertex11 = otri.Apex(); } } this.mesh.MakeTriangle(ref otri2); otri2.SetOrg(vertex9); otri2.SetDest(vertex10); otri2.Bond(ref otri7); otri2.LnextSelf(); otri2.Bond(ref otri1); otri2.LnextSelf(); otri2.Bond(ref otri); if (this.useDwyer && axis == 1) { vertex = farleft.Org(); vertex2 = farleft.Apex(); vertex1 = farright.Dest(); vertex3 = farright.Apex(); farleft.Sym(ref otri6); for (i = otri6.Apex(); i.x < vertex.x; i = otri6.Apex()) { otri6.Lprev(ref farleft); vertex2 = vertex; vertex = i; farleft.Sym(ref otri6); } while (vertex3.x > vertex1.x) { farright.LprevSelf(); farright.SymSelf(); vertex1 = vertex3; vertex3 = farright.Apex(); } } }
/// <summary> /// Find a triangle or edge containing a given point. /// </summary> /// <param name="searchpoint">The point to locate.</param> /// <param name="searchtri">The triangle to start the search at.</param> /// <param name="stopatsubsegment"> If 'stopatsubsegment' is set, the search /// will stop if it tries to walk through a subsegment, and will return OUTSIDE.</param> /// <returns>Location information.</returns> /// <remarks> /// Begins its search from 'searchtri'. It is important that 'searchtri' /// be a handle with the property that 'searchpoint' is strictly to the left /// of the edge denoted by 'searchtri', or is collinear with that edge and /// does not intersect that edge. (In particular, 'searchpoint' should not /// be the origin or destination of that edge.) /// /// These conditions are imposed because preciselocate() is normally used in /// one of two situations: /// /// (1) To try to find the location to insert a new point. Normally, we /// know an edge that the point is strictly to the left of. In the /// incremental Delaunay algorithm, that edge is a bounding box edge. /// In Ruppert's Delaunay refinement algorithm for quality meshing, /// that edge is the shortest edge of the triangle whose circumcenter /// is being inserted. /// /// (2) To try to find an existing point. In this case, any edge on the /// convex hull is a good starting edge. You must screen out the /// possibility that the vertex sought is an endpoint of the starting /// edge before you call preciselocate(). /// /// On completion, 'searchtri' is a triangle that contains 'searchpoint'. /// /// This implementation differs from that given by Guibas and Stolfi. It /// walks from triangle to triangle, crossing an edge only if 'searchpoint' /// is on the other side of the line containing that edge. After entering /// a triangle, there are two edges by which one can leave that triangle. /// If both edges are valid ('searchpoint' is on the other side of both /// edges), one of the two is chosen by drawing a line perpendicular to /// the entry edge (whose endpoints are 'forg' and 'fdest') passing through /// 'fapex'. Depending on which side of this perpendicular 'searchpoint' /// falls on, an exit edge is chosen. /// /// This implementation is empirically faster than the Guibas and Stolfi /// point location routine (which I originally used), which tends to spiral /// in toward its target. /// /// Returns ONVERTEX if the point lies on an existing vertex. 'searchtri' /// is a handle whose origin is the existing vertex. /// /// Returns ONEDGE if the point lies on a mesh edge. 'searchtri' is a /// handle whose primary edge is the edge on which the point lies. /// /// Returns INTRIANGLE if the point lies strictly within a triangle. /// 'searchtri' is a handle on the triangle that contains the point. /// /// Returns OUTSIDE if the point lies outside the mesh. 'searchtri' is a /// handle whose primary edge the point is to the right of. This might /// occur when the circumcenter of a triangle falls just slightly outside /// the mesh due to floating-point roundoff error. It also occurs when /// seeking a hole or region point that a foolish user has placed outside /// the mesh. /// /// WARNING: This routine is designed for convex triangulations, and will /// not generally work after the holes and concavities have been carved. /// However, it can still be used to find the circumcenter of a triangle, as /// long as the search is begun from the triangle in question.</remarks> public LocateResult PreciseLocate(Point searchpoint, ref Otri searchtri, bool stopatsubsegment) { Otri backtracktri = default(Otri); Osub checkedge = default(Osub); Vertex forg, fdest, fapex; double orgorient, destorient; bool moveleft; // Where are we? forg = searchtri.Org(); fdest = searchtri.Dest(); fapex = searchtri.Apex(); while (true) { // Check whether the apex is the point we seek. if ((fapex.x == searchpoint.X) && (fapex.y == searchpoint.Y)) { searchtri.LprevSelf(); return(LocateResult.OnVertex); } // Does the point lie on the other side of the line defined by the // triangle edge opposite the triangle's destination? destorient = Primitives.CounterClockwise(forg, fapex, searchpoint); // Does the point lie on the other side of the line defined by the // triangle edge opposite the triangle's origin? orgorient = Primitives.CounterClockwise(fapex, fdest, searchpoint); if (destorient > 0.0) { if (orgorient > 0.0) { // Move left if the inner product of (fapex - searchpoint) and // (fdest - forg) is positive. This is equivalent to drawing // a line perpendicular to the line (forg, fdest) and passing // through 'fapex', and determining which side of this line // 'searchpoint' falls on. moveleft = (fapex.x - searchpoint.X) * (fdest.x - forg.x) + (fapex.y - searchpoint.Y) * (fdest.y - forg.y) > 0.0; } else { moveleft = true; } } else { if (orgorient > 0.0) { moveleft = false; } else { // The point we seek must be on the boundary of or inside this // triangle. if (destorient == 0.0) { searchtri.LprevSelf(); return(LocateResult.OnEdge); } if (orgorient == 0.0) { searchtri.LnextSelf(); return(LocateResult.OnEdge); } return(LocateResult.InTriangle); } } // Move to another triangle. Leave a trace 'backtracktri' in case // floating-point roundoff or some such bogey causes us to walk // off a boundary of the triangulation. if (moveleft) { searchtri.Lprev(ref backtracktri); fdest = fapex; } else { searchtri.Lnext(ref backtracktri); forg = fapex; } backtracktri.Sym(ref searchtri); if (mesh.checksegments && stopatsubsegment) { // Check for walking through a subsegment. backtracktri.SegPivot(ref checkedge); if (checkedge.seg != Mesh.dummysub) { // Go back to the last triangle. backtracktri.Copy(ref searchtri); return(LocateResult.Outside); } } // Check for walking right out of the triangulation. if (searchtri.triangle == Mesh.dummytri) { // Go back to the last triangle. backtracktri.Copy(ref searchtri); return(LocateResult.Outside); } fapex = searchtri.Apex(); } }
/// <summary> /// Remove the "infinite" bounding triangle, setting boundary markers as appropriate. /// </summary> /// <returns>Returns the number of edges on the convex hull of the triangulation.</returns> /// <remarks> /// The triangular bounding box has three boundary triangles (one for each /// side of the bounding box), and a bunch of triangles fanning out from /// the three bounding box vertices (one triangle for each edge of the /// convex hull of the inner mesh). This routine removes these triangles. /// </remarks> int RemoveBox() { Otri deadtriangle = default(Otri); Otri searchedge = default(Otri); Otri checkedge = default(Otri); Otri nextedge = default(Otri), finaledge = default(Otri), dissolveedge = default(Otri); Vertex markorg; int hullsize; bool noPoly = !mesh.behavior.Poly; // Find a boundary triangle. nextedge.triangle = Mesh.dummytri; nextedge.orient = 0; nextedge.SymSelf(); // Mark a place to stop. nextedge.Lprev(ref finaledge); nextedge.LnextSelf(); nextedge.SymSelf(); // Find a triangle (on the boundary of the vertex set) that isn't // a bounding box triangle. nextedge.Lprev(ref searchedge); searchedge.SymSelf(); // Check whether nextedge is another boundary triangle // adjacent to the first one. nextedge.Lnext(ref checkedge); checkedge.SymSelf(); if (checkedge.triangle == Mesh.dummytri) { // Go on to the next triangle. There are only three boundary // triangles, and this next triangle cannot be the third one, // so it's safe to stop here. searchedge.LprevSelf(); searchedge.SymSelf(); } // Find a new boundary edge to search from, as the current search // edge lies on a bounding box triangle and will be deleted. Mesh.dummytri.neighbors[0] = searchedge; hullsize = -2; while (!nextedge.Equal(finaledge)) { hullsize++; nextedge.Lprev(ref dissolveedge); dissolveedge.SymSelf(); // If not using a PSLG, the vertices should be marked now. // (If using a PSLG, markhull() will do the job.) if (noPoly) { // Be careful! One must check for the case where all the input // vertices are collinear, and thus all the triangles are part of // the bounding box. Otherwise, the setvertexmark() call below // will cause a bad pointer reference. if (dissolveedge.triangle != Mesh.dummytri) { markorg = dissolveedge.Org(); if (markorg.mark == 0) { markorg.mark = 1; } } } // Disconnect the bounding box triangle from the mesh triangle. dissolveedge.Dissolve(); nextedge.Lnext(ref deadtriangle); deadtriangle.Sym(ref nextedge); // Get rid of the bounding box triangle. mesh.TriangleDealloc(deadtriangle.triangle); // Do we need to turn the corner? if (nextedge.triangle == Mesh.dummytri) { // Turn the corner. dissolveedge.Copy(ref nextedge); } } mesh.TriangleDealloc(finaledge.triangle); return(hullsize); }
public LocateResult PreciseLocate(Point searchpoint, ref Otri searchtri, bool stopatsubsegment) { bool flag; Otri otri = new Otri(); Osub osub = new Osub(); Vertex vertex = searchtri.Org(); Vertex vertex1 = searchtri.Dest(); for (Vertex i = searchtri.Apex(); i.x != searchpoint.X || i.y != searchpoint.Y; i = searchtri.Apex()) { double num = Primitives.CounterClockwise(vertex, i, searchpoint); double num1 = Primitives.CounterClockwise(i, vertex1, searchpoint); if (num <= 0) { if (num1 <= 0) { if (num == 0) { searchtri.LprevSelf(); return(LocateResult.OnEdge); } if (num1 != 0) { return(LocateResult.InTriangle); } searchtri.LnextSelf(); return(LocateResult.OnEdge); } flag = false; } else { flag = (num1 <= 0 ? true : (i.x - searchpoint.X) * (vertex1.x - vertex.x) + (i.y - searchpoint.Y) * (vertex1.y - vertex.y) > 0); } if (!flag) { searchtri.Lnext(ref otri); vertex = i; } else { searchtri.Lprev(ref otri); vertex1 = i; } otri.Sym(ref searchtri); if (this.mesh.checksegments & stopatsubsegment) { otri.SegPivot(ref osub); if (osub.seg != Mesh.dummysub) { otri.Copy(ref searchtri); return(LocateResult.Outside); } } if (searchtri.triangle == Mesh.dummytri) { otri.Copy(ref searchtri); return(LocateResult.Outside); } } searchtri.LprevSelf(); return(LocateResult.OnVertex); }
/// <summary> /// Construct Voronoi region for given vertex. /// </summary> /// <param name="region"></param> private void ConstructCell(VoronoiRegion region) { var vertex = region.Generator as Vertex; var vpoints = new List <Point>(); Otri f = default(Otri); Otri f_init = default(Otri); Otri f_next = default(Otri); Otri f_prev = default(Otri); Osub sub = default(Osub); // Call f_init a triangle incident to x vertex.tri.Copy(ref f_init); f_init.Copy(ref f); f_init.Onext(ref f_next); // Check if f_init lies on the boundary of the triangulation. if (f_next.tri.id == Mesh.DUMMY) { f_init.Oprev(ref f_prev); if (f_prev.tri.id != Mesh.DUMMY) { f_init.Copy(ref f_next); // Move one triangle clockwise f_init.Oprev(); f_init.Copy(ref f); } } // Go counterclockwise until we reach the border or the initial triangle. while (f_next.tri.id != Mesh.DUMMY) { // Add circumcenter of current triangle vpoints.Add(points[f.tri.id]); region.AddNeighbor(f.tri.id, regions[f.Apex().id]); if (f_next.Equals(f_init)) { // Voronoi cell is complete (bounded case). region.Add(vpoints); return; } f_next.Copy(ref f); f_next.Onext(); } // Voronoi cell is unbounded region.Bounded = false; Vertex torg, tdest, tapex; Point intersection; int sid, n = mesh.triangles.Count; // Find the boundary segment id (we use this id to number the endpoints of infinit rays). f.Lprev(ref f_next); f_next.Pivot(ref sub); sid = sub.seg.hash; // Last valid f lies at the boundary. Add the circumcenter. vpoints.Add(points[f.tri.id]); region.AddNeighbor(f.tri.id, regions[f.Apex().id]); // Check if the intersection with the bounding box has already been computed. if (!rayPoints.TryGetValue(sid, out intersection)) { torg = f.Org(); tapex = f.Apex(); intersection = IntersectionHelper.BoxRayIntersection(bounds, points[f.tri.id], torg.y - tapex.y, tapex.x - torg.x); // Set the correct id for the vertex intersection.id = n + rayIndex; points[n + rayIndex] = intersection; rayIndex++; rayPoints.Add(sid, intersection); } vpoints.Add(intersection); // Now walk from f_init clockwise till we reach the boundary. vpoints.Reverse(); f_init.Copy(ref f); f.Oprev(ref f_prev); while (f_prev.tri.id != Mesh.DUMMY) { vpoints.Add(points[f_prev.tri.id]); region.AddNeighbor(f_prev.tri.id, regions[f_prev.Apex().id]); f_prev.Copy(ref f); f_prev.Oprev(); } // Find the boundary segment id. f.Pivot(ref sub); sid = sub.seg.hash; if (!rayPoints.TryGetValue(sid, out intersection)) { // Intersection has not been computed yet. torg = f.Org(); tdest = f.Dest(); intersection = IntersectionHelper.BoxRayIntersection(bounds, points[f.tri.id], tdest.y - torg.y, torg.x - tdest.x); // Set the correct id for the vertex intersection.id = n + rayIndex; rayPoints.Add(sid, intersection); points[n + rayIndex] = intersection; rayIndex++; } vpoints.Add(intersection); region.AddNeighbor(intersection.id, regions[f.Dest().id]); // Add the new points to the region (in counter-clockwise order) vpoints.Reverse(); region.Add(vpoints); }
/// <summary> /// Merge two adjacent Delaunay triangulations into a single Delaunay triangulation. /// </summary> /// <param name="farleft">Bounding triangles of the left triangulation.</param> /// <param name="innerleft">Bounding triangles of the left triangulation.</param> /// <param name="innerright">Bounding triangles of the right triangulation.</param> /// <param name="farright">Bounding triangles of the right triangulation.</param> /// <param name="axis"></param> /// <remarks> /// This is similar to the algorithm given by Guibas and Stolfi, but uses /// a triangle-based, rather than edge-based, data structure. /// /// The algorithm walks up the gap between the two triangulations, knitting /// them together. As they are merged, some of their bounding triangles /// are converted into real triangles of the triangulation. The procedure /// pulls each hull's bounding triangles apart, then knits them together /// like the teeth of two gears. The Delaunay property determines, at each /// step, whether the next "tooth" is a bounding triangle of the left hull /// or the right. When a bounding triangle becomes real, its apex is /// changed from NULL to a real vertex. /// /// Only two new triangles need to be allocated. These become new bounding /// triangles at the top and bottom of the seam. They are used to connect /// the remaining bounding triangles (those that have not been converted /// into real triangles) into a single fan. /// /// On entry, 'farleft' and 'innerleft' are bounding triangles of the left /// triangulation. The origin of 'farleft' is the leftmost vertex, and /// the destination of 'innerleft' is the rightmost vertex of the /// triangulation. Similarly, 'innerright' and 'farright' are bounding /// triangles of the right triangulation. The origin of 'innerright' and /// destination of 'farright' are the leftmost and rightmost vertices. /// /// On completion, the origin of 'farleft' is the leftmost vertex of the /// merged triangulation, and the destination of 'farright' is the rightmost /// vertex. /// </remarks> void MergeHulls(ref Otri farleft, ref Otri innerleft, ref Otri innerright, ref Otri farright, int axis) { Otri leftcand = default(Otri), rightcand = default(Otri); Otri nextedge = default(Otri); Otri sidecasing = default(Otri), topcasing = default(Otri), outercasing = default(Otri); Otri checkedge = default(Otri); Otri baseedge = default(Otri); Vertex innerleftdest; Vertex innerrightorg; Vertex innerleftapex, innerrightapex; Vertex farleftpt, farrightpt; Vertex farleftapex, farrightapex; Vertex lowerleft, lowerright; Vertex upperleft, upperright; Vertex nextapex; Vertex checkvertex; bool changemade; bool badedge; bool leftfinished, rightfinished; innerleftdest = innerleft.Dest(); innerleftapex = innerleft.Apex(); innerrightorg = innerright.Org(); innerrightapex = innerright.Apex(); // Special treatment for horizontal cuts. if (useDwyer && (axis == 1)) { farleftpt = farleft.Org(); farleftapex = farleft.Apex(); farrightpt = farright.Dest(); farrightapex = farright.Apex(); // The pointers to the extremal vertices are shifted to point to the // topmost and bottommost vertex of each hull, rather than the // leftmost and rightmost vertices. while (farleftapex.y < farleftpt.y) { farleft.LnextSelf(); farleft.SymSelf(); farleftpt = farleftapex; farleftapex = farleft.Apex(); } innerleft.Sym(ref checkedge); checkvertex = checkedge.Apex(); while (checkvertex.y > innerleftdest.y) { checkedge.Lnext(ref innerleft); innerleftapex = innerleftdest; innerleftdest = checkvertex; innerleft.Sym(ref checkedge); checkvertex = checkedge.Apex(); } while (innerrightapex.y < innerrightorg.y) { innerright.LnextSelf(); innerright.SymSelf(); innerrightorg = innerrightapex; innerrightapex = innerright.Apex(); } farright.Sym(ref checkedge); checkvertex = checkedge.Apex(); while (checkvertex.y > farrightpt.y) { checkedge.Lnext(ref farright); farrightapex = farrightpt; farrightpt = checkvertex; farright.Sym(ref checkedge); checkvertex = checkedge.Apex(); } } // Find a line tangent to and below both hulls. do { changemade = false; // Make innerleftdest the "bottommost" vertex of the left hull. if (Primitives.CounterClockwise(innerleftdest, innerleftapex, innerrightorg) > 0.0) { innerleft.LprevSelf(); innerleft.SymSelf(); innerleftdest = innerleftapex; innerleftapex = innerleft.Apex(); changemade = true; } // Make innerrightorg the "bottommost" vertex of the right hull. if (Primitives.CounterClockwise(innerrightapex, innerrightorg, innerleftdest) > 0.0) { innerright.LnextSelf(); innerright.SymSelf(); innerrightorg = innerrightapex; innerrightapex = innerright.Apex(); changemade = true; } } while (changemade); // Find the two candidates to be the next "gear tooth." innerleft.Sym(ref leftcand); innerright.Sym(ref rightcand); // Create the bottom new bounding triangle. mesh.MakeTriangle(ref baseedge); // Connect it to the bounding boxes of the left and right triangulations. baseedge.Bond(ref innerleft); baseedge.LnextSelf(); baseedge.Bond(ref innerright); baseedge.LnextSelf(); baseedge.SetOrg(innerrightorg); baseedge.SetDest(innerleftdest); // Apex is intentionally left NULL. // Fix the extreme triangles if necessary. farleftpt = farleft.Org(); if (innerleftdest == farleftpt) { baseedge.Lnext(ref farleft); } farrightpt = farright.Dest(); if (innerrightorg == farrightpt) { baseedge.Lprev(ref farright); } // The vertices of the current knitting edge. lowerleft = innerleftdest; lowerright = innerrightorg; // The candidate vertices for knitting. upperleft = leftcand.Apex(); upperright = rightcand.Apex(); // Walk up the gap between the two triangulations, knitting them together. while (true) { // Have we reached the top? (This isn't quite the right question, // because even though the left triangulation might seem finished now, // moving up on the right triangulation might reveal a new vertex of // the left triangulation. And vice-versa.) leftfinished = Primitives.CounterClockwise(upperleft, lowerleft, lowerright) <= 0.0; rightfinished = Primitives.CounterClockwise(upperright, lowerleft, lowerright) <= 0.0; if (leftfinished && rightfinished) { // Create the top new bounding triangle. mesh.MakeTriangle(ref nextedge); nextedge.SetOrg(lowerleft); nextedge.SetDest(lowerright); // Apex is intentionally left NULL. // Connect it to the bounding boxes of the two triangulations. nextedge.Bond(ref baseedge); nextedge.LnextSelf(); nextedge.Bond(ref rightcand); nextedge.LnextSelf(); nextedge.Bond(ref leftcand); // Special treatment for horizontal cuts. if (useDwyer && (axis == 1)) { farleftpt = farleft.Org(); farleftapex = farleft.Apex(); farrightpt = farright.Dest(); farrightapex = farright.Apex(); farleft.Sym(ref checkedge); checkvertex = checkedge.Apex(); // The pointers to the extremal vertices are restored to the // leftmost and rightmost vertices (rather than topmost and // bottommost). while (checkvertex.x < farleftpt.x) { checkedge.Lprev(ref farleft); farleftapex = farleftpt; farleftpt = checkvertex; farleft.Sym(ref checkedge); checkvertex = checkedge.Apex(); } while (farrightapex.x > farrightpt.x) { farright.LprevSelf(); farright.SymSelf(); farrightpt = farrightapex; farrightapex = farright.Apex(); } } return; } // Consider eliminating edges from the left triangulation. if (!leftfinished) { // What vertex would be exposed if an edge were deleted? leftcand.Lprev(ref nextedge); nextedge.SymSelf(); nextapex = nextedge.Apex(); // If nextapex is NULL, then no vertex would be exposed; the // triangulation would have been eaten right through. if (nextapex != null) { // Check whether the edge is Delaunay. badedge = Primitives.InCircle(lowerleft, lowerright, upperleft, nextapex) > 0.0; while (badedge) { // Eliminate the edge with an edge flip. As a result, the // left triangulation will have one more boundary triangle. nextedge.LnextSelf(); nextedge.Sym(ref topcasing); nextedge.LnextSelf(); nextedge.Sym(ref sidecasing); nextedge.Bond(ref topcasing); leftcand.Bond(ref sidecasing); leftcand.LnextSelf(); leftcand.Sym(ref outercasing); nextedge.LprevSelf(); nextedge.Bond(ref outercasing); // Correct the vertices to reflect the edge flip. leftcand.SetOrg(lowerleft); leftcand.SetDest(null); leftcand.SetApex(nextapex); nextedge.SetOrg(null); nextedge.SetDest(upperleft); nextedge.SetApex(nextapex); // Consider the newly exposed vertex. upperleft = nextapex; // What vertex would be exposed if another edge were deleted? sidecasing.Copy(ref nextedge); nextapex = nextedge.Apex(); if (nextapex != null) { // Check whether the edge is Delaunay. badedge = Primitives.InCircle(lowerleft, lowerright, upperleft, nextapex) > 0.0; } else { // Avoid eating right through the triangulation. badedge = false; } } } } // Consider eliminating edges from the right triangulation. if (!rightfinished) { // What vertex would be exposed if an edge were deleted? rightcand.Lnext(ref nextedge); nextedge.SymSelf(); nextapex = nextedge.Apex(); // If nextapex is NULL, then no vertex would be exposed; the // triangulation would have been eaten right through. if (nextapex != null) { // Check whether the edge is Delaunay. badedge = Primitives.InCircle(lowerleft, lowerright, upperright, nextapex) > 0.0; while (badedge) { // Eliminate the edge with an edge flip. As a result, the // right triangulation will have one more boundary triangle. nextedge.LprevSelf(); nextedge.Sym(ref topcasing); nextedge.LprevSelf(); nextedge.Sym(ref sidecasing); nextedge.Bond(ref topcasing); rightcand.Bond(ref sidecasing); rightcand.LprevSelf(); rightcand.Sym(ref outercasing); nextedge.LnextSelf(); nextedge.Bond(ref outercasing); // Correct the vertices to reflect the edge flip. rightcand.SetOrg(null); rightcand.SetDest(lowerright); rightcand.SetApex(nextapex); nextedge.SetOrg(upperright); nextedge.SetDest(null); nextedge.SetApex(nextapex); // Consider the newly exposed vertex. upperright = nextapex; // What vertex would be exposed if another edge were deleted? sidecasing.Copy(ref nextedge); nextapex = nextedge.Apex(); if (nextapex != null) { // Check whether the edge is Delaunay. badedge = Primitives.InCircle(lowerleft, lowerright, upperright, nextapex) > 0.0; } else { // Avoid eating right through the triangulation. badedge = false; } } } } if (leftfinished || (!rightfinished && (Primitives.InCircle(upperleft, lowerleft, lowerright, upperright) > 0.0))) { // Knit the triangulations, adding an edge from 'lowerleft' // to 'upperright'. baseedge.Bond(ref rightcand); rightcand.Lprev(ref baseedge); baseedge.SetDest(lowerleft); lowerright = upperright; baseedge.Sym(ref rightcand); upperright = rightcand.Apex(); } else { // Knit the triangulations, adding an edge from 'upperleft' // to 'lowerright'. baseedge.Bond(ref leftcand); leftcand.Lnext(ref baseedge); baseedge.SetOrg(lowerright); lowerleft = upperleft; baseedge.Sym(ref leftcand); upperleft = leftcand.Apex(); } } }
public void TestTriangle(ref Otri testtri) { Vertex vertex; Vertex vertex1; double num; double num1; double num2; Otri otri = new Otri(); Otri otri1 = new Otri(); Osub osub = new Osub(); Vertex vertex2 = testtri.Org(); Vertex vertex3 = testtri.Dest(); Vertex vertex4 = testtri.Apex(); double num3 = vertex2.x - vertex3.x; double num4 = vertex2.y - vertex3.y; double num5 = vertex3.x - vertex4.x; double num6 = vertex3.y - vertex4.y; double num7 = vertex4.x - vertex2.x; double num8 = vertex4.y - vertex2.y; double num9 = num3 * num3; double num10 = num4 * num4; double num11 = num5 * num5; double num12 = num6 * num6; double num13 = num8 * num8; double num14 = num9 + num10; double num15 = num11 + num12; double num16 = num7 * num7 + num13; if (num14 < num15 && num14 < num16) { num = num14; num1 = num5 * num7 + num6 * num8; num1 = num1 * num1 / (num15 * num16); vertex = vertex2; vertex1 = vertex3; testtri.Copy(ref otri); } else if (num15 >= num16) { num = num16; num1 = num3 * num5 + num4 * num6; num1 = num1 * num1 / (num14 * num15); vertex = vertex4; vertex1 = vertex2; testtri.Lprev(ref otri); } else { num = num15; num1 = num3 * num7 + num4 * num8; num1 = num1 * num1 / (num14 * num16); vertex = vertex3; vertex1 = vertex4; testtri.Lnext(ref otri); } if (this.behavior.VarArea || this.behavior.fixedArea || this.behavior.Usertest) { double num17 = 0.5 * (num3 * num6 - num4 * num5); if (this.behavior.fixedArea && num17 > this.behavior.MaxArea) { this.queue.Enqueue(ref testtri, num, vertex4, vertex2, vertex3); return; } if (this.behavior.VarArea && num17 > testtri.triangle.area && testtri.triangle.area > 0) { this.queue.Enqueue(ref testtri, num, vertex4, vertex2, vertex3); return; } if (this.behavior.Usertest && this.userTest != null && this.userTest(vertex2, vertex3, vertex4, num17)) { this.queue.Enqueue(ref testtri, num, vertex4, vertex2, vertex3); return; } } if (num14 <= num15 || num14 <= num16) { num2 = (num15 <= num16 ? (num14 + num15 - num16) / (2 * Math.Sqrt(num14 * num15)) : (num14 + num16 - num15) / (2 * Math.Sqrt(num14 * num16))); } else { num2 = (num15 + num16 - num14) / (2 * Math.Sqrt(num15 * num16)); } if (num1 > this.behavior.goodAngle || num2 < this.behavior.maxGoodAngle && this.behavior.MaxAngle != 0) { if (vertex.type == VertexType.SegmentVertex && vertex1.type == VertexType.SegmentVertex) { otri.SegPivot(ref osub); if (osub.seg == Mesh.dummysub) { otri.Copy(ref otri1); do { otri.OprevSelf(); otri.SegPivot(ref osub); }while (osub.seg == Mesh.dummysub); Vertex vertex5 = osub.SegOrg(); Vertex vertex6 = osub.SegDest(); do { otri1.DnextSelf(); otri1.SegPivot(ref osub); }while (osub.seg == Mesh.dummysub); Vertex vertex7 = osub.SegOrg(); Vertex vertex8 = osub.SegDest(); Vertex vertex9 = null; if (vertex6.x == vertex7.x && vertex6.y == vertex7.y) { vertex9 = vertex6; } else if (vertex5.x == vertex8.x && vertex5.y == vertex8.y) { vertex9 = vertex5; } if (vertex9 != null) { double num18 = (vertex.x - vertex9.x) * (vertex.x - vertex9.x) + (vertex.y - vertex9.y) * (vertex.y - vertex9.y); double num19 = (vertex1.x - vertex9.x) * (vertex1.x - vertex9.x) + (vertex1.y - vertex9.y) * (vertex1.y - vertex9.y); if (num18 < 1.001 * num19 && num18 > 0.999 * num19) { return; } } } } this.queue.Enqueue(ref testtri, num, vertex4, vertex2, vertex3); } }
/// <summary> /// Split all the encroached subsegments. /// </summary> /// <param name="triflaws">A flag that specifies whether one should take /// note of new bad triangles that result from inserting vertices to repair /// encroached subsegments.</param> /// <remarks> /// Each encroached subsegment is repaired by splitting it - inserting a /// vertex at or near its midpoint. Newly inserted vertices may encroach /// upon other subsegments; these are also repaired. /// </remarks> private void SplitEncSegs(bool triflaws) { Otri enctri = default(Otri); Otri testtri = default(Otri); Osub testsh = default(Osub); Osub currentenc = default(Osub); BadSubseg seg; Vertex eorg, edest, eapex; Vertex newvertex; InsertVertexResult success; float segmentlength, nearestpoweroftwo; float split; float multiplier, divisor; bool acuteorg, acuteorg2, acutedest, acutedest2; // Note that steinerleft == -1 if an unlimited number // of Steiner points is allowed. while (badsubsegs.Count > 0) { if (mesh.steinerleft == 0) { break; } seg = badsubsegs.Dequeue(); currentenc = seg.encsubseg; eorg = currentenc.Org(); edest = currentenc.Dest(); // Make sure that this segment is still the same segment it was // when it was determined to be encroached. If the segment was // enqueued multiple times (because several newly inserted // vertices encroached it), it may have already been split. if (!Osub.IsDead(currentenc.seg) && (eorg == seg.subsegorg) && (edest == seg.subsegdest)) { // To decide where to split a segment, we need to know if the // segment shares an endpoint with an adjacent segment. // The concern is that, if we simply split every encroached // segment in its center, two adjacent segments with a small // angle between them might lead to an infinite loop; each // vertex added to split one segment will encroach upon the // other segment, which must then be split with a vertex that // will encroach upon the first segment, and so on forever. // To avoid this, imagine a set of concentric circles, whose // radii are powers of two, about each segment endpoint. // These concentric circles determine where the segment is // split. (If both endpoints are shared with adjacent // segments, split the segment in the middle, and apply the // concentric circles for later splittings.) // Is the origin shared with another segment? currentenc.TriPivot(ref enctri); enctri.Lnext(ref testtri); testtri.SegPivot(ref testsh); acuteorg = testsh.seg != Mesh.dummysub; // Is the destination shared with another segment? testtri.LnextSelf(); testtri.SegPivot(ref testsh); acutedest = testsh.seg != Mesh.dummysub; // If we're using Chew's algorithm (rather than Ruppert's) // to define encroachment, delete free vertices from the // subsegment's diametral circle. if (!behavior.ConformingDelaunay && !acuteorg && !acutedest) { eapex = enctri.Apex(); while ((eapex.type == VertexType.FreeVertex) && ((eorg.x - eapex.x) * (edest.x - eapex.x) + (eorg.y - eapex.y) * (edest.y - eapex.y) < 0.0)) { mesh.DeleteVertex(ref testtri); currentenc.TriPivot(ref enctri); eapex = enctri.Apex(); enctri.Lprev(ref testtri); } } // Now, check the other side of the segment, if there's a triangle there. enctri.Sym(ref testtri); if (testtri.triangle != Mesh.dummytri) { // Is the destination shared with another segment? testtri.LnextSelf(); testtri.SegPivot(ref testsh); acutedest2 = testsh.seg != Mesh.dummysub; acutedest = acutedest || acutedest2; // Is the origin shared with another segment? testtri.LnextSelf(); testtri.SegPivot(ref testsh); acuteorg2 = testsh.seg != Mesh.dummysub; acuteorg = acuteorg || acuteorg2; // Delete free vertices from the subsegment's diametral circle. if (!behavior.ConformingDelaunay && !acuteorg2 && !acutedest2) { eapex = testtri.Org(); while ((eapex.type == VertexType.FreeVertex) && ((eorg.x - eapex.x) * (edest.x - eapex.x) + (eorg.y - eapex.y) * (edest.y - eapex.y) < 0.0)) { mesh.DeleteVertex(ref testtri); enctri.Sym(ref testtri); eapex = testtri.Apex(); testtri.LprevSelf(); } } } // Use the concentric circles if exactly one endpoint is shared // with another adjacent segment. if (acuteorg || acutedest) { segmentlength = UnityEngine.Mathf.Sqrt((edest.x - eorg.x) * (edest.x - eorg.x) + (edest.y - eorg.y) * (edest.y - eorg.y)); // Find the power of two that most evenly splits the segment. // The worst case is a 2:1 ratio between subsegment lengths. nearestpoweroftwo = 1.0f; while (segmentlength > 3.0f * nearestpoweroftwo) { nearestpoweroftwo *= 2.0f; } while (segmentlength < 1.5f * nearestpoweroftwo) { nearestpoweroftwo *= 0.5f; } // Where do we split the segment? split = nearestpoweroftwo / segmentlength; if (acutedest) { split = 1.0f - split; } } else { // If we're not worried about adjacent segments, split // this segment in the middle. split = 0.5f; } // Create the new vertex (interpolate coordinates). newvertex = new Vertex( eorg.x + split * (edest.x - eorg.x), eorg.y + split * (edest.y - eorg.y), currentenc.Mark(), mesh.nextras); newvertex.type = VertexType.SegmentVertex; newvertex.hash = mesh.hash_vtx++; newvertex.id = newvertex.hash; mesh.vertices.Add(newvertex.hash, newvertex); // Interpolate attributes. for (int i = 0; i < mesh.nextras; i++) { newvertex.attributes[i] = eorg.attributes[i] + split * (edest.attributes[i] - eorg.attributes[i]); } if (!Behavior.NoExact) { // Roundoff in the above calculation may yield a 'newvertex' // that is not precisely collinear with 'eorg' and 'edest'. // Improve collinearity by one step of iterative refinement. multiplier = Primitives.CounterClockwise(eorg, edest, newvertex); divisor = ((eorg.x - edest.x) * (eorg.x - edest.x) + (eorg.y - edest.y) * (eorg.y - edest.y)); if ((multiplier != 0.0) && (divisor != 0.0)) { multiplier = multiplier / divisor; // Watch out for NANs. if (!float.IsNaN(multiplier)) { newvertex.x += multiplier * (edest.y - eorg.y); newvertex.y += multiplier * (eorg.x - edest.x); } } } // Check whether the new vertex lies on an endpoint. if (((newvertex.x == eorg.x) && (newvertex.y == eorg.y)) || ((newvertex.x == edest.x) && (newvertex.y == edest.y))) { logger.Error("Ran out of precision: I attempted to split a" + " segment to a smaller size than can be accommodated by" + " the finite precision of floating point arithmetic.", "Quality.SplitEncSegs()"); throw new Exception("Ran out of precision"); } // Insert the splitting vertex. This should always succeed. success = mesh.InsertVertex(newvertex, ref enctri, ref currentenc, true, triflaws); if ((success != InsertVertexResult.Successful) && (success != InsertVertexResult.Encroaching)) { logger.Error("Failure to split a segment.", "Quality.SplitEncSegs()"); throw new Exception("Failure to split a segment."); } if (mesh.steinerleft > 0) { mesh.steinerleft--; } // Check the two new subsegments to see if they're encroached. CheckSeg4Encroach(ref currentenc); currentenc.NextSelf(); CheckSeg4Encroach(ref currentenc); } // Set subsegment's origin to NULL. This makes it possible to detect dead // badsubsegs when traversing the list of all badsubsegs. seg.subsegorg = null; } }
private void SplitEncSegs(bool triflaws) { Vertex vertex; double num; Otri otri = new Otri(); Otri otri1 = new Otri(); Osub osub = new Osub(); Osub osub1 = new Osub(); while (this.badsubsegs.Count > 0 && this.mesh.steinerleft != 0) { BadSubseg badSubseg = this.badsubsegs.Dequeue(); osub1 = badSubseg.encsubseg; Vertex vertex1 = osub1.Org(); Vertex vertex2 = osub1.Dest(); if (!Osub.IsDead(osub1.seg) && vertex1 == badSubseg.subsegorg && vertex2 == badSubseg.subsegdest) { osub1.TriPivot(ref otri); otri.Lnext(ref otri1); otri1.SegPivot(ref osub); bool flag = osub.seg != Mesh.dummysub; otri1.LnextSelf(); otri1.SegPivot(ref osub); bool flag1 = osub.seg != Mesh.dummysub; if (!this.behavior.ConformingDelaunay && !flag && !flag1) { vertex = otri.Apex(); while (vertex.type == VertexType.FreeVertex && (vertex1.x - vertex.x) * (vertex2.x - vertex.x) + (vertex1.y - vertex.y) * (vertex2.y - vertex.y) < 0) { this.mesh.DeleteVertex(ref otri1); osub1.TriPivot(ref otri); vertex = otri.Apex(); otri.Lprev(ref otri1); } } otri.Sym(ref otri1); if (otri1.triangle != Mesh.dummytri) { otri1.LnextSelf(); otri1.SegPivot(ref osub); bool flag2 = osub.seg != Mesh.dummysub; flag1 = flag1 | flag2; otri1.LnextSelf(); otri1.SegPivot(ref osub); bool flag3 = osub.seg != Mesh.dummysub; flag = flag | flag3; if (!this.behavior.ConformingDelaunay && !flag3 && !flag2) { vertex = otri1.Org(); while (vertex.type == VertexType.FreeVertex && (vertex1.x - vertex.x) * (vertex2.x - vertex.x) + (vertex1.y - vertex.y) * (vertex2.y - vertex.y) < 0) { this.mesh.DeleteVertex(ref otri1); otri.Sym(ref otri1); vertex = otri1.Apex(); otri1.LprevSelf(); } } } if (!(flag | flag1)) { num = 0.5; } else { double num1 = Math.Sqrt((vertex2.x - vertex1.x) * (vertex2.x - vertex1.x) + (vertex2.y - vertex1.y) * (vertex2.y - vertex1.y)); double num2 = 1; while (num1 > 3 * num2) { num2 = num2 * 2; } while (num1 < 1.5 * num2) { num2 = num2 * 0.5; } num = num2 / num1; if (flag1) { num = 1 - num; } } Vertex vertex3 = new Vertex(vertex1.x + num * (vertex2.x - vertex1.x), vertex1.y + num * (vertex2.y - vertex1.y), osub1.Mark(), this.mesh.nextras) { type = VertexType.SegmentVertex }; Mesh mesh = this.mesh; int hashVtx = mesh.hash_vtx; mesh.hash_vtx = hashVtx + 1; vertex3.hash = hashVtx; vertex3.id = vertex3.hash; this.mesh.vertices.Add(vertex3.hash, vertex3); for (int i = 0; i < this.mesh.nextras; i++) { vertex3.attributes[i] = vertex1.attributes[i] + num * (vertex2.attributes[i] - vertex1.attributes[i]); } if (!Behavior.NoExact) { double num3 = Primitives.CounterClockwise(vertex1, vertex2, vertex3); double num4 = (vertex1.x - vertex2.x) * (vertex1.x - vertex2.x) + (vertex1.y - vertex2.y) * (vertex1.y - vertex2.y); if (num3 != 0 && num4 != 0) { num3 = num3 / num4; if (!double.IsNaN(num3)) { Vertex vertex4 = vertex3; vertex4.x = vertex4.x + num3 * (vertex2.y - vertex1.y); Vertex vertex5 = vertex3; vertex5.y = vertex5.y + num3 * (vertex1.x - vertex2.x); } } } if (vertex3.x == vertex1.x && vertex3.y == vertex1.y || vertex3.x == vertex2.x && vertex3.y == vertex2.y) { this.logger.Error("Ran out of precision: I attempted to split a segment to a smaller size than can be accommodated by the finite precision of floating point arithmetic.", "Quality.SplitEncSegs()"); throw new Exception("Ran out of precision"); } InsertVertexResult insertVertexResult = this.mesh.InsertVertex(vertex3, ref otri, ref osub1, true, triflaws); if (insertVertexResult != InsertVertexResult.Successful && insertVertexResult != InsertVertexResult.Encroaching) { this.logger.Error("Failure to split a segment.", "Quality.SplitEncSegs()"); throw new Exception("Failure to split a segment."); } if (this.mesh.steinerleft > 0) { Mesh mesh1 = this.mesh; mesh1.steinerleft = mesh1.steinerleft - 1; } this.CheckSeg4Encroach(ref osub1); osub1.NextSelf(); this.CheckSeg4Encroach(ref osub1); } badSubseg.subsegorg = null; } }
/// <summary> /// Finds the adjacencies between triangles by forming a stack of triangles for /// each vertex. Each triangle is on three different stacks simultaneously. /// </summary> private static List <Otri>[] SetNeighbors(Mesh mesh, ITriangle[] triangles) { Otri tri = default(Otri); Otri triangleleft = default(Otri); Otri checktri = default(Otri); Otri checkleft = default(Otri); Otri nexttri; TVertex tdest, tapex; TVertex checkdest, checkapex; int[] corner = new int[3]; int aroundvertex; int i; // Allocate a temporary array that maps each vertex to some adjacent triangle. var vertexarray = new List <Otri> [mesh.vertices.Count]; // Each vertex is initially unrepresented. for (i = 0; i < mesh.vertices.Count; i++) { Otri tmp = default(Otri); tmp.tri = mesh.dummytri; vertexarray[i] = new List <Otri>(3); vertexarray[i].Add(tmp); } i = 0; // Read the triangles from the .ele file, and link // together those that share an edge. foreach (var item in mesh.triangles) { tri.tri = item; // Copy the triangle's three corners. for (int j = 0; j < 3; j++) { corner[j] = triangles[i].GetVertexID(j); if ((corner[j] < 0) || (corner[j] >= mesh.invertices)) { Log.Instance.Error("Triangle has an invalid vertex index.", "MeshReader.Reconstruct()"); throw new Exception("Triangle has an invalid vertex index."); } } // Read the triangle's attributes. tri.tri.label = triangles[i].Label; // TODO: VarArea if (mesh.behavior.VarArea) { tri.tri.area = triangles[i].Area; } // Set the triangle's vertices. tri.orient = 0; tri.SetOrg(mesh.vertices[corner[0]]); tri.SetDest(mesh.vertices[corner[1]]); tri.SetApex(mesh.vertices[corner[2]]); // Try linking the triangle to others that share these vertices. for (tri.orient = 0; tri.orient < 3; tri.orient++) { // Take the number for the origin of triangleloop. aroundvertex = corner[tri.orient]; int index = vertexarray[aroundvertex].Count - 1; // Look for other triangles having this vertex. nexttri = vertexarray[aroundvertex][index]; // Push the current triangle onto the stack. vertexarray[aroundvertex].Add(tri); checktri = nexttri; if (checktri.tri.id != Mesh.DUMMY) { tdest = tri.Dest(); tapex = tri.Apex(); // Look for other triangles that share an edge. do { checkdest = checktri.Dest(); checkapex = checktri.Apex(); if (tapex == checkdest) { // The two triangles share an edge; bond them together. tri.Lprev(ref triangleleft); triangleleft.Bond(ref checktri); } if (tdest == checkapex) { // The two triangles share an edge; bond them together. checktri.Lprev(ref checkleft); tri.Bond(ref checkleft); } // Find the next triangle in the stack. index--; nexttri = vertexarray[aroundvertex][index]; checktri = nexttri; }while (checktri.tri.id != Mesh.DUMMY); } } i++; } return(vertexarray); }
/// <summary> /// Inserts a vertex at the circumcenter of a triangle. Deletes /// the newly inserted vertex if it encroaches upon a segment. /// </summary> /// <param name="badtri"></param> private void SplitTriangle(BadTriangle badtri) { Otri badotri = default(Otri); Vertex borg, bdest, bapex; Point newloc; // Location of the new vertex double xi = 0, eta = 0; InsertVertexResult success; bool errorflag; badotri = badtri.poortri; borg = badotri.Org(); bdest = badotri.Dest(); bapex = badotri.Apex(); // Make sure that this triangle is still the same triangle it was // when it was tested and determined to be of bad quality. // Subsequent transformations may have made it a different triangle. if (!Otri.IsDead(badotri.tri) && (borg == badtri.org) && (bdest == badtri.dest) && (bapex == badtri.apex)) { errorflag = false; // Create a new vertex at the triangle's circumcenter. // Using the original (simpler) Steiner point location method // for mesh refinement. // TODO: NewLocation doesn't work for refinement. Why? Maybe // reset VertexType? newloc = RobustPredicates.FindCircumcenter(borg, bdest, bapex, ref xi, ref eta, behavior.offconstant); // Check whether the new vertex lies on a triangle vertex. if (((newloc.X == borg.X) && (newloc.Y == borg.Y)) || ((newloc.X == bdest.X) && (newloc.Y == bdest.Y)) || ((newloc.X == bapex.X) && (newloc.Y == bapex.Y))) { //errorflag = true; } else { // The new vertex must be in the interior, and therefore is a // free vertex with a marker of zero. Vertex newvertex = new Vertex(newloc.X, newloc.Y, 0); newvertex.type = VertexType.FreeVertex; // Ensure that the handle 'badotri' does not represent the longest // edge of the triangle. This ensures that the circumcenter must // fall to the left of this edge, so point location will work. // (If the angle org-apex-dest exceeds 90 degrees, then the // circumcenter lies outside the org-dest edge, and eta is // negative. Roundoff error might prevent eta from being // negative when it should be, so I test eta against xi.) if (eta < xi) { badotri.Lprev(); } // Insert the circumcenter, searching from the edge of the triangle, // and maintain the Delaunay property of the triangulation. Osub tmp = default(Osub); success = mesh.InsertVertex(newvertex, ref badotri, ref tmp, true, true); if (success == InsertVertexResult.Successful) { newvertex.Id = mesh.hash_vtx++; mesh.vertices.Add(newvertex.Id, newvertex); if (mesh.steinerleft > 0) { mesh.steinerleft--; } } else if (success == InsertVertexResult.Encroaching) { // If the newly inserted vertex encroaches upon a subsegment, // delete the new vertex. mesh.UndoVertex(); } else if (success == InsertVertexResult.Violating) { // Failed to insert the new vertex, but some subsegment was // marked as being encroached. } else { //errorflag = true; } } if (errorflag) { throw new Exception("The new vertex is at the circumcenter of triangle."); } } }
public IMesh Triangulate(IList <Vertex> points, Configuration config) { this.predicates = config.Predicates(); this.mesh = new Mesh(config); this.mesh.TransferNodes(points); // Nonexistent x value used as a flag to mark circle events in sweepline // Delaunay algorithm. xminextreme = 10 * mesh.bounds.Left - 9 * mesh.bounds.Right; SweepEvent[] eventheap; SweepEvent nextevent; SweepEvent newevent; SplayNode splayroot; Otri bottommost = default(Otri); Otri searchtri = default(Otri); Otri fliptri; Otri lefttri = default(Otri); Otri righttri = default(Otri); Otri farlefttri = default(Otri); Otri farrighttri = default(Otri); Otri inserttri = default(Otri); Vertex firstvertex, secondvertex; Vertex nextvertex, lastvertex; Vertex connectvertex; Vertex leftvertex, midvertex, rightvertex; double lefttest, righttest; int heapsize; bool check4events, farrightflag = false; splaynodes = new List <SplayNode>(); splayroot = null; heapsize = points.Count; CreateHeap(out eventheap, heapsize);//, out events, out freeevents); mesh.MakeTriangle(ref lefttri); mesh.MakeTriangle(ref righttri); lefttri.Bond(ref righttri); lefttri.Lnext(); righttri.Lprev(); lefttri.Bond(ref righttri); lefttri.Lnext(); righttri.Lprev(); lefttri.Bond(ref righttri); firstvertex = eventheap[0].vertexEvent; HeapDelete(eventheap, heapsize, 0); heapsize--; do { if (heapsize == 0) { Log.Instance.Error("Input vertices are all identical.", "SweepLine.Triangulate()"); throw new Exception("Input vertices are all identical."); } secondvertex = eventheap[0].vertexEvent; HeapDelete(eventheap, heapsize, 0); heapsize--; if ((firstvertex.x == secondvertex.x) && (firstvertex.y == secondvertex.y)) { if (Log.Verbose) { Log.Instance.Warning("A duplicate vertex appeared and was ignored (ID " + secondvertex.id + ").", "SweepLine.Triangulate().1"); } secondvertex.type = VertexType.UndeadVertex; mesh.undeads++; } } while ((firstvertex.x == secondvertex.x) && (firstvertex.y == secondvertex.y)); lefttri.SetOrg(firstvertex); lefttri.SetDest(secondvertex); righttri.SetOrg(secondvertex); righttri.SetDest(firstvertex); lefttri.Lprev(ref bottommost); lastvertex = secondvertex; while (heapsize > 0) { nextevent = eventheap[0]; HeapDelete(eventheap, heapsize, 0); heapsize--; check4events = true; if (nextevent.xkey < mesh.bounds.Left) { fliptri = nextevent.otriEvent; fliptri.Oprev(ref farlefttri); Check4DeadEvent(ref farlefttri, eventheap, ref heapsize); fliptri.Onext(ref farrighttri); Check4DeadEvent(ref farrighttri, eventheap, ref heapsize); if (farlefttri.Equals(bottommost)) { fliptri.Lprev(ref bottommost); } mesh.Flip(ref fliptri); fliptri.SetApex(null); fliptri.Lprev(ref lefttri); fliptri.Lnext(ref righttri); lefttri.Sym(ref farlefttri); if (randomnation(SAMPLERATE) == 0) { fliptri.Sym(); leftvertex = fliptri.Dest(); midvertex = fliptri.Apex(); rightvertex = fliptri.Org(); splayroot = CircleTopInsert(splayroot, lefttri, leftvertex, midvertex, rightvertex, nextevent.ykey); } } else { nextvertex = nextevent.vertexEvent; if ((nextvertex.x == lastvertex.x) && (nextvertex.y == lastvertex.y)) { if (Log.Verbose) { Log.Instance.Warning("A duplicate vertex appeared and was ignored (ID " + nextvertex.id + ").", "SweepLine.Triangulate().2"); } nextvertex.type = VertexType.UndeadVertex; mesh.undeads++; check4events = false; } else { lastvertex = nextvertex; splayroot = FrontLocate(splayroot, bottommost, nextvertex, ref searchtri, ref farrightflag); //bottommost.Copy(ref searchtri); //farrightflag = false; //while (!farrightflag && RightOfHyperbola(ref searchtri, nextvertex)) //{ // searchtri.OnextSelf(); // farrightflag = searchtri.Equal(bottommost); //} Check4DeadEvent(ref searchtri, eventheap, ref heapsize); searchtri.Copy(ref farrighttri); searchtri.Sym(ref farlefttri); mesh.MakeTriangle(ref lefttri); mesh.MakeTriangle(ref righttri); connectvertex = farrighttri.Dest(); lefttri.SetOrg(connectvertex); lefttri.SetDest(nextvertex); righttri.SetOrg(nextvertex); righttri.SetDest(connectvertex); lefttri.Bond(ref righttri); lefttri.Lnext(); righttri.Lprev(); lefttri.Bond(ref righttri); lefttri.Lnext(); righttri.Lprev(); lefttri.Bond(ref farlefttri); righttri.Bond(ref farrighttri); if (!farrightflag && farrighttri.Equals(bottommost)) { lefttri.Copy(ref bottommost); } if (randomnation(SAMPLERATE) == 0) { splayroot = SplayInsert(splayroot, lefttri, nextvertex); } else if (randomnation(SAMPLERATE) == 0) { righttri.Lnext(ref inserttri); splayroot = SplayInsert(splayroot, inserttri, nextvertex); } } } if (check4events) { leftvertex = farlefttri.Apex(); midvertex = lefttri.Dest(); rightvertex = lefttri.Apex(); lefttest = predicates.CounterClockwise(leftvertex, midvertex, rightvertex); if (lefttest > 0.0) { newevent = new SweepEvent(); newevent.xkey = xminextreme; newevent.ykey = CircleTop(leftvertex, midvertex, rightvertex, lefttest); newevent.otriEvent = lefttri; HeapInsert(eventheap, heapsize, newevent); heapsize++; lefttri.SetOrg(new SweepEventVertex(newevent)); } leftvertex = righttri.Apex(); midvertex = righttri.Org(); rightvertex = farrighttri.Apex(); righttest = predicates.CounterClockwise(leftvertex, midvertex, rightvertex); if (righttest > 0.0) { newevent = new SweepEvent(); newevent.xkey = xminextreme; newevent.ykey = CircleTop(leftvertex, midvertex, rightvertex, righttest); newevent.otriEvent = farrighttri; HeapInsert(eventheap, heapsize, newevent); heapsize++; farrighttri.SetOrg(new SweepEventVertex(newevent)); } } } splaynodes.Clear(); bottommost.Lprev(); this.mesh.hullsize = RemoveGhosts(ref bottommost); return(this.mesh); }
public static int Reconstruct(Mesh mesh, InputGeometry input, ITriangle[] triangles) { Otri item; int num; int num1 = 0; Otri region = new Otri(); Otri otri = new Otri(); Otri l = new Otri(); Otri otri1 = new Otri(); Otri otri2 = new Otri(); Osub osub = new Osub(); int[] p0 = new int[3]; int[] p1 = new int[2]; int i = 0; int num2 = (triangles == null ? 0 : (int)triangles.Length); int count = input.segments.Count; mesh.inelements = num2; mesh.regions.AddRange(input.regions); for (i = 0; i < mesh.inelements; i++) { mesh.MakeTriangle(ref region); } if (mesh.behavior.Poly) { mesh.insegments = count; for (i = 0; i < mesh.insegments; i++) { mesh.MakeSegment(ref osub); } } List <Otri>[] otris = new List <Otri> [mesh.vertices.Count]; for (i = 0; i < mesh.vertices.Count; i++) { Otri otri3 = new Otri() { triangle = Mesh.dummytri }; otris[i] = new List <Otri>(3); otris[i].Add(otri3); } i = 0; foreach (Triangle value in mesh.triangles.Values) { region.triangle = value; p0[0] = triangles[i].P0; p0[1] = triangles[i].P1; p0[2] = triangles[i].P2; for (int j = 0; j < 3; j++) { if (p0[j] < 0 || p0[j] >= mesh.invertices) { SimpleLog.Instance.Error("Triangle has an invalid vertex index.", "MeshReader.Reconstruct()"); throw new Exception("Triangle has an invalid vertex index."); } } region.triangle.region = triangles[i].Region; if (mesh.behavior.VarArea) { region.triangle.area = triangles[i].Area; } region.orient = 0; region.SetOrg(mesh.vertices[p0[0]]); region.SetDest(mesh.vertices[p0[1]]); region.SetApex(mesh.vertices[p0[2]]); region.orient = 0; while (region.orient < 3) { num = p0[region.orient]; int count1 = otris[num].Count - 1; item = otris[num][count1]; otris[num].Add(region); l = item; if (l.triangle != Mesh.dummytri) { Vertex vertex = region.Dest(); Vertex vertex1 = region.Apex(); do { Vertex vertex2 = l.Dest(); Vertex vertex3 = l.Apex(); if (vertex1 == vertex2) { region.Lprev(ref otri); otri.Bond(ref l); } if (vertex == vertex3) { l.Lprev(ref otri1); region.Bond(ref otri1); } count1--; item = otris[num][count1]; l = item; }while (l.triangle != Mesh.dummytri); } region.orient = region.orient + 1; } i++; } num1 = 0; if (mesh.behavior.Poly) { int boundary = 0; i = 0; foreach (Segment segment in mesh.subsegs.Values) { osub.seg = segment; p1[0] = input.segments[i].P0; p1[1] = input.segments[i].P1; boundary = input.segments[i].Boundary; for (int k = 0; k < 2; k++) { if (p1[k] < 0 || p1[k] >= mesh.invertices) { SimpleLog.Instance.Error("Segment has an invalid vertex index.", "MeshReader.Reconstruct()"); throw new Exception("Segment has an invalid vertex index."); } } osub.orient = 0; Vertex item1 = mesh.vertices[p1[0]]; Vertex item2 = mesh.vertices[p1[1]]; osub.SetOrg(item1); osub.SetDest(item2); osub.SetSegOrg(item1); osub.SetSegDest(item2); osub.seg.boundary = boundary; osub.orient = 0; while (osub.orient < 2) { num = p1[1 - osub.orient]; int count2 = otris[num].Count - 1; Otri item3 = otris[num][count2]; item = otris[num][count2]; l = item; Vertex vertex4 = osub.Org(); bool flag = true; while (flag && l.triangle != Mesh.dummytri) { if (vertex4 == l.Dest()) { otris[num].Remove(item3); l.SegBond(ref osub); l.Sym(ref otri2); if (otri2.triangle == Mesh.dummytri) { mesh.InsertSubseg(ref l, 1); num1++; } flag = false; } count2--; item3 = otris[num][count2]; item = otris[num][count2]; l = item; } osub.orient = osub.orient + 1; } i++; } } for (i = 0; i < mesh.vertices.Count; i++) { int count3 = otris[i].Count - 1; item = otris[i][count3]; for (l = item; l.triangle != Mesh.dummytri; l = item) { count3--; item = otris[i][count3]; l.SegDissolve(); l.Sym(ref otri2); if (otri2.triangle == Mesh.dummytri) { mesh.InsertSubseg(ref l, 1); num1++; } } } return(num1); }
/// <summary> /// Test a triangle for quality and size. /// </summary> /// <param name="testtri">Triangle to check.</param> /// <remarks> /// Tests a triangle to see if it satisfies the minimum angle condition and /// the maximum area condition. Triangles that aren't up to spec are added /// to the bad triangle queue. /// </remarks> public void TestTriangle(ref Otri testtri) { Otri tri1 = default(Otri), tri2 = default(Otri); Osub testsub = default(Osub); Vertex torg, tdest, tapex; Vertex base1, base2; Vertex org1, dest1, org2, dest2; Vertex joinvertex; float dxod, dyod, dxda, dyda, dxao, dyao; float dxod2, dyod2, dxda2, dyda2, dxao2, dyao2; float apexlen, orglen, destlen, minedge; float angle; float area; float dist1, dist2; float maxangle; torg = testtri.Org(); tdest = testtri.Dest(); tapex = testtri.Apex(); dxod = torg.x - tdest.x; dyod = torg.y - tdest.y; dxda = tdest.x - tapex.x; dyda = tdest.y - tapex.y; dxao = tapex.x - torg.x; dyao = tapex.y - torg.y; dxod2 = dxod * dxod; dyod2 = dyod * dyod; dxda2 = dxda * dxda; dyda2 = dyda * dyda; dxao2 = dxao * dxao; dyao2 = dyao * dyao; // Find the lengths of the triangle's three edges. apexlen = dxod2 + dyod2; orglen = dxda2 + dyda2; destlen = dxao2 + dyao2; if ((apexlen < orglen) && (apexlen < destlen)) { // The edge opposite the apex is shortest. minedge = apexlen; // Find the square of the cosine of the angle at the apex. angle = dxda * dxao + dyda * dyao; angle = angle * angle / (orglen * destlen); base1 = torg; base2 = tdest; testtri.Copy(ref tri1); } else if (orglen < destlen) { // The edge opposite the origin is shortest. minedge = orglen; // Find the square of the cosine of the angle at the origin. angle = dxod * dxao + dyod * dyao; angle = angle * angle / (apexlen * destlen); base1 = tdest; base2 = tapex; testtri.Lnext(ref tri1); } else { // The edge opposite the destination is shortest. minedge = destlen; // Find the square of the cosine of the angle at the destination. angle = dxod * dxda + dyod * dyda; angle = angle * angle / (apexlen * orglen); base1 = tapex; base2 = torg; testtri.Lprev(ref tri1); } if (behavior.VarArea || behavior.fixedArea || behavior.Usertest) { // Check whether the area is larger than permitted. area = 0.5f * (dxod * dyda - dyod * dxda); if (behavior.fixedArea && (area > behavior.MaxArea)) { // Add this triangle to the list of bad triangles. queue.Enqueue(ref testtri, minedge, tapex, torg, tdest); return; } // Nonpositive area constraints are treated as unconstrained. if ((behavior.VarArea) && (area > testtri.triangle.area) && (testtri.triangle.area > 0.0)) { // Add this triangle to the list of bad triangles. queue.Enqueue(ref testtri, minedge, tapex, torg, tdest); return; } } // find the maximum edge and accordingly the pqr orientation if ((apexlen > orglen) && (apexlen > destlen)) { // The edge opposite the apex is longest. // maxedge = apexlen; // Find the cosine of the angle at the apex. maxangle = (orglen + destlen - apexlen) / (2 * UnityEngine.Mathf.Sqrt(orglen * destlen)); } else if (orglen > destlen) { // The edge opposite the origin is longest. // maxedge = orglen; // Find the cosine of the angle at the origin. maxangle = (apexlen + destlen - orglen) / (2 * UnityEngine.Mathf.Sqrt(apexlen * destlen)); } else { // The edge opposite the destination is longest. // maxedge = destlen; // Find the cosine of the angle at the destination. maxangle = (apexlen + orglen - destlen) / (2 * UnityEngine.Mathf.Sqrt(apexlen * orglen)); } // Check whether the angle is smaller than permitted. if ((angle > behavior.goodAngle) || (maxangle < behavior.maxGoodAngle && behavior.MaxAngle != 0.0)) { // Use the rules of Miller, Pav, and Walkington to decide that certain // triangles should not be split, even if they have bad angles. // A skinny triangle is not split if its shortest edge subtends a // small input angle, and both endpoints of the edge lie on a // concentric circular shell. For convenience, I make a small // adjustment to that rule: I check if the endpoints of the edge // both lie in segment interiors, equidistant from the apex where // the two segments meet. // First, check if both points lie in segment interiors. if ((base1.type == VertexType.SegmentVertex) && (base2.type == VertexType.SegmentVertex)) { // Check if both points lie in a common segment. If they do, the // skinny triangle is enqueued to be split as usual. tri1.SegPivot(ref testsub); if (testsub.seg == Mesh.dummysub) { // No common segment. Find a subsegment that contains 'torg'. tri1.Copy(ref tri2); do { tri1.OprevSelf(); tri1.SegPivot(ref testsub); } while (testsub.seg == Mesh.dummysub); // Find the endpoints of the containing segment. org1 = testsub.SegOrg(); dest1 = testsub.SegDest(); // Find a subsegment that contains 'tdest'. do { tri2.DnextSelf(); tri2.SegPivot(ref testsub); } while (testsub.seg == Mesh.dummysub); // Find the endpoints of the containing segment. org2 = testsub.SegOrg(); dest2 = testsub.SegDest(); // Check if the two containing segments have an endpoint in common. joinvertex = null; if ((dest1.x == org2.x) && (dest1.y == org2.y)) { joinvertex = dest1; } else if ((org1.x == dest2.x) && (org1.y == dest2.y)) { joinvertex = org1; } if (joinvertex != null) { // Compute the distance from the common endpoint (of the two // segments) to each of the endpoints of the shortest edge. dist1 = ((base1.x - joinvertex.x) * (base1.x - joinvertex.x) + (base1.y - joinvertex.y) * (base1.y - joinvertex.y)); dist2 = ((base2.x - joinvertex.x) * (base2.x - joinvertex.x) + (base2.y - joinvertex.y) * (base2.y - joinvertex.y)); // If the two distances are equal, don't split the triangle. if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2)) { // Return now to avoid enqueueing the bad triangle. return; } } } } // Add this triangle to the list of bad triangles. queue.Enqueue(ref testtri, minedge, tapex, torg, tdest); } }
private void DivconqRecurse(int left, int right, int axis, ref Otri farleft, ref Otri farright) { Otri otri = new Otri(); Otri otri1 = new Otri(); Otri otri2 = new Otri(); Otri otri3 = new Otri(); Otri otri4 = new Otri(); Otri otri5 = new Otri(); int num = right - left + 1; if (num == 2) { this.mesh.MakeTriangle(ref farleft); farleft.SetOrg(this.sortarray[left]); farleft.SetDest(this.sortarray[left + 1]); this.mesh.MakeTriangle(ref farright); farright.SetOrg(this.sortarray[left + 1]); farright.SetDest(this.sortarray[left]); farleft.Bond(ref farright); farleft.LprevSelf(); farright.LnextSelf(); farleft.Bond(ref farright); farleft.LprevSelf(); farright.LnextSelf(); farleft.Bond(ref farright); farright.Lprev(ref farleft); return; } if (num != 3) { int num1 = num >> 1; this.DivconqRecurse(left, left + num1 - 1, 1 - axis, ref farleft, ref otri4); this.DivconqRecurse(left + num1, right, 1 - axis, ref otri5, ref farright); this.MergeHulls(ref farleft, ref otri4, ref otri5, ref farright, axis); return; } this.mesh.MakeTriangle(ref otri); this.mesh.MakeTriangle(ref otri1); this.mesh.MakeTriangle(ref otri2); this.mesh.MakeTriangle(ref otri3); double num2 = Primitives.CounterClockwise(this.sortarray[left], this.sortarray[left + 1], this.sortarray[left + 2]); if (num2 == 0) { otri.SetOrg(this.sortarray[left]); otri.SetDest(this.sortarray[left + 1]); otri1.SetOrg(this.sortarray[left + 1]); otri1.SetDest(this.sortarray[left]); otri2.SetOrg(this.sortarray[left + 2]); otri2.SetDest(this.sortarray[left + 1]); otri3.SetOrg(this.sortarray[left + 1]); otri3.SetDest(this.sortarray[left + 2]); otri.Bond(ref otri1); otri2.Bond(ref otri3); otri.LnextSelf(); otri1.LprevSelf(); otri2.LnextSelf(); otri3.LprevSelf(); otri.Bond(ref otri3); otri1.Bond(ref otri2); otri.LnextSelf(); otri1.LprevSelf(); otri2.LnextSelf(); otri3.LprevSelf(); otri.Bond(ref otri1); otri2.Bond(ref otri3); otri1.Copy(ref farleft); otri2.Copy(ref farright); return; } otri.SetOrg(this.sortarray[left]); otri1.SetDest(this.sortarray[left]); otri3.SetOrg(this.sortarray[left]); if (num2 <= 0) { otri.SetDest(this.sortarray[left + 2]); otri1.SetOrg(this.sortarray[left + 2]); otri2.SetDest(this.sortarray[left + 2]); otri.SetApex(this.sortarray[left + 1]); otri2.SetOrg(this.sortarray[left + 1]); otri3.SetDest(this.sortarray[left + 1]); } else { otri.SetDest(this.sortarray[left + 1]); otri1.SetOrg(this.sortarray[left + 1]); otri2.SetDest(this.sortarray[left + 1]); otri.SetApex(this.sortarray[left + 2]); otri2.SetOrg(this.sortarray[left + 2]); otri3.SetDest(this.sortarray[left + 2]); } otri.Bond(ref otri1); otri.LnextSelf(); otri.Bond(ref otri2); otri.LnextSelf(); otri.Bond(ref otri3); otri1.LprevSelf(); otri2.LnextSelf(); otri1.Bond(ref otri2); otri1.LprevSelf(); otri3.LprevSelf(); otri1.Bond(ref otri3); otri2.LnextSelf(); otri3.LprevSelf(); otri2.Bond(ref otri3); otri1.Copy(ref farleft); if (num2 > 0) { otri2.Copy(ref farright); return; } farleft.Lnext(ref farright); }
/// <summary> /// Reconstruct a triangulation from its raw data representation. /// </summary> /// <param name="mesh"></param> /// <param name="input"></param> /// <returns></returns> /// <remarks> /// Reads an .ele file and reconstructs the original mesh. If the -p switch /// is used, this procedure will also read a .poly file and reconstruct the /// subsegments of the original mesh. If the -a switch is used, this /// procedure will also read an .area file and set a maximum area constraint /// on each triangle. /// /// Vertices that are not corners of triangles, such as nodes on edges of /// subparametric elements, are discarded. /// /// This routine finds the adjacencies between triangles (and subsegments) /// by forming one stack of triangles for each vertex. Each triangle is on /// three different stacks simultaneously. Each triangle's subsegment /// pointers are used to link the items in each stack. This memory-saving /// feature makes the code harder to read. The most important thing to keep /// in mind is that each triangle is removed from a stack precisely when /// the corresponding pointer is adjusted to refer to a subsegment rather /// than the next triangle of the stack. /// </remarks> public static int Reconstruct(Mesh mesh, InputGeometry input, ITriangle[] triangles) { int hullsize = 0; Otri tri = default(Otri); Otri triangleleft = default(Otri); Otri checktri = default(Otri); Otri checkleft = default(Otri); Otri checkneighbor = default(Otri); Osub subseg = default(Osub); List <Otri>[] vertexarray; // Triangle Otri prevlink; // Triangle Otri nexttri; // Triangle Vertex tdest, tapex; Vertex checkdest, checkapex; Vertex shorg; Vertex segmentorg, segmentdest; int[] corner = new int[3]; int[] end = new int[2]; //bool segmentmarkers = false; int boundmarker; int aroundvertex; bool notfound; int i = 0; int elements = triangles == null ? 0 : triangles.Length; int numberofsegments = input.segments.Count; mesh.inelements = elements; mesh.regions.AddRange(input.regions); // Create the triangles. for (i = 0; i < mesh.inelements; i++) { mesh.MakeTriangle(ref tri); // Mark the triangle as living. //tri.triangle.neighbors[0].triangle = tri.triangle; } if (mesh.behavior.Poly) { mesh.insegments = numberofsegments; // Create the subsegments. for (i = 0; i < mesh.insegments; i++) { mesh.MakeSegment(ref subseg); // Mark the subsegment as living. //subseg.ss.subsegs[0].ss = subseg.ss; } } // Allocate a temporary array that maps each vertex to some adjacent // triangle. I took care to allocate all the permanent memory for // triangles and subsegments first. vertexarray = new List <Otri> [mesh.vertices.Count]; // Each vertex is initially unrepresented. for (i = 0; i < mesh.vertices.Count; i++) { Otri tmp = default(Otri); tmp.triangle = Mesh.dummytri; vertexarray[i] = new List <Otri>(3); vertexarray[i].Add(tmp); } i = 0; // Read the triangles from the .ele file, and link // together those that share an edge. foreach (var item in mesh.triangles.Values) { tri.triangle = item; corner[0] = triangles[i].P0; corner[1] = triangles[i].P1; corner[2] = triangles[i].P2; // Copy the triangle's three corners. for (int j = 0; j < 3; j++) { if ((corner[j] < 0) || (corner[j] >= mesh.invertices)) { SimpleLog.Instance.Error("Triangle has an invalid vertex index.", "MeshReader.Reconstruct()"); throw new Exception("Triangle has an invalid vertex index."); } } // Read the triangle's attributes. tri.triangle.region = triangles[i].Region; // TODO: VarArea if (mesh.behavior.VarArea) { tri.triangle.area = triangles[i].Area; } // Set the triangle's vertices. tri.orient = 0; tri.SetOrg(mesh.vertices[corner[0]]); tri.SetDest(mesh.vertices[corner[1]]); tri.SetApex(mesh.vertices[corner[2]]); // Try linking the triangle to others that share these vertices. for (tri.orient = 0; tri.orient < 3; tri.orient++) { // Take the number for the origin of triangleloop. aroundvertex = corner[tri.orient]; int index = vertexarray[aroundvertex].Count - 1; // Look for other triangles having this vertex. nexttri = vertexarray[aroundvertex][index]; // Link the current triangle to the next one in the stack. //tri.triangle.neighbors[tri.orient] = nexttri; // Push the current triangle onto the stack. vertexarray[aroundvertex].Add(tri); checktri = nexttri; if (checktri.triangle != Mesh.dummytri) { tdest = tri.Dest(); tapex = tri.Apex(); // Look for other triangles that share an edge. do { checkdest = checktri.Dest(); checkapex = checktri.Apex(); if (tapex == checkdest) { // The two triangles share an edge; bond them together. tri.Lprev(ref triangleleft); triangleleft.Bond(ref checktri); } if (tdest == checkapex) { // The two triangles share an edge; bond them together. checktri.Lprev(ref checkleft); tri.Bond(ref checkleft); } // Find the next triangle in the stack. index--; nexttri = vertexarray[aroundvertex][index]; checktri = nexttri; } while (checktri.triangle != Mesh.dummytri); } } i++; } // Prepare to count the boundary edges. hullsize = 0; if (mesh.behavior.Poly) { // Read the segments from the .poly file, and link them // to their neighboring triangles. boundmarker = 0; i = 0; foreach (var item in mesh.subsegs.Values) { subseg.seg = item; end[0] = input.segments[i].P0; end[1] = input.segments[i].P1; boundmarker = input.segments[i].Boundary; for (int j = 0; j < 2; j++) { if ((end[j] < 0) || (end[j] >= mesh.invertices)) { SimpleLog.Instance.Error("Segment has an invalid vertex index.", "MeshReader.Reconstruct()"); throw new Exception("Segment has an invalid vertex index."); } } // set the subsegment's vertices. subseg.orient = 0; segmentorg = mesh.vertices[end[0]]; segmentdest = mesh.vertices[end[1]]; subseg.SetOrg(segmentorg); subseg.SetDest(segmentdest); subseg.SetSegOrg(segmentorg); subseg.SetSegDest(segmentdest); subseg.seg.boundary = boundmarker; // Try linking the subsegment to triangles that share these vertices. for (subseg.orient = 0; subseg.orient < 2; subseg.orient++) { // Take the number for the destination of subsegloop. aroundvertex = end[1 - subseg.orient]; int index = vertexarray[aroundvertex].Count - 1; // Look for triangles having this vertex. prevlink = vertexarray[aroundvertex][index]; nexttri = vertexarray[aroundvertex][index]; checktri = nexttri; shorg = subseg.Org(); notfound = true; // Look for triangles having this edge. Note that I'm only // comparing each triangle's destination with the subsegment; // each triangle's apex is handled through a different vertex. // Because each triangle appears on three vertices' lists, each // occurrence of a triangle on a list can (and does) represent // an edge. In this way, most edges are represented twice, and // every triangle-subsegment bond is represented once. while (notfound && (checktri.triangle != Mesh.dummytri)) { checkdest = checktri.Dest(); if (shorg == checkdest) { // We have a match. Remove this triangle from the list. //prevlink = vertexarray[aroundvertex][index]; vertexarray[aroundvertex].Remove(prevlink); // Bond the subsegment to the triangle. checktri.SegBond(ref subseg); // Check if this is a boundary edge. checktri.Sym(ref checkneighbor); if (checkneighbor.triangle == Mesh.dummytri) { // The next line doesn't insert a subsegment (because there's // already one there), but it sets the boundary markers of // the existing subsegment and its vertices. mesh.InsertSubseg(ref checktri, 1); hullsize++; } notfound = false; } index--; // Find the next triangle in the stack. prevlink = vertexarray[aroundvertex][index]; nexttri = vertexarray[aroundvertex][index]; checktri = nexttri; } } i++; } } // Mark the remaining edges as not being attached to any subsegment. // Also, count the (yet uncounted) boundary edges. for (i = 0; i < mesh.vertices.Count; i++) { // Search the stack of triangles adjacent to a vertex. int index = vertexarray[i].Count - 1; nexttri = vertexarray[i][index]; checktri = nexttri; while (checktri.triangle != Mesh.dummytri) { // Find the next triangle in the stack before this // information gets overwritten. index--; nexttri = vertexarray[i][index]; // No adjacent subsegment. (This overwrites the stack info.) checktri.SegDissolve(); checktri.Sym(ref checkneighbor); if (checkneighbor.triangle == Mesh.dummytri) { mesh.InsertSubseg(ref checktri, 1); hullsize++; } checktri = nexttri; } } return(hullsize); }
/// <summary> /// Enforce the Delaunay condition at an edge, fanning out recursively from /// an existing vertex. Pay special attention to stacking inverted triangles. /// </summary> /// <param name="fixuptri"></param> /// <param name="leftside"> /// Indicates whether or not fixuptri is to the left of /// the segment being inserted. (Imagine that the segment is pointing up from /// endpoint1 to endpoint2.) /// </param> /// <remarks> /// This is a support routine for inserting segments into a constrained /// Delaunay triangulation. /// The origin of fixuptri is treated as if it has just been inserted, and /// the local Delaunay condition needs to be enforced. It is only enforced /// in one sector, however, that being the angular range defined by /// fixuptri. /// This routine also needs to make decisions regarding the "stacking" of /// triangles. (Read the description of ConstrainedEdge() below before /// reading on here, so you understand the algorithm.) If the position of /// the new vertex (the origin of fixuptri) indicates that the vertex before /// it on the polygon is a reflex vertex, then "stack" the triangle by /// doing nothing. (fixuptri is an inverted triangle, which is how stacked /// triangles are identified.) /// Otherwise, check whether the vertex before that was a reflex vertex. /// If so, perform an edge flip, thereby eliminating an inverted triangle /// (popping it off the stack). The edge flip may result in the creation /// of a new inverted triangle, depending on whether or not the new vertex /// is visible to the vertex three edges behind on the polygon. /// If neither of the two vertices behind the new vertex are reflex /// vertices, fixuptri and fartri, the triangle opposite it, are not /// inverted; hence, ensure that the edge between them is locally Delaunay. /// </remarks> private void DelaunayFixup(ref Otri fixuptri, bool leftside) { Otri neartri = default(Otri); Otri fartri = default(Otri); Osub faredge = default(Osub); Vertex nearvertex, leftvertex, rightvertex, farvertex; fixuptri.Lnext(ref neartri); neartri.Sym(ref fartri); // Check if the edge opposite the origin of fixuptri can be flipped. if (fartri.tri.Id == Mesh.DUMMY) { return; } neartri.Pivot(ref faredge); if (faredge.seg.hash != Mesh.DUMMY) { return; } // Find all the relevant vertices. nearvertex = neartri.Apex(); leftvertex = neartri.Org(); rightvertex = neartri.Dest(); farvertex = fartri.Apex(); // Check whether the previous polygon vertex is a reflex vertex. if (leftside) { if (RobustPredicates.CounterClockwise(nearvertex, leftvertex, farvertex) <= 0.0) { // leftvertex is a reflex vertex too. Nothing can // be done until a convex section is found. return; } } else { if (RobustPredicates.CounterClockwise(farvertex, rightvertex, nearvertex) <= 0.0) { // rightvertex is a reflex vertex too. Nothing can // be done until a convex section is found. return; } } if (RobustPredicates.CounterClockwise(rightvertex, leftvertex, farvertex) > 0.0) { // fartri is not an inverted triangle, and farvertex is not a reflex // vertex. As there are no reflex vertices, fixuptri isn't an // inverted triangle, either. Hence, test the edge between the // triangles to ensure it is locally Delaunay. if (RobustPredicates.InCircle(leftvertex, farvertex, rightvertex, nearvertex) <= 0.0) { return; } // Not locally Delaunay; go on to an edge flip. } // else fartri is inverted; remove it from the stack by flipping. mesh.Flip(ref neartri); fixuptri.Lprev(); // Restore the origin of fixuptri after the flip. // Recursively process the two triangles that result from the flip. DelaunayFixup(ref fixuptri, leftside); DelaunayFixup(ref fartri, leftside); }
/// <summary> /// Construct Voronoi region for given vertex. /// </summary> /// <param name="vertex"></param> /// <returns>The circumcenter indices which make up the cell.</returns> private void ConstructVoronoiRegion(Vertex vertex) { VoronoiRegion region = new VoronoiRegion(vertex); regions.Add(region); List <Point> vpoints = new List <Point>(); Otri f = default(Otri); Otri f_init = default(Otri); Otri f_next = default(Otri); Otri f_prev = default(Otri); Osub sub = default(Osub); // Call f_init a triangle incident to x vertex.tri.Copy(ref f_init); f_init.Copy(ref f); f_init.Onext(ref f_next); // Check if f_init lies on the boundary of the triangulation. if (f_next.triangle == Mesh.dummytri) { f_init.Oprev(ref f_prev); if (f_prev.triangle != Mesh.dummytri) { f_init.Copy(ref f_next); // Move one triangle clockwise f_init.OprevSelf(); f_init.Copy(ref f); } } // Go counterclockwise until we reach the border or the initial triangle. while (f_next.triangle != Mesh.dummytri) { // Add circumcenter of current triangle vpoints.Add(points[f.triangle.id]); if (f_next.Equal(f_init)) { // Voronoi cell is complete (bounded case). region.Add(vpoints); return; } f_next.Copy(ref f); f_next.OnextSelf(); } // Voronoi cell is unbounded region.Bounded = false; Vertex torg, tdest, tapex, intersection; int sid, n = mesh.triangles.Count; // Find the boundary segment id. f.Lprev(ref f_next); f_next.SegPivot(ref sub); sid = sub.seg.hash; // Last valid f lies at the boundary. Add the circumcenter. vpoints.Add(points[f.triangle.id]); // Check if the intersection with the bounding box has already been computed. if (rayPoints.ContainsKey(sid)) { vpoints.Add(rayPoints[sid]); } else { torg = f.Org(); tapex = f.Apex(); BoxRayIntersection(points[f.triangle.id], torg.y - tapex.y, tapex.x - torg.x, out intersection); // Set the correct id for the vertex intersection.id = n + rayIndex; points[n + rayIndex] = intersection; rayIndex++; vpoints.Add(intersection); rayPoints.Add(sid, intersection); } // Now walk from f_init clockwise till we reach the boundary. vpoints.Reverse(); f_init.Copy(ref f); f.Oprev(ref f_prev); while (f_prev.triangle != Mesh.dummytri) { vpoints.Add(points[f_prev.triangle.id]); f_prev.Copy(ref f); f_prev.OprevSelf(); } // Find the boundary segment id. f.SegPivot(ref sub); sid = sub.seg.hash; if (rayPoints.ContainsKey(sid)) { vpoints.Add(rayPoints[sid]); } else { // Intersection has not been computed yet. torg = f.Org(); tdest = f.Dest(); BoxRayIntersection(points[f.triangle.id], tdest.y - torg.y, torg.x - tdest.x, out intersection); // Set the correct id for the vertex intersection.id = n + rayIndex; points[n + rayIndex] = intersection; rayIndex++; vpoints.Add(intersection); rayPoints.Add(sid, intersection); } // Add the new points to the region (in counter-clockwise order) vpoints.Reverse(); region.Add(vpoints); }
/// <summary> /// Force a segment into a constrained Delaunay triangulation by deleting the /// triangles it intersects, and triangulating the polygons that form on each /// side of it. /// </summary> /// <param name="starttri"></param> /// <param name="endpoint2"></param> /// <param name="newmark"></param> /// <remarks> /// Generates a single subsegment connecting 'endpoint1' to 'endpoint2'. /// The triangle 'starttri' has 'endpoint1' as its origin. 'newmark' is the /// boundary marker of the segment. /// To insert a segment, every triangle whose interior intersects the /// segment is deleted. The union of these deleted triangles is a polygon /// (which is not necessarily monotone, but is close enough), which is /// divided into two polygons by the new segment. This routine's task is /// to generate the Delaunay triangulation of these two polygons. /// You might think of this routine's behavior as a two-step process. The /// first step is to walk from endpoint1 to endpoint2, flipping each edge /// encountered. This step creates a fan of edges connected to endpoint1, /// including the desired edge to endpoint2. The second step enforces the /// Delaunay condition on each side of the segment in an incremental manner: /// proceeding along the polygon from endpoint1 to endpoint2 (this is done /// independently on each side of the segment), each vertex is "enforced" /// as if it had just been inserted, but affecting only the previous /// vertices. The result is the same as if the vertices had been inserted /// in the order they appear on the polygon, so the result is Delaunay. /// In truth, ConstrainedEdge() interleaves these two steps. The procedure /// walks from endpoint1 to endpoint2, and each time an edge is encountered /// and flipped, the newly exposed vertex (at the far end of the flipped /// edge) is "enforced" upon the previously flipped edges, usually affecting /// only one side of the polygon (depending upon which side of the segment /// the vertex falls on). /// The algorithm is complicated by the need to handle polygons that are not /// convex. Although the polygon is not necessarily monotone, it can be /// triangulated in a manner similar to the stack-based algorithms for /// monotone polygons. For each reflex vertex (local concavity) of the /// polygon, there will be an inverted triangle formed by one of the edge /// flips. (An inverted triangle is one with negative area - that is, its /// vertices are arranged in clockwise order - and is best thought of as a /// wrinkle in the fabric of the mesh.) Each inverted triangle can be /// thought of as a reflex vertex pushed on the stack, waiting to be fixed /// later. /// A reflex vertex is popped from the stack when a vertex is inserted that /// is visible to the reflex vertex. (However, if the vertex behind the /// reflex vertex is not visible to the reflex vertex, a new inverted /// triangle will take its place on the stack.) These details are handled /// by the DelaunayFixup() routine above. /// </remarks> private void ConstrainedEdge(ref Otri starttri, Vertex endpoint2, ushort newmark) { Otri fixuptri = default(Otri), fixuptri2 = default(Otri); Osub crosssubseg = default(Osub); Vertex endpoint1; Vertex farvertex; double area; bool collision; bool done; endpoint1 = starttri.Org(); starttri.Lnext(ref fixuptri); mesh.Flip(ref fixuptri); // 'collision' indicates whether we have found a vertex directly // between endpoint1 and endpoint2. collision = false; done = false; do { farvertex = fixuptri.Org(); // 'farvertex' is the extreme point of the polygon we are "digging" // to get from endpoint1 to endpoint2. if ((farvertex.X == endpoint2.X) && (farvertex.Y == endpoint2.Y)) { fixuptri.Oprev(ref fixuptri2); // Enforce the Delaunay condition around endpoint2. DelaunayFixup(ref fixuptri, false); DelaunayFixup(ref fixuptri2, true); done = true; } else { // Check whether farvertex is to the left or right of the segment being // inserted, to decide which edge of fixuptri to dig through next. area = RobustPredicates.CounterClockwise(endpoint1, endpoint2, farvertex); if (area == 0.0) { // We've collided with a vertex between endpoint1 and endpoint2. collision = true; fixuptri.Oprev(ref fixuptri2); // Enforce the Delaunay condition around farvertex. DelaunayFixup(ref fixuptri, false); DelaunayFixup(ref fixuptri2, true); done = true; } else { if (area > 0.0) { // farvertex is to the left of the segment. fixuptri.Oprev(ref fixuptri2); // Enforce the Delaunay condition around farvertex, on the // left side of the segment only. DelaunayFixup(ref fixuptri2, true); // Flip the edge that crosses the segment. After the edge is // flipped, one of its endpoints is the fan vertex, and the // destination of fixuptri is the fan vertex. fixuptri.Lprev(); } else { // farvertex is to the right of the segment. DelaunayFixup(ref fixuptri, false); // Flip the edge that crosses the segment. After the edge is // flipped, one of its endpoints is the fan vertex, and the // destination of fixuptri is the fan vertex. fixuptri.Oprev(); } // Check for two intersecting segments. fixuptri.Pivot(ref crosssubseg); if (crosssubseg.seg.hash == Mesh.DUMMY) { mesh.Flip(ref fixuptri); // May create inverted triangle at left. } else { // We've collided with a segment between endpoint1 and endpoint2. collision = true; // Insert a vertex at the intersection. SegmentIntersection(ref fixuptri, ref crosssubseg, endpoint2); done = true; } } } } while (!done); // Insert a subsegment to make the segment permanent. mesh.InsertSubseg(ref fixuptri, newmark); // If there was a collision with an interceding vertex, install another // segment connecting that vertex with endpoint2. if (collision) { // Insert the remainder of the segment. if (!ScoutSegment(ref fixuptri, endpoint2, newmark)) { ConstrainedEdge(ref fixuptri, endpoint2, newmark); } } }
/// <summary> /// Recursively form a Delaunay triangulation by the divide-and-conquer method. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="axis"></param> /// <param name="farleft"></param> /// <param name="farright"></param> /// <remarks> /// Recursively breaks down the problem into smaller pieces, which are /// knitted together by mergehulls(). The base cases (problems of two or /// three vertices) are handled specially here. /// /// On completion, 'farleft' and 'farright' are bounding triangles such that /// the origin of 'farleft' is the leftmost vertex (breaking ties by /// choosing the highest leftmost vertex), and the destination of /// 'farright' is the rightmost vertex (breaking ties by choosing the /// lowest rightmost vertex). /// </remarks> void DivconqRecurse(int left, int right, int axis, ref Otri farleft, ref Otri farright) { Otri midtri = default(Otri); Otri tri1 = default(Otri); Otri tri2 = default(Otri); Otri tri3 = default(Otri); Otri innerleft = default(Otri), innerright = default(Otri); double area; int vertices = right - left + 1; int divider; if (vertices == 2) { // The triangulation of two vertices is an edge. An edge is // represented by two bounding triangles. mesh.MakeTriangle(ref farleft); farleft.SetOrg(sortarray[left]); farleft.SetDest(sortarray[left + 1]); // The apex is intentionally left NULL. mesh.MakeTriangle(ref farright); farright.SetOrg(sortarray[left + 1]); farright.SetDest(sortarray[left]); // The apex is intentionally left NULL. farleft.Bond(ref farright); farleft.LprevSelf(); farright.LnextSelf(); farleft.Bond(ref farright); farleft.LprevSelf(); farright.LnextSelf(); farleft.Bond(ref farright); // Ensure that the origin of 'farleft' is sortarray[0]. farright.Lprev(ref farleft); return; } else if (vertices == 3) { // The triangulation of three vertices is either a triangle (with // three bounding triangles) or two edges (with four bounding // triangles). In either case, four triangles are created. mesh.MakeTriangle(ref midtri); mesh.MakeTriangle(ref tri1); mesh.MakeTriangle(ref tri2); mesh.MakeTriangle(ref tri3); area = Primitives.CounterClockwise(sortarray[left], sortarray[left + 1], sortarray[left + 2]); if (area == 0.0) { // Three collinear vertices; the triangulation is two edges. midtri.SetOrg(sortarray[left]); midtri.SetDest(sortarray[left + 1]); tri1.SetOrg(sortarray[left + 1]); tri1.SetDest(sortarray[left]); tri2.SetOrg(sortarray[left + 2]); tri2.SetDest(sortarray[left + 1]); tri3.SetOrg(sortarray[left + 1]); tri3.SetDest(sortarray[left + 2]); // All apices are intentionally left NULL. midtri.Bond(ref tri1); tri2.Bond(ref tri3); midtri.LnextSelf(); tri1.LprevSelf(); tri2.LnextSelf(); tri3.LprevSelf(); midtri.Bond(ref tri3); tri1.Bond(ref tri2); midtri.LnextSelf(); tri1.LprevSelf(); tri2.LnextSelf(); tri3.LprevSelf(); midtri.Bond(ref tri1); tri2.Bond(ref tri3); // Ensure that the origin of 'farleft' is sortarray[0]. tri1.Copy(ref farleft); // Ensure that the destination of 'farright' is sortarray[2]. tri2.Copy(ref farright); } else { // The three vertices are not collinear; the triangulation is one // triangle, namely 'midtri'. midtri.SetOrg(sortarray[left]); tri1.SetDest(sortarray[left]); tri3.SetOrg(sortarray[left]); // Apices of tri1, tri2, and tri3 are left NULL. if (area > 0.0) { // The vertices are in counterclockwise order. midtri.SetDest(sortarray[left + 1]); tri1.SetOrg(sortarray[left + 1]); tri2.SetDest(sortarray[left + 1]); midtri.SetApex(sortarray[left + 2]); tri2.SetOrg(sortarray[left + 2]); tri3.SetDest(sortarray[left + 2]); } else { // The vertices are in clockwise order. midtri.SetDest(sortarray[left + 2]); tri1.SetOrg(sortarray[left + 2]); tri2.SetDest(sortarray[left + 2]); midtri.SetApex(sortarray[left + 1]); tri2.SetOrg(sortarray[left + 1]); tri3.SetDest(sortarray[left + 1]); } // The topology does not depend on how the vertices are ordered. midtri.Bond(ref tri1); midtri.LnextSelf(); midtri.Bond(ref tri2); midtri.LnextSelf(); midtri.Bond(ref tri3); tri1.LprevSelf(); tri2.LnextSelf(); tri1.Bond(ref tri2); tri1.LprevSelf(); tri3.LprevSelf(); tri1.Bond(ref tri3); tri2.LnextSelf(); tri3.LprevSelf(); tri2.Bond(ref tri3); // Ensure that the origin of 'farleft' is sortarray[0]. tri1.Copy(ref farleft); // Ensure that the destination of 'farright' is sortarray[2]. if (area > 0.0) { tri2.Copy(ref farright); } else { farleft.Lnext(ref farright); } } return; } else { // Split the vertices in half. divider = vertices >> 1; // Recursively triangulate each half. DivconqRecurse(left, left + divider - 1, 1 - axis, ref farleft, ref innerleft); //DebugWriter.Session.Write(mesh, true); DivconqRecurse(left + divider, right, 1 - axis, ref innerright, ref farright); //DebugWriter.Session.Write(mesh, true); // Merge the two triangulations into one. MergeHulls(ref farleft, ref innerleft, ref innerright, ref farright, axis); //DebugWriter.Session.Write(mesh, true); } }
private void ConstructVoronoiRegion(Vertex vertex) { Vertex vertex1; Vertex vertex2; VoronoiRegion voronoiRegion = new VoronoiRegion(vertex); this.regions.Add(voronoiRegion); List <Point> points = new List <Point>(); Otri otri = new Otri(); Otri otri1 = new Otri(); Otri otri2 = new Otri(); Otri otri3 = new Otri(); Osub osub = new Osub(); vertex.tri.Copy(ref otri1); otri1.Copy(ref otri); otri1.Onext(ref otri2); if (otri2.triangle == Mesh.dummytri) { otri1.Oprev(ref otri3); if (otri3.triangle != Mesh.dummytri) { otri1.Copy(ref otri2); otri1.OprevSelf(); otri1.Copy(ref otri); } } while (otri2.triangle != Mesh.dummytri) { points.Add(this.points[otri.triangle.id]); if (otri2.Equal(otri1)) { voronoiRegion.Add(points); return; } otri2.Copy(ref otri); otri2.OnextSelf(); } voronoiRegion.Bounded = false; int count = this.mesh.triangles.Count; otri.Lprev(ref otri2); otri2.SegPivot(ref osub); int num = osub.seg.hash; points.Add(this.points[otri.triangle.id]); if (!this.rayPoints.ContainsKey(num)) { vertex1 = otri.Org(); Vertex vertex3 = otri.Apex(); this.BoxRayIntersection(this.points[otri.triangle.id], vertex1.y - vertex3.y, vertex3.x - vertex1.x, out vertex2); vertex2.id = count + this.rayIndex; this.points[count + this.rayIndex] = vertex2; this.rayIndex = this.rayIndex + 1; points.Add(vertex2); this.rayPoints.Add(num, vertex2); } else { points.Add(this.rayPoints[num]); } points.Reverse(); otri1.Copy(ref otri); otri.Oprev(ref otri3); while (otri3.triangle != Mesh.dummytri) { points.Add(this.points[otri3.triangle.id]); otri3.Copy(ref otri); otri3.OprevSelf(); } otri.SegPivot(ref osub); num = osub.seg.hash; if (!this.rayPoints.ContainsKey(num)) { vertex1 = otri.Org(); Vertex vertex4 = otri.Dest(); this.BoxRayIntersection(this.points[otri.triangle.id], vertex4.y - vertex1.y, vertex1.x - vertex4.x, out vertex2); vertex2.id = count + this.rayIndex; this.points[count + this.rayIndex] = vertex2; this.rayIndex = this.rayIndex + 1; points.Add(vertex2); this.rayPoints.Add(num, vertex2); } else { points.Add(this.rayPoints[num]); } points.Reverse(); voronoiRegion.Add(points); }