1 #define ANSI_DECLARATORS
2 /*****************************************************************************/
4 /* 888888888 ,o, / 888 */
5 /* 888 88o88o " o8888o 88o8888o o88888o 888 o88888o */
6 /* 888 888 888 88b 888 888 888 888 888 d888 88b */
7 /* 888 888 888 o88^o888 888 888 "88888" 888 8888oo888 */
8 /* 888 888 888 C888 888 888 888 / 888 q888 */
9 /* 888 888 888 "88o^888 888 888 Cb 888 "88oooo" */
12 /* A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator. */
19 /* Jonathan Richard Shewchuk */
20 /* School of Computer Science */
21 /* Carnegie Mellon University */
22 /* 5000 Forbes Avenue */
23 /* Pittsburgh, Pennsylvania 15213-3891 */
26 /* This program may be freely redistributed under the condition that the */
27 /* copyright notices (including this entire header and the copyright */
28 /* notice printed when the `-h' switch is selected) are not removed, and */
29 /* no compensation is received. Private, research, and institutional */
30 /* use is free. You may distribute modified versions of this code UNDER */
31 /* THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE */
32 /* SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE */
33 /* AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR */
34 /* NOTICE IS GIVEN OF THE MODIFICATIONS. Distribution of this code as */
35 /* part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT */
36 /* WITH THE AUTHOR. (If you are not directly supplying this code to a */
37 /* customer, and you are instead telling them how they can obtain it for */
38 /* free, then you are not required to make any arrangement with me.) */
40 /* Hypertext instructions for Triangle are available on the Web at */
42 /* http://www.cs.cmu.edu/~quake/triangle.html */
44 /* Some of the references listed below are marked [*]. These are available */
45 /* for downloading from the Web page */
47 /* http://www.cs.cmu.edu/~quake/triangle.research.html */
49 /* A paper discussing some aspects of Triangle is available. See Jonathan */
50 /* Richard Shewchuk, "Triangle: Engineering a 2D Quality Mesh Generator */
51 /* and Delaunay Triangulator," First Workshop on Applied Computational */
52 /* Geometry, ACM, May 1996. [*] */
54 /* Triangle was created as part of the Archimedes project in the School of */
55 /* Computer Science at Carnegie Mellon University. Archimedes is a */
56 /* system for compiling parallel finite element solvers. For further */
57 /* information, see Anja Feldmann, Omar Ghattas, John R. Gilbert, Gary L. */
58 /* Miller, David R. O'Hallaron, Eric J. Schwabe, Jonathan R. Shewchuk, */
59 /* and Shang-Hua Teng, "Automated Parallel Solution of Unstructured PDE */
60 /* Problems." To appear in Communications of the ACM, we hope. */
62 /* The quality mesh generation algorithm is due to Jim Ruppert, "A */
63 /* Delaunay Refinement Algorithm for Quality 2-Dimensional Mesh */
64 /* Generation," Journal of Algorithms 18(3):548-585, May 1995. [*] */
66 /* My implementation of the divide-and-conquer and incremental Delaunay */
67 /* triangulation algorithms follows closely the presentation of Guibas */
68 /* and Stolfi, even though I use a triangle-based data structure instead */
69 /* of their quad-edge data structure. (In fact, I originally implemented */
70 /* Triangle using the quad-edge data structure, but switching to a */
71 /* triangle-based data structure sped Triangle by a factor of two.) The */
72 /* mesh manipulation primitives and the two aforementioned Delaunay */
73 /* triangulation algorithms are described by Leonidas J. Guibas and Jorge */
74 /* Stolfi, "Primitives for the Manipulation of General Subdivisions and */
75 /* the Computation of Voronoi Diagrams," ACM Transactions on Graphics */
76 /* 4(2):74-123, April 1985. */
78 /* Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai */
79 /* Lee and Bruce J. Schachter, "Two Algorithms for Constructing the */
80 /* Delaunay Triangulation," International Journal of Computer and */
81 /* Information Science 9(3):219-242, 1980. The idea to improve the */
82 /* divide-and-conquer algorithm by alternating between vertical and */
83 /* horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and- */
84 /* Conquer Algorithm for Constructing Delaunay Triangulations," */
85 /* Algorithmica 2(2):137-151, 1987. */
87 /* The incremental insertion algorithm was first proposed by C. L. Lawson, */
88 /* "Software for C1 Surface Interpolation," in Mathematical Software III, */
89 /* John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977. */
90 /* For point location, I use the algorithm of Ernst P. Mucke, Isaac */
91 /* Saias, and Binhai Zhu, "Fast Randomized Point Location Without */
92 /* Preprocessing in Two- and Three-dimensional Delaunay Triangulations," */
93 /* Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
94 /* ACM, May 1996. [*] If I were to randomize the order of point */
95 /* insertion (I currently don't bother), their result combined with the */
96 /* result of Leonidas J. Guibas, Donald E. Knuth, and Micha Sharir, */
97 /* "Randomized Incremental Construction of Delaunay and Voronoi */
98 /* Diagrams," Algorithmica 7(4):381-413, 1992, would yield an expected */
99 /* O(n^{4/3}) bound on running time. */
101 /* The O(n log n) sweepline Delaunay triangulation algorithm is taken from */
102 /* Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams", */
103 /* Algorithmica 2(2):153-174, 1987. A random sample of edges on the */
104 /* boundary of the triangulation are maintained in a splay tree for the */
105 /* purpose of point location. Splay trees are described by Daniel */
106 /* Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
107 /* Trees," Journal of the ACM 32(3):652-686, July 1985. */
109 /* The algorithms for exact computation of the signs of determinants are */
110 /* described in Jonathan Richard Shewchuk, "Adaptive Precision Floating- */
111 /* Point Arithmetic and Fast Robust Geometric Predicates," Technical */
112 /* Report CMU-CS-96-140, School of Computer Science, Carnegie Mellon */
113 /* University, Pittsburgh, Pennsylvania, May 1996. [*] (Submitted to */
114 /* Discrete & Computational Geometry.) An abbreviated version appears as */
115 /* Jonathan Richard Shewchuk, "Robust Adaptive Floating-Point Geometric */
116 /* Predicates," Proceedings of the Twelfth Annual Symposium on Computa- */
117 /* tional Geometry, ACM, May 1996. [*] Many of the ideas for my exact */
118 /* arithmetic routines originate with Douglas M. Priest, "Algorithms for */
119 /* Arbitrary Precision Floating Point Arithmetic," Tenth Symposium on */
120 /* Computer Arithmetic, 132-143, IEEE Computer Society Press, 1991. [*] */
121 /* Many of the ideas for the correct evaluation of the signs of */
122 /* determinants are taken from Steven Fortune and Christopher J. Van Wyk, */
123 /* "Efficient Exact Arithmetic for Computational Geometry," Proceedings */
124 /* of the Ninth Annual Symposium on Computational Geometry, ACM, */
125 /* pp. 163-172, May 1993, and from Steven Fortune, "Numerical Stability */
126 /* of Algorithms for 2D Delaunay Triangulations," International Journal */
127 /* of Computational Geometry & Applications 5(1-2):193-213, March-June */
130 /* For definitions of and results involving Delaunay triangulations, */
131 /* constrained and conforming versions thereof, and other aspects of */
132 /* triangular mesh generation, see the excellent survey by Marshall Bern */
133 /* and David Eppstein, "Mesh Generation and Optimal Triangulation," in */
134 /* Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang, */
135 /* editors, World Scientific, Singapore, pp. 23-90, 1992. */
137 /* The time for incrementally adding PSLG (planar straight line graph) */
138 /* segments to create a constrained Delaunay triangulation is probably */
139 /* O(n^2) per segment in the worst case and O(n) per edge in the common */
140 /* case, where n is the number of triangles that intersect the segment */
141 /* before it is inserted. This doesn't count point location, which can */
142 /* be much more expensive. (This note does not apply to conforming */
143 /* Delaunay triangulations, for which a different method is used to */
144 /* insert segments.) */
146 /* The time for adding segments to a conforming Delaunay triangulation is */
147 /* not clear, but does not depend upon n alone. In some cases, very */
148 /* small features (like a point lying next to a segment) can cause a */
149 /* single segment to be split an arbitrary number of times. Of course, */
150 /* floating-point precision is a practical barrier to how much this can */
153 /* The time for deleting a point from a Delaunay triangulation is O(n^2) in */
154 /* the worst case and O(n) in the common case, where n is the degree of */
155 /* the point being deleted. I could improve this to expected O(n) time */
156 /* by "inserting" the neighboring vertices in random order, but n is */
157 /* usually quite small, so it's not worth the bother. (The O(n) time */
158 /* for random insertion follows from L. Paul Chew, "Building Voronoi */
159 /* Diagrams for Convex Polygons in Linear Expected Time," Technical */
160 /* Report PCS-TR90-147, Department of Mathematics and Computer Science, */
161 /* Dartmouth College, 1990. */
163 /* Ruppert's Delaunay refinement algorithm typically generates triangles */
164 /* at a linear rate (constant time per triangle) after the initial */
165 /* triangulation is formed. There may be pathological cases where more */
166 /* time is required, but these never arise in practice. */
168 /* The segment intersection formulae are straightforward. If you want to */
169 /* see them derived, see Franklin Antonio. "Faster Line Segment */
170 /* Intersection." In Graphics Gems III (David Kirk, editor), pp. 199- */
171 /* 202. Academic Press, Boston, 1992. */
173 /* If you make any improvements to this code, please please please let me */
174 /* know, so that I may obtain the improvements. Even if you don't change */
175 /* the code, I'd still love to hear what it's being used for. */
177 /* Disclaimer: Neither I nor Carnegie Mellon warrant this code in any way */
178 /* whatsoever. This code is provided "as-is". Use at your own risk. */
180 /*****************************************************************************/
182 /* For single precision (which will save some memory and reduce paging), */
183 /* define the symbol SINGLE by using the -DSINGLE compiler switch or by */
184 /* writing "#define SINGLE" below. */
186 /* For double precision (which will allow you to refine meshes to a smaller */
187 /* edge length), leave SINGLE undefined. */
189 /* Double precision uses more memory, but improves the resolution of the */
190 /* meshes you can generate with Triangle. It also reduces the likelihood */
191 /* of a floating exception due to overflow. Finally, it is much faster */
192 /* than single precision on 64-bit architectures like the DEC Alpha. I */
193 /* recommend double precision unless you want to generate a mesh for which */
194 /* you do not have enough memory. */
200 #else /* not SINGLE */
202 #endif /* not SINGLE */
204 /* If yours is not a Unix system, define the NO_TIMER compiler switch to */
205 /* remove the Unix-specific timing code. */
209 /* To insert lots of self-checks for internal errors, define the SELF_CHECK */
210 /* symbol. This will slow down the program significantly. It is best to */
211 /* define the symbol using the -DSELF_CHECK compiler switch, but you could */
212 /* write "#define SELF_CHECK" below. If you are modifying this code, I */
213 /* recommend you turn self-checks on. */
215 /* #define SELF_CHECK */
217 /* To compile Triangle as a callable object library (triangle.o), define the */
218 /* TRILIBRARY symbol. Read the file triangle.h for details on how to call */
219 /* the procedure triangulate() that results. */
223 /* It is possible to generate a smaller version of Triangle using one or */
224 /* both of the following symbols. Define the REDUCED symbol to eliminate */
225 /* all features that are primarily of research interest; specifically, the */
226 /* -i, -F, -s, and -C switches. Define the CDT_ONLY symbol to eliminate */
227 /* all meshing algorithms above and beyond constrained Delaunay */
228 /* triangulation; specifically, the -r, -q, -a, -S, and -s switches. */
229 /* These reductions are most likely to be useful when generating an object */
230 /* library (triangle.o) by defining the TRILIBRARY symbol. */
235 /* On some machines, the exact arithmetic routines might be defeated by the */
236 /* use of internal extended precision floating-point registers. Sometimes */
237 /* this problem can be fixed by defining certain values to be volatile, */
238 /* thus forcing them to be stored to memory and rounded off. This isn't */
239 /* a great solution, though, as it slows Triangle down. */
241 /* To try this out, write "#define INEXACT volatile" below. Normally, */
242 /* however, INEXACT should be defined to be nothing. ("#define INEXACT".) */
244 #define INEXACT /* Nothing */
245 /* #define INEXACT volatile */
247 /* Maximum number of characters in a file name (including the null). */
249 #define FILENAMESIZE 512
251 /* Maximum number of characters in a line read from a file (including the */
254 #define INPUTLINESIZE 512
256 /* For efficiency, a variety of data structures are allocated in bulk. The */
257 /* following constants determine how many of each structure is allocated */
260 #define TRIPERBLOCK 4092 /* Number of triangles allocated at once. */
261 #define SHELLEPERBLOCK 508 /* Number of shell edges allocated at once. */
262 #define POINTPERBLOCK 4092 /* Number of points allocated at once. */
263 #define VIRUSPERBLOCK 1020 /* Number of virus triangles allocated at once. */
264 /* Number of encroached segments allocated at once. */
265 #define BADSEGMENTPERBLOCK 252
266 /* Number of skinny triangles allocated at once. */
267 #define BADTRIPERBLOCK 4092
268 /* Number of splay tree nodes allocated at once. */
269 #define SPLAYNODEPERBLOCK 508
271 /* The point marker DEADPOINT is an arbitrary number chosen large enough to */
272 /* (hopefully) not conflict with user boundary markers. Make sure that it */
273 /* is small enough to fit into your machine's integer size. */
275 #define DEADPOINT -1073741824
277 /* The next line is used to outsmart some very stupid compilers. If your */
278 /* compiler is smarter, feel free to replace the "int" with "void". */
279 /* Not that it matters. */
283 /* Two constants for algorithms based on random sampling. Both constants */
284 /* have been chosen empirically to optimize their respective algorithms. */
286 /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide */
287 /* how large a random sample of triangles to inspect. */
288 #define SAMPLEFACTOR 11
289 /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
290 /* of boundary edges should be maintained in the splay tree for point */
291 /* location on the front. */
292 #define SAMPLERATE 10
294 /* A number that speaks for itself, every kissable digit. */
296 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
300 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
302 /* And here's one for those of you who are intimidated by math. */
304 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
310 #include <sys/time.h>
311 #endif /* NO_TIMER */
313 #include "triangle.h"
314 #endif /* TRILIBRARY */
316 /* The following obscenity seems to be necessary to ensure that this program */
317 /* will port to Dec Alphas running OSF/1, because their stdio.h file commits */
318 /* the unpardonable sin of including stdlib.h. Hence, malloc(), free(), and */
319 /* exit() may or may not already be defined at this point. I declare these */
320 /* functions explicitly because some non-ANSI C compilers lack stdlib.h. */
323 extern void *malloc();
326 extern double strtod();
327 extern long strtol();
328 #endif /* _STDLIB_H_ */
330 /* A few forward declarations. */
336 #endif /* not TRILIBRARY */
338 /* Labels that signify whether a record consists primarily of pointers or of */
339 /* floating-point words. Used to make decisions about data alignment. */
341 enum wordtype {POINTER, FLOATINGPOINT};
343 /* Labels that signify the result of point location. The result of a */
344 /* search indicates that the point falls in the interior of a triangle, on */
345 /* an edge, on a vertex, or outside the mesh. */
347 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
349 /* Labels that signify the result of site insertion. The result indicates */
350 /* that the point was inserted with complete success, was inserted but */
351 /* encroaches on a segment, was not inserted because it lies on a segment, */
352 /* or was not inserted because another point occupies the same location. */
354 enum insertsiteresult {SUCCESSFULPOINT, ENCROACHINGPOINT, VIOLATINGPOINT,
357 /* Labels that signify the result of direction finding. The result */
358 /* indicates that a segment connecting the two query points falls within */
359 /* the direction triangle, along the left edge of the direction triangle, */
360 /* or along the right edge of the direction triangle. */
362 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
364 /* Labels that signify the result of the circumcenter computation routine. */
365 /* The return value indicates which edge of the triangle is shortest. */
367 enum circumcenterresult {OPPOSITEORG, OPPOSITEDEST, OPPOSITEAPEX};
369 /*****************************************************************************/
371 /* The basic mesh data structures */
373 /* There are three: points, triangles, and shell edges (abbreviated */
374 /* `shelle'). These three data structures, linked by pointers, comprise */
375 /* the mesh. A point simply represents a point in space and its properties.*/
376 /* A triangle is a triangle. A shell edge is a special data structure used */
377 /* to represent impenetrable segments in the mesh (including the outer */
378 /* boundary, boundaries of holes, and internal boundaries separating two */
379 /* triangulated regions). Shell edges represent boundaries defined by the */
380 /* user that triangles may not lie across. */
382 /* A triangle consists of a list of three vertices, a list of three */
383 /* adjoining triangles, a list of three adjoining shell edges (when shell */
384 /* edges are used), an arbitrary number of optional user-defined floating- */
385 /* point attributes, and an optional area constraint. The latter is an */
386 /* upper bound on the permissible area of each triangle in a region, used */
387 /* for mesh refinement. */
389 /* For a triangle on a boundary of the mesh, some or all of the neighboring */
390 /* triangles may not be present. For a triangle in the interior of the */
391 /* mesh, often no neighboring shell edges are present. Such absent */
392 /* triangles and shell edges are never represented by NULL pointers; they */
393 /* are represented by two special records: `dummytri', the triangle that */
394 /* fills "outer space", and `dummysh', the omnipresent shell edge. */
395 /* `dummytri' and `dummysh' are used for several reasons; for instance, */
396 /* they can be dereferenced and their contents examined without causing the */
397 /* memory protection exception that would occur if NULL were dereferenced. */
399 /* However, it is important to understand that a triangle includes other */
400 /* information as well. The pointers to adjoining vertices, triangles, and */
401 /* shell edges are ordered in a way that indicates their geometric relation */
402 /* to each other. Furthermore, each of these pointers contains orientation */
403 /* information. Each pointer to an adjoining triangle indicates which face */
404 /* of that triangle is contacted. Similarly, each pointer to an adjoining */
405 /* shell edge indicates which side of that shell edge is contacted, and how */
406 /* the shell edge is oriented relative to the triangle. */
408 /* Shell edges are found abutting edges of triangles; either sandwiched */
409 /* between two triangles, or resting against one triangle on an exterior */
410 /* boundary or hole boundary. */
412 /* A shell edge consists of a list of two vertices, a list of two */
413 /* adjoining shell edges, and a list of two adjoining triangles. One of */
414 /* the two adjoining triangles may not be present (though there should */
415 /* always be one), and neighboring shell edges might not be present. */
416 /* Shell edges also store a user-defined integer "boundary marker". */
417 /* Typically, this integer is used to indicate what sort of boundary */
418 /* conditions are to be applied at that location in a finite element */
421 /* Like triangles, shell edges maintain information about the relative */
422 /* orientation of neighboring objects. */
424 /* Points are relatively simple. A point is a list of floating point */
425 /* numbers, starting with the x, and y coordinates, followed by an */
426 /* arbitrary number of optional user-defined floating-point attributes, */
427 /* followed by an integer boundary marker. During the segment insertion */
428 /* phase, there is also a pointer from each point to a triangle that may */
429 /* contain it. Each pointer is not always correct, but when one is, it */
430 /* speeds up segment insertion. These pointers are assigned values once */
431 /* at the beginning of the segment insertion phase, and are not used or */
432 /* updated at any other time. Edge swapping during segment insertion will */
433 /* render some of them incorrect. Hence, don't rely upon them for */
434 /* anything. For the most part, points do not have any information about */
435 /* what triangles or shell edges they are linked to. */
437 /*****************************************************************************/
439 /*****************************************************************************/
443 /* The oriented triangle (`triedge') and oriented shell edge (`edge') data */
444 /* structures defined below do not themselves store any part of the mesh. */
445 /* The mesh itself is made of `triangle's, `shelle's, and `point's. */
447 /* Oriented triangles and oriented shell edges will usually be referred to */
448 /* as "handles". A handle is essentially a pointer into the mesh; it */
449 /* allows you to "hold" one particular part of the mesh. Handles are used */
450 /* to specify the regions in which one is traversing and modifying the mesh.*/
451 /* A single `triangle' may be held by many handles, or none at all. (The */
452 /* latter case is not a memory leak, because the triangle is still */
453 /* connected to other triangles in the mesh.) */
455 /* A `triedge' is a handle that holds a triangle. It holds a specific side */
456 /* of the triangle. An `edge' is a handle that holds a shell edge. It */
457 /* holds either the left or right side of the edge. */
459 /* Navigation about the mesh is accomplished through a set of mesh */
460 /* manipulation primitives, further below. Many of these primitives take */
461 /* a handle and produce a new handle that holds the mesh near the first */
462 /* handle. Other primitives take two handles and glue the corresponding */
463 /* parts of the mesh together. The exact position of the handles is */
464 /* important. For instance, when two triangles are glued together by the */
465 /* bond() primitive, they are glued by the sides on which the handles lie. */
467 /* Because points have no information about which triangles they are */
468 /* attached to, I commonly represent a point by use of a handle whose */
469 /* origin is the point. A single handle can simultaneously represent a */
470 /* triangle, an edge, and a point. */
472 /*****************************************************************************/
474 /* The triangle data structure. Each triangle contains three pointers to */
475 /* adjoining triangles, plus three pointers to vertex points, plus three */
476 /* pointers to shell edges (defined below; these pointers are usually */
477 /* `dummysh'). It may or may not also contain user-defined attributes */
478 /* and/or a floating-point "area constraint". It may also contain extra */
479 /* pointers for nodes, when the user asks for high-order elements. */
480 /* Because the size and structure of a `triangle' is not decided until */
481 /* runtime, I haven't simply defined the type `triangle' to be a struct. */
483 typedef REAL **triangle; /* Really: typedef triangle *triangle */
485 /* An oriented triangle: includes a pointer to a triangle and orientation. */
486 /* The orientation denotes an edge of the triangle. Hence, there are */
487 /* three possible orientations. By convention, each edge is always */
488 /* directed to point counterclockwise about the corresponding triangle. */
492 int orient; /* Ranges from 0 to 2. */
495 /* The shell data structure. Each shell edge contains two pointers to */
496 /* adjoining shell edges, plus two pointers to vertex points, plus two */
497 /* pointers to adjoining triangles, plus one shell marker. */
499 typedef REAL **shelle; /* Really: typedef shelle *shelle */
501 /* An oriented shell edge: includes a pointer to a shell edge and an */
502 /* orientation. The orientation denotes a side of the edge. Hence, there */
503 /* are two possible orientations. By convention, the edge is always */
504 /* directed so that the "side" denoted is the right side of the edge. */
508 int shorient; /* Ranges from 0 to 1. */
511 /* The point data structure. Each point is actually an array of REALs. */
512 /* The number of REALs is unknown until runtime. An integer boundary */
513 /* marker, and sometimes a pointer to a triangle, is appended after the */
518 /* A queue used to store encroached segments. Each segment's vertices are */
519 /* stored so that one can check whether a segment is still the same. */
522 struct edge encsegment; /* An encroached segment. */
523 point segorg, segdest; /* The two vertices. */
524 struct badsegment *nextsegment; /* Pointer to next encroached segment. */
527 /* A queue used to store bad triangles. The key is the square of the cosine */
528 /* of the smallest angle of the triangle. Each triangle's vertices are */
529 /* stored so that one can check whether a triangle is still the same. */
532 struct triedge badfacetri; /* A bad triangle. */
533 REAL key; /* cos^2 of smallest (apical) angle. */
534 point faceorg, facedest, faceapex; /* The three vertices. */
535 struct badface *nextface; /* Pointer to next bad triangle. */
538 /* A node in a heap used to store events for the sweepline Delaunay */
539 /* algorithm. Nodes do not point directly to their parents or children in */
540 /* the heap. Instead, each node knows its position in the heap, and can */
541 /* look up its parent and children in a separate array. The `eventptr' */
542 /* points either to a `point' or to a triangle (in encoded format, so that */
543 /* an orientation is included). In the latter case, the origin of the */
544 /* oriented triangle is the apex of a "circle event" of the sweepline */
545 /* algorithm. To distinguish site events from circle events, all circle */
546 /* events are given an invalid (smaller than `xmin') x-coordinate `xkey'. */
549 REAL xkey, ykey; /* Coordinates of the event. */
550 VOID *eventptr; /* Can be a point or the location of a circle event. */
551 int heapposition; /* Marks this event's position in the heap. */
554 /* A node in the splay tree. Each node holds an oriented ghost triangle */
555 /* that represents a boundary edge of the growing triangulation. When a */
556 /* circle event covers two boundary edges with a triangle, so that they */
557 /* are no longer boundary edges, those edges are not immediately deleted */
558 /* from the tree; rather, they are lazily deleted when they are next */
559 /* encountered. (Since only a random sample of boundary edges are kept */
560 /* in the tree, lazy deletion is faster.) `keydest' is used to verify */
561 /* that a triangle is still the same as when it entered the splay tree; if */
562 /* it has been rotated (due to a circle event), it no longer represents a */
563 /* boundary edge and should be deleted. */
566 struct triedge keyedge; /* Lprev of an edge on the front. */
567 point keydest; /* Used to verify that splay node is still live. */
568 struct splaynode *lchild, *rchild; /* Children in splay tree. */
571 /* A type used to allocate memory. firstblock is the first block of items. */
572 /* nowblock is the block from which items are currently being allocated. */
573 /* nextitem points to the next slab of free memory for an item. */
574 /* deaditemstack is the head of a linked list (stack) of deallocated items */
575 /* that can be recycled. unallocateditems is the number of items that */
576 /* remain to be allocated from nowblock. */
578 /* Traversal is the process of walking through the entire list of items, and */
579 /* is separate from allocation. Note that a traversal will visit items on */
580 /* the "deaditemstack" stack as well as live items. pathblock points to */
581 /* the block currently being traversed. pathitem points to the next item */
582 /* to be traversed. pathitemsleft is the number of items that remain to */
583 /* be traversed in pathblock. */
585 /* itemwordtype is set to POINTER or FLOATINGPOINT, and is used to suggest */
586 /* what sort of word the record is primarily made up of. alignbytes */
587 /* determines how new records should be aligned in memory. itembytes and */
588 /* itemwords are the length of a record in bytes (after rounding up) and */
589 /* words. itemsperblock is the number of items allocated at once in a */
590 /* single block. items is the number of currently allocated items. */
591 /* maxitems is the maximum number of items that have been allocated at */
592 /* once; it is the current number of items plus the number of records kept */
593 /* on deaditemstack. */
596 VOID **firstblock, **nowblock;
601 enum wordtype itemwordtype;
603 int itembytes, itemwords;
605 long items, maxitems;
606 int unallocateditems;
610 /* Variables used to allocate memory for triangles, shell edges, points, */
611 /* viri (triangles being eaten), bad (encroached) segments, bad (skinny */
612 /* or too large) triangles, and splay tree nodes. */
614 static struct memorypool triangles;
615 static struct memorypool shelles;
616 static struct memorypool points;
617 static struct memorypool viri;
618 static struct memorypool badsegments;
619 static struct memorypool badtriangles;
620 static struct memorypool splaynodes;
622 /* Variables that maintain the bad triangle queues. The tails are pointers */
623 /* to the pointers that have to be filled in to enqueue an item. */
625 static struct badface *queuefront[64];
626 static struct badface **queuetail[64];
628 static REAL xmin, xmax, ymin, ymax; /* x and y bounds. */
629 static REAL xminextreme; /* Nonexistent x value used as a flag in sweepline. */
630 static int inpoints; /* Number of input points. */
631 static int inelements; /* Number of input triangles. */
632 static int insegments; /* Number of input segments. */
633 static int holes; /* Number of input holes. */
634 static int regions; /* Number of input regions. */
635 static long edges; /* Number of output edges. */
636 static int mesh_dim; /* Dimension (ought to be 2). */
637 static int nextras; /* Number of attributes per point. */
638 static int eextras; /* Number of attributes per triangle. */
639 static long hullsize; /* Number of edges of convex hull. */
640 static int triwords; /* Total words per triangle. */
641 static int shwords; /* Total words per shell edge. */
642 static int pointmarkindex; /* Index to find boundary marker of a point. */
643 static int point2triindex; /* Index to find a triangle adjacent to a point. */
644 static int highorderindex; /* Index to find extra nodes for high-order elements. */
645 static int elemattribindex; /* Index to find attributes of a triangle. */
646 static int areaboundindex; /* Index to find area bound of a triangle. */
647 static int checksegments; /* Are there segments in the triangulation yet? */
648 static int readnodefile; /* Has a .node file been read? */
649 static long samples; /* Number of random samples for point location. */
650 static unsigned long randomseed; /* Current random number seed. */
652 static REAL splitter; /* Used to split REAL factors for exact multiplication. */
653 static REAL epsilon; /* Floating-point machine epsilon. */
654 static REAL resulterrbound;
655 static REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
656 static REAL iccerrboundA, iccerrboundB, iccerrboundC;
658 static long incirclecount; /* Number of incircle tests performed. */
659 static long counterclockcount; /* Number of counterclockwise tests performed. */
660 static long hyperbolacount; /* Number of right-of-hyperbola tests performed. */
661 static long circumcentercount; /* Number of circumcenter calculations performed. */
662 static long circletopcount; /* Number of circle top calculations performed. */
664 /* Switches for the triangulator. */
665 /* poly: -p switch. refine: -r switch. */
666 /* quality: -q switch. */
667 /* minangle: minimum angle bound, specified after -q switch. */
668 /* goodangle: cosine squared of minangle. */
669 /* vararea: -a switch without number. */
670 /* fixedarea: -a switch with number. */
671 /* maxarea: maximum area bound, specified after -a switch. */
672 /* regionattrib: -A switch. convex: -c switch. */
673 /* firstnumber: inverse of -z switch. All items are numbered starting */
674 /* from firstnumber. */
675 /* edgesout: -e switch. voronoi: -v switch. */
676 /* neighbors: -n switch. geomview: -g switch. */
677 /* nobound: -B switch. nopolywritten: -P switch. */
678 /* nonodewritten: -N switch. noelewritten: -E switch. */
679 /* noiterationnum: -I switch. noholes: -O switch. */
680 /* noexact: -X switch. */
681 /* order: element order, specified after -o switch. */
682 /* nobisect: count of how often -Y switch is selected. */
683 /* steiner: maximum number of Steiner points, specified after -S switch. */
684 /* steinerleft: number of Steiner points not yet used. */
685 /* incremental: -i switch. sweepline: -F switch. */
686 /* dwyer: inverse of -l switch. */
687 /* splitseg: -s switch. */
688 /* docheck: -C switch. */
689 /* quiet: -Q switch. verbose: count of how often -V switch is selected. */
690 /* useshelles: -p, -r, -q, or -c switch; determines whether shell edges */
691 /* are used at all. */
693 /* Read the instructions to find out the meaning of these switches. */
695 static int poly, refine, quality, vararea, fixedarea, regionattrib, convex;
696 static int firstnumber;
697 static int edgesout, voronoi, neighbors, geomview;
698 static int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
699 static int noholes, noexact;
700 static int incremental, sweepline, dwyer;
703 static int quiet, verbose;
704 static int useshelles;
707 static int steiner, steinerleft;
708 static REAL minangle, goodangle;
711 /* Variables for file names. */
714 char innodefilename[FILENAMESIZE];
715 char inelefilename[FILENAMESIZE];
716 char inpolyfilename[FILENAMESIZE];
717 char areafilename[FILENAMESIZE];
718 char outnodefilename[FILENAMESIZE];
719 char outelefilename[FILENAMESIZE];
720 char outpolyfilename[FILENAMESIZE];
721 char edgefilename[FILENAMESIZE];
722 char vnodefilename[FILENAMESIZE];
723 char vedgefilename[FILENAMESIZE];
724 char neighborfilename[FILENAMESIZE];
725 char offfilename[FILENAMESIZE];
726 #endif /* not TRILIBRARY */
728 /* Triangular bounding box points. */
730 static point infpoint1, infpoint2, infpoint3;
732 /* Pointer to the `triangle' that occupies all of "outer space". */
734 static triangle *dummytri;
735 static triangle *dummytribase; /* Keep base address so we can free() it later. */
737 /* Pointer to the omnipresent shell edge. Referenced by any triangle or */
738 /* shell edge that isn't really connected to a shell edge at that */
741 static shelle *dummysh;
742 static shelle *dummyshbase; /* Keep base address so we can free() it later. */
744 /* Pointer to a recently visited triangle. Improves point location if */
745 /* proximate points are inserted sequentially. */
747 static struct triedge recenttri;
749 /*****************************************************************************/
751 /* Mesh manipulation primitives. Each triangle contains three pointers to */
752 /* other triangles, with orientations. Each pointer points not to the */
753 /* first byte of a triangle, but to one of the first three bytes of a */
754 /* triangle. It is necessary to extract both the triangle itself and the */
755 /* orientation. To save memory, I keep both pieces of information in one */
756 /* pointer. To make this possible, I assume that all triangles are aligned */
757 /* to four-byte boundaries. The `decode' routine below decodes a pointer, */
758 /* extracting an orientation (in the range 0 to 2) and a pointer to the */
759 /* beginning of a triangle. The `encode' routine compresses a pointer to a */
760 /* triangle and an orientation into a single pointer. My assumptions that */
761 /* triangles are four-byte-aligned and that the `unsigned long' type is */
762 /* long enough to hold a pointer are two of the few kludges in this program.*/
764 /* Shell edges are manipulated similarly. A pointer to a shell edge */
765 /* carries both an address and an orientation in the range 0 to 1. */
767 /* The other primitives take an oriented triangle or oriented shell edge, */
768 /* and return an oriented triangle or oriented shell edge or point; or they */
769 /* change the connections in the data structure. */
771 /*****************************************************************************/
773 /********* Mesh manipulation primitives begin here *********/
777 /* Fast lookup arrays to speed some of the mesh manipulation primitives. */
779 int plus1mod3[3] = {1, 2, 0};
780 int minus1mod3[3] = {2, 0, 1};
782 /********* Primitives for triangles *********/
786 /* decode() converts a pointer to an oriented triangle. The orientation is */
787 /* extracted from the two least significant bits of the pointer. */
789 #define decode(ptr, triedge) \
790 (triedge).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l); \
791 (triedge).tri = (triangle *) \
792 ((unsigned long) (ptr) ^ (unsigned long) (triedge).orient)
794 /* encode() compresses an oriented triangle into a single pointer. It */
795 /* relies on the assumption that all triangles are aligned to four-byte */
796 /* boundaries, so the two least significant bits of (triedge).tri are zero.*/
798 #define encode(triedge) \
799 (triangle) ((unsigned long) (triedge).tri | (unsigned long) (triedge).orient)
801 /* The following edge manipulation primitives are all described by Guibas */
802 /* and Stolfi. However, they use an edge-based data structure, whereas I */
803 /* am using a triangle-based data structure. */
805 /* sym() finds the abutting triangle, on the same edge. Note that the */
806 /* edge direction is necessarily reversed, because triangle/edge handles */
807 /* are always directed counterclockwise around the triangle. */
809 #define sym(triedge1, triedge2) \
810 ptr = (triedge1).tri[(triedge1).orient]; \
811 decode(ptr, triedge2);
813 #define symself(triedge) \
814 ptr = (triedge).tri[(triedge).orient]; \
815 decode(ptr, triedge);
817 /* lnext() finds the next edge (counterclockwise) of a triangle. */
819 #define lnext(triedge1, triedge2) \
820 (triedge2).tri = (triedge1).tri; \
821 (triedge2).orient = plus1mod3[(triedge1).orient]
823 #define lnextself(triedge) \
824 (triedge).orient = plus1mod3[(triedge).orient]
826 /* lprev() finds the previous edge (clockwise) of a triangle. */
828 #define lprev(triedge1, triedge2) \
829 (triedge2).tri = (triedge1).tri; \
830 (triedge2).orient = minus1mod3[(triedge1).orient]
832 #define lprevself(triedge) \
833 (triedge).orient = minus1mod3[(triedge).orient]
835 /* onext() spins counterclockwise around a point; that is, it finds the next */
836 /* edge with the same origin in the counterclockwise direction. This edge */
837 /* will be part of a different triangle. */
839 #define onext(triedge1, triedge2) \
840 lprev(triedge1, triedge2); \
843 #define onextself(triedge) \
844 lprevself(triedge); \
847 /* oprev() spins clockwise around a point; that is, it finds the next edge */
848 /* with the same origin in the clockwise direction. This edge will be */
849 /* part of a different triangle. */
851 #define oprev(triedge1, triedge2) \
852 sym(triedge1, triedge2); \
855 #define oprevself(triedge) \
859 /* dnext() spins counterclockwise around a point; that is, it finds the next */
860 /* edge with the same destination in the counterclockwise direction. This */
861 /* edge will be part of a different triangle. */
863 #define dnext(triedge1, triedge2) \
864 sym(triedge1, triedge2); \
867 #define dnextself(triedge) \
871 /* dprev() spins clockwise around a point; that is, it finds the next edge */
872 /* with the same destination in the clockwise direction. This edge will */
873 /* be part of a different triangle. */
875 #define dprev(triedge1, triedge2) \
876 lnext(triedge1, triedge2); \
879 #define dprevself(triedge) \
880 lnextself(triedge); \
883 /* rnext() moves one edge counterclockwise about the adjacent triangle. */
884 /* (It's best understood by reading Guibas and Stolfi. It involves */
885 /* changing triangles twice.) */
887 #define rnext(triedge1, triedge2) \
888 sym(triedge1, triedge2); \
889 lnextself(triedge2); \
892 #define rnextself(triedge) \
894 lnextself(triedge); \
897 /* rnext() moves one edge clockwise about the adjacent triangle. */
898 /* (It's best understood by reading Guibas and Stolfi. It involves */
899 /* changing triangles twice.) */
901 #define rprev(triedge1, triedge2) \
902 sym(triedge1, triedge2); \
903 lprevself(triedge2); \
906 #define rprevself(triedge) \
908 lprevself(triedge); \
911 /* These primitives determine or set the origin, destination, or apex of a */
914 #define org(triedge, pointptr) \
915 pointptr = (point) (triedge).tri[plus1mod3[(triedge).orient] + 3]
917 #define dest(triedge, pointptr) \
918 pointptr = (point) (triedge).tri[minus1mod3[(triedge).orient] + 3]
920 #define apex(triedge, pointptr) \
921 pointptr = (point) (triedge).tri[(triedge).orient + 3]
923 #define setorg(triedge, pointptr) \
924 (triedge).tri[plus1mod3[(triedge).orient] + 3] = (triangle) pointptr
926 #define setdest(triedge, pointptr) \
927 (triedge).tri[minus1mod3[(triedge).orient] + 3] = (triangle) pointptr
929 #define setapex(triedge, pointptr) \
930 (triedge).tri[(triedge).orient + 3] = (triangle) pointptr
932 #define setvertices2null(triedge) \
933 (triedge).tri[3] = (triangle) NULL; \
934 (triedge).tri[4] = (triangle) NULL; \
935 (triedge).tri[5] = (triangle) NULL;
937 /* Bond two triangles together. */
939 #define bond(triedge1, triedge2) \
940 (triedge1).tri[(triedge1).orient] = encode(triedge2); \
941 (triedge2).tri[(triedge2).orient] = encode(triedge1)
943 /* Dissolve a bond (from one side). Note that the other triangle will still */
944 /* think it's connected to this triangle. Usually, however, the other */
945 /* triangle is being deleted entirely, or bonded to another triangle, so */
946 /* it doesn't matter. */
948 #define dissolve(triedge) \
949 (triedge).tri[(triedge).orient] = (triangle) dummytri
951 /* Copy a triangle/edge handle. */
953 #define triedgecopy(triedge1, triedge2) \
954 (triedge2).tri = (triedge1).tri; \
955 (triedge2).orient = (triedge1).orient
957 /* Test for equality of triangle/edge handles. */
959 #define triedgeequal(triedge1, triedge2) \
960 (((triedge1).tri == (triedge2).tri) && \
961 ((triedge1).orient == (triedge2).orient))
963 /* Primitives to infect or cure a triangle with the virus. These rely on */
964 /* the assumption that all shell edges are aligned to four-byte boundaries.*/
966 #define infect(triedge) \
967 (triedge).tri[6] = (triangle) \
968 ((unsigned long) (triedge).tri[6] | (unsigned long) 2l)
970 #define uninfect(triedge) \
971 (triedge).tri[6] = (triangle) \
972 ((unsigned long) (triedge).tri[6] & ~ (unsigned long) 2l)
974 /* Test a triangle for viral infection. */
976 #define infected(triedge) \
977 (((unsigned long) (triedge).tri[6] & (unsigned long) 2l) != 0)
979 /* Check or set a triangle's attributes. */
981 #define elemattribute(triedge, attnum) \
982 ((REAL *) (triedge).tri)[elemattribindex + (attnum)]
984 #define setelemattribute(triedge, attnum, value) \
985 ((REAL *) (triedge).tri)[elemattribindex + (attnum)] = (REAL)value
987 /* Check or set a triangle's maximum area bound. */
989 #define areabound(triedge) ((REAL *) (triedge).tri)[areaboundindex]
991 #define setareabound(triedge, value) \
992 ((REAL *) (triedge).tri)[areaboundindex] = (REAL)value
994 /********* Primitives for shell edges *********/
998 /* sdecode() converts a pointer to an oriented shell edge. The orientation */
999 /* is extracted from the least significant bit of the pointer. The two */
1000 /* least significant bits (one for orientation, one for viral infection) */
1001 /* are masked out to produce the real pointer. */
1003 #define sdecode(sptr, edge) \
1004 (edge).shorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l); \
1005 (edge).sh = (shelle *) \
1006 ((unsigned long) (sptr) & ~ (unsigned long) 3l)
1008 /* sencode() compresses an oriented shell edge into a single pointer. It */
1009 /* relies on the assumption that all shell edges are aligned to two-byte */
1010 /* boundaries, so the least significant bit of (edge).sh is zero. */
1012 #define sencode(edge) \
1013 (shelle) ((unsigned long) (edge).sh | (unsigned long) (edge).shorient)
1015 /* ssym() toggles the orientation of a shell edge. */
1017 #define ssym(edge1, edge2) \
1018 (edge2).sh = (edge1).sh; \
1019 (edge2).shorient = 1 - (edge1).shorient
1021 #define ssymself(edge) \
1022 (edge).shorient = 1 - (edge).shorient
1024 /* spivot() finds the other shell edge (from the same segment) that shares */
1025 /* the same origin. */
1027 #define spivot(edge1, edge2) \
1028 sptr = (edge1).sh[(edge1).shorient]; \
1029 sdecode(sptr, edge2)
1031 #define spivotself(edge) \
1032 sptr = (edge).sh[(edge).shorient]; \
1035 /* snext() finds the next shell edge (from the same segment) in sequence; */
1036 /* one whose origin is the input shell edge's destination. */
1038 #define snext(edge1, edge2) \
1039 sptr = (edge1).sh[1 - (edge1).shorient]; \
1040 sdecode(sptr, edge2)
1042 #define snextself(edge) \
1043 sptr = (edge).sh[1 - (edge).shorient]; \
1046 /* These primitives determine or set the origin or destination of a shell */
1049 #define sorg(edge, pointptr) \
1050 pointptr = (point) (edge).sh[2 + (edge).shorient]
1052 #define sdest(edge, pointptr) \
1053 pointptr = (point) (edge).sh[3 - (edge).shorient]
1055 #define setsorg(edge, pointptr) \
1056 (edge).sh[2 + (edge).shorient] = (shelle) pointptr
1058 #define setsdest(edge, pointptr) \
1059 (edge).sh[3 - (edge).shorient] = (shelle) pointptr
1061 /* These primitives read or set a shell marker. Shell markers are used to */
1062 /* hold user boundary information. */
1064 #define mark(edge) (* (int *) ((edge).sh + 6))
1066 #define setmark(edge, value) \
1067 * (int *) ((edge).sh + 6) = value
1069 /* Bond two shell edges together. */
1071 #define sbond(edge1, edge2) \
1072 (edge1).sh[(edge1).shorient] = sencode(edge2); \
1073 (edge2).sh[(edge2).shorient] = sencode(edge1)
1075 /* Dissolve a shell edge bond (from one side). Note that the other shell */
1076 /* edge will still think it's connected to this shell edge. */
1078 #define sdissolve(edge) \
1079 (edge).sh[(edge).shorient] = (shelle) dummysh
1081 /* Copy a shell edge. */
1083 #define shellecopy(edge1, edge2) \
1084 (edge2).sh = (edge1).sh; \
1085 (edge2).shorient = (edge1).shorient
1087 /* Test for equality of shell edges. */
1089 #define shelleequal(edge1, edge2) \
1090 (((edge1).sh == (edge2).sh) && \
1091 ((edge1).shorient == (edge2).shorient))
1093 /********* Primitives for interacting triangles and shell edges *********/
1097 /* tspivot() finds a shell edge abutting a triangle. */
1099 #define tspivot(triedge, edge) \
1100 sptr = (shelle) (triedge).tri[6 + (triedge).orient]; \
1103 /* stpivot() finds a triangle abutting a shell edge. It requires that the */
1104 /* variable `ptr' of type `triangle' be defined. */
1106 #define stpivot(edge, triedge) \
1107 ptr = (triangle) (edge).sh[4 + (edge).shorient]; \
1108 decode(ptr, triedge)
1110 /* Bond a triangle to a shell edge. */
1112 #define tsbond(triedge, edge) \
1113 (triedge).tri[6 + (triedge).orient] = (triangle) sencode(edge); \
1114 (edge).sh[4 + (edge).shorient] = (shelle) encode(triedge)
1116 /* Dissolve a bond (from the triangle side). */
1118 #define tsdissolve(triedge) \
1119 (triedge).tri[6 + (triedge).orient] = (triangle) dummysh
1121 /* Dissolve a bond (from the shell edge side). */
1123 #define stdissolve(edge) \
1124 (edge).sh[4 + (edge).shorient] = (shelle) dummytri
1126 /********* Primitives for points *********/
1130 #define pointmark(pt) ((int *) (pt))[pointmarkindex]
1132 #define setpointmark(pt, value) \
1133 ((int *) (pt))[pointmarkindex] = value
1135 #define point2tri(pt) ((triangle *) (pt))[point2triindex]
1137 #define setpoint2tri(pt, value) \
1138 ((triangle *) (pt))[point2triindex] = value
1142 /********* Mesh manipulation primitives end here *********/
1144 /********* User interaction routines begin here *********/
1148 /*****************************************************************************/
1150 /* syntax() Print list of command line switches. */
1152 /*****************************************************************************/
1160 printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n");
1161 #else /* not REDUCED */
1162 printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n");
1163 #endif /* not REDUCED */
1164 #else /* not CDT_ONLY */
1166 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n");
1167 #else /* not REDUCED */
1168 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
1169 #endif /* not REDUCED */
1170 #endif /* not CDT_ONLY */
1172 printf(" -p Triangulates a Planar Straight Line Graph (.poly file).\n");
1174 printf(" -r Refines a previously generated mesh.\n");
1176 " -q Quality mesh generation. A minimum angle may be specified.\n");
1177 printf(" -a Applies a maximum triangle area constraint.\n");
1178 #endif /* not CDT_ONLY */
1180 " -A Applies attributes to identify elements in certain regions.\n");
1181 printf(" -c Encloses the convex hull with segments.\n");
1182 printf(" -e Generates an edge list.\n");
1183 printf(" -v Generates a Voronoi diagram.\n");
1184 printf(" -n Generates a list of triangle neighbors.\n");
1185 printf(" -g Generates an .off file for Geomview.\n");
1186 printf(" -B Suppresses output of boundary information.\n");
1187 printf(" -P Suppresses output of .poly file.\n");
1188 printf(" -N Suppresses output of .node file.\n");
1189 printf(" -E Suppresses output of .ele file.\n");
1190 printf(" -I Suppresses mesh iteration numbers.\n");
1191 printf(" -O Ignores holes in .poly file.\n");
1192 printf(" -X Suppresses use of exact arithmetic.\n");
1193 printf(" -z Numbers all items starting from zero (rather than one).\n");
1194 printf(" -o2 Generates second-order subparametric elements.\n");
1196 printf(" -Y Suppresses boundary segment splitting.\n");
1197 printf(" -S Specifies maximum number of added Steiner points.\n");
1198 #endif /* not CDT_ONLY */
1200 printf(" -i Uses incremental method, rather than divide-and-conquer.\n");
1201 printf(" -F Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
1202 #endif /* not REDUCED */
1203 printf(" -l Uses vertical cuts only, rather than alternating cuts.\n");
1207 " -s Force segments into mesh by splitting (instead of using CDT).\n");
1208 #endif /* not CDT_ONLY */
1209 printf(" -C Check consistency of final mesh.\n");
1210 #endif /* not REDUCED */
1211 printf(" -Q Quiet: No terminal output except errors.\n");
1212 printf(" -V Verbose: Detailed information on what I'm doing.\n");
1213 printf(" -h Help: Detailed instructions for Triangle.\n");
1217 #endif /* not TRILIBRARY */
1219 /*****************************************************************************/
1221 /* info() Print out complete instructions. */
1223 /*****************************************************************************/
1229 printf("Triangle\n");
1231 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
1232 printf("Version 1.3\n\n");
1234 "Copyright 1996 Jonathan Richard Shewchuk (bugs/comments to jrs@cs.cmu.edu)\n"
1236 printf("School of Computer Science / Carnegie Mellon University\n");
1237 printf("5000 Forbes Avenue / Pittsburgh, Pennsylvania 15213-3891\n");
1239 "Created as part of the Archimedes project (tools for parallel FEM).\n");
1241 "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
1242 printf("There is no warranty whatsoever. Use at your own risk.\n");
1244 printf("This executable is compiled for single precision arithmetic.\n\n\n");
1245 #else /* not SINGLE */
1246 printf("This executable is compiled for double precision arithmetic.\n\n\n");
1247 #endif /* not SINGLE */
1249 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
1251 "triangulations, and quality conforming Delaunay triangulations. The latter\n"
1254 "can be generated with no small angles, and are thus suitable for finite\n");
1256 "element analysis. If no command line switches are specified, your .node\n");
1258 "input file will be read, and the Delaunay triangulation will be returned in\n"
1260 printf(".node and .ele output files. The command syntax is:\n\n");
1263 printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n\n");
1264 #else /* not REDUCED */
1265 printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n\n");
1266 #endif /* not REDUCED */
1267 #else /* not CDT_ONLY */
1269 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n\n");
1270 #else /* not REDUCED */
1271 printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
1272 #endif /* not REDUCED */
1273 #endif /* not CDT_ONLY */
1275 "Underscores indicate that numbers may optionally follow certain switches;\n");
1277 "do not leave any space between a switch and its numeric parameter.\n");
1279 "input_file must be a file with extension .node, or extension .poly if the\n");
1281 "-p switch is used. If -r is used, you must supply .node and .ele files,\n");
1283 "and possibly a .poly file and .area file as well. The formats of these\n");
1284 printf("files are described below.\n\n");
1285 printf("Command Line Switches:\n\n");
1287 " -p Reads a Planar Straight Line Graph (.poly file), which can specify\n"
1290 " points, segments, holes, and regional attributes and area\n");
1292 " constraints. Will generate a constrained Delaunay triangulation\n");
1294 " fitting the input; or, if -s, -q, or -a is used, a conforming\n");
1296 " Delaunay triangulation. If -p is not used, Triangle reads a .node\n"
1298 printf(" file by default.\n");
1300 " -r Refines a previously generated mesh. The mesh is read from a .node\n"
1303 " file and an .ele file. If -p is also used, a .poly file is read\n");
1305 " and used to constrain edges in the mesh. Further details on\n");
1306 printf(" refinement are given below.\n");
1308 " -q Quality mesh generation by Jim Ruppert's Delaunay refinement\n");
1310 " algorithm. Adds points to the mesh to ensure that no angles\n");
1312 " smaller than 20 degrees occur. An alternative minimum angle may be\n"
1315 " specified after the `q'. If the minimum angle is 20.7 degrees or\n");
1317 " smaller, the triangulation algorithm is theoretically guaranteed to\n"
1320 " terminate (assuming infinite precision arithmetic - Triangle may\n");
1322 " fail to terminate if you run out of precision). In practice, the\n");
1324 " algorithm often succeeds for minimum angles up to 33.8 degrees.\n");
1326 " For highly refined meshes, however, it may be necessary to reduce\n");
1328 " the minimum angle to well below 20 to avoid problems associated\n");
1330 " with insufficient floating-point precision. The specified angle\n");
1331 printf(" may include a decimal point.\n");
1333 " -a Imposes a maximum triangle area. If a number follows the `a', no\n");
1335 " triangle will be generated whose area is larger than that number.\n");
1337 " If no number is specified, an .area file (if -r is used) or .poly\n");
1339 " file (if -r is not used) specifies a number of maximum area\n");
1341 " constraints. An .area file contains a separate area constraint for\n"
1344 " each triangle, and is useful for refining a finite element mesh\n");
1346 " based on a posteriori error estimates. A .poly file can optionally\n"
1349 " contain an area constraint for each segment-bounded region, thereby\n"
1352 " enforcing triangle densities in a first triangulation. You can\n");
1354 " impose both a fixed area constraint and a varying area constraint\n");
1356 " by invoking the -a switch twice, once with and once without a\n");
1358 " number following. Each area specified may include a decimal point.\n"
1361 " -A Assigns an additional attribute to each triangle that identifies\n");
1363 " what segment-bounded region each triangle belongs to. Attributes\n");
1365 " are assigned to regions by the .poly file. If a region is not\n");
1367 " explicitly marked by the .poly file, triangles in that region are\n");
1369 " assigned an attribute of zero. The -A switch has an effect only\n");
1370 printf(" when the -p switch is used and the -r switch is not.\n");
1372 " -c Creates segments on the convex hull of the triangulation. If you\n");
1374 " are triangulating a point set, this switch causes a .poly file to\n");
1376 " be written, containing all edges in the convex hull. (By default,\n"
1379 " a .poly file is written only if a .poly file is read.) If you are\n"
1382 " triangulating a PSLG, this switch specifies that the interior of\n");
1384 " the convex hull of the PSLG should be triangulated. If you do not\n"
1387 " use this switch when triangulating a PSLG, it is assumed that you\n");
1389 " have identified the region to be triangulated by surrounding it\n");
1391 " with segments of the input PSLG. Beware: if you are not careful,\n"
1394 " this switch can cause the introduction of an extremely thin angle\n");
1396 " between a PSLG segment and a convex hull segment, which can cause\n");
1398 " overrefinement or failure if Triangle runs out of precision. If\n");
1400 " you are refining a mesh, the -c switch works differently; it\n");
1402 " generates the set of boundary edges of the mesh, rather than the\n");
1403 printf(" convex hull.\n");
1405 " -e Outputs (to an .edge file) a list of edges of the triangulation.\n");
1407 " -v Outputs the Voronoi diagram associated with the triangulation.\n");
1408 printf(" Does not attempt to detect degeneracies.\n");
1410 " -n Outputs (to a .neigh file) a list of triangles neighboring each\n");
1411 printf(" triangle.\n");
1413 " -g Outputs the mesh to an Object File Format (.off) file, suitable for\n"
1415 printf(" viewing with the Geometry Center's Geomview package.\n");
1417 " -B No boundary markers in the output .node, .poly, and .edge output\n");
1419 " files. See the detailed discussion of boundary markers below.\n");
1421 " -P No output .poly file. Saves disk space, but you lose the ability\n");
1423 " to impose segment constraints on later refinements of the mesh.\n");
1424 printf(" -N No output .node file.\n");
1425 printf(" -E No output .ele file.\n");
1427 " -I No iteration numbers. Suppresses the output of .node and .poly\n");
1429 " files, so your input files won't be overwritten. (If your input is\n"
1432 " a .poly file only, a .node file will be written.) Cannot be used\n");
1434 " with the -r switch, because that would overwrite your input .ele\n");
1436 " file. Shouldn't be used with the -s, -q, or -a switch if you are\n");
1438 " using a .node file for input, because no .node file will be\n");
1439 printf(" written, so there will be no record of any added points.\n");
1440 printf(" -O No holes. Ignores the holes in the .poly file.\n");
1442 " -X No exact arithmetic. Normally, Triangle uses exact floating-point\n"
1445 " arithmetic for certain tests if it thinks the inexact tests are not\n"
1448 " accurate enough. Exact arithmetic ensures the robustness of the\n");
1450 " triangulation algorithms, despite floating-point roundoff error.\n");
1452 " Disabling exact arithmetic with the -X switch will cause a small\n");
1454 " improvement in speed and create the possibility (albeit small) that\n"
1457 " Triangle will fail to produce a valid mesh. Not recommended.\n");
1459 " -z Numbers all items starting from zero (rather than one). Note that\n"
1462 " this switch is normally overrided by the value used to number the\n");
1464 " first point of the input .node or .poly file. However, this switch\n"
1466 printf(" is useful when calling Triangle from another program.\n");
1468 " -o2 Generates second-order subparametric elements with six nodes each.\n"
1471 " -Y No new points on the boundary. This switch is useful when the mesh\n"
1474 " boundary must be preserved so that it conforms to some adjacent\n");
1476 " mesh. Be forewarned that you will probably sacrifice some of the\n");
1478 " quality of the mesh; Triangle will try, but the resulting mesh may\n"
1481 " contain triangles of poor aspect ratio. Works well if all the\n");
1483 " boundary points are closely spaced. Specify this switch twice\n");
1485 " (`-YY') to prevent all segment splitting, including internal\n");
1486 printf(" boundaries.\n");
1488 " -S Specifies the maximum number of Steiner points (points that are not\n"
1491 " in the input, but are added to meet the constraints of minimum\n");
1493 " angle and maximum area). The default is to allow an unlimited\n");
1495 " number. If you specify this switch with no number after it,\n");
1497 " the limit is set to zero. Triangle always adds points at segment\n");
1499 " intersections, even if it needs to use more points than the limit\n");
1501 " you set. When Triangle inserts segments by splitting (-s), it\n");
1503 " always adds enough points to ensure that all the segments appear in\n"
1506 " the triangulation, again ignoring the limit. Be forewarned that\n");
1508 " the -S switch may result in a conforming triangulation that is not\n"
1511 " truly Delaunay, because Triangle may be forced to stop adding\n");
1513 " points when the mesh is in a state where a segment is non-Delaunay\n"
1516 " and needs to be split. If so, Triangle will print a warning.\n");
1518 " -i Uses an incremental rather than divide-and-conquer algorithm to\n");
1520 " form a Delaunay triangulation. Try it if the divide-and-conquer\n");
1521 printf(" algorithm fails.\n");
1523 " -F Uses Steven Fortune's sweepline algorithm to form a Delaunay\n");
1525 " triangulation. Warning: does not use exact arithmetic for all\n");
1526 printf(" calculations. An exact result is not guaranteed.\n");
1528 " -l Uses only vertical cuts in the divide-and-conquer algorithm. By\n");
1530 " default, Triangle uses alternating vertical and horizontal cuts,\n");
1532 " which usually improve the speed except with point sets that are\n");
1534 " small or short and wide. This switch is primarily of theoretical\n");
1535 printf(" interest.\n");
1537 " -s Specifies that segments should be forced into the triangulation by\n"
1540 " recursively splitting them at their midpoints, rather than by\n");
1542 " generating a constrained Delaunay triangulation. Segment splitting\n"
1545 " is true to Ruppert's original algorithm, but can create needlessly\n"
1547 printf(" small triangles near external small features.\n");
1549 " -C Check the consistency of the final mesh. Uses exact arithmetic for\n"
1552 " checking, even if the -X switch is used. Useful if you suspect\n");
1553 printf(" Triangle is buggy.\n");
1555 " -Q Quiet: Suppresses all explanation of what Triangle is doing, unless\n"
1557 printf(" an error occurs.\n");
1559 " -V Verbose: Gives detailed information about what Triangle is doing.\n");
1561 " Add more `V's for increasing amount of detail. `-V' gives\n");
1563 " information on algorithmic progress and more detailed statistics.\n");
1565 " `-VV' gives point-by-point details, and will print so much that\n");
1567 " Triangle will run much more slowly. `-VVV' gives information only\n"
1569 printf(" a debugger could love.\n");
1570 printf(" -h Help: Displays these instructions.\n");
1572 printf("Definitions:\n");
1575 " A Delaunay triangulation of a point set is a triangulation whose vertices\n"
1578 " are the point set, having the property that no point in the point set\n");
1580 " falls in the interior of the circumcircle (circle that passes through all\n"
1582 printf(" three vertices) of any triangle in the triangulation.\n\n");
1584 " A Voronoi diagram of a point set is a subdivision of the plane into\n");
1586 " polygonal regions (some of which may be infinite), where each region is\n");
1588 " the set of points in the plane that are closer to some input point than\n");
1590 " to any other input point. (The Voronoi diagram is the geometric dual of\n"
1592 printf(" the Delaunay triangulation.)\n\n");
1594 " A Planar Straight Line Graph (PSLG) is a collection of points and\n");
1596 " segments. Segments are simply edges, whose endpoints are points in the\n");
1598 " PSLG. The file format for PSLGs (.poly files) is described below.\n");
1601 " A constrained Delaunay triangulation of a PSLG is similar to a Delaunay\n");
1603 " triangulation, but each PSLG segment is present as a single edge in the\n");
1605 " triangulation. (A constrained Delaunay triangulation is not truly a\n");
1606 printf(" Delaunay triangulation.)\n\n");
1608 " A conforming Delaunay triangulation of a PSLG is a true Delaunay\n");
1610 " triangulation in which each PSLG segment may have been subdivided into\n");
1612 " several edges by the insertion of additional points. These inserted\n");
1614 " points are necessary to allow the segments to exist in the mesh while\n");
1615 printf(" maintaining the Delaunay property.\n\n");
1616 printf("File Formats:\n\n");
1618 " All files may contain comments prefixed by the character '#'. Points,\n");
1620 " triangles, edges, holes, and maximum area constraints must be numbered\n");
1622 " consecutively, starting from either 1 or 0. Whichever you choose, all\n");
1624 " input files must be consistent; if the nodes are numbered from 1, so must\n"
1627 " be all other objects. Triangle automatically detects your choice while\n");
1629 " reading the .node (or .poly) file. (When calling Triangle from another\n");
1631 " program, use the -z switch if you wish to number objects from zero.)\n");
1632 printf(" Examples of these file formats are given below.\n\n");
1633 printf(" .node files:\n");
1635 " First line: <# of points> <dimension (must be 2)> <# of attributes>\n");
1637 " <# of boundary markers (0 or 1)>\n"
1640 " Remaining lines: <point #> <x> <y> [attributes] [boundary marker]\n");
1643 " The attributes, which are typically floating-point values of physical\n");
1645 " quantities (such as mass or conductivity) associated with the nodes of\n"
1648 " a finite element mesh, are copied unchanged to the output mesh. If -s,\n"
1651 " -q, or -a is selected, each new Steiner point added to the mesh will\n");
1652 printf(" have attributes assigned to it by linear interpolation.\n\n");
1654 " If the fourth entry of the first line is `1', the last column of the\n");
1656 " remainder of the file is assumed to contain boundary markers. Boundary\n"
1659 " markers are used to identify boundary points and points resting on PSLG\n"
1662 " segments; a complete description appears in a section below. The .node\n"
1665 " file produced by Triangle will contain boundary markers in the last\n");
1666 printf(" column unless they are suppressed by the -B switch.\n\n");
1667 printf(" .ele files:\n");
1669 " First line: <# of triangles> <points per triangle> <# of attributes>\n");
1671 " Remaining lines: <triangle #> <point> <point> <point> ... [attributes]\n"
1675 " Points are indices into the corresponding .node file. The first three\n"
1678 " points are the corners, and are listed in counterclockwise order around\n"
1681 " each triangle. (The remaining points, if any, depend on the type of\n");
1683 " finite element used.) The attributes are just like those of .node\n");
1685 " files. Because there is no simple mapping from input to output\n");
1687 " triangles, an attempt is made to interpolate attributes, which may\n");
1689 " result in a good deal of diffusion of attributes among nearby triangles\n"
1692 " as the triangulation is refined. Diffusion does not occur across\n");
1694 " segments, so attributes used to identify segment-bounded regions remain\n"
1697 " intact. In output .ele files, all triangles have three points each\n");
1699 " unless the -o2 switch is used, in which case they have six, and the\n");
1701 " fourth, fifth, and sixth points lie on the midpoints of the edges\n");
1702 printf(" opposite the first, second, and third corners.\n\n");
1703 printf(" .poly files:\n");
1705 " First line: <# of points> <dimension (must be 2)> <# of attributes>\n");
1707 " <# of boundary markers (0 or 1)>\n"
1710 " Following lines: <point #> <x> <y> [attributes] [boundary marker]\n");
1711 printf(" One line: <# of segments> <# of boundary markers (0 or 1)>\n");
1713 " Following lines: <segment #> <endpoint> <endpoint> [boundary marker]\n");
1714 printf(" One line: <# of holes>\n");
1715 printf(" Following lines: <hole #> <x> <y>\n");
1717 " Optional line: <# of regional attributes and/or area constraints>\n");
1719 " Optional following lines: <constraint #> <x> <y> <attrib> <max area>\n");
1722 " A .poly file represents a PSLG, as well as some additional information.\n"
1725 " The first section lists all the points, and is identical to the format\n"
1728 " of .node files. <# of points> may be set to zero to indicate that the\n"
1731 " points are listed in a separate .node file; .poly files produced by\n");
1733 " Triangle always have this format. This has the advantage that a point\n"
1736 " set may easily be triangulated with or without segments. (The same\n");
1738 " effect can be achieved, albeit using more disk space, by making a copy\n"
1741 " of the .poly file with the extension .node; all sections of the file\n");
1742 printf(" but the first are ignored.)\n\n");
1744 " The second section lists the segments. Segments are edges whose\n");
1746 " presence in the triangulation is enforced. Each segment is specified\n");
1748 " by listing the indices of its two endpoints. This means that you must\n"
1751 " include its endpoints in the point list. If -s, -q, and -a are not\n");
1753 " selected, Triangle will produce a constrained Delaunay triangulation,\n");
1755 " in which each segment appears as a single edge in the triangulation.\n");
1757 " If -q or -a is selected, Triangle will produce a conforming Delaunay\n");
1759 " triangulation, in which segments may be subdivided into smaller edges.\n"
1761 printf(" Each segment, like each point, may have a boundary marker.\n\n");
1763 " The third section lists holes (and concavities, if -c is selected) in\n");
1765 " the triangulation. Holes are specified by identifying a point inside\n");
1767 " each hole. After the triangulation is formed, Triangle creates holes\n");
1769 " by eating triangles, spreading out from each hole point until its\n");
1771 " progress is blocked by PSLG segments; you must be careful to enclose\n");
1773 " each hole in segments, or your whole triangulation may be eaten away.\n");
1775 " If the two triangles abutting a segment are eaten, the segment itself\n");
1777 " is also eaten. Do not place a hole directly on a segment; if you do,\n");
1778 printf(" Triangle will choose one side of the segment arbitrarily.\n\n");
1780 " The optional fourth section lists regional attributes (to be assigned\n");
1782 " to all triangles in a region) and regional constraints on the maximum\n");
1784 " triangle area. Triangle will read this section only if the -A switch\n");
1786 " is used or the -a switch is used without a number following it, and the\n"
1789 " -r switch is not used. Regional attributes and area constraints are\n");
1791 " propagated in the same manner as holes; you specify a point for each\n");
1793 " attribute and/or constraint, and the attribute and/or constraint will\n");
1795 " affect the whole region (bounded by segments) containing the point. If\n"
1798 " two values are written on a line after the x and y coordinate, the\n");
1800 " former is assumed to be a regional attribute (but will only be applied\n"
1803 " if the -A switch is selected), and the latter is assumed to be a\n");
1805 " regional area constraint (but will only be applied if the -a switch is\n"
1808 " selected). You may also specify just one value after the coordinates,\n"
1811 " which can serve as both an attribute and an area constraint, depending\n"
1814 " on the choice of switches. If you are using the -A and -a switches\n");
1816 " simultaneously and wish to assign an attribute to some region without\n");
1817 printf(" imposing an area constraint, use a negative maximum area.\n\n");
1819 " When a triangulation is created from a .poly file, you must either\n");
1821 " enclose the entire region to be triangulated in PSLG segments, or\n");
1823 " use the -c switch, which encloses the convex hull of the input point\n");
1825 " set. If you do not use the -c switch, Triangle will eat all triangles\n"
1828 " on the outer boundary that are not protected by segments; if you are\n");
1830 " not careful, your whole triangulation may be eaten away. If you do\n");
1832 " use the -c switch, you can still produce concavities by appropriate\n");
1833 printf(" placement of holes just inside the convex hull.\n\n");
1835 " An ideal PSLG has no intersecting segments, nor any points that lie\n");
1837 " upon segments (except, of course, the endpoints of each segment.) You\n"
1840 " aren't required to make your .poly files ideal, but you should be aware\n"
1843 " of what can go wrong. Segment intersections are relatively safe -\n");
1845 " Triangle will calculate the intersection points for you and add them to\n"
1848 " the triangulation - as long as your machine's floating-point precision\n"
1851 " doesn't become a problem. You are tempting the fates if you have three\n"
1854 " segments that cross at the same location, and expect Triangle to figure\n"
1857 " out where the intersection point is. Thanks to floating-point roundoff\n"
1860 " error, Triangle will probably decide that the three segments intersect\n"
1863 " at three different points, and you will find a minuscule triangle in\n");
1865 " your output - unless Triangle tries to refine the tiny triangle, uses\n");
1867 " up the last bit of machine precision, and fails to terminate at all.\n");
1869 " You're better off putting the intersection point in the input files,\n");
1871 " and manually breaking up each segment into two. Similarly, if you\n");
1873 " place a point at the middle of a segment, and hope that Triangle will\n");
1875 " break up the segment at that point, you might get lucky. On the other\n"
1878 " hand, Triangle might decide that the point doesn't lie precisely on the\n"
1881 " line, and you'll have a needle-sharp triangle in your output - or a lot\n"
1883 printf(" of tiny triangles if you're generating a quality mesh.\n\n");
1885 " When Triangle reads a .poly file, it also writes a .poly file, which\n");
1887 " includes all edges that are part of input segments. If the -c switch\n");
1889 " is used, the output .poly file will also include all of the edges on\n");
1891 " the convex hull. Hence, the output .poly file is useful for finding\n");
1893 " edges associated with input segments and setting boundary conditions in\n"
1896 " finite element simulations. More importantly, you will need it if you\n"
1899 " plan to refine the output mesh, and don't want segments to be missing\n");
1900 printf(" in later triangulations.\n\n");
1901 printf(" .area files:\n");
1902 printf(" First line: <# of triangles>\n");
1903 printf(" Following lines: <triangle #> <maximum area>\n\n");
1905 " An .area file associates with each triangle a maximum area that is used\n"
1908 " for mesh refinement. As with other file formats, every triangle must\n");
1910 " be represented, and they must be numbered consecutively. A triangle\n");
1912 " may be left unconstrained by assigning it a negative maximum area.\n");
1914 printf(" .edge files:\n");
1915 printf(" First line: <# of edges> <# of boundary markers (0 or 1)>\n");
1917 " Following lines: <edge #> <endpoint> <endpoint> [boundary marker]\n");
1920 " Endpoints are indices into the corresponding .node file. Triangle can\n"
1923 " produce .edge files (use the -e switch), but cannot read them. The\n");
1925 " optional column of boundary markers is suppressed by the -B switch.\n");
1928 " In Voronoi diagrams, one also finds a special kind of edge that is an\n");
1930 " infinite ray with only one endpoint. For these edges, a different\n");
1931 printf(" format is used:\n\n");
1932 printf(" <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
1934 " The `direction' is a floating-point vector that indicates the direction\n"
1936 printf(" of the infinite ray.\n\n");
1937 printf(" .neigh files:\n");
1939 " First line: <# of triangles> <# of neighbors per triangle (always 3)>\n"
1942 " Following lines: <triangle #> <neighbor> <neighbor> <neighbor>\n");
1945 " Neighbors are indices into the corresponding .ele file. An index of -1\n"
1948 " indicates a mesh boundary, and therefore no neighbor. Triangle can\n");
1950 " produce .neigh files (use the -n switch), but cannot read them.\n");
1953 " The first neighbor of triangle i is opposite the first corner of\n");
1954 printf(" triangle i, and so on.\n\n");
1955 printf("Boundary Markers:\n\n");
1957 " Boundary markers are tags used mainly to identify which output points and\n"
1960 " edges are associated with which PSLG segment, and to identify which\n");
1962 " points and edges occur on a boundary of the triangulation. A common use\n"
1965 " is to determine where boundary conditions should be applied to a finite\n");
1967 " element mesh. You can prevent boundary markers from being written into\n");
1968 printf(" files produced by Triangle by using the -B switch.\n\n");
1970 " The boundary marker associated with each segment in an output .poly file\n"
1972 printf(" or edge in an output .edge file is chosen as follows:\n");
1974 " - If an output edge is part or all of a PSLG segment with a nonzero\n");
1976 " boundary marker, then the edge is assigned the same marker.\n");
1978 " - Otherwise, if the edge occurs on a boundary of the triangulation\n");
1980 " (including boundaries of holes), then the edge is assigned the marker\n"
1982 printf(" one (1).\n");
1983 printf(" - Otherwise, the edge is assigned the marker zero (0).\n");
1985 " The boundary marker associated with each point in an output .node file is\n"
1987 printf(" chosen as follows:\n");
1989 " - If a point is assigned a nonzero boundary marker in the input file,\n");
1991 " then it is assigned the same marker in the output .node file.\n");
1993 " - Otherwise, if the point lies on a PSLG segment (including the\n");
1995 " segment's endpoints) with a nonzero boundary marker, then the point\n");
1997 " is assigned the same marker. If the point lies on several such\n");
1998 printf(" segments, one of the markers is chosen arbitrarily.\n");
2000 " - Otherwise, if the point occurs on a boundary of the triangulation,\n");
2001 printf(" then the point is assigned the marker one (1).\n");
2002 printf(" - Otherwise, the point is assigned the marker zero (0).\n");
2005 " If you want Triangle to determine for you which points and edges are on\n");
2007 " the boundary, assign them the boundary marker zero (or use no markers at\n"
2010 " all) in your input files. Alternatively, you can mark some of them and\n");
2011 printf(" leave others marked zero, allowing Triangle to label them.\n\n");
2012 printf("Triangulation Iteration Numbers:\n\n");
2014 " Because Triangle can read and refine its own triangulations, input\n");
2016 " and output files have iteration numbers. For instance, Triangle might\n");
2018 " read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
2020 " triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
2021 printf(" mesh.4.poly. Files with no iteration number are treated as if\n");
2023 " their iteration number is zero; hence, Triangle might read the file\n");
2025 " points.node, triangulate it, and produce the files points.1.node and\n");
2026 printf(" points.1.ele.\n\n");
2028 " Iteration numbers allow you to create a sequence of successively finer\n");
2030 " meshes suitable for multigrid methods. They also allow you to produce a\n"
2033 " sequence of meshes using error estimate-driven mesh refinement.\n");
2036 " If you're not using refinement or quality meshing, and you don't like\n");
2038 " iteration numbers, use the -I switch to disable them. This switch will\n");
2040 " also disable output of .node and .poly files to prevent your input files\n"
2043 " from being overwritten. (If the input is a .poly file that contains its\n"
2045 printf(" own points, a .node file will be written.)\n\n");
2046 printf("Examples of How to Use Triangle:\n\n");
2048 " `triangle dots' will read points from dots.node, and write their Delaunay\n"
2051 " triangulation to dots.1.node and dots.1.ele. (dots.1.node will be\n");
2053 " identical to dots.node.) `triangle -I dots' writes the triangulation to\n"
2056 " dots.ele instead. (No additional .node file is needed, so none is\n");
2057 printf(" written.)\n\n");
2059 " `triangle -pe object.1' will read a PSLG from object.1.poly (and possibly\n"
2062 " object.1.node, if the points are omitted from object.1.poly) and write\n");
2063 printf(" their constrained Delaunay triangulation to object.2.node and\n");
2065 " object.2.ele. The segments will be copied to object.2.poly, and all\n");
2066 printf(" edges will be written to object.2.edge.\n\n");
2068 " `triangle -pq31.5a.1 object' will read a PSLG from object.poly (and\n");
2070 " possibly object.node), generate a mesh whose angles are all greater than\n"
2073 " 31.5 degrees and whose triangles all have area smaller than 0.1, and\n");
2075 " write the mesh to object.1.node and object.1.ele. Each segment may have\n"
2078 " been broken up into multiple edges; the resulting constrained edges are\n");
2079 printf(" written to object.1.poly.\n\n");
2081 " Here is a sample file `box.poly' describing a square with a square hole:\n"
2085 " # A box with eight points in 2D, no attributes, one boundary marker.\n");
2086 printf(" 8 2 0 1\n");
2087 printf(" # Outer box has these vertices:\n");
2088 printf(" 1 0 0 0\n");
2089 printf(" 2 0 3 0\n");
2090 printf(" 3 3 0 0\n");
2091 printf(" 4 3 3 33 # A special marker for this point.\n");
2092 printf(" # Inner square has these vertices:\n");
2093 printf(" 5 1 1 0\n");
2094 printf(" 6 1 2 0\n");
2095 printf(" 7 2 1 0\n");
2096 printf(" 8 2 2 0\n");
2097 printf(" # Five segments with boundary markers.\n");
2099 printf(" 1 1 2 5 # Left side of outer box.\n");
2100 printf(" 2 5 7 0 # Segments 2 through 5 enclose the hole.\n");
2101 printf(" 3 7 8 0\n");
2102 printf(" 4 8 6 10\n");
2103 printf(" 5 6 5 0\n");
2104 printf(" # One hole in the middle of the inner square.\n");
2106 printf(" 1 1.5 1.5\n\n");
2108 " Note that some segments are missing from the outer square, so one must\n");
2110 " use the `-c' switch. After `triangle -pqc box.poly', here is the output\n"
2113 " file `box.1.node', with twelve points. The last four points were added\n");
2115 " to meet the angle constraint. Points 1, 2, and 9 have markers from\n");
2117 " segment 1. Points 6 and 8 have markers from segment 4. All the other\n");
2119 " points but 4 have been marked to indicate that they lie on a boundary.\n");
2121 printf(" 12 2 0 1\n");
2122 printf(" 1 0 0 5\n");
2123 printf(" 2 0 3 5\n");
2124 printf(" 3 3 0 1\n");
2125 printf(" 4 3 3 33\n");
2126 printf(" 5 1 1 1\n");
2127 printf(" 6 1 2 10\n");
2128 printf(" 7 2 1 1\n");
2129 printf(" 8 2 2 10\n");
2130 printf(" 9 0 1.5 5\n");
2131 printf(" 10 1.5 0 1\n");
2132 printf(" 11 3 1.5 1\n");
2133 printf(" 12 1.5 3 1\n");
2134 printf(" # Generated by triangle -pqc box.poly\n\n");
2135 printf(" Here is the output file `box.1.ele', with twelve triangles.\n\n");
2136 printf(" 12 3 0\n");
2137 printf(" 1 5 6 9\n");
2138 printf(" 2 10 3 7\n");
2139 printf(" 3 6 8 12\n");
2140 printf(" 4 9 1 5\n");
2141 printf(" 5 6 2 9\n");
2142 printf(" 6 7 3 11\n");
2143 printf(" 7 11 4 8\n");
2144 printf(" 8 7 5 10\n");
2145 printf(" 9 12 2 6\n");
2146 printf(" 10 8 7 11\n");
2147 printf(" 11 5 1 10\n");
2148 printf(" 12 8 4 12\n");
2149 printf(" # Generated by triangle -pqc box.poly\n\n");
2151 " Here is the output file `box.1.poly'. Note that segments have been added\n"
2154 " to represent the convex hull, and some segments have been split by newly\n"
2157 " added points. Note also that <# of points> is set to zero to indicate\n");
2158 printf(" that the points should be read from the .node file.\n\n");
2159 printf(" 0 2 0 1\n");
2161 printf(" 1 1 9 5\n");
2162 printf(" 2 5 7 1\n");
2163 printf(" 3 8 7 1\n");
2164 printf(" 4 6 8 10\n");
2165 printf(" 5 5 6 1\n");
2166 printf(" 6 3 10 1\n");
2167 printf(" 7 4 11 1\n");
2168 printf(" 8 2 12 1\n");
2169 printf(" 9 9 2 5\n");
2170 printf(" 10 10 1 1\n");
2171 printf(" 11 11 3 1\n");
2172 printf(" 12 12 4 1\n");
2174 printf(" 1 1.5 1.5\n");
2175 printf(" # Generated by triangle -pqc box.poly\n\n");
2176 printf("Refinement and Area Constraints:\n\n");
2178 " The -r switch causes a mesh (.node and .ele files) to be read and\n");
2180 " refined. If the -p switch is also used, a .poly file is read and used to\n"
2183 " specify edges that are constrained and cannot be eliminated (although\n");
2185 " they can be divided into smaller edges) by the refinement process.\n");
2188 " When you refine a mesh, you generally want to impose tighter quality\n");
2190 " constraints. One way to accomplish this is to use -q with a larger\n");
2192 " angle, or -a followed by a smaller area than you used to generate the\n");
2194 " mesh you are refining. Another way to do this is to create an .area\n");
2196 " file, which specifies a maximum area for each triangle, and use the -a\n");
2198 " switch (without a number following). Each triangle's area constraint is\n"
2201 " applied to that triangle. Area constraints tend to diffuse as the mesh\n");
2203 " is refined, so if there are large variations in area constraint between\n");
2204 printf(" adjacent triangles, you may not get the results you want.\n\n");
2206 " If you are refining a mesh composed of linear (three-node) elements, the\n"
2209 " output mesh will contain all the nodes present in the input mesh, in the\n"
2212 " same order, with new nodes added at the end of the .node file. However,\n"
2215 " there is no guarantee that each output element is contained in a single\n");
2217 " input element. Often, output elements will overlap two input elements,\n");
2219 " and input edges are not present in the output mesh. Hence, a sequence of\n"
2222 " refined meshes will form a hierarchy of nodes, but not a hierarchy of\n");
2224 " elements. If you a refining a mesh of higher-order elements, the\n");
2226 " hierarchical property applies only to the nodes at the corners of an\n");
2227 printf(" element; other nodes may not be present in the refined mesh.\n\n");
2229 " It is important to understand that maximum area constraints in .poly\n");
2231 " files are handled differently from those in .area files. A maximum area\n"
2234 " in a .poly file applies to the whole (segment-bounded) region in which a\n"
2237 " point falls, whereas a maximum area in an .area file applies to only one\n"
2240 " triangle. Area constraints in .poly files are used only when a mesh is\n");
2242 " first generated, whereas area constraints in .area files are used only to\n"
2245 " refine an existing mesh, and are typically based on a posteriori error\n");
2247 " estimates resulting from a finite element simulation on that mesh.\n");
2250 " `triangle -rq25 object.1' will read object.1.node and object.1.ele, then\n"
2253 " refine the triangulation to enforce a 25 degree minimum angle, and then\n");
2255 " write the refined triangulation to object.2.node and object.2.ele.\n");
2258 " `triangle -rpaa6.2 z.3' will read z.3.node, z.3.ele, z.3.poly, and\n");
2260 " z.3.area. After reconstructing the mesh and its segments, Triangle will\n"
2263 " refine the mesh so that no triangle has area greater than 6.2, and\n");
2265 " furthermore the triangles satisfy the maximum area constraints in\n");
2267 " z.3.area. The output is written to z.4.node, z.4.ele, and z.4.poly.\n");
2270 " The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
2272 " x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
2273 printf(" suitable for multigrid.\n\n");
2274 printf("Convex Hulls and Mesh Boundaries:\n\n");
2276 " If the input is a point set (rather than a PSLG), Triangle produces its\n");
2278 " convex hull as a by-product in the output .poly file if you use the -c\n");
2280 " switch. There are faster algorithms for finding a two-dimensional convex\n"
2283 " hull than triangulation, of course, but this one comes for free. If the\n"
2286 " input is an unconstrained mesh (you are using the -r switch but not the\n");
2288 " -p switch), Triangle produces a list of its boundary edges (including\n");
2289 printf(" hole boundaries) as a by-product if you use the -c switch.\n\n");
2290 printf("Voronoi Diagrams:\n\n");
2292 " The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
2294 " .v.edge. For example, `triangle -v points' will read points.node,\n");
2296 " produce its Delaunay triangulation in points.1.node and points.1.ele,\n");
2298 " and produce its Voronoi diagram in points.1.v.node and points.1.v.edge.\n");
2300 " The .v.node file contains a list of all Voronoi vertices, and the .v.edge\n"
2303 " file contains a list of all Voronoi edges, some of which may be infinite\n"
2306 " rays. (The choice of filenames makes it easy to run the set of Voronoi\n");
2307 printf(" vertices through Triangle, if so desired.)\n\n");
2309 " This implementation does not use exact arithmetic to compute the Voronoi\n"
2312 " vertices, and does not check whether neighboring vertices are identical.\n"
2315 " Be forewarned that if the Delaunay triangulation is degenerate or\n");
2317 " near-degenerate, the Voronoi diagram may have duplicate points, crossing\n"
2320 " edges, or infinite rays whose direction vector is zero. Also, if you\n");
2322 " generate a constrained (as opposed to conforming) Delaunay triangulation,\n"
2325 " or if the triangulation has holes, the corresponding Voronoi diagram is\n");
2326 printf(" likely to have crossing edges and unlikely to make sense.\n\n");
2327 printf("Mesh Topology:\n\n");
2329 " You may wish to know which triangles are adjacent to a certain Delaunay\n");
2331 " edge in an .edge file, which Voronoi regions are adjacent to a certain\n");
2333 " Voronoi edge in a .v.edge file, or which Voronoi regions are adjacent to\n"
2336 " each other. All of this information can be found by cross-referencing\n");
2338 " output files with the recollection that the Delaunay triangulation and\n");
2339 printf(" the Voronoi diagrams are planar duals.\n\n");
2341 " Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
2343 " the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
2345 " wise from the Voronoi edge. Triangle j of an .ele file is the dual of\n");
2347 " vertex j of the corresponding .v.node file; and Voronoi region k is the\n");
2348 printf(" dual of point k of the corresponding .node file.\n\n");
2350 " Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
2352 " vertices of the corresponding Voronoi edge; their dual triangles are on\n");
2354 " the left and right of the Delaunay edge, respectively. To find the\n");
2356 " Voronoi regions adjacent to a Voronoi edge, look at the endpoints of the\n"
2359 " corresponding Delaunay edge; their dual regions are on the right and left\n"
2362 " of the Voronoi edge, respectively. To find which Voronoi regions are\n");
2363 printf(" adjacent to each other, just read the list of Delaunay edges.\n");
2365 printf("Statistics:\n");
2368 " After generating a mesh, Triangle prints a count of the number of points,\n"
2371 " triangles, edges, boundary edges, and segments in the output mesh. If\n");
2373 " you've forgotten the statistics for an existing mesh, the -rNEP switches\n"
2376 " (or -rpNEP if you've got a .poly file for the existing mesh) will\n");
2377 printf(" regenerate these statistics without writing any output.\n\n");
2379 " The -V switch produces extended statistics, including a rough estimate\n");
2381 " of memory use and a histogram of triangle aspect ratios and angles in the\n"
2383 printf(" mesh.\n\n");
2384 printf("Exact Arithmetic:\n\n");
2386 " Triangle uses adaptive exact arithmetic to perform what computational\n");
2388 " geometers call the `orientation' and `incircle' tests. If the floating-\n"
2391 " point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
2393 " most workstations do), and does not use extended precision internal\n");
2395 " registers, then your output is guaranteed to be an absolutely true\n");
2396 printf(" Delaunay or conforming Delaunay triangulation, roundoff error\n");
2398 " notwithstanding. The word `adaptive' implies that these arithmetic\n");
2400 " routines compute the result only to the precision necessary to guarantee\n"
2403 " correctness, so they are usually nearly as fast as their approximate\n");
2405 " counterparts. The exact tests can be disabled with the -X switch. On\n");
2407 " most inputs, this switch will reduce the computation time by about eight\n"
2410 " percent - it's not worth the risk. There are rare difficult inputs\n");
2412 " (having many collinear and cocircular points), however, for which the\n");
2414 " difference could be a factor of two. These are precisely the inputs most\n"
2416 printf(" likely to cause errors if you use the -X switch.\n\n");
2418 " Unfortunately, these routines don't solve every numerical problem. Exact\n"
2421 " arithmetic is not used to compute the positions of points, because the\n");
2423 " bit complexity of point coordinates would grow without bound. Hence,\n");
2425 " segment intersections aren't computed exactly; in very unusual cases,\n");
2427 " roundoff error in computing an intersection point might actually lead to\n"
2430 " an inverted triangle and an invalid triangulation. (This is one reason\n");
2432 " to compute your own intersection points in your .poly files.) Similarly,\n"
2435 " exact arithmetic is not used to compute the vertices of the Voronoi\n");
2436 printf(" diagram.\n\n");
2438 " Underflow and overflow can also cause difficulties; the exact arithmetic\n"
2441 " routines do not ameliorate out-of-bounds exponents, which can arise\n");
2443 " during the orientation and incircle tests. As a rule of thumb, you\n");
2445 " should ensure that your input values are within a range such that their\n");
2447 " third powers can be taken without underflow or overflow. Underflow can\n");
2449 " silently prevent the tests from being performed exactly, while overflow\n");
2450 printf(" will typically cause a floating exception.\n\n");
2451 printf("Calling Triangle from Another Program:\n\n");
2452 printf(" Read the file triangle.h for details.\n\n");
2453 printf("Troubleshooting:\n\n");
2454 printf(" Please read this section before mailing me bugs.\n\n");
2455 printf(" `My output mesh has no triangles!'\n\n");
2457 " If you're using a PSLG, you've probably failed to specify a proper set\n"
2460 " of bounding segments, or forgotten to use the -c switch. Or you may\n");
2462 " have placed a hole badly. To test these possibilities, try again with\n"
2465 " the -c and -O switches. Alternatively, all your input points may be\n");
2467 " collinear, in which case you can hardly expect to triangulate them.\n");
2469 printf(" `Triangle doesn't terminate, or just crashes.'\n");
2472 " Bad things can happen when triangles get so small that the distance\n");
2474 " between their vertices isn't much larger than the precision of your\n");
2476 " machine's arithmetic. If you've compiled Triangle for single-precision\n"
2479 " arithmetic, you might do better by recompiling it for double-precision.\n"
2482 " Then again, you might just have to settle for more lenient constraints\n"
2485 " on the minimum angle and the maximum area than you had planned.\n");
2488 " You can minimize precision problems by ensuring that the origin lies\n");
2490 " inside your point set, or even inside the densest part of your\n");
2492 " mesh. On the other hand, if you're triangulating an object whose x\n");
2494 " coordinates all fall between 6247133 and 6247134, you're not leaving\n");
2495 printf(" much floating-point precision for Triangle to work with.\n\n");
2497 " Precision problems can occur covertly if the input PSLG contains two\n");
2499 " segments that meet (or intersect) at a very small angle, or if such an\n"
2502 " angle is introduced by the -c switch, which may occur if a point lies\n");
2504 " ever-so-slightly inside the convex hull, and is connected by a PSLG\n");
2506 " segment to a point on the convex hull. If you don't realize that a\n");
2508 " small angle is being formed, you might never discover why Triangle is\n");
2510 " crashing. To check for this possibility, use the -S switch (with an\n");
2512 " appropriate limit on the number of Steiner points, found by trial-and-\n"
2515 " error) to stop Triangle early, and view the output .poly file with\n");
2517 " Show Me (described below). Look carefully for small angles between\n");
2519 " segments; zoom in closely, as such segments might look like a single\n");
2520 printf(" segment from a distance.\n\n");
2522 " If some of the input values are too large, Triangle may suffer a\n");
2524 " floating exception due to overflow when attempting to perform an\n");
2526 " orientation or incircle test. (Read the section on exact arithmetic\n");
2528 " above.) Again, I recommend compiling Triangle for double (rather\n");
2529 printf(" than single) precision arithmetic.\n\n");
2531 " `The numbering of the output points doesn't match the input points.'\n");
2534 " You may have eaten some of your input points with a hole, or by placing\n"
2536 printf(" them outside the area enclosed by segments.\n\n");
2538 " `Triangle executes without incident, but when I look at the resulting\n");
2540 " mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
2543 " If you select the -X switch, Triangle's divide-and-conquer Delaunay\n");
2545 " triangulation algorithm occasionally makes mistakes due to floating-\n");
2547 " point roundoff error. Although these errors are rare, don't use the -X\n"
2549 printf(" switch. If you still have problems, please report the bug.\n");
2552 " Strange things can happen if you've taken liberties with your PSLG. Do\n");
2554 " you have a point lying in the middle of a segment? Triangle sometimes\n");
2556 " copes poorly with that sort of thing. Do you want to lay out a collinear\n"
2559 " row of evenly spaced, segment-connected points? Have you simply defined\n"
2562 " one long segment connecting the leftmost point to the rightmost point,\n");
2564 " and a bunch of points lying along it? This method occasionally works,\n");
2566 " especially with horizontal and vertical lines, but often it doesn't, and\n"
2569 " you'll have to connect each adjacent pair of points with a separate\n");
2570 printf(" segment. If you don't like it, tough.\n\n");
2572 " Furthermore, if you have segments that intersect other than at their\n");
2574 " endpoints, try not to let the intersections fall extremely close to PSLG\n"
2576 printf(" points or each other.\n\n");
2578 " If you have problems refining a triangulation not produced by Triangle:\n");
2580 " Are you sure the triangulation is geometrically valid? Is it formatted\n");
2582 " correctly for Triangle? Are the triangles all listed so the first three\n"
2584 printf(" points are their corners in counterclockwise order?\n\n");
2585 printf("Show Me:\n\n");
2587 " Triangle comes with a separate program named `Show Me', whose primary\n");
2589 " purpose is to draw meshes on your screen or in PostScript. Its secondary\n"
2592 " purpose is to check the validity of your input files, and do so more\n");
2594 " thoroughly than Triangle does. Show Me requires that you have the X\n");
2596 " Windows system. If you didn't receive Show Me with Triangle, complain to\n"
2598 printf(" whomever you obtained Triangle from, then send me mail.\n\n");
2599 printf("Triangle on the Web:\n\n");
2601 " To see an illustrated, updated version of these instructions, check out\n");
2603 printf(" http://www.cs.cmu.edu/~quake/triangle.html\n");
2605 printf("A Brief Plea:\n");
2608 " If you use Triangle, and especially if you use it to accomplish real\n");
2610 " work, I would like very much to hear from you. A short letter or email\n");
2612 " (to jrs@cs.cmu.edu) describing how you use Triangle will mean a lot to\n");
2614 " me. The more people I know are using this program, the more easily I can\n"
2617 " justify spending time on improvements and on the three-dimensional\n");
2619 " successor to Triangle, which in turn will benefit you. Also, I can put\n");
2621 " you on a list to receive email whenever a new version of Triangle is\n");
2622 printf(" available.\n\n");
2624 " If you use a mesh generated by Triangle in a publication, please include\n"
2626 printf(" an acknowledgment as well.\n\n");
2627 printf("Research credit:\n\n");
2629 " Of course, I can take credit for only a fraction of the ideas that made\n");
2631 " this mesh generator possible. Triangle owes its existence to the efforts\n"
2634 " of many fine computational geometers and other researchers, including\n");
2636 " Marshall Bern, L. Paul Chew, Boris Delaunay, Rex A. Dwyer, David\n");
2638 " Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E. Knuth, C. L.\n");
2640 " Lawson, Der-Tsai Lee, Ernst P. Mucke, Douglas M. Priest, Jim Ruppert,\n");
2642 " Isaac Saias, Bruce J. Schachter, Micha Sharir, Jorge Stolfi, Christopher\n"
2645 " J. Van Wyk, David F. Watson, and Binhai Zhu. See the comments at the\n");
2646 printf(" beginning of the source code for references.\n\n");
2650 #endif /* not TRILIBRARY */
2652 /*****************************************************************************/
2654 /* internalerror() Ask the user to send me the defective product. Exit. */
2656 /*****************************************************************************/
2658 void internalerror()
2660 printf(" Please report this bug to jrs@cs.cmu.edu\n");
2661 printf(" Include the message above, your input data set, and the exact\n");
2662 printf(" command line you used to run Triangle.\n");
2666 /*****************************************************************************/
2668 /* parsecommandline() Read the command line, identify switches, and set */
2669 /* up options and file names. */
2671 /* The effects of this routine are felt entirely through global variables. */
2673 /*****************************************************************************/
2675 void parsecommandline(argc, argv)
2680 #define STARTINDEX 0
2681 #else /* not TRILIBRARY */
2682 #define STARTINDEX 1
2685 #endif /* not TRILIBRARY */
2689 char workstring[FILENAMESIZE];
2692 poly = refine = quality = vararea = fixedarea = regionattrib = convex = 0;
2694 edgesout = voronoi = neighbors = geomview = 0;
2695 nobound = nopolywritten = nonodewritten = noelewritten = noiterationnum = 0;
2696 noholes = noexact = 0;
2697 incremental = sweepline = 0;
2706 quiet = verbose = 0;
2708 innodefilename[0] = '\0';
2709 #endif /* not TRILIBRARY */
2711 for (i = STARTINDEX; i < argc; i++) {
2713 if (argv[i][0] == '-') {
2714 #endif /* not TRILIBRARY */
2715 for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
2716 if (argv[i][j] == 'p') {
2720 if (argv[i][j] == 'r') {
2723 if (argv[i][j] == 'q') {
2725 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2726 (argv[i][j + 1] == '.')) {
2728 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2729 (argv[i][j + 1] == '.')) {
2731 workstring[k] = argv[i][j];
2734 workstring[k] = '\0';
2735 minangle = (REAL) strtod(workstring, (char **) NULL);
2740 if (argv[i][j] == 'a') {
2742 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2743 (argv[i][j + 1] == '.')) {
2746 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2747 (argv[i][j + 1] == '.')) {
2749 workstring[k] = argv[i][j];
2752 workstring[k] = '\0';
2753 maxarea = (REAL) strtod(workstring, (char **) NULL);
2754 if (maxarea <= 0.0) {
2755 printf("Error: Maximum area must be greater than zero.\n");
2762 #endif /* not CDT_ONLY */
2763 if (argv[i][j] == 'A') {
2766 if (argv[i][j] == 'c') {
2769 if (argv[i][j] == 'z') {
2772 if (argv[i][j] == 'e') {
2775 if (argv[i][j] == 'v') {
2778 if (argv[i][j] == 'n') {
2781 if (argv[i][j] == 'g') {
2784 if (argv[i][j] == 'B') {
2787 if (argv[i][j] == 'P') {
2790 if (argv[i][j] == 'N') {
2793 if (argv[i][j] == 'E') {
2797 if (argv[i][j] == 'I') {
2800 #endif /* not TRILIBRARY */
2801 if (argv[i][j] == 'O') {
2804 if (argv[i][j] == 'X') {
2807 if (argv[i][j] == 'o') {
2808 if (argv[i][j + 1] == '2') {
2814 if (argv[i][j] == 'Y') {
2817 if (argv[i][j] == 'S') {
2819 while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
2821 steiner = steiner * 10 + (int) (argv[i][j] - '0');
2824 #endif /* not CDT_ONLY */
2826 if (argv[i][j] == 'i') {
2829 if (argv[i][j] == 'F') {
2832 #endif /* not REDUCED */
2833 if (argv[i][j] == 'l') {
2838 if (argv[i][j] == 's') {
2841 #endif /* not CDT_ONLY */
2842 if (argv[i][j] == 'C') {
2845 #endif /* not REDUCED */
2846 if (argv[i][j] == 'Q') {
2849 if (argv[i][j] == 'V') {
2853 if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
2854 (argv[i][j] == '?')) {
2857 #endif /* not TRILIBRARY */
2861 strncpy(innodefilename, argv[i], FILENAMESIZE - 1);
2862 innodefilename[FILENAMESIZE - 1] = '\0';
2864 #endif /* not TRILIBRARY */
2867 if (innodefilename[0] == '\0') {
2870 if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".node")) {
2871 innodefilename[strlen(innodefilename) - 5] = '\0';
2873 if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".poly")) {
2874 innodefilename[strlen(innodefilename) - 5] = '\0';
2878 if (!strcmp(&innodefilename[strlen(innodefilename) - 4], ".ele")) {
2879 innodefilename[strlen(innodefilename) - 4] = '\0';
2882 if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".area")) {
2883 innodefilename[strlen(innodefilename) - 5] = '\0';
2888 #endif /* not CDT_ONLY */
2889 #endif /* not TRILIBRARY */
2890 steinerleft = steiner;
2891 useshelles = poly || refine || quality || convex;
2892 goodangle = (REAL)cos(minangle * PI / 180.0);
2893 goodangle *= goodangle;
2894 if (refine && noiterationnum) {
2896 "Error: You cannot use the -I switch when refining a triangulation.\n");
2899 /* Be careful not to allocate space for element area constraints that */
2900 /* will never be assigned any value (other than the default -1.0). */
2901 if (!refine && !poly) {
2904 /* Be careful not to add an extra attribute to each element unless the */
2905 /* input supports it (PSLG in, but not refining a preexisting mesh). */
2906 if (refine || !poly) {
2911 strcpy(inpolyfilename, innodefilename);
2912 strcpy(inelefilename, innodefilename);
2913 strcpy(areafilename, innodefilename);
2915 strcpy(workstring, innodefilename);
2917 while (workstring[j] != '\0') {
2918 if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
2924 if (increment > 0) {
2927 if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
2928 meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
2933 } while (workstring[j] != '\0');
2935 if (noiterationnum) {
2936 strcpy(outnodefilename, innodefilename);
2937 strcpy(outelefilename, innodefilename);
2938 strcpy(edgefilename, innodefilename);
2939 strcpy(vnodefilename, innodefilename);
2940 strcpy(vedgefilename, innodefilename);
2941 strcpy(neighborfilename, innodefilename);
2942 strcpy(offfilename, innodefilename);
2943 strcat(outnodefilename, ".node");
2944 strcat(outelefilename, ".ele");
2945 strcat(edgefilename, ".edge");
2946 strcat(vnodefilename, ".v.node");
2947 strcat(vedgefilename, ".v.edge");
2948 strcat(neighborfilename, ".neigh");
2949 strcat(offfilename, ".off");
2950 } else if (increment == 0) {
2951 strcpy(outnodefilename, innodefilename);
2952 strcpy(outpolyfilename, innodefilename);
2953 strcpy(outelefilename, innodefilename);
2954 strcpy(edgefilename, innodefilename);
2955 strcpy(vnodefilename, innodefilename);
2956 strcpy(vedgefilename, innodefilename);
2957 strcpy(neighborfilename, innodefilename);
2958 strcpy(offfilename, innodefilename);
2959 strcat(outnodefilename, ".1.node");
2960 strcat(outpolyfilename, ".1.poly");
2961 strcat(outelefilename, ".1.ele");
2962 strcat(edgefilename, ".1.edge");
2963 strcat(vnodefilename, ".1.v.node");
2964 strcat(vedgefilename, ".1.v.edge");
2965 strcat(neighborfilename, ".1.neigh");
2966 strcat(offfilename, ".1.off");
2968 workstring[increment] = '%';
2969 workstring[increment + 1] = 'd';
2970 workstring[increment + 2] = '\0';
2971 sprintf(outnodefilename, workstring, meshnumber + 1);
2972 strcpy(outpolyfilename, outnodefilename);
2973 strcpy(outelefilename, outnodefilename);
2974 strcpy(edgefilename, outnodefilename);
2975 strcpy(vnodefilename, outnodefilename);
2976 strcpy(vedgefilename, outnodefilename);
2977 strcpy(neighborfilename, outnodefilename);
2978 strcpy(offfilename, outnodefilename);
2979 strcat(outnodefilename, ".node");
2980 strcat(outpolyfilename, ".poly");
2981 strcat(outelefilename, ".ele");
2982 strcat(edgefilename, ".edge");
2983 strcat(vnodefilename, ".v.node");
2984 strcat(vedgefilename, ".v.edge");
2985 strcat(neighborfilename, ".neigh");
2986 strcat(offfilename, ".off");
2988 strcat(innodefilename, ".node");
2989 strcat(inpolyfilename, ".poly");
2990 strcat(inelefilename, ".ele");
2991 strcat(areafilename, ".area");
2992 #endif /* not TRILIBRARY */
2997 /********* User interaction routines begin here *********/
2999 /********* Debugging routines begin here *********/
3003 /*****************************************************************************/
3005 /* printtriangle() Print out the details of a triangle/edge handle. */
3007 /* I originally wrote this procedure to simplify debugging; it can be */
3008 /* called directly from the debugger, and presents information about a */
3009 /* triangle/edge handle in digestible form. It's also used when the */
3010 /* highest level of verbosity (`-VVV') is specified. */
3012 /*****************************************************************************/
3014 void printtriangle(t)
3017 struct triedge printtri;
3018 struct edge printsh;
3021 printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
3023 decode(t->tri[0], printtri);
3024 if (printtri.tri == dummytri) {
3025 printf(" [0] = Outer space\n");
3027 printf(" [0] = x%lx %d\n", (unsigned long) printtri.tri,
3030 decode(t->tri[1], printtri);
3031 if (printtri.tri == dummytri) {
3032 printf(" [1] = Outer space\n");
3034 printf(" [1] = x%lx %d\n", (unsigned long) printtri.tri,
3037 decode(t->tri[2], printtri);
3038 if (printtri.tri == dummytri) {
3039 printf(" [2] = Outer space\n");
3041 printf(" [2] = x%lx %d\n", (unsigned long) printtri.tri,
3044 org(*t, printpoint);
3045 if (printpoint == (point) NULL)
3046 printf(" Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
3048 printf(" Origin[%d] = x%lx (%.12g, %.12g)\n",
3049 (t->orient + 1) % 3 + 3, (unsigned long) printpoint,
3050 printpoint[0], printpoint[1]);
3051 dest(*t, printpoint);
3052 if (printpoint == (point) NULL)
3053 printf(" Dest [%d] = NULL\n", (t->orient + 2) % 3 + 3);
3055 printf(" Dest [%d] = x%lx (%.12g, %.12g)\n",
3056 (t->orient + 2) % 3 + 3, (unsigned long) printpoint,
3057 printpoint[0], printpoint[1]);
3058 apex(*t, printpoint);
3059 if (printpoint == (point) NULL)
3060 printf(" Apex [%d] = NULL\n", t->orient + 3);
3062 printf(" Apex [%d] = x%lx (%.12g, %.12g)\n",
3063 t->orient + 3, (unsigned long) printpoint,
3064 printpoint[0], printpoint[1]);
3066 sdecode(t->tri[6], printsh);
3067 if (printsh.sh != dummysh) {
3068 printf(" [6] = x%lx %d\n", (unsigned long) printsh.sh,
3071 sdecode(t->tri[7], printsh);
3072 if (printsh.sh != dummysh) {
3073 printf(" [7] = x%lx %d\n", (unsigned long) printsh.sh,
3076 sdecode(t->tri[8], printsh);
3077 if (printsh.sh != dummysh) {
3078 printf(" [8] = x%lx %d\n", (unsigned long) printsh.sh,
3083 printf(" Area constraint: %.4g\n", areabound(*t));
3087 /*****************************************************************************/
3089 /* printshelle() Print out the details of a shell edge handle. */
3091 /* I originally wrote this procedure to simplify debugging; it can be */
3092 /* called directly from the debugger, and presents information about a */
3093 /* shell edge handle in digestible form. It's also used when the highest */
3094 /* level of verbosity (`-VVV') is specified. */
3096 /*****************************************************************************/
3101 struct edge printsh;
3102 struct triedge printtri;
3105 printf("shell edge x%lx with orientation %d and mark %d:\n",
3106 (unsigned long) s->sh, s->shorient, mark(*s));
3107 sdecode(s->sh[0], printsh);
3108 if (printsh.sh == dummysh) {
3109 printf(" [0] = No shell\n");
3111 printf(" [0] = x%lx %d\n", (unsigned long) printsh.sh,
3114 sdecode(s->sh[1], printsh);
3115 if (printsh.sh == dummysh) {
3116 printf(" [1] = No shell\n");
3118 printf(" [1] = x%lx %d\n", (unsigned long) printsh.sh,
3121 sorg(*s, printpoint);
3122 if (printpoint == (point) NULL)
3123 printf(" Origin[%d] = NULL\n", 2 + s->shorient);
3125 printf(" Origin[%d] = x%lx (%.12g, %.12g)\n",
3126 2 + s->shorient, (unsigned long) printpoint,
3127 printpoint[0], printpoint[1]);
3128 sdest(*s, printpoint);
3129 if (printpoint == (point) NULL)
3130 printf(" Dest [%d] = NULL\n", 3 - s->shorient);
3132 printf(" Dest [%d] = x%lx (%.12g, %.12g)\n",
3133 3 - s->shorient, (unsigned long) printpoint,
3134 printpoint[0], printpoint[1]);
3135 decode(s->sh[4], printtri);
3136 if (printtri.tri == dummytri) {
3137 printf(" [4] = Outer space\n");
3139 printf(" [4] = x%lx %d\n", (unsigned long) printtri.tri,
3142 decode(s->sh[5], printtri);
3143 if (printtri.tri == dummytri) {
3144 printf(" [5] = Outer space\n");
3146 printf(" [5] = x%lx %d\n", (unsigned long) printtri.tri,
3153 /********* Debugging routines end here *********/
3155 /********* Memory management routines begin here *********/
3159 /*****************************************************************************/
3161 /* poolinit() Initialize a pool of memory for allocation of items. */
3163 /* This routine initializes the machinery for allocating items. A `pool' */
3164 /* is created whose records have size at least `bytecount'. Items will be */
3165 /* allocated in `itemcount'-item blocks. Each item is assumed to be a */
3166 /* collection of words, and either pointers or floating-point values are */
3167 /* assumed to be the "primary" word type. (The "primary" word type is used */
3168 /* to determine alignment of items.) If `alignment' isn't zero, all items */
3169 /* will be `alignment'-byte aligned in memory. `alignment' must be either */
3170 /* a multiple or a factor of the primary word size; powers of two are safe. */
3171 /* `alignment' is normally used to create a few unused bits at the bottom */
3172 /* of each item's pointer, in which information may be stored. */
3174 /* Don't change this routine unless you understand it. */
3176 /*****************************************************************************/
3178 void poolinit(pool, bytecount, itemcount, wtype, alignment)
3179 struct memorypool *pool;
3182 enum wordtype wtype;
3187 /* Initialize values in the pool. */
3188 pool->itemwordtype = wtype;
3189 wordsize = (pool->itemwordtype == POINTER) ? sizeof(VOID *) : sizeof(REAL);
3190 /* Find the proper alignment, which must be at least as large as: */
3191 /* - The parameter `alignment'. */
3192 /* - The primary word type, to avoid unaligned accesses. */
3193 /* - sizeof(VOID *), so the stack of dead items can be maintained */
3194 /* without unaligned accesses. */
3195 if (alignment > wordsize) {
3196 pool->alignbytes = alignment;
3198 pool->alignbytes = wordsize;
3200 if (sizeof(VOID *) > pool->alignbytes) {
3201 pool->alignbytes = sizeof(VOID *);
3203 pool->itemwords = ((bytecount + pool->alignbytes - 1) / pool->alignbytes)
3204 * (pool->alignbytes / wordsize);
3205 pool->itembytes = pool->itemwords * wordsize;
3206 pool->itemsperblock = itemcount;
3208 /* Allocate a block of items. Space for `itemsperblock' items and one */
3209 /* pointer (to point to the next block) are allocated, as well as space */
3210 /* to ensure alignment of the items. */
3211 pool->firstblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes
3212 + sizeof(VOID *) + pool->alignbytes);
3213 if (pool->firstblock == (VOID **) NULL) {
3214 printf("Error: Out of memory.\n");
3217 /* Set the next block pointer to NULL. */
3218 *(pool->firstblock) = (VOID *) NULL;
3222 /*****************************************************************************/
3224 /* poolrestart() Deallocate all items in a pool. */
3226 /* The pool is returned to its starting state, except that no memory is */
3227 /* freed to the operating system. Rather, the previously allocated blocks */
3228 /* are ready to be reused. */
3230 /*****************************************************************************/
3232 void poolrestart(pool)
3233 struct memorypool *pool;
3235 unsigned long alignptr;
3240 /* Set the currently active block. */
3241 pool->nowblock = pool->firstblock;
3242 /* Find the first item in the pool. Increment by the size of (VOID *). */
3243 alignptr = (unsigned long) (pool->nowblock + 1);
3244 /* Align the item on an `alignbytes'-byte boundary. */
3245 pool->nextitem = (VOID *)
3246 (alignptr + (unsigned long) pool->alignbytes
3247 - (alignptr % (unsigned long) pool->alignbytes));
3248 /* There are lots of unallocated items left in this block. */
3249 pool->unallocateditems = pool->itemsperblock;
3250 /* The stack of deallocated items is empty. */
3251 pool->deaditemstack = (VOID *) NULL;
3254 /*****************************************************************************/
3256 /* pooldeinit() Free to the operating system all memory taken by a pool. */
3258 /*****************************************************************************/
3260 void pooldeinit(pool)
3261 struct memorypool *pool;
3263 while (pool->firstblock != (VOID **) NULL) {
3264 pool->nowblock = (VOID **) *(pool->firstblock);
3265 free(pool->firstblock);
3266 pool->firstblock = pool->nowblock;
3270 /*****************************************************************************/
3272 /* poolalloc() Allocate space for an item. */
3274 /*****************************************************************************/
3276 VOID *poolalloc(pool)
3277 struct memorypool *pool;
3281 unsigned long alignptr;
3283 /* First check the linked list of dead items. If the list is not */
3284 /* empty, allocate an item from the list rather than a fresh one. */
3285 if (pool->deaditemstack != (VOID *) NULL) {
3286 newitem = pool->deaditemstack; /* Take first item in list. */
3287 pool->deaditemstack = * (VOID **) pool->deaditemstack;
3289 /* Check if there are any free items left in the current block. */
3290 if (pool->unallocateditems == 0) {
3291 /* Check if another block must be allocated. */
3292 if (*(pool->nowblock) == (VOID *) NULL) {
3293 /* Allocate a new block of items, pointed to by the previous block. */
3294 newblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes
3295 + sizeof(VOID *) + pool->alignbytes);
3296 if (newblock == (VOID **) NULL) {
3297 printf("Error: Out of memory.\n");
3300 *(pool->nowblock) = (VOID *) newblock;
3301 /* The next block pointer is NULL. */
3302 *newblock = (VOID *) NULL;
3304 /* Move to the new block. */
3305 pool->nowblock = (VOID **) *(pool->nowblock);
3306 /* Find the first item in the block. */
3307 /* Increment by the size of (VOID *). */
3308 alignptr = (unsigned long) (pool->nowblock + 1);
3309 /* Align the item on an `alignbytes'-byte boundary. */
3310 pool->nextitem = (VOID *)
3311 (alignptr + (unsigned long) pool->alignbytes
3312 - (alignptr % (unsigned long) pool->alignbytes));
3313 /* There are lots of unallocated items left in this block. */
3314 pool->unallocateditems = pool->itemsperblock;
3316 /* Allocate a new item. */
3317 newitem = pool->nextitem;
3318 /* Advance `nextitem' pointer to next free item in block. */
3319 if (pool->itemwordtype == POINTER) {
3320 pool->nextitem = (VOID *) ((VOID **) pool->nextitem + pool->itemwords);
3322 pool->nextitem = (VOID *) ((REAL *) pool->nextitem + pool->itemwords);
3324 pool->unallocateditems--;
3331 /*****************************************************************************/
3333 /* pooldealloc() Deallocate space for an item. */
3335 /* The deallocated space is stored in a queue for later reuse. */
3337 /*****************************************************************************/
3339 void pooldealloc(pool, dyingitem)
3340 struct memorypool *pool;
3343 /* Push freshly killed item onto stack. */
3344 *((VOID **) dyingitem) = pool->deaditemstack;
3345 pool->deaditemstack = dyingitem;
3349 /*****************************************************************************/
3351 /* traversalinit() Prepare to traverse the entire list of items. */
3353 /* This routine is used in conjunction with traverse(). */
3355 /*****************************************************************************/
3357 void traversalinit(pool)
3358 struct memorypool *pool;
3360 unsigned long alignptr;
3362 /* Begin the traversal in the first block. */
3363 pool->pathblock = pool->firstblock;
3364 /* Find the first item in the block. Increment by the size of (VOID *). */
3365 alignptr = (unsigned long) (pool->pathblock + 1);
3366 /* Align with item on an `alignbytes'-byte boundary. */
3367 pool->pathitem = (VOID *)
3368 (alignptr + (unsigned long) pool->alignbytes
3369 - (alignptr % (unsigned long) pool->alignbytes));
3370 /* Set the number of items left in the current block. */
3371 pool->pathitemsleft = pool->itemsperblock;
3374 /*****************************************************************************/
3376 /* traverse() Find the next item in the list. */
3378 /* This routine is used in conjunction with traversalinit(). Be forewarned */
3379 /* that this routine successively returns all items in the list, including */
3380 /* deallocated ones on the deaditemqueue. It's up to you to figure out */
3381 /* which ones are actually dead. Why? I don't want to allocate extra */
3382 /* space just to demarcate dead items. It can usually be done more */
3383 /* space-efficiently by a routine that knows something about the structure */
3386 /*****************************************************************************/
3388 VOID *traverse(pool)
3389 struct memorypool *pool;
3392 unsigned long alignptr;
3394 /* Stop upon exhausting the list of items. */
3395 if (pool->pathitem == pool->nextitem) {
3396 return (VOID *) NULL;
3398 /* Check whether any untraversed items remain in the current block. */
3399 if (pool->pathitemsleft == 0) {
3400 /* Find the next block. */
3401 pool->pathblock = (VOID **) *(pool->pathblock);
3402 /* Find the first item in the block. Increment by the size of (VOID *). */
3403 alignptr = (unsigned long) (pool->pathblock + 1);
3404 /* Align with item on an `alignbytes'-byte boundary. */
3405 pool->pathitem = (VOID *)
3406 (alignptr + (unsigned long) pool->alignbytes
3407 - (alignptr % (unsigned long) pool->alignbytes));
3408 /* Set the number of items left in the current block. */
3409 pool->pathitemsleft = pool->itemsperblock;
3411 newitem = pool->pathitem;
3412 /* Find the next item in the block. */
3413 if (pool->itemwordtype == POINTER) {
3414 pool->pathitem = (VOID *) ((VOID **) pool->pathitem + pool->itemwords);
3416 pool->pathitem = (VOID *) ((REAL *) pool->pathitem + pool->itemwords);
3418 pool->pathitemsleft--;
3422 /*****************************************************************************/
3424 /* dummyinit() Initialize the triangle that fills "outer space" and the */
3425 /* omnipresent shell edge. */
3427 /* The triangle that fills "outer space", called `dummytri', is pointed to */
3428 /* by every triangle and shell edge on a boundary (be it outer or inner) of */
3429 /* the triangulation. Also, `dummytri' points to one of the triangles on */
3430 /* the convex hull (until the holes and concavities are carved), making it */
3431 /* possible to find a starting triangle for point location. */
3433 /* The omnipresent shell edge, `dummysh', is pointed to by every triangle */
3434 /* or shell edge that doesn't have a full complement of real shell edges */
3437 /*****************************************************************************/
3439 void dummyinit(trianglewords, shellewords)
3443 unsigned long alignptr;
3445 /* `triwords' and `shwords' are used by the mesh manipulation primitives */
3446 /* to extract orientations of triangles and shell edges from pointers. */
3447 triwords = trianglewords; /* Initialize `triwords' once and for all. */
3448 shwords = shellewords; /* Initialize `shwords' once and for all. */
3450 /* Set up `dummytri', the `triangle' that occupies "outer space". */
3451 dummytribase = (triangle *) malloc(triwords * sizeof(triangle)
3452 + triangles.alignbytes);
3453 if (dummytribase == (triangle *) NULL) {
3454 printf("Error: Out of memory.\n");
3457 /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
3458 alignptr = (unsigned long) dummytribase;
3459 dummytri = (triangle *)
3460 (alignptr + (unsigned long) triangles.alignbytes
3461 - (alignptr % (unsigned long) triangles.alignbytes));
3462 /* Initialize the three adjoining triangles to be "outer space". These */
3463 /* will eventually be changed by various bonding operations, but their */
3464 /* values don't really matter, as long as they can legally be */
3466 dummytri[0] = (triangle) dummytri;
3467 dummytri[1] = (triangle) dummytri;
3468 dummytri[2] = (triangle) dummytri;
3469 /* Three NULL vertex points. */
3470 dummytri[3] = (triangle) NULL;
3471 dummytri[4] = (triangle) NULL;
3472 dummytri[5] = (triangle) NULL;
3475 /* Set up `dummysh', the omnipresent "shell edge" pointed to by any */
3476 /* triangle side or shell edge end that isn't attached to a real shell */
3478 dummyshbase = (shelle *) malloc(shwords * sizeof(shelle)
3479 + shelles.alignbytes);
3480 if (dummyshbase == (shelle *) NULL) {
3481 printf("Error: Out of memory.\n");
3484 /* Align `dummysh' on a `shelles.alignbytes'-byte boundary. */
3485 alignptr = (unsigned long) dummyshbase;
3486 dummysh = (shelle *)
3487 (alignptr + (unsigned long) shelles.alignbytes
3488 - (alignptr % (unsigned long) shelles.alignbytes));
3489 /* Initialize the two adjoining shell edges to be the omnipresent shell */
3490 /* edge. These will eventually be changed by various bonding */
3491 /* operations, but their values don't really matter, as long as they */
3492 /* can legally be dereferenced. */
3493 dummysh[0] = (shelle) dummysh;
3494 dummysh[1] = (shelle) dummysh;
3495 /* Two NULL vertex points. */
3496 dummysh[2] = (shelle) NULL;
3497 dummysh[3] = (shelle) NULL;
3498 /* Initialize the two adjoining triangles to be "outer space". */
3499 dummysh[4] = (shelle) dummytri;
3500 dummysh[5] = (shelle) dummytri;
3501 /* Set the boundary marker to zero. */
3502 * (int *) (dummysh + 6) = 0;
3504 /* Initialize the three adjoining shell edges of `dummytri' to be */
3505 /* the omnipresent shell edge. */
3506 dummytri[6] = (triangle) dummysh;
3507 dummytri[7] = (triangle) dummysh;
3508 dummytri[8] = (triangle) dummysh;
3512 /*****************************************************************************/
3514 /* initializepointpool() Calculate the size of the point data structure */
3515 /* and initialize its memory pool. */
3517 /* This routine also computes the `pointmarkindex' and `point2triindex' */
3518 /* indices used to find values within each point. */
3520 /*****************************************************************************/
3522 void initializepointpool()
3526 /* The index within each point at which the boundary marker is found. */
3527 /* Ensure the point marker is aligned to a sizeof(int)-byte address. */
3528 pointmarkindex = ((mesh_dim + nextras) * sizeof(REAL) + sizeof(int) - 1)
3530 pointsize = (pointmarkindex + 1) * sizeof(int);
3532 /* The index within each point at which a triangle pointer is found. */
3533 /* Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
3534 point2triindex = (pointsize + sizeof(triangle) - 1) / sizeof(triangle);
3535 pointsize = (point2triindex + 1) * sizeof(triangle);
3537 /* Initialize the pool of points. */
3538 poolinit(&points, pointsize, POINTPERBLOCK,
3539 (sizeof(REAL) >= sizeof(triangle)) ? FLOATINGPOINT : POINTER, 0);
3542 /*****************************************************************************/
3544 /* initializetrisegpools() Calculate the sizes of the triangle and shell */
3545 /* edge data structures and initialize their */
3548 /* This routine also computes the `highorderindex', `elemattribindex', and */
3549 /* `areaboundindex' indices used to find values within each triangle. */
3551 /*****************************************************************************/
3553 void initializetrisegpools()
3557 /* The index within each triangle at which the extra nodes (above three) */
3558 /* associated with high order elements are found. There are three */
3559 /* pointers to other triangles, three pointers to corners, and possibly */
3560 /* three pointers to shell edges before the extra nodes. */
3561 highorderindex = 6 + (useshelles * 3);
3562 /* The number of bytes occupied by a triangle. */
3563 trisize = ((order + 1) * (order + 2) / 2 + (highorderindex - 3)) *
3565 /* The index within each triangle at which its attributes are found, */
3566 /* where the index is measured in REALs. */
3567 elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
3568 /* The index within each triangle at which the maximum area constraint */
3569 /* is found, where the index is measured in REALs. Note that if the */
3570 /* `regionattrib' flag is set, an additional attribute will be added. */
3571 areaboundindex = elemattribindex + eextras + regionattrib;
3572 /* If triangle attributes or an area bound are needed, increase the number */
3573 /* of bytes occupied by a triangle. */
3575 trisize = (areaboundindex + 1) * sizeof(REAL);
3576 } else if (eextras + regionattrib > 0) {
3577 trisize = areaboundindex * sizeof(REAL);
3579 /* If a Voronoi diagram or triangle neighbor graph is requested, make */
3580 /* sure there's room to store an integer index in each triangle. This */
3581 /* integer index can occupy the same space as the shell edges or */
3582 /* attributes or area constraint or extra nodes. */
3583 if ((voronoi || neighbors) &&
3584 (trisize < 6 * sizeof(triangle) + sizeof(int))) {
3585 trisize = 6 * sizeof(triangle) + sizeof(int);
3587 /* Having determined the memory size of a triangle, initialize the pool. */
3588 poolinit(&triangles, trisize, TRIPERBLOCK, POINTER, 4);
3591 /* Initialize the pool of shell edges. */
3592 poolinit(&shelles, 6 * sizeof(triangle) + sizeof(int), SHELLEPERBLOCK,
3595 /* Initialize the "outer space" triangle and omnipresent shell edge. */
3596 dummyinit(triangles.itemwords, shelles.itemwords);
3598 /* Initialize the "outer space" triangle. */
3599 dummyinit(triangles.itemwords, 0);
3603 /*****************************************************************************/
3605 /* triangledealloc() Deallocate space for a triangle, marking it dead. */
3607 /*****************************************************************************/
3609 void triangledealloc(dyingtriangle)
3610 triangle *dyingtriangle;
3612 /* Set triangle's vertices to NULL. This makes it possible to */
3613 /* detect dead triangles when traversing the list of all triangles. */
3614 dyingtriangle[3] = (triangle) NULL;
3615 dyingtriangle[4] = (triangle) NULL;
3616 dyingtriangle[5] = (triangle) NULL;
3617 pooldealloc(&triangles, (VOID *) dyingtriangle);
3620 /*****************************************************************************/
3622 /* triangletraverse() Traverse the triangles, skipping dead ones. */
3624 /*****************************************************************************/
3626 triangle *triangletraverse()
3628 triangle *newtriangle;
3631 newtriangle = (triangle *) traverse(&triangles);
3632 if (newtriangle == (triangle *) NULL) {
3633 return (triangle *) NULL;
3635 } while (newtriangle[3] == (triangle) NULL); /* Skip dead ones. */
3639 /*****************************************************************************/
3641 /* shelledealloc() Deallocate space for a shell edge, marking it dead. */
3643 /*****************************************************************************/
3645 void shelledealloc(dyingshelle)
3646 shelle *dyingshelle;
3648 /* Set shell edge's vertices to NULL. This makes it possible to */
3649 /* detect dead shells when traversing the list of all shells. */
3650 dyingshelle[2] = (shelle) NULL;
3651 dyingshelle[3] = (shelle) NULL;
3652 pooldealloc(&shelles, (VOID *) dyingshelle);
3655 /*****************************************************************************/
3657 /* shelletraverse() Traverse the shell edges, skipping dead ones. */
3659 /*****************************************************************************/
3661 shelle *shelletraverse()
3666 newshelle = (shelle *) traverse(&shelles);
3667 if (newshelle == (shelle *) NULL) {
3668 return (shelle *) NULL;
3670 } while (newshelle[2] == (shelle) NULL); /* Skip dead ones. */
3674 /*****************************************************************************/
3676 /* pointdealloc() Deallocate space for a point, marking it dead. */
3678 /*****************************************************************************/
3680 void pointdealloc(dyingpoint)
3683 /* Mark the point as dead. This makes it possible to detect dead points */
3684 /* when traversing the list of all points. */
3685 setpointmark(dyingpoint, DEADPOINT);
3686 pooldealloc(&points, (VOID *) dyingpoint);
3689 /*****************************************************************************/
3691 /* pointtraverse() Traverse the points, skipping dead ones. */
3693 /*****************************************************************************/
3695 point pointtraverse()
3700 newpoint = (point) traverse(&points);
3701 if (newpoint == (point) NULL) {
3702 return (point) NULL;
3704 } while (pointmark(newpoint) == DEADPOINT); /* Skip dead ones. */
3708 /*****************************************************************************/
3710 /* badsegmentdealloc() Deallocate space for a bad segment, marking it */
3713 /*****************************************************************************/
3717 void badsegmentdealloc(dyingseg)
3718 struct edge *dyingseg;
3720 /* Set segment's orientation to -1. This makes it possible to */
3721 /* detect dead segments when traversing the list of all segments. */
3722 dyingseg->shorient = -1;
3723 pooldealloc(&badsegments, (VOID *) dyingseg);
3726 #endif /* not CDT_ONLY */
3728 /*****************************************************************************/
3730 /* badsegmenttraverse() Traverse the bad segments, skipping dead ones. */
3732 /*****************************************************************************/
3736 struct edge *badsegmenttraverse()
3738 struct edge *newseg;
3741 newseg = (struct edge *) traverse(&badsegments);
3742 if (newseg == (struct edge *) NULL) {
3743 return (struct edge *) NULL;
3745 } while (newseg->shorient == -1); /* Skip dead ones. */
3749 #endif /* not CDT_ONLY */
3751 /*****************************************************************************/
3753 /* getpoint() Get a specific point, by number, from the list. */
3755 /* The first point is number 'firstnumber'. */
3757 /* Note that this takes O(n) time (with a small constant, if POINTPERBLOCK */
3758 /* is large). I don't care to take the trouble to make it work in constant */
3761 /*****************************************************************************/
3763 point getpoint(number)
3768 unsigned long alignptr;
3771 getblock = points.firstblock;
3772 current = firstnumber;
3773 /* Find the right block. */
3774 while (current + points.itemsperblock <= number) {
3775 getblock = (VOID **) *getblock;
3776 current += points.itemsperblock;
3778 /* Now find the right point. */
3779 alignptr = (unsigned long) (getblock + 1);
3780 foundpoint = (point) (alignptr + (unsigned long) points.alignbytes
3781 - (alignptr % (unsigned long) points.alignbytes));
3782 while (current < number) {
3783 foundpoint += points.itemwords;
3789 /*****************************************************************************/
3791 /* triangledeinit() Free all remaining allocated memory. */
3793 /*****************************************************************************/
3795 void triangledeinit()
3797 pooldeinit(&triangles);
3800 pooldeinit(&shelles);
3803 pooldeinit(&points);
3806 pooldeinit(&badsegments);
3807 if ((minangle > 0.0) || vararea || fixedarea) {
3808 pooldeinit(&badtriangles);
3811 #endif /* not CDT_ONLY */
3816 /********* Memory management routines end here *********/
3818 /********* Constructors begin here *********/
3822 /*****************************************************************************/
3824 /* maketriangle() Create a new triangle with orientation zero. */
3826 /*****************************************************************************/
3828 void maketriangle(newtriedge)
3829 struct triedge *newtriedge;
3833 newtriedge->tri = (triangle *) poolalloc(&triangles);
3834 /* Initialize the three adjoining triangles to be "outer space". */
3835 newtriedge->tri[0] = (triangle) dummytri;
3836 newtriedge->tri[1] = (triangle) dummytri;
3837 newtriedge->tri[2] = (triangle) dummytri;
3838 /* Three NULL vertex points. */
3839 newtriedge->tri[3] = (triangle) NULL;
3840 newtriedge->tri[4] = (triangle) NULL;
3841 newtriedge->tri[5] = (triangle) NULL;
3842 /* Initialize the three adjoining shell edges to be the omnipresent */
3845 newtriedge->tri[6] = (triangle) dummysh;
3846 newtriedge->tri[7] = (triangle) dummysh;
3847 newtriedge->tri[8] = (triangle) dummysh;
3849 for (i = 0; i < eextras; i++) {
3850 setelemattribute(*newtriedge, i, 0.0);
3853 setareabound(*newtriedge, -1.0);
3856 newtriedge->orient = 0;
3859 /*****************************************************************************/
3861 /* makeshelle() Create a new shell edge with orientation zero. */
3863 /*****************************************************************************/
3865 void makeshelle(newedge)
3866 struct edge *newedge;
3868 newedge->sh = (shelle *) poolalloc(&shelles);
3869 /* Initialize the two adjoining shell edges to be the omnipresent */
3871 newedge->sh[0] = (shelle) dummysh;
3872 newedge->sh[1] = (shelle) dummysh;
3873 /* Two NULL vertex points. */
3874 newedge->sh[2] = (shelle) NULL;
3875 newedge->sh[3] = (shelle) NULL;
3876 /* Initialize the two adjoining triangles to be "outer space". */
3877 newedge->sh[4] = (shelle) dummytri;
3878 newedge->sh[5] = (shelle) dummytri;
3879 /* Set the boundary marker to zero. */
3880 setmark(*newedge, 0);
3882 newedge->shorient = 0;
3887 /********* Constructors end here *********/
3889 /********* Determinant evaluation routines begin here *********/
3893 /* The adaptive exact arithmetic geometric predicates implemented herein are */
3894 /* described in detail in my Technical Report CMU-CS-96-140. The complete */
3895 /* reference is given in the header. */
3897 /* Which of the following two methods of finding the absolute values is */
3898 /* fastest is compiler-dependent. A few compilers can inline and optimize */
3899 /* the fabs() call; but most will incur the overhead of a function call, */
3900 /* which is disastrously slow. A faster way on IEEE machines might be to */
3901 /* mask the appropriate bit, but that's difficult to do in C. */
3903 #define Absolute(a) ((a) >= 0.0 ? (a) : -(a))
3904 /* #define Absolute(a) fabs(a) */
3906 /* Many of the operations are broken up into two pieces, a main part that */
3907 /* performs an approximate operation, and a "tail" that computes the */
3908 /* roundoff error of that operation. */
3910 /* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(), */
3911 /* Split(), and Two_Product() are all implemented as described in the */
3912 /* reference. Each of these macros requires certain variables to be */
3913 /* defined in the calling routine. The variables `bvirt', `c', `abig', */
3914 /* `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because */
3915 /* they store the result of an operation that may incur roundoff error. */
3916 /* The input parameter `x' (or the highest numbered `x_' parameter) must */
3917 /* also be declared `INEXACT'. */
3919 #define Fast_Two_Sum_Tail(a, b, x, y) \
3923 #define Fast_Two_Sum(a, b, x, y) \
3924 x = (REAL) (a + b); \
3925 Fast_Two_Sum_Tail(a, b, x, y)
3927 #define Two_Sum_Tail(a, b, x, y) \
3928 bvirt = (REAL) (x - a); \
3929 avirt = x - bvirt; \
3930 bround = b - bvirt; \
3931 around = a - avirt; \
3934 #define Two_Sum(a, b, x, y) \
3935 x = (REAL) (a + b); \
3936 Two_Sum_Tail(a, b, x, y)
3938 #define Two_Diff_Tail(a, b, x, y) \
3939 bvirt = (REAL) (a - x); \
3940 avirt = x + bvirt; \
3941 bround = bvirt - b; \
3942 around = a - avirt; \
3945 #define Two_Diff(a, b, x, y) \
3946 x = (REAL) (a - b); \
3947 Two_Diff_Tail(a, b, x, y)
3949 #define Split(a, ahi, alo) \
3950 c = (REAL) (splitter * a); \
3951 abig = (REAL) (c - a); \
3952 ahi = (REAL)(c - abig); \
3953 alo = (REAL)(a - ahi)
3955 #define Two_Product_Tail(a, b, x, y) \
3956 Split(a, ahi, alo); \
3957 Split(b, bhi, blo); \
3958 err1 = x - (ahi * bhi); \
3959 err2 = err1 - (alo * bhi); \
3960 err3 = err2 - (ahi * blo); \
3961 y = (alo * blo) - err3
3963 #define Two_Product(a, b, x, y) \
3964 x = (REAL) (a * b); \
3965 Two_Product_Tail(a, b, x, y)
3967 /* Two_Product_Presplit() is Two_Product() where one of the inputs has */
3968 /* already been split. Avoids redundant splitting. */
3970 #define Two_Product_Presplit(a, b, bhi, blo, x, y) \
3971 x = (REAL) (a * b); \
3972 Split(a, ahi, alo); \
3973 err1 = x - (ahi * bhi); \
3974 err2 = err1 - (alo * bhi); \
3975 err3 = err2 - (ahi * blo); \
3976 y = (alo * blo) - err3
3978 /* Square() can be done more quickly than Two_Product(). */
3980 #define Square_Tail(a, x, y) \
3981 Split(a, ahi, alo); \
3982 err1 = x - (ahi * ahi); \
3983 err3 = err1 - ((ahi + ahi) * alo); \
3984 y = (alo * alo) - err3
3986 #define Square(a, x, y) \
3987 x = (REAL) (a * a); \
3988 Square_Tail(a, x, y)
3990 /* Macros for summing expansions of various fixed lengths. These are all */
3991 /* unrolled versions of Expansion_Sum(). */
3993 #define Two_One_Sum(a1, a0, b, x2, x1, x0) \
3994 Two_Sum(a0, b , _i, x0); \
3995 Two_Sum(a1, _i, x2, x1)
3997 #define Two_One_Diff(a1, a0, b, x2, x1, x0) \
3998 Two_Diff(a0, b , _i, x0); \
3999 Two_Sum( a1, _i, x2, x1)
4001 #define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
4002 Two_One_Sum(a1, a0, b0, _j, _0, x0); \
4003 Two_One_Sum(_j, _0, b1, x3, x2, x1)
4005 #define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
4006 Two_One_Diff(a1, a0, b0, _j, _0, x0); \
4007 Two_One_Diff(_j, _0, b1, x3, x2, x1)
4009 /*****************************************************************************/
4011 /* exactinit() Initialize the variables used for exact arithmetic. */
4013 /* `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in */
4014 /* floating-point arithmetic. `epsilon' bounds the relative roundoff */
4015 /* error. It is used for floating-point error analysis. */
4017 /* `splitter' is used to split floating-point numbers into two half- */
4018 /* length significands for exact multiplication. */
4020 /* I imagine that a highly optimizing compiler might be too smart for its */
4021 /* own good, and somehow cause this routine to fail, if it pretends that */
4022 /* floating-point arithmetic is too much like real arithmetic. */
4024 /* Don't change this routine unless you fully understand it. */
4026 /*****************************************************************************/
4031 REAL check, lastcheck;
4039 /* Repeatedly divide `epsilon' by two until it is too small to add to */
4040 /* one without causing roundoff. (Also check if the sum is equal to */
4041 /* the previous sum, for machines that round up instead of using exact */
4042 /* rounding. Not that these routines will work on such machines anyway. */
4049 every_other = !every_other;
4050 check = (REAL)(1.0 + epsilon);
4051 } while ((check != 1.0) && (check != lastcheck));
4054 printf("Floating point roundoff is of magnitude %.17g\n", epsilon);
4055 printf("Floating point splitter is %.17g\n", splitter);
4057 /* Error bounds for orientation and incircle tests. */
4058 resulterrbound = (REAL)((3.0 + 8.0 * epsilon) * epsilon);
4059 ccwerrboundA = (REAL)((3.0 + 16.0 * epsilon) * epsilon);
4060 ccwerrboundB = (REAL)((2.0 + 12.0 * epsilon) * epsilon);
4061 ccwerrboundC = (REAL)((9.0 + 64.0 * epsilon) * epsilon * epsilon);
4062 iccerrboundA = (REAL)((10.0 + 96.0 * epsilon) * epsilon);
4063 iccerrboundB = (REAL)((4.0 + 48.0 * epsilon) * epsilon);
4064 iccerrboundC = (REAL)((44.0 + 576.0 * epsilon) * epsilon * epsilon);
4067 /*****************************************************************************/
4069 /* fast_expansion_sum_zeroelim() Sum two expansions, eliminating zero */
4070 /* components from the output expansion. */
4072 /* Sets h = e + f. See my Robust Predicates paper for details. */
4074 /* If round-to-even is used (as with IEEE 754), maintains the strongly */
4075 /* nonoverlapping property. (That is, if e is strongly nonoverlapping, h */
4076 /* will be also.) Does NOT maintain the nonoverlapping or nonadjacent */
4079 /*****************************************************************************/
4081 int fast_expansion_sum_zeroelim(elen, e, flen, f, h) /* h cannot be e or f. */
4092 REAL avirt, bround, around;
4093 int eindex, findex, hindex;
4098 eindex = findex = 0;
4099 if ((fnow > enow) == (fnow > -enow)) {
4107 if ((eindex < elen) && (findex < flen)) {
4108 if ((fnow > enow) == (fnow > -enow)) {
4109 Fast_Two_Sum(enow, Q, Qnew, hh);
4112 Fast_Two_Sum(fnow, Q, Qnew, hh);
4119 while ((eindex < elen) && (findex < flen)) {
4120 if ((fnow > enow) == (fnow > -enow)) {
4121 Two_Sum(Q, enow, Qnew, hh);
4124 Two_Sum(Q, fnow, Qnew, hh);
4133 while (eindex < elen) {
4134 Two_Sum(Q, enow, Qnew, hh);
4141 while (findex < flen) {
4142 Two_Sum(Q, fnow, Qnew, hh);
4149 if ((Q != 0.0) || (hindex == 0)) {
4155 /*****************************************************************************/
4157 /* scale_expansion_zeroelim() Multiply an expansion by a scalar, */
4158 /* eliminating zero components from the */
4159 /* output expansion. */
4161 /* Sets h = be. See my Robust Predicates paper for details. */
4163 /* Maintains the nonoverlapping property. If round-to-even is used (as */
4164 /* with IEEE 754), maintains the strongly nonoverlapping and nonadjacent */
4165 /* properties as well. (That is, if e has one of these properties, so */
4168 /*****************************************************************************/
4170 int scale_expansion_zeroelim(elen, e, b, h) /* e and h cannot be the same. */
4176 INEXACT REAL Q, sum;
4178 INEXACT REAL product1;
4183 REAL avirt, bround, around;
4186 REAL ahi, alo, bhi, blo;
4187 REAL err1, err2, err3;
4190 Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
4195 for (eindex = 1; eindex < elen; eindex++) {
4197 Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
4198 Two_Sum(Q, product0, sum, hh);
4202 Fast_Two_Sum(product1, sum, Q, hh);
4207 if ((Q != 0.0) || (hindex == 0)) {
4213 /*****************************************************************************/
4215 /* estimate() Produce a one-word estimate of an expansion's value. */
4217 /* See my Robust Predicates paper for details. */
4219 /*****************************************************************************/
4221 REAL estimate(elen, e)
4229 for (eindex = 1; eindex < elen; eindex++) {
4235 /*****************************************************************************/
4237 /* counterclockwise() Return a positive value if the points pa, pb, and */
4238 /* pc occur in counterclockwise order; a negative */
4239 /* value if they occur in clockwise order; and zero */
4240 /* if they are collinear. The result is also a rough */
4241 /* approximation of twice the signed area of the */
4242 /* triangle defined by the three points. */
4244 /* Uses exact arithmetic if necessary to ensure a correct answer. The */
4245 /* result returned is the determinant of a matrix. This determinant is */
4246 /* computed adaptively, in the sense that exact arithmetic is used only to */
4247 /* the degree it is needed to ensure that the returned value has the */
4248 /* correct sign. Hence, this function is usually quite fast, but will run */
4249 /* more slowly when the input points are collinear or nearly so. */
4251 /* See my Robust Predicates paper for details. */
4253 /*****************************************************************************/
4255 REAL counterclockwiseadapt(pa, pb, pc, detsum)
4261 INEXACT REAL acx, acy, bcx, bcy;
4262 REAL acxtail, acytail, bcxtail, bcytail;
4263 INEXACT REAL detleft, detright;
4264 REAL detlefttail, detrighttail;
4266 REAL B[4], C1[8], C2[12], D[16];
4268 int C1length, C2length, Dlength;
4271 INEXACT REAL s1, t1;
4275 REAL avirt, bround, around;
4278 REAL ahi, alo, bhi, blo;
4279 REAL err1, err2, err3;
4280 INEXACT REAL _i, _j;
4283 acx = (REAL) (pa[0] - pc[0]);
4284 bcx = (REAL) (pb[0] - pc[0]);
4285 acy = (REAL) (pa[1] - pc[1]);
4286 bcy = (REAL) (pb[1] - pc[1]);
4288 Two_Product(acx, bcy, detleft, detlefttail);
4289 Two_Product(acy, bcx, detright, detrighttail);
4291 Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
4292 B3, B[2], B[1], B[0]);
4295 det = estimate(4, B);
4296 errbound = (REAL)(ccwerrboundB * detsum);
4297 if ((det >= errbound) || (-det >= errbound)) {
4301 Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
4302 Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
4303 Two_Diff_Tail(pa[1], pc[1], acy, acytail);
4304 Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
4306 if ((acxtail == 0.0) && (acytail == 0.0)
4307 && (bcxtail == 0.0) && (bcytail == 0.0)) {
4311 errbound = (REAL)(ccwerrboundC * detsum + resulterrbound * Absolute(det));
4312 det += (acx * bcytail + bcy * acxtail)
4313 - (acy * bcxtail + bcx * acytail);
4314 if ((det >= errbound) || (-det >= errbound)) {
4318 Two_Product(acxtail, bcy, s1, s0);
4319 Two_Product(acytail, bcx, t1, t0);
4320 Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
4322 C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
4324 Two_Product(acx, bcytail, s1, s0);
4325 Two_Product(acy, bcxtail, t1, t0);
4326 Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
4328 C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
4330 Two_Product(acxtail, bcytail, s1, s0);
4331 Two_Product(acytail, bcxtail, t1, t0);
4332 Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
4334 Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
4336 return(D[Dlength - 1]);
4339 REAL counterclockwise(pa, pb, pc)
4344 REAL detleft, detright, det;
4345 REAL detsum, errbound;
4347 counterclockcount++;
4349 detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
4350 detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
4351 det = detleft - detright;
4357 if (detleft > 0.0) {
4358 if (detright <= 0.0) {
4361 detsum = detleft + detright;
4363 } else if (detleft < 0.0) {
4364 if (detright >= 0.0) {
4367 detsum = -detleft - detright;
4373 errbound = ccwerrboundA * detsum;
4374 if ((det >= errbound) || (-det >= errbound)) {
4378 return counterclockwiseadapt(pa, pb, pc, detsum);
4381 /*****************************************************************************/
4383 /* incircle() Return a positive value if the point pd lies inside the */
4384 /* circle passing through pa, pb, and pc; a negative value if */
4385 /* it lies outside; and zero if the four points are cocircular.*/
4386 /* The points pa, pb, and pc must be in counterclockwise */
4387 /* order, or the sign of the result will be reversed. */
4389 /* Uses exact arithmetic if necessary to ensure a correct answer. The */
4390 /* result returned is the determinant of a matrix. This determinant is */
4391 /* computed adaptively, in the sense that exact arithmetic is used only to */
4392 /* the degree it is needed to ensure that the returned value has the */
4393 /* correct sign. Hence, this function is usually quite fast, but will run */
4394 /* more slowly when the input points are cocircular or nearly so. */
4396 /* See my Robust Predicates paper for details. */
4398 /*****************************************************************************/
4400 REAL incircleadapt(pa, pb, pc, pd, permanent)
4407 INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
4410 INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
4411 REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
4412 REAL bc[4], ca[4], ab[4];
4413 INEXACT REAL bc3, ca3, ab3;
4414 REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
4415 int axbclen, axxbclen, aybclen, ayybclen, alen;
4416 REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
4417 int bxcalen, bxxcalen, bycalen, byycalen, blen;
4418 REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
4419 int cxablen, cxxablen, cyablen, cyyablen, clen;
4422 REAL fin1[1152], fin2[1152];
4423 REAL *finnow, *finother, *finswap;
4426 REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
4427 INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
4428 REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
4429 REAL aa[4], bb[4], cc[4];
4430 INEXACT REAL aa3, bb3, cc3;
4431 INEXACT REAL ti1, tj1;
4434 INEXACT REAL u3, v3;
4435 REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
4436 REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
4437 int temp8len, temp16alen, temp16blen, temp16clen;
4438 int temp32alen, temp32blen, temp48len, temp64len;
4439 REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
4440 int axtbblen, axtcclen, aytbblen, aytcclen;
4441 REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
4442 int bxtaalen, bxtcclen, bytaalen, bytcclen;
4443 REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
4444 int cxtaalen, cxtbblen, cytaalen, cytbblen;
4445 REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
4446 int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen;
4447 REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
4448 int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
4449 REAL axtbctt[8], aytbctt[8], bxtcatt[8];
4450 REAL bytcatt[8], cxtabtt[8], cytabtt[8];
4451 int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
4452 REAL abt[8], bct[8], cat[8];
4453 int abtlen, bctlen, catlen;
4454 REAL abtt[4], bctt[4], catt[4];
4455 int abttlen, bcttlen, cattlen;
4456 INEXACT REAL abtt3, bctt3, catt3;
4460 REAL avirt, bround, around;
4463 REAL ahi, alo, bhi, blo;
4464 REAL err1, err2, err3;
4465 INEXACT REAL _i, _j;
4468 adx = (REAL) (pa[0] - pd[0]);
4469 bdx = (REAL) (pb[0] - pd[0]);
4470 cdx = (REAL) (pc[0] - pd[0]);
4471 ady = (REAL) (pa[1] - pd[1]);
4472 bdy = (REAL) (pb[1] - pd[1]);
4473 cdy = (REAL) (pc[1] - pd[1]);
4475 Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
4476 Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
4477 Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
4479 axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
4480 axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
4481 aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
4482 ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
4483 alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
4485 Two_Product(cdx, ady, cdxady1, cdxady0);
4486 Two_Product(adx, cdy, adxcdy1, adxcdy0);
4487 Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
4489 bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
4490 bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
4491 bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
4492 byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
4493 blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
4495 Two_Product(adx, bdy, adxbdy1, adxbdy0);
4496 Two_Product(bdx, ady, bdxady1, bdxady0);
4497 Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
4499 cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
4500 cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
4501 cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
4502 cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
4503 clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
4505 ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
4506 finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
4508 det = estimate(finlength, fin1);
4509 errbound = (REAL)(iccerrboundB * permanent);
4510 if ((det >= errbound) || (-det >= errbound)) {
4514 Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
4515 Two_Diff_Tail(pa[1], pd[1], ady, adytail);
4516 Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
4517 Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
4518 Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
4519 Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
4520 if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
4521 && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
4525 errbound = (REAL)(iccerrboundC * permanent + resulterrbound * Absolute(det));
4526 det += (REAL)(((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
4527 - (bdy * cdxtail + cdx * bdytail))
4528 + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
4529 + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
4530 - (cdy * adxtail + adx * cdytail))
4531 + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
4532 + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
4533 - (ady * bdxtail + bdx * adytail))
4534 + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx)));
4535 if ((det >= errbound) || (-det >= errbound)) {
4542 if ((bdxtail != 0.0) || (bdytail != 0.0)
4543 || (cdxtail != 0.0) || (cdytail != 0.0)) {
4544 Square(adx, adxadx1, adxadx0);
4545 Square(ady, adyady1, adyady0);
4546 Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
4549 if ((cdxtail != 0.0) || (cdytail != 0.0)
4550 || (adxtail != 0.0) || (adytail != 0.0)) {
4551 Square(bdx, bdxbdx1, bdxbdx0);
4552 Square(bdy, bdybdy1, bdybdy0);
4553 Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
4556 if ((adxtail != 0.0) || (adytail != 0.0)
4557 || (bdxtail != 0.0) || (bdytail != 0.0)) {
4558 Square(cdx, cdxcdx1, cdxcdx0);
4559 Square(cdy, cdycdy1, cdycdy0);
4560 Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
4564 if (adxtail != 0.0) {
4565 axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
4566 temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
4569 axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
4570 temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
4572 axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
4573 temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
4575 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4576 temp16blen, temp16b, temp32a);
4577 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
4578 temp32alen, temp32a, temp48);
4579 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4581 finswap = finnow; finnow = finother; finother = finswap;
4583 if (adytail != 0.0) {
4584 aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
4585 temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
4588 aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
4589 temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
4591 aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
4592 temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
4594 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4595 temp16blen, temp16b, temp32a);
4596 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
4597 temp32alen, temp32a, temp48);
4598 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4600 finswap = finnow; finnow = finother; finother = finswap;
4602 if (bdxtail != 0.0) {
4603 bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
4604 temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
4607 bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
4608 temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
4610 bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
4611 temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
4613 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4614 temp16blen, temp16b, temp32a);
4615 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
4616 temp32alen, temp32a, temp48);
4617 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4619 finswap = finnow; finnow = finother; finother = finswap;
4621 if (bdytail != 0.0) {
4622 bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
4623 temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
4626 bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
4627 temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
4629 bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
4630 temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
4632 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4633 temp16blen, temp16b, temp32a);
4634 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
4635 temp32alen, temp32a, temp48);
4636 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4638 finswap = finnow; finnow = finother; finother = finswap;
4640 if (cdxtail != 0.0) {
4641 cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
4642 temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
4645 cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
4646 temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
4648 cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
4649 temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
4651 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4652 temp16blen, temp16b, temp32a);
4653 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
4654 temp32alen, temp32a, temp48);
4655 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4657 finswap = finnow; finnow = finother; finother = finswap;
4659 if (cdytail != 0.0) {
4660 cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
4661 temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
4664 cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
4665 temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
4667 cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
4668 temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
4670 temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4671 temp16blen, temp16b, temp32a);
4672 temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
4673 temp32alen, temp32a, temp48);
4674 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4676 finswap = finnow; finnow = finother; finother = finswap;
4679 if ((adxtail != 0.0) || (adytail != 0.0)) {
4680 if ((bdxtail != 0.0) || (bdytail != 0.0)
4681 || (cdxtail != 0.0) || (cdytail != 0.0)) {
4682 Two_Product(bdxtail, cdy, ti1, ti0);
4683 Two_Product(bdx, cdytail, tj1, tj0);
4684 Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
4687 Two_Product(cdxtail, negate, ti1, ti0);
4689 Two_Product(cdx, negate, tj1, tj0);
4690 Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
4692 bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
4694 Two_Product(bdxtail, cdytail, ti1, ti0);
4695 Two_Product(cdxtail, bdytail, tj1, tj0);
4696 Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
4706 if (adxtail != 0.0) {
4707 temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
4708 axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
4709 temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
4711 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4712 temp32alen, temp32a, temp48);
4713 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4715 finswap = finnow; finnow = finother; finother = finswap;
4716 if (bdytail != 0.0) {
4717 temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
4718 temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
4720 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4722 finswap = finnow; finnow = finother; finother = finswap;
4724 if (cdytail != 0.0) {
4725 temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
4726 temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
4728 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4730 finswap = finnow; finnow = finother; finother = finswap;
4733 temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
4735 axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
4736 temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
4738 temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
4740 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4741 temp16blen, temp16b, temp32b);
4742 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
4743 temp32blen, temp32b, temp64);
4744 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
4746 finswap = finnow; finnow = finother; finother = finswap;
4748 if (adytail != 0.0) {
4749 temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
4750 aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
4751 temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
4753 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4754 temp32alen, temp32a, temp48);
4755 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4757 finswap = finnow; finnow = finother; finother = finswap;
4760 temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
4762 aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
4763 temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
4765 temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
4767 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4768 temp16blen, temp16b, temp32b);
4769 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
4770 temp32blen, temp32b, temp64);
4771 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
4773 finswap = finnow; finnow = finother; finother = finswap;
4776 if ((bdxtail != 0.0) || (bdytail != 0.0)) {
4777 if ((cdxtail != 0.0) || (cdytail != 0.0)
4778 || (adxtail != 0.0) || (adytail != 0.0)) {
4779 Two_Product(cdxtail, ady, ti1, ti0);
4780 Two_Product(cdx, adytail, tj1, tj0);
4781 Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
4784 Two_Product(adxtail, negate, ti1, ti0);
4786 Two_Product(adx, negate, tj1, tj0);
4787 Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
4789 catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
4791 Two_Product(cdxtail, adytail, ti1, ti0);
4792 Two_Product(adxtail, cdytail, tj1, tj0);
4793 Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
4803 if (bdxtail != 0.0) {
4804 temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
4805 bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
4806 temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
4808 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4809 temp32alen, temp32a, temp48);
4810 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4812 finswap = finnow; finnow = finother; finother = finswap;
4813 if (cdytail != 0.0) {
4814 temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
4815 temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
4817 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4819 finswap = finnow; finnow = finother; finother = finswap;
4821 if (adytail != 0.0) {
4822 temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
4823 temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
4825 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4827 finswap = finnow; finnow = finother; finother = finswap;
4830 temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
4832 bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
4833 temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
4835 temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
4837 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4838 temp16blen, temp16b, temp32b);
4839 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
4840 temp32blen, temp32b, temp64);
4841 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
4843 finswap = finnow; finnow = finother; finother = finswap;
4845 if (bdytail != 0.0) {
4846 temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
4847 bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
4848 temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
4850 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4851 temp32alen, temp32a, temp48);
4852 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4854 finswap = finnow; finnow = finother; finother = finswap;
4857 temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
4859 bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
4860 temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
4862 temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
4864 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4865 temp16blen, temp16b, temp32b);
4866 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
4867 temp32blen, temp32b, temp64);
4868 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
4870 finswap = finnow; finnow = finother; finother = finswap;
4873 if ((cdxtail != 0.0) || (cdytail != 0.0)) {
4874 if ((adxtail != 0.0) || (adytail != 0.0)
4875 || (bdxtail != 0.0) || (bdytail != 0.0)) {
4876 Two_Product(adxtail, bdy, ti1, ti0);
4877 Two_Product(adx, bdytail, tj1, tj0);
4878 Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
4881 Two_Product(bdxtail, negate, ti1, ti0);
4883 Two_Product(bdx, negate, tj1, tj0);
4884 Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
4886 abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
4888 Two_Product(adxtail, bdytail, ti1, ti0);
4889 Two_Product(bdxtail, adytail, tj1, tj0);
4890 Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
4900 if (cdxtail != 0.0) {
4901 temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
4902 cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
4903 temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
4905 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4906 temp32alen, temp32a, temp48);
4907 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4909 finswap = finnow; finnow = finother; finother = finswap;
4910 if (adytail != 0.0) {
4911 temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
4912 temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
4914 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4916 finswap = finnow; finnow = finother; finother = finswap;
4918 if (bdytail != 0.0) {
4919 temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
4920 temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
4922 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4924 finswap = finnow; finnow = finother; finother = finswap;
4927 temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
4929 cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
4930 temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
4932 temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
4934 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4935 temp16blen, temp16b, temp32b);
4936 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
4937 temp32blen, temp32b, temp64);
4938 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
4940 finswap = finnow; finnow = finother; finother = finswap;
4942 if (cdytail != 0.0) {
4943 temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
4944 cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
4945 temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
4947 temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4948 temp32alen, temp32a, temp48);
4949 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4951 finswap = finnow; finnow = finother; finother = finswap;
4954 temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
4956 cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
4957 temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
4959 temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
4961 temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4962 temp16blen, temp16b, temp32b);
4963 temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
4964 temp32blen, temp32b, temp64);
4965 finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
4967 finswap = finnow; finnow = finother; finother = finswap;
4971 return finnow[finlength - 1];
4974 REAL incircle(pa, pb, pc, pd)
4980 REAL adx, bdx, cdx, ady, bdy, cdy;
4981 REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
4982 REAL alift, blift, clift;
4984 REAL permanent, errbound;
4988 adx = pa[0] - pd[0];
4989 bdx = pb[0] - pd[0];
4990 cdx = pc[0] - pd[0];
4991 ady = pa[1] - pd[1];
4992 bdy = pb[1] - pd[1];
4993 cdy = pc[1] - pd[1];
4997 alift = adx * adx + ady * ady;
5001 blift = bdx * bdx + bdy * bdy;
5005 clift = cdx * cdx + cdy * cdy;
5007 det = alift * (bdxcdy - cdxbdy)
5008 + blift * (cdxady - adxcdy)
5009 + clift * (adxbdy - bdxady);
5015 permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
5016 + (Absolute(cdxady) + Absolute(adxcdy)) * blift
5017 + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
5018 errbound = iccerrboundA * permanent;
5019 if ((det > errbound) || (-det > errbound)) {
5023 return incircleadapt(pa, pb, pc, pd, permanent);
5028 /********* Determinant evaluation routines end here *********/
5030 /*****************************************************************************/
5032 /* triangleinit() Initialize some variables. */
5034 /*****************************************************************************/
5038 points.maxitems = triangles.maxitems = shelles.maxitems = viri.maxitems =
5039 badsegments.maxitems = badtriangles.maxitems = splaynodes.maxitems = 0l;
5040 points.itembytes = triangles.itembytes = shelles.itembytes = viri.itembytes =
5041 badsegments.itembytes = badtriangles.itembytes = splaynodes.itembytes = 0;
5042 recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
5043 samples = 1; /* Point location should take at least one sample. */
5044 checksegments = 0; /* There are no segments in the triangulation yet. */
5045 incirclecount = counterclockcount = hyperbolacount = 0;
5046 circumcentercount = circletopcount = 0;
5049 exactinit(); /* Initialize exact arithmetic constants. */
5052 /*****************************************************************************/
5054 /* randomnation() Generate a random number between 0 and `choices' - 1. */
5056 /* This is a simple linear congruential random number generator. Hence, it */
5057 /* is a bad random number generator, but good enough for most randomized */
5058 /* geometric algorithms. */
5060 /*****************************************************************************/
5062 unsigned long randomnation(choices)
5063 unsigned int choices;
5065 randomseed = (randomseed * 1366l + 150889l) % 714025l;
5066 return randomseed / (714025l / choices + 1);
5069 /********* Mesh quality testing routines begin here *********/
5073 /*****************************************************************************/
5075 /* checkmesh() Test the mesh for topological consistency. */
5077 /*****************************************************************************/
5083 struct triedge triangleloop;
5084 struct triedge oppotri, oppooppotri;
5085 point triorg, tridest, triapex;
5086 point oppoorg, oppodest;
5089 triangle ptr; /* Temporary variable used by sym(). */
5091 /* Temporarily turn on exact arithmetic if it's off. */
5092 saveexact = noexact;
5095 printf(" Checking consistency of mesh...\n");
5098 /* Run through the list of triangles, checking each one. */
5099 traversalinit(&triangles);
5100 triangleloop.tri = triangletraverse();
5101 while (triangleloop.tri != (triangle *) NULL) {
5102 /* Check all three edges of the triangle. */
5103 for (triangleloop.orient = 0; triangleloop.orient < 3;
5104 triangleloop.orient++) {
5105 org(triangleloop, triorg);
5106 dest(triangleloop, tridest);
5107 if (triangleloop.orient == 0) { /* Only test for inversion once. */
5108 /* Test if the triangle is flat or inverted. */
5109 apex(triangleloop, triapex);
5110 if (counterclockwise(triorg, tridest, triapex) <= 0.0) {
5111 printf(" !! !! Inverted ");
5112 printtriangle(&triangleloop);
5116 /* Find the neighboring triangle on this edge. */
5117 sym(triangleloop, oppotri);
5118 if (oppotri.tri != dummytri) {
5119 /* Check that the triangle's neighbor knows it's a neighbor. */
5120 sym(oppotri, oppooppotri);
5121 if ((triangleloop.tri != oppooppotri.tri)
5122 || (triangleloop.orient != oppooppotri.orient)) {
5123 printf(" !! !! Asymmetric triangle-triangle bond:\n");
5124 if (triangleloop.tri == oppooppotri.tri) {
5125 printf(" (Right triangle, wrong orientation)\n");
5128 printtriangle(&triangleloop);
5129 printf(" Second (nonreciprocating) ");
5130 printtriangle(&oppotri);
5133 /* Check that both triangles agree on the identities */
5134 /* of their shared vertices. */
5135 org(oppotri, oppoorg);
5136 dest(oppotri, oppodest);
5137 if ((triorg != oppodest) || (tridest != oppoorg)) {
5138 printf(" !! !! Mismatched edge coordinates between two triangles:\n"
5140 printf(" First mismatched ");
5141 printtriangle(&triangleloop);
5142 printf(" Second mismatched ");
5143 printtriangle(&oppotri);
5148 triangleloop.tri = triangletraverse();
5152 printf(" In my studied opinion, the mesh appears to be consistent.\n");
5154 } else if (horrors == 1) {
5155 printf(" !! !! !! !! Precisely one festering wound discovered.\n");
5157 printf(" !! !! !! !! %d abominations witnessed.\n", horrors);
5159 /* Restore the status of exact arithmetic. */
5160 noexact = saveexact;
5163 #endif /* not REDUCED */
5165 /*****************************************************************************/
5167 /* checkdelaunay() Ensure that the mesh is (constrained) Delaunay. */
5169 /*****************************************************************************/
5173 void checkdelaunay()
5175 struct triedge triangleloop;
5176 struct triedge oppotri;
5177 struct edge opposhelle;
5178 point triorg, tridest, triapex;
5180 int shouldbedelaunay;
5183 triangle ptr; /* Temporary variable used by sym(). */
5184 shelle sptr; /* Temporary variable used by tspivot(). */
5186 /* Temporarily turn on exact arithmetic if it's off. */
5187 saveexact = noexact;
5190 printf(" Checking Delaunay property of mesh...\n");
5193 /* Run through the list of triangles, checking each one. */
5194 traversalinit(&triangles);
5195 triangleloop.tri = triangletraverse();
5196 while (triangleloop.tri != (triangle *) NULL) {
5197 /* Check all three edges of the triangle. */
5198 for (triangleloop.orient = 0; triangleloop.orient < 3;
5199 triangleloop.orient++) {
5200 org(triangleloop, triorg);
5201 dest(triangleloop, tridest);
5202 apex(triangleloop, triapex);
5203 sym(triangleloop, oppotri);
5204 apex(oppotri, oppoapex);
5205 /* Only test that the edge is locally Delaunay if there is an */
5206 /* adjoining triangle whose pointer is larger (to ensure that */
5207 /* each pair isn't tested twice). */
5208 shouldbedelaunay = (oppotri.tri != dummytri)
5209 && (triapex != (point) NULL) && (oppoapex != (point) NULL)
5210 && (triangleloop.tri < oppotri.tri);
5211 if (checksegments && shouldbedelaunay) {
5212 /* If a shell edge separates the triangles, then the edge is */
5213 /* constrained, so no local Delaunay test should be done. */
5214 tspivot(triangleloop, opposhelle);
5215 if (opposhelle.sh != dummysh){
5216 shouldbedelaunay = 0;
5219 if (shouldbedelaunay) {
5220 if (incircle(triorg, tridest, triapex, oppoapex) > 0.0) {
5221 printf(" !! !! Non-Delaunay pair of triangles:\n");
5222 printf(" First non-Delaunay ");
5223 printtriangle(&triangleloop);
5224 printf(" Second non-Delaunay ");
5225 printtriangle(&oppotri);
5230 triangleloop.tri = triangletraverse();
5235 " By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
5237 } else if (horrors == 1) {
5239 " !! !! !! !! Precisely one terrifying transgression identified.\n");
5241 printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors);
5243 /* Restore the status of exact arithmetic. */
5244 noexact = saveexact;
5247 #endif /* not REDUCED */
5249 /*****************************************************************************/
5251 /* enqueuebadtri() Add a bad triangle to the end of a queue. */
5253 /* The queue is actually a set of 64 queues. I use multiple queues to give */
5254 /* priority to smaller angles. I originally implemented a heap, but the */
5255 /* queues are (to my surprise) much faster. */
5257 /*****************************************************************************/
5261 void enqueuebadtri(instri, angle, insapex, insorg, insdest)
5262 struct triedge *instri;
5268 struct badface *newface;
5272 printf(" Queueing bad triangle:\n");
5273 printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", insorg[0],
5274 insorg[1], insdest[0], insdest[1], insapex[0], insapex[1]);
5276 /* Allocate space for the bad triangle. */
5277 newface = (struct badface *) poolalloc(&badtriangles);
5278 triedgecopy(*instri, newface->badfacetri);
5279 newface->key = angle;
5280 newface->faceapex = insapex;
5281 newface->faceorg = insorg;
5282 newface->facedest = insdest;
5283 newface->nextface = (struct badface *) NULL;
5284 /* Determine the appropriate queue to put the bad triangle into. */
5286 queuenumber = (int) (160.0 * (angle - 0.6));
5287 if (queuenumber > 63) {
5291 /* It's not a bad angle; put the triangle in the lowest-priority queue. */
5294 /* Add the triangle to the end of a queue. */
5295 *queuetail[queuenumber] = newface;
5296 /* Maintain a pointer to the NULL pointer at the end of the queue. */
5297 queuetail[queuenumber] = &newface->nextface;
5300 #endif /* not CDT_ONLY */
5302 /*****************************************************************************/
5304 /* dequeuebadtri() Remove a triangle from the front of the queue. */
5306 /*****************************************************************************/
5310 struct badface *dequeuebadtri()
5312 struct badface *result;
5315 /* Look for a nonempty queue. */
5316 for (queuenumber = 63; queuenumber >= 0; queuenumber--) {
5317 result = queuefront[queuenumber];
5318 if (result != (struct badface *) NULL) {
5319 /* Remove the triangle from the queue. */
5320 queuefront[queuenumber] = result->nextface;
5321 /* Maintain a pointer to the NULL pointer at the end of the queue. */
5322 if (queuefront[queuenumber] == (struct badface *) NULL) {
5323 queuetail[queuenumber] = &queuefront[queuenumber];
5328 return (struct badface *) NULL;
5331 #endif /* not CDT_ONLY */
5333 /*****************************************************************************/
5335 /* checkedge4encroach() Check a segment to see if it is encroached; add */
5336 /* it to the list if it is. */
5338 /* An encroached segment is an unflippable edge that has a point in its */
5339 /* diametral circle (that is, it faces an angle greater than 90 degrees). */
5340 /* This definition is due to Ruppert. */
5342 /* Returns a nonzero value if the edge is encroached. */
5344 /*****************************************************************************/
5348 int checkedge4encroach(testedge)
5349 struct edge *testedge;
5351 struct triedge neighbortri;
5352 struct edge testsym;
5353 struct edge *badedge;
5356 point eorg, edest, eapex;
5357 triangle ptr; /* Temporary variable used by stpivot(). */
5362 sorg(*testedge, eorg);
5363 sdest(*testedge, edest);
5364 /* Check one neighbor of the shell edge. */
5365 stpivot(*testedge, neighbortri);
5366 /* Does the neighbor exist, or is this a boundary edge? */
5367 if (neighbortri.tri != dummytri) {
5369 /* Find a vertex opposite this edge. */
5370 apex(neighbortri, eapex);
5371 /* Check whether the vertex is inside the diametral circle of the */
5372 /* shell edge. Pythagoras' Theorem is used to check whether the */
5373 /* angle at the vertex is greater than 90 degrees. */
5374 if (eapex[0] * (eorg[0] + edest[0]) + eapex[1] * (eorg[1] + edest[1]) >
5375 eapex[0] * eapex[0] + eorg[0] * edest[0] +
5376 eapex[1] * eapex[1] + eorg[1] * edest[1]) {
5380 /* Check the other neighbor of the shell edge. */
5381 ssym(*testedge, testsym);
5382 stpivot(testsym, neighbortri);
5383 /* Does the neighbor exist, or is this a boundary edge? */
5384 if (neighbortri.tri != dummytri) {
5386 /* Find the other vertex opposite this edge. */
5387 apex(neighbortri, eapex);
5388 /* Check whether the vertex is inside the diametral circle of the */
5389 /* shell edge. Pythagoras' Theorem is used to check whether the */
5390 /* angle at the vertex is greater than 90 degrees. */
5391 if (eapex[0] * (eorg[0] + edest[0]) +
5392 eapex[1] * (eorg[1] + edest[1]) >
5393 eapex[0] * eapex[0] + eorg[0] * edest[0] +
5394 eapex[1] * eapex[1] + eorg[1] * edest[1]) {
5399 if (addtolist && (!nobisect || ((nobisect == 1) && (sides == 2)))) {
5401 printf(" Queueing encroached segment (%.12g, %.12g) (%.12g, %.12g).\n",
5402 eorg[0], eorg[1], edest[0], edest[1]);
5404 /* Add the shell edge to the list of encroached segments. */
5405 /* Be sure to get the orientation right. */
5406 badedge = (struct edge *) poolalloc(&badsegments);
5407 if (addtolist == 1) {
5408 shellecopy(*testedge, *badedge);
5410 shellecopy(testsym, *badedge);
5416 #endif /* not CDT_ONLY */
5418 /*****************************************************************************/
5420 /* testtriangle() Test a face for quality measures. */
5422 /* Tests a triangle to see if it satisfies the minimum angle condition and */
5423 /* the maximum area condition. Triangles that aren't up to spec are added */
5424 /* to the bad triangle queue. */
5426 /*****************************************************************************/
5430 void testtriangle(testtri)
5431 struct triedge *testtri;
5433 struct triedge sametesttri;
5434 struct edge edge1, edge2;
5435 point torg, tdest, tapex;
5437 REAL dxod, dyod, dxda, dyda, dxao, dyao;
5438 REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
5439 REAL apexlen, orglen, destlen;
5442 shelle sptr; /* Temporary variable used by tspivot(). */
5444 org(*testtri, torg);
5445 dest(*testtri, tdest);
5446 apex(*testtri, tapex);
5447 dxod = torg[0] - tdest[0];
5448 dyod = torg[1] - tdest[1];
5449 dxda = tdest[0] - tapex[0];
5450 dyda = tdest[1] - tapex[1];
5451 dxao = tapex[0] - torg[0];
5452 dyao = tapex[1] - torg[1];
5453 dxod2 = dxod * dxod;
5454 dyod2 = dyod * dyod;
5455 dxda2 = dxda * dxda;
5456 dyda2 = dyda * dyda;
5457 dxao2 = dxao * dxao;
5458 dyao2 = dyao * dyao;
5459 /* Find the lengths of the triangle's three edges. */
5460 apexlen = dxod2 + dyod2;
5461 orglen = dxda2 + dyda2;
5462 destlen = dxao2 + dyao2;
5463 if ((apexlen < orglen) && (apexlen < destlen)) {
5464 /* The edge opposite the apex is shortest. */
5465 /* Find the square of the cosine of the angle at the apex. */
5466 angle = dxda * dxao + dyda * dyao;
5467 angle = angle * angle / (orglen * destlen);
5468 anglevertex = tapex;
5469 lnext(*testtri, sametesttri);
5470 tspivot(sametesttri, edge1);
5471 lnextself(sametesttri);
5472 tspivot(sametesttri, edge2);
5473 } else if (orglen < destlen) {
5474 /* The edge opposite the origin is shortest. */
5475 /* Find the square of the cosine of the angle at the origin. */
5476 angle = dxod * dxao + dyod * dyao;
5477 angle = angle * angle / (apexlen * destlen);
5479 tspivot(*testtri, edge1);
5480 lprev(*testtri, sametesttri);
5481 tspivot(sametesttri, edge2);
5483 /* The edge opposite the destination is shortest. */
5484 /* Find the square of the cosine of the angle at the destination. */
5485 angle = dxod * dxda + dyod * dyda;
5486 angle = angle * angle / (apexlen * orglen);
5487 anglevertex = tdest;
5488 tspivot(*testtri, edge1);
5489 lnext(*testtri, sametesttri);
5490 tspivot(sametesttri, edge2);
5492 /* Check if both edges that form the angle are segments. */
5493 if ((edge1.sh != dummysh) && (edge2.sh != dummysh)) {
5494 /* The angle is a segment intersection. */
5495 if ((angle > 0.9924) && !quiet) { /* Roughly 5 degrees. */
5497 /* Beware of a floating exception in acos(). */
5500 /* Find the actual angle in degrees, for printing. */
5501 angle = acos(sqrt(angle)) * (180.0 / PI);
5503 "Warning: Small angle (%.4g degrees) between segments at point\n",
5505 printf(" (%.12g, %.12g)\n", anglevertex[0], anglevertex[1]);
5507 /* Don't add this bad triangle to the list; there's nothing that */
5508 /* can be done about a small angle between two segments. */
5511 /* Check whether the angle is smaller than permitted. */
5512 if (angle > goodangle) {
5513 /* Add this triangle to the list of bad triangles. */
5514 enqueuebadtri(testtri, angle, tapex, torg, tdest);
5517 if (vararea || fixedarea) {
5518 /* Check whether the area is larger than permitted. */
5519 area = 0.5 * (dxod * dyda - dyod * dxda);
5520 if (fixedarea && (area > maxarea)) {
5521 /* Add this triangle to the list of bad triangles. */
5522 enqueuebadtri(testtri, angle, tapex, torg, tdest);
5523 } else if (vararea) {
5524 /* Nonpositive area constraints are treated as unconstrained. */
5525 if ((area > areabound(*testtri)) && (areabound(*testtri) > 0.0)) {
5526 /* Add this triangle to the list of bad triangles. */
5527 enqueuebadtri(testtri, angle, tapex, torg, tdest);
5533 #endif /* not CDT_ONLY */
5537 /********* Mesh quality testing routines end here *********/
5539 /********* Point location routines begin here *********/
5543 /*****************************************************************************/
5545 /* makepointmap() Construct a mapping from points to triangles to improve */
5546 /* the speed of point location for segment insertion. */
5548 /* Traverses all the triangles, and provides each corner of each triangle */
5549 /* with a pointer to that triangle. Of course, pointers will be */
5550 /* overwritten by other pointers because (almost) each point is a corner */
5551 /* of several triangles, but in the end every point will point to some */
5552 /* triangle that contains it. */
5554 /*****************************************************************************/
5558 struct triedge triangleloop;
5562 printf(" Constructing mapping from points to triangles.\n");
5564 traversalinit(&triangles);
5565 triangleloop.tri = triangletraverse();
5566 while (triangleloop.tri != (triangle *) NULL) {
5567 /* Check all three points of the triangle. */
5568 for (triangleloop.orient = 0; triangleloop.orient < 3;
5569 triangleloop.orient++) {
5570 org(triangleloop, triorg);
5571 setpoint2tri(triorg, encode(triangleloop));
5573 triangleloop.tri = triangletraverse();
5577 /*****************************************************************************/
5579 /* preciselocate() Find a triangle or edge containing a given point. */
5581 /* Begins its search from `searchtri'. It is important that `searchtri' */
5582 /* be a handle with the property that `searchpoint' is strictly to the left */
5583 /* of the edge denoted by `searchtri', or is collinear with that edge and */
5584 /* does not intersect that edge. (In particular, `searchpoint' should not */
5585 /* be the origin or destination of that edge.) */
5587 /* These conditions are imposed because preciselocate() is normally used in */
5588 /* one of two situations: */
5590 /* (1) To try to find the location to insert a new point. Normally, we */
5591 /* know an edge that the point is strictly to the left of. In the */
5592 /* incremental Delaunay algorithm, that edge is a bounding box edge. */
5593 /* In Ruppert's Delaunay refinement algorithm for quality meshing, */
5594 /* that edge is the shortest edge of the triangle whose circumcenter */
5595 /* is being inserted. */
5597 /* (2) To try to find an existing point. In this case, any edge on the */
5598 /* convex hull is a good starting edge. The possibility that the */
5599 /* vertex one seeks is an endpoint of the starting edge must be */
5600 /* screened out before preciselocate() is called. */
5602 /* On completion, `searchtri' is a triangle that contains `searchpoint'. */
5604 /* This implementation differs from that given by Guibas and Stolfi. It */
5605 /* walks from triangle to triangle, crossing an edge only if `searchpoint' */
5606 /* is on the other side of the line containing that edge. After entering */
5607 /* a triangle, there are two edges by which one can leave that triangle. */
5608 /* If both edges are valid (`searchpoint' is on the other side of both */
5609 /* edges), one of the two is chosen by drawing a line perpendicular to */
5610 /* the entry edge (whose endpoints are `forg' and `fdest') passing through */
5611 /* `fapex'. Depending on which side of this perpendicular `searchpoint' */
5612 /* falls on, an exit edge is chosen. */
5614 /* This implementation is empirically faster than the Guibas and Stolfi */
5615 /* point location routine (which I originally used), which tends to spiral */
5616 /* in toward its target. */
5618 /* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */
5619 /* is a handle whose origin is the existing vertex. */
5621 /* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */
5622 /* handle whose primary edge is the edge on which the point lies. */
5624 /* Returns INTRIANGLE if the point lies strictly within a triangle. */
5625 /* `searchtri' is a handle on the triangle that contains the point. */
5627 /* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */
5628 /* handle whose primary edge the point is to the right of. This might */
5629 /* occur when the circumcenter of a triangle falls just slightly outside */
5630 /* the mesh due to floating-point roundoff error. It also occurs when */
5631 /* seeking a hole or region point that a foolish user has placed outside */
5634 /* WARNING: This routine is designed for convex triangulations, and will */
5635 /* not generally work after the holes and concavities have been carved. */
5636 /* However, it can still be used to find the circumcenter of a triangle, as */
5637 /* long as the search is begun from the triangle in question. */
5639 /*****************************************************************************/
5641 enum locateresult preciselocate(searchpoint, searchtri)
5643 struct triedge *searchtri;
5645 struct triedge backtracktri;
5646 point forg, fdest, fapex;
5648 REAL orgorient, destorient;
5650 triangle ptr; /* Temporary variable used by sym(). */
5653 printf(" Searching for point (%.12g, %.12g).\n",
5654 searchpoint[0], searchpoint[1]);
5657 org(*searchtri, forg);
5658 dest(*searchtri, fdest);
5659 apex(*searchtri, fapex);
5662 printf(" At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
5663 forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
5665 /* Check whether the apex is the point we seek. */
5666 if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
5667 lprevself(*searchtri);
5670 /* Does the point lie on the other side of the line defined by the */
5671 /* triangle edge opposite the triangle's destination? */
5672 destorient = counterclockwise(forg, fapex, searchpoint);
5673 /* Does the point lie on the other side of the line defined by the */
5674 /* triangle edge opposite the triangle's origin? */
5675 orgorient = counterclockwise(fapex, fdest, searchpoint);
5676 if (destorient > 0.0) {
5677 if (orgorient > 0.0) {
5678 /* Move left if the inner product of (fapex - searchpoint) and */
5679 /* (fdest - forg) is positive. This is equivalent to drawing */
5680 /* a line perpendicular to the line (forg, fdest) passing */
5681 /* through `fapex', and determining which side of this line */
5682 /* `searchpoint' falls on. */
5683 moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
5684 (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
5689 if (orgorient > 0.0) {
5692 /* The point we seek must be on the boundary of or inside this */
5694 if (destorient == 0.0) {
5695 lprevself(*searchtri);
5698 if (orgorient == 0.0) {
5699 lnextself(*searchtri);
5706 /* Move to another triangle. Leave a trace `backtracktri' in case */
5707 /* floating-point roundoff or some such bogey causes us to walk */
5708 /* off a boundary of the triangulation. We can just bounce off */
5709 /* the boundary as if it were an elastic band. */
5711 lprev(*searchtri, backtracktri);
5714 lnext(*searchtri, backtracktri);
5717 sym(backtracktri, *searchtri);
5719 /* Check for walking off the edge. */
5720 if (searchtri->tri == dummytri) {
5722 triedgecopy(backtracktri, *searchtri);
5726 apex(*searchtri, fapex);
5727 /* Check if the point really is beyond the triangulation boundary. */
5728 destorient = counterclockwise(forg, fapex, searchpoint);
5729 orgorient = counterclockwise(fapex, fdest, searchpoint);
5730 if ((orgorient < 0.0) && (destorient < 0.0)) {
5734 apex(*searchtri, fapex);
5739 /*****************************************************************************/
5741 /* locate() Find a triangle or edge containing a given point. */
5743 /* Searching begins from one of: the input `searchtri', a recently */
5744 /* encountered triangle `recenttri', or from a triangle chosen from a */
5745 /* random sample. The choice is made by determining which triangle's */
5746 /* origin is closest to the point we are searcing for. Normally, */
5747 /* `searchtri' should be a handle on the convex hull of the triangulation. */
5749 /* Details on the random sampling method can be found in the Mucke, Saias, */
5750 /* and Zhu paper cited in the header of this code. */
5752 /* On completion, `searchtri' is a triangle that contains `searchpoint'. */
5754 /* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */
5755 /* is a handle whose origin is the existing vertex. */
5757 /* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */
5758 /* handle whose primary edge is the edge on which the point lies. */
5760 /* Returns INTRIANGLE if the point lies strictly within a triangle. */
5761 /* `searchtri' is a handle on the triangle that contains the point. */
5763 /* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */
5764 /* handle whose primary edge the point is to the right of. This might */
5765 /* occur when the circumcenter of a triangle falls just slightly outside */
5766 /* the mesh due to floating-point roundoff error. It also occurs when */
5767 /* seeking a hole or region point that a foolish user has placed outside */
5770 /* WARNING: This routine is designed for convex triangulations, and will */
5771 /* not generally work after the holes and concavities have been carved. */
5773 /*****************************************************************************/
5775 enum locateresult locate(searchpoint, searchtri)
5777 struct triedge *searchtri;
5781 struct triedge sampletri;
5783 unsigned long alignptr;
5784 REAL searchdist, dist;
5786 long sampleblocks, samplesperblock, samplenum;
5789 triangle ptr; /* Temporary variable used by sym(). */
5792 printf(" Randomly sampling for a triangle near point (%.12g, %.12g).\n",
5793 searchpoint[0], searchpoint[1]);
5795 /* Record the distance from the suggested starting triangle to the */
5796 /* point we seek. */
5797 org(*searchtri, torg);
5798 searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
5799 + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
5801 printf(" Boundary triangle has origin (%.12g, %.12g).\n",
5805 /* If a recently encountered triangle has been recorded and has not been */
5806 /* deallocated, test it as a good starting point. */
5807 if (recenttri.tri != (triangle *) NULL) {
5808 if (recenttri.tri[3] != (triangle) NULL) {
5809 org(recenttri, torg);
5810 if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
5811 triedgecopy(recenttri, *searchtri);
5814 dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
5815 + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
5816 if (dist < searchdist) {
5817 triedgecopy(recenttri, *searchtri);
5820 printf(" Choosing recent triangle with origin (%.12g, %.12g).\n",
5827 /* The number of random samples taken is proportional to the cube root of */
5828 /* the number of triangles in the mesh. The next bit of code assumes */
5829 /* that the number of triangles increases monotonically. */
5830 while (SAMPLEFACTOR * samples * samples * samples < triangles.items) {
5833 triblocks = (triangles.maxitems + TRIPERBLOCK - 1) / TRIPERBLOCK;
5834 samplesperblock = 1 + (samples / triblocks);
5835 sampleblocks = samples / samplesperblock;
5836 sampleblock = triangles.firstblock;
5837 sampletri.orient = 0;
5838 for (i = 0; i < sampleblocks; i++) {
5839 alignptr = (unsigned long) (sampleblock + 1);
5840 firsttri = (triangle *) (alignptr + (unsigned long) triangles.alignbytes
5841 - (alignptr % (unsigned long) triangles.alignbytes));
5842 for (j = 0; j < samplesperblock; j++) {
5843 if (i == triblocks - 1) {
5844 samplenum = randomnation((int)
5845 (triangles.maxitems - (i * TRIPERBLOCK)));
5847 samplenum = randomnation(TRIPERBLOCK);
5849 sampletri.tri = (triangle *)
5850 (firsttri + (samplenum * triangles.itemwords));
5851 if (sampletri.tri[3] != (triangle) NULL) {
5852 org(sampletri, torg);
5853 dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
5854 + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
5855 if (dist < searchdist) {
5856 triedgecopy(sampletri, *searchtri);
5859 printf(" Choosing triangle with origin (%.12g, %.12g).\n",
5865 sampleblock = (VOID **) *sampleblock;
5868 org(*searchtri, torg);
5869 dest(*searchtri, tdest);
5870 /* Check the starting triangle's vertices. */
5871 if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
5874 if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
5875 lnextself(*searchtri);
5878 /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
5879 ahead = counterclockwise(torg, tdest, searchpoint);
5881 /* Turn around so that `searchpoint' is to the left of the */
5882 /* edge specified by `searchtri'. */
5883 symself(*searchtri);
5884 } else if (ahead == 0.0) {
5885 /* Check if `searchpoint' is between `torg' and `tdest'. */
5886 if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0]))
5887 && ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
5891 return preciselocate(searchpoint, searchtri);
5896 /********* Point location routines end here *********/
5898 /********* Mesh transformation routines begin here *********/
5902 /*****************************************************************************/
5904 /* insertshelle() Create a new shell edge and insert it between two */
5907 /* The new shell edge is inserted at the edge described by the handle */
5908 /* `tri'. Its vertices are properly initialized. The marker `shellemark' */
5909 /* is applied to the shell edge and, if appropriate, its vertices. */
5911 /*****************************************************************************/
5913 void insertshelle(tri, shellemark)
5914 struct triedge *tri; /* Edge at which to insert the new shell edge. */
5915 int shellemark; /* Marker for the new shell edge. */
5917 struct triedge oppotri;
5918 struct edge newshelle;
5919 point triorg, tridest;
5920 triangle ptr; /* Temporary variable used by sym(). */
5921 shelle sptr; /* Temporary variable used by tspivot(). */
5923 /* Mark points if possible. */
5925 dest(*tri, tridest);
5926 if (pointmark(triorg) == 0) {
5927 setpointmark(triorg, shellemark);
5929 if (pointmark(tridest) == 0) {
5930 setpointmark(tridest, shellemark);
5932 /* Check if there's already a shell edge here. */
5933 tspivot(*tri, newshelle);
5934 if (newshelle.sh == dummysh) {
5935 /* Make new shell edge and initialize its vertices. */
5936 makeshelle(&newshelle);
5937 setsorg(newshelle, tridest);
5938 setsdest(newshelle, triorg);
5939 /* Bond new shell edge to the two triangles it is sandwiched between. */
5940 /* Note that the facing triangle `oppotri' might be equal to */
5941 /* `dummytri' (outer space), but the new shell edge is bonded to it */
5943 tsbond(*tri, newshelle);
5945 ssymself(newshelle);
5946 tsbond(oppotri, newshelle);
5947 setmark(newshelle, shellemark);
5949 printf(" Inserting new ");
5950 printshelle(&newshelle);
5953 if (mark(newshelle) == 0) {
5954 setmark(newshelle, shellemark);
5959 /*****************************************************************************/
5963 /* A "local transformation" replaces a small set of triangles with another */
5964 /* set of triangles. This may or may not involve inserting or deleting a */
5967 /* The term "casing" is used to describe the set of triangles that are */
5968 /* attached to the triangles being transformed, but are not transformed */
5969 /* themselves. Think of the casing as a fixed hollow structure inside */
5970 /* which all the action happens. A "casing" is only defined relative to */
5971 /* a single transformation; each occurrence of a transformation will */
5972 /* involve a different casing. */
5974 /* A "shell" is similar to a "casing". The term "shell" describes the set */
5975 /* of shell edges (if any) that are attached to the triangles being */
5976 /* transformed. However, I sometimes use "shell" to refer to a single */
5977 /* shell edge, so don't get confused. */
5979 /*****************************************************************************/
5981 /*****************************************************************************/
5983 /* flip() Transform two triangles to two different triangles by flipping */
5984 /* an edge within a quadrilateral. */
5986 /* Imagine the original triangles, abc and bad, oriented so that the */
5987 /* shared edge ab lies in a horizontal plane, with the point b on the left */
5988 /* and the point a on the right. The point c lies below the edge, and the */
5989 /* point d lies above the edge. The `flipedge' handle holds the edge ab */
5990 /* of triangle abc, and is directed left, from vertex a to vertex b. */
5992 /* The triangles abc and bad are deleted and replaced by the triangles cdb */
5993 /* and dca. The triangles that represent abc and bad are NOT deallocated; */
5994 /* they are reused for dca and cdb, respectively. Hence, any handles that */
5995 /* may have held the original triangles are still valid, although not */
5996 /* directed as they were before. */
5998 /* Upon completion of this routine, the `flipedge' handle holds the edge */
5999 /* dc of triangle dca, and is directed down, from vertex d to vertex c. */
6000 /* (Hence, the two triangles have rotated counterclockwise.) */
6002 /* WARNING: This transformation is geometrically valid only if the */
6003 /* quadrilateral adbc is convex. Furthermore, this transformation is */
6004 /* valid only if there is not a shell edge between the triangles abc and */
6005 /* bad. This routine does not check either of these preconditions, and */
6006 /* it is the responsibility of the calling routine to ensure that they are */
6007 /* met. If they are not, the streets shall be filled with wailing and */
6008 /* gnashing of teeth. */
6010 /*****************************************************************************/
6013 struct triedge *flipedge; /* Handle for the triangle abc. */
6015 struct triedge botleft, botright;
6016 struct triedge topleft, topright;
6018 struct triedge botlcasing, botrcasing;
6019 struct triedge toplcasing, toprcasing;
6020 struct edge botlshelle, botrshelle;
6021 struct edge toplshelle, toprshelle;
6022 point leftpoint, rightpoint, botpoint;
6024 triangle ptr; /* Temporary variable used by sym(). */
6025 shelle sptr; /* Temporary variable used by tspivot(). */
6027 /* Identify the vertices of the quadrilateral. */
6028 org(*flipedge, rightpoint);
6029 dest(*flipedge, leftpoint);
6030 apex(*flipedge, botpoint);
6031 sym(*flipedge, top);
6033 if (top.tri == dummytri) {
6034 printf("Internal error in flip(): Attempt to flip on boundary.\n");
6035 lnextself(*flipedge);
6038 if (checksegments) {
6039 tspivot(*flipedge, toplshelle);
6040 if (toplshelle.sh != dummysh) {
6041 printf("Internal error in flip(): Attempt to flip a segment.\n");
6042 lnextself(*flipedge);
6046 #endif /* SELF_CHECK */
6047 apex(top, farpoint);
6049 /* Identify the casing of the quadrilateral. */
6050 lprev(top, topleft);
6051 sym(topleft, toplcasing);
6052 lnext(top, topright);
6053 sym(topright, toprcasing);
6054 lnext(*flipedge, botleft);
6055 sym(botleft, botlcasing);
6056 lprev(*flipedge, botright);
6057 sym(botright, botrcasing);
6058 /* Rotate the quadrilateral one-quarter turn counterclockwise. */
6059 bond(topleft, botlcasing);
6060 bond(botleft, botrcasing);
6061 bond(botright, toprcasing);
6062 bond(topright, toplcasing);
6064 if (checksegments) {
6065 /* Check for shell edges and rebond them to the quadrilateral. */
6066 tspivot(topleft, toplshelle);
6067 tspivot(botleft, botlshelle);
6068 tspivot(botright, botrshelle);
6069 tspivot(topright, toprshelle);
6070 if (toplshelle.sh == dummysh) {
6071 tsdissolve(topright);
6073 tsbond(topright, toplshelle);
6075 if (botlshelle.sh == dummysh) {
6076 tsdissolve(topleft);
6078 tsbond(topleft, botlshelle);
6080 if (botrshelle.sh == dummysh) {
6081 tsdissolve(botleft);
6083 tsbond(botleft, botrshelle);
6085 if (toprshelle.sh == dummysh) {
6086 tsdissolve(botright);
6088 tsbond(botright, toprshelle);
6092 /* New point assignments for the rotated quadrilateral. */
6093 setorg(*flipedge, farpoint);
6094 setdest(*flipedge, botpoint);
6095 setapex(*flipedge, rightpoint);
6096 setorg(top, botpoint);
6097 setdest(top, farpoint);
6098 setapex(top, leftpoint);
6100 printf(" Edge flip results in left ");
6102 printtriangle(&topleft);
6103 printf(" and right ");
6104 printtriangle(flipedge);
6108 /*****************************************************************************/
6110 /* insertsite() Insert a vertex into a Delaunay triangulation, */
6111 /* performing flips as necessary to maintain the Delaunay */
6114 /* The point `insertpoint' is located. If `searchtri.tri' is not NULL, */
6115 /* the search for the containing triangle begins from `searchtri'. If */
6116 /* `searchtri.tri' is NULL, a full point location procedure is called. */
6117 /* If `insertpoint' is found inside a triangle, the triangle is split into */
6118 /* three; if `insertpoint' lies on an edge, the edge is split in two, */
6119 /* thereby splitting the two adjacent triangles into four. Edge flips are */
6120 /* used to restore the Delaunay property. If `insertpoint' lies on an */
6121 /* existing vertex, no action is taken, and the value DUPLICATEPOINT is */
6122 /* returned. On return, `searchtri' is set to a handle whose origin is the */
6123 /* existing vertex. */
6125 /* Normally, the parameter `splitedge' is set to NULL, implying that no */
6126 /* segment should be split. In this case, if `insertpoint' is found to */
6127 /* lie on a segment, no action is taken, and the value VIOLATINGPOINT is */
6128 /* returned. On return, `searchtri' is set to a handle whose primary edge */
6129 /* is the violated segment. */
6131 /* If the calling routine wishes to split a segment by inserting a point in */
6132 /* it, the parameter `splitedge' should be that segment. In this case, */
6133 /* `searchtri' MUST be the triangle handle reached by pivoting from that */
6134 /* segment; no point location is done. */
6136 /* `segmentflaws' and `triflaws' are flags that indicate whether or not */
6137 /* there should be checks for the creation of encroached segments or bad */
6138 /* quality faces. If a newly inserted point encroaches upon segments, */
6139 /* these segments are added to the list of segments to be split if */
6140 /* `segmentflaws' is set. If bad triangles are created, these are added */
6141 /* to the queue if `triflaws' is set. */
6143 /* If a duplicate point or violated segment does not prevent the point */
6144 /* from being inserted, the return value will be ENCROACHINGPOINT if the */
6145 /* point encroaches upon a segment (and checking is enabled), or */
6146 /* SUCCESSFULPOINT otherwise. In either case, `searchtri' is set to a */
6147 /* handle whose origin is the newly inserted vertex. */
6149 /* insertsite() does not use flip() for reasons of speed; some */
6150 /* information can be reused from edge flip to edge flip, like the */
6151 /* locations of shell edges. */
6153 /*****************************************************************************/
6155 enum insertsiteresult insertsite(insertpoint, searchtri, splitedge,
6156 segmentflaws, triflaws)
6158 struct triedge *searchtri;
6159 struct edge *splitedge;
6163 struct triedge horiz;
6165 struct triedge botleft, botright;
6166 struct triedge topleft, topright;
6167 struct triedge newbotleft, newbotright;
6168 struct triedge newtopright;
6169 struct triedge botlcasing, botrcasing;
6170 struct triedge toplcasing, toprcasing;
6171 struct triedge testtri;
6172 struct edge botlshelle, botrshelle;
6173 struct edge toplshelle, toprshelle;
6174 struct edge brokenshelle;
6175 struct edge checkshelle;
6176 struct edge rightedge;
6177 struct edge newedge;
6178 struct edge *encroached;
6180 point leftpoint, rightpoint, botpoint, toppoint, farpoint;
6183 enum insertsiteresult success;
6184 enum locateresult intersect;
6188 triangle ptr; /* Temporary variable used by sym(). */
6189 shelle sptr; /* Temporary variable used by spivot() and tspivot(). */
6192 printf(" Inserting (%.12g, %.12g).\n", insertpoint[0], insertpoint[1]);
6194 if (splitedge == (struct edge *) NULL) {
6195 /* Find the location of the point to be inserted. Check if a good */
6196 /* starting triangle has already been provided by the caller. */
6197 if (searchtri->tri == (triangle *) NULL) {
6198 /* Find a boundary triangle. */
6199 horiz.tri = dummytri;
6202 /* Search for a triangle containing `insertpoint'. */
6203 intersect = locate(insertpoint, &horiz);
6205 /* Start searching from the triangle provided by the caller. */
6206 triedgecopy(*searchtri, horiz);
6207 intersect = preciselocate(insertpoint, &horiz);
6210 /* The calling routine provides the edge in which the point is inserted. */
6211 triedgecopy(*searchtri, horiz);
6214 if (intersect == ONVERTEX) {
6215 /* There's already a vertex there. Return in `searchtri' a triangle */
6216 /* whose origin is the existing vertex. */
6217 triedgecopy(horiz, *searchtri);
6218 triedgecopy(horiz, recenttri);
6219 return DUPLICATEPOINT;
6221 if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
6222 /* The vertex falls on an edge or boundary. */
6223 if (checksegments && (splitedge == (struct edge *) NULL)) {
6224 /* Check whether the vertex falls on a shell edge. */
6225 tspivot(horiz, brokenshelle);
6226 if (brokenshelle.sh != dummysh) {
6227 /* The vertex falls on a shell edge. */
6229 if (nobisect == 0) {
6230 /* Add the shell edge to the list of encroached segments. */
6231 encroached = (struct edge *) poolalloc(&badsegments);
6232 shellecopy(brokenshelle, *encroached);
6233 } else if ((nobisect == 1) && (intersect == ONEDGE)) {
6234 /* This segment may be split only if it is an internal boundary. */
6235 sym(horiz, testtri);
6236 if (testtri.tri != dummytri) {
6237 /* Add the shell edge to the list of encroached segments. */
6238 encroached = (struct edge *) poolalloc(&badsegments);
6239 shellecopy(brokenshelle, *encroached);
6243 /* Return a handle whose primary edge contains the point, */
6244 /* which has not been inserted. */
6245 triedgecopy(horiz, *searchtri);
6246 triedgecopy(horiz, recenttri);
6247 return VIOLATINGPOINT;
6250 /* Insert the point on an edge, dividing one triangle into two (if */
6251 /* the edge lies on a boundary) or two triangles into four. */
6252 lprev(horiz, botright);
6253 sym(botright, botrcasing);
6254 sym(horiz, topright);
6255 /* Is there a second triangle? (Or does this edge lie on a boundary?) */
6256 mirrorflag = topright.tri != dummytri;
6258 lnextself(topright);
6259 sym(topright, toprcasing);
6260 maketriangle(&newtopright);
6262 /* Splitting the boundary edge increases the number of boundary edges. */
6265 maketriangle(&newbotright);
6267 /* Set the vertices of changed and new triangles. */
6268 org(horiz, rightpoint);
6269 dest(horiz, leftpoint);
6270 apex(horiz, botpoint);
6271 setorg(newbotright, botpoint);
6272 setdest(newbotright, rightpoint);
6273 setapex(newbotright, insertpoint);
6274 setorg(horiz, insertpoint);
6275 for (i = 0; i < eextras; i++) {
6276 /* Set the element attributes of a new triangle. */
6277 setelemattribute(newbotright, i, elemattribute(botright, i));
6280 /* Set the area constraint of a new triangle. */
6281 setareabound(newbotright, areabound(botright));
6284 dest(topright, toppoint);
6285 setorg(newtopright, rightpoint);
6286 setdest(newtopright, toppoint);
6287 setapex(newtopright, insertpoint);
6288 setorg(topright, insertpoint);
6289 for (i = 0; i < eextras; i++) {
6290 /* Set the element attributes of another new triangle. */
6291 setelemattribute(newtopright, i, elemattribute(topright, i));
6294 /* Set the area constraint of another new triangle. */
6295 setareabound(newtopright, areabound(topright));
6299 /* There may be shell edges that need to be bonded */
6300 /* to the new triangle(s). */
6301 if (checksegments) {
6302 tspivot(botright, botrshelle);
6303 if (botrshelle.sh != dummysh) {
6304 tsdissolve(botright);
6305 tsbond(newbotright, botrshelle);
6308 tspivot(topright, toprshelle);
6309 if (toprshelle.sh != dummysh) {
6310 tsdissolve(topright);
6311 tsbond(newtopright, toprshelle);
6316 /* Bond the new triangle(s) to the surrounding triangles. */
6317 bond(newbotright, botrcasing);
6318 lprevself(newbotright);
6319 bond(newbotright, botright);
6320 lprevself(newbotright);
6322 bond(newtopright, toprcasing);
6323 lnextself(newtopright);
6324 bond(newtopright, topright);
6325 lnextself(newtopright);
6326 bond(newtopright, newbotright);
6329 if (splitedge != (struct edge *) NULL) {
6330 /* Split the shell edge into two. */
6331 setsdest(*splitedge, insertpoint);
6332 ssymself(*splitedge);
6333 spivot(*splitedge, rightedge);
6334 insertshelle(&newbotright, mark(*splitedge));
6335 tspivot(newbotright, newedge);
6336 sbond(*splitedge, newedge);
6338 sbond(newedge, rightedge);
6339 ssymself(*splitedge);
6343 if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) {
6344 printf("Internal error in insertsite():\n");
6345 printf(" Clockwise triangle prior to edge point insertion (bottom).\n");
6348 if (counterclockwise(leftpoint, rightpoint, toppoint) < 0.0) {
6349 printf("Internal error in insertsite():\n");
6350 printf(" Clockwise triangle prior to edge point insertion (top).\n");
6352 if (counterclockwise(rightpoint, toppoint, insertpoint) < 0.0) {
6353 printf("Internal error in insertsite():\n");
6354 printf(" Clockwise triangle after edge point insertion (top right).\n"
6357 if (counterclockwise(toppoint, leftpoint, insertpoint) < 0.0) {
6358 printf("Internal error in insertsite():\n");
6359 printf(" Clockwise triangle after edge point insertion (top left).\n"
6363 if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) {
6364 printf("Internal error in insertsite():\n");
6365 printf(" Clockwise triangle after edge point insertion (bottom left).\n"
6368 if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
6369 printf("Internal error in insertsite():\n");
6371 " Clockwise triangle after edge point insertion (bottom right).\n");
6373 #endif /* SELF_CHECK */
6375 printf(" Updating bottom left ");
6376 printtriangle(&botright);
6378 printf(" Updating top left ");
6379 printtriangle(&topright);
6380 printf(" Creating top right ");
6381 printtriangle(&newtopright);
6383 printf(" Creating bottom right ");
6384 printtriangle(&newbotright);
6387 /* Position `horiz' on the first edge to check for */
6388 /* the Delaunay property. */
6391 /* Insert the point in a triangle, splitting it into three. */
6392 lnext(horiz, botleft);
6393 lprev(horiz, botright);
6394 sym(botleft, botlcasing);
6395 sym(botright, botrcasing);
6396 maketriangle(&newbotleft);
6397 maketriangle(&newbotright);
6399 /* Set the vertices of changed and new triangles. */
6400 org(horiz, rightpoint);
6401 dest(horiz, leftpoint);
6402 apex(horiz, botpoint);
6403 setorg(newbotleft, leftpoint);
6404 setdest(newbotleft, botpoint);
6405 setapex(newbotleft, insertpoint);
6406 setorg(newbotright, botpoint);
6407 setdest(newbotright, rightpoint);
6408 setapex(newbotright, insertpoint);
6409 setapex(horiz, insertpoint);
6410 for (i = 0; i < eextras; i++) {
6411 /* Set the element attributes of the new triangles. */
6412 attrib = elemattribute(horiz, i);
6413 setelemattribute(newbotleft, i, attrib);
6414 setelemattribute(newbotright, i, attrib);
6417 /* Set the area constraint of the new triangles. */
6418 area = areabound(horiz);
6419 setareabound(newbotleft, area);
6420 setareabound(newbotright, area);
6423 /* There may be shell edges that need to be bonded */
6424 /* to the new triangles. */
6425 if (checksegments) {
6426 tspivot(botleft, botlshelle);
6427 if (botlshelle.sh != dummysh) {
6428 tsdissolve(botleft);
6429 tsbond(newbotleft, botlshelle);
6431 tspivot(botright, botrshelle);
6432 if (botrshelle.sh != dummysh) {
6433 tsdissolve(botright);
6434 tsbond(newbotright, botrshelle);
6438 /* Bond the new triangles to the surrounding triangles. */
6439 bond(newbotleft, botlcasing);
6440 bond(newbotright, botrcasing);
6441 lnextself(newbotleft);
6442 lprevself(newbotright);
6443 bond(newbotleft, newbotright);
6444 lnextself(newbotleft);
6445 bond(botleft, newbotleft);
6446 lprevself(newbotright);
6447 bond(botright, newbotright);
6450 if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) {
6451 printf("Internal error in insertsite():\n");
6452 printf(" Clockwise triangle prior to point insertion.\n");
6454 if (counterclockwise(rightpoint, leftpoint, insertpoint) < 0.0) {
6455 printf("Internal error in insertsite():\n");
6456 printf(" Clockwise triangle after point insertion (top).\n");
6458 if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) {
6459 printf("Internal error in insertsite():\n");
6460 printf(" Clockwise triangle after point insertion (left).\n");
6462 if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
6463 printf("Internal error in insertsite():\n");
6464 printf(" Clockwise triangle after point insertion (right).\n");
6466 #endif /* SELF_CHECK */
6468 printf(" Updating top ");
6469 printtriangle(&horiz);
6470 printf(" Creating left ");
6471 printtriangle(&newbotleft);
6472 printf(" Creating right ");
6473 printtriangle(&newbotright);
6477 /* The insertion is successful by default, unless an encroached */
6478 /* edge is found. */
6479 success = SUCCESSFULPOINT;
6480 /* Circle around the newly inserted vertex, checking each edge opposite */
6481 /* it for the Delaunay property. Non-Delaunay edges are flipped. */
6482 /* `horiz' is always the edge being checked. `first' marks where to */
6483 /* stop circling. */
6486 dest(horiz, leftpoint);
6487 /* Circle until finished. */
6489 /* By default, the edge will be flipped. */
6491 if (checksegments) {
6492 /* Check for a segment, which cannot be flipped. */
6493 tspivot(horiz, checkshelle);
6494 if (checkshelle.sh != dummysh) {
6495 /* The edge is a segment and cannot be flipped. */
6499 /* Does the new point encroach upon this segment? */
6500 if (checkedge4encroach(&checkshelle)) {
6501 success = ENCROACHINGPOINT;
6504 #endif /* not CDT_ONLY */
6508 /* Check if the edge is a boundary edge. */
6510 if (top.tri == dummytri) {
6511 /* The edge is a boundary edge and cannot be flipped. */
6514 /* Find the point on the other side of the edge. */
6515 apex(top, farpoint);
6516 /* In the incremental Delaunay triangulation algorithm, any of */
6517 /* `leftpoint', `rightpoint', and `farpoint' could be vertices */
6518 /* of the triangular bounding box. These vertices must be */
6519 /* treated as if they are infinitely distant, even though their */
6520 /* "coordinates" are not. */
6521 if ((leftpoint == infpoint1) || (leftpoint == infpoint2)
6522 || (leftpoint == infpoint3)) {
6523 /* `leftpoint' is infinitely distant. Check the convexity of */
6524 /* the boundary of the triangulation. 'farpoint' might be */
6525 /* infinite as well, but trust me, this same condition */
6526 /* should be applied. */
6527 doflip = counterclockwise(insertpoint, rightpoint, farpoint) > 0.0;
6528 } else if ((rightpoint == infpoint1) || (rightpoint == infpoint2)
6529 || (rightpoint == infpoint3)) {
6530 /* `rightpoint' is infinitely distant. Check the convexity of */
6531 /* the boundary of the triangulation. 'farpoint' might be */
6532 /* infinite as well, but trust me, this same condition */
6533 /* should be applied. */
6534 doflip = counterclockwise(farpoint, leftpoint, insertpoint) > 0.0;
6535 } else if ((farpoint == infpoint1) || (farpoint == infpoint2)
6536 || (farpoint == infpoint3)) {
6537 /* `farpoint' is infinitely distant and cannot be inside */
6538 /* the circumcircle of the triangle `horiz'. */
6541 /* Test whether the edge is locally Delaunay. */
6542 doflip = incircle(leftpoint, insertpoint, rightpoint, farpoint)
6546 /* We made it! Flip the edge `horiz' by rotating its containing */
6547 /* quadrilateral (the two triangles adjacent to `horiz'). */
6548 /* Identify the casing of the quadrilateral. */
6549 lprev(top, topleft);
6550 sym(topleft, toplcasing);
6551 lnext(top, topright);
6552 sym(topright, toprcasing);
6553 lnext(horiz, botleft);
6554 sym(botleft, botlcasing);
6555 lprev(horiz, botright);
6556 sym(botright, botrcasing);
6557 /* Rotate the quadrilateral one-quarter turn counterclockwise. */
6558 bond(topleft, botlcasing);
6559 bond(botleft, botrcasing);
6560 bond(botright, toprcasing);
6561 bond(topright, toplcasing);
6562 if (checksegments) {
6563 /* Check for shell edges and rebond them to the quadrilateral. */
6564 tspivot(topleft, toplshelle);
6565 tspivot(botleft, botlshelle);
6566 tspivot(botright, botrshelle);
6567 tspivot(topright, toprshelle);
6568 if (toplshelle.sh == dummysh) {
6569 tsdissolve(topright);
6571 tsbond(topright, toplshelle);
6573 if (botlshelle.sh == dummysh) {
6574 tsdissolve(topleft);
6576 tsbond(topleft, botlshelle);
6578 if (botrshelle.sh == dummysh) {
6579 tsdissolve(botleft);
6581 tsbond(botleft, botrshelle);
6583 if (toprshelle.sh == dummysh) {
6584 tsdissolve(botright);
6586 tsbond(botright, toprshelle);
6589 /* New point assignments for the rotated quadrilateral. */
6590 setorg(horiz, farpoint);
6591 setdest(horiz, insertpoint);
6592 setapex(horiz, rightpoint);
6593 setorg(top, insertpoint);
6594 setdest(top, farpoint);
6595 setapex(top, leftpoint);
6596 for (i = 0; i < eextras; i++) {
6597 /* Take the average of the two triangles' attributes. */
6598 attrib = (REAL)(0.5 * (elemattribute(top, i) + elemattribute(horiz, i)));
6599 setelemattribute(top, i, attrib);
6600 setelemattribute(horiz, i, attrib);
6603 if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
6606 /* Take the average of the two triangles' area constraints. */
6607 /* This prevents small area constraints from migrating a */
6608 /* long, long way from their original location due to flips. */
6609 area = (REAL)(0.5 * (areabound(top) + areabound(horiz)));
6611 setareabound(top, area);
6612 setareabound(horiz, area);
6615 if (insertpoint != (point) NULL) {
6616 if (counterclockwise(leftpoint, insertpoint, rightpoint) < 0.0) {
6617 printf("Internal error in insertsite():\n");
6618 printf(" Clockwise triangle prior to edge flip (bottom).\n");
6620 /* The following test has been removed because constrainededge() */
6621 /* sometimes generates inverted triangles that insertsite() */
6624 if (counterclockwise(rightpoint, farpoint, leftpoint) < 0.0) {
6625 printf("Internal error in insertsite():\n");
6626 printf(" Clockwise triangle prior to edge flip (top).\n");
6629 if (counterclockwise(farpoint, leftpoint, insertpoint) < 0.0) {
6630 printf("Internal error in insertsite():\n");
6631 printf(" Clockwise triangle after edge flip (left).\n");
6633 if (counterclockwise(insertpoint, rightpoint, farpoint) < 0.0) {
6634 printf("Internal error in insertsite():\n");
6635 printf(" Clockwise triangle after edge flip (right).\n");
6638 #endif /* SELF_CHECK */
6640 printf(" Edge flip results in left ");
6642 printtriangle(&topleft);
6643 printf(" and right ");
6644 printtriangle(&horiz);
6646 /* On the next iterations, consider the two edges that were */
6647 /* exposed (this is, are now visible to the newly inserted */
6648 /* point) by the edge flip. */
6650 leftpoint = farpoint;
6655 /* The handle `horiz' is accepted as locally Delaunay. */
6658 /* Check the triangle `horiz' for quality. */
6659 testtriangle(&horiz);
6661 #endif /* not CDT_ONLY */
6662 /* Look for the next edge around the newly inserted point. */
6664 sym(horiz, testtri);
6665 /* Check for finishing a complete revolution about the new point, or */
6666 /* falling off the edge of the triangulation. The latter will */
6667 /* happen when a point is inserted at a boundary. */
6668 if ((leftpoint == first) || (testtri.tri == dummytri)) {
6669 /* We're done. Return a triangle whose origin is the new point. */
6670 lnext(horiz, *searchtri);
6671 lnext(horiz, recenttri);
6674 /* Finish finding the next edge around the newly inserted point. */
6675 lnext(testtri, horiz);
6676 rightpoint = leftpoint;
6677 dest(horiz, leftpoint);
6682 /*****************************************************************************/
6684 /* triangulatepolygon() Find the Delaunay triangulation of a polygon that */
6685 /* has a certain "nice" shape. This includes the */
6686 /* polygons that result from deletion of a point or */
6687 /* insertion of a segment. */
6689 /* This is a conceptually difficult routine. The starting assumption is */
6690 /* that we have a polygon with n sides. n - 1 of these sides are currently */
6691 /* represented as edges in the mesh. One side, called the "base", need not */
6694 /* Inside the polygon is a structure I call a "fan", consisting of n - 1 */
6695 /* triangles that share a common origin. For each of these triangles, the */
6696 /* edge opposite the origin is one of the sides of the polygon. The */
6697 /* primary edge of each triangle is the edge directed from the origin to */
6698 /* the destination; note that this is not the same edge that is a side of */
6699 /* the polygon. `firstedge' is the primary edge of the first triangle. */
6700 /* From there, the triangles follow in counterclockwise order about the */
6701 /* polygon, until `lastedge', the primary edge of the last triangle. */
6702 /* `firstedge' and `lastedge' are probably connected to other triangles */
6703 /* beyond the extremes of the fan, but their identity is not important, as */
6704 /* long as the fan remains connected to them. */
6706 /* Imagine the polygon oriented so that its base is at the bottom. This */
6707 /* puts `firstedge' on the far right, and `lastedge' on the far left. */
6708 /* The right vertex of the base is the destination of `firstedge', and the */
6709 /* left vertex of the base is the apex of `lastedge'. */
6711 /* The challenge now is to find the right sequence of edge flips to */
6712 /* transform the fan into a Delaunay triangulation of the polygon. Each */
6713 /* edge flip effectively removes one triangle from the fan, committing it */
6714 /* to the polygon. The resulting polygon has one fewer edge. If `doflip' */
6715 /* is set, the final flip will be performed, resulting in a fan of one */
6716 /* (useless?) triangle. If `doflip' is not set, the final flip is not */
6717 /* performed, resulting in a fan of two triangles, and an unfinished */
6718 /* triangular polygon that is not yet filled out with a single triangle. */
6719 /* On completion of the routine, `lastedge' is the last remaining triangle, */
6720 /* or the leftmost of the last two. */
6722 /* Although the flips are performed in the order described above, the */
6723 /* decisions about what flips to perform are made in precisely the reverse */
6724 /* order. The recursive triangulatepolygon() procedure makes a decision, */
6725 /* uses up to two recursive calls to triangulate the "subproblems" */
6726 /* (polygons with fewer edges), and then performs an edge flip. */
6728 /* The "decision" it makes is which vertex of the polygon should be */
6729 /* connected to the base. This decision is made by testing every possible */
6730 /* vertex. Once the best vertex is found, the two edges that connect this */
6731 /* vertex to the base become the bases for two smaller polygons. These */
6732 /* are triangulated recursively. Unfortunately, this approach can take */
6733 /* O(n^2) time not only in the worst case, but in many common cases. It's */
6734 /* rarely a big deal for point deletion, where n is rarely larger than ten, */
6735 /* but it could be a big deal for segment insertion, especially if there's */
6736 /* a lot of long segments that each cut many triangles. I ought to code */
6737 /* a faster algorithm some time. */
6739 /* The `edgecount' parameter is the number of sides of the polygon, */
6740 /* including its base. `triflaws' is a flag that determines whether the */
6741 /* new triangles should be tested for quality, and enqueued if they are */
6744 /*****************************************************************************/
6746 void triangulatepolygon(firstedge, lastedge, edgecount, doflip, triflaws)
6747 struct triedge *firstedge;
6748 struct triedge *lastedge;
6753 struct triedge testtri;
6754 struct triedge besttri;
6755 struct triedge tempedge;
6756 point leftbasepoint, rightbasepoint;
6761 triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
6763 /* Identify the base vertices. */
6764 apex(*lastedge, leftbasepoint);
6765 dest(*firstedge, rightbasepoint);
6767 printf(" Triangulating interior polygon at edge\n");
6768 printf(" (%.12g, %.12g) (%.12g, %.12g)\n", leftbasepoint[0],
6769 leftbasepoint[1], rightbasepoint[0], rightbasepoint[1]);
6771 /* Find the best vertex to connect the base to. */
6772 onext(*firstedge, besttri);
6773 dest(besttri, bestpoint);
6774 triedgecopy(besttri, testtri);
6776 for (i = 2; i <= edgecount - 2; i++) {
6778 dest(testtri, testpoint);
6779 /* Is this a better vertex? */
6780 if (incircle(leftbasepoint, rightbasepoint, bestpoint, testpoint) > 0.0) {
6781 triedgecopy(testtri, besttri);
6782 bestpoint = testpoint;
6787 printf(" Connecting edge to (%.12g, %.12g)\n", bestpoint[0],
6790 if (bestnumber > 1) {
6791 /* Recursively triangulate the smaller polygon on the right. */
6792 oprev(besttri, tempedge);
6793 triangulatepolygon(firstedge, &tempedge, bestnumber + 1, 1, triflaws);
6795 if (bestnumber < edgecount - 2) {
6796 /* Recursively triangulate the smaller polygon on the left. */
6797 sym(besttri, tempedge);
6798 triangulatepolygon(&besttri, lastedge, edgecount - bestnumber, 1,
6800 /* Find `besttri' again; it may have been lost to edge flips. */
6801 sym(tempedge, besttri);
6804 /* Do one final edge flip. */
6808 /* Check the quality of the newly committed triangle. */
6809 sym(besttri, testtri);
6810 testtriangle(&testtri);
6812 #endif /* not CDT_ONLY */
6814 /* Return the base triangle. */
6815 triedgecopy(besttri, *lastedge);
6818 /*****************************************************************************/
6820 /* deletesite() Delete a vertex from a Delaunay triangulation, ensuring */
6821 /* that the triangulation remains Delaunay. */
6823 /* The origin of `deltri' is deleted. The union of the triangles adjacent */
6824 /* to this point is a polygon, for which the Delaunay triangulation is */
6825 /* found. Two triangles are removed from the mesh. */
6827 /* Only interior points that do not lie on segments (shell edges) or */
6828 /* boundaries may be deleted. */
6830 /*****************************************************************************/
6834 void deletesite(deltri)
6835 struct triedge *deltri;
6837 struct triedge countingtri;
6838 struct triedge firstedge, lastedge;
6839 struct triedge deltriright;
6840 struct triedge lefttri, righttri;
6841 struct triedge leftcasing, rightcasing;
6842 struct edge leftshelle, rightshelle;
6846 triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
6847 shelle sptr; /* Temporary variable used by tspivot(). */
6849 org(*deltri, delpoint);
6851 printf(" Deleting (%.12g, %.12g).\n", delpoint[0], delpoint[1]);
6853 pointdealloc(delpoint);
6855 /* Count the degree of the point being deleted. */
6856 onext(*deltri, countingtri);
6858 while (!triedgeequal(*deltri, countingtri)) {
6860 if (countingtri.tri == dummytri) {
6861 printf("Internal error in deletesite():\n");
6862 printf(" Attempt to delete boundary point.\n");
6865 #endif /* SELF_CHECK */
6867 onextself(countingtri);
6871 if (edgecount < 3) {
6872 printf("Internal error in deletesite():\n Point has degree %d.\n",
6876 #endif /* SELF_CHECK */
6877 if (edgecount > 3) {
6878 /* Triangulate the polygon defined by the union of all triangles */
6879 /* adjacent to the point being deleted. Check the quality of */
6880 /* the resulting triangles. */
6881 onext(*deltri, firstedge);
6882 oprev(*deltri, lastedge);
6883 triangulatepolygon(&firstedge, &lastedge, edgecount, 0, !nobisect);
6885 /* Splice out two triangles. */
6886 lprev(*deltri, deltriright);
6887 dnext(*deltri, lefttri);
6888 sym(lefttri, leftcasing);
6889 oprev(deltriright, righttri);
6890 sym(righttri, rightcasing);
6891 bond(*deltri, leftcasing);
6892 bond(deltriright, rightcasing);
6893 tspivot(lefttri, leftshelle);
6894 if (leftshelle.sh != dummysh) {
6895 tsbond(*deltri, leftshelle);
6897 tspivot(righttri, rightshelle);
6898 if (rightshelle.sh != dummysh) {
6899 tsbond(deltriright, rightshelle);
6902 /* Set the new origin of `deltri' and check its quality. */
6903 org(lefttri, neworg);
6904 setorg(*deltri, neworg);
6906 testtriangle(deltri);
6909 /* Delete the two spliced-out triangles. */
6910 triangledealloc(lefttri.tri);
6911 triangledealloc(righttri.tri);
6914 #endif /* not CDT_ONLY */
6918 /********* Mesh transformation routines end here *********/
6920 /********* Divide-and-conquer Delaunay triangulation begins here *********/
6924 /*****************************************************************************/
6926 /* The divide-and-conquer bounding box */
6928 /* I originally implemented the divide-and-conquer and incremental Delaunay */
6929 /* triangulations using the edge-based data structure presented by Guibas */
6930 /* and Stolfi. Switching to a triangle-based data structure doubled the */
6931 /* speed. However, I had to think of a few extra tricks to maintain the */
6932 /* elegance of the original algorithms. */
6934 /* The "bounding box" used by my variant of the divide-and-conquer */
6935 /* algorithm uses one triangle for each edge of the convex hull of the */
6936 /* triangulation. These bounding triangles all share a common apical */
6937 /* vertex, which is represented by NULL and which represents nothing. */
6938 /* The bounding triangles are linked in a circular fan about this NULL */
6939 /* vertex, and the edges on the convex hull of the triangulation appear */
6940 /* opposite the NULL vertex. You might find it easiest to imagine that */
6941 /* the NULL vertex is a point in 3D space behind the center of the */
6942 /* triangulation, and that the bounding triangles form a sort of cone. */
6944 /* This bounding box makes it easy to represent degenerate cases. For */
6945 /* instance, the triangulation of two vertices is a single edge. This edge */
6946 /* is represented by two bounding box triangles, one on each "side" of the */
6947 /* edge. These triangles are also linked together in a fan about the NULL */
6950 /* The bounding box also makes it easy to traverse the convex hull, as the */
6951 /* divide-and-conquer algorithm needs to do. */
6953 /*****************************************************************************/
6955 /*****************************************************************************/
6957 /* pointsort() Sort an array of points by x-coordinate, using the */
6958 /* y-coordinate as a secondary key. */
6960 /* Uses quicksort. Randomized O(n log n) time. No, I did not make any of */
6961 /* the usual quicksort mistakes. */
6963 /*****************************************************************************/
6965 void pointsort(sortarray, arraysize)
6971 REAL pivotx, pivoty;
6974 if (arraysize == 2) {
6975 /* Recursive base case. */
6976 if ((sortarray[0][0] > sortarray[1][0]) ||
6977 ((sortarray[0][0] == sortarray[1][0]) &&
6978 (sortarray[0][1] > sortarray[1][1]))) {
6979 temp = sortarray[1];
6980 sortarray[1] = sortarray[0];
6981 sortarray[0] = temp;
6985 /* Choose a random pivot to split the array. */
6986 pivot = (int) randomnation(arraysize);
6987 pivotx = sortarray[pivot][0];
6988 pivoty = sortarray[pivot][1];
6989 /* Split the array. */
6992 while (left < right) {
6993 /* Search for a point whose x-coordinate is too large for the left. */
6996 } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
6997 ((sortarray[left][0] == pivotx) &&
6998 (sortarray[left][1] < pivoty))));
6999 /* Search for a point whose x-coordinate is too small for the right. */
7002 } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
7003 ((sortarray[right][0] == pivotx) &&
7004 (sortarray[right][1] > pivoty))));
7006 /* Swap the left and right points. */
7007 temp = sortarray[left];
7008 sortarray[left] = sortarray[right];
7009 sortarray[right] = temp;
7013 /* Recursively sort the left subset. */
7014 pointsort(sortarray, left);
7016 if (right < arraysize - 2) {
7017 /* Recursively sort the right subset. */
7018 pointsort(&sortarray[right + 1], arraysize - right - 1);
7022 /*****************************************************************************/
7024 /* pointmedian() An order statistic algorithm, almost. Shuffles an array */
7025 /* of points so that the first `median' points occur */
7026 /* lexicographically before the remaining points. */
7028 /* Uses the x-coordinate as the primary key if axis == 0; the y-coordinate */
7029 /* if axis == 1. Very similar to the pointsort() procedure, but runs in */
7030 /* randomized linear time. */
7032 /*****************************************************************************/
7034 void pointmedian(sortarray, arraysize, median, axis)
7042 REAL pivot1, pivot2;
7045 if (arraysize == 2) {
7046 /* Recursive base case. */
7047 if ((sortarray[0][axis] > sortarray[1][axis]) ||
7048 ((sortarray[0][axis] == sortarray[1][axis]) &&
7049 (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
7050 temp = sortarray[1];
7051 sortarray[1] = sortarray[0];
7052 sortarray[0] = temp;
7056 /* Choose a random pivot to split the array. */
7057 pivot = (int) randomnation(arraysize);
7058 pivot1 = sortarray[pivot][axis];
7059 pivot2 = sortarray[pivot][1 - axis];
7060 /* Split the array. */
7063 while (left < right) {
7064 /* Search for a point whose x-coordinate is too large for the left. */
7067 } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
7068 ((sortarray[left][axis] == pivot1) &&
7069 (sortarray[left][1 - axis] < pivot2))));
7070 /* Search for a point whose x-coordinate is too small for the right. */
7073 } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
7074 ((sortarray[right][axis] == pivot1) &&
7075 (sortarray[right][1 - axis] > pivot2))));
7077 /* Swap the left and right points. */
7078 temp = sortarray[left];
7079 sortarray[left] = sortarray[right];
7080 sortarray[right] = temp;
7083 /* Unlike in pointsort(), at most one of the following */
7084 /* conditionals is true. */
7085 if (left > median) {
7086 /* Recursively shuffle the left subset. */
7087 pointmedian(sortarray, left, median, axis);
7089 if (right < median - 1) {
7090 /* Recursively shuffle the right subset. */
7091 pointmedian(&sortarray[right + 1], arraysize - right - 1,
7092 median - right - 1, axis);
7096 /*****************************************************************************/
7098 /* alternateaxes() Sorts the points as appropriate for the divide-and- */
7099 /* conquer algorithm with alternating cuts. */
7101 /* Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1. */
7102 /* For the base case, subsets containing only two or three points are */
7103 /* always sorted by x-coordinate. */
7105 /*****************************************************************************/
7107 void alternateaxes(sortarray, arraysize, axis)
7114 divider = arraysize >> 1;
7115 if (arraysize <= 3) {
7116 /* Recursive base case: subsets of two or three points will be */
7117 /* handled specially, and should always be sorted by x-coordinate. */
7120 /* Partition with a horizontal or vertical cut. */
7121 pointmedian(sortarray, arraysize, divider, axis);
7122 /* Recursively partition the subsets with a cross cut. */
7123 if (arraysize - divider >= 2) {
7125 alternateaxes(sortarray, divider, 1 - axis);
7127 alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
7131 /*****************************************************************************/
7133 /* mergehulls() Merge two adjacent Delaunay triangulations into a */
7134 /* single Delaunay triangulation. */
7136 /* This is similar to the algorithm given by Guibas and Stolfi, but uses */
7137 /* a triangle-based, rather than edge-based, data structure. */
7139 /* The algorithm walks up the gap between the two triangulations, knitting */
7140 /* them together. As they are merged, some of their bounding triangles */
7141 /* are converted into real triangles of the triangulation. The procedure */
7142 /* pulls each hull's bounding triangles apart, then knits them together */
7143 /* like the teeth of two gears. The Delaunay property determines, at each */
7144 /* step, whether the next "tooth" is a bounding triangle of the left hull */
7145 /* or the right. When a bounding triangle becomes real, its apex is */
7146 /* changed from NULL to a real point. */
7148 /* Only two new triangles need to be allocated. These become new bounding */
7149 /* triangles at the top and bottom of the seam. They are used to connect */
7150 /* the remaining bounding triangles (those that have not been converted */
7151 /* into real triangles) into a single fan. */
7153 /* On entry, `farleft' and `innerleft' are bounding triangles of the left */
7154 /* triangulation. The origin of `farleft' is the leftmost vertex, and */
7155 /* the destination of `innerleft' is the rightmost vertex of the */
7156 /* triangulation. Similarly, `innerright' and `farright' are bounding */
7157 /* triangles of the right triangulation. The origin of `innerright' and */
7158 /* destination of `farright' are the leftmost and rightmost vertices. */
7160 /* On completion, the origin of `farleft' is the leftmost vertex of the */
7161 /* merged triangulation, and the destination of `farright' is the rightmost */
7164 /*****************************************************************************/
7166 void mergehulls(farleft, innerleft, innerright, farright, axis)
7167 struct triedge *farleft;
7168 struct triedge *innerleft;
7169 struct triedge *innerright;
7170 struct triedge *farright;
7173 struct triedge leftcand, rightcand;
7174 struct triedge baseedge;
7175 struct triedge nextedge;
7176 struct triedge sidecasing, topcasing, outercasing;
7177 struct triedge checkedge;
7178 point innerleftdest;
7179 point innerrightorg;
7180 point innerleftapex, innerrightapex;
7181 point farleftpt, farrightpt;
7182 point farleftapex, farrightapex;
7183 point lowerleft, lowerright;
7184 point upperleft, upperright;
7189 int leftfinished, rightfinished;
7190 triangle ptr; /* Temporary variable used by sym(). */
7192 dest(*innerleft, innerleftdest);
7193 apex(*innerleft, innerleftapex);
7194 org(*innerright, innerrightorg);
7195 apex(*innerright, innerrightapex);
7196 /* Special treatment for horizontal cuts. */
7197 if (dwyer && (axis == 1)) {
7198 org(*farleft, farleftpt);
7199 apex(*farleft, farleftapex);
7200 dest(*farright, farrightpt);
7201 apex(*farright, farrightapex);
7202 /* The pointers to the extremal points are shifted to point to the */
7203 /* topmost and bottommost point of each hull, rather than the */
7204 /* leftmost and rightmost points. */
7205 while (farleftapex[1] < farleftpt[1]) {
7206 lnextself(*farleft);
7208 farleftpt = farleftapex;
7209 apex(*farleft, farleftapex);
7211 sym(*innerleft, checkedge);
7212 apex(checkedge, checkvertex);
7213 while (checkvertex[1] > innerleftdest[1]) {
7214 lnext(checkedge, *innerleft);
7215 innerleftapex = innerleftdest;
7216 innerleftdest = checkvertex;
7217 sym(*innerleft, checkedge);
7218 apex(checkedge, checkvertex);
7220 while (innerrightapex[1] < innerrightorg[1]) {
7221 lnextself(*innerright);
7222 symself(*innerright);
7223 innerrightorg = innerrightapex;
7224 apex(*innerright, innerrightapex);
7226 sym(*farright, checkedge);
7227 apex(checkedge, checkvertex);
7228 while (checkvertex[1] > farrightpt[1]) {
7229 lnext(checkedge, *farright);
7230 farrightapex = farrightpt;
7231 farrightpt = checkvertex;
7232 sym(*farright, checkedge);
7233 apex(checkedge, checkvertex);
7236 /* Find a line tangent to and below both hulls. */
7239 /* Make innerleftdest the "bottommost" point of the left hull. */
7240 if (counterclockwise(innerleftdest, innerleftapex, innerrightorg) > 0.0) {
7241 lprevself(*innerleft);
7242 symself(*innerleft);
7243 innerleftdest = innerleftapex;
7244 apex(*innerleft, innerleftapex);
7247 /* Make innerrightorg the "bottommost" point of the right hull. */
7248 if (counterclockwise(innerrightapex, innerrightorg, innerleftdest) > 0.0) {
7249 lnextself(*innerright);
7250 symself(*innerright);
7251 innerrightorg = innerrightapex;
7252 apex(*innerright, innerrightapex);
7255 } while (changemade);
7256 /* Find the two candidates to be the next "gear tooth". */
7257 sym(*innerleft, leftcand);
7258 sym(*innerright, rightcand);
7259 /* Create the bottom new bounding triangle. */
7260 maketriangle(&baseedge);
7261 /* Connect it to the bounding boxes of the left and right triangulations. */
7262 bond(baseedge, *innerleft);
7263 lnextself(baseedge);
7264 bond(baseedge, *innerright);
7265 lnextself(baseedge);
7266 setorg(baseedge, innerrightorg);
7267 setdest(baseedge, innerleftdest);
7268 /* Apex is intentionally left NULL. */
7270 printf(" Creating base bounding ");
7271 printtriangle(&baseedge);
7273 /* Fix the extreme triangles if necessary. */
7274 org(*farleft, farleftpt);
7275 if (innerleftdest == farleftpt) {
7276 lnext(baseedge, *farleft);
7278 dest(*farright, farrightpt);
7279 if (innerrightorg == farrightpt) {
7280 lprev(baseedge, *farright);
7282 /* The vertices of the current knitting edge. */
7283 lowerleft = innerleftdest;
7284 lowerright = innerrightorg;
7285 /* The candidate vertices for knitting. */
7286 apex(leftcand, upperleft);
7287 apex(rightcand, upperright);
7288 /* Walk up the gap between the two triangulations, knitting them together. */
7290 /* Have we reached the top? (This isn't quite the right question, */
7291 /* because even though the left triangulation might seem finished now, */
7292 /* moving up on the right triangulation might reveal a new point of */
7293 /* the left triangulation. And vice-versa.) */
7294 leftfinished = counterclockwise(upperleft, lowerleft, lowerright) <= 0.0;
7295 rightfinished = counterclockwise(upperright, lowerleft, lowerright) <= 0.0;
7296 if (leftfinished && rightfinished) {
7297 /* Create the top new bounding triangle. */
7298 maketriangle(&nextedge);
7299 setorg(nextedge, lowerleft);
7300 setdest(nextedge, lowerright);
7301 /* Apex is intentionally left NULL. */
7302 /* Connect it to the bounding boxes of the two triangulations. */
7303 bond(nextedge, baseedge);
7304 lnextself(nextedge);
7305 bond(nextedge, rightcand);
7306 lnextself(nextedge);
7307 bond(nextedge, leftcand);
7309 printf(" Creating top bounding ");
7310 printtriangle(&baseedge);
7312 /* Special treatment for horizontal cuts. */
7313 if (dwyer && (axis == 1)) {
7314 org(*farleft, farleftpt);
7315 apex(*farleft, farleftapex);
7316 dest(*farright, farrightpt);
7317 apex(*farright, farrightapex);
7318 sym(*farleft, checkedge);
7319 apex(checkedge, checkvertex);
7320 /* The pointers to the extremal points are restored to the leftmost */
7321 /* and rightmost points (rather than topmost and bottommost). */
7322 while (checkvertex[0] < farleftpt[0]) {
7323 lprev(checkedge, *farleft);
7324 farleftapex = farleftpt;
7325 farleftpt = checkvertex;
7326 sym(*farleft, checkedge);
7327 apex(checkedge, checkvertex);
7329 while (farrightapex[0] > farrightpt[0]) {
7330 lprevself(*farright);
7332 farrightpt = farrightapex;
7333 apex(*farright, farrightapex);
7338 /* Consider eliminating edges from the left triangulation. */
7339 if (!leftfinished) {
7340 /* What vertex would be exposed if an edge were deleted? */
7341 lprev(leftcand, nextedge);
7343 apex(nextedge, nextapex);
7344 /* If nextapex is NULL, then no vertex would be exposed; the */
7345 /* triangulation would have been eaten right through. */
7346 if (nextapex != (point) NULL) {
7347 /* Check whether the edge is Delaunay. */
7348 badedge = incircle(lowerleft, lowerright, upperleft, nextapex) > 0.0;
7350 /* Eliminate the edge with an edge flip. As a result, the */
7351 /* left triangulation will have one more boundary triangle. */
7352 lnextself(nextedge);
7353 sym(nextedge, topcasing);
7354 lnextself(nextedge);
7355 sym(nextedge, sidecasing);
7356 bond(nextedge, topcasing);
7357 bond(leftcand, sidecasing);
7358 lnextself(leftcand);
7359 sym(leftcand, outercasing);
7360 lprevself(nextedge);
7361 bond(nextedge, outercasing);
7362 /* Correct the vertices to reflect the edge flip. */
7363 setorg(leftcand, lowerleft);
7364 setdest(leftcand, NULL);
7365 setapex(leftcand, nextapex);
7366 setorg(nextedge, NULL);
7367 setdest(nextedge, upperleft);
7368 setapex(nextedge, nextapex);
7369 /* Consider the newly exposed vertex. */
7370 upperleft = nextapex;
7371 /* What vertex would be exposed if another edge were deleted? */
7372 triedgecopy(sidecasing, nextedge);
7373 apex(nextedge, nextapex);
7374 if (nextapex != (point) NULL) {
7375 /* Check whether the edge is Delaunay. */
7376 badedge = incircle(lowerleft, lowerright, upperleft, nextapex)
7379 /* Avoid eating right through the triangulation. */
7385 /* Consider eliminating edges from the right triangulation. */
7386 if (!rightfinished) {
7387 /* What vertex would be exposed if an edge were deleted? */
7388 lnext(rightcand, nextedge);
7390 apex(nextedge, nextapex);
7391 /* If nextapex is NULL, then no vertex would be exposed; the */
7392 /* triangulation would have been eaten right through. */
7393 if (nextapex != (point) NULL) {
7394 /* Check whether the edge is Delaunay. */
7395 badedge = incircle(lowerleft, lowerright, upperright, nextapex) > 0.0;
7397 /* Eliminate the edge with an edge flip. As a result, the */
7398 /* right triangulation will have one more boundary triangle. */
7399 lprevself(nextedge);
7400 sym(nextedge, topcasing);
7401 lprevself(nextedge);
7402 sym(nextedge, sidecasing);
7403 bond(nextedge, topcasing);
7404 bond(rightcand, sidecasing);
7405 lprevself(rightcand);
7406 sym(rightcand, outercasing);
7407 lnextself(nextedge);
7408 bond(nextedge, outercasing);
7409 /* Correct the vertices to reflect the edge flip. */
7410 setorg(rightcand, NULL);
7411 setdest(rightcand, lowerright);
7412 setapex(rightcand, nextapex);
7413 setorg(nextedge, upperright);
7414 setdest(nextedge, NULL);
7415 setapex(nextedge, nextapex);
7416 /* Consider the newly exposed vertex. */
7417 upperright = nextapex;
7418 /* What vertex would be exposed if another edge were deleted? */
7419 triedgecopy(sidecasing, nextedge);
7420 apex(nextedge, nextapex);
7421 if (nextapex != (point) NULL) {
7422 /* Check whether the edge is Delaunay. */
7423 badedge = incircle(lowerleft, lowerright, upperright, nextapex)
7426 /* Avoid eating right through the triangulation. */
7432 if (leftfinished || (!rightfinished &&
7433 (incircle(upperleft, lowerleft, lowerright, upperright) > 0.0))) {
7434 /* Knit the triangulations, adding an edge from `lowerleft' */
7435 /* to `upperright'. */
7436 bond(baseedge, rightcand);
7437 lprev(rightcand, baseedge);
7438 setdest(baseedge, lowerleft);
7439 lowerright = upperright;
7440 sym(baseedge, rightcand);
7441 apex(rightcand, upperright);
7443 /* Knit the triangulations, adding an edge from `upperleft' */
7444 /* to `lowerright'. */
7445 bond(baseedge, leftcand);
7446 lnext(leftcand, baseedge);
7447 setorg(baseedge, lowerright);
7448 lowerleft = upperleft;
7449 sym(baseedge, leftcand);
7450 apex(leftcand, upperleft);
7453 printf(" Connecting ");
7454 printtriangle(&baseedge);
7459 /*****************************************************************************/
7461 /* divconqrecurse() Recursively form a Delaunay triangulation by the */
7462 /* divide-and-conquer method. */
7464 /* Recursively breaks down the problem into smaller pieces, which are */
7465 /* knitted together by mergehulls(). The base cases (problems of two or */
7466 /* three points) are handled specially here. */
7468 /* On completion, `farleft' and `farright' are bounding triangles such that */
7469 /* the origin of `farleft' is the leftmost vertex (breaking ties by */
7470 /* choosing the highest leftmost vertex), and the destination of */
7471 /* `farright' is the rightmost vertex (breaking ties by choosing the */
7472 /* lowest rightmost vertex). */
7474 /*****************************************************************************/
7476 void divconqrecurse(sortarray, vertices, axis, farleft, farright)
7480 struct triedge *farleft;
7481 struct triedge *farright;
7483 struct triedge midtri, tri1, tri2, tri3;
7484 struct triedge innerleft, innerright;
7489 printf(" Triangulating %d points.\n", vertices);
7491 if (vertices == 2) {
7492 /* The triangulation of two vertices is an edge. An edge is */
7493 /* represented by two bounding triangles. */
7494 maketriangle(farleft);
7495 setorg(*farleft, sortarray[0]);
7496 setdest(*farleft, sortarray[1]);
7497 /* The apex is intentionally left NULL. */
7498 maketriangle(farright);
7499 setorg(*farright, sortarray[1]);
7500 setdest(*farright, sortarray[0]);
7501 /* The apex is intentionally left NULL. */
7502 bond(*farleft, *farright);
7503 lprevself(*farleft);
7504 lnextself(*farright);
7505 bond(*farleft, *farright);
7506 lprevself(*farleft);
7507 lnextself(*farright);
7508 bond(*farleft, *farright);
7510 printf(" Creating ");
7511 printtriangle(farleft);
7512 printf(" Creating ");
7513 printtriangle(farright);
7515 /* Ensure that the origin of `farleft' is sortarray[0]. */
7516 lprev(*farright, *farleft);
7518 } else if (vertices == 3) {
7519 /* The triangulation of three vertices is either a triangle (with */
7520 /* three bounding triangles) or two edges (with four bounding */
7521 /* triangles). In either case, four triangles are created. */
7522 maketriangle(&midtri);
7523 maketriangle(&tri1);
7524 maketriangle(&tri2);
7525 maketriangle(&tri3);
7526 area = counterclockwise(sortarray[0], sortarray[1], sortarray[2]);
7528 /* Three collinear points; the triangulation is two edges. */
7529 setorg(midtri, sortarray[0]);
7530 setdest(midtri, sortarray[1]);
7531 setorg(tri1, sortarray[1]);
7532 setdest(tri1, sortarray[0]);
7533 setorg(tri2, sortarray[2]);
7534 setdest(tri2, sortarray[1]);
7535 setorg(tri3, sortarray[1]);
7536 setdest(tri3, sortarray[2]);
7537 /* All apices are intentionally left NULL. */
7552 /* Ensure that the origin of `farleft' is sortarray[0]. */
7553 triedgecopy(tri1, *farleft);
7554 /* Ensure that the destination of `farright' is sortarray[2]. */
7555 triedgecopy(tri2, *farright);
7557 /* The three points are not collinear; the triangulation is one */
7558 /* triangle, namely `midtri'. */
7559 setorg(midtri, sortarray[0]);
7560 setdest(tri1, sortarray[0]);
7561 setorg(tri3, sortarray[0]);
7562 /* Apices of tri1, tri2, and tri3 are left NULL. */
7564 /* The vertices are in counterclockwise order. */
7565 setdest(midtri, sortarray[1]);
7566 setorg(tri1, sortarray[1]);
7567 setdest(tri2, sortarray[1]);
7568 setapex(midtri, sortarray[2]);
7569 setorg(tri2, sortarray[2]);
7570 setdest(tri3, sortarray[2]);
7572 /* The vertices are in clockwise order. */
7573 setdest(midtri, sortarray[2]);
7574 setorg(tri1, sortarray[2]);
7575 setdest(tri2, sortarray[2]);
7576 setapex(midtri, sortarray[1]);
7577 setorg(tri2, sortarray[1]);
7578 setdest(tri3, sortarray[1]);
7580 /* The topology does not depend on how the vertices are ordered. */
7595 /* Ensure that the origin of `farleft' is sortarray[0]. */
7596 triedgecopy(tri1, *farleft);
7597 /* Ensure that the destination of `farright' is sortarray[2]. */
7599 triedgecopy(tri2, *farright);
7601 lnext(*farleft, *farright);
7605 printf(" Creating ");
7606 printtriangle(&midtri);
7607 printf(" Creating ");
7608 printtriangle(&tri1);
7609 printf(" Creating ");
7610 printtriangle(&tri2);
7611 printf(" Creating ");
7612 printtriangle(&tri3);
7616 /* Split the vertices in half. */
7617 divider = vertices >> 1;
7618 /* Recursively triangulate each half. */
7619 divconqrecurse(sortarray, divider, 1 - axis, farleft, &innerleft);
7620 divconqrecurse(&sortarray[divider], vertices - divider, 1 - axis,
7621 &innerright, farright);
7623 printf(" Joining triangulations with %d and %d vertices.\n", divider,
7624 vertices - divider);
7626 /* Merge the two triangulations into one. */
7627 mergehulls(farleft, &innerleft, &innerright, farright, axis);
7631 long removeghosts(startghost)
7632 struct triedge *startghost;
7634 struct triedge searchedge;
7635 struct triedge dissolveedge;
7636 struct triedge deadtri;
7639 triangle ptr; /* Temporary variable used by sym(). */
7642 printf(" Removing ghost triangles.\n");
7644 /* Find an edge on the convex hull to start point location from. */
7645 lprev(*startghost, searchedge);
7646 symself(searchedge);
7647 dummytri[0] = encode(searchedge);
7648 /* Remove the bounding box and count the convex hull edges. */
7649 triedgecopy(*startghost, dissolveedge);
7653 lnext(dissolveedge, deadtri);
7654 lprevself(dissolveedge);
7655 symself(dissolveedge);
7656 /* If no PSLG is involved, set the boundary markers of all the points */
7657 /* on the convex hull. If a PSLG is used, this step is done later. */
7659 /* Watch out for the case where all the input points are collinear. */
7660 if (dissolveedge.tri != dummytri) {
7661 org(dissolveedge, markorg);
7662 if (pointmark(markorg) == 0) {
7663 setpointmark(markorg, 1);
7667 /* Remove a bounding triangle from a convex hull triangle. */
7668 dissolve(dissolveedge);
7669 /* Find the next bounding triangle. */
7670 sym(deadtri, dissolveedge);
7671 /* Delete the bounding triangle. */
7672 triangledealloc(deadtri.tri);
7673 } while (!triedgeequal(dissolveedge, *startghost));
7677 /*****************************************************************************/
7679 /* divconqdelaunay() Form a Delaunay triangulation by the divide-and- */
7680 /* conquer method. */
7682 /* Sorts the points, calls a recursive procedure to triangulate them, and */
7683 /* removes the bounding box, setting boundary markers as appropriate. */
7685 /*****************************************************************************/
7687 long divconqdelaunay()
7690 struct triedge hullleft, hullright;
7694 /* Allocate an array of pointers to points for sorting. */
7695 sortarray = (point *) malloc(inpoints * sizeof(point));
7696 if (sortarray == (point *) NULL) {
7697 printf("Error: Out of memory.\n");
7700 traversalinit(&points);
7701 for (i = 0; i < inpoints; i++) {
7702 sortarray[i] = pointtraverse();
7705 printf(" Sorting points.\n");
7707 /* Sort the points. */
7708 pointsort(sortarray, inpoints);
7709 /* Discard duplicate points, which can really mess up the algorithm. */
7711 for (j = 1; j < inpoints; j++) {
7712 if ((sortarray[i][0] == sortarray[j][0])
7713 && (sortarray[i][1] == sortarray[j][1])) {
7716 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
7717 sortarray[j][0], sortarray[j][1]);
7719 /* Commented out - would eliminate point from output .node file, but causes
7720 a failure if some segment has this point as an endpoint.
7721 setpointmark(sortarray[j], DEADPOINT);
7725 sortarray[i] = sortarray[j];
7730 /* Re-sort the array of points to accommodate alternating cuts. */
7732 if (i - divider >= 2) {
7734 alternateaxes(sortarray, divider, 1);
7736 alternateaxes(&sortarray[divider], i - divider, 1);
7740 printf(" Forming triangulation.\n");
7742 /* Form the Delaunay triangulation. */
7743 divconqrecurse(sortarray, i, 0, &hullleft, &hullright);
7746 return removeghosts(&hullleft);
7751 /********* Divide-and-conquer Delaunay triangulation ends here *********/
7753 /********* Incremental Delaunay triangulation begins here *********/
7757 /*****************************************************************************/
7759 /* boundingbox() Form an "infinite" bounding triangle to insert points */
7762 /* The points at "infinity" are assigned finite coordinates, which are used */
7763 /* by the point location routines, but (mostly) ignored by the Delaunay */
7764 /* edge flip routines. */
7766 /*****************************************************************************/
7772 struct triedge inftri; /* Handle for the triangular bounding box. */
7776 printf(" Creating triangular bounding box.\n");
7778 /* Find the width (or height, whichever is larger) of the triangulation. */
7779 width = xmax - xmin;
7780 if (ymax - ymin > width) {
7781 width = ymax - ymin;
7786 /* Create the vertices of the bounding box. */
7787 infpoint1 = (point) malloc(points.itembytes);
7788 infpoint2 = (point) malloc(points.itembytes);
7789 infpoint3 = (point) malloc(points.itembytes);
7790 if ((infpoint1 == (point) NULL) || (infpoint2 == (point) NULL)
7791 || (infpoint3 == (point) NULL)) {
7792 printf("Error: Out of memory.\n");
7795 infpoint1[0] = xmin - 50.0 * width;
7796 infpoint1[1] = ymin - 40.0 * width;
7797 infpoint2[0] = xmax + 50.0 * width;
7798 infpoint2[1] = ymin - 40.0 * width;
7799 infpoint3[0] = 0.5 * (xmin + xmax);
7800 infpoint3[1] = ymax + 60.0 * width;
7802 /* Create the bounding box. */
7803 maketriangle(&inftri);
7804 setorg(inftri, infpoint1);
7805 setdest(inftri, infpoint2);
7806 setapex(inftri, infpoint3);
7807 /* Link dummytri to the bounding box so we can always find an */
7808 /* edge to begin searching (point location) from. */
7809 dummytri[0] = (triangle) inftri.tri;
7811 printf(" Creating ");
7812 printtriangle(&inftri);
7816 #endif /* not REDUCED */
7818 /*****************************************************************************/
7820 /* removebox() Remove the "infinite" bounding triangle, setting boundary */
7821 /* markers as appropriate. */
7823 /* The triangular bounding box has three boundary triangles (one for each */
7824 /* side of the bounding box), and a bunch of triangles fanning out from */
7825 /* the three bounding box vertices (one triangle for each edge of the */
7826 /* convex hull of the inner mesh). This routine removes these triangles. */
7828 /*****************************************************************************/
7834 struct triedge deadtri;
7835 struct triedge searchedge;
7836 struct triedge checkedge;
7837 struct triedge nextedge, finaledge, dissolveedge;
7840 triangle ptr; /* Temporary variable used by sym(). */
7843 printf(" Removing triangular bounding box.\n");
7845 /* Find a boundary triangle. */
7846 nextedge.tri = dummytri;
7847 nextedge.orient = 0;
7849 /* Mark a place to stop. */
7850 lprev(nextedge, finaledge);
7851 lnextself(nextedge);
7853 /* Find a triangle (on the boundary of the point set) that isn't */
7854 /* a bounding box triangle. */
7855 lprev(nextedge, searchedge);
7856 symself(searchedge);
7857 /* Check whether nextedge is another boundary triangle */
7858 /* adjacent to the first one. */
7859 lnext(nextedge, checkedge);
7861 if (checkedge.tri == dummytri) {
7862 /* Go on to the next triangle. There are only three boundary */
7863 /* triangles, and this next triangle cannot be the third one, */
7864 /* so it's safe to stop here. */
7865 lprevself(searchedge);
7866 symself(searchedge);
7868 /* Find a new boundary edge to search from, as the current search */
7869 /* edge lies on a bounding box triangle and will be deleted. */
7870 dummytri[0] = encode(searchedge);
7872 while (!triedgeequal(nextedge, finaledge)) {
7874 lprev(nextedge, dissolveedge);
7875 symself(dissolveedge);
7876 /* If not using a PSLG, the vertices should be marked now. */
7877 /* (If using a PSLG, markhull() will do the job.) */
7879 /* Be careful! One must check for the case where all the input */
7880 /* points are collinear, and thus all the triangles are part of */
7881 /* the bounding box. Otherwise, the setpointmark() call below */
7882 /* will cause a bad pointer reference. */
7883 if (dissolveedge.tri != dummytri) {
7884 org(dissolveedge, markorg);
7885 if (pointmark(markorg) == 0) {
7886 setpointmark(markorg, 1);
7890 /* Disconnect the bounding box triangle from the mesh triangle. */
7891 dissolve(dissolveedge);
7892 lnext(nextedge, deadtri);
7893 sym(deadtri, nextedge);
7894 /* Get rid of the bounding box triangle. */
7895 triangledealloc(deadtri.tri);
7896 /* Do we need to turn the corner? */
7897 if (nextedge.tri == dummytri) {
7898 /* Turn the corner. */
7899 triedgecopy(dissolveedge, nextedge);
7902 triangledealloc(finaledge.tri);
7904 free(infpoint1); /* Deallocate the bounding box vertices. */
7911 #endif /* not REDUCED */
7913 /*****************************************************************************/
7915 /* incrementaldelaunay() Form a Delaunay triangulation by incrementally */
7916 /* adding vertices. */
7918 /*****************************************************************************/
7922 long incrementaldelaunay()
7924 struct triedge starttri;
7928 /* Create a triangular bounding box. */
7931 printf(" Incrementally inserting points.\n");
7933 traversalinit(&points);
7934 pointloop = pointtraverse();
7936 while (pointloop != (point) NULL) {
7937 /* Find a boundary triangle to search from. */
7938 starttri.tri = (triangle *) NULL;
7939 if (insertsite(pointloop, &starttri, (struct edge *) NULL, 0, 0) ==
7943 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
7944 pointloop[0], pointloop[1]);
7946 /* Commented out - would eliminate point from output .node file.
7947 setpointmark(pointloop, DEADPOINT);
7950 pointloop = pointtraverse();
7953 /* Remove the bounding box. */
7957 #endif /* not REDUCED */
7961 /********* Incremental Delaunay triangulation ends here *********/
7963 /********* Sweepline Delaunay triangulation begins here *********/
7969 void eventheapinsert(heap, heapsize, newevent)
7970 struct event **heap;
7972 struct event *newevent;
7974 REAL eventx, eventy;
7979 eventx = newevent->xkey;
7980 eventy = newevent->ykey;
7981 eventnum = heapsize;
7982 notdone = eventnum > 0;
7984 parent = (eventnum - 1) >> 1;
7985 if ((heap[parent]->ykey < eventy) ||
7986 ((heap[parent]->ykey == eventy)
7987 && (heap[parent]->xkey <= eventx))) {
7990 heap[eventnum] = heap[parent];
7991 heap[eventnum]->heapposition = eventnum;
7994 notdone = eventnum > 0;
7997 heap[eventnum] = newevent;
7998 newevent->heapposition = eventnum;
8001 #endif /* not REDUCED */
8005 void eventheapify(heap, heapsize, eventnum)
8006 struct event **heap;
8010 struct event *thisevent;
8011 REAL eventx, eventy;
8012 int leftchild, rightchild;
8016 thisevent = heap[eventnum];
8017 eventx = thisevent->xkey;
8018 eventy = thisevent->ykey;
8019 leftchild = 2 * eventnum + 1;
8020 notdone = leftchild < heapsize;
8022 if ((heap[leftchild]->ykey < eventy) ||
8023 ((heap[leftchild]->ykey == eventy)
8024 && (heap[leftchild]->xkey < eventx))) {
8025 smallest = leftchild;
8027 smallest = eventnum;
8029 rightchild = leftchild + 1;
8030 if (rightchild < heapsize) {
8031 if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
8032 ((heap[rightchild]->ykey == heap[smallest]->ykey)
8033 && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
8034 smallest = rightchild;
8037 if (smallest == eventnum) {
8040 heap[eventnum] = heap[smallest];
8041 heap[eventnum]->heapposition = eventnum;
8042 heap[smallest] = thisevent;
8043 thisevent->heapposition = smallest;
8045 eventnum = smallest;
8046 leftchild = 2 * eventnum + 1;
8047 notdone = leftchild < heapsize;
8052 #endif /* not REDUCED */
8056 void eventheapdelete(heap, heapsize, eventnum)
8057 struct event **heap;
8061 struct event *moveevent;
8062 REAL eventx, eventy;
8066 moveevent = heap[heapsize - 1];
8068 eventx = moveevent->xkey;
8069 eventy = moveevent->ykey;
8071 parent = (eventnum - 1) >> 1;
8072 if ((heap[parent]->ykey < eventy) ||
8073 ((heap[parent]->ykey == eventy)
8074 && (heap[parent]->xkey <= eventx))) {
8077 heap[eventnum] = heap[parent];
8078 heap[eventnum]->heapposition = eventnum;
8081 notdone = eventnum > 0;
8085 heap[eventnum] = moveevent;
8086 moveevent->heapposition = eventnum;
8087 eventheapify(heap, heapsize - 1, eventnum);
8090 #endif /* not REDUCED */
8094 void createeventheap(eventheap, events, freeevents)
8095 struct event ***eventheap;
8096 struct event **events;
8097 struct event **freeevents;
8103 maxevents = (3 * inpoints) / 2;
8104 *eventheap = (struct event **) malloc(maxevents * sizeof(struct event *));
8105 if (*eventheap == (struct event **) NULL) {
8106 printf("Error: Out of memory.\n");
8109 *events = (struct event *) malloc(maxevents * sizeof(struct event));
8110 if (*events == (struct event *) NULL) {
8111 printf("Error: Out of memory.\n");
8114 traversalinit(&points);
8115 for (i = 0; i < inpoints; i++) {
8116 thispoint = pointtraverse();
8117 (*events)[i].eventptr = (VOID *) thispoint;
8118 (*events)[i].xkey = thispoint[0];
8119 (*events)[i].ykey = thispoint[1];
8120 eventheapinsert(*eventheap, i, *events + i);
8122 *freeevents = (struct event *) NULL;
8123 for (i = maxevents - 1; i >= inpoints; i--) {
8124 (*events)[i].eventptr = (VOID *) *freeevents;
8125 *freeevents = *events + i;
8129 #endif /* not REDUCED */
8133 int rightofhyperbola(fronttri, newsite)
8134 struct triedge *fronttri;
8137 point leftpoint, rightpoint;
8138 REAL dxa, dya, dxb, dyb;
8142 dest(*fronttri, leftpoint);
8143 apex(*fronttri, rightpoint);
8144 if ((leftpoint[1] < rightpoint[1])
8145 || ((leftpoint[1] == rightpoint[1]) && (leftpoint[0] < rightpoint[0]))) {
8146 if (newsite[0] >= rightpoint[0]) {
8150 if (newsite[0] <= leftpoint[0]) {
8154 dxa = leftpoint[0] - newsite[0];
8155 dya = leftpoint[1] - newsite[1];
8156 dxb = rightpoint[0] - newsite[0];
8157 dyb = rightpoint[1] - newsite[1];
8158 return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
8161 #endif /* not REDUCED */
8165 REAL circletop(pa, pb, pc, ccwabc)
8171 REAL xac, yac, xbc, ybc, xab, yab;
8172 REAL aclen2, bclen2, ablen2;
8176 xac = pa[0] - pc[0];
8177 yac = pa[1] - pc[1];
8178 xbc = pb[0] - pc[0];
8179 ybc = pb[1] - pc[1];
8180 xab = pa[0] - pb[0];
8181 yab = pa[1] - pb[1];
8182 aclen2 = xac * xac + yac * yac;
8183 bclen2 = xbc * xbc + ybc * ybc;
8184 ablen2 = xab * xab + yab * yab;
8185 return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
8189 #endif /* not REDUCED */
8193 void check4deadevent(checktri, freeevents, eventheap, heapsize)
8194 struct triedge *checktri;
8195 struct event **freeevents;
8196 struct event **eventheap;
8199 struct event *deadevent;
8203 org(*checktri, eventpoint);
8204 if (eventpoint != (point) NULL) {
8205 deadevent = (struct event *) eventpoint;
8206 eventnum = deadevent->heapposition;
8207 deadevent->eventptr = (VOID *) *freeevents;
8208 *freeevents = deadevent;
8209 eventheapdelete(eventheap, *heapsize, eventnum);
8211 setorg(*checktri, NULL);
8215 #endif /* not REDUCED */
8219 struct splaynode *splay(splaytree, searchpoint, searchtri)
8220 struct splaynode *splaytree;
8222 struct triedge *searchtri;
8224 struct splaynode *child, *grandchild;
8225 struct splaynode *lefttree, *righttree;
8226 struct splaynode *leftright;
8228 int rightofroot, rightofchild;
8230 if (splaytree == (struct splaynode *) NULL) {
8231 return (struct splaynode *) NULL;
8233 dest(splaytree->keyedge, checkpoint);
8234 if (checkpoint == splaytree->keydest) {
8235 rightofroot = rightofhyperbola(&splaytree->keyedge, searchpoint);
8237 triedgecopy(splaytree->keyedge, *searchtri);
8238 child = splaytree->rchild;
8240 child = splaytree->lchild;
8242 if (child == (struct splaynode *) NULL) {
8245 dest(child->keyedge, checkpoint);
8246 if (checkpoint != child->keydest) {
8247 child = splay(child, searchpoint, searchtri);
8248 if (child == (struct splaynode *) NULL) {
8250 splaytree->rchild = (struct splaynode *) NULL;
8252 splaytree->lchild = (struct splaynode *) NULL;
8257 rightofchild = rightofhyperbola(&child->keyedge, searchpoint);
8259 triedgecopy(child->keyedge, *searchtri);
8260 grandchild = splay(child->rchild, searchpoint, searchtri);
8261 child->rchild = grandchild;
8263 grandchild = splay(child->lchild, searchpoint, searchtri);
8264 child->lchild = grandchild;
8266 if (grandchild == (struct splaynode *) NULL) {
8268 splaytree->rchild = child->lchild;
8269 child->lchild = splaytree;
8271 splaytree->lchild = child->rchild;
8272 child->rchild = splaytree;
8278 splaytree->rchild = child->lchild;
8279 child->lchild = splaytree;
8281 splaytree->lchild = grandchild->rchild;
8282 grandchild->rchild = splaytree;
8284 child->rchild = grandchild->lchild;
8285 grandchild->lchild = child;
8288 splaytree->rchild = grandchild->lchild;
8289 grandchild->lchild = splaytree;
8291 splaytree->lchild = child->rchild;
8292 child->rchild = splaytree;
8294 child->lchild = grandchild->rchild;
8295 grandchild->rchild = child;
8299 lefttree = splay(splaytree->lchild, searchpoint, searchtri);
8300 righttree = splay(splaytree->rchild, searchpoint, searchtri);
8302 pooldealloc(&splaynodes, (VOID *) splaytree);
8303 if (lefttree == (struct splaynode *) NULL) {
8305 } else if (righttree == (struct splaynode *) NULL) {
8307 } else if (lefttree->rchild == (struct splaynode *) NULL) {
8308 lefttree->rchild = righttree->lchild;
8309 righttree->lchild = lefttree;
8311 } else if (righttree->lchild == (struct splaynode *) NULL) {
8312 righttree->lchild = lefttree->rchild;
8313 lefttree->rchild = righttree;
8316 /* printf("Holy Toledo!!!\n"); */
8317 leftright = lefttree->rchild;
8318 while (leftright->rchild != (struct splaynode *) NULL) {
8319 leftright = leftright->rchild;
8321 leftright->rchild = righttree;
8327 #endif /* not REDUCED */
8331 struct splaynode *splayinsert(splayroot, newkey, searchpoint)
8332 struct splaynode *splayroot;
8333 struct triedge *newkey;
8336 struct splaynode *newsplaynode;
8338 newsplaynode = (struct splaynode *) poolalloc(&splaynodes);
8339 triedgecopy(*newkey, newsplaynode->keyedge);
8340 dest(*newkey, newsplaynode->keydest);
8341 if (splayroot == (struct splaynode *) NULL) {
8342 newsplaynode->lchild = (struct splaynode *) NULL;
8343 newsplaynode->rchild = (struct splaynode *) NULL;
8344 } else if (rightofhyperbola(&splayroot->keyedge, searchpoint)) {
8345 newsplaynode->lchild = splayroot;
8346 newsplaynode->rchild = splayroot->rchild;
8347 splayroot->rchild = (struct splaynode *) NULL;
8349 newsplaynode->lchild = splayroot->lchild;
8350 newsplaynode->rchild = splayroot;
8351 splayroot->lchild = (struct splaynode *) NULL;
8353 return newsplaynode;
8356 #endif /* not REDUCED */
8360 struct splaynode *circletopinsert(splayroot, newkey, pa, pb, pc, topy)
8361 struct splaynode *splayroot;
8362 struct triedge *newkey;
8369 REAL xac, yac, xbc, ybc;
8370 REAL aclen2, bclen2;
8371 REAL searchpoint[2];
8372 struct triedge dummytri;
8374 ccwabc = counterclockwise(pa, pb, pc);
8375 xac = pa[0] - pc[0];
8376 yac = pa[1] - pc[1];
8377 xbc = pb[0] - pc[0];
8378 ybc = pb[1] - pc[1];
8379 aclen2 = xac * xac + yac * yac;
8380 bclen2 = xbc * xbc + ybc * ybc;
8381 searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
8382 searchpoint[1] = topy;
8383 return splayinsert(splay(splayroot, (point) searchpoint, &dummytri), newkey,
8384 (point) searchpoint);
8387 #endif /* not REDUCED */
8391 struct splaynode *frontlocate(splayroot, bottommost, searchpoint, searchtri,
8393 struct splaynode *splayroot;
8394 struct triedge *bottommost;
8396 struct triedge *searchtri;
8400 triangle ptr; /* Temporary variable used by onext(). */
8402 triedgecopy(*bottommost, *searchtri);
8403 splayroot = splay(splayroot, searchpoint, searchtri);
8406 while (!farrightflag && rightofhyperbola(searchtri, searchpoint)) {
8407 onextself(*searchtri);
8408 farrightflag = triedgeequal(*searchtri, *bottommost);
8410 *farright = farrightflag;
8414 #endif /* not REDUCED */
8418 long sweeplinedelaunay()
8420 struct event **eventheap;
8421 struct event *events;
8422 struct event *freeevents;
8423 struct event *nextevent;
8424 struct event *newevent;
8425 struct splaynode *splayroot;
8426 struct triedge bottommost;
8427 struct triedge searchtri;
8428 struct triedge fliptri;
8429 struct triedge lefttri, righttri, farlefttri, farrighttri;
8430 struct triedge inserttri;
8431 point firstpoint, secondpoint;
8432 point nextpoint, lastpoint;
8434 point leftpoint, midpoint, rightpoint;
8435 REAL lefttest, righttest;
8437 int check4events, farrightflag;
8438 triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
8440 poolinit(&splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK, POINTER,
8442 splayroot = (struct splaynode *) NULL;
8445 printf(" Placing points in event heap.\n");
8447 createeventheap(&eventheap, &events, &freeevents);
8448 heapsize = inpoints;
8451 printf(" Forming triangulation.\n");
8453 maketriangle(&lefttri);
8454 maketriangle(&righttri);
8455 bond(lefttri, righttri);
8457 lprevself(righttri);
8458 bond(lefttri, righttri);
8460 lprevself(righttri);
8461 bond(lefttri, righttri);
8462 firstpoint = (point) eventheap[0]->eventptr;
8463 eventheap[0]->eventptr = (VOID *) freeevents;
8464 freeevents = eventheap[0];
8465 eventheapdelete(eventheap, heapsize, 0);
8468 if (heapsize == 0) {
8469 printf("Error: Input points are all identical.\n");
8472 secondpoint = (point) eventheap[0]->eventptr;
8473 eventheap[0]->eventptr = (VOID *) freeevents;
8474 freeevents = eventheap[0];
8475 eventheapdelete(eventheap, heapsize, 0);
8477 if ((firstpoint[0] == secondpoint[0])
8478 && (firstpoint[1] == secondpoint[1])) {
8480 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
8481 secondpoint[0], secondpoint[1]);
8482 /* Commented out - would eliminate point from output .node file.
8483 setpointmark(secondpoint, DEADPOINT);
8486 } while ((firstpoint[0] == secondpoint[0])
8487 && (firstpoint[1] == secondpoint[1]));
8488 setorg(lefttri, firstpoint);
8489 setdest(lefttri, secondpoint);
8490 setorg(righttri, secondpoint);
8491 setdest(righttri, firstpoint);
8492 lprev(lefttri, bottommost);
8493 lastpoint = secondpoint;
8494 while (heapsize > 0) {
8495 nextevent = eventheap[0];
8496 eventheapdelete(eventheap, heapsize, 0);
8499 if (nextevent->xkey < xmin) {
8500 decode(nextevent->eventptr, fliptri);
8501 oprev(fliptri, farlefttri);
8502 check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
8503 onext(fliptri, farrighttri);
8504 check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
8506 if (triedgeequal(farlefttri, bottommost)) {
8507 lprev(fliptri, bottommost);
8510 setapex(fliptri, NULL);
8511 lprev(fliptri, lefttri);
8512 lnext(fliptri, righttri);
8513 sym(lefttri, farlefttri);
8515 if (randomnation(SAMPLERATE) == 0) {
8517 dest(fliptri, leftpoint);
8518 apex(fliptri, midpoint);
8519 org(fliptri, rightpoint);
8520 splayroot = circletopinsert(splayroot, &lefttri, leftpoint, midpoint,
8521 rightpoint, nextevent->ykey);
8524 nextpoint = (point) nextevent->eventptr;
8525 if ((nextpoint[0] == lastpoint[0]) && (nextpoint[1] == lastpoint[1])) {
8527 "Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
8528 nextpoint[0], nextpoint[1]);
8529 /* Commented out - would eliminate point from output .node file.
8530 setpointmark(nextpoint, DEADPOINT);
8534 lastpoint = nextpoint;
8536 splayroot = frontlocate(splayroot, &bottommost, nextpoint, &searchtri,
8539 triedgecopy(bottommost, searchtri);
8541 while (!farrightflag && rightofhyperbola(&searchtri, nextpoint)) {
8542 onextself(searchtri);
8543 farrightflag = triedgeequal(searchtri, bottommost);
8547 check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
8549 triedgecopy(searchtri, farrighttri);
8550 sym(searchtri, farlefttri);
8551 maketriangle(&lefttri);
8552 maketriangle(&righttri);
8553 dest(farrighttri, connectpoint);
8554 setorg(lefttri, connectpoint);
8555 setdest(lefttri, nextpoint);
8556 setorg(righttri, nextpoint);
8557 setdest(righttri, connectpoint);
8558 bond(lefttri, righttri);
8560 lprevself(righttri);
8561 bond(lefttri, righttri);
8563 lprevself(righttri);
8564 bond(lefttri, farlefttri);
8565 bond(righttri, farrighttri);
8566 if (!farrightflag && triedgeequal(farrighttri, bottommost)) {
8567 triedgecopy(lefttri, bottommost);
8570 if (randomnation(SAMPLERATE) == 0) {
8571 splayroot = splayinsert(splayroot, &lefttri, nextpoint);
8572 } else if (randomnation(SAMPLERATE) == 0) {
8573 lnext(righttri, inserttri);
8574 splayroot = splayinsert(splayroot, &inserttri, nextpoint);
8578 nextevent->eventptr = (VOID *) freeevents;
8579 freeevents = nextevent;
8582 apex(farlefttri, leftpoint);
8583 dest(lefttri, midpoint);
8584 apex(lefttri, rightpoint);
8585 lefttest = counterclockwise(leftpoint, midpoint, rightpoint);
8586 if (lefttest > 0.0) {
8587 newevent = freeevents;
8588 freeevents = (struct event *) freeevents->eventptr;
8589 newevent->xkey = xminextreme;
8590 newevent->ykey = circletop(leftpoint, midpoint, rightpoint,
8592 newevent->eventptr = (VOID *) encode(lefttri);
8593 eventheapinsert(eventheap, heapsize, newevent);
8595 setorg(lefttri, newevent);
8597 apex(righttri, leftpoint);
8598 org(righttri, midpoint);
8599 apex(farrighttri, rightpoint);
8600 righttest = counterclockwise(leftpoint, midpoint, rightpoint);
8601 if (righttest > 0.0) {
8602 newevent = freeevents;
8603 freeevents = (struct event *) freeevents->eventptr;
8604 newevent->xkey = xminextreme;
8605 newevent->ykey = circletop(leftpoint, midpoint, rightpoint,
8607 newevent->eventptr = (VOID *) encode(farrighttri);
8608 eventheapinsert(eventheap, heapsize, newevent);
8610 setorg(farrighttri, newevent);
8615 pooldeinit(&splaynodes);
8616 lprevself(bottommost);
8617 return removeghosts(&bottommost);
8620 #endif /* not REDUCED */
8624 /********* Sweepline Delaunay triangulation ends here *********/
8626 /********* General mesh construction routines begin here *********/
8630 /*****************************************************************************/
8632 /* delaunay() Form a Delaunay triangulation. */
8634 /*****************************************************************************/
8639 initializetrisegpools();
8644 "Constructing Delaunay triangulation by divide-and-conquer method.\n");
8646 return divconqdelaunay();
8647 #else /* not REDUCED */
8649 printf("Constructing Delaunay triangulation ");
8651 printf("by incremental method.\n");
8652 } else if (sweepline) {
8653 printf("by sweepline method.\n");
8655 printf("by divide-and-conquer method.\n");
8659 return incrementaldelaunay();
8660 } else if (sweepline) {
8661 return sweeplinedelaunay();
8663 return divconqdelaunay();
8665 #endif /* not REDUCED */
8668 /*****************************************************************************/
8670 /* reconstruct() Reconstruct a triangulation from its .ele (and possibly */
8671 /* .poly) file. Used when the -r switch is used. */
8673 /* Reads an .ele file and reconstructs the original mesh. If the -p switch */
8674 /* is used, this procedure will also read a .poly file and reconstruct the */
8675 /* shell edges of the original mesh. If the -a switch is used, this */
8676 /* procedure will also read an .area file and set a maximum area constraint */
8677 /* on each triangle. */
8679 /* Points that are not corners of triangles, such as nodes on edges of */
8680 /* subparametric elements, are discarded. */
8682 /* This routine finds the adjacencies between triangles (and shell edges) */
8683 /* by forming one stack of triangles for each vertex. Each triangle is on */
8684 /* three different stacks simultaneously. Each triangle's shell edge */
8685 /* pointers are used to link the items in each stack. This memory-saving */
8686 /* feature makes the code harder to read. The most important thing to keep */
8687 /* in mind is that each triangle is removed from a stack precisely when */
8688 /* the corresponding pointer is adjusted to refer to a shell edge rather */
8689 /* than the next triangle of the stack. */
8691 /*****************************************************************************/
8697 int reconstruct(trianglelist, triangleattriblist, trianglearealist, elements,
8698 corners, attribs, segmentlist, segmentmarkerlist,
8701 REAL *triangleattriblist;
8702 REAL *trianglearealist;
8707 int *segmentmarkerlist;
8708 int numberofsegments;
8710 #else /* not TRILIBRARY */
8712 long reconstruct(elefilename, areafilename, polyfilename, polyfile)
8718 #endif /* not TRILIBRARY */
8724 #else /* not TRILIBRARY */
8727 char inputline[INPUTLINESIZE];
8730 #endif /* not TRILIBRARY */
8731 struct triedge triangleloop;
8732 struct triedge triangleleft;
8733 struct triedge checktri;
8734 struct triedge checkleft;
8735 struct triedge checkneighbor;
8736 struct edge shelleloop;
8737 triangle *vertexarray;
8741 point checkdest, checkapex;
8754 int elementnumber, segmentnumber;
8756 triangle ptr; /* Temporary variable used by sym(). */
8759 inelements = elements;
8760 incorners = corners;
8761 if (incorners < 3) {
8762 printf("Error: Triangles must have at least 3 points.\n");
8766 #else /* not TRILIBRARY */
8767 /* Read the triangles from an .ele file. */
8769 printf("Opening %s.\n", elefilename);
8771 elefile = fopen(elefilename, "r");
8772 if (elefile == (FILE *) NULL) {
8773 printf(" Error: Cannot access file %s.\n", elefilename);
8776 /* Read number of triangles, number of points per triangle, and */
8777 /* number of triangle attributes from .ele file. */
8778 stringptr = readline(inputline, elefile, elefilename);
8779 inelements = (int) strtol (stringptr, &stringptr, 0);
8780 stringptr = findfield(stringptr);
8781 if (*stringptr == '\0') {
8784 incorners = (int) strtol (stringptr, &stringptr, 0);
8785 if (incorners < 3) {
8786 printf("Error: Triangles in %s must have at least 3 points.\n",
8791 stringptr = findfield(stringptr);
8792 if (*stringptr == '\0') {
8795 eextras = (int) strtol (stringptr, &stringptr, 0);
8797 #endif /* not TRILIBRARY */
8799 initializetrisegpools();
8801 /* Create the triangles. */
8802 for (elementnumber = 1; elementnumber <= inelements; elementnumber++) {
8803 maketriangle(&triangleloop);
8804 /* Mark the triangle as living. */
8805 triangleloop.tri[3] = (triangle) triangleloop.tri;
8810 insegments = numberofsegments;
8811 segmentmarkers = segmentmarkerlist != (int *) NULL;
8812 #else /* not TRILIBRARY */
8813 /* Read number of segments and number of segment */
8814 /* boundary markers from .poly file. */
8815 stringptr = readline(inputline, polyfile, inpolyfilename);
8816 insegments = (int) strtol (stringptr, &stringptr, 0);
8817 stringptr = findfield(stringptr);
8818 if (*stringptr == '\0') {
8821 segmentmarkers = (int) strtol (stringptr, &stringptr, 0);
8823 #endif /* not TRILIBRARY */
8825 /* Create the shell edges. */
8826 for (segmentnumber = 1; segmentnumber <= insegments; segmentnumber++) {
8827 makeshelle(&shelleloop);
8828 /* Mark the shell edge as living. */
8829 shelleloop.sh[2] = (shelle) shelleloop.sh;
8836 #else /* not TRILIBRARY */
8838 /* Open an .area file, check for consistency with the .ele file. */
8840 printf("Opening %s.\n", areafilename);
8842 areafile = fopen(areafilename, "r");
8843 if (areafile == (FILE *) NULL) {
8844 printf(" Error: Cannot access file %s.\n", areafilename);
8847 stringptr = readline(inputline, areafile, areafilename);
8848 areaelements = (int) strtol (stringptr, &stringptr, 0);
8849 if (areaelements != inelements) {
8850 printf("Error: %s and %s disagree on number of triangles.\n",
8851 elefilename, areafilename);
8855 #endif /* not TRILIBRARY */
8858 printf("Reconstructing mesh.\n");
8860 /* Allocate a temporary array that maps each point to some adjacent */
8861 /* triangle. I took care to allocate all the permanent memory for */
8862 /* triangles and shell edges first. */
8863 vertexarray = (triangle *) malloc(points.items * sizeof(triangle));
8864 if (vertexarray == (triangle *) NULL) {
8865 printf("Error: Out of memory.\n");
8868 /* Each point is initially unrepresented. */
8869 for (i = 0; i < points.items; i++) {
8870 vertexarray[i] = (triangle) dummytri;
8874 printf(" Assembling triangles.\n");
8876 /* Read the triangles from the .ele file, and link */
8877 /* together those that share an edge. */
8878 traversalinit(&triangles);
8879 triangleloop.tri = triangletraverse();
8880 elementnumber = firstnumber;
8881 while (triangleloop.tri != (triangle *) NULL) {
8883 /* Copy the triangle's three corners. */
8884 for (j = 0; j < 3; j++) {
8885 corner[j] = trianglelist[pointindex++];
8886 if ((corner[j] < firstnumber) || (corner[j] >= firstnumber + inpoints)) {
8887 printf("Error: Triangle %d has an invalid vertex index.\n",
8892 #else /* not TRILIBRARY */
8893 /* Read triangle number and the triangle's three corners. */
8894 stringptr = readline(inputline, elefile, elefilename);
8895 for (j = 0; j < 3; j++) {
8896 stringptr = findfield(stringptr);
8897 if (*stringptr == '\0') {
8898 printf("Error: Triangle %d is missing point %d in %s.\n",
8899 elementnumber, j + 1, elefilename);
8902 corner[j] = (int) strtol (stringptr, &stringptr, 0);
8903 if ((corner[j] < firstnumber) ||
8904 (corner[j] >= firstnumber + inpoints)) {
8905 printf("Error: Triangle %d has an invalid vertex index.\n",
8911 #endif /* not TRILIBRARY */
8913 /* Find out about (and throw away) extra nodes. */
8914 for (j = 3; j < incorners; j++) {
8916 killpointindex = trianglelist[pointindex++];
8917 #else /* not TRILIBRARY */
8918 stringptr = findfield(stringptr);
8919 if (*stringptr != '\0') {
8920 killpointindex = (int) strtol (stringptr, &stringptr, 0);
8921 #endif /* not TRILIBRARY */
8922 if ((killpointindex >= firstnumber) &&
8923 (killpointindex < firstnumber + inpoints)) {
8924 /* Delete the non-corner point if it's not already deleted. */
8925 killpoint = getpoint(killpointindex);
8926 if (pointmark(killpoint) != DEADPOINT) {
8927 pointdealloc(killpoint);
8932 #endif /* not TRILIBRARY */
8935 /* Read the triangle's attributes. */
8936 for (j = 0; j < eextras; j++) {
8938 setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
8939 #else /* not TRILIBRARY */
8940 stringptr = findfield(stringptr);
8941 if (*stringptr == '\0') {
8942 setelemattribute(triangleloop, j, 0);
8944 setelemattribute(triangleloop, j,
8945 (REAL) strtod (stringptr, &stringptr));
8947 #endif /* not TRILIBRARY */
8952 area = trianglearealist[elementnumber - firstnumber];
8953 #else /* not TRILIBRARY */
8954 /* Read an area constraint from the .area file. */
8955 stringptr = readline(inputline, areafile, areafilename);
8956 stringptr = findfield(stringptr);
8957 if (*stringptr == '\0') {
8958 area = -1.0; /* No constraint on this triangle. */
8960 area = (REAL) strtod(stringptr, &stringptr);
8962 #endif /* not TRILIBRARY */
8963 setareabound(triangleloop, area);
8966 /* Set the triangle's vertices. */
8967 triangleloop.orient = 0;
8968 setorg(triangleloop, getpoint(corner[0]));
8969 setdest(triangleloop, getpoint(corner[1]));
8970 setapex(triangleloop, getpoint(corner[2]));
8971 /* Try linking the triangle to others that share these vertices. */
8972 for (triangleloop.orient = 0; triangleloop.orient < 3;
8973 triangleloop.orient++) {
8974 /* Take the number for the origin of triangleloop. */
8975 aroundpoint = corner[triangleloop.orient];
8976 /* Look for other triangles having this vertex. */
8977 nexttri = vertexarray[aroundpoint - firstnumber];
8978 /* Link the current triangle to the next one in the stack. */
8979 triangleloop.tri[6 + triangleloop.orient] = nexttri;
8980 /* Push the current triangle onto the stack. */
8981 vertexarray[aroundpoint - firstnumber] = encode(triangleloop);
8982 decode(nexttri, checktri);
8983 if (checktri.tri != dummytri) {
8984 dest(triangleloop, tdest);
8985 apex(triangleloop, tapex);
8986 /* Look for other triangles that share an edge. */
8988 dest(checktri, checkdest);
8989 apex(checktri, checkapex);
8990 if (tapex == checkdest) {
8991 /* The two triangles share an edge; bond them together. */
8992 lprev(triangleloop, triangleleft);
8993 bond(triangleleft, checktri);
8995 if (tdest == checkapex) {
8996 /* The two triangles share an edge; bond them together. */
8997 lprev(checktri, checkleft);
8998 bond(triangleloop, checkleft);
9000 /* Find the next triangle in the stack. */
9001 nexttri = checktri.tri[6 + checktri.orient];
9002 decode(nexttri, checktri);
9003 } while (checktri.tri != dummytri);
9006 triangleloop.tri = triangletraverse();
9012 #else /* not TRILIBRARY */
9017 #endif /* not TRILIBRARY */
9019 hullsize = 0; /* Prepare to count the boundary edges. */
9022 printf(" Marking segments in triangulation.\n");
9024 /* Read the segments from the .poly file, and link them */
9025 /* to their neighboring triangles. */
9027 traversalinit(&shelles);
9028 shelleloop.sh = shelletraverse();
9029 segmentnumber = firstnumber;
9030 while (shelleloop.sh != (shelle *) NULL) {
9032 end[0] = segmentlist[pointindex++];
9033 end[1] = segmentlist[pointindex++];
9034 if (segmentmarkers) {
9035 boundmarker = segmentmarkerlist[segmentnumber - firstnumber];
9037 #else /* not TRILIBRARY */
9038 /* Read the endpoints of each segment, and possibly a boundary marker. */
9039 stringptr = readline(inputline, polyfile, inpolyfilename);
9040 /* Skip the first (segment number) field. */
9041 stringptr = findfield(stringptr);
9042 if (*stringptr == '\0') {
9043 printf("Error: Segment %d has no endpoints in %s.\n", segmentnumber,
9047 end[0] = (int) strtol (stringptr, &stringptr, 0);
9049 stringptr = findfield(stringptr);
9050 if (*stringptr == '\0') {
9051 printf("Error: Segment %d is missing its second endpoint in %s.\n",
9052 segmentnumber, polyfilename);
9055 end[1] = (int) strtol (stringptr, &stringptr, 0);
9057 if (segmentmarkers) {
9058 stringptr = findfield(stringptr);
9059 if (*stringptr == '\0') {
9062 boundmarker = (int) strtol (stringptr, &stringptr, 0);
9065 #endif /* not TRILIBRARY */
9066 for (j = 0; j < 2; j++) {
9067 if ((end[j] < firstnumber) || (end[j] >= firstnumber + inpoints)) {
9068 printf("Error: Segment %d has an invalid vertex index.\n",
9074 /* set the shell edge's vertices. */
9075 shelleloop.shorient = 0;
9076 setsorg(shelleloop, getpoint(end[0]));
9077 setsdest(shelleloop, getpoint(end[1]));
9078 setmark(shelleloop, boundmarker);
9079 /* Try linking the shell edge to triangles that share these vertices. */
9080 for (shelleloop.shorient = 0; shelleloop.shorient < 2;
9081 shelleloop.shorient++) {
9082 /* Take the number for the destination of shelleloop. */
9083 aroundpoint = end[1 - shelleloop.shorient];
9084 /* Look for triangles having this vertex. */
9085 prevlink = &vertexarray[aroundpoint - firstnumber];
9086 nexttri = vertexarray[aroundpoint - firstnumber];
9087 decode(nexttri, checktri);
9088 sorg(shelleloop, shorg);
9090 /* Look for triangles having this edge. Note that I'm only */
9091 /* comparing each triangle's destination with the shell edge; */
9092 /* each triangle's apex is handled through a different vertex. */
9093 /* Because each triangle appears on three vertices' lists, each */
9094 /* occurrence of a triangle on a list can (and does) represent */
9095 /* an edge. In this way, most edges are represented twice, and */
9096 /* every triangle-segment bond is represented once. */
9097 while (notfound && (checktri.tri != dummytri)) {
9098 dest(checktri, checkdest);
9099 if (shorg == checkdest) {
9100 /* We have a match. Remove this triangle from the list. */
9101 *prevlink = checktri.tri[6 + checktri.orient];
9102 /* Bond the shell edge to the triangle. */
9103 tsbond(checktri, shelleloop);
9104 /* Check if this is a boundary edge. */
9105 sym(checktri, checkneighbor);
9106 if (checkneighbor.tri == dummytri) {
9107 /* The next line doesn't insert a shell edge (because there's */
9108 /* already one there), but it sets the boundary markers of */
9109 /* the existing shell edge and its vertices. */
9110 insertshelle(&checktri, 1);
9115 /* Find the next triangle in the stack. */
9116 prevlink = &checktri.tri[6 + checktri.orient];
9117 nexttri = checktri.tri[6 + checktri.orient];
9118 decode(nexttri, checktri);
9121 shelleloop.sh = shelletraverse();
9126 /* Mark the remaining edges as not being attached to any shell edge. */
9127 /* Also, count the (yet uncounted) boundary edges. */
9128 for (i = 0; i < points.items; i++) {
9129 /* Search the stack of triangles adjacent to a point. */
9130 nexttri = vertexarray[i];
9131 decode(nexttri, checktri);
9132 while (checktri.tri != dummytri) {
9133 /* Find the next triangle in the stack before this */
9134 /* information gets overwritten. */
9135 nexttri = checktri.tri[6 + checktri.orient];
9136 /* No adjacent shell edge. (This overwrites the stack info.) */
9137 tsdissolve(checktri);
9138 sym(checktri, checkneighbor);
9139 if (checkneighbor.tri == dummytri) {
9140 insertshelle(&checktri, 1);
9143 decode(nexttri, checktri);
9151 #endif /* not CDT_ONLY */
9155 /********* General mesh construction routines end here *********/
9157 /********* Segment (shell edge) insertion begins here *********/
9161 /*****************************************************************************/
9163 /* finddirection() Find the first triangle on the path from one point */
9166 /* Finds the triangle that intersects a line segment drawn from the */
9167 /* origin of `searchtri' to the point `endpoint', and returns the result */
9168 /* in `searchtri'. The origin of `searchtri' does not change, even though */
9169 /* the triangle returned may differ from the one passed in. This routine */
9170 /* is used to find the direction to move in to get from one point to */
9173 /* The return value notes whether the destination or apex of the found */
9174 /* triangle is collinear with the two points in question. */
9176 /*****************************************************************************/
9178 enum finddirectionresult finddirection(searchtri, endpoint)
9179 struct triedge *searchtri;
9182 struct triedge checktri;
9184 point leftpoint, rightpoint;
9185 REAL leftccw, rightccw;
9186 int leftflag, rightflag;
9187 triangle ptr; /* Temporary variable used by onext() and oprev(). */
9189 org(*searchtri, startpoint);
9190 dest(*searchtri, rightpoint);
9191 apex(*searchtri, leftpoint);
9192 /* Is `endpoint' to the left? */
9193 leftccw = counterclockwise(endpoint, startpoint, leftpoint);
9194 leftflag = leftccw > 0.0;
9195 /* Is `endpoint' to the right? */
9196 rightccw = counterclockwise(startpoint, endpoint, rightpoint);
9197 rightflag = rightccw > 0.0;
9198 if (leftflag && rightflag) {
9199 /* `searchtri' faces directly away from `endpoint'. We could go */
9200 /* left or right. Ask whether it's a triangle or a boundary */
9202 onext(*searchtri, checktri);
9203 if (checktri.tri == dummytri) {
9210 /* Turn left until satisfied. */
9211 onextself(*searchtri);
9212 if (searchtri->tri == dummytri) {
9213 printf("Internal error in finddirection(): Unable to find a\n");
9214 printf(" triangle leading from (%.12g, %.12g) to", startpoint[0],
9216 printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]);
9219 apex(*searchtri, leftpoint);
9221 leftccw = counterclockwise(endpoint, startpoint, leftpoint);
9222 leftflag = leftccw > 0.0;
9225 /* Turn right until satisfied. */
9226 oprevself(*searchtri);
9227 if (searchtri->tri == dummytri) {
9228 printf("Internal error in finddirection(): Unable to find a\n");
9229 printf(" triangle leading from (%.12g, %.12g) to", startpoint[0],
9231 printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]);
9234 dest(*searchtri, rightpoint);
9236 rightccw = counterclockwise(startpoint, endpoint, rightpoint);
9237 rightflag = rightccw > 0.0;
9239 if (leftccw == 0.0) {
9240 return LEFTCOLLINEAR;
9241 } else if (rightccw == 0.0) {
9242 return RIGHTCOLLINEAR;
9248 /*****************************************************************************/
9250 /* segmentintersection() Find the intersection of an existing segment */
9251 /* and a segment that is being inserted. Insert */
9252 /* a point at the intersection, splitting an */
9253 /* existing shell edge. */
9255 /* The segment being inserted connects the apex of splittri to endpoint2. */
9256 /* splitshelle is the shell edge being split, and MUST be opposite */
9257 /* splittri. Hence, the edge being split connects the origin and */
9258 /* destination of splittri. */
9260 /* On completion, splittri is a handle having the newly inserted */
9261 /* intersection point as its origin, and endpoint1 as its destination. */
9263 /*****************************************************************************/
9265 void segmentintersection(splittri, splitshelle, endpoint2)
9266 struct triedge *splittri;
9267 struct edge *splitshelle;
9272 point leftpoint, rightpoint;
9274 enum insertsiteresult success;
9275 enum finddirectionresult collinear;
9281 triangle ptr; /* Temporary variable used by onext(). */
9283 /* Find the other three segment endpoints. */
9284 apex(*splittri, endpoint1);
9285 org(*splittri, torg);
9286 dest(*splittri, tdest);
9287 /* Segment intersection formulae; see the Antonio reference. */
9288 tx = tdest[0] - torg[0];
9289 ty = tdest[1] - torg[1];
9290 ex = endpoint2[0] - endpoint1[0];
9291 ey = endpoint2[1] - endpoint1[1];
9292 etx = torg[0] - endpoint2[0];
9293 ety = torg[1] - endpoint2[1];
9294 denom = ty * ex - tx * ey;
9296 printf("Internal error in segmentintersection():");
9297 printf(" Attempt to find intersection of parallel segments.\n");
9300 split = (ey * etx - ex * ety) / denom;
9301 /* Create the new point. */
9302 newpoint = (point) poolalloc(&points);
9303 /* Interpolate its coordinate and attributes. */
9304 for (i = 0; i < 2 + nextras; i++) {
9305 newpoint[i] = torg[i] + split * (tdest[i] - torg[i]);
9307 setpointmark(newpoint, mark(*splitshelle));
9310 " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
9311 torg[0], torg[1], tdest[0], tdest[1], newpoint[0], newpoint[1]);
9313 /* Insert the intersection point. This should always succeed. */
9314 success = insertsite(newpoint, splittri, splitshelle, 0, 0);
9315 if (success != SUCCESSFULPOINT) {
9316 printf("Internal error in segmentintersection():\n");
9317 printf(" Failure to split a segment.\n");
9320 if (steinerleft > 0) {
9323 /* Inserting the point may have caused edge flips. We wish to rediscover */
9324 /* the edge connecting endpoint1 to the new intersection point. */
9325 collinear = finddirection(splittri, endpoint1);
9326 dest(*splittri, rightpoint);
9327 apex(*splittri, leftpoint);
9328 if ((leftpoint[0] == endpoint1[0]) && (leftpoint[1] == endpoint1[1])) {
9329 onextself(*splittri);
9330 } else if ((rightpoint[0] != endpoint1[0]) ||
9331 (rightpoint[1] != endpoint1[1])) {
9332 printf("Internal error in segmentintersection():\n");
9333 printf(" Topological inconsistency after splitting a segment.\n");
9336 /* `splittri' should have destination endpoint1. */
9339 /*****************************************************************************/
9341 /* scoutsegment() Scout the first triangle on the path from one endpoint */
9342 /* to another, and check for completion (reaching the */
9343 /* second endpoint), a collinear point, and the */
9344 /* intersection of two segments. */
9346 /* Returns one if the entire segment is successfully inserted, and zero if */
9347 /* the job must be finished by conformingedge() or constrainededge(). */
9349 /* If the first triangle on the path has the second endpoint as its */
9350 /* destination or apex, a shell edge is inserted and the job is done. */
9352 /* If the first triangle on the path has a destination or apex that lies on */
9353 /* the segment, a shell edge is inserted connecting the first endpoint to */
9354 /* the collinear point, and the search is continued from the collinear */
9357 /* If the first triangle on the path has a shell edge opposite its origin, */
9358 /* then there is a segment that intersects the segment being inserted. */
9359 /* Their intersection point is inserted, splitting the shell edge. */
9361 /* Otherwise, return zero. */
9363 /*****************************************************************************/
9365 int scoutsegment(searchtri, endpoint2, newmark)
9366 struct triedge *searchtri;
9370 struct triedge crosstri;
9371 struct edge crossedge;
9372 point leftpoint, rightpoint;
9374 enum finddirectionresult collinear;
9375 shelle sptr; /* Temporary variable used by tspivot(). */
9377 collinear = finddirection(searchtri, endpoint2);
9378 dest(*searchtri, rightpoint);
9379 apex(*searchtri, leftpoint);
9380 if (((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) ||
9381 ((rightpoint[0] == endpoint2[0]) && (rightpoint[1] == endpoint2[1]))) {
9382 /* The segment is already an edge in the mesh. */
9383 if ((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) {
9384 lprevself(*searchtri);
9386 /* Insert a shell edge, if there isn't already one there. */
9387 insertshelle(searchtri, newmark);
9389 } else if (collinear == LEFTCOLLINEAR) {
9390 /* We've collided with a point between the segment's endpoints. */
9391 /* Make the collinear point be the triangle's origin. */
9392 lprevself(*searchtri);
9393 insertshelle(searchtri, newmark);
9394 /* Insert the remainder of the segment. */
9395 return scoutsegment(searchtri, endpoint2, newmark);
9396 } else if (collinear == RIGHTCOLLINEAR) {
9397 /* We've collided with a point between the segment's endpoints. */
9398 insertshelle(searchtri, newmark);
9399 /* Make the collinear point be the triangle's origin. */
9400 lnextself(*searchtri);
9401 /* Insert the remainder of the segment. */
9402 return scoutsegment(searchtri, endpoint2, newmark);
9404 lnext(*searchtri, crosstri);
9405 tspivot(crosstri, crossedge);
9406 /* Check for a crossing segment. */
9407 if (crossedge.sh == dummysh) {
9410 org(*searchtri, endpoint1);
9411 /* Insert a point at the intersection. */
9412 segmentintersection(&crosstri, &crossedge, endpoint2);
9413 triedgecopy(crosstri, *searchtri);
9414 insertshelle(searchtri, newmark);
9415 /* Insert the remainder of the segment. */
9416 return scoutsegment(searchtri, endpoint2, newmark);
9421 /*****************************************************************************/
9423 /* conformingedge() Force a segment into a conforming Delaunay */
9424 /* triangulation by inserting a point at its midpoint, */
9425 /* and recursively forcing in the two half-segments if */
9428 /* Generates a sequence of edges connecting `endpoint1' to `endpoint2'. */
9429 /* `newmark' is the boundary marker of the segment, assigned to each new */
9430 /* splitting point and shell edge. */
9432 /* Note that conformingedge() does not always maintain the conforming */
9433 /* Delaunay property. Once inserted, segments are locked into place; */
9434 /* points inserted later (to force other segments in) may render these */
9435 /* fixed segments non-Delaunay. The conforming Delaunay property will be */
9436 /* restored by enforcequality() by splitting encroached segments. */
9438 /*****************************************************************************/
9443 void conformingedge(endpoint1, endpoint2, newmark)
9448 struct triedge searchtri1, searchtri2;
9449 struct edge brokenshelle;
9451 point midpoint1, midpoint2;
9452 enum insertsiteresult success;
9453 int result1, result2;
9455 shelle sptr; /* Temporary variable used by tspivot(). */
9458 printf("Forcing segment into triangulation by recursive splitting:\n");
9459 printf(" (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
9460 endpoint2[0], endpoint2[1]);
9462 /* Create a new point to insert in the middle of the segment. */
9463 newpoint = (point) poolalloc(&points);
9464 /* Interpolate coordinates and attributes. */
9465 for (i = 0; i < 2 + nextras; i++) {
9466 newpoint[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
9468 setpointmark(newpoint, newmark);
9469 /* Find a boundary triangle to search from. */
9470 searchtri1.tri = (triangle *) NULL;
9471 /* Attempt to insert the new point. */
9472 success = insertsite(newpoint, &searchtri1, (struct edge *) NULL, 0, 0);
9473 if (success == DUPLICATEPOINT) {
9475 printf(" Segment intersects existing point (%.12g, %.12g).\n",
9476 newpoint[0], newpoint[1]);
9478 /* Use the point that's already there. */
9479 pointdealloc(newpoint);
9480 org(searchtri1, newpoint);
9482 if (success == VIOLATINGPOINT) {
9484 printf(" Two segments intersect at (%.12g, %.12g).\n",
9485 newpoint[0], newpoint[1]);
9487 /* By fluke, we've landed right on another segment. Split it. */
9488 tspivot(searchtri1, brokenshelle);
9489 success = insertsite(newpoint, &searchtri1, &brokenshelle, 0, 0);
9490 if (success != SUCCESSFULPOINT) {
9491 printf("Internal error in conformingedge():\n");
9492 printf(" Failure to split a segment.\n");
9496 /* The point has been inserted successfully. */
9497 if (steinerleft > 0) {
9501 triedgecopy(searchtri1, searchtri2);
9502 result1 = scoutsegment(&searchtri1, endpoint1, newmark);
9503 result2 = scoutsegment(&searchtri2, endpoint2, newmark);
9505 /* The origin of searchtri1 may have changed if a collision with an */
9506 /* intervening vertex on the segment occurred. */
9507 org(searchtri1, midpoint1);
9508 conformingedge(midpoint1, endpoint1, newmark);
9511 /* The origin of searchtri2 may have changed if a collision with an */
9512 /* intervening vertex on the segment occurred. */
9513 org(searchtri2, midpoint2);
9514 conformingedge(midpoint2, endpoint2, newmark);
9518 #endif /* not CDT_ONLY */
9519 #endif /* not REDUCED */
9521 /*****************************************************************************/
9523 /* delaunayfixup() Enforce the Delaunay condition at an edge, fanning out */
9524 /* recursively from an existing point. Pay special */
9525 /* attention to stacking inverted triangles. */
9527 /* This is a support routine for inserting segments into a constrained */
9528 /* Delaunay triangulation. */
9530 /* The origin of fixuptri is treated as if it has just been inserted, and */
9531 /* the local Delaunay condition needs to be enforced. It is only enforced */
9532 /* in one sector, however, that being the angular range defined by */
9535 /* This routine also needs to make decisions regarding the "stacking" of */
9536 /* triangles. (Read the description of constrainededge() below before */
9537 /* reading on here, so you understand the algorithm.) If the position of */
9538 /* the new point (the origin of fixuptri) indicates that the vertex before */
9539 /* it on the polygon is a reflex vertex, then "stack" the triangle by */
9540 /* doing nothing. (fixuptri is an inverted triangle, which is how stacked */
9541 /* triangles are identified.) */
9543 /* Otherwise, check whether the vertex before that was a reflex vertex. */
9544 /* If so, perform an edge flip, thereby eliminating an inverted triangle */
9545 /* (popping it off the stack). The edge flip may result in the creation */
9546 /* of a new inverted triangle, depending on whether or not the new vertex */
9547 /* is visible to the vertex three edges behind on the polygon. */
9549 /* If neither of the two vertices behind the new vertex are reflex */
9550 /* vertices, fixuptri and fartri, the triangle opposite it, are not */
9551 /* inverted; hence, ensure that the edge between them is locally Delaunay. */
9553 /* `leftside' indicates whether or not fixuptri is to the left of the */
9554 /* segment being inserted. (Imagine that the segment is pointing up from */
9555 /* endpoint1 to endpoint2.) */
9557 /*****************************************************************************/
9559 void delaunayfixup(fixuptri, leftside)
9560 struct triedge *fixuptri;
9563 struct triedge neartri;
9564 struct triedge fartri;
9565 struct edge faredge;
9566 point nearpoint, leftpoint, rightpoint, farpoint;
9567 triangle ptr; /* Temporary variable used by sym(). */
9568 shelle sptr; /* Temporary variable used by tspivot(). */
9570 lnext(*fixuptri, neartri);
9571 sym(neartri, fartri);
9572 /* Check if the edge opposite the origin of fixuptri can be flipped. */
9573 if (fartri.tri == dummytri) {
9576 tspivot(neartri, faredge);
9577 if (faredge.sh != dummysh) {
9580 /* Find all the relevant vertices. */
9581 apex(neartri, nearpoint);
9582 org(neartri, leftpoint);
9583 dest(neartri, rightpoint);
9584 apex(fartri, farpoint);
9585 /* Check whether the previous polygon vertex is a reflex vertex. */
9587 if (counterclockwise(nearpoint, leftpoint, farpoint) <= 0.0) {
9588 /* leftpoint is a reflex vertex too. Nothing can */
9589 /* be done until a convex section is found. */
9593 if (counterclockwise(farpoint, rightpoint, nearpoint) <= 0.0) {
9594 /* rightpoint is a reflex vertex too. Nothing can */
9595 /* be done until a convex section is found. */
9599 if (counterclockwise(rightpoint, leftpoint, farpoint) > 0.0) {
9600 /* fartri is not an inverted triangle, and farpoint is not a reflex */
9601 /* vertex. As there are no reflex vertices, fixuptri isn't an */
9602 /* inverted triangle, either. Hence, test the edge between the */
9603 /* triangles to ensure it is locally Delaunay. */
9604 if (incircle(leftpoint, farpoint, rightpoint, nearpoint) <= 0.0) {
9607 /* Not locally Delaunay; go on to an edge flip. */
9608 } /* else fartri is inverted; remove it from the stack by flipping. */
9610 lprevself(*fixuptri); /* Restore the origin of fixuptri after the flip. */
9611 /* Recursively process the two triangles that result from the flip. */
9612 delaunayfixup(fixuptri, leftside);
9613 delaunayfixup(&fartri, leftside);
9616 /*****************************************************************************/
9618 /* constrainededge() Force a segment into a constrained Delaunay */
9619 /* triangulation by deleting the triangles it */
9620 /* intersects, and triangulating the polygons that */
9621 /* form on each side of it. */
9623 /* Generates a single edge connecting `endpoint1' to `endpoint2'. The */
9624 /* triangle `starttri' has `endpoint1' as its origin. `newmark' is the */
9625 /* boundary marker of the segment. */
9627 /* To insert a segment, every triangle whose interior intersects the */
9628 /* segment is deleted. The union of these deleted triangles is a polygon */
9629 /* (which is not necessarily monotone, but is close enough), which is */
9630 /* divided into two polygons by the new segment. This routine's task is */
9631 /* to generate the Delaunay triangulation of these two polygons. */
9633 /* You might think of this routine's behavior as a two-step process. The */
9634 /* first step is to walk from endpoint1 to endpoint2, flipping each edge */
9635 /* encountered. This step creates a fan of edges connected to endpoint1, */
9636 /* including the desired edge to endpoint2. The second step enforces the */
9637 /* Delaunay condition on each side of the segment in an incremental manner: */
9638 /* proceeding along the polygon from endpoint1 to endpoint2 (this is done */
9639 /* independently on each side of the segment), each vertex is "enforced" */
9640 /* as if it had just been inserted, but affecting only the previous */
9641 /* vertices. The result is the same as if the vertices had been inserted */
9642 /* in the order they appear on the polygon, so the result is Delaunay. */
9644 /* In truth, constrainededge() interleaves these two steps. The procedure */
9645 /* walks from endpoint1 to endpoint2, and each time an edge is encountered */
9646 /* and flipped, the newly exposed vertex (at the far end of the flipped */
9647 /* edge) is "enforced" upon the previously flipped edges, usually affecting */
9648 /* only one side of the polygon (depending upon which side of the segment */
9649 /* the vertex falls on). */
9651 /* The algorithm is complicated by the need to handle polygons that are not */
9652 /* convex. Although the polygon is not necessarily monotone, it can be */
9653 /* triangulated in a manner similar to the stack-based algorithms for */
9654 /* monotone polygons. For each reflex vertex (local concavity) of the */
9655 /* polygon, there will be an inverted triangle formed by one of the edge */
9656 /* flips. (An inverted triangle is one with negative area - that is, its */
9657 /* vertices are arranged in clockwise order - and is best thought of as a */
9658 /* wrinkle in the fabric of the mesh.) Each inverted triangle can be */
9659 /* thought of as a reflex vertex pushed on the stack, waiting to be fixed */
9662 /* A reflex vertex is popped from the stack when a vertex is inserted that */
9663 /* is visible to the reflex vertex. (However, if the vertex behind the */
9664 /* reflex vertex is not visible to the reflex vertex, a new inverted */
9665 /* triangle will take its place on the stack.) These details are handled */
9666 /* by the delaunayfixup() routine above. */
9668 /*****************************************************************************/
9670 void constrainededge(starttri, endpoint2, newmark)
9671 struct triedge *starttri;
9675 struct triedge fixuptri, fixuptri2;
9676 struct edge fixupedge;
9682 triangle ptr; /* Temporary variable used by sym() and oprev(). */
9683 shelle sptr; /* Temporary variable used by tspivot(). */
9685 org(*starttri, endpoint1);
9686 lnext(*starttri, fixuptri);
9688 /* `collision' indicates whether we have found a point directly */
9689 /* between endpoint1 and endpoint2. */
9693 org(fixuptri, farpoint);
9694 /* `farpoint' is the extreme point of the polygon we are "digging" */
9695 /* to get from endpoint1 to endpoint2. */
9696 if ((farpoint[0] == endpoint2[0]) && (farpoint[1] == endpoint2[1])) {
9697 oprev(fixuptri, fixuptri2);
9698 /* Enforce the Delaunay condition around endpoint2. */
9699 delaunayfixup(&fixuptri, 0);
9700 delaunayfixup(&fixuptri2, 1);
9703 /* Check whether farpoint is to the left or right of the segment */
9704 /* being inserted, to decide which edge of fixuptri to dig */
9706 area = counterclockwise(endpoint1, endpoint2, farpoint);
9708 /* We've collided with a point between endpoint1 and endpoint2. */
9710 oprev(fixuptri, fixuptri2);
9711 /* Enforce the Delaunay condition around farpoint. */
9712 delaunayfixup(&fixuptri, 0);
9713 delaunayfixup(&fixuptri2, 1);
9716 if (area > 0.0) { /* farpoint is to the left of the segment. */
9717 oprev(fixuptri, fixuptri2);
9718 /* Enforce the Delaunay condition around farpoint, on the */
9719 /* left side of the segment only. */
9720 delaunayfixup(&fixuptri2, 1);
9721 /* Flip the edge that crosses the segment. After the edge is */
9722 /* flipped, one of its endpoints is the fan vertex, and the */
9723 /* destination of fixuptri is the fan vertex. */
9724 lprevself(fixuptri);
9725 } else { /* farpoint is to the right of the segment. */
9726 delaunayfixup(&fixuptri, 0);
9727 /* Flip the edge that crosses the segment. After the edge is */
9728 /* flipped, one of its endpoints is the fan vertex, and the */
9729 /* destination of fixuptri is the fan vertex. */
9730 oprevself(fixuptri);
9732 /* Check for two intersecting segments. */
9733 tspivot(fixuptri, fixupedge);
9734 if (fixupedge.sh == dummysh) {
9735 flip(&fixuptri); /* May create an inverted triangle on the left. */
9737 /* We've collided with a segment between endpoint1 and endpoint2. */
9739 /* Insert a point at the intersection. */
9740 segmentintersection(&fixuptri, &fixupedge, endpoint2);
9746 /* Insert a shell edge to make the segment permanent. */
9747 insertshelle(&fixuptri, newmark);
9748 /* If there was a collision with an interceding vertex, install another */
9749 /* segment connecting that vertex with endpoint2. */
9751 /* Insert the remainder of the segment. */
9752 if (!scoutsegment(&fixuptri, endpoint2, newmark)) {
9753 constrainededge(&fixuptri, endpoint2, newmark);
9758 /*****************************************************************************/
9760 /* insertsegment() Insert a PSLG segment into a triangulation. */
9762 /*****************************************************************************/
9764 void insertsegment(endpoint1, endpoint2, newmark)
9769 struct triedge searchtri1, searchtri2;
9770 triangle encodedtri;
9772 triangle ptr; /* Temporary variable used by sym(). */
9775 printf(" Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
9776 endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
9779 /* Find a triangle whose origin is the segment's first endpoint. */
9780 checkpoint = (point) NULL;
9781 encodedtri = point2tri(endpoint1);
9782 if (encodedtri != (triangle) NULL) {
9783 decode(encodedtri, searchtri1);
9784 org(searchtri1, checkpoint);
9786 if (checkpoint != endpoint1) {
9787 /* Find a boundary triangle to search from. */
9788 searchtri1.tri = dummytri;
9789 searchtri1.orient = 0;
9790 symself(searchtri1);
9791 /* Search for the segment's first endpoint by point location. */
9792 if (locate(endpoint1, &searchtri1) != ONVERTEX) {
9794 "Internal error in insertsegment(): Unable to locate PSLG point\n");
9795 printf(" (%.12g, %.12g) in triangulation.\n",
9796 endpoint1[0], endpoint1[1]);
9800 /* Remember this triangle to improve subsequent point location. */
9801 triedgecopy(searchtri1, recenttri);
9802 /* Scout the beginnings of a path from the first endpoint */
9803 /* toward the second. */
9804 if (scoutsegment(&searchtri1, endpoint2, newmark)) {
9805 /* The segment was easily inserted. */
9808 /* The first endpoint may have changed if a collision with an intervening */
9809 /* vertex on the segment occurred. */
9810 org(searchtri1, endpoint1);
9812 /* Find a triangle whose origin is the segment's second endpoint. */
9813 checkpoint = (point) NULL;
9814 encodedtri = point2tri(endpoint2);
9815 if (encodedtri != (triangle) NULL) {
9816 decode(encodedtri, searchtri2);
9817 org(searchtri2, checkpoint);
9819 if (checkpoint != endpoint2) {
9820 /* Find a boundary triangle to search from. */
9821 searchtri2.tri = dummytri;
9822 searchtri2.orient = 0;
9823 symself(searchtri2);
9824 /* Search for the segment's second endpoint by point location. */
9825 if (locate(endpoint2, &searchtri2) != ONVERTEX) {
9827 "Internal error in insertsegment(): Unable to locate PSLG point\n");
9828 printf(" (%.12g, %.12g) in triangulation.\n",
9829 endpoint2[0], endpoint2[1]);
9833 /* Remember this triangle to improve subsequent point location. */
9834 triedgecopy(searchtri2, recenttri);
9835 /* Scout the beginnings of a path from the second endpoint */
9836 /* toward the first. */
9837 if (scoutsegment(&searchtri2, endpoint1, newmark)) {
9838 /* The segment was easily inserted. */
9841 /* The second endpoint may have changed if a collision with an intervening */
9842 /* vertex on the segment occurred. */
9843 org(searchtri2, endpoint2);
9848 /* Insert vertices to force the segment into the triangulation. */
9849 conformingedge(endpoint1, endpoint2, newmark);
9851 #endif /* not CDT_ONLY */
9852 #endif /* not REDUCED */
9853 /* Insert the segment directly into the triangulation. */
9854 constrainededge(&searchtri1, endpoint2, newmark);
9858 #endif /* not CDT_ONLY */
9859 #endif /* not REDUCED */
9862 /*****************************************************************************/
9864 /* markhull() Cover the convex hull of a triangulation with shell edges. */
9866 /*****************************************************************************/
9870 struct triedge hulltri;
9871 struct triedge nexttri;
9872 struct triedge starttri;
9873 triangle ptr; /* Temporary variable used by sym() and oprev(). */
9875 /* Find a triangle handle on the hull. */
9876 hulltri.tri = dummytri;
9879 /* Remember where we started so we know when to stop. */
9880 triedgecopy(hulltri, starttri);
9881 /* Go once counterclockwise around the convex hull. */
9883 /* Create a shell edge if there isn't already one here. */
9884 insertshelle(&hulltri, 1);
9885 /* To find the next hull edge, go clockwise around the next vertex. */
9887 oprev(hulltri, nexttri);
9888 while (nexttri.tri != dummytri) {
9889 triedgecopy(nexttri, hulltri);
9890 oprev(hulltri, nexttri);
9892 } while (!triedgeequal(hulltri, starttri));
9895 /*****************************************************************************/
9897 /* formskeleton() Create the shell edges of a triangulation, including */
9898 /* PSLG edges and edges on the convex hull. */
9900 /* The PSLG edges are read from a .poly file. The return value is the */
9901 /* number of segments in the file. */
9903 /*****************************************************************************/
9907 int formskeleton(segmentlist, segmentmarkerlist, numberofsegments)
9909 int *segmentmarkerlist;
9910 int numberofsegments;
9912 #else /* not TRILIBRARY */
9914 int formskeleton(polyfile, polyfilename)
9918 #endif /* not TRILIBRARY */
9922 char polyfilename[6];
9924 #else /* not TRILIBRARY */
9925 char inputline[INPUTLINESIZE];
9927 #endif /* not TRILIBRARY */
9928 point endpoint1, endpoint2;
9937 printf("Inserting segments into Delaunay triangulation.\n");
9940 strcpy(polyfilename, "input");
9941 segments = numberofsegments;
9942 segmentmarkers = segmentmarkerlist != (int *) NULL;
9944 #else /* not TRILIBRARY */
9945 /* Read the segments from a .poly file. */
9946 /* Read number of segments and number of boundary markers. */
9947 stringptr = readline(inputline, polyfile, polyfilename);
9948 segments = (int) strtol (stringptr, &stringptr, 0);
9949 stringptr = findfield(stringptr);
9950 if (*stringptr == '\0') {
9953 segmentmarkers = (int) strtol (stringptr, &stringptr, 0);
9955 #endif /* not TRILIBRARY */
9956 /* If segments are to be inserted, compute a mapping */
9957 /* from points to triangles. */
9960 printf(" Inserting PSLG segments.\n");
9966 /* Read and insert the segments. */
9967 for (i = 1; i <= segments; i++) {
9969 end1 = segmentlist[index++];
9970 end2 = segmentlist[index++];
9971 if (segmentmarkers) {
9972 boundmarker = segmentmarkerlist[i - 1];
9974 #else /* not TRILIBRARY */
9975 stringptr = readline(inputline, polyfile, inpolyfilename);
9976 stringptr = findfield(stringptr);
9977 if (*stringptr == '\0') {
9978 printf("Error: Segment %d has no endpoints in %s.\n", i,
9982 end1 = (int) strtol (stringptr, &stringptr, 0);
9984 stringptr = findfield(stringptr);
9985 if (*stringptr == '\0') {
9986 printf("Error: Segment %d is missing its second endpoint in %s.\n", i,
9990 end2 = (int) strtol (stringptr, &stringptr, 0);
9992 if (segmentmarkers) {
9993 stringptr = findfield(stringptr);
9994 if (*stringptr == '\0') {
9997 boundmarker = (int) strtol (stringptr, &stringptr, 0);
10000 #endif /* not TRILIBRARY */
10001 if ((end1 < firstnumber) || (end1 >= firstnumber + inpoints)) {
10003 printf("Warning: Invalid first endpoint of segment %d in %s.\n", i,
10006 } else if ((end2 < firstnumber) || (end2 >= firstnumber + inpoints)) {
10008 printf("Warning: Invalid second endpoint of segment %d in %s.\n", i,
10012 endpoint1 = getpoint(end1);
10013 endpoint2 = getpoint(end2);
10014 if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
10016 printf("Warning: Endpoints of segment %d are coincident in %s.\n",
10020 insertsegment(endpoint1, endpoint2, boundmarker);
10027 if (convex || !poly) {
10028 /* Enclose the convex hull with shell edges. */
10030 printf(" Enclosing convex hull with segments.\n");
10039 /********* Segment (shell edge) insertion ends here *********/
10041 /********* Carving out holes and concavities begins here *********/
10045 /*****************************************************************************/
10047 /* infecthull() Virally infect all of the triangles of the convex hull */
10048 /* that are not protected by shell edges. Where there are */
10049 /* shell edges, set boundary markers as appropriate. */
10051 /*****************************************************************************/
10055 struct triedge hulltri;
10056 struct triedge nexttri;
10057 struct triedge starttri;
10058 struct edge hulledge;
10059 triangle **deadtri;
10061 triangle ptr; /* Temporary variable used by sym(). */
10062 shelle sptr; /* Temporary variable used by tspivot(). */
10065 printf(" Marking concavities (external triangles) for elimination.\n");
10067 /* Find a triangle handle on the hull. */
10068 hulltri.tri = dummytri;
10069 hulltri.orient = 0;
10071 /* Remember where we started so we know when to stop. */
10072 triedgecopy(hulltri, starttri);
10073 /* Go once counterclockwise around the convex hull. */
10075 /* Ignore triangles that are already infected. */
10076 if (!infected(hulltri)) {
10077 /* Is the triangle protected by a shell edge? */
10078 tspivot(hulltri, hulledge);
10079 if (hulledge.sh == dummysh) {
10080 /* The triangle is not protected; infect it. */
10082 deadtri = (triangle **) poolalloc(&viri);
10083 *deadtri = hulltri.tri;
10085 /* The triangle is protected; set boundary markers if appropriate. */
10086 if (mark(hulledge) == 0) {
10087 setmark(hulledge, 1);
10088 org(hulltri, horg);
10089 dest(hulltri, hdest);
10090 if (pointmark(horg) == 0) {
10091 setpointmark(horg, 1);
10093 if (pointmark(hdest) == 0) {
10094 setpointmark(hdest, 1);
10099 /* To find the next hull edge, go clockwise around the next vertex. */
10100 lnextself(hulltri);
10101 oprev(hulltri, nexttri);
10102 while (nexttri.tri != dummytri) {
10103 triedgecopy(nexttri, hulltri);
10104 oprev(hulltri, nexttri);
10106 } while (!triedgeequal(hulltri, starttri));
10109 /*****************************************************************************/
10111 /* plague() Spread the virus from all infected triangles to any neighbors */
10112 /* not protected by shell edges. Delete all infected triangles. */
10114 /* This is the procedure that actually creates holes and concavities. */
10116 /* This procedure operates in two phases. The first phase identifies all */
10117 /* the triangles that will die, and marks them as infected. They are */
10118 /* marked to ensure that each triangle is added to the virus pool only */
10119 /* once, so the procedure will terminate. */
10121 /* The second phase actually eliminates the infected triangles. It also */
10122 /* eliminates orphaned points. */
10124 /*****************************************************************************/
10128 struct triedge testtri;
10129 struct triedge neighbor;
10130 triangle **virusloop;
10131 triangle **deadtri;
10132 struct edge neighborshelle;
10135 point deadorg, deaddest, deadapex;
10137 triangle ptr; /* Temporary variable used by sym() and onext(). */
10138 shelle sptr; /* Temporary variable used by tspivot(). */
10141 printf(" Marking neighbors of marked triangles.\n");
10143 /* Loop through all the infected triangles, spreading the virus to */
10144 /* their neighbors, then to their neighbors' neighbors. */
10145 traversalinit(&viri);
10146 virusloop = (triangle **) traverse(&viri);
10147 while (virusloop != (triangle **) NULL) {
10148 testtri.tri = *virusloop;
10149 /* A triangle is marked as infected by messing with one of its shell */
10150 /* edges, setting it to an illegal value. Hence, we have to */
10151 /* temporarily uninfect this triangle so that we can examine its */
10152 /* adjacent shell edges. */
10155 /* Assign the triangle an orientation for convenience in */
10156 /* checking its points. */
10157 testtri.orient = 0;
10158 org(testtri, deadorg);
10159 dest(testtri, deaddest);
10160 apex(testtri, deadapex);
10161 printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
10162 deadorg[0], deadorg[1], deaddest[0], deaddest[1],
10163 deadapex[0], deadapex[1]);
10165 /* Check each of the triangle's three neighbors. */
10166 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
10167 /* Find the neighbor. */
10168 sym(testtri, neighbor);
10169 /* Check for a shell between the triangle and its neighbor. */
10170 tspivot(testtri, neighborshelle);
10171 /* Check if the neighbor is nonexistent or already infected. */
10172 if ((neighbor.tri == dummytri) || infected(neighbor)) {
10173 if (neighborshelle.sh != dummysh) {
10174 /* There is a shell edge separating the triangle from its */
10175 /* neighbor, but both triangles are dying, so the shell */
10176 /* edge dies too. */
10177 shelledealloc(neighborshelle.sh);
10178 if (neighbor.tri != dummytri) {
10179 /* Make sure the shell edge doesn't get deallocated again */
10180 /* later when the infected neighbor is visited. */
10181 uninfect(neighbor);
10182 tsdissolve(neighbor);
10186 } else { /* The neighbor exists and is not infected. */
10187 if (neighborshelle.sh == dummysh) {
10188 /* There is no shell edge protecting the neighbor, so */
10189 /* the neighbor becomes infected. */
10191 org(neighbor, deadorg);
10192 dest(neighbor, deaddest);
10193 apex(neighbor, deadapex);
10195 " Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
10196 deadorg[0], deadorg[1], deaddest[0], deaddest[1],
10197 deadapex[0], deadapex[1]);
10200 /* Ensure that the neighbor's neighbors will be infected. */
10201 deadtri = (triangle **) poolalloc(&viri);
10202 *deadtri = neighbor.tri;
10203 } else { /* The neighbor is protected by a shell edge. */
10204 /* Remove this triangle from the shell edge. */
10205 stdissolve(neighborshelle);
10206 /* The shell edge becomes a boundary. Set markers accordingly. */
10207 if (mark(neighborshelle) == 0) {
10208 setmark(neighborshelle, 1);
10210 org(neighbor, norg);
10211 dest(neighbor, ndest);
10212 if (pointmark(norg) == 0) {
10213 setpointmark(norg, 1);
10215 if (pointmark(ndest) == 0) {
10216 setpointmark(ndest, 1);
10221 /* Remark the triangle as infected, so it doesn't get added to the */
10222 /* virus pool again. */
10224 virusloop = (triangle **) traverse(&viri);
10228 printf(" Deleting marked triangles.\n");
10230 traversalinit(&viri);
10231 virusloop = (triangle **) traverse(&viri);
10232 while (virusloop != (triangle **) NULL) {
10233 testtri.tri = *virusloop;
10235 /* Check each of the three corners of the triangle for elimination. */
10236 /* This is done by walking around each point, checking if it is */
10237 /* still connected to at least one live triangle. */
10238 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
10239 org(testtri, testpoint);
10240 /* Check if the point has already been tested. */
10241 if (testpoint != (point) NULL) {
10243 /* Mark the corner of the triangle as having been tested. */
10244 setorg(testtri, NULL);
10245 /* Walk counterclockwise about the point. */
10246 onext(testtri, neighbor);
10247 /* Stop upon reaching a boundary or the starting triangle. */
10248 while ((neighbor.tri != dummytri)
10249 && (!triedgeequal(neighbor, testtri))) {
10250 if (infected(neighbor)) {
10251 /* Mark the corner of this triangle as having been tested. */
10252 setorg(neighbor, NULL);
10254 /* A live triangle. The point survives. */
10257 /* Walk counterclockwise about the point. */
10258 onextself(neighbor);
10260 /* If we reached a boundary, we must walk clockwise as well. */
10261 if (neighbor.tri == dummytri) {
10262 /* Walk clockwise about the point. */
10263 oprev(testtri, neighbor);
10264 /* Stop upon reaching a boundary. */
10265 while (neighbor.tri != dummytri) {
10266 if (infected(neighbor)) {
10267 /* Mark the corner of this triangle as having been tested. */
10268 setorg(neighbor, NULL);
10270 /* A live triangle. The point survives. */
10273 /* Walk clockwise about the point. */
10274 oprevself(neighbor);
10279 printf(" Deleting point (%.12g, %.12g)\n",
10280 testpoint[0], testpoint[1]);
10282 pointdealloc(testpoint);
10287 /* Record changes in the number of boundary edges, and disconnect */
10288 /* dead triangles from their neighbors. */
10289 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
10290 sym(testtri, neighbor);
10291 if (neighbor.tri == dummytri) {
10292 /* There is no neighboring triangle on this edge, so this edge */
10293 /* is a boundary edge. This triangle is being deleted, so this */
10294 /* boundary edge is deleted. */
10297 /* Disconnect the triangle from its neighbor. */
10298 dissolve(neighbor);
10299 /* There is a neighboring triangle on this edge, so this edge */
10300 /* becomes a boundary edge when this triangle is deleted. */
10304 /* Return the dead triangle to the pool of triangles. */
10305 triangledealloc(testtri.tri);
10306 virusloop = (triangle **) traverse(&viri);
10308 /* Empty the virus pool. */
10309 poolrestart(&viri);
10312 /*****************************************************************************/
10314 /* regionplague() Spread regional attributes and/or area constraints */
10315 /* (from a .poly file) throughout the mesh. */
10317 /* This procedure operates in two phases. The first phase spreads an */
10318 /* attribute and/or an area constraint through a (segment-bounded) region. */
10319 /* The triangles are marked to ensure that each triangle is added to the */
10320 /* virus pool only once, so the procedure will terminate. */
10322 /* The second phase uninfects all infected triangles, returning them to */
10325 /*****************************************************************************/
10327 void regionplague(attribute, area)
10331 struct triedge testtri;
10332 struct triedge neighbor;
10333 triangle **virusloop;
10334 triangle **regiontri;
10335 struct edge neighborshelle;
10336 point regionorg, regiondest, regionapex;
10337 triangle ptr; /* Temporary variable used by sym() and onext(). */
10338 shelle sptr; /* Temporary variable used by tspivot(). */
10341 printf(" Marking neighbors of marked triangles.\n");
10343 /* Loop through all the infected triangles, spreading the attribute */
10344 /* and/or area constraint to their neighbors, then to their neighbors' */
10346 traversalinit(&viri);
10347 virusloop = (triangle **) traverse(&viri);
10348 while (virusloop != (triangle **) NULL) {
10349 testtri.tri = *virusloop;
10350 /* A triangle is marked as infected by messing with one of its shell */
10351 /* edges, setting it to an illegal value. Hence, we have to */
10352 /* temporarily uninfect this triangle so that we can examine its */
10353 /* adjacent shell edges. */
10355 if (regionattrib) {
10356 /* Set an attribute. */
10357 setelemattribute(testtri, eextras, attribute);
10360 /* Set an area constraint. */
10361 setareabound(testtri, area);
10364 /* Assign the triangle an orientation for convenience in */
10365 /* checking its points. */
10366 testtri.orient = 0;
10367 org(testtri, regionorg);
10368 dest(testtri, regiondest);
10369 apex(testtri, regionapex);
10370 printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
10371 regionorg[0], regionorg[1], regiondest[0], regiondest[1],
10372 regionapex[0], regionapex[1]);
10374 /* Check each of the triangle's three neighbors. */
10375 for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
10376 /* Find the neighbor. */
10377 sym(testtri, neighbor);
10378 /* Check for a shell between the triangle and its neighbor. */
10379 tspivot(testtri, neighborshelle);
10380 /* Make sure the neighbor exists, is not already infected, and */
10381 /* isn't protected by a shell edge. */
10382 if ((neighbor.tri != dummytri) && !infected(neighbor)
10383 && (neighborshelle.sh == dummysh)) {
10385 org(neighbor, regionorg);
10386 dest(neighbor, regiondest);
10387 apex(neighbor, regionapex);
10388 printf(" Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
10389 regionorg[0], regionorg[1], regiondest[0], regiondest[1],
10390 regionapex[0], regionapex[1]);
10392 /* Infect the neighbor. */
10394 /* Ensure that the neighbor's neighbors will be infected. */
10395 regiontri = (triangle **) poolalloc(&viri);
10396 *regiontri = neighbor.tri;
10399 /* Remark the triangle as infected, so it doesn't get added to the */
10400 /* virus pool again. */
10402 virusloop = (triangle **) traverse(&viri);
10405 /* Uninfect all triangles. */
10407 printf(" Unmarking marked triangles.\n");
10409 traversalinit(&viri);
10410 virusloop = (triangle **) traverse(&viri);
10411 while (virusloop != (triangle **) NULL) {
10412 testtri.tri = *virusloop;
10414 virusloop = (triangle **) traverse(&viri);
10416 /* Empty the virus pool. */
10417 poolrestart(&viri);
10420 /*****************************************************************************/
10422 /* carveholes() Find the holes and infect them. Find the area */
10423 /* constraints and infect them. Infect the convex hull. */
10424 /* Spread the infection and kill triangles. Spread the */
10425 /* area constraints. */
10427 /* This routine mainly calls other routines to carry out all these */
10430 /*****************************************************************************/
10432 void carveholes(holelist, holes, regionlist, regions)
10438 struct triedge searchtri;
10439 struct triedge triangleloop;
10440 struct triedge *regiontris;
10441 triangle **holetri;
10442 triangle **regiontri;
10443 point searchorg, searchdest;
10444 enum locateresult intersect;
10446 triangle ptr; /* Temporary variable used by sym(). */
10448 if (!(quiet || (noholes && convex))) {
10449 printf("Removing unwanted triangles.\n");
10450 if (verbose && (holes > 0)) {
10451 printf(" Marking holes for elimination.\n");
10456 /* Allocate storage for the triangles in which region points fall. */
10457 regiontris = (struct triedge *) malloc(regions * sizeof(struct triedge));
10458 if (regiontris == (struct triedge *) NULL) {
10459 printf("Error: Out of memory.\n");
10464 if (((holes > 0) && !noholes) || !convex || (regions > 0)) {
10465 /* Initialize a pool of viri to be used for holes, concavities, */
10466 /* regional attributes, and/or regional area constraints. */
10467 poolinit(&viri, sizeof(triangle *), VIRUSPERBLOCK, POINTER, 0);
10471 /* Mark as infected any unprotected triangles on the boundary. */
10472 /* This is one way by which concavities are created. */
10476 if ((holes > 0) && !noholes) {
10477 /* Infect each triangle in which a hole lies. */
10478 for (i = 0; i < 2 * holes; i += 2) {
10479 /* Ignore holes that aren't within the bounds of the mesh. */
10480 if ((holelist[i] >= xmin) && (holelist[i] <= xmax)
10481 && (holelist[i + 1] >= ymin) && (holelist[i + 1] <= ymax)) {
10482 /* Start searching from some triangle on the outer boundary. */
10483 searchtri.tri = dummytri;
10484 searchtri.orient = 0;
10485 symself(searchtri);
10486 /* Ensure that the hole is to the left of this boundary edge; */
10487 /* otherwise, locate() will falsely report that the hole */
10488 /* falls within the starting triangle. */
10489 org(searchtri, searchorg);
10490 dest(searchtri, searchdest);
10491 if (counterclockwise(searchorg, searchdest, &holelist[i]) > 0.0) {
10492 /* Find a triangle that contains the hole. */
10493 intersect = locate(&holelist[i], &searchtri);
10494 if ((intersect != OUTSIDE) && (!infected(searchtri))) {
10495 /* Infect the triangle. This is done by marking the triangle */
10496 /* as infect and including the triangle in the virus pool. */
10498 holetri = (triangle **) poolalloc(&viri);
10499 *holetri = searchtri.tri;
10506 /* Now, we have to find all the regions BEFORE we carve the holes, because */
10507 /* locate() won't work when the triangulation is no longer convex. */
10508 /* (Incidentally, this is the reason why regional attributes and area */
10509 /* constraints can't be used when refining a preexisting mesh, which */
10510 /* might not be convex; they can only be used with a freshly */
10511 /* triangulated PSLG.) */
10513 /* Find the starting triangle for each region. */
10514 for (i = 0; i < regions; i++) {
10515 regiontris[i].tri = dummytri;
10516 /* Ignore region points that aren't within the bounds of the mesh. */
10517 if ((regionlist[4 * i] >= xmin) && (regionlist[4 * i] <= xmax) &&
10518 (regionlist[4 * i + 1] >= ymin) && (regionlist[4 * i + 1] <= ymax)) {
10519 /* Start searching from some triangle on the outer boundary. */
10520 searchtri.tri = dummytri;
10521 searchtri.orient = 0;
10522 symself(searchtri);
10523 /* Ensure that the region point is to the left of this boundary */
10524 /* edge; otherwise, locate() will falsely report that the */
10525 /* region point falls within the starting triangle. */
10526 org(searchtri, searchorg);
10527 dest(searchtri, searchdest);
10528 if (counterclockwise(searchorg, searchdest, ®ionlist[4 * i]) >
10530 /* Find a triangle that contains the region point. */
10531 intersect = locate(®ionlist[4 * i], &searchtri);
10532 if ((intersect != OUTSIDE) && (!infected(searchtri))) {
10533 /* Record the triangle for processing after the */
10534 /* holes have been carved. */
10535 triedgecopy(searchtri, regiontris[i]);
10542 if (viri.items > 0) {
10543 /* Carve the holes and concavities. */
10546 /* The virus pool should be empty now. */
10550 if (regionattrib) {
10552 printf("Spreading regional attributes and area constraints.\n");
10554 printf("Spreading regional attributes.\n");
10557 printf("Spreading regional area constraints.\n");
10560 if (regionattrib && !refine) {
10561 /* Assign every triangle a regional attribute of zero. */
10562 traversalinit(&triangles);
10563 triangleloop.orient = 0;
10564 triangleloop.tri = triangletraverse();
10565 while (triangleloop.tri != (triangle *) NULL) {
10566 setelemattribute(triangleloop, eextras, 0.0);
10567 triangleloop.tri = triangletraverse();
10570 for (i = 0; i < regions; i++) {
10571 if (regiontris[i].tri != dummytri) {
10572 /* Make sure the triangle under consideration still exists. */
10573 /* It may have been eaten by the virus. */
10574 if (regiontris[i].tri[3] != (triangle) NULL) {
10575 /* Put one triangle in the virus pool. */
10576 infect(regiontris[i]);
10577 regiontri = (triangle **) poolalloc(&viri);
10578 *regiontri = regiontris[i].tri;
10579 /* Apply one region's attribute and/or area constraint. */
10580 regionplague(regionlist[4 * i + 2], regionlist[4 * i + 3]);
10581 /* The virus pool should be empty now. */
10585 if (regionattrib && !refine) {
10586 /* Note the fact that each triangle has an additional attribute. */
10591 /* Free up memory. */
10592 if (((holes > 0) && !noholes) || !convex || (regions > 0)) {
10602 /********* Carving out holes and concavities ends here *********/
10604 /********* Mesh quality maintenance begins here *********/
10608 /*****************************************************************************/
10610 /* tallyencs() Traverse the entire list of shell edges, check each edge */
10611 /* to see if it is encroached. If so, add it to the list. */
10613 /*****************************************************************************/
10619 struct edge edgeloop;
10622 traversalinit(&shelles);
10623 edgeloop.shorient = 0;
10624 edgeloop.sh = shelletraverse();
10625 while (edgeloop.sh != (shelle *) NULL) {
10626 /* If the segment is encroached, add it to the list. */
10627 dummy = checkedge4encroach(&edgeloop);
10628 edgeloop.sh = shelletraverse();
10632 #endif /* not CDT_ONLY */
10634 /*****************************************************************************/
10636 /* precisionerror() Print an error message for precision problems. */
10638 /*****************************************************************************/
10642 void precisionerror()
10644 printf("Try increasing the area criterion and/or reducing the minimum\n");
10645 printf(" allowable angle so that tiny triangles are not created.\n");
10647 printf("Alternatively, try recompiling me with double precision\n");
10648 printf(" arithmetic (by removing \"#define SINGLE\" from the\n");
10649 printf(" source file or \"-DSINGLE\" from the makefile).\n");
10650 #endif /* SINGLE */
10653 #endif /* not CDT_ONLY */
10655 /*****************************************************************************/
10657 /* repairencs() Find and repair all the encroached segments. */
10659 /* Encroached segments are repaired by splitting them by inserting a point */
10660 /* at or near their centers. */
10662 /* `flaws' is a flag that specifies whether one should take note of new */
10663 /* encroached segments and bad triangles that result from inserting points */
10664 /* to repair existing encroached segments. */
10666 /* When a segment is split, the two resulting subsegments are always */
10667 /* tested to see if they are encroached upon, regardless of the value */
10670 /*****************************************************************************/
10674 void repairencs(flaws)
10677 struct triedge enctri;
10678 struct triedge testtri;
10679 struct edge *encloop;
10680 struct edge testsh;
10683 enum insertsiteresult success;
10684 REAL segmentlength, nearestpoweroftwo;
10686 int acuteorg, acutedest;
10689 triangle ptr; /* Temporary variable used by stpivot(). */
10690 shelle sptr; /* Temporary variable used by snext(). */
10692 while ((badsegments.items > 0) && (steinerleft != 0)) {
10693 traversalinit(&badsegments);
10694 encloop = badsegmenttraverse();
10695 while ((encloop != (struct edge *) NULL) && (steinerleft != 0)) {
10696 /* To decide where to split a segment, we need to know if the */
10697 /* segment shares an endpoint with an adjacent segment. */
10698 /* The concern is that, if we simply split every encroached */
10699 /* segment in its center, two adjacent segments with a small */
10700 /* angle between them might lead to an infinite loop; each */
10701 /* point added to split one segment will encroach upon the */
10702 /* other segment, which must then be split with a point that */
10703 /* will encroach upon the first segment, and so on forever. */
10704 /* To avoid this, imagine a set of concentric circles, whose */
10705 /* radii are powers of two, about each segment endpoint. */
10706 /* These concentric circles determine where the segment is */
10707 /* split. (If both endpoints are shared with adjacent */
10708 /* segments, split the segment in the middle, and apply the */
10709 /* concentric shells for later splittings.) */
10711 /* Is the origin shared with another segment? */
10712 stpivot(*encloop, enctri);
10713 lnext(enctri, testtri);
10714 tspivot(testtri, testsh);
10715 acuteorg = testsh.sh != dummysh;
10716 /* Is the destination shared with another segment? */
10717 lnextself(testtri);
10718 tspivot(testtri, testsh);
10719 acutedest = testsh.sh != dummysh;
10720 /* Now, check the other side of the segment, if there's a triangle */
10722 sym(enctri, testtri);
10723 if (testtri.tri != dummytri) {
10724 /* Is the destination shared with another segment? */
10725 lnextself(testtri);
10726 tspivot(testtri, testsh);
10727 acutedest = acutedest || (testsh.sh != dummysh);
10728 /* Is the origin shared with another segment? */
10729 lnextself(testtri);
10730 tspivot(testtri, testsh);
10731 acuteorg = acuteorg || (testsh.sh != dummysh);
10734 sorg(*encloop, eorg);
10735 sdest(*encloop, edest);
10736 /* Use the concentric circles if exactly one endpoint is shared */
10737 /* with another adjacent segment. */
10738 if (acuteorg ^ acutedest) {
10739 segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0])
10740 + (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
10741 /* Find the power of two nearest the segment's length. */
10742 nearestpoweroftwo = 1.0;
10743 while (segmentlength > SQUAREROOTTWO * nearestpoweroftwo) {
10744 nearestpoweroftwo *= 2.0;
10746 while (segmentlength < (0.5 * SQUAREROOTTWO) * nearestpoweroftwo) {
10747 nearestpoweroftwo *= 0.5;
10749 /* Where do we split the segment? */
10750 split = 0.5 * nearestpoweroftwo / segmentlength;
10752 split = 1.0 - split;
10755 /* If we're not worried about adjacent segments, split */
10756 /* this segment in the middle. */
10760 /* Create the new point. */
10761 newpoint = (point) poolalloc(&points);
10762 /* Interpolate its coordinate and attributes. */
10763 for (i = 0; i < 2 + nextras; i++) {
10764 newpoint[i] = (1.0 - split) * eorg[i] + split * edest[i];
10766 setpointmark(newpoint, mark(*encloop));
10769 " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
10770 eorg[0], eorg[1], edest[0], edest[1], newpoint[0], newpoint[1]);
10772 /* Check whether the new point lies on an endpoint. */
10773 if (((newpoint[0] == eorg[0]) && (newpoint[1] == eorg[1]))
10774 || ((newpoint[0] == edest[0]) && (newpoint[1] == edest[1]))) {
10775 printf("Error: Ran out of precision at (%.12g, %.12g).\n",
10776 newpoint[0], newpoint[1]);
10777 printf("I attempted to split a segment to a smaller size than can\n");
10778 printf(" be accommodated by the finite precision of floating point\n"
10780 printf(" arithmetic.\n");
10784 /* Insert the splitting point. This should always succeed. */
10785 success = insertsite(newpoint, &enctri, encloop, flaws, flaws);
10786 if ((success != SUCCESSFULPOINT) && (success != ENCROACHINGPOINT)) {
10787 printf("Internal error in repairencs():\n");
10788 printf(" Failure to split a segment.\n");
10791 if (steinerleft > 0) {
10794 /* Check the two new subsegments to see if they're encroached. */
10795 dummy = checkedge4encroach(encloop);
10796 snextself(*encloop);
10797 dummy = checkedge4encroach(encloop);
10799 badsegmentdealloc(encloop);
10800 encloop = badsegmenttraverse();
10805 #endif /* not CDT_ONLY */
10807 /*****************************************************************************/
10809 /* tallyfaces() Test every triangle in the mesh for quality measures. */
10811 /*****************************************************************************/
10817 struct triedge triangleloop;
10820 printf(" Making a list of bad triangles.\n");
10822 traversalinit(&triangles);
10823 triangleloop.orient = 0;
10824 triangleloop.tri = triangletraverse();
10825 while (triangleloop.tri != (triangle *) NULL) {
10826 /* If the triangle is bad, enqueue it. */
10827 testtriangle(&triangleloop);
10828 triangleloop.tri = triangletraverse();
10832 #endif /* not CDT_ONLY */
10834 /*****************************************************************************/
10836 /* findcircumcenter() Find the circumcenter of a triangle. */
10838 /* The result is returned both in terms of x-y coordinates and xi-eta */
10839 /* coordinates. The xi-eta coordinate system is defined in terms of the */
10840 /* triangle: the origin of the triangle is the origin of the coordinate */
10841 /* system; the destination of the triangle is one unit along the xi axis; */
10842 /* and the apex of the triangle is one unit along the eta axis. */
10844 /* The return value indicates which edge of the triangle is shortest. */
10846 /*****************************************************************************/
10848 enum circumcenterresult findcircumcenter(torg, tdest, tapex, circumcenter,
10853 point circumcenter;
10857 REAL xdo, ydo, xao, yao, xad, yad;
10858 REAL dodist, aodist, addist;
10862 circumcentercount++;
10864 /* Compute the circumcenter of the triangle. */
10865 xdo = tdest[0] - torg[0];
10866 ydo = tdest[1] - torg[1];
10867 xao = tapex[0] - torg[0];
10868 yao = tapex[1] - torg[1];
10869 dodist = xdo * xdo + ydo * ydo;
10870 aodist = xao * xao + yao * yao;
10872 denominator = (REAL)(0.5 / (xdo * yao - xao * ydo));
10874 /* Use the counterclockwise() routine to ensure a positive (and */
10875 /* reasonably accurate) result, avoiding any possibility of */
10876 /* division by zero. */
10877 denominator = (REAL)(0.5 / counterclockwise(tdest, tapex, torg));
10878 /* Don't count the above as an orientation test. */
10879 counterclockcount--;
10881 circumcenter[0] = torg[0] - (ydo * aodist - yao * dodist) * denominator;
10882 circumcenter[1] = torg[1] + (xdo * aodist - xao * dodist) * denominator;
10884 /* To interpolate point attributes for the new point inserted at */
10885 /* the circumcenter, define a coordinate system with a xi-axis, */
10886 /* directed from the triangle's origin to its destination, and */
10887 /* an eta-axis, directed from its origin to its apex. */
10888 /* Calculate the xi and eta coordinates of the circumcenter. */
10889 dx = circumcenter[0] - torg[0];
10890 dy = circumcenter[1] - torg[1];
10891 *xi = (REAL)((dx * yao - xao * dy) * (2.0 * denominator));
10892 *eta = (REAL)((xdo * dy - dx * ydo) * (2.0 * denominator));
10894 xad = tapex[0] - tdest[0];
10895 yad = tapex[1] - tdest[1];
10896 addist = xad * xad + yad * yad;
10897 if ((addist < dodist) && (addist < aodist)) {
10898 return OPPOSITEORG;
10899 } else if (dodist < aodist) {
10900 return OPPOSITEAPEX;
10902 return OPPOSITEDEST;
10906 /*****************************************************************************/
10908 /* splittriangle() Inserts a point at the circumcenter of a triangle. */
10909 /* Deletes the newly inserted point if it encroaches upon */
10912 /*****************************************************************************/
10916 void splittriangle(badtri)
10917 struct badface *badtri;
10919 point borg, bdest, bapex;
10922 enum insertsiteresult success;
10923 enum circumcenterresult shortedge;
10927 org(badtri->badfacetri, borg);
10928 dest(badtri->badfacetri, bdest);
10929 apex(badtri->badfacetri, bapex);
10930 /* Make sure that this triangle is still the same triangle it was */
10931 /* when it was tested and determined to be of bad quality. */
10932 /* Subsequent transformations may have made it a different triangle. */
10933 if ((borg == badtri->faceorg) && (bdest == badtri->facedest) &&
10934 (bapex == badtri->faceapex)) {
10936 printf(" Splitting this triangle at its circumcenter:\n");
10937 printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
10938 borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
10941 /* Create a new point at the triangle's circumcenter. */
10942 newpoint = (point) poolalloc(&points);
10943 shortedge = findcircumcenter(borg, bdest, bapex, newpoint, &xi, &eta);
10944 /* Check whether the new point lies on a triangle vertex. */
10945 if (((newpoint[0] == borg[0]) && (newpoint[1] == borg[1]))
10946 || ((newpoint[0] == bdest[0]) && (newpoint[1] == bdest[1]))
10947 || ((newpoint[0] == bapex[0]) && (newpoint[1] == bapex[1]))) {
10949 printf("Warning: New point (%.12g, %.12g) falls on existing vertex.\n"
10950 , newpoint[0], newpoint[1]);
10953 pointdealloc(newpoint);
10955 for (i = 2; i < 2 + nextras; i++) {
10956 /* Interpolate the point attributes at the circumcenter. */
10957 newpoint[i] = borg[i] + xi * (bdest[i] - borg[i])
10958 + eta * (bapex[i] - borg[i]);
10960 /* The new point must be in the interior, and have a marker of zero. */
10961 setpointmark(newpoint, 0);
10962 /* Ensure that the handle `badtri->badfacetri' represents the shortest */
10963 /* edge of the triangle. This ensures that the circumcenter must */
10964 /* fall to the left of this edge, so point location will work. */
10965 if (shortedge == OPPOSITEORG) {
10966 lnextself(badtri->badfacetri);
10967 } else if (shortedge == OPPOSITEDEST) {
10968 lprevself(badtri->badfacetri);
10970 /* Insert the circumcenter, searching from the edge of the triangle, */
10971 /* and maintain the Delaunay property of the triangulation. */
10972 success = insertsite(newpoint, &(badtri->badfacetri),
10973 (struct edge *) NULL, 1, 1);
10974 if (success == SUCCESSFULPOINT) {
10975 if (steinerleft > 0) {
10978 } else if (success == ENCROACHINGPOINT) {
10979 /* If the newly inserted point encroaches upon a segment, delete it. */
10980 deletesite(&(badtri->badfacetri));
10981 } else if (success == VIOLATINGPOINT) {
10982 /* Failed to insert the new point, but some segment was */
10983 /* marked as being encroached. */
10984 pointdealloc(newpoint);
10985 } else { /* success == DUPLICATEPOINT */
10986 /* Failed to insert the new point because a vertex is already there. */
10989 "Warning: New point (%.12g, %.12g) falls on existing vertex.\n"
10990 , newpoint[0], newpoint[1]);
10993 pointdealloc(newpoint);
10998 printf(" The new point is at the circumcenter of triangle\n");
10999 printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
11000 borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
11002 printf("This probably means that I am trying to refine triangles\n");
11003 printf(" to a smaller size than can be accommodated by the finite\n");
11004 printf(" precision of floating point arithmetic. (You can be\n");
11005 printf(" sure of this if I fail to terminate.)\n");
11009 /* Return the bad triangle to the pool. */
11010 pooldealloc(&badtriangles, (VOID *) badtri);
11013 #endif /* not CDT_ONLY */
11015 /*****************************************************************************/
11017 /* enforcequality() Remove all the encroached edges and bad triangles */
11018 /* from the triangulation. */
11020 /*****************************************************************************/
11024 void enforcequality()
11029 printf("Adding Steiner points to enforce quality.\n");
11031 /* Initialize the pool of encroached segments. */
11032 poolinit(&badsegments, sizeof(struct edge), BADSEGMENTPERBLOCK, POINTER, 0);
11034 printf(" Looking for encroached segments.\n");
11036 /* Test all segments to see if they're encroached. */
11038 if (verbose && (badsegments.items > 0)) {
11039 printf(" Splitting encroached segments.\n");
11041 /* Note that steinerleft == -1 if an unlimited number */
11042 /* of Steiner points is allowed. */
11043 while ((badsegments.items > 0) && (steinerleft != 0)) {
11044 /* Fix the segments without noting newly encroached segments or */
11045 /* bad triangles. The reason we don't want to note newly */
11046 /* encroached segments is because some encroached segments are */
11047 /* likely to be noted multiple times, and would then be blindly */
11048 /* split multiple times. I should fix that some time. */
11050 /* Now, find all the segments that became encroached while adding */
11051 /* points to split encroached segments. */
11054 /* At this point, if we haven't run out of Steiner points, the */
11055 /* triangulation should be (conforming) Delaunay. */
11057 /* Next, we worry about enforcing triangle quality. */
11058 if ((minangle > 0.0) || vararea || fixedarea) {
11059 /* Initialize the pool of bad triangles. */
11060 poolinit(&badtriangles, sizeof(struct badface), BADTRIPERBLOCK, POINTER,
11062 /* Initialize the queues of bad triangles. */
11063 for (i = 0; i < 64; i++) {
11064 queuefront[i] = (struct badface *) NULL;
11065 queuetail[i] = &queuefront[i];
11067 /* Test all triangles to see if they're bad. */
11070 printf(" Splitting bad triangles.\n");
11072 while ((badtriangles.items > 0) && (steinerleft != 0)) {
11073 /* Fix one bad triangle by inserting a point at its circumcenter. */
11074 splittriangle(dequeuebadtri());
11075 /* Fix any encroached segments that may have resulted. Record */
11076 /* any new bad triangles or encroached segments that result. */
11077 if (badsegments.items > 0) {
11082 /* At this point, if we haven't run out of Steiner points, the */
11083 /* triangulation should be (conforming) Delaunay and have no */
11084 /* low-quality triangles. */
11086 /* Might we have run out of Steiner points too soon? */
11087 if (!quiet && (badsegments.items > 0) && (steinerleft == 0)) {
11088 printf("\nWarning: I ran out of Steiner points, but the mesh has\n");
11089 if (badsegments.items == 1) {
11090 printf(" an encroached segment, and therefore might not be truly\n");
11092 printf(" %ld encroached segments, and therefore might not be truly\n",
11093 badsegments.items);
11095 printf(" Delaunay. If the Delaunay property is important to you,\n");
11096 printf(" try increasing the number of Steiner points (controlled by\n");
11097 printf(" the -S switch) slightly and try again.\n\n");
11101 #endif /* not CDT_ONLY */
11105 /********* Mesh quality maintenance ends here *********/
11107 /*****************************************************************************/
11109 /* highorder() Create extra nodes for quadratic subparametric elements. */
11111 /*****************************************************************************/
11115 struct triedge triangleloop, trisym;
11116 struct edge checkmark;
11120 triangle ptr; /* Temporary variable used by sym(). */
11121 shelle sptr; /* Temporary variable used by tspivot(). */
11124 printf("Adding vertices for second-order triangles.\n");
11126 /* The following line ensures that dead items in the pool of nodes */
11127 /* cannot be allocated for the extra nodes associated with high */
11128 /* order elements. This ensures that the primary nodes (at the */
11129 /* corners of elements) will occur earlier in the output files, and */
11130 /* have lower indices, than the extra nodes. */
11131 points.deaditemstack = (VOID *) NULL;
11133 traversalinit(&triangles);
11134 triangleloop.tri = triangletraverse();
11135 /* To loop over the set of edges, loop over all triangles, and look at */
11136 /* the three edges of each triangle. If there isn't another triangle */
11137 /* adjacent to the edge, operate on the edge. If there is another */
11138 /* adjacent triangle, operate on the edge only if the current triangle */
11139 /* has a smaller pointer than its neighbor. This way, each edge is */
11140 /* considered only once. */
11141 while (triangleloop.tri != (triangle *) NULL) {
11142 for (triangleloop.orient = 0; triangleloop.orient < 3;
11143 triangleloop.orient++) {
11144 sym(triangleloop, trisym);
11145 if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) {
11146 org(triangleloop, torg);
11147 dest(triangleloop, tdest);
11148 /* Create a new node in the middle of the edge. Interpolate */
11149 /* its attributes. */
11150 newpoint = (point) poolalloc(&points);
11151 for (i = 0; i < 2 + nextras; i++) {
11152 newpoint[i] = (REAL)(0.5 * (torg[i] + tdest[i]));
11154 /* Set the new node's marker to zero or one, depending on */
11155 /* whether it lies on a boundary. */
11156 setpointmark(newpoint, trisym.tri == dummytri);
11158 tspivot(triangleloop, checkmark);
11159 /* If this edge is a segment, transfer the marker to the new node. */
11160 if (checkmark.sh != dummysh) {
11161 setpointmark(newpoint, mark(checkmark));
11165 printf(" Creating (%.12g, %.12g).\n", newpoint[0], newpoint[1]);
11167 /* Record the new node in the (one or two) adjacent elements. */
11168 triangleloop.tri[highorderindex + triangleloop.orient] =
11169 (triangle) newpoint;
11170 if (trisym.tri != dummytri) {
11171 trisym.tri[highorderindex + trisym.orient] = (triangle) newpoint;
11175 triangleloop.tri = triangletraverse();
11179 /********* File I/O routines begin here *********/
11183 /*****************************************************************************/
11185 /* readline() Read a nonempty line from a file. */
11187 /* A line is considered "nonempty" if it contains something that looks like */
11190 /*****************************************************************************/
11194 char *readline(string, infile, infilename)
11201 /* Search for something that looks like a number. */
11203 result = fgets(string, INPUTLINESIZE, infile);
11204 if (result == (char *) NULL) {
11205 printf(" Error: Unexpected end of file in %s.\n", infilename);
11208 /* Skip anything that doesn't look like a number, a comment, */
11209 /* or the end of a line. */
11210 while ((*result != '\0') && (*result != '#')
11211 && (*result != '.') && (*result != '+') && (*result != '-')
11212 && ((*result < '0') || (*result > '9'))) {
11215 /* If it's a comment or end of line, read another line and try again. */
11216 } while ((*result == '#') || (*result == '\0'));
11220 #endif /* not TRILIBRARY */
11222 /*****************************************************************************/
11224 /* findfield() Find the next field of a string. */
11226 /* Jumps past the current field by searching for whitespace, then jumps */
11227 /* past the whitespace to find the next field. */
11229 /*****************************************************************************/
11233 char *findfield(string)
11239 /* Skip the current field. Stop upon reaching whitespace. */
11240 while ((*result != '\0') && (*result != '#')
11241 && (*result != ' ') && (*result != '\t')) {
11244 /* Now skip the whitespace and anything else that doesn't look like a */
11245 /* number, a comment, or the end of a line. */
11246 while ((*result != '\0') && (*result != '#')
11247 && (*result != '.') && (*result != '+') && (*result != '-')
11248 && ((*result < '0') || (*result > '9'))) {
11251 /* Check for a comment (prefixed with `#'). */
11252 if (*result == '#') {
11258 #endif /* not TRILIBRARY */
11260 /*****************************************************************************/
11262 /* readnodes() Read the points from a file, which may be a .node or .poly */
11265 /*****************************************************************************/
11269 void readnodes(nodefilename, polyfilename, polyfile)
11270 char *nodefilename;
11271 char *polyfilename;
11276 char inputline[INPUTLINESIZE];
11286 /* Read the points from a .poly file. */
11288 printf("Opening %s.\n", polyfilename);
11290 *polyfile = fopen(polyfilename, "r");
11291 if (*polyfile == (FILE *) NULL) {
11292 printf(" Error: Cannot access file %s.\n", polyfilename);
11295 /* Read number of points, number of dimensions, number of point */
11296 /* attributes, and number of boundary markers. */
11297 stringptr = readline(inputline, *polyfile, polyfilename);
11298 inpoints = (int) strtol (stringptr, &stringptr, 0);
11299 stringptr = findfield(stringptr);
11300 if (*stringptr == '\0') {
11303 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
11305 stringptr = findfield(stringptr);
11306 if (*stringptr == '\0') {
11309 nextras = (int) strtol (stringptr, &stringptr, 0);
11311 stringptr = findfield(stringptr);
11312 if (*stringptr == '\0') {
11315 nodemarkers = (int) strtol (stringptr, &stringptr, 0);
11317 if (inpoints > 0) {
11318 infile = *polyfile;
11319 infilename = polyfilename;
11322 /* If the .poly file claims there are zero points, that means that */
11323 /* the points should be read from a separate .node file. */
11325 infilename = innodefilename;
11329 infilename = innodefilename;
11330 *polyfile = (FILE *) NULL;
11333 if (readnodefile) {
11334 /* Read the points from a .node file. */
11336 printf("Opening %s.\n", innodefilename);
11338 infile = fopen(innodefilename, "r");
11339 if (infile == (FILE *) NULL) {
11340 printf(" Error: Cannot access file %s.\n", innodefilename);
11343 /* Read number of points, number of dimensions, number of point */
11344 /* attributes, and number of boundary markers. */
11345 stringptr = readline(inputline, infile, innodefilename);
11346 inpoints = (int) strtol (stringptr, &stringptr, 0);
11347 stringptr = findfield(stringptr);
11348 if (*stringptr == '\0') {
11351 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
11353 stringptr = findfield(stringptr);
11354 if (*stringptr == '\0') {
11357 nextras = (int) strtol (stringptr, &stringptr, 0);
11359 stringptr = findfield(stringptr);
11360 if (*stringptr == '\0') {
11363 nodemarkers = (int) strtol (stringptr, &stringptr, 0);
11367 if (inpoints < 3) {
11368 printf("Error: Input must have at least three input points.\n");
11371 if (mesh_dim != 2) {
11372 printf("Error: Triangle only works with two-dimensional meshes.\n");
11376 initializepointpool();
11378 /* Read the points. */
11379 for (i = 0; i < inpoints; i++) {
11380 pointloop = (point) poolalloc(&points);
11381 stringptr = readline(inputline, infile, infilename);
11383 firstnode = (int) strtol (stringptr, &stringptr, 0);
11384 if ((firstnode == 0) || (firstnode == 1)) {
11385 firstnumber = firstnode;
11388 stringptr = findfield(stringptr);
11389 if (*stringptr == '\0') {
11390 printf("Error: Point %d has no x coordinate.\n", firstnumber + i);
11393 x = (REAL) strtod(stringptr, &stringptr);
11394 stringptr = findfield(stringptr);
11395 if (*stringptr == '\0') {
11396 printf("Error: Point %d has no y coordinate.\n", firstnumber + i);
11399 y = (REAL) strtod(stringptr, &stringptr);
11402 /* Read the point attributes. */
11403 for (j = 2; j < 2 + nextras; j++) {
11404 stringptr = findfield(stringptr);
11405 if (*stringptr == '\0') {
11406 pointloop[j] = 0.0;
11408 pointloop[j] = (REAL) strtod(stringptr, &stringptr);
11412 /* Read a point marker. */
11413 stringptr = findfield(stringptr);
11414 if (*stringptr == '\0') {
11415 setpointmark(pointloop, 0);
11417 currentmarker = (int) strtol (stringptr, &stringptr, 0);
11418 setpointmark(pointloop, currentmarker);
11421 /* If no markers are specified in the file, they default to zero. */
11422 setpointmark(pointloop, 0);
11424 /* Determine the smallest and largest x and y coordinates. */
11429 xmin = (x < xmin) ? x : xmin;
11430 xmax = (x > xmax) ? x : xmax;
11431 ymin = (y < ymin) ? y : ymin;
11432 ymax = (y > ymax) ? y : ymax;
11435 if (readnodefile) {
11439 /* Nonexistent x value used as a flag to mark circle events in sweepline */
11440 /* Delaunay algorithm. */
11441 xminextreme = 10 * xmin - 9 * xmax;
11444 #endif /* not TRILIBRARY */
11446 /*****************************************************************************/
11448 /* transfernodes() Read the points from memory. */
11450 /*****************************************************************************/
11454 void transfernodes(pointlist, pointattriblist, pointmarkerlist, numberofpoints,
11455 numberofpointattribs)
11457 REAL *pointattriblist;
11458 int *pointmarkerlist;
11459 int numberofpoints;
11460 int numberofpointattribs;
11468 inpoints = numberofpoints;
11470 nextras = numberofpointattribs;
11472 if (inpoints < 3) {
11473 printf("Error: Input must have at least three input points.\n");
11477 initializepointpool();
11479 /* Read the points. */
11482 for (i = 0; i < inpoints; i++) {
11483 pointloop = (point) poolalloc(&points);
11484 /* Read the point coordinates. */
11485 x = pointloop[0] = pointlist[coordindex++];
11486 y = pointloop[1] = pointlist[coordindex++];
11487 /* Read the point attributes. */
11488 for (j = 0; j < numberofpointattribs; j++) {
11489 pointloop[2 + j] = pointattriblist[attribindex++];
11491 if (pointmarkerlist != (int *) NULL) {
11492 /* Read a point marker. */
11493 setpointmark(pointloop, pointmarkerlist[i]);
11495 /* If no markers are specified, they default to zero. */
11496 setpointmark(pointloop, 0);
11500 /* Determine the smallest and largest x and y coordinates. */
11505 xmin = (x < xmin) ? x : xmin;
11506 xmax = (x > xmax) ? x : xmax;
11507 ymin = (y < ymin) ? y : ymin;
11508 ymax = (y > ymax) ? y : ymax;
11512 /* Nonexistent x value used as a flag to mark circle events in sweepline */
11513 /* Delaunay algorithm. */
11514 xminextreme = 10 * xmin - 9 * xmax;
11517 #endif /* TRILIBRARY */
11519 /*****************************************************************************/
11521 /* readholes() Read the holes, and possibly regional attributes and area */
11522 /* constraints, from a .poly file. */
11524 /*****************************************************************************/
11528 void readholes(polyfile, polyfilename, hlist, holes, rlist, regions)
11530 char *polyfilename;
11538 char inputline[INPUTLINESIZE];
11543 /* Read the holes. */
11544 stringptr = readline(inputline, polyfile, polyfilename);
11545 *holes = (int) strtol (stringptr, &stringptr, 0);
11547 holelist = (REAL *) malloc(2 * *holes * sizeof(REAL));
11549 if (holelist == (REAL *) NULL) {
11550 printf("Error: Out of memory.\n");
11553 for (i = 0; i < 2 * *holes; i += 2) {
11554 stringptr = readline(inputline, polyfile, polyfilename);
11555 stringptr = findfield(stringptr);
11556 if (*stringptr == '\0') {
11557 printf("Error: Hole %d has no x coordinate.\n",
11558 firstnumber + (i >> 1));
11561 holelist[i] = (REAL) strtod(stringptr, &stringptr);
11563 stringptr = findfield(stringptr);
11564 if (*stringptr == '\0') {
11565 printf("Error: Hole %d has no y coordinate.\n",
11566 firstnumber + (i >> 1));
11569 holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
11573 *hlist = (REAL *) NULL;
11577 if ((regionattrib || vararea) && !refine) {
11578 /* Read the area constraints. */
11579 stringptr = readline(inputline, polyfile, polyfilename);
11580 *regions = (int) strtol (stringptr, &stringptr, 0);
11581 if (*regions > 0) {
11582 regionlist = (REAL *) malloc(4 * *regions * sizeof(REAL));
11583 *rlist = regionlist;
11584 if (regionlist == (REAL *) NULL) {
11585 printf("Error: Out of memory.\n");
11589 for (i = 0; i < *regions; i++) {
11590 stringptr = readline(inputline, polyfile, polyfilename);
11591 stringptr = findfield(stringptr);
11592 if (*stringptr == '\0') {
11593 printf("Error: Region %d has no x coordinate.\n",
11597 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
11599 stringptr = findfield(stringptr);
11600 if (*stringptr == '\0') {
11601 printf("Error: Region %d has no y coordinate.\n",
11605 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
11607 stringptr = findfield(stringptr);
11608 if (*stringptr == '\0') {
11610 "Error: Region %d has no region attribute or area constraint.\n",
11614 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
11616 stringptr = findfield(stringptr);
11617 if (*stringptr == '\0') {
11618 regionlist[index] = regionlist[index - 1];
11620 regionlist[index] = (REAL) strtod(stringptr, &stringptr);
11626 /* Set `*regions' to zero to avoid an accidental free() later. */
11628 *rlist = (REAL *) NULL;
11630 #endif /* not CDT_ONLY */
11635 #endif /* not TRILIBRARY */
11637 /*****************************************************************************/
11639 /* finishfile() Write the command line to the output file so the user */
11640 /* can remember how the file was generated. Close the file. */
11642 /*****************************************************************************/
11646 void finishfile(outfile, argc, argv)
11653 fprintf(outfile, "# Generated by");
11654 for (i = 0; i < argc; i++) {
11655 fprintf(outfile, " ");
11656 fputs(argv[i], outfile);
11658 fprintf(outfile, "\n");
11662 #endif /* not TRILIBRARY */
11664 /*****************************************************************************/
11666 /* writenodes() Number the points and write them to a .node file. */
11668 /* To save memory, the point numbers are written over the shell markers */
11669 /* after the points are written to a file. */
11671 /*****************************************************************************/
11675 void writenodes(pointlist, pointattriblist, pointmarkerlist)
11677 REAL **pointattriblist;
11678 int **pointmarkerlist;
11680 #else /* not TRILIBRARY */
11682 void writenodes(nodefilename, argc, argv)
11683 char *nodefilename;
11687 #endif /* not TRILIBRARY */
11696 #else /* not TRILIBRARY */
11698 #endif /* not TRILIBRARY */
11705 printf("Writing points.\n");
11707 /* Allocate memory for output points if necessary. */
11708 if (*pointlist == (REAL *) NULL) {
11709 *pointlist = (REAL *) malloc(points.items * 2 * sizeof(REAL));
11710 if (*pointlist == (REAL *) NULL) {
11711 printf("Error: Out of memory.\n");
11715 /* Allocate memory for output point attributes if necessary. */
11716 if ((nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
11717 *pointattriblist = (REAL *) malloc(points.items * nextras * sizeof(REAL));
11718 if (*pointattriblist == (REAL *) NULL) {
11719 printf("Error: Out of memory.\n");
11723 /* Allocate memory for output point markers if necessary. */
11724 if (!nobound && (*pointmarkerlist == (int *) NULL)) {
11725 *pointmarkerlist = (int *) malloc(points.items * sizeof(int));
11726 if (*pointmarkerlist == (int *) NULL) {
11727 printf("Error: Out of memory.\n");
11731 plist = *pointlist;
11732 palist = *pointattriblist;
11733 pmlist = *pointmarkerlist;
11736 #else /* not TRILIBRARY */
11738 printf("Writing %s.\n", nodefilename);
11740 outfile = fopen(nodefilename, "w");
11741 if (outfile == (FILE *) NULL) {
11742 printf(" Error: Cannot create file %s.\n", nodefilename);
11745 /* Number of points, number of dimensions, number of point attributes, */
11746 /* and number of boundary markers (zero or one). */
11747 fprintf(outfile, "%ld %d %d %d\n", points.items, mesh_dim, nextras,
11749 #endif /* not TRILIBRARY */
11751 traversalinit(&points);
11752 pointloop = pointtraverse();
11753 pointnumber = firstnumber;
11754 while (pointloop != (point) NULL) {
11756 /* X and y coordinates. */
11757 plist[coordindex++] = pointloop[0];
11758 plist[coordindex++] = pointloop[1];
11759 /* Point attributes. */
11760 for (i = 0; i < nextras; i++) {
11761 palist[attribindex++] = pointloop[2 + i];
11764 /* Copy the boundary marker. */
11765 pmlist[pointnumber - firstnumber] = pointmark(pointloop);
11767 #else /* not TRILIBRARY */
11768 /* Point number, x and y coordinates. */
11769 fprintf(outfile, "%4d %.17g %.17g", pointnumber, pointloop[0],
11771 for (i = 0; i < nextras; i++) {
11772 /* Write an attribute. */
11773 fprintf(outfile, " %.17g", pointloop[i + 2]);
11776 fprintf(outfile, "\n");
11778 /* Write the boundary marker. */
11779 fprintf(outfile, " %d\n", pointmark(pointloop));
11781 #endif /* not TRILIBRARY */
11783 setpointmark(pointloop, pointnumber);
11784 pointloop = pointtraverse();
11789 finishfile(outfile, argc, argv);
11790 #endif /* not TRILIBRARY */
11793 /*****************************************************************************/
11795 /* numbernodes() Number the points. */
11797 /* Each point is assigned a marker equal to its number. */
11799 /* Used when writenodes() is not called because no .node file is written. */
11801 /*****************************************************************************/
11808 traversalinit(&points);
11809 pointloop = pointtraverse();
11810 pointnumber = firstnumber;
11811 while (pointloop != (point) NULL) {
11812 setpointmark(pointloop, pointnumber);
11813 pointloop = pointtraverse();
11818 /*****************************************************************************/
11820 /* writeelements() Write the triangles to an .ele file. */
11822 /*****************************************************************************/
11826 void writeelements(trianglelist, triangleattriblist)
11827 int **trianglelist;
11828 REAL **triangleattriblist;
11830 #else /* not TRILIBRARY */
11832 void writeelements(elefilename, argc, argv)
11837 #endif /* not TRILIBRARY */
11845 #else /* not TRILIBRARY */
11847 #endif /* not TRILIBRARY */
11848 struct triedge triangleloop;
11850 point mid1, mid2, mid3;
11856 printf("Writing triangles.\n");
11858 /* Allocate memory for output triangles if necessary. */
11859 if (*trianglelist == (int *) NULL) {
11860 *trianglelist = (int *) malloc(triangles.items *
11861 ((order + 1) * (order + 2) / 2) * sizeof(int));
11862 if (*trianglelist == (int *) NULL) {
11863 printf("Error: Out of memory.\n");
11867 /* Allocate memory for output triangle attributes if necessary. */
11868 if ((eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
11869 *triangleattriblist = (REAL *) malloc(triangles.items * eextras *
11871 if (*triangleattriblist == (REAL *) NULL) {
11872 printf("Error: Out of memory.\n");
11876 tlist = *trianglelist;
11877 talist = *triangleattriblist;
11880 #else /* not TRILIBRARY */
11882 printf("Writing %s.\n", elefilename);
11884 outfile = fopen(elefilename, "w");
11885 if (outfile == (FILE *) NULL) {
11886 printf(" Error: Cannot create file %s.\n", elefilename);
11889 /* Number of triangles, points per triangle, attributes per triangle. */
11890 fprintf(outfile, "%ld %d %d\n", triangles.items,
11891 (order + 1) * (order + 2) / 2, eextras);
11892 #endif /* not TRILIBRARY */
11894 traversalinit(&triangles);
11895 triangleloop.tri = triangletraverse();
11896 triangleloop.orient = 0;
11897 elementnumber = firstnumber;
11898 while (triangleloop.tri != (triangle *) NULL) {
11899 org(triangleloop, p1);
11900 dest(triangleloop, p2);
11901 apex(triangleloop, p3);
11904 tlist[pointindex++] = pointmark(p1);
11905 tlist[pointindex++] = pointmark(p2);
11906 tlist[pointindex++] = pointmark(p3);
11907 #else /* not TRILIBRARY */
11908 /* Triangle number, indices for three points. */
11909 fprintf(outfile, "%4d %4d %4d %4d", elementnumber,
11910 pointmark(p1), pointmark(p2), pointmark(p3));
11911 #endif /* not TRILIBRARY */
11913 mid1 = (point) triangleloop.tri[highorderindex + 1];
11914 mid2 = (point) triangleloop.tri[highorderindex + 2];
11915 mid3 = (point) triangleloop.tri[highorderindex];
11917 tlist[pointindex++] = pointmark(p1);
11918 tlist[pointindex++] = pointmark(p2);
11919 tlist[pointindex++] = pointmark(p3);
11920 tlist[pointindex++] = pointmark(mid1);
11921 tlist[pointindex++] = pointmark(mid2);
11922 tlist[pointindex++] = pointmark(mid3);
11923 #else /* not TRILIBRARY */
11924 /* Triangle number, indices for six points. */
11925 fprintf(outfile, "%4d %4d %4d %4d %4d %4d %4d", elementnumber,
11926 pointmark(p1), pointmark(p2), pointmark(p3), pointmark(mid1),
11927 pointmark(mid2), pointmark(mid3));
11928 #endif /* not TRILIBRARY */
11932 for (i = 0; i < eextras; i++) {
11933 talist[attribindex++] = elemattribute(triangleloop, i);
11935 #else /* not TRILIBRARY */
11936 for (i = 0; i < eextras; i++) {
11937 fprintf(outfile, " %.17g", elemattribute(triangleloop, i));
11939 fprintf(outfile, "\n");
11940 #endif /* not TRILIBRARY */
11942 triangleloop.tri = triangletraverse();
11947 finishfile(outfile, argc, argv);
11948 #endif /* not TRILIBRARY */
11951 /*****************************************************************************/
11953 /* writepoly() Write the segments and holes to a .poly file. */
11955 /*****************************************************************************/
11959 void writepoly(segmentlist, segmentmarkerlist)
11961 int **segmentmarkerlist;
11963 #else /* not TRILIBRARY */
11965 void writepoly(polyfilename, holelist, holes, regionlist, regions, argc, argv)
11966 char *polyfilename;
11974 #endif /* not TRILIBRARY */
11981 #else /* not TRILIBRARY */
11984 #endif /* not TRILIBRARY */
11985 struct edge shelleloop;
11986 point endpoint1, endpoint2;
11991 printf("Writing segments.\n");
11993 /* Allocate memory for output segments if necessary. */
11994 if (*segmentlist == (int *) NULL) {
11995 *segmentlist = (int *) malloc(shelles.items * 2 * sizeof(int));
11996 if (*segmentlist == (int *) NULL) {
11997 printf("Error: Out of memory.\n");
12001 /* Allocate memory for output segment markers if necessary. */
12002 if (!nobound && (*segmentmarkerlist == (int *) NULL)) {
12003 *segmentmarkerlist = (int *) malloc(shelles.items * sizeof(int));
12004 if (*segmentmarkerlist == (int *) NULL) {
12005 printf("Error: Out of memory.\n");
12009 slist = *segmentlist;
12010 smlist = *segmentmarkerlist;
12012 #else /* not TRILIBRARY */
12014 printf("Writing %s.\n", polyfilename);
12016 outfile = fopen(polyfilename, "w");
12017 if (outfile == (FILE *) NULL) {
12018 printf(" Error: Cannot create file %s.\n", polyfilename);
12021 /* The zero indicates that the points are in a separate .node file. */
12022 /* Followed by number of dimensions, number of point attributes, */
12023 /* and number of boundary markers (zero or one). */
12024 fprintf(outfile, "%d %d %d %d\n", 0, mesh_dim, nextras, 1 - nobound);
12025 /* Number of segments, number of boundary markers (zero or one). */
12026 fprintf(outfile, "%ld %d\n", shelles.items, 1 - nobound);
12027 #endif /* not TRILIBRARY */
12029 traversalinit(&shelles);
12030 shelleloop.sh = shelletraverse();
12031 shelleloop.shorient = 0;
12032 shellenumber = firstnumber;
12033 while (shelleloop.sh != (shelle *) NULL) {
12034 sorg(shelleloop, endpoint1);
12035 sdest(shelleloop, endpoint2);
12037 /* Copy indices of the segment's two endpoints. */
12038 slist[index++] = pointmark(endpoint1);
12039 slist[index++] = pointmark(endpoint2);
12041 /* Copy the boundary marker. */
12042 smlist[shellenumber - firstnumber] = mark(shelleloop);
12044 #else /* not TRILIBRARY */
12045 /* Segment number, indices of its two endpoints, and possibly a marker. */
12047 fprintf(outfile, "%4d %4d %4d\n", shellenumber,
12048 pointmark(endpoint1), pointmark(endpoint2));
12050 fprintf(outfile, "%4d %4d %4d %4d\n", shellenumber,
12051 pointmark(endpoint1), pointmark(endpoint2), mark(shelleloop));
12053 #endif /* not TRILIBRARY */
12055 shelleloop.sh = shelletraverse();
12061 fprintf(outfile, "%d\n", holes);
12063 for (i = 0; i < holes; i++) {
12064 /* Hole number, x and y coordinates. */
12065 fprintf(outfile, "%4d %.17g %.17g\n", firstnumber + i,
12066 holelist[2 * i], holelist[2 * i + 1]);
12070 fprintf(outfile, "%d\n", regions);
12071 for (i = 0; i < regions; i++) {
12072 /* Region number, x and y coordinates, attribute, maximum area. */
12073 fprintf(outfile, "%4d %.17g %.17g %.17g %.17g\n", firstnumber + i,
12074 regionlist[4 * i], regionlist[4 * i + 1],
12075 regionlist[4 * i + 2], regionlist[4 * i + 3]);
12078 #endif /* not CDT_ONLY */
12080 finishfile(outfile, argc, argv);
12081 #endif /* not TRILIBRARY */
12084 /*****************************************************************************/
12086 /* writeedges() Write the edges to a .edge file. */
12088 /*****************************************************************************/
12092 void writeedges(edgelist, edgemarkerlist)
12094 int **edgemarkerlist;
12096 #else /* not TRILIBRARY */
12098 void writeedges(edgefilename, argc, argv)
12099 char *edgefilename;
12103 #endif /* not TRILIBRARY */
12110 #else /* not TRILIBRARY */
12112 #endif /* not TRILIBRARY */
12113 struct triedge triangleloop, trisym;
12114 struct edge checkmark;
12117 triangle ptr; /* Temporary variable used by sym(). */
12118 shelle sptr; /* Temporary variable used by tspivot(). */
12122 printf("Writing edges.\n");
12124 /* Allocate memory for edges if necessary. */
12125 if (*edgelist == (int *) NULL) {
12126 *edgelist = (int *) malloc(edges * 2 * sizeof(int));
12127 if (*edgelist == (int *) NULL) {
12128 printf("Error: Out of memory.\n");
12132 /* Allocate memory for edge markers if necessary. */
12133 if (!nobound && (*edgemarkerlist == (int *) NULL)) {
12134 *edgemarkerlist = (int *) malloc(edges * sizeof(int));
12135 if (*edgemarkerlist == (int *) NULL) {
12136 printf("Error: Out of memory.\n");
12141 emlist = *edgemarkerlist;
12143 #else /* not TRILIBRARY */
12145 printf("Writing %s.\n", edgefilename);
12147 outfile = fopen(edgefilename, "w");
12148 if (outfile == (FILE *) NULL) {
12149 printf(" Error: Cannot create file %s.\n", edgefilename);
12152 /* Number of edges, number of boundary markers (zero or one). */
12153 fprintf(outfile, "%ld %d\n", edges, 1 - nobound);
12154 #endif /* not TRILIBRARY */
12156 traversalinit(&triangles);
12157 triangleloop.tri = triangletraverse();
12158 edgenumber = firstnumber;
12159 /* To loop over the set of edges, loop over all triangles, and look at */
12160 /* the three edges of each triangle. If there isn't another triangle */
12161 /* adjacent to the edge, operate on the edge. If there is another */
12162 /* adjacent triangle, operate on the edge only if the current triangle */
12163 /* has a smaller pointer than its neighbor. This way, each edge is */
12164 /* considered only once. */
12165 while (triangleloop.tri != (triangle *) NULL) {
12166 for (triangleloop.orient = 0; triangleloop.orient < 3;
12167 triangleloop.orient++) {
12168 sym(triangleloop, trisym);
12169 if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) {
12170 org(triangleloop, p1);
12171 dest(triangleloop, p2);
12173 elist[index++] = pointmark(p1);
12174 elist[index++] = pointmark(p2);
12175 #endif /* TRILIBRARY */
12178 /* Edge number, indices of two endpoints. */
12179 fprintf(outfile, "%4d %d %d\n", edgenumber,
12180 pointmark(p1), pointmark(p2));
12181 #endif /* not TRILIBRARY */
12183 /* Edge number, indices of two endpoints, and a boundary marker. */
12184 /* If there's no shell edge, the boundary marker is zero. */
12186 tspivot(triangleloop, checkmark);
12187 if (checkmark.sh == dummysh) {
12189 emlist[edgenumber - firstnumber] = 0;
12190 #else /* not TRILIBRARY */
12191 fprintf(outfile, "%4d %d %d %d\n", edgenumber,
12192 pointmark(p1), pointmark(p2), 0);
12193 #endif /* not TRILIBRARY */
12196 emlist[edgenumber - firstnumber] = mark(checkmark);
12197 #else /* not TRILIBRARY */
12198 fprintf(outfile, "%4d %d %d %d\n", edgenumber,
12199 pointmark(p1), pointmark(p2), mark(checkmark));
12200 #endif /* not TRILIBRARY */
12204 emlist[edgenumber - firstnumber] = trisym.tri == dummytri;
12205 #else /* not TRILIBRARY */
12206 fprintf(outfile, "%4d %d %d %d\n", edgenumber,
12207 pointmark(p1), pointmark(p2), trisym.tri == dummytri);
12208 #endif /* not TRILIBRARY */
12214 triangleloop.tri = triangletraverse();
12218 finishfile(outfile, argc, argv);
12219 #endif /* not TRILIBRARY */
12222 /*****************************************************************************/
12224 /* writevoronoi() Write the Voronoi diagram to a .v.node and .v.edge */
12227 /* The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
12228 /* Hence, the Voronoi vertices are listed by traversing the Delaunay */
12229 /* triangles, and the Voronoi edges are listed by traversing the Delaunay */
12232 /* WARNING: In order to assign numbers to the Voronoi vertices, this */
12233 /* procedure messes up the shell edges or the extra nodes of every */
12234 /* element. Hence, you should call this procedure last. */
12236 /*****************************************************************************/
12240 void writevoronoi(vpointlist, vpointattriblist, vpointmarkerlist, vedgelist,
12241 vedgemarkerlist, vnormlist)
12243 REAL **vpointattriblist;
12244 int **vpointmarkerlist;
12246 int **vedgemarkerlist;
12249 #else /* not TRILIBRARY */
12251 void writevoronoi(vnodefilename, vedgefilename, argc, argv)
12252 char *vnodefilename;
12253 char *vedgefilename;
12257 #endif /* not TRILIBRARY */
12267 #else /* not TRILIBRARY */
12269 #endif /* not TRILIBRARY */
12270 struct triedge triangleloop, trisym;
12271 point torg, tdest, tapex;
12272 REAL circumcenter[2];
12274 int vnodenumber, vedgenumber;
12277 triangle ptr; /* Temporary variable used by sym(). */
12281 printf("Writing Voronoi vertices.\n");
12283 /* Allocate memory for Voronoi vertices if necessary. */
12284 if (*vpointlist == (REAL *) NULL) {
12285 *vpointlist = (REAL *) malloc(triangles.items * 2 * sizeof(REAL));
12286 if (*vpointlist == (REAL *) NULL) {
12287 printf("Error: Out of memory.\n");
12291 /* Allocate memory for Voronoi vertex attributes if necessary. */
12292 if (*vpointattriblist == (REAL *) NULL) {
12293 *vpointattriblist = (REAL *) malloc(triangles.items * nextras *
12295 if (*vpointattriblist == (REAL *) NULL) {
12296 printf("Error: Out of memory.\n");
12300 *vpointmarkerlist = (int *) NULL;
12301 plist = *vpointlist;
12302 palist = *vpointattriblist;
12305 #else /* not TRILIBRARY */
12307 printf("Writing %s.\n", vnodefilename);
12309 outfile = fopen(vnodefilename, "w");
12310 if (outfile == (FILE *) NULL) {
12311 printf(" Error: Cannot create file %s.\n", vnodefilename);
12314 /* Number of triangles, two dimensions, number of point attributes, */
12315 /* zero markers. */
12316 fprintf(outfile, "%ld %d %d %d\n", triangles.items, 2, nextras, 0);
12317 #endif /* not TRILIBRARY */
12319 traversalinit(&triangles);
12320 triangleloop.tri = triangletraverse();
12321 triangleloop.orient = 0;
12322 vnodenumber = firstnumber;
12323 while (triangleloop.tri != (triangle *) NULL) {
12324 org(triangleloop, torg);
12325 dest(triangleloop, tdest);
12326 apex(triangleloop, tapex);
12327 findcircumcenter(torg, tdest, tapex, circumcenter, &xi, &eta);
12329 /* X and y coordinates. */
12330 plist[coordindex++] = circumcenter[0];
12331 plist[coordindex++] = circumcenter[1];
12332 for (i = 2; i < 2 + nextras; i++) {
12333 /* Interpolate the point attributes at the circumcenter. */
12334 palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
12335 + eta * (tapex[i] - torg[i]);
12337 #else /* not TRILIBRARY */
12338 /* Voronoi vertex number, x and y coordinates. */
12339 fprintf(outfile, "%4d %.17g %.17g", vnodenumber, circumcenter[0],
12341 for (i = 2; i < 2 + nextras; i++) {
12342 /* Interpolate the point attributes at the circumcenter. */
12343 fprintf(outfile, " %.17g", torg[i] + xi * (tdest[i] - torg[i])
12344 + eta * (tapex[i] - torg[i]));
12346 fprintf(outfile, "\n");
12347 #endif /* not TRILIBRARY */
12349 * (int *) (triangleloop.tri + 6) = vnodenumber;
12350 triangleloop.tri = triangletraverse();
12355 finishfile(outfile, argc, argv);
12356 #endif /* not TRILIBRARY */
12360 printf("Writing Voronoi edges.\n");
12362 /* Allocate memory for output Voronoi edges if necessary. */
12363 if (*vedgelist == (int *) NULL) {
12364 *vedgelist = (int *) malloc(edges * 2 * sizeof(int));
12365 if (*vedgelist == (int *) NULL) {
12366 printf("Error: Out of memory.\n");
12370 *vedgemarkerlist = (int *) NULL;
12371 /* Allocate memory for output Voronoi norms if necessary. */
12372 if (*vnormlist == (REAL *) NULL) {
12373 *vnormlist = (REAL *) malloc(edges * 2 * sizeof(REAL));
12374 if (*vnormlist == (REAL *) NULL) {
12375 printf("Error: Out of memory.\n");
12379 elist = *vedgelist;
12380 normlist = *vnormlist;
12382 #else /* not TRILIBRARY */
12384 printf("Writing %s.\n", vedgefilename);
12386 outfile = fopen(vedgefilename, "w");
12387 if (outfile == (FILE *) NULL) {
12388 printf(" Error: Cannot create file %s.\n", vedgefilename);
12391 /* Number of edges, zero boundary markers. */
12392 fprintf(outfile, "%ld %d\n", edges, 0);
12393 #endif /* not TRILIBRARY */
12395 traversalinit(&triangles);
12396 triangleloop.tri = triangletraverse();
12397 vedgenumber = firstnumber;
12398 /* To loop over the set of edges, loop over all triangles, and look at */
12399 /* the three edges of each triangle. If there isn't another triangle */
12400 /* adjacent to the edge, operate on the edge. If there is another */
12401 /* adjacent triangle, operate on the edge only if the current triangle */
12402 /* has a smaller pointer than its neighbor. This way, each edge is */
12403 /* considered only once. */
12404 while (triangleloop.tri != (triangle *) NULL) {
12405 for (triangleloop.orient = 0; triangleloop.orient < 3;
12406 triangleloop.orient++) {
12407 sym(triangleloop, trisym);
12408 if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) {
12409 /* Find the number of this triangle (and Voronoi vertex). */
12410 p1 = * (int *) (triangleloop.tri + 6);
12411 if (trisym.tri == dummytri) {
12412 org(triangleloop, torg);
12413 dest(triangleloop, tdest);
12415 /* Copy an infinite ray. Index of one endpoint, and -1. */
12416 elist[coordindex] = p1;
12417 normlist[coordindex++] = tdest[1] - torg[1];
12418 elist[coordindex] = -1;
12419 normlist[coordindex++] = torg[0] - tdest[0];
12420 #else /* not TRILIBRARY */
12421 /* Write an infinite ray. Edge number, index of one endpoint, -1, */
12422 /* and x and y coordinates of a vector representing the */
12423 /* direction of the ray. */
12424 fprintf(outfile, "%4d %d %d %.17g %.17g\n", vedgenumber,
12425 p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
12426 #endif /* not TRILIBRARY */
12428 /* Find the number of the adjacent triangle (and Voronoi vertex). */
12429 p2 = * (int *) (trisym.tri + 6);
12430 /* Finite edge. Write indices of two endpoints. */
12432 elist[coordindex] = p1;
12433 normlist[coordindex++] = 0.0;
12434 elist[coordindex] = p2;
12435 normlist[coordindex++] = 0.0;
12436 #else /* not TRILIBRARY */
12437 fprintf(outfile, "%4d %d %d\n", vedgenumber, p1, p2);
12438 #endif /* not TRILIBRARY */
12443 triangleloop.tri = triangletraverse();
12447 finishfile(outfile, argc, argv);
12448 #endif /* not TRILIBRARY */
12453 void writeneighbors(neighborlist)
12454 int **neighborlist;
12456 #else /* not TRILIBRARY */
12458 void writeneighbors(neighborfilename, argc, argv)
12459 char *neighborfilename;
12463 #endif /* not TRILIBRARY */
12469 #else /* not TRILIBRARY */
12471 #endif /* not TRILIBRARY */
12472 struct triedge triangleloop, trisym;
12474 int neighbor1, neighbor2, neighbor3;
12475 triangle ptr; /* Temporary variable used by sym(). */
12479 printf("Writing neighbors.\n");
12481 /* Allocate memory for neighbors if necessary. */
12482 if (*neighborlist == (int *) NULL) {
12483 *neighborlist = (int *) malloc(triangles.items * 3 * sizeof(int));
12484 if (*neighborlist == (int *) NULL) {
12485 printf("Error: Out of memory.\n");
12489 nlist = *neighborlist;
12491 #else /* not TRILIBRARY */
12493 printf("Writing %s.\n", neighborfilename);
12495 outfile = fopen(neighborfilename, "w");
12496 if (outfile == (FILE *) NULL) {
12497 printf(" Error: Cannot create file %s.\n", neighborfilename);
12500 /* Number of triangles, three edges per triangle. */
12501 fprintf(outfile, "%ld %d\n", triangles.items, 3);
12502 #endif /* not TRILIBRARY */
12504 traversalinit(&triangles);
12505 triangleloop.tri = triangletraverse();
12506 triangleloop.orient = 0;
12507 elementnumber = firstnumber;
12508 while (triangleloop.tri != (triangle *) NULL) {
12509 * (int *) (triangleloop.tri + 6) = elementnumber;
12510 triangleloop.tri = triangletraverse();
12513 * (int *) (dummytri + 6) = -1;
12515 traversalinit(&triangles);
12516 triangleloop.tri = triangletraverse();
12517 elementnumber = firstnumber;
12518 while (triangleloop.tri != (triangle *) NULL) {
12519 triangleloop.orient = 1;
12520 sym(triangleloop, trisym);
12521 neighbor1 = * (int *) (trisym.tri + 6);
12522 triangleloop.orient = 2;
12523 sym(triangleloop, trisym);
12524 neighbor2 = * (int *) (trisym.tri + 6);
12525 triangleloop.orient = 0;
12526 sym(triangleloop, trisym);
12527 neighbor3 = * (int *) (trisym.tri + 6);
12529 nlist[index++] = neighbor1;
12530 nlist[index++] = neighbor2;
12531 nlist[index++] = neighbor3;
12532 #else /* not TRILIBRARY */
12533 /* Triangle number, neighboring triangle numbers. */
12534 fprintf(outfile, "%4d %d %d %d\n", elementnumber,
12535 neighbor1, neighbor2, neighbor3);
12536 #endif /* not TRILIBRARY */
12538 triangleloop.tri = triangletraverse();
12543 finishfile(outfile, argc, argv);
12544 #endif /* TRILIBRARY */
12547 /*****************************************************************************/
12549 /* writeoff() Write the triangulation to an .off file. */
12551 /* OFF stands for the Object File Format, a format used by the Geometry */
12552 /* Center's Geomview package. */
12554 /*****************************************************************************/
12558 void writeoff(offfilename, argc, argv)
12564 struct triedge triangleloop;
12569 printf("Writing %s.\n", offfilename);
12571 outfile = fopen(offfilename, "w");
12572 if (outfile == (FILE *) NULL) {
12573 printf(" Error: Cannot create file %s.\n", offfilename);
12576 /* Number of points, triangles, and edges. */
12577 fprintf(outfile, "OFF\n%ld %ld %ld\n", points.items, triangles.items,
12580 /* Write the points. */
12581 traversalinit(&points);
12582 pointloop = pointtraverse();
12583 while (pointloop != (point) NULL) {
12584 /* The "0.0" is here because the OFF format uses 3D coordinates. */
12585 fprintf(outfile, " %.17g %.17g %.17g\n", pointloop[0],
12586 pointloop[1], 0.0);
12587 pointloop = pointtraverse();
12590 /* Write the triangles. */
12591 traversalinit(&triangles);
12592 triangleloop.tri = triangletraverse();
12593 triangleloop.orient = 0;
12594 while (triangleloop.tri != (triangle *) NULL) {
12595 org(triangleloop, p1);
12596 dest(triangleloop, p2);
12597 apex(triangleloop, p3);
12598 /* The "3" means a three-vertex polygon. */
12599 fprintf(outfile, " 3 %4d %4d %4d\n", pointmark(p1) - 1,
12600 pointmark(p2) - 1, pointmark(p3) - 1);
12601 triangleloop.tri = triangletraverse();
12603 finishfile(outfile, argc, argv);
12606 #endif /* not TRILIBRARY */
12610 /********* File I/O routines end here *********/
12612 /*****************************************************************************/
12614 /* quality_statistics() Print statistics about the quality of the mesh. */
12616 /*****************************************************************************/
12618 void quality_statistics()
12620 struct triedge triangleloop;
12622 REAL cossquaretable[8];
12623 REAL ratiotable[16];
12625 REAL edgelength[3];
12629 REAL shortest, longest;
12631 REAL smallestarea, biggestarea;
12632 REAL triminaltitude2;
12636 REAL smallestangle, biggestangle;
12637 REAL radconst, degconst;
12638 int angletable[18];
12639 int aspecttable[16];
12645 printf("Mesh quality statistics:\n\n");
12646 radconst = (REAL)(PI / 18.0);
12647 degconst = (REAL)(180.0 / PI);
12648 for (i = 0; i < 8; i++) {
12649 cossquaretable[i] = (REAL)(cos(radconst * (REAL) (i + 1)));
12650 cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
12652 for (i = 0; i < 18; i++) {
12656 ratiotable[0] = 1.5; ratiotable[1] = 2.0;
12657 ratiotable[2] = 2.5; ratiotable[3] = 3.0;
12658 ratiotable[4] = 4.0; ratiotable[5] = 6.0;
12659 ratiotable[6] = 10.0; ratiotable[7] = 15.0;
12660 ratiotable[8] = 25.0; ratiotable[9] = 50.0;
12661 ratiotable[10] = 100.0; ratiotable[11] = 300.0;
12662 ratiotable[12] = 1000.0; ratiotable[13] = 10000.0;
12663 ratiotable[14] = 100000.0; ratiotable[15] = 0.0;
12664 for (i = 0; i < 16; i++) {
12665 aspecttable[i] = 0;
12669 minaltitude = xmax - xmin + ymax - ymin;
12670 minaltitude = minaltitude * minaltitude;
12671 shortest = minaltitude;
12673 smallestarea = minaltitude;
12676 smallestangle = 0.0;
12677 biggestangle = 2.0;
12680 traversalinit(&triangles);
12681 triangleloop.tri = triangletraverse();
12682 triangleloop.orient = 0;
12683 while (triangleloop.tri != (triangle *) NULL) {
12684 org(triangleloop, p[0]);
12685 dest(triangleloop, p[1]);
12686 apex(triangleloop, p[2]);
12689 for (i = 0; i < 3; i++) {
12692 dx[i] = p[j][0] - p[k][0];
12693 dy[i] = p[j][1] - p[k][1];
12694 edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
12695 if (edgelength[i] > trilongest2) {
12696 trilongest2 = edgelength[i];
12698 if (edgelength[i] > longest) {
12699 longest = edgelength[i];
12701 if (edgelength[i] < shortest) {
12702 shortest = edgelength[i];
12706 triarea = counterclockwise(p[0], p[1], p[2]);
12707 if (triarea < smallestarea) {
12708 smallestarea = triarea;
12710 if (triarea > biggestarea) {
12711 biggestarea = triarea;
12713 triminaltitude2 = triarea * triarea / trilongest2;
12714 if (triminaltitude2 < minaltitude) {
12715 minaltitude = triminaltitude2;
12717 triaspect2 = trilongest2 / triminaltitude2;
12718 if (triaspect2 > worstaspect) {
12719 worstaspect = triaspect2;
12722 while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
12723 && (aspectindex < 15)) {
12726 aspecttable[aspectindex]++;
12728 for (i = 0; i < 3; i++) {
12731 dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
12732 cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
12734 for (ii = 7; ii >= 0; ii--) {
12735 if (cossquare > cossquaretable[ii]) {
12739 if (dotproduct <= 0.0) {
12740 angletable[tendegree]++;
12741 if (cossquare > smallestangle) {
12742 smallestangle = cossquare;
12744 if (acutebiggest && (cossquare < biggestangle)) {
12745 biggestangle = cossquare;
12748 angletable[17 - tendegree]++;
12749 if (acutebiggest || (cossquare > biggestangle)) {
12750 biggestangle = cossquare;
12755 triangleloop.tri = triangletraverse();
12758 shortest = (REAL)sqrt(shortest);
12759 longest = (REAL)sqrt(longest);
12760 minaltitude = (REAL)sqrt(minaltitude);
12761 worstaspect = (REAL)sqrt(worstaspect);
12762 smallestarea *= 2.0;
12763 biggestarea *= 2.0;
12764 if (smallestangle >= 1.0) {
12765 smallestangle = 0.0;
12767 smallestangle = (REAL)(degconst * acos(sqrt(smallestangle)));
12769 if (biggestangle >= 1.0) {
12770 biggestangle = 180.0;
12772 if (acutebiggest) {
12773 biggestangle = (REAL)(degconst * acos(sqrt(biggestangle)));
12775 biggestangle = (REAL)(180.0 - degconst * acos(sqrt(biggestangle)));
12779 printf(" Smallest area: %16.5g | Largest area: %16.5g\n",
12780 smallestarea, biggestarea);
12781 printf(" Shortest edge: %16.5g | Longest edge: %16.5g\n",
12782 shortest, longest);
12783 printf(" Shortest altitude: %12.5g | Largest aspect ratio: %8.5g\n\n",
12784 minaltitude, worstaspect);
12785 printf(" Aspect ratio histogram:\n");
12786 printf(" 1.1547 - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
12787 ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
12789 for (i = 1; i < 7; i++) {
12790 printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
12791 ratiotable[i - 1], ratiotable[i], aspecttable[i],
12792 ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
12794 printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n",
12795 ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
12798 " (Triangle aspect ratio is longest edge divided by shortest altitude)\n\n");
12799 printf(" Smallest angle: %15.5g | Largest angle: %15.5g\n\n",
12800 smallestangle, biggestangle);
12801 printf(" Angle histogram:\n");
12802 for (i = 0; i < 9; i++) {
12803 printf(" %3d - %3d degrees: %8d | %3d - %3d degrees: %8d\n",
12804 i * 10, i * 10 + 10, angletable[i],
12805 i * 10 + 90, i * 10 + 100, angletable[i + 9]);
12810 /*****************************************************************************/
12812 /* statistics() Print all sorts of cool facts. */
12814 /*****************************************************************************/
12818 printf("\nStatistics:\n\n");
12819 printf(" Input points: %d\n", inpoints);
12821 printf(" Input triangles: %d\n", inelements);
12824 printf(" Input segments: %d\n", insegments);
12826 printf(" Input holes: %d\n", holes);
12830 printf("\n Mesh points: %ld\n", points.items);
12831 printf(" Mesh triangles: %ld\n", triangles.items);
12832 printf(" Mesh edges: %ld\n", edges);
12833 if (poly || refine) {
12834 printf(" Mesh boundary edges: %ld\n", hullsize);
12835 printf(" Mesh segments: %ld\n\n", shelles.items);
12837 printf(" Mesh convex hull edges: %ld\n\n", hullsize);
12840 quality_statistics();
12841 printf("Memory allocation statistics:\n\n");
12842 printf(" Maximum number of points: %ld\n", points.maxitems);
12843 printf(" Maximum number of triangles: %ld\n", triangles.maxitems);
12844 if (shelles.maxitems > 0) {
12845 printf(" Maximum number of segments: %ld\n", shelles.maxitems);
12847 if (viri.maxitems > 0) {
12848 printf(" Maximum number of viri: %ld\n", viri.maxitems);
12850 if (badsegments.maxitems > 0) {
12851 printf(" Maximum number of encroached segments: %ld\n",
12852 badsegments.maxitems);
12854 if (badtriangles.maxitems > 0) {
12855 printf(" Maximum number of bad triangles: %ld\n",
12856 badtriangles.maxitems);
12858 if (splaynodes.maxitems > 0) {
12859 printf(" Maximum number of splay tree nodes: %ld\n",
12860 splaynodes.maxitems);
12862 printf(" Approximate heap memory use (bytes): %ld\n\n",
12863 points.maxitems * points.itembytes
12864 + triangles.maxitems * triangles.itembytes
12865 + shelles.maxitems * shelles.itembytes
12866 + viri.maxitems * viri.itembytes
12867 + badsegments.maxitems * badsegments.itembytes
12868 + badtriangles.maxitems * badtriangles.itembytes
12869 + splaynodes.maxitems * splaynodes.itembytes);
12871 printf("Algorithmic statistics:\n\n");
12872 printf(" Number of incircle tests: %ld\n", incirclecount);
12873 printf(" Number of orientation tests: %ld\n", counterclockcount);
12874 if (hyperbolacount > 0) {
12875 printf(" Number of right-of-hyperbola tests: %ld\n",
12878 if (circumcentercount > 0) {
12879 printf(" Number of circumcenter computations: %ld\n",
12880 circumcentercount);
12882 if (circletopcount > 0) {
12883 printf(" Number of circle top computations: %ld\n",
12890 /*****************************************************************************/
12892 /* main() or triangulate() Gosh, do everything. */
12894 /* The sequence is roughly as follows. Many of these steps can be skipped, */
12895 /* depending on the command line switches. */
12897 /* - Initialize constants and parse the command line. */
12898 /* - Read the points from a file and either */
12899 /* - triangulate them (no -r), or */
12900 /* - read an old mesh from files and reconstruct it (-r). */
12901 /* - Insert the PSLG segments (-p), and possibly segments on the convex */
12903 /* - Read the holes (-p), regional attributes (-pA), and regional area */
12904 /* constraints (-pa). Carve the holes and concavities, and spread the */
12905 /* regional attributes and area constraints. */
12906 /* - Enforce the constraints on minimum angle (-q) and maximum area (-a). */
12907 /* Also enforce the conforming Delaunay property (-q and -a). */
12908 /* - Compute the number of edges in the resulting mesh. */
12909 /* - Promote the mesh's linear triangles to higher order elements (-o). */
12910 /* - Write the output files and print the statistics. */
12911 /* - Check the consistency and Delaunay property of the mesh (-C). */
12913 /*****************************************************************************/
12917 void triangulate(triswitches, in, out, vorout)
12919 struct triangulateio *in;
12920 struct triangulateio *out;
12921 struct triangulateio *vorout;
12923 #else /* not TRILIBRARY */
12925 int main(argc, argv)
12929 #endif /* not TRILIBRARY */
12932 REAL *holearray; /* Array of holes. */
12933 REAL *regionarray; /* Array of regional attributes and area constraints. */
12936 #endif /* not TRILIBRARY */
12938 /* Variables for timing the performance of Triangle. The types are */
12939 /* defined in sys/time.h. */
12940 struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
12941 struct timezone tz;
12942 #endif /* NO_TIMER */
12945 gettimeofday(&tv0, &tz);
12946 #endif /* NO_TIMER */
12950 parsecommandline(1, &triswitches);
12951 #else /* not TRILIBRARY */
12952 parsecommandline(argc, argv);
12953 #endif /* not TRILIBRARY */
12956 transfernodes(in->pointlist, in->pointattributelist, in->pointmarkerlist,
12957 in->numberofpoints, in->numberofpointattributes);
12958 #else /* not TRILIBRARY */
12959 readnodes(innodefilename, inpolyfilename, &polyfile);
12960 #endif /* not TRILIBRARY */
12964 gettimeofday(&tv1, &tz);
12966 #endif /* NO_TIMER */
12969 hullsize = delaunay(); /* Triangulate the points. */
12970 #else /* not CDT_ONLY */
12972 /* Read and reconstruct a mesh. */
12974 hullsize = reconstruct(in->trianglelist, in->triangleattributelist,
12975 in->trianglearealist, in->numberoftriangles,
12976 in->numberofcorners, in->numberoftriangleattributes,
12977 in->segmentlist, in->segmentmarkerlist,
12978 in->numberofsegments);
12979 #else /* not TRILIBRARY */
12980 hullsize = reconstruct(inelefilename, areafilename, inpolyfilename,
12982 #endif /* not TRILIBRARY */
12984 hullsize = delaunay(); /* Triangulate the points. */
12986 #endif /* not CDT_ONLY */
12990 gettimeofday(&tv2, &tz);
12992 printf("Mesh reconstruction");
12994 printf("Delaunay");
12996 printf(" milliseconds: %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec)
12997 + (tv2.tv_usec - tv1.tv_usec) / 1000l);
12999 #endif /* NO_TIMER */
13001 /* Ensure that no point can be mistaken for a triangular bounding */
13002 /* box point in insertsite(). */
13003 infpoint1 = (point) NULL;
13004 infpoint2 = (point) NULL;
13005 infpoint3 = (point) NULL;
13008 checksegments = 1; /* Segments will be introduced next. */
13010 /* Insert PSLG segments and/or convex hull segments. */
13012 insegments = formskeleton(in->segmentlist, in->segmentmarkerlist,
13013 in->numberofsegments);
13014 #else /* not TRILIBRARY */
13015 insegments = formskeleton(polyfile, inpolyfilename);
13016 #endif /* not TRILIBRARY */
13022 gettimeofday(&tv3, &tz);
13023 if (useshelles && !refine) {
13024 printf("Segment milliseconds: %ld\n",
13025 1000l * (tv3.tv_sec - tv2.tv_sec)
13026 + (tv3.tv_usec - tv2.tv_usec) / 1000l);
13029 #endif /* NO_TIMER */
13033 holearray = in->holelist;
13034 holes = in->numberofholes;
13035 regionarray = in->regionlist;
13036 regions = in->numberofregions;
13037 #else /* not TRILIBRARY */
13038 readholes(polyfile, inpolyfilename, &holearray, &holes,
13039 ®ionarray, ®ions);
13040 #endif /* not TRILIBRARY */
13042 /* Carve out holes and concavities. */
13043 carveholes(holearray, holes, regionarray, regions);
13046 /* Without a PSLG, there can be no holes or regional attributes */
13047 /* or area constraints. The following are set to zero to avoid */
13048 /* an accidental free() later. */
13055 gettimeofday(&tv4, &tz);
13056 if (poly && !refine) {
13057 printf("Hole milliseconds: %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec)
13058 + (tv4.tv_usec - tv3.tv_usec) / 1000l);
13061 #endif /* NO_TIMER */
13065 enforcequality(); /* Enforce angle and area constraints. */
13067 #endif /* not CDT_ONLY */
13071 gettimeofday(&tv5, &tz);
13074 printf("Quality milliseconds: %ld\n",
13075 1000l * (tv5.tv_sec - tv4.tv_sec)
13076 + (tv5.tv_usec - tv4.tv_usec) / 1000l);
13078 #endif /* not CDT_ONLY */
13080 #endif /* NO_TIMER */
13082 /* Compute the number of edges. */
13083 edges = (3l * triangles.items + hullsize) / 2l;
13086 highorder(); /* Promote elements to higher polynomial order. */
13093 out->numberofpoints = points.items;
13094 out->numberofpointattributes = nextras;
13095 out->numberoftriangles = triangles.items;
13096 out->numberofcorners = (order + 1) * (order + 2) / 2;
13097 out->numberoftriangleattributes = eextras;
13098 out->numberofedges = edges;
13100 out->numberofsegments = shelles.items;
13102 out->numberofsegments = hullsize;
13104 if (vorout != (struct triangulateio *) NULL) {
13105 vorout->numberofpoints = triangles.items;
13106 vorout->numberofpointattributes = nextras;
13107 vorout->numberofedges = edges;
13109 #endif /* TRILIBRARY */
13110 /* If not using iteration numbers, don't write a .node file if one was */
13111 /* read, because the original one would be overwritten! */
13112 if (nonodewritten || (noiterationnum && readnodefile)) {
13115 printf("NOT writing points.\n");
13116 #else /* not TRILIBRARY */
13117 printf("NOT writing a .node file.\n");
13118 #endif /* not TRILIBRARY */
13120 numbernodes(); /* We must remember to number the points. */
13123 writenodes(&out->pointlist, &out->pointattributelist,
13124 &out->pointmarkerlist);
13125 #else /* not TRILIBRARY */
13126 writenodes(outnodefilename, argc, argv); /* Numbers the points too. */
13127 #endif /* TRILIBRARY */
13129 if (noelewritten) {
13132 printf("NOT writing triangles.\n");
13133 #else /* not TRILIBRARY */
13134 printf("NOT writing an .ele file.\n");
13135 #endif /* not TRILIBRARY */
13139 writeelements(&out->trianglelist, &out->triangleattributelist);
13140 #else /* not TRILIBRARY */
13141 writeelements(outelefilename, argc, argv);
13142 #endif /* not TRILIBRARY */
13144 /* The -c switch (convex switch) causes a PSLG to be written */
13145 /* even if none was read. */
13146 if (poly || convex) {
13147 /* If not using iteration numbers, don't overwrite the .poly file. */
13148 if (nopolywritten || noiterationnum) {
13151 printf("NOT writing segments.\n");
13152 #else /* not TRILIBRARY */
13153 printf("NOT writing a .poly file.\n");
13154 #endif /* not TRILIBRARY */
13158 writepoly(&out->segmentlist, &out->segmentmarkerlist);
13159 out->numberofholes = holes;
13160 out->numberofregions = regions;
13162 out->holelist = in->holelist;
13163 out->regionlist = in->regionlist;
13165 out->holelist = (REAL *) NULL;
13166 out->regionlist = (REAL *) NULL;
13168 #else /* not TRILIBRARY */
13169 writepoly(outpolyfilename, holearray, holes, regionarray, regions,
13171 #endif /* not TRILIBRARY */
13179 #endif /* not CDT_ONLY */
13184 writeoff(offfilename, argc, argv);
13186 #endif /* not TRILIBRARY */
13189 writeedges(&out->edgelist, &out->edgemarkerlist);
13190 #else /* not TRILIBRARY */
13191 writeedges(edgefilename, argc, argv);
13192 #endif /* not TRILIBRARY */
13196 writevoronoi(&vorout->pointlist, &vorout->pointattributelist,
13197 &vorout->pointmarkerlist, &vorout->edgelist,
13198 &vorout->edgemarkerlist, &vorout->normlist);
13199 #else /* not TRILIBRARY */
13200 writevoronoi(vnodefilename, vedgefilename, argc, argv);
13201 #endif /* not TRILIBRARY */
13205 writeneighbors(&out->neighborlist);
13206 #else /* not TRILIBRARY */
13207 writeneighbors(neighborfilename, argc, argv);
13208 #endif /* not TRILIBRARY */
13213 gettimeofday(&tv6, &tz);
13214 printf("\nOutput milliseconds: %ld\n",
13215 1000l * (tv6.tv_sec - tv5.tv_sec)
13216 + (tv6.tv_usec - tv5.tv_usec) / 1000l);
13217 printf("Total running milliseconds: %ld\n",
13218 1000l * (tv6.tv_sec - tv0.tv_sec)
13219 + (tv6.tv_usec - tv0.tv_usec) / 1000l);
13220 #endif /* NO_TIMER */
13230 #endif /* not REDUCED */
13235 #endif /* not TRILIBRARY */