]> de.git.xonotic.org Git - voretournament/voretournament.git/blob - misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/triangle.c
Include netRadiant source in this GIT
[voretournament/voretournament.git] / misc / mediasource / extra / netradiant-src / contrib / gtkgensurf / triangle.c
1 #define ANSI_DECLARATORS
2 /*****************************************************************************/
3 /*                                                                           */
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"        */
10 /*                                              "8oo8D                       */
11 /*                                                                           */
12 /*  A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.      */
13 /*  (triangle.c)                                                             */
14 /*                                                                           */
15 /*  Version 1.3                                                              */
16 /*  July 19, 1996                                                            */
17 /*                                                                           */
18 /*  Copyright 1996                                                           */
19 /*  Jonathan Richard Shewchuk                                                */
20 /*  School of Computer Science                                               */
21 /*  Carnegie Mellon University                                               */
22 /*  5000 Forbes Avenue                                                       */
23 /*  Pittsburgh, Pennsylvania  15213-3891                                     */
24 /*  jrs@cs.cmu.edu                                                           */
25 /*                                                                           */
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.)      */
39 /*                                                                           */
40 /*  Hypertext instructions for Triangle are available on the Web at          */
41 /*                                                                           */
42 /*      http://www.cs.cmu.edu/~quake/triangle.html                           */
43 /*                                                                           */
44 /*  Some of the references listed below are marked [*].  These are available */
45 /*    for downloading from the Web page                                      */
46 /*                                                                           */
47 /*      http://www.cs.cmu.edu/~quake/triangle.research.html                  */
48 /*                                                                           */
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.  [*]                                          */
53 /*                                                                           */
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.           */
61 /*                                                                           */
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.  [*]       */
65 /*                                                                           */
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.                                               */
77 /*                                                                           */
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.                                       */
86 /*                                                                           */
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.                                      */
100 /*                                                                           */
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.                   */
108 /*                                                                           */
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    */
128 /*    1995.                                                                  */
129 /*                                                                           */
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.                 */
136 /*                                                                           */
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.)                                                      */
145 /*                                                                           */
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   */
151 /*    happen.                                                                */
152 /*                                                                           */
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.                                               */
162 /*                                                                           */
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.                   */
167 /*                                                                           */
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.                                    */
172 /*                                                                           */
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.             */
176 /*                                                                           */
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.     */
179 /*                                                                           */
180 /*****************************************************************************/
181
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.                                         */
185 /*                                                                           */
186 /* For double precision (which will allow you to refine meshes to a smaller  */
187 /*   edge length), leave SINGLE undefined.                                   */
188 /*                                                                           */
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.                                          */
195
196 #define SINGLE
197
198 #ifdef SINGLE
199 #define REAL float
200 #else /* not SINGLE */
201 #define REAL double
202 #endif /* not SINGLE */
203
204 /* If yours is not a Unix system, define the NO_TIMER compiler switch to     */
205 /*   remove the Unix-specific timing code.                                   */
206
207 #define NO_TIMER
208
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.                                      */
214
215 /* #define SELF_CHECK */
216
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.                               */
220
221 #define TRILIBRARY
222
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.                 */
231
232 #define REDUCED
233 #define CDT_ONLY
234
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.                    */
240 /*                                                                           */
241 /* To try this out, write "#define INEXACT volatile" below.  Normally,       */
242 /*   however, INEXACT should be defined to be nothing.  ("#define INEXACT".) */
243
244 #define INEXACT /* Nothing */
245 /* #define INEXACT volatile */
246
247 /* Maximum number of characters in a file name (including the null).         */
248
249 #define FILENAMESIZE 512
250
251 /* Maximum number of characters in a line read from a file (including the    */
252 /*   null).                                                                  */
253
254 #define INPUTLINESIZE 512
255
256 /* For efficiency, a variety of data structures are allocated in bulk.  The  */
257 /*   following constants determine how many of each structure is allocated   */
258 /*   at once.                                                                */
259
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
270
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.                */
274
275 #define DEADPOINT -1073741824
276
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.                                                    */
280
281 #define VOID int
282
283 /* Two constants for algorithms based on random sampling.  Both constants    */
284 /*   have been chosen empirically to optimize their respective algorithms.   */
285
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
293
294 /* A number that speaks for itself, every kissable digit.                    */
295
296 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
297
298 /* Another fave.                                                             */
299
300 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
301
302 /* And here's one for those of you who are intimidated by math.              */
303
304 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
305
306 #include <stdio.h>
307 #include <string.h>
308 #include <math.h>
309 #ifndef NO_TIMER
310 #include <sys/time.h>
311 #endif /* NO_TIMER */
312 #ifdef TRILIBRARY
313 #include "triangle.h"
314 #endif /* TRILIBRARY */
315
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.     */
321
322 #ifndef _STDLIB_H_
323 extern void *malloc();
324 extern void free();
325 extern void exit();
326 extern double strtod();
327 extern long strtol();
328 #endif /* _STDLIB_H_ */
329
330 /* A few forward declarations.                                               */
331
332 void poolrestart();
333 #ifndef TRILIBRARY
334 char *readline();
335 char *findfield();
336 #endif /* not TRILIBRARY */
337
338 /* Labels that signify whether a record consists primarily of pointers or of */
339 /*   floating-point words.  Used to make decisions about data alignment.     */
340
341 enum wordtype {POINTER, FLOATINGPOINT};
342
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.                              */
346
347 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
348
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.   */
353
354 enum insertsiteresult {SUCCESSFULPOINT, ENCROACHINGPOINT, VIOLATINGPOINT,
355                        DUPLICATEPOINT};
356
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.                      */
361
362 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
363
364 /* Labels that signify the result of the circumcenter computation routine.   */
365 /*   The return value indicates which edge of the triangle is shortest.      */
366
367 enum circumcenterresult {OPPOSITEORG, OPPOSITEDEST, OPPOSITEAPEX};
368
369 /*****************************************************************************/
370 /*                                                                           */
371 /*  The basic mesh data structures                                           */
372 /*                                                                           */
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.                                  */
381 /*                                                                           */
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.                                                     */
388 /*                                                                           */
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.  */
398 /*                                                                           */
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.                     */
407 /*                                                                           */
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.                                               */
411 /*                                                                           */
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        */
419 /*  simulation.                                                              */
420 /*                                                                           */
421 /*  Like triangles, shell edges maintain information about the relative      */
422 /*  orientation of neighboring objects.                                      */
423 /*                                                                           */
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.                        */
436 /*                                                                           */
437 /*****************************************************************************/
438
439 /*****************************************************************************/
440 /*                                                                           */
441 /*  Handles                                                                  */
442 /*                                                                           */
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.         */
446 /*                                                                           */
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.)                               */
454 /*                                                                           */
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.                         */
458 /*                                                                           */
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.  */
466 /*                                                                           */
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.                                          */
471 /*                                                                           */
472 /*****************************************************************************/
473
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.   */
482
483 typedef REAL **triangle;            /* Really:  typedef triangle *triangle   */
484
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.    */
489
490 struct triedge {
491   triangle *tri;
492   int orient;                                         /* Ranges from 0 to 2. */
493 };
494
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.                 */
498
499 typedef REAL **shelle;                  /* Really:  typedef shelle *shelle   */
500
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.      */
505
506 struct edge {
507   shelle *sh;
508   int shorient;                                       /* Ranges from 0 to 1. */
509 };
510
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    */
514 /*   REALs.                                                                  */
515
516 typedef REAL *point;
517
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.       */
520
521 struct badsegment {
522   struct edge encsegment;                          /* An encroached segment. */
523   point segorg, segdest;                                /* The two vertices. */
524   struct badsegment *nextsegment;     /* Pointer to next encroached segment. */
525 };
526
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.      */
530
531 struct badface {
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. */
536 };
537
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'.  */
547
548 struct event {
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. */
552 };
553
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.                                    */
564
565 struct splaynode {
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. */
569 };
570
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.                                   */
577 /*                                                                           */
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.                                              */
584 /*                                                                           */
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.                                                       */
594
595 struct memorypool {
596   VOID **firstblock, **nowblock;
597   VOID *nextitem;
598   VOID *deaditemstack;
599   VOID **pathblock;
600   VOID *pathitem;
601   enum wordtype itemwordtype;
602   int alignbytes;
603   int itembytes, itemwords;
604   int itemsperblock;
605   long items, maxitems;
606   int unallocateditems;
607   int pathitemsleft;
608 };
609
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.                          */
613
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;
621
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.           */
624
625 static struct badface *queuefront[64];
626 static struct badface **queuetail[64];
627
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. */
651
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;
657
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. */
663
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.                                                      */
692 /*                                                                           */
693 /* Read the instructions to find out the meaning of these switches.          */
694
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;
701 static int splitseg;
702 static int docheck;
703 static int quiet, verbose;
704 static int useshelles;
705 static int order;
706 static int nobisect;
707 static int steiner, steinerleft;
708 static REAL minangle, goodangle;
709 static REAL maxarea;
710
711 /* Variables for file names.                                                 */
712
713 #ifndef TRILIBRARY
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 */
727
728 /* Triangular bounding box points.                                           */
729
730 static point infpoint1, infpoint2, infpoint3;
731
732 /* Pointer to the `triangle' that occupies all of "outer space".             */
733
734 static triangle *dummytri;
735 static triangle *dummytribase;      /* Keep base address so we can free() it later. */
736
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          */
739 /*   location.                                                               */
740
741 static shelle *dummysh;
742 static shelle *dummyshbase;         /* Keep base address so we can free() it later. */
743
744 /* Pointer to a recently visited triangle.  Improves point location if       */
745 /*   proximate points are inserted sequentially.                             */
746
747 static struct triedge recenttri;
748
749 /*****************************************************************************/
750 /*                                                                           */
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.*/
763 /*                                                                           */
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.          */
766 /*                                                                           */
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.                            */
770 /*                                                                           */
771 /*****************************************************************************/
772
773 /********* Mesh manipulation primitives begin here                   *********/
774 /**                                                                         **/
775 /**                                                                         **/
776
777 /* Fast lookup arrays to speed some of the mesh manipulation primitives.     */
778
779 int plus1mod3[3] = {1, 2, 0};
780 int minus1mod3[3] = {2, 0, 1};
781
782 /********* Primitives for triangles                                  *********/
783 /*                                                                           */
784 /*                                                                           */
785
786 /* decode() converts a pointer to an oriented triangle.  The orientation is  */
787 /*   extracted from the two least significant bits of the pointer.           */
788
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)
793
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.*/
797
798 #define encode(triedge)                                                       \
799   (triangle) ((unsigned long) (triedge).tri | (unsigned long) (triedge).orient)
800
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.                               */
804
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.               */
808
809 #define sym(triedge1, triedge2)                                               \
810   ptr = (triedge1).tri[(triedge1).orient];                                    \
811   decode(ptr, triedge2);
812
813 #define symself(triedge)                                                      \
814   ptr = (triedge).tri[(triedge).orient];                                      \
815   decode(ptr, triedge);
816
817 /* lnext() finds the next edge (counterclockwise) of a triangle.             */
818
819 #define lnext(triedge1, triedge2)                                             \
820   (triedge2).tri = (triedge1).tri;                                            \
821   (triedge2).orient = plus1mod3[(triedge1).orient]
822
823 #define lnextself(triedge)                                                    \
824   (triedge).orient = plus1mod3[(triedge).orient]
825
826 /* lprev() finds the previous edge (clockwise) of a triangle.                */
827
828 #define lprev(triedge1, triedge2)                                             \
829   (triedge2).tri = (triedge1).tri;                                            \
830   (triedge2).orient = minus1mod3[(triedge1).orient]
831
832 #define lprevself(triedge)                                                    \
833   (triedge).orient = minus1mod3[(triedge).orient]
834
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.                                   */
838
839 #define onext(triedge1, triedge2)                                             \
840   lprev(triedge1, triedge2);                                                  \
841   symself(triedge2);
842
843 #define onextself(triedge)                                                    \
844   lprevself(triedge);                                                         \
845   symself(triedge);
846
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.                                           */
850
851 #define oprev(triedge1, triedge2)                                             \
852   sym(triedge1, triedge2);                                                    \
853   lnextself(triedge2);
854
855 #define oprevself(triedge)                                                    \
856   symself(triedge);                                                           \
857   lnextself(triedge);
858
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.                              */
862
863 #define dnext(triedge1, triedge2)                                             \
864   sym(triedge1, triedge2);                                                    \
865   lprevself(triedge2);
866
867 #define dnextself(triedge)                                                    \
868   symself(triedge);                                                           \
869   lprevself(triedge);
870
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.                                        */
874
875 #define dprev(triedge1, triedge2)                                             \
876   lnext(triedge1, triedge2);                                                  \
877   symself(triedge2);
878
879 #define dprevself(triedge)                                                    \
880   lnextself(triedge);                                                         \
881   symself(triedge);
882
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.)                                              */
886
887 #define rnext(triedge1, triedge2)                                             \
888   sym(triedge1, triedge2);                                                    \
889   lnextself(triedge2);                                                        \
890   symself(triedge2);
891
892 #define rnextself(triedge)                                                    \
893   symself(triedge);                                                           \
894   lnextself(triedge);                                                         \
895   symself(triedge);
896
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.)                                              */
900
901 #define rprev(triedge1, triedge2)                                             \
902   sym(triedge1, triedge2);                                                    \
903   lprevself(triedge2);                                                        \
904   symself(triedge2);
905
906 #define rprevself(triedge)                                                    \
907   symself(triedge);                                                           \
908   lprevself(triedge);                                                         \
909   symself(triedge);
910
911 /* These primitives determine or set the origin, destination, or apex of a   */
912 /* triangle.                                                                 */
913
914 #define org(triedge, pointptr)                                                \
915   pointptr = (point) (triedge).tri[plus1mod3[(triedge).orient] + 3]
916
917 #define dest(triedge, pointptr)                                               \
918   pointptr = (point) (triedge).tri[minus1mod3[(triedge).orient] + 3]
919
920 #define apex(triedge, pointptr)                                               \
921   pointptr = (point) (triedge).tri[(triedge).orient + 3]
922
923 #define setorg(triedge, pointptr)                                             \
924   (triedge).tri[plus1mod3[(triedge).orient] + 3] = (triangle) pointptr
925
926 #define setdest(triedge, pointptr)                                            \
927   (triedge).tri[minus1mod3[(triedge).orient] + 3] = (triangle) pointptr
928
929 #define setapex(triedge, pointptr)                                            \
930   (triedge).tri[(triedge).orient + 3] = (triangle) pointptr
931
932 #define setvertices2null(triedge)                                             \
933   (triedge).tri[3] = (triangle) NULL;                                         \
934   (triedge).tri[4] = (triangle) NULL;                                         \
935   (triedge).tri[5] = (triangle) NULL;
936
937 /* Bond two triangles together.                                              */
938
939 #define bond(triedge1, triedge2)                                              \
940   (triedge1).tri[(triedge1).orient] = encode(triedge2);                       \
941   (triedge2).tri[(triedge2).orient] = encode(triedge1)
942
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.                                                      */
947
948 #define dissolve(triedge)                                                     \
949   (triedge).tri[(triedge).orient] = (triangle) dummytri
950
951 /* Copy a triangle/edge handle.                                              */
952
953 #define triedgecopy(triedge1, triedge2)                                       \
954   (triedge2).tri = (triedge1).tri;                                            \
955   (triedge2).orient = (triedge1).orient
956
957 /* Test for equality of triangle/edge handles.                               */
958
959 #define triedgeequal(triedge1, triedge2)                                      \
960   (((triedge1).tri == (triedge2).tri) &&                                      \
961    ((triedge1).orient == (triedge2).orient))
962
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.*/
965
966 #define infect(triedge)                                                       \
967   (triedge).tri[6] = (triangle)                                               \
968                      ((unsigned long) (triedge).tri[6] | (unsigned long) 2l)
969
970 #define uninfect(triedge)                                                     \
971   (triedge).tri[6] = (triangle)                                               \
972                      ((unsigned long) (triedge).tri[6] & ~ (unsigned long) 2l)
973
974 /* Test a triangle for viral infection.                                      */
975
976 #define infected(triedge)                                                     \
977   (((unsigned long) (triedge).tri[6] & (unsigned long) 2l) != 0)
978
979 /* Check or set a triangle's attributes.                                     */
980
981 #define elemattribute(triedge, attnum)                                        \
982   ((REAL *) (triedge).tri)[elemattribindex + (attnum)]
983
984 #define setelemattribute(triedge, attnum, value)                              \
985   ((REAL *) (triedge).tri)[elemattribindex + (attnum)] = (REAL)value
986
987 /* Check or set a triangle's maximum area bound.                             */
988
989 #define areabound(triedge)  ((REAL *) (triedge).tri)[areaboundindex]
990
991 #define setareabound(triedge, value)                                          \
992   ((REAL *) (triedge).tri)[areaboundindex] = (REAL)value
993
994 /********* Primitives for shell edges                                *********/
995 /*                                                                           */
996 /*                                                                           */
997
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.                             */
1002
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)
1007
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.          */
1011
1012 #define sencode(edge)                                                         \
1013   (shelle) ((unsigned long) (edge).sh | (unsigned long) (edge).shorient)
1014
1015 /* ssym() toggles the orientation of a shell edge.                           */
1016
1017 #define ssym(edge1, edge2)                                                    \
1018   (edge2).sh = (edge1).sh;                                                    \
1019   (edge2).shorient = 1 - (edge1).shorient
1020
1021 #define ssymself(edge)                                                        \
1022   (edge).shorient = 1 - (edge).shorient
1023
1024 /* spivot() finds the other shell edge (from the same segment) that shares   */
1025 /*   the same origin.                                                        */
1026
1027 #define spivot(edge1, edge2)                                                  \
1028   sptr = (edge1).sh[(edge1).shorient];                                        \
1029   sdecode(sptr, edge2)
1030
1031 #define spivotself(edge)                                                      \
1032   sptr = (edge).sh[(edge).shorient];                                          \
1033   sdecode(sptr, edge)
1034
1035 /* snext() finds the next shell edge (from the same segment) in sequence;    */
1036 /*   one whose origin is the input shell edge's destination.                 */
1037
1038 #define snext(edge1, edge2)                                                   \
1039   sptr = (edge1).sh[1 - (edge1).shorient];                                    \
1040   sdecode(sptr, edge2)
1041
1042 #define snextself(edge)                                                       \
1043   sptr = (edge).sh[1 - (edge).shorient];                                      \
1044   sdecode(sptr, edge)
1045
1046 /* These primitives determine or set the origin or destination of a shell    */
1047 /*   edge.                                                                   */
1048
1049 #define sorg(edge, pointptr)                                                  \
1050   pointptr = (point) (edge).sh[2 + (edge).shorient]
1051
1052 #define sdest(edge, pointptr)                                                 \
1053   pointptr = (point) (edge).sh[3 - (edge).shorient]
1054
1055 #define setsorg(edge, pointptr)                                               \
1056   (edge).sh[2 + (edge).shorient] = (shelle) pointptr
1057
1058 #define setsdest(edge, pointptr)                                              \
1059   (edge).sh[3 - (edge).shorient] = (shelle) pointptr
1060
1061 /* These primitives read or set a shell marker.  Shell markers are used to   */
1062 /*   hold user boundary information.                                         */
1063
1064 #define mark(edge)  (* (int *) ((edge).sh + 6))
1065
1066 #define setmark(edge, value)                                                  \
1067   * (int *) ((edge).sh + 6) = value
1068
1069 /* Bond two shell edges together.                                            */
1070
1071 #define sbond(edge1, edge2)                                                   \
1072   (edge1).sh[(edge1).shorient] = sencode(edge2);                              \
1073   (edge2).sh[(edge2).shorient] = sencode(edge1)
1074
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.                */
1077
1078 #define sdissolve(edge)                                                       \
1079   (edge).sh[(edge).shorient] = (shelle) dummysh
1080
1081 /* Copy a shell edge.                                                        */
1082
1083 #define shellecopy(edge1, edge2)                                              \
1084   (edge2).sh = (edge1).sh;                                                    \
1085   (edge2).shorient = (edge1).shorient
1086
1087 /* Test for equality of shell edges.                                         */
1088
1089 #define shelleequal(edge1, edge2)                                             \
1090   (((edge1).sh == (edge2).sh) &&                                              \
1091    ((edge1).shorient == (edge2).shorient))
1092
1093 /********* Primitives for interacting triangles and shell edges      *********/
1094 /*                                                                           */
1095 /*                                                                           */
1096
1097 /* tspivot() finds a shell edge abutting a triangle.                         */
1098
1099 #define tspivot(triedge, edge)                                                \
1100   sptr = (shelle) (triedge).tri[6 + (triedge).orient];                        \
1101   sdecode(sptr, edge)
1102
1103 /* stpivot() finds a triangle abutting a shell edge.  It requires that the   */
1104 /*   variable `ptr' of type `triangle' be defined.                           */
1105
1106 #define stpivot(edge, triedge)                                                \
1107   ptr = (triangle) (edge).sh[4 + (edge).shorient];                            \
1108   decode(ptr, triedge)
1109
1110 /* Bond a triangle to a shell edge.                                          */
1111
1112 #define tsbond(triedge, edge)                                                 \
1113   (triedge).tri[6 + (triedge).orient] = (triangle) sencode(edge);             \
1114   (edge).sh[4 + (edge).shorient] = (shelle) encode(triedge)
1115
1116 /* Dissolve a bond (from the triangle side).                                 */
1117
1118 #define tsdissolve(triedge)                                                   \
1119   (triedge).tri[6 + (triedge).orient] = (triangle) dummysh
1120
1121 /* Dissolve a bond (from the shell edge side).                               */
1122
1123 #define stdissolve(edge)                                                      \
1124   (edge).sh[4 + (edge).shorient] = (shelle) dummytri
1125
1126 /********* Primitives for points                                     *********/
1127 /*                                                                           */
1128 /*                                                                           */
1129
1130 #define pointmark(pt)  ((int *) (pt))[pointmarkindex]
1131
1132 #define setpointmark(pt, value)                                               \
1133   ((int *) (pt))[pointmarkindex] = value
1134
1135 #define point2tri(pt)  ((triangle *) (pt))[point2triindex]
1136
1137 #define setpoint2tri(pt, value)                                               \
1138   ((triangle *) (pt))[point2triindex] = value
1139
1140 /**                                                                         **/
1141 /**                                                                         **/
1142 /********* Mesh manipulation primitives end here                     *********/
1143
1144 /********* User interaction routines begin here                      *********/
1145 /**                                                                         **/
1146 /**                                                                         **/
1147
1148 /*****************************************************************************/
1149 /*                                                                           */
1150 /*  syntax()   Print list of command line switches.                          */
1151 /*                                                                           */
1152 /*****************************************************************************/
1153
1154 #ifndef TRILIBRARY
1155
1156 void syntax()
1157 {
1158 #ifdef CDT_ONLY
1159 #ifdef REDUCED
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 */
1165 #ifdef REDUCED
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 */
1171
1172   printf("    -p  Triangulates a Planar Straight Line Graph (.poly file).\n");
1173 #ifndef CDT_ONLY
1174   printf("    -r  Refines a previously generated mesh.\n");
1175   printf(
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 */
1179   printf(
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");
1195 #ifndef CDT_ONLY
1196   printf("    -Y  Suppresses boundary segment splitting.\n");
1197   printf("    -S  Specifies maximum number of added Steiner points.\n");
1198 #endif /* not CDT_ONLY */
1199 #ifndef REDUCED
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");
1204 #ifndef REDUCED
1205 #ifndef CDT_ONLY
1206   printf(
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");
1214   exit(0);
1215 }
1216
1217 #endif /* not TRILIBRARY */
1218
1219 /*****************************************************************************/
1220 /*                                                                           */
1221 /*  info()   Print out complete instructions.                                */
1222 /*                                                                           */
1223 /*****************************************************************************/
1224
1225 #ifndef TRILIBRARY
1226
1227 void info()
1228 {
1229   printf("Triangle\n");
1230   printf(
1231 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
1232   printf("Version 1.3\n\n");
1233   printf(
1234 "Copyright 1996 Jonathan Richard Shewchuk  (bugs/comments to jrs@cs.cmu.edu)\n"
1235 );
1236   printf("School of Computer Science / Carnegie Mellon University\n");
1237   printf("5000 Forbes Avenue / Pittsburgh, Pennsylvania  15213-3891\n");
1238   printf(
1239 "Created as part of the Archimedes project (tools for parallel FEM).\n");
1240   printf(
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");
1243 #ifdef SINGLE
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 */
1248   printf(
1249 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
1250   printf(
1251 "triangulations, and quality conforming Delaunay triangulations.  The latter\n"
1252 );
1253   printf(
1254 "can be generated with no small angles, and are thus suitable for finite\n");
1255   printf(
1256 "element analysis.  If no command line switches are specified, your .node\n");
1257   printf(
1258 "input file will be read, and the Delaunay triangulation will be returned in\n"
1259 );
1260   printf(".node and .ele output files.  The command syntax is:\n\n");
1261 #ifdef CDT_ONLY
1262 #ifdef REDUCED
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 */
1268 #ifdef REDUCED
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 */
1274   printf(
1275 "Underscores indicate that numbers may optionally follow certain switches;\n");
1276   printf(
1277 "do not leave any space between a switch and its numeric parameter.\n");
1278   printf(
1279 "input_file must be a file with extension .node, or extension .poly if the\n");
1280   printf(
1281 "-p switch is used.  If -r is used, you must supply .node and .ele files,\n");
1282   printf(
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");
1286   printf(
1287 "    -p  Reads a Planar Straight Line Graph (.poly file), which can specify\n"
1288 );
1289   printf(
1290 "        points, segments, holes, and regional attributes and area\n");
1291   printf(
1292 "        constraints.  Will generate a constrained Delaunay triangulation\n");
1293   printf(
1294 "        fitting the input; or, if -s, -q, or -a is used, a conforming\n");
1295   printf(
1296 "        Delaunay triangulation.  If -p is not used, Triangle reads a .node\n"
1297 );
1298   printf("        file by default.\n");
1299   printf(
1300 "    -r  Refines a previously generated mesh.  The mesh is read from a .node\n"
1301 );
1302   printf(
1303 "        file and an .ele file.  If -p is also used, a .poly file is read\n");
1304   printf(
1305 "        and used to constrain edges in the mesh.  Further details on\n");
1306   printf("        refinement are given below.\n");
1307   printf(
1308 "    -q  Quality mesh generation by Jim Ruppert's Delaunay refinement\n");
1309   printf(
1310 "        algorithm.  Adds points to the mesh to ensure that no angles\n");
1311   printf(
1312 "        smaller than 20 degrees occur.  An alternative minimum angle may be\n"
1313 );
1314   printf(
1315 "        specified after the `q'.  If the minimum angle is 20.7 degrees or\n");
1316   printf(
1317 "        smaller, the triangulation algorithm is theoretically guaranteed to\n"
1318 );
1319   printf(
1320 "        terminate (assuming infinite precision arithmetic - Triangle may\n");
1321   printf(
1322 "        fail to terminate if you run out of precision).  In practice, the\n");
1323   printf(
1324 "        algorithm often succeeds for minimum angles up to 33.8 degrees.\n");
1325   printf(
1326 "        For highly refined meshes, however, it may be necessary to reduce\n");
1327   printf(
1328 "        the minimum angle to well below 20 to avoid problems associated\n");
1329   printf(
1330 "        with insufficient floating-point precision.  The specified angle\n");
1331   printf("        may include a decimal point.\n");
1332   printf(
1333 "    -a  Imposes a maximum triangle area.  If a number follows the `a', no\n");
1334   printf(
1335 "        triangle will be generated whose area is larger than that number.\n");
1336   printf(
1337 "        If no number is specified, an .area file (if -r is used) or .poly\n");
1338   printf(
1339 "        file (if -r is not used) specifies a number of maximum area\n");
1340   printf(
1341 "        constraints.  An .area file contains a separate area constraint for\n"
1342 );
1343   printf(
1344 "        each triangle, and is useful for refining a finite element mesh\n");
1345   printf(
1346 "        based on a posteriori error estimates.  A .poly file can optionally\n"
1347 );
1348   printf(
1349 "        contain an area constraint for each segment-bounded region, thereby\n"
1350 );
1351   printf(
1352 "        enforcing triangle densities in a first triangulation.  You can\n");
1353   printf(
1354 "        impose both a fixed area constraint and a varying area constraint\n");
1355   printf(
1356 "        by invoking the -a switch twice, once with and once without a\n");
1357   printf(
1358 "        number following.  Each area specified may include a decimal point.\n"
1359 );
1360   printf(
1361 "    -A  Assigns an additional attribute to each triangle that identifies\n");
1362   printf(
1363 "        what segment-bounded region each triangle belongs to.  Attributes\n");
1364   printf(
1365 "        are assigned to regions by the .poly file.  If a region is not\n");
1366   printf(
1367 "        explicitly marked by the .poly file, triangles in that region are\n");
1368   printf(
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");
1371   printf(
1372 "    -c  Creates segments on the convex hull of the triangulation.  If you\n");
1373   printf(
1374 "        are triangulating a point set, this switch causes a .poly file to\n");
1375   printf(
1376 "        be written, containing all edges in the convex hull.  (By default,\n"
1377 );
1378   printf(
1379 "        a .poly file is written only if a .poly file is read.)  If you are\n"
1380 );
1381   printf(
1382 "        triangulating a PSLG, this switch specifies that the interior of\n");
1383   printf(
1384 "        the convex hull of the PSLG should be triangulated.  If you do not\n"
1385 );
1386   printf(
1387 "        use this switch when triangulating a PSLG, it is assumed that you\n");
1388   printf(
1389 "        have identified the region to be triangulated by surrounding it\n");
1390   printf(
1391 "        with segments of the input PSLG.  Beware:  if you are not careful,\n"
1392 );
1393   printf(
1394 "        this switch can cause the introduction of an extremely thin angle\n");
1395   printf(
1396 "        between a PSLG segment and a convex hull segment, which can cause\n");
1397   printf(
1398 "        overrefinement or failure if Triangle runs out of precision.  If\n");
1399   printf(
1400 "        you are refining a mesh, the -c switch works differently; it\n");
1401   printf(
1402 "        generates the set of boundary edges of the mesh, rather than the\n");
1403   printf("        convex hull.\n");
1404   printf(
1405 "    -e  Outputs (to an .edge file) a list of edges of the triangulation.\n");
1406   printf(
1407 "    -v  Outputs the Voronoi diagram associated with the triangulation.\n");
1408   printf("        Does not attempt to detect degeneracies.\n");
1409   printf(
1410 "    -n  Outputs (to a .neigh file) a list of triangles neighboring each\n");
1411   printf("        triangle.\n");
1412   printf(
1413 "    -g  Outputs the mesh to an Object File Format (.off) file, suitable for\n"
1414 );
1415   printf("        viewing with the Geometry Center's Geomview package.\n");
1416   printf(
1417 "    -B  No boundary markers in the output .node, .poly, and .edge output\n");
1418   printf(
1419 "        files.  See the detailed discussion of boundary markers below.\n");
1420   printf(
1421 "    -P  No output .poly file.  Saves disk space, but you lose the ability\n");
1422   printf(
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");
1426   printf(
1427 "    -I  No iteration numbers.  Suppresses the output of .node and .poly\n");
1428   printf(
1429 "        files, so your input files won't be overwritten.  (If your input is\n"
1430 );
1431   printf(
1432 "        a .poly file only, a .node file will be written.)  Cannot be used\n");
1433   printf(
1434 "        with the -r switch, because that would overwrite your input .ele\n");
1435   printf(
1436 "        file.  Shouldn't be used with the -s, -q, or -a switch if you are\n");
1437   printf(
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");
1441   printf(
1442 "    -X  No exact arithmetic.  Normally, Triangle uses exact floating-point\n"
1443 );
1444   printf(
1445 "        arithmetic for certain tests if it thinks the inexact tests are not\n"
1446 );
1447   printf(
1448 "        accurate enough.  Exact arithmetic ensures the robustness of the\n");
1449   printf(
1450 "        triangulation algorithms, despite floating-point roundoff error.\n");
1451   printf(
1452 "        Disabling exact arithmetic with the -X switch will cause a small\n");
1453   printf(
1454 "        improvement in speed and create the possibility (albeit small) that\n"
1455 );
1456   printf(
1457 "        Triangle will fail to produce a valid mesh.  Not recommended.\n");
1458   printf(
1459 "    -z  Numbers all items starting from zero (rather than one).  Note that\n"
1460 );
1461   printf(
1462 "        this switch is normally overrided by the value used to number the\n");
1463   printf(
1464 "        first point of the input .node or .poly file.  However, this switch\n"
1465 );
1466   printf("        is useful when calling Triangle from another program.\n");
1467   printf(
1468 "    -o2 Generates second-order subparametric elements with six nodes each.\n"
1469 );
1470   printf(
1471 "    -Y  No new points on the boundary.  This switch is useful when the mesh\n"
1472 );
1473   printf(
1474 "        boundary must be preserved so that it conforms to some adjacent\n");
1475   printf(
1476 "        mesh.  Be forewarned that you will probably sacrifice some of the\n");
1477   printf(
1478 "        quality of the mesh; Triangle will try, but the resulting mesh may\n"
1479 );
1480   printf(
1481 "        contain triangles of poor aspect ratio.  Works well if all the\n");
1482   printf(
1483 "        boundary points are closely spaced.  Specify this switch twice\n");
1484   printf(
1485 "        (`-YY') to prevent all segment splitting, including internal\n");
1486   printf("        boundaries.\n");
1487   printf(
1488 "    -S  Specifies the maximum number of Steiner points (points that are not\n"
1489 );
1490   printf(
1491 "        in the input, but are added to meet the constraints of minimum\n");
1492   printf(
1493 "        angle and maximum area).  The default is to allow an unlimited\n");
1494   printf(
1495 "        number.  If you specify this switch with no number after it,\n");
1496   printf(
1497 "        the limit is set to zero.  Triangle always adds points at segment\n");
1498   printf(
1499 "        intersections, even if it needs to use more points than the limit\n");
1500   printf(
1501 "        you set.  When Triangle inserts segments by splitting (-s), it\n");
1502   printf(
1503 "        always adds enough points to ensure that all the segments appear in\n"
1504 );
1505   printf(
1506 "        the triangulation, again ignoring the limit.  Be forewarned that\n");
1507   printf(
1508 "        the -S switch may result in a conforming triangulation that is not\n"
1509 );
1510   printf(
1511 "        truly Delaunay, because Triangle may be forced to stop adding\n");
1512   printf(
1513 "        points when the mesh is in a state where a segment is non-Delaunay\n"
1514 );
1515   printf(
1516 "        and needs to be split.  If so, Triangle will print a warning.\n");
1517   printf(
1518 "    -i  Uses an incremental rather than divide-and-conquer algorithm to\n");
1519   printf(
1520 "        form a Delaunay triangulation.  Try it if the divide-and-conquer\n");
1521   printf("        algorithm fails.\n");
1522   printf(
1523 "    -F  Uses Steven Fortune's sweepline algorithm to form a Delaunay\n");
1524   printf(
1525 "        triangulation.  Warning:  does not use exact arithmetic for all\n");
1526   printf("        calculations.  An exact result is not guaranteed.\n");
1527   printf(
1528 "    -l  Uses only vertical cuts in the divide-and-conquer algorithm.  By\n");
1529   printf(
1530 "        default, Triangle uses alternating vertical and horizontal cuts,\n");
1531   printf(
1532 "        which usually improve the speed except with point sets that are\n");
1533   printf(
1534 "        small or short and wide.  This switch is primarily of theoretical\n");
1535   printf("        interest.\n");
1536   printf(
1537 "    -s  Specifies that segments should be forced into the triangulation by\n"
1538 );
1539   printf(
1540 "        recursively splitting them at their midpoints, rather than by\n");
1541   printf(
1542 "        generating a constrained Delaunay triangulation.  Segment splitting\n"
1543 );
1544   printf(
1545 "        is true to Ruppert's original algorithm, but can create needlessly\n"
1546 );
1547   printf("        small triangles near external small features.\n");
1548   printf(
1549 "    -C  Check the consistency of the final mesh.  Uses exact arithmetic for\n"
1550 );
1551   printf(
1552 "        checking, even if the -X switch is used.  Useful if you suspect\n");
1553   printf("        Triangle is buggy.\n");
1554   printf(
1555 "    -Q  Quiet: Suppresses all explanation of what Triangle is doing, unless\n"
1556 );
1557   printf("        an error occurs.\n");
1558   printf(
1559 "    -V  Verbose: Gives detailed information about what Triangle is doing.\n");
1560   printf(
1561 "        Add more `V's for increasing amount of detail.  `-V' gives\n");
1562   printf(
1563 "        information on algorithmic progress and more detailed statistics.\n");
1564   printf(
1565 "        `-VV' gives point-by-point details, and will print so much that\n");
1566   printf(
1567 "        Triangle will run much more slowly.  `-VVV' gives information only\n"
1568 );
1569   printf("        a debugger could love.\n");
1570   printf("    -h  Help:  Displays these instructions.\n");
1571   printf("\n");
1572   printf("Definitions:\n");
1573   printf("\n");
1574   printf(
1575 "  A Delaunay triangulation of a point set is a triangulation whose vertices\n"
1576 );
1577   printf(
1578 "  are the point set, having the property that no point in the point set\n");
1579   printf(
1580 "  falls in the interior of the circumcircle (circle that passes through all\n"
1581 );
1582   printf("  three vertices) of any triangle in the triangulation.\n\n");
1583   printf(
1584 "  A Voronoi diagram of a point set is a subdivision of the plane into\n");
1585   printf(
1586 "  polygonal regions (some of which may be infinite), where each region is\n");
1587   printf(
1588 "  the set of points in the plane that are closer to some input point than\n");
1589   printf(
1590 "  to any other input point.  (The Voronoi diagram is the geometric dual of\n"
1591 );
1592   printf("  the Delaunay triangulation.)\n\n");
1593   printf(
1594 "  A Planar Straight Line Graph (PSLG) is a collection of points and\n");
1595   printf(
1596 "  segments.  Segments are simply edges, whose endpoints are points in the\n");
1597   printf(
1598 "  PSLG.  The file format for PSLGs (.poly files) is described below.\n");
1599   printf("\n");
1600   printf(
1601 "  A constrained Delaunay triangulation of a PSLG is similar to a Delaunay\n");
1602   printf(
1603 "  triangulation, but each PSLG segment is present as a single edge in the\n");
1604   printf(
1605 "  triangulation.  (A constrained Delaunay triangulation is not truly a\n");
1606   printf("  Delaunay triangulation.)\n\n");
1607   printf(
1608 "  A conforming Delaunay triangulation of a PSLG is a true Delaunay\n");
1609   printf(
1610 "  triangulation in which each PSLG segment may have been subdivided into\n");
1611   printf(
1612 "  several edges by the insertion of additional points.  These inserted\n");
1613   printf(
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");
1617   printf(
1618 "  All files may contain comments prefixed by the character '#'.  Points,\n");
1619   printf(
1620 "  triangles, edges, holes, and maximum area constraints must be numbered\n");
1621   printf(
1622 "  consecutively, starting from either 1 or 0.  Whichever you choose, all\n");
1623   printf(
1624 "  input files must be consistent; if the nodes are numbered from 1, so must\n"
1625 );
1626   printf(
1627 "  be all other objects.  Triangle automatically detects your choice while\n");
1628   printf(
1629 "  reading the .node (or .poly) file.  (When calling Triangle from another\n");
1630   printf(
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");
1634   printf(
1635 "    First line:  <# of points> <dimension (must be 2)> <# of attributes>\n");
1636   printf(
1637 "                                           <# of boundary markers (0 or 1)>\n"
1638 );
1639   printf(
1640 "    Remaining lines:  <point #> <x> <y> [attributes] [boundary marker]\n");
1641   printf("\n");
1642   printf(
1643 "    The attributes, which are typically floating-point values of physical\n");
1644   printf(
1645 "    quantities (such as mass or conductivity) associated with the nodes of\n"
1646 );
1647   printf(
1648 "    a finite element mesh, are copied unchanged to the output mesh.  If -s,\n"
1649 );
1650   printf(
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");
1653   printf(
1654 "    If the fourth entry of the first line is `1', the last column of the\n");
1655   printf(
1656 "    remainder of the file is assumed to contain boundary markers.  Boundary\n"
1657 );
1658   printf(
1659 "    markers are used to identify boundary points and points resting on PSLG\n"
1660 );
1661   printf(
1662 "    segments; a complete description appears in a section below.  The .node\n"
1663 );
1664   printf(
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");
1668   printf(
1669 "    First line:  <# of triangles> <points per triangle> <# of attributes>\n");
1670   printf(
1671 "    Remaining lines:  <triangle #> <point> <point> <point> ... [attributes]\n"
1672 );
1673   printf("\n");
1674   printf(
1675 "    Points are indices into the corresponding .node file.  The first three\n"
1676 );
1677   printf(
1678 "    points are the corners, and are listed in counterclockwise order around\n"
1679 );
1680   printf(
1681 "    each triangle.  (The remaining points, if any, depend on the type of\n");
1682   printf(
1683 "    finite element used.)  The attributes are just like those of .node\n");
1684   printf(
1685 "    files.  Because there is no simple mapping from input to output\n");
1686   printf(
1687 "    triangles, an attempt is made to interpolate attributes, which may\n");
1688   printf(
1689 "    result in a good deal of diffusion of attributes among nearby triangles\n"
1690 );
1691   printf(
1692 "    as the triangulation is refined.  Diffusion does not occur across\n");
1693   printf(
1694 "    segments, so attributes used to identify segment-bounded regions remain\n"
1695 );
1696   printf(
1697 "    intact.  In output .ele files, all triangles have three points each\n");
1698   printf(
1699 "    unless the -o2 switch is used, in which case they have six, and the\n");
1700   printf(
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");
1704   printf(
1705 "    First line:  <# of points> <dimension (must be 2)> <# of attributes>\n");
1706   printf(
1707 "                                           <# of boundary markers (0 or 1)>\n"
1708 );
1709   printf(
1710 "    Following lines:  <point #> <x> <y> [attributes] [boundary marker]\n");
1711   printf("    One line:  <# of segments> <# of boundary markers (0 or 1)>\n");
1712   printf(
1713 "    Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]\n");
1714   printf("    One line:  <# of holes>\n");
1715   printf("    Following lines:  <hole #> <x> <y>\n");
1716   printf(
1717 "    Optional line:  <# of regional attributes and/or area constraints>\n");
1718   printf(
1719 "    Optional following lines:  <constraint #> <x> <y> <attrib> <max area>\n");
1720   printf("\n");
1721   printf(
1722 "    A .poly file represents a PSLG, as well as some additional information.\n"
1723 );
1724   printf(
1725 "    The first section lists all the points, and is identical to the format\n"
1726 );
1727   printf(
1728 "    of .node files.  <# of points> may be set to zero to indicate that the\n"
1729 );
1730   printf(
1731 "    points are listed in a separate .node file; .poly files produced by\n");
1732   printf(
1733 "    Triangle always have this format.  This has the advantage that a point\n"
1734 );
1735   printf(
1736 "    set may easily be triangulated with or without segments.  (The same\n");
1737   printf(
1738 "    effect can be achieved, albeit using more disk space, by making a copy\n"
1739 );
1740   printf(
1741 "    of the .poly file with the extension .node; all sections of the file\n");
1742   printf("    but the first are ignored.)\n\n");
1743   printf(
1744 "    The second section lists the segments.  Segments are edges whose\n");
1745   printf(
1746 "    presence in the triangulation is enforced.  Each segment is specified\n");
1747   printf(
1748 "    by listing the indices of its two endpoints.  This means that you must\n"
1749 );
1750   printf(
1751 "    include its endpoints in the point list.  If -s, -q, and -a are not\n");
1752   printf(
1753 "    selected, Triangle will produce a constrained Delaunay triangulation,\n");
1754   printf(
1755 "    in which each segment appears as a single edge in the triangulation.\n");
1756   printf(
1757 "    If -q or -a is selected, Triangle will produce a conforming Delaunay\n");
1758   printf(
1759 "    triangulation, in which segments may be subdivided into smaller edges.\n"
1760 );
1761   printf("    Each segment, like each point, may have a boundary marker.\n\n");
1762   printf(
1763 "    The third section lists holes (and concavities, if -c is selected) in\n");
1764   printf(
1765 "    the triangulation.  Holes are specified by identifying a point inside\n");
1766   printf(
1767 "    each hole.  After the triangulation is formed, Triangle creates holes\n");
1768   printf(
1769 "    by eating triangles, spreading out from each hole point until its\n");
1770   printf(
1771 "    progress is blocked by PSLG segments; you must be careful to enclose\n");
1772   printf(
1773 "    each hole in segments, or your whole triangulation may be eaten away.\n");
1774   printf(
1775 "    If the two triangles abutting a segment are eaten, the segment itself\n");
1776   printf(
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");
1779   printf(
1780 "    The optional fourth section lists regional attributes (to be assigned\n");
1781   printf(
1782 "    to all triangles in a region) and regional constraints on the maximum\n");
1783   printf(
1784 "    triangle area.  Triangle will read this section only if the -A switch\n");
1785   printf(
1786 "    is used or the -a switch is used without a number following it, and the\n"
1787 );
1788   printf(
1789 "    -r switch is not used.  Regional attributes and area constraints are\n");
1790   printf(
1791 "    propagated in the same manner as holes; you specify a point for each\n");
1792   printf(
1793 "    attribute and/or constraint, and the attribute and/or constraint will\n");
1794   printf(
1795 "    affect the whole region (bounded by segments) containing the point.  If\n"
1796 );
1797   printf(
1798 "    two values are written on a line after the x and y coordinate, the\n");
1799   printf(
1800 "    former is assumed to be a regional attribute (but will only be applied\n"
1801 );
1802   printf(
1803 "    if the -A switch is selected), and the latter is assumed to be a\n");
1804   printf(
1805 "    regional area constraint (but will only be applied if the -a switch is\n"
1806 );
1807   printf(
1808 "    selected).  You may also specify just one value after the coordinates,\n"
1809 );
1810   printf(
1811 "    which can serve as both an attribute and an area constraint, depending\n"
1812 );
1813   printf(
1814 "    on the choice of switches.  If you are using the -A and -a switches\n");
1815   printf(
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");
1818   printf(
1819 "    When a triangulation is created from a .poly file, you must either\n");
1820   printf(
1821 "    enclose the entire region to be triangulated in PSLG segments, or\n");
1822   printf(
1823 "    use the -c switch, which encloses the convex hull of the input point\n");
1824   printf(
1825 "    set.  If you do not use the -c switch, Triangle will eat all triangles\n"
1826 );
1827   printf(
1828 "    on the outer boundary that are not protected by segments; if you are\n");
1829   printf(
1830 "    not careful, your whole triangulation may be eaten away.  If you do\n");
1831   printf(
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");
1834   printf(
1835 "    An ideal PSLG has no intersecting segments, nor any points that lie\n");
1836   printf(
1837 "    upon segments (except, of course, the endpoints of each segment.)  You\n"
1838 );
1839   printf(
1840 "    aren't required to make your .poly files ideal, but you should be aware\n"
1841 );
1842   printf(
1843 "    of what can go wrong.  Segment intersections are relatively safe -\n");
1844   printf(
1845 "    Triangle will calculate the intersection points for you and add them to\n"
1846 );
1847   printf(
1848 "    the triangulation - as long as your machine's floating-point precision\n"
1849 );
1850   printf(
1851 "    doesn't become a problem.  You are tempting the fates if you have three\n"
1852 );
1853   printf(
1854 "    segments that cross at the same location, and expect Triangle to figure\n"
1855 );
1856   printf(
1857 "    out where the intersection point is.  Thanks to floating-point roundoff\n"
1858 );
1859   printf(
1860 "    error, Triangle will probably decide that the three segments intersect\n"
1861 );
1862   printf(
1863 "    at three different points, and you will find a minuscule triangle in\n");
1864   printf(
1865 "    your output - unless Triangle tries to refine the tiny triangle, uses\n");
1866   printf(
1867 "    up the last bit of machine precision, and fails to terminate at all.\n");
1868   printf(
1869 "    You're better off putting the intersection point in the input files,\n");
1870   printf(
1871 "    and manually breaking up each segment into two.  Similarly, if you\n");
1872   printf(
1873 "    place a point at the middle of a segment, and hope that Triangle will\n");
1874   printf(
1875 "    break up the segment at that point, you might get lucky.  On the other\n"
1876 );
1877   printf(
1878 "    hand, Triangle might decide that the point doesn't lie precisely on the\n"
1879 );
1880   printf(
1881 "    line, and you'll have a needle-sharp triangle in your output - or a lot\n"
1882 );
1883   printf("    of tiny triangles if you're generating a quality mesh.\n\n");
1884   printf(
1885 "    When Triangle reads a .poly file, it also writes a .poly file, which\n");
1886   printf(
1887 "    includes all edges that are part of input segments.  If the -c switch\n");
1888   printf(
1889 "    is used, the output .poly file will also include all of the edges on\n");
1890   printf(
1891 "    the convex hull.  Hence, the output .poly file is useful for finding\n");
1892   printf(
1893 "    edges associated with input segments and setting boundary conditions in\n"
1894 );
1895   printf(
1896 "    finite element simulations.  More importantly, you will need it if you\n"
1897 );
1898   printf(
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");
1904   printf(
1905 "    An .area file associates with each triangle a maximum area that is used\n"
1906 );
1907   printf(
1908 "    for mesh refinement.  As with other file formats, every triangle must\n");
1909   printf(
1910 "    be represented, and they must be numbered consecutively.  A triangle\n");
1911   printf(
1912 "    may be left unconstrained by assigning it a negative maximum area.\n");
1913   printf("\n");
1914   printf("  .edge files:\n");
1915   printf("    First line:  <# of edges> <# of boundary markers (0 or 1)>\n");
1916   printf(
1917 "    Following lines:  <edge #> <endpoint> <endpoint> [boundary marker]\n");
1918   printf("\n");
1919   printf(
1920 "    Endpoints are indices into the corresponding .node file.  Triangle can\n"
1921 );
1922   printf(
1923 "    produce .edge files (use the -e switch), but cannot read them.  The\n");
1924   printf(
1925 "    optional column of boundary markers is suppressed by the -B switch.\n");
1926   printf("\n");
1927   printf(
1928 "    In Voronoi diagrams, one also finds a special kind of edge that is an\n");
1929   printf(
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");
1933   printf(
1934 "    The `direction' is a floating-point vector that indicates the direction\n"
1935 );
1936   printf("    of the infinite ray.\n\n");
1937   printf("  .neigh files:\n");
1938   printf(
1939 "    First line:  <# of triangles> <# of neighbors per triangle (always 3)>\n"
1940 );
1941   printf(
1942 "    Following lines:  <triangle #> <neighbor> <neighbor> <neighbor>\n");
1943   printf("\n");
1944   printf(
1945 "    Neighbors are indices into the corresponding .ele file.  An index of -1\n"
1946 );
1947   printf(
1948 "    indicates a mesh boundary, and therefore no neighbor.  Triangle can\n");
1949   printf(
1950 "    produce .neigh files (use the -n switch), but cannot read them.\n");
1951   printf("\n");
1952   printf(
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");
1956   printf(
1957 "  Boundary markers are tags used mainly to identify which output points and\n"
1958 );
1959   printf(
1960 "  edges are associated with which PSLG segment, and to identify which\n");
1961   printf(
1962 "  points and edges occur on a boundary of the triangulation.  A common use\n"
1963 );
1964   printf(
1965 "  is to determine where boundary conditions should be applied to a finite\n");
1966   printf(
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");
1969   printf(
1970 "  The boundary marker associated with each segment in an output .poly file\n"
1971 );
1972   printf("  or edge in an output .edge file is chosen as follows:\n");
1973   printf(
1974 "    - If an output edge is part or all of a PSLG segment with a nonzero\n");
1975   printf(
1976 "      boundary marker, then the edge is assigned the same marker.\n");
1977   printf(
1978 "    - Otherwise, if the edge occurs on a boundary of the triangulation\n");
1979   printf(
1980 "      (including boundaries of holes), then the edge is assigned the marker\n"
1981 );
1982   printf("      one (1).\n");
1983   printf("    - Otherwise, the edge is assigned the marker zero (0).\n");
1984   printf(
1985 "  The boundary marker associated with each point in an output .node file is\n"
1986 );
1987   printf("  chosen as follows:\n");
1988   printf(
1989 "    - If a point is assigned a nonzero boundary marker in the input file,\n");
1990   printf(
1991 "      then it is assigned the same marker in the output .node file.\n");
1992   printf(
1993 "    - Otherwise, if the point lies on a PSLG segment (including the\n");
1994   printf(
1995 "      segment's endpoints) with a nonzero boundary marker, then the point\n");
1996   printf(
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");
1999   printf(
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");
2003   printf("\n");
2004   printf(
2005 "  If you want Triangle to determine for you which points and edges are on\n");
2006   printf(
2007 "  the boundary, assign them the boundary marker zero (or use no markers at\n"
2008 );
2009   printf(
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");
2013   printf(
2014 "  Because Triangle can read and refine its own triangulations, input\n");
2015   printf(
2016 "  and output files have iteration numbers.  For instance, Triangle might\n");
2017   printf(
2018 "  read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
2019   printf(
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");
2022   printf(
2023 "  their iteration number is zero; hence, Triangle might read the file\n");
2024   printf(
2025 "  points.node, triangulate it, and produce the files points.1.node and\n");
2026   printf("  points.1.ele.\n\n");
2027   printf(
2028 "  Iteration numbers allow you to create a sequence of successively finer\n");
2029   printf(
2030 "  meshes suitable for multigrid methods.  They also allow you to produce a\n"
2031 );
2032   printf(
2033 "  sequence of meshes using error estimate-driven mesh refinement.\n");
2034   printf("\n");
2035   printf(
2036 "  If you're not using refinement or quality meshing, and you don't like\n");
2037   printf(
2038 "  iteration numbers, use the -I switch to disable them.  This switch will\n");
2039   printf(
2040 "  also disable output of .node and .poly files to prevent your input files\n"
2041 );
2042   printf(
2043 "  from being overwritten.  (If the input is a .poly file that contains its\n"
2044 );
2045   printf("  own points, a .node file will be written.)\n\n");
2046   printf("Examples of How to Use Triangle:\n\n");
2047   printf(
2048 "  `triangle dots' will read points from dots.node, and write their Delaunay\n"
2049 );
2050   printf(
2051 "  triangulation to dots.1.node and dots.1.ele.  (dots.1.node will be\n");
2052   printf(
2053 "  identical to dots.node.)  `triangle -I dots' writes the triangulation to\n"
2054 );
2055   printf(
2056 "  dots.ele instead.  (No additional .node file is needed, so none is\n");
2057   printf("  written.)\n\n");
2058   printf(
2059 "  `triangle -pe object.1' will read a PSLG from object.1.poly (and possibly\n"
2060 );
2061   printf(
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");
2064   printf(
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");
2067   printf(
2068 "  `triangle -pq31.5a.1 object' will read a PSLG from object.poly (and\n");
2069   printf(
2070 "  possibly object.node), generate a mesh whose angles are all greater than\n"
2071 );
2072   printf(
2073 "  31.5 degrees and whose triangles all have area smaller than 0.1, and\n");
2074   printf(
2075 "  write the mesh to object.1.node and object.1.ele.  Each segment may have\n"
2076 );
2077   printf(
2078 "  been broken up into multiple edges; the resulting constrained edges are\n");
2079   printf("  written to object.1.poly.\n\n");
2080   printf(
2081 "  Here is a sample file `box.poly' describing a square with a square hole:\n"
2082 );
2083   printf("\n");
2084   printf(
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");
2098   printf("    5 1\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");
2105   printf("    1\n");
2106   printf("     1   1.5 1.5\n\n");
2107   printf(
2108 "  Note that some segments are missing from the outer square, so one must\n");
2109   printf(
2110 "  use the `-c' switch.  After `triangle -pqc box.poly', here is the output\n"
2111 );
2112   printf(
2113 "  file `box.1.node', with twelve points.  The last four points were added\n");
2114   printf(
2115 "  to meet the angle constraint.  Points 1, 2, and 9 have markers from\n");
2116   printf(
2117 "  segment 1.  Points 6 and 8 have markers from segment 4.  All the other\n");
2118   printf(
2119 "  points but 4 have been marked to indicate that they lie on a boundary.\n");
2120   printf("\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");
2150   printf(
2151 "  Here is the output file `box.1.poly'.  Note that segments have been added\n"
2152 );
2153   printf(
2154 "  to represent the convex hull, and some segments have been split by newly\n"
2155 );
2156   printf(
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");
2160   printf("    12  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");
2173   printf("    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");
2177   printf(
2178 "  The -r switch causes a mesh (.node and .ele files) to be read and\n");
2179   printf(
2180 "  refined.  If the -p switch is also used, a .poly file is read and used to\n"
2181 );
2182   printf(
2183 "  specify edges that are constrained and cannot be eliminated (although\n");
2184   printf(
2185 "  they can be divided into smaller edges) by the refinement process.\n");
2186   printf("\n");
2187   printf(
2188 "  When you refine a mesh, you generally want to impose tighter quality\n");
2189   printf(
2190 "  constraints.  One way to accomplish this is to use -q with a larger\n");
2191   printf(
2192 "  angle, or -a followed by a smaller area than you used to generate the\n");
2193   printf(
2194 "  mesh you are refining.  Another way to do this is to create an .area\n");
2195   printf(
2196 "  file, which specifies a maximum area for each triangle, and use the -a\n");
2197   printf(
2198 "  switch (without a number following).  Each triangle's area constraint is\n"
2199 );
2200   printf(
2201 "  applied to that triangle.  Area constraints tend to diffuse as the mesh\n");
2202   printf(
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");
2205   printf(
2206 "  If you are refining a mesh composed of linear (three-node) elements, the\n"
2207 );
2208   printf(
2209 "  output mesh will contain all the nodes present in the input mesh, in the\n"
2210 );
2211   printf(
2212 "  same order, with new nodes added at the end of the .node file.  However,\n"
2213 );
2214   printf(
2215 "  there is no guarantee that each output element is contained in a single\n");
2216   printf(
2217 "  input element.  Often, output elements will overlap two input elements,\n");
2218   printf(
2219 "  and input edges are not present in the output mesh.  Hence, a sequence of\n"
2220 );
2221   printf(
2222 "  refined meshes will form a hierarchy of nodes, but not a hierarchy of\n");
2223   printf(
2224 "  elements.  If you a refining a mesh of higher-order elements, the\n");
2225   printf(
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");
2228   printf(
2229 "  It is important to understand that maximum area constraints in .poly\n");
2230   printf(
2231 "  files are handled differently from those in .area files.  A maximum area\n"
2232 );
2233   printf(
2234 "  in a .poly file applies to the whole (segment-bounded) region in which a\n"
2235 );
2236   printf(
2237 "  point falls, whereas a maximum area in an .area file applies to only one\n"
2238 );
2239   printf(
2240 "  triangle.  Area constraints in .poly files are used only when a mesh is\n");
2241   printf(
2242 "  first generated, whereas area constraints in .area files are used only to\n"
2243 );
2244   printf(
2245 "  refine an existing mesh, and are typically based on a posteriori error\n");
2246   printf(
2247 "  estimates resulting from a finite element simulation on that mesh.\n");
2248   printf("\n");
2249   printf(
2250 "  `triangle -rq25 object.1' will read object.1.node and object.1.ele, then\n"
2251 );
2252   printf(
2253 "  refine the triangulation to enforce a 25 degree minimum angle, and then\n");
2254   printf(
2255 "  write the refined triangulation to object.2.node and object.2.ele.\n");
2256   printf("\n");
2257   printf(
2258 "  `triangle -rpaa6.2 z.3' will read z.3.node, z.3.ele, z.3.poly, and\n");
2259   printf(
2260 "  z.3.area.  After reconstructing the mesh and its segments, Triangle will\n"
2261 );
2262   printf(
2263 "  refine the mesh so that no triangle has area greater than 6.2, and\n");
2264   printf(
2265 "  furthermore the triangles satisfy the maximum area constraints in\n");
2266   printf(
2267 "  z.3.area.  The output is written to z.4.node, z.4.ele, and z.4.poly.\n");
2268   printf("\n");
2269   printf(
2270 "  The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
2271   printf(
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");
2275   printf(
2276 "  If the input is a point set (rather than a PSLG), Triangle produces its\n");
2277   printf(
2278 "  convex hull as a by-product in the output .poly file if you use the -c\n");
2279   printf(
2280 "  switch.  There are faster algorithms for finding a two-dimensional convex\n"
2281 );
2282   printf(
2283 "  hull than triangulation, of course, but this one comes for free.  If the\n"
2284 );
2285   printf(
2286 "  input is an unconstrained mesh (you are using the -r switch but not the\n");
2287   printf(
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");
2291   printf(
2292 "  The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
2293   printf(
2294 "  .v.edge.  For example, `triangle -v points' will read points.node,\n");
2295   printf(
2296 "  produce its Delaunay triangulation in points.1.node and points.1.ele,\n");
2297   printf(
2298 "  and produce its Voronoi diagram in points.1.v.node and points.1.v.edge.\n");
2299   printf(
2300 "  The .v.node file contains a list of all Voronoi vertices, and the .v.edge\n"
2301 );
2302   printf(
2303 "  file contains a list of all Voronoi edges, some of which may be infinite\n"
2304 );
2305   printf(
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");
2308   printf(
2309 "  This implementation does not use exact arithmetic to compute the Voronoi\n"
2310 );
2311   printf(
2312 "  vertices, and does not check whether neighboring vertices are identical.\n"
2313 );
2314   printf(
2315 "  Be forewarned that if the Delaunay triangulation is degenerate or\n");
2316   printf(
2317 "  near-degenerate, the Voronoi diagram may have duplicate points, crossing\n"
2318 );
2319   printf(
2320 "  edges, or infinite rays whose direction vector is zero.  Also, if you\n");
2321   printf(
2322 "  generate a constrained (as opposed to conforming) Delaunay triangulation,\n"
2323 );
2324   printf(
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");
2328   printf(
2329 "  You may wish to know which triangles are adjacent to a certain Delaunay\n");
2330   printf(
2331 "  edge in an .edge file, which Voronoi regions are adjacent to a certain\n");
2332   printf(
2333 "  Voronoi edge in a .v.edge file, or which Voronoi regions are adjacent to\n"
2334 );
2335   printf(
2336 "  each other.  All of this information can be found by cross-referencing\n");
2337   printf(
2338 "  output files with the recollection that the Delaunay triangulation and\n");
2339   printf("  the Voronoi diagrams are planar duals.\n\n");
2340   printf(
2341 "  Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
2342   printf(
2343 "  the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
2344   printf(
2345 "  wise from the Voronoi edge.  Triangle j of an .ele file is the dual of\n");
2346   printf(
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");
2349   printf(
2350 "  Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
2351   printf(
2352 "  vertices of the corresponding Voronoi edge; their dual triangles are on\n");
2353   printf(
2354 "  the left and right of the Delaunay edge, respectively.  To find the\n");
2355   printf(
2356 "  Voronoi regions adjacent to a Voronoi edge, look at the endpoints of the\n"
2357 );
2358   printf(
2359 "  corresponding Delaunay edge; their dual regions are on the right and left\n"
2360 );
2361   printf(
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");
2364   printf("\n");
2365   printf("Statistics:\n");
2366   printf("\n");
2367   printf(
2368 "  After generating a mesh, Triangle prints a count of the number of points,\n"
2369 );
2370   printf(
2371 "  triangles, edges, boundary edges, and segments in the output mesh.  If\n");
2372   printf(
2373 "  you've forgotten the statistics for an existing mesh, the -rNEP switches\n"
2374 );
2375   printf(
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");
2378   printf(
2379 "  The -V switch produces extended statistics, including a rough estimate\n");
2380   printf(
2381 "  of memory use and a histogram of triangle aspect ratios and angles in the\n"
2382 );
2383   printf("  mesh.\n\n");
2384   printf("Exact Arithmetic:\n\n");
2385   printf(
2386 "  Triangle uses adaptive exact arithmetic to perform what computational\n");
2387   printf(
2388 "  geometers call the `orientation' and `incircle' tests.  If the floating-\n"
2389 );
2390   printf(
2391 "  point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
2392   printf(
2393 "  most workstations do), and does not use extended precision internal\n");
2394   printf(
2395 "  registers, then your output is guaranteed to be an absolutely true\n");
2396   printf("  Delaunay or conforming Delaunay triangulation, roundoff error\n");
2397   printf(
2398 "  notwithstanding.  The word `adaptive' implies that these arithmetic\n");
2399   printf(
2400 "  routines compute the result only to the precision necessary to guarantee\n"
2401 );
2402   printf(
2403 "  correctness, so they are usually nearly as fast as their approximate\n");
2404   printf(
2405 "  counterparts.  The exact tests can be disabled with the -X switch.  On\n");
2406   printf(
2407 "  most inputs, this switch will reduce the computation time by about eight\n"
2408 );
2409   printf(
2410 "  percent - it's not worth the risk.  There are rare difficult inputs\n");
2411   printf(
2412 "  (having many collinear and cocircular points), however, for which the\n");
2413   printf(
2414 "  difference could be a factor of two.  These are precisely the inputs most\n"
2415 );
2416   printf("  likely to cause errors if you use the -X switch.\n\n");
2417   printf(
2418 "  Unfortunately, these routines don't solve every numerical problem.  Exact\n"
2419 );
2420   printf(
2421 "  arithmetic is not used to compute the positions of points, because the\n");
2422   printf(
2423 "  bit complexity of point coordinates would grow without bound.  Hence,\n");
2424   printf(
2425 "  segment intersections aren't computed exactly; in very unusual cases,\n");
2426   printf(
2427 "  roundoff error in computing an intersection point might actually lead to\n"
2428 );
2429   printf(
2430 "  an inverted triangle and an invalid triangulation.  (This is one reason\n");
2431   printf(
2432 "  to compute your own intersection points in your .poly files.)  Similarly,\n"
2433 );
2434   printf(
2435 "  exact arithmetic is not used to compute the vertices of the Voronoi\n");
2436   printf("  diagram.\n\n");
2437   printf(
2438 "  Underflow and overflow can also cause difficulties; the exact arithmetic\n"
2439 );
2440   printf(
2441 "  routines do not ameliorate out-of-bounds exponents, which can arise\n");
2442   printf(
2443 "  during the orientation and incircle tests.  As a rule of thumb, you\n");
2444   printf(
2445 "  should ensure that your input values are within a range such that their\n");
2446   printf(
2447 "  third powers can be taken without underflow or overflow.  Underflow can\n");
2448   printf(
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");
2456   printf(
2457 "    If you're using a PSLG, you've probably failed to specify a proper set\n"
2458 );
2459   printf(
2460 "    of bounding segments, or forgotten to use the -c switch.  Or you may\n");
2461   printf(
2462 "    have placed a hole badly.  To test these possibilities, try again with\n"
2463 );
2464   printf(
2465 "    the -c and -O switches.  Alternatively, all your input points may be\n");
2466   printf(
2467 "    collinear, in which case you can hardly expect to triangulate them.\n");
2468   printf("\n");
2469   printf("  `Triangle doesn't terminate, or just crashes.'\n");
2470   printf("\n");
2471   printf(
2472 "    Bad things can happen when triangles get so small that the distance\n");
2473   printf(
2474 "    between their vertices isn't much larger than the precision of your\n");
2475   printf(
2476 "    machine's arithmetic.  If you've compiled Triangle for single-precision\n"
2477 );
2478   printf(
2479 "    arithmetic, you might do better by recompiling it for double-precision.\n"
2480 );
2481   printf(
2482 "    Then again, you might just have to settle for more lenient constraints\n"
2483 );
2484   printf(
2485 "    on the minimum angle and the maximum area than you had planned.\n");
2486   printf("\n");
2487   printf(
2488 "    You can minimize precision problems by ensuring that the origin lies\n");
2489   printf(
2490 "    inside your point set, or even inside the densest part of your\n");
2491   printf(
2492 "    mesh.  On the other hand, if you're triangulating an object whose x\n");
2493   printf(
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");
2496   printf(
2497 "    Precision problems can occur covertly if the input PSLG contains two\n");
2498   printf(
2499 "    segments that meet (or intersect) at a very small angle, or if such an\n"
2500 );
2501   printf(
2502 "    angle is introduced by the -c switch, which may occur if a point lies\n");
2503   printf(
2504 "    ever-so-slightly inside the convex hull, and is connected by a PSLG\n");
2505   printf(
2506 "    segment to a point on the convex hull.  If you don't realize that a\n");
2507   printf(
2508 "    small angle is being formed, you might never discover why Triangle is\n");
2509   printf(
2510 "    crashing.  To check for this possibility, use the -S switch (with an\n");
2511   printf(
2512 "    appropriate limit on the number of Steiner points, found by trial-and-\n"
2513 );
2514   printf(
2515 "    error) to stop Triangle early, and view the output .poly file with\n");
2516   printf(
2517 "    Show Me (described below).  Look carefully for small angles between\n");
2518   printf(
2519 "    segments; zoom in closely, as such segments might look like a single\n");
2520   printf("    segment from a distance.\n\n");
2521   printf(
2522 "    If some of the input values are too large, Triangle may suffer a\n");
2523   printf(
2524 "    floating exception due to overflow when attempting to perform an\n");
2525   printf(
2526 "    orientation or incircle test.  (Read the section on exact arithmetic\n");
2527   printf(
2528 "    above.)  Again, I recommend compiling Triangle for double (rather\n");
2529   printf("    than single) precision arithmetic.\n\n");
2530   printf(
2531 "  `The numbering of the output points doesn't match the input points.'\n");
2532   printf("\n");
2533   printf(
2534 "    You may have eaten some of your input points with a hole, or by placing\n"
2535 );
2536   printf("    them outside the area enclosed by segments.\n\n");
2537   printf(
2538 "  `Triangle executes without incident, but when I look at the resulting\n");
2539   printf(
2540 "  mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
2541   printf("\n");
2542   printf(
2543 "    If you select the -X switch, Triangle's divide-and-conquer Delaunay\n");
2544   printf(
2545 "    triangulation algorithm occasionally makes mistakes due to floating-\n");
2546   printf(
2547 "    point roundoff error.  Although these errors are rare, don't use the -X\n"
2548 );
2549   printf("    switch.  If you still have problems, please report the bug.\n");
2550   printf("\n");
2551   printf(
2552 "  Strange things can happen if you've taken liberties with your PSLG.  Do\n");
2553   printf(
2554 "  you have a point lying in the middle of a segment?  Triangle sometimes\n");
2555   printf(
2556 "  copes poorly with that sort of thing.  Do you want to lay out a collinear\n"
2557 );
2558   printf(
2559 "  row of evenly spaced, segment-connected points?  Have you simply defined\n"
2560 );
2561   printf(
2562 "  one long segment connecting the leftmost point to the rightmost point,\n");
2563   printf(
2564 "  and a bunch of points lying along it?  This method occasionally works,\n");
2565   printf(
2566 "  especially with horizontal and vertical lines, but often it doesn't, and\n"
2567 );
2568   printf(
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");
2571   printf(
2572 "  Furthermore, if you have segments that intersect other than at their\n");
2573   printf(
2574 "  endpoints, try not to let the intersections fall extremely close to PSLG\n"
2575 );
2576   printf("  points or each other.\n\n");
2577   printf(
2578 "  If you have problems refining a triangulation not produced by Triangle:\n");
2579   printf(
2580 "  Are you sure the triangulation is geometrically valid?  Is it formatted\n");
2581   printf(
2582 "  correctly for Triangle?  Are the triangles all listed so the first three\n"
2583 );
2584   printf("  points are their corners in counterclockwise order?\n\n");
2585   printf("Show Me:\n\n");
2586   printf(
2587 "  Triangle comes with a separate program named `Show Me', whose primary\n");
2588   printf(
2589 "  purpose is to draw meshes on your screen or in PostScript.  Its secondary\n"
2590 );
2591   printf(
2592 "  purpose is to check the validity of your input files, and do so more\n");
2593   printf(
2594 "  thoroughly than Triangle does.  Show Me requires that you have the X\n");
2595   printf(
2596 "  Windows system.  If you didn't receive Show Me with Triangle, complain to\n"
2597 );
2598   printf("  whomever you obtained Triangle from, then send me mail.\n\n");
2599   printf("Triangle on the Web:\n\n");
2600   printf(
2601 "  To see an illustrated, updated version of these instructions, check out\n");
2602   printf("\n");
2603   printf("    http://www.cs.cmu.edu/~quake/triangle.html\n");
2604   printf("\n");
2605   printf("A Brief Plea:\n");
2606   printf("\n");
2607   printf(
2608 "  If you use Triangle, and especially if you use it to accomplish real\n");
2609   printf(
2610 "  work, I would like very much to hear from you.  A short letter or email\n");
2611   printf(
2612 "  (to jrs@cs.cmu.edu) describing how you use Triangle will mean a lot to\n");
2613   printf(
2614 "  me.  The more people I know are using this program, the more easily I can\n"
2615 );
2616   printf(
2617 "  justify spending time on improvements and on the three-dimensional\n");
2618   printf(
2619 "  successor to Triangle, which in turn will benefit you.  Also, I can put\n");
2620   printf(
2621 "  you on a list to receive email whenever a new version of Triangle is\n");
2622   printf("  available.\n\n");
2623   printf(
2624 "  If you use a mesh generated by Triangle in a publication, please include\n"
2625 );
2626   printf("  an acknowledgment as well.\n\n");
2627   printf("Research credit:\n\n");
2628   printf(
2629 "  Of course, I can take credit for only a fraction of the ideas that made\n");
2630   printf(
2631 "  this mesh generator possible.  Triangle owes its existence to the efforts\n"
2632 );
2633   printf(
2634 "  of many fine computational geometers and other researchers, including\n");
2635   printf(
2636 "  Marshall Bern, L. Paul Chew, Boris Delaunay, Rex A. Dwyer, David\n");
2637   printf(
2638 "  Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E. Knuth, C. L.\n");
2639   printf(
2640 "  Lawson, Der-Tsai Lee, Ernst P. Mucke, Douglas M. Priest, Jim Ruppert,\n");
2641   printf(
2642 "  Isaac Saias, Bruce J. Schachter, Micha Sharir, Jorge Stolfi, Christopher\n"
2643 );
2644   printf(
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");
2647   exit(0);
2648 }
2649
2650 #endif /* not TRILIBRARY */
2651
2652 /*****************************************************************************/
2653 /*                                                                           */
2654 /*  internalerror()   Ask the user to send me the defective product.  Exit.  */
2655 /*                                                                           */
2656 /*****************************************************************************/
2657
2658 void internalerror()
2659 {
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");
2663   exit(1);
2664 }
2665
2666 /*****************************************************************************/
2667 /*                                                                           */
2668 /*  parsecommandline()   Read the command line, identify switches, and set   */
2669 /*                       up options and file names.                          */
2670 /*                                                                           */
2671 /*  The effects of this routine are felt entirely through global variables.  */
2672 /*                                                                           */
2673 /*****************************************************************************/
2674
2675 void parsecommandline(argc, argv)
2676 int argc;
2677 char **argv;
2678 {
2679 #ifdef TRILIBRARY
2680 #define STARTINDEX 0
2681 #else /* not TRILIBRARY */
2682 #define STARTINDEX 1
2683   int increment;
2684   int meshnumber;
2685 #endif /* not TRILIBRARY */
2686   int i, j;
2687 #ifndef CDT_ONLY
2688   int k;
2689   char workstring[FILENAMESIZE];
2690 #endif
2691
2692   poly = refine = quality = vararea = fixedarea = regionattrib = convex = 0;
2693   firstnumber = 1;
2694   edgesout = voronoi = neighbors = geomview = 0;
2695   nobound = nopolywritten = nonodewritten = noelewritten = noiterationnum = 0;
2696   noholes = noexact = 0;
2697   incremental = sweepline = 0;
2698   dwyer = 1;
2699   splitseg = 0;
2700   docheck = 0;
2701   nobisect = 0;
2702   steiner = -1;
2703   order = 1;
2704   minangle = 0.0;
2705   maxarea = -1.0;
2706   quiet = verbose = 0;
2707 #ifndef TRILIBRARY
2708   innodefilename[0] = '\0';
2709 #endif /* not TRILIBRARY */
2710
2711   for (i = STARTINDEX; i < argc; i++) {
2712 #ifndef TRILIBRARY
2713     if (argv[i][0] == '-') {
2714 #endif /* not TRILIBRARY */
2715       for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
2716         if (argv[i][j] == 'p') {
2717           poly = 1;
2718         }
2719 #ifndef CDT_ONLY
2720         if (argv[i][j] == 'r') {
2721           refine = 1;
2722         }
2723         if (argv[i][j] == 'q') {
2724           quality = 1;
2725           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2726               (argv[i][j + 1] == '.')) {
2727             k = 0;
2728             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2729                    (argv[i][j + 1] == '.')) {
2730               j++;
2731               workstring[k] = argv[i][j];
2732               k++;
2733             }
2734             workstring[k] = '\0';
2735             minangle = (REAL) strtod(workstring, (char **) NULL);
2736           } else {
2737             minangle = 20.0;
2738           }
2739         }
2740         if (argv[i][j] == 'a') {
2741           quality = 1;
2742           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2743               (argv[i][j + 1] == '.')) {
2744             fixedarea = 1;
2745             k = 0;
2746             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
2747                    (argv[i][j + 1] == '.')) {
2748               j++;
2749               workstring[k] = argv[i][j];
2750               k++;
2751             }
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");
2756               exit(1);
2757             }
2758           } else {
2759             vararea = 1;
2760           }
2761         }
2762 #endif /* not CDT_ONLY */
2763         if (argv[i][j] == 'A') {
2764           regionattrib = 1;
2765         }
2766         if (argv[i][j] == 'c') {
2767           convex = 1;
2768         }
2769         if (argv[i][j] == 'z') {
2770           firstnumber = 0;
2771         }
2772         if (argv[i][j] == 'e') {
2773           edgesout = 1;
2774         }
2775         if (argv[i][j] == 'v') {
2776           voronoi = 1;
2777         }
2778         if (argv[i][j] == 'n') {
2779           neighbors = 1;
2780         }
2781         if (argv[i][j] == 'g') {
2782           geomview = 1;
2783         }
2784         if (argv[i][j] == 'B') {
2785           nobound = 1;
2786         }
2787         if (argv[i][j] == 'P') {
2788           nopolywritten = 1;
2789         }
2790         if (argv[i][j] == 'N') {
2791           nonodewritten = 1;
2792         }
2793         if (argv[i][j] == 'E') {
2794           noelewritten = 1;
2795         }
2796 #ifndef TRILIBRARY
2797         if (argv[i][j] == 'I') {
2798           noiterationnum = 1;
2799         }
2800 #endif /* not TRILIBRARY */
2801         if (argv[i][j] == 'O') {
2802           noholes = 1;
2803         }
2804         if (argv[i][j] == 'X') {
2805           noexact = 1;
2806         }
2807         if (argv[i][j] == 'o') {
2808           if (argv[i][j + 1] == '2') {
2809             j++;
2810             order = 2;
2811           }
2812         }
2813 #ifndef CDT_ONLY
2814         if (argv[i][j] == 'Y') {
2815           nobisect++;
2816         }
2817         if (argv[i][j] == 'S') {
2818           steiner = 0;
2819           while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
2820             j++;
2821             steiner = steiner * 10 + (int) (argv[i][j] - '0');
2822           }
2823         }
2824 #endif /* not CDT_ONLY */
2825 #ifndef REDUCED
2826         if (argv[i][j] == 'i') {
2827           incremental = 1;
2828         }
2829         if (argv[i][j] == 'F') {
2830           sweepline = 1;
2831         }
2832 #endif /* not REDUCED */
2833         if (argv[i][j] == 'l') {
2834           dwyer = 0;
2835         }
2836 #ifndef REDUCED
2837 #ifndef CDT_ONLY
2838         if (argv[i][j] == 's') {
2839           splitseg = 1;
2840         }
2841 #endif /* not CDT_ONLY */
2842         if (argv[i][j] == 'C') {
2843           docheck = 1;
2844         }
2845 #endif /* not REDUCED */
2846         if (argv[i][j] == 'Q') {
2847           quiet = 1;
2848         }
2849         if (argv[i][j] == 'V') {
2850           verbose++;
2851         }
2852 #ifndef TRILIBRARY
2853         if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
2854             (argv[i][j] == '?')) {
2855           info();
2856         }
2857 #endif /* not TRILIBRARY */
2858       }
2859 #ifndef TRILIBRARY
2860     } else {
2861       strncpy(innodefilename, argv[i], FILENAMESIZE - 1);
2862       innodefilename[FILENAMESIZE - 1] = '\0';
2863     }
2864 #endif /* not TRILIBRARY */
2865   }
2866 #ifndef TRILIBRARY
2867   if (innodefilename[0] == '\0') {
2868     syntax();
2869   }
2870   if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".node")) {
2871     innodefilename[strlen(innodefilename) - 5] = '\0';
2872   }
2873   if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".poly")) {
2874     innodefilename[strlen(innodefilename) - 5] = '\0';
2875     poly = 1;
2876   }
2877 #ifndef CDT_ONLY
2878   if (!strcmp(&innodefilename[strlen(innodefilename) - 4], ".ele")) {
2879     innodefilename[strlen(innodefilename) - 4] = '\0';
2880     refine = 1;
2881   }
2882   if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".area")) {
2883     innodefilename[strlen(innodefilename) - 5] = '\0';
2884     refine = 1;
2885     quality = 1;
2886     vararea = 1;
2887   }
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) {
2895     printf(
2896       "Error:  You cannot use the -I switch when refining a triangulation.\n");
2897     exit(1);
2898   }
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) {
2902     vararea = 0;
2903   }
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) {
2907     regionattrib = 0;
2908   }
2909
2910 #ifndef TRILIBRARY
2911   strcpy(inpolyfilename, innodefilename);
2912   strcpy(inelefilename, innodefilename);
2913   strcpy(areafilename, innodefilename);
2914   increment = 0;
2915   strcpy(workstring, innodefilename);
2916   j = 1;
2917   while (workstring[j] != '\0') {
2918     if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
2919       increment = j + 1;
2920     }
2921     j++;
2922   }
2923   meshnumber = 0;
2924   if (increment > 0) {
2925     j = increment;
2926     do {
2927       if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
2928         meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
2929       } else {
2930         increment = 0;
2931       }
2932       j++;
2933     } while (workstring[j] != '\0');
2934   }
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");
2967   } else {
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");
2987   }
2988   strcat(innodefilename, ".node");
2989   strcat(inpolyfilename, ".poly");
2990   strcat(inelefilename, ".ele");
2991   strcat(areafilename, ".area");
2992 #endif /* not TRILIBRARY */
2993 }
2994
2995 /**                                                                         **/
2996 /**                                                                         **/
2997 /********* User interaction routines begin here                      *********/
2998
2999 /********* Debugging routines begin here                             *********/
3000 /**                                                                         **/
3001 /**                                                                         **/
3002
3003 /*****************************************************************************/
3004 /*                                                                           */
3005 /*  printtriangle()   Print out the details of a triangle/edge handle.       */
3006 /*                                                                           */
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.                        */
3011 /*                                                                           */
3012 /*****************************************************************************/
3013
3014 void printtriangle(t)
3015 struct triedge *t;
3016 {
3017   struct triedge printtri;
3018   struct edge printsh;
3019   point printpoint;
3020
3021   printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
3022          t->orient);
3023   decode(t->tri[0], printtri);
3024   if (printtri.tri == dummytri) {
3025     printf("    [0] = Outer space\n");
3026   } else {
3027     printf("    [0] = x%lx  %d\n", (unsigned long) printtri.tri,
3028            printtri.orient);
3029   }
3030   decode(t->tri[1], printtri);
3031   if (printtri.tri == dummytri) {
3032     printf("    [1] = Outer space\n");
3033   } else {
3034     printf("    [1] = x%lx  %d\n", (unsigned long) printtri.tri,
3035            printtri.orient);
3036   }
3037   decode(t->tri[2], printtri);
3038   if (printtri.tri == dummytri) {
3039     printf("    [2] = Outer space\n");
3040   } else {
3041     printf("    [2] = x%lx  %d\n", (unsigned long) printtri.tri,
3042            printtri.orient);
3043   }
3044   org(*t, printpoint);
3045   if (printpoint == (point) NULL)
3046     printf("    Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
3047   else
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);
3054   else
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);
3061   else
3062     printf("    Apex  [%d] = x%lx  (%.12g, %.12g)\n",
3063            t->orient + 3, (unsigned long) printpoint,
3064            printpoint[0], printpoint[1]);
3065   if (useshelles) {
3066     sdecode(t->tri[6], printsh);
3067     if (printsh.sh != dummysh) {
3068       printf("    [6] = x%lx  %d\n", (unsigned long) printsh.sh,
3069              printsh.shorient);
3070     }
3071     sdecode(t->tri[7], printsh);
3072     if (printsh.sh != dummysh) {
3073       printf("    [7] = x%lx  %d\n", (unsigned long) printsh.sh,
3074              printsh.shorient);
3075     }
3076     sdecode(t->tri[8], printsh);
3077     if (printsh.sh != dummysh) {
3078       printf("    [8] = x%lx  %d\n", (unsigned long) printsh.sh,
3079              printsh.shorient);
3080     }
3081   }
3082   if (vararea) {
3083     printf("    Area constraint:  %.4g\n", areabound(*t));
3084   }
3085 }
3086
3087 /*****************************************************************************/
3088 /*                                                                           */
3089 /*  printshelle()   Print out the details of a shell edge handle.            */
3090 /*                                                                           */
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.                                */
3095 /*                                                                           */
3096 /*****************************************************************************/
3097
3098 void printshelle(s)
3099 struct edge *s;
3100 {
3101   struct edge printsh;
3102   struct triedge printtri;
3103   point printpoint;
3104
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");
3110   } else {
3111     printf("    [0] = x%lx  %d\n", (unsigned long) printsh.sh,
3112            printsh.shorient);
3113   }
3114   sdecode(s->sh[1], printsh);
3115   if (printsh.sh == dummysh) {
3116     printf("    [1] = No shell\n");
3117   } else {
3118     printf("    [1] = x%lx  %d\n", (unsigned long) printsh.sh,
3119            printsh.shorient);
3120   }
3121   sorg(*s, printpoint);
3122   if (printpoint == (point) NULL)
3123     printf("    Origin[%d] = NULL\n", 2 + s->shorient);
3124   else
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);
3131   else
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");
3138   } else {
3139     printf("    [4] = x%lx  %d\n", (unsigned long) printtri.tri,
3140            printtri.orient);
3141   }
3142   decode(s->sh[5], printtri);
3143   if (printtri.tri == dummytri) {
3144     printf("    [5] = Outer space\n");
3145   } else {
3146     printf("    [5] = x%lx  %d\n", (unsigned long) printtri.tri,
3147            printtri.orient);
3148   }
3149 }
3150
3151 /**                                                                         **/
3152 /**                                                                         **/
3153 /********* Debugging routines end here                               *********/
3154
3155 /********* Memory management routines begin here                     *********/
3156 /**                                                                         **/
3157 /**                                                                         **/
3158
3159 /*****************************************************************************/
3160 /*                                                                           */
3161 /*  poolinit()   Initialize a pool of memory for allocation of items.        */
3162 /*                                                                           */
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.              */
3173 /*                                                                           */
3174 /*  Don't change this routine unless you understand it.                      */
3175 /*                                                                           */
3176 /*****************************************************************************/
3177
3178 void poolinit(pool, bytecount, itemcount, wtype, alignment)
3179 struct memorypool *pool;
3180 int bytecount;
3181 int itemcount;
3182 enum wordtype wtype;
3183 int alignment;
3184 {
3185   int wordsize;
3186
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;
3197   } else {
3198     pool->alignbytes = wordsize;
3199   }
3200   if (sizeof(VOID *) > pool->alignbytes) {
3201     pool->alignbytes = sizeof(VOID *);
3202   }
3203   pool->itemwords = ((bytecount + pool->alignbytes - 1) / pool->alignbytes)
3204                   * (pool->alignbytes / wordsize);
3205   pool->itembytes = pool->itemwords * wordsize;
3206   pool->itemsperblock = itemcount;
3207
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");
3215     exit(1);
3216   }
3217   /* Set the next block pointer to NULL. */
3218   *(pool->firstblock) = (VOID *) NULL;
3219   poolrestart(pool);
3220 }
3221
3222 /*****************************************************************************/
3223 /*                                                                           */
3224 /*  poolrestart()   Deallocate all items in a pool.                          */
3225 /*                                                                           */
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.                                                  */
3229 /*                                                                           */
3230 /*****************************************************************************/
3231
3232 void poolrestart(pool)
3233 struct memorypool *pool;
3234 {
3235   unsigned long alignptr;
3236
3237   pool->items = 0;
3238   pool->maxitems = 0;
3239
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;
3252 }
3253
3254 /*****************************************************************************/
3255 /*                                                                           */
3256 /*  pooldeinit()   Free to the operating system all memory taken by a pool.  */
3257 /*                                                                           */
3258 /*****************************************************************************/
3259
3260 void pooldeinit(pool)
3261 struct memorypool *pool;
3262 {
3263   while (pool->firstblock != (VOID **) NULL) {
3264     pool->nowblock = (VOID **) *(pool->firstblock);
3265     free(pool->firstblock);
3266     pool->firstblock = pool->nowblock;
3267   }
3268 }
3269
3270 /*****************************************************************************/
3271 /*                                                                           */
3272 /*  poolalloc()   Allocate space for an item.                                */
3273 /*                                                                           */
3274 /*****************************************************************************/
3275
3276 VOID *poolalloc(pool)
3277 struct memorypool *pool;
3278 {
3279   VOID *newitem;
3280   VOID **newblock;
3281   unsigned long alignptr;
3282
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;
3288   } else {
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");
3298           exit(1);
3299         }
3300         *(pool->nowblock) = (VOID *) newblock;
3301         /* The next block pointer is NULL. */
3302         *newblock = (VOID *) NULL;
3303       }
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;
3315     }
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);
3321     } else {
3322       pool->nextitem = (VOID *) ((REAL *) pool->nextitem + pool->itemwords);
3323     }
3324     pool->unallocateditems--;
3325     pool->maxitems++;
3326   }
3327   pool->items++;
3328   return newitem;
3329 }
3330
3331 /*****************************************************************************/
3332 /*                                                                           */
3333 /*  pooldealloc()   Deallocate space for an item.                            */
3334 /*                                                                           */
3335 /*  The deallocated space is stored in a queue for later reuse.              */
3336 /*                                                                           */
3337 /*****************************************************************************/
3338
3339 void pooldealloc(pool, dyingitem)
3340 struct memorypool *pool;
3341 VOID *dyingitem;
3342 {
3343   /* Push freshly killed item onto stack. */
3344   *((VOID **) dyingitem) = pool->deaditemstack;
3345   pool->deaditemstack = dyingitem;
3346   pool->items--;
3347 }
3348
3349 /*****************************************************************************/
3350 /*                                                                           */
3351 /*  traversalinit()   Prepare to traverse the entire list of items.          */
3352 /*                                                                           */
3353 /*  This routine is used in conjunction with traverse().                     */
3354 /*                                                                           */
3355 /*****************************************************************************/
3356
3357 void traversalinit(pool)
3358 struct memorypool *pool;
3359 {
3360   unsigned long alignptr;
3361
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;
3372 }
3373
3374 /*****************************************************************************/
3375 /*                                                                           */
3376 /*  traverse()   Find the next item in the list.                             */
3377 /*                                                                           */
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  */
3384 /*  of the item.                                                             */
3385 /*                                                                           */
3386 /*****************************************************************************/
3387
3388 VOID *traverse(pool)
3389 struct memorypool *pool;
3390 {
3391   VOID *newitem;
3392   unsigned long alignptr;
3393
3394   /* Stop upon exhausting the list of items. */
3395   if (pool->pathitem == pool->nextitem) {
3396     return (VOID *) NULL;
3397   }
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;
3410   }
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);
3415   } else {
3416     pool->pathitem = (VOID *) ((REAL *) pool->pathitem + pool->itemwords);
3417   }
3418   pool->pathitemsleft--;
3419   return newitem;
3420 }
3421
3422 /*****************************************************************************/
3423 /*                                                                           */
3424 /*  dummyinit()   Initialize the triangle that fills "outer space" and the   */
3425 /*                omnipresent shell edge.                                    */
3426 /*                                                                           */
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.                 */
3432 /*                                                                           */
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    */
3435 /*  to point to.                                                             */
3436 /*                                                                           */
3437 /*****************************************************************************/
3438
3439 void dummyinit(trianglewords, shellewords)
3440 int trianglewords;
3441 int shellewords;
3442 {
3443   unsigned long alignptr;
3444
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. */
3449
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");
3455     exit(1);
3456   }
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          */
3465   /*   dereferenced.                                                       */
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;
3473
3474   if (useshelles) {
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 */
3477     /*   edge.                                                               */
3478     dummyshbase = (shelle *) malloc(shwords * sizeof(shelle)
3479                                     + shelles.alignbytes);
3480     if (dummyshbase == (shelle *) NULL) {
3481       printf("Error:  Out of memory.\n");
3482       exit(1);
3483     }
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;
3503
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;
3509   }
3510 }
3511
3512 /*****************************************************************************/
3513 /*                                                                           */
3514 /*  initializepointpool()   Calculate the size of the point data structure   */
3515 /*                          and initialize its memory pool.                  */
3516 /*                                                                           */
3517 /*  This routine also computes the `pointmarkindex' and `point2triindex'     */
3518 /*  indices used to find values within each point.                           */
3519 /*                                                                           */
3520 /*****************************************************************************/
3521
3522 void initializepointpool()
3523 {
3524   int pointsize;
3525
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)
3529                  / sizeof(int);
3530   pointsize = (pointmarkindex + 1) * sizeof(int);
3531   if (poly) {
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);
3536   }
3537   /* Initialize the pool of points. */
3538   poolinit(&points, pointsize, POINTPERBLOCK,
3539            (sizeof(REAL) >= sizeof(triangle)) ? FLOATINGPOINT : POINTER, 0);
3540 }
3541
3542 /*****************************************************************************/
3543 /*                                                                           */
3544 /*  initializetrisegpools()   Calculate the sizes of the triangle and shell  */
3545 /*                            edge data structures and initialize their      */
3546 /*                            memory pools.                                  */
3547 /*                                                                           */
3548 /*  This routine also computes the `highorderindex', `elemattribindex', and  */
3549 /*  `areaboundindex' indices used to find values within each triangle.       */
3550 /*                                                                           */
3551 /*****************************************************************************/
3552
3553 void initializetrisegpools()
3554 {
3555   int trisize;
3556
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)) *
3564             sizeof(triangle);
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.                                      */
3574   if (vararea) {
3575     trisize = (areaboundindex + 1) * sizeof(REAL);
3576   } else if (eextras + regionattrib > 0) {
3577     trisize = areaboundindex * sizeof(REAL);
3578   }
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);
3586   }
3587   /* Having determined the memory size of a triangle, initialize the pool. */
3588   poolinit(&triangles, trisize, TRIPERBLOCK, POINTER, 4);
3589
3590   if (useshelles) {
3591     /* Initialize the pool of shell edges. */
3592     poolinit(&shelles, 6 * sizeof(triangle) + sizeof(int), SHELLEPERBLOCK,
3593              POINTER, 4);
3594
3595     /* Initialize the "outer space" triangle and omnipresent shell edge. */
3596     dummyinit(triangles.itemwords, shelles.itemwords);
3597   } else {
3598     /* Initialize the "outer space" triangle. */
3599     dummyinit(triangles.itemwords, 0);
3600   }
3601 }
3602
3603 /*****************************************************************************/
3604 /*                                                                           */
3605 /*  triangledealloc()   Deallocate space for a triangle, marking it dead.    */
3606 /*                                                                           */
3607 /*****************************************************************************/
3608
3609 void triangledealloc(dyingtriangle)
3610 triangle *dyingtriangle;
3611 {
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);
3618 }
3619
3620 /*****************************************************************************/
3621 /*                                                                           */
3622 /*  triangletraverse()   Traverse the triangles, skipping dead ones.         */
3623 /*                                                                           */
3624 /*****************************************************************************/
3625
3626 triangle *triangletraverse()
3627 {
3628   triangle *newtriangle;
3629
3630   do {
3631     newtriangle = (triangle *) traverse(&triangles);
3632     if (newtriangle == (triangle *) NULL) {
3633       return (triangle *) NULL;
3634     }
3635   } while (newtriangle[3] == (triangle) NULL);            /* Skip dead ones. */
3636   return newtriangle;
3637 }
3638
3639 /*****************************************************************************/
3640 /*                                                                           */
3641 /*  shelledealloc()   Deallocate space for a shell edge, marking it dead.    */
3642 /*                                                                           */
3643 /*****************************************************************************/
3644
3645 void shelledealloc(dyingshelle)
3646 shelle *dyingshelle;
3647 {
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);
3653 }
3654
3655 /*****************************************************************************/
3656 /*                                                                           */
3657 /*  shelletraverse()   Traverse the shell edges, skipping dead ones.         */
3658 /*                                                                           */
3659 /*****************************************************************************/
3660
3661 shelle *shelletraverse()
3662 {
3663   shelle *newshelle;
3664
3665   do {
3666     newshelle = (shelle *) traverse(&shelles);
3667     if (newshelle == (shelle *) NULL) {
3668       return (shelle *) NULL;
3669     }
3670   } while (newshelle[2] == (shelle) NULL);                /* Skip dead ones. */
3671   return newshelle;
3672 }
3673
3674 /*****************************************************************************/
3675 /*                                                                           */
3676 /*  pointdealloc()   Deallocate space for a point, marking it dead.          */
3677 /*                                                                           */
3678 /*****************************************************************************/
3679
3680 void pointdealloc(dyingpoint)
3681 point dyingpoint;
3682 {
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);
3687 }
3688
3689 /*****************************************************************************/
3690 /*                                                                           */
3691 /*  pointtraverse()   Traverse the points, skipping dead ones.               */
3692 /*                                                                           */
3693 /*****************************************************************************/
3694
3695 point pointtraverse()
3696 {
3697   point newpoint;
3698
3699   do {
3700     newpoint = (point) traverse(&points);
3701     if (newpoint == (point) NULL) {
3702       return (point) NULL;
3703     }
3704   } while (pointmark(newpoint) == DEADPOINT);             /* Skip dead ones. */
3705   return newpoint;
3706 }
3707
3708 /*****************************************************************************/
3709 /*                                                                           */
3710 /*  badsegmentdealloc()   Deallocate space for a bad segment, marking it     */
3711 /*                        dead.                                              */
3712 /*                                                                           */
3713 /*****************************************************************************/
3714
3715 #ifndef CDT_ONLY
3716
3717 void badsegmentdealloc(dyingseg)
3718 struct edge *dyingseg;
3719 {
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);
3724 }
3725
3726 #endif /* not CDT_ONLY */
3727
3728 /*****************************************************************************/
3729 /*                                                                           */
3730 /*  badsegmenttraverse()   Traverse the bad segments, skipping dead ones.    */
3731 /*                                                                           */
3732 /*****************************************************************************/
3733
3734 #ifndef CDT_ONLY
3735
3736 struct edge *badsegmenttraverse()
3737 {
3738   struct edge *newseg;
3739
3740   do {
3741     newseg = (struct edge *) traverse(&badsegments);
3742     if (newseg == (struct edge *) NULL) {
3743       return (struct edge *) NULL;
3744     }
3745   } while (newseg->shorient == -1);                       /* Skip dead ones. */
3746   return newseg;
3747 }
3748
3749 #endif /* not CDT_ONLY */
3750
3751 /*****************************************************************************/
3752 /*                                                                           */
3753 /*  getpoint()   Get a specific point, by number, from the list.             */
3754 /*                                                                           */
3755 /*  The first point is number 'firstnumber'.                                 */
3756 /*                                                                           */
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 */
3759 /*  time.                                                                    */
3760 /*                                                                           */
3761 /*****************************************************************************/
3762
3763 point getpoint(number)
3764 int number;
3765 {
3766   VOID **getblock;
3767   point foundpoint;
3768   unsigned long alignptr;
3769   int current;
3770
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;
3777   }
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;
3784     current++;
3785   }
3786   return foundpoint;
3787 }
3788
3789 /*****************************************************************************/
3790 /*                                                                           */
3791 /*  triangledeinit()   Free all remaining allocated memory.                  */
3792 /*                                                                           */
3793 /*****************************************************************************/
3794
3795 void triangledeinit()
3796 {
3797   pooldeinit(&triangles);
3798   free(dummytribase);
3799   if (useshelles) {
3800     pooldeinit(&shelles);
3801     free(dummyshbase);
3802   }
3803   pooldeinit(&points);
3804 #ifndef CDT_ONLY
3805   if (quality) {
3806     pooldeinit(&badsegments);
3807     if ((minangle > 0.0) || vararea || fixedarea) {
3808       pooldeinit(&badtriangles);
3809     }
3810   }
3811 #endif /* not CDT_ONLY */
3812 }
3813
3814 /**                                                                         **/
3815 /**                                                                         **/
3816 /********* Memory management routines end here                       *********/
3817
3818 /********* Constructors begin here                                   *********/
3819 /**                                                                         **/
3820 /**                                                                         **/
3821
3822 /*****************************************************************************/
3823 /*                                                                           */
3824 /*  maketriangle()   Create a new triangle with orientation zero.            */
3825 /*                                                                           */
3826 /*****************************************************************************/
3827
3828 void maketriangle(newtriedge)
3829 struct triedge *newtriedge;
3830 {
3831   int i;
3832
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 */
3843   /*   shell edge.                                                    */
3844   if (useshelles) {
3845     newtriedge->tri[6] = (triangle) dummysh;
3846     newtriedge->tri[7] = (triangle) dummysh;
3847     newtriedge->tri[8] = (triangle) dummysh;
3848   }
3849   for (i = 0; i < eextras; i++) {
3850     setelemattribute(*newtriedge, i, 0.0);
3851   }
3852   if (vararea) {
3853     setareabound(*newtriedge, -1.0);
3854   }
3855
3856   newtriedge->orient = 0;
3857 }
3858
3859 /*****************************************************************************/
3860 /*                                                                           */
3861 /*  makeshelle()   Create a new shell edge with orientation zero.            */
3862 /*                                                                           */
3863 /*****************************************************************************/
3864
3865 void makeshelle(newedge)
3866 struct edge *newedge;
3867 {
3868   newedge->sh = (shelle *) poolalloc(&shelles);
3869   /* Initialize the two adjoining shell edges to be the omnipresent */
3870   /*   shell edge.                                                  */
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);
3881
3882   newedge->shorient = 0;
3883 }
3884
3885 /**                                                                         **/
3886 /**                                                                         **/
3887 /********* Constructors end here                                     *********/
3888
3889 /********* Determinant evaluation routines begin here                *********/
3890 /**                                                                         **/
3891 /**                                                                         **/
3892
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.                                       */
3896
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.              */
3902
3903 #define Absolute(a)  ((a) >= 0.0 ? (a) : -(a))
3904 /* #define Absolute(a)  fabs(a) */
3905
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.                                       */
3909 /*                                                                           */
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'.                                             */
3918
3919 #define Fast_Two_Sum_Tail(a, b, x, y) \
3920   bvirt = x - a; \
3921   y = b - bvirt
3922
3923 #define Fast_Two_Sum(a, b, x, y) \
3924   x = (REAL) (a + b); \
3925   Fast_Two_Sum_Tail(a, b, x, y)
3926
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; \
3932   y = around + bround
3933
3934 #define Two_Sum(a, b, x, y) \
3935   x = (REAL) (a + b); \
3936   Two_Sum_Tail(a, b, x, y)
3937
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; \
3943   y = around + bround
3944
3945 #define Two_Diff(a, b, x, y) \
3946   x = (REAL) (a - b); \
3947   Two_Diff_Tail(a, b, x, y)
3948
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)
3954
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
3962
3963 #define Two_Product(a, b, x, y) \
3964   x = (REAL) (a * b); \
3965   Two_Product_Tail(a, b, x, y)
3966
3967 /* Two_Product_Presplit() is Two_Product() where one of the inputs has       */
3968 /*   already been split.  Avoids redundant splitting.                        */
3969
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
3977
3978 /* Square() can be done more quickly than Two_Product().                     */
3979
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
3985
3986 #define Square(a, x, y) \
3987   x = (REAL) (a * a); \
3988   Square_Tail(a, x, y)
3989
3990 /* Macros for summing expansions of various fixed lengths.  These are all    */
3991 /*   unrolled versions of Expansion_Sum().                                   */
3992
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)
3996
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)
4000
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)
4004
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)
4008
4009 /*****************************************************************************/
4010 /*                                                                           */
4011 /*  exactinit()   Initialize the variables used for exact arithmetic.        */
4012 /*                                                                           */
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.                    */
4016 /*                                                                           */
4017 /*  `splitter' is used to split floating-point numbers into two half-        */
4018 /*  length significands for exact multiplication.                            */
4019 /*                                                                           */
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.              */
4023 /*                                                                           */
4024 /*  Don't change this routine unless you fully understand it.                */
4025 /*                                                                           */
4026 /*****************************************************************************/
4027
4028 void exactinit()
4029 {
4030   REAL half;
4031   REAL check, lastcheck;
4032   int every_other;
4033
4034   every_other = 1;
4035   half = 0.5;
4036   epsilon = 1.0;
4037   splitter = 1.0;
4038   check = 1.0;
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. */
4043   do {
4044     lastcheck = check;
4045     epsilon *= half;
4046     if (every_other) {
4047       splitter *= 2.0;
4048     }
4049     every_other = !every_other;
4050     check = (REAL)(1.0 + epsilon);
4051   } while ((check != 1.0) && (check != lastcheck));
4052   splitter += 1.0;
4053   if (verbose > 1) {
4054     printf("Floating point roundoff is of magnitude %.17g\n", epsilon);
4055     printf("Floating point splitter is %.17g\n", splitter);
4056   }
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);
4065 }
4066
4067 /*****************************************************************************/
4068 /*                                                                           */
4069 /*  fast_expansion_sum_zeroelim()   Sum two expansions, eliminating zero     */
4070 /*                                  components from the output expansion.    */
4071 /*                                                                           */
4072 /*  Sets h = e + f.  See my Robust Predicates paper for details.             */
4073 /*                                                                           */
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      */
4077 /*  properties.                                                              */
4078 /*                                                                           */
4079 /*****************************************************************************/
4080
4081 int fast_expansion_sum_zeroelim(elen, e, flen, f, h)  /* h cannot be e or f. */
4082 int elen;
4083 REAL *e;
4084 int flen;
4085 REAL *f;
4086 REAL *h;
4087 {
4088   REAL Q;
4089   INEXACT REAL Qnew;
4090   INEXACT REAL hh;
4091   INEXACT REAL bvirt;
4092   REAL avirt, bround, around;
4093   int eindex, findex, hindex;
4094   REAL enow, fnow;
4095
4096   enow = e[0];
4097   fnow = f[0];
4098   eindex = findex = 0;
4099   if ((fnow > enow) == (fnow > -enow)) {
4100     Q = enow;
4101     enow = e[++eindex];
4102   } else {
4103     Q = fnow;
4104     fnow = f[++findex];
4105   }
4106   hindex = 0;
4107   if ((eindex < elen) && (findex < flen)) {
4108     if ((fnow > enow) == (fnow > -enow)) {
4109       Fast_Two_Sum(enow, Q, Qnew, hh);
4110       enow = e[++eindex];
4111     } else {
4112       Fast_Two_Sum(fnow, Q, Qnew, hh);
4113       fnow = f[++findex];
4114     }
4115     Q = Qnew;
4116     if (hh != 0.0) {
4117       h[hindex++] = hh;
4118     }
4119     while ((eindex < elen) && (findex < flen)) {
4120       if ((fnow > enow) == (fnow > -enow)) {
4121         Two_Sum(Q, enow, Qnew, hh);
4122         enow = e[++eindex];
4123       } else {
4124         Two_Sum(Q, fnow, Qnew, hh);
4125         fnow = f[++findex];
4126       }
4127       Q = Qnew;
4128       if (hh != 0.0) {
4129         h[hindex++] = hh;
4130       }
4131     }
4132   }
4133   while (eindex < elen) {
4134     Two_Sum(Q, enow, Qnew, hh);
4135     enow = e[++eindex];
4136     Q = Qnew;
4137     if (hh != 0.0) {
4138       h[hindex++] = hh;
4139     }
4140   }
4141   while (findex < flen) {
4142     Two_Sum(Q, fnow, Qnew, hh);
4143     fnow = f[++findex];
4144     Q = Qnew;
4145     if (hh != 0.0) {
4146       h[hindex++] = hh;
4147     }
4148   }
4149   if ((Q != 0.0) || (hindex == 0)) {
4150     h[hindex++] = Q;
4151   }
4152   return hindex;
4153 }
4154
4155 /*****************************************************************************/
4156 /*                                                                           */
4157 /*  scale_expansion_zeroelim()   Multiply an expansion by a scalar,          */
4158 /*                               eliminating zero components from the        */
4159 /*                               output expansion.                           */
4160 /*                                                                           */
4161 /*  Sets h = be.  See my Robust Predicates paper for details.                */
4162 /*                                                                           */
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      */
4166 /*  will h.)                                                                 */
4167 /*                                                                           */
4168 /*****************************************************************************/
4169
4170 int scale_expansion_zeroelim(elen, e, b, h)   /* e and h cannot be the same. */
4171 int elen;
4172 REAL *e;
4173 REAL b;
4174 REAL *h;
4175 {
4176   INEXACT REAL Q, sum;
4177   REAL hh;
4178   INEXACT REAL product1;
4179   REAL product0;
4180   int eindex, hindex;
4181   REAL enow;
4182   INEXACT REAL bvirt;
4183   REAL avirt, bround, around;
4184   INEXACT REAL c;
4185   INEXACT REAL abig;
4186   REAL ahi, alo, bhi, blo;
4187   REAL err1, err2, err3;
4188
4189   Split(b, bhi, blo);
4190   Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
4191   hindex = 0;
4192   if (hh != 0) {
4193     h[hindex++] = hh;
4194   }
4195   for (eindex = 1; eindex < elen; eindex++) {
4196     enow = e[eindex];
4197     Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
4198     Two_Sum(Q, product0, sum, hh);
4199     if (hh != 0) {
4200       h[hindex++] = hh;
4201     }
4202     Fast_Two_Sum(product1, sum, Q, hh);
4203     if (hh != 0) {
4204       h[hindex++] = hh;
4205     }
4206   }
4207   if ((Q != 0.0) || (hindex == 0)) {
4208     h[hindex++] = Q;
4209   }
4210   return hindex;
4211 }
4212
4213 /*****************************************************************************/
4214 /*                                                                           */
4215 /*  estimate()   Produce a one-word estimate of an expansion's value.        */
4216 /*                                                                           */
4217 /*  See my Robust Predicates paper for details.                              */
4218 /*                                                                           */
4219 /*****************************************************************************/
4220
4221 REAL estimate(elen, e)
4222 int elen;
4223 REAL *e;
4224 {
4225   REAL Q;
4226   int eindex;
4227
4228   Q = e[0];
4229   for (eindex = 1; eindex < elen; eindex++) {
4230     Q += e[eindex];
4231   }
4232   return Q;
4233 }
4234
4235 /*****************************************************************************/
4236 /*                                                                           */
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.               */
4243 /*                                                                           */
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.            */
4250 /*                                                                           */
4251 /*  See my Robust Predicates paper for details.                              */
4252 /*                                                                           */
4253 /*****************************************************************************/
4254
4255 REAL counterclockwiseadapt(pa, pb, pc, detsum)
4256 point pa;
4257 point pb;
4258 point pc;
4259 REAL detsum;
4260 {
4261   INEXACT REAL acx, acy, bcx, bcy;
4262   REAL acxtail, acytail, bcxtail, bcytail;
4263   INEXACT REAL detleft, detright;
4264   REAL detlefttail, detrighttail;
4265   REAL det, errbound;
4266   REAL B[4], C1[8], C2[12], D[16];
4267   INEXACT REAL B3;
4268   int C1length, C2length, Dlength;
4269   REAL u[4];
4270   INEXACT REAL u3;
4271   INEXACT REAL s1, t1;
4272   REAL s0, t0;
4273
4274   INEXACT REAL bvirt;
4275   REAL avirt, bround, around;
4276   INEXACT REAL c;
4277   INEXACT REAL abig;
4278   REAL ahi, alo, bhi, blo;
4279   REAL err1, err2, err3;
4280   INEXACT REAL _i, _j;
4281   REAL _0;
4282
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]);
4287
4288   Two_Product(acx, bcy, detleft, detlefttail);
4289   Two_Product(acy, bcx, detright, detrighttail);
4290
4291   Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
4292                B3, B[2], B[1], B[0]);
4293   B[3] = B3;
4294
4295   det = estimate(4, B);
4296   errbound = (REAL)(ccwerrboundB * detsum);
4297   if ((det >= errbound) || (-det >= errbound)) {
4298     return det;
4299   }
4300
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);
4305
4306   if ((acxtail == 0.0) && (acytail == 0.0)
4307       && (bcxtail == 0.0) && (bcytail == 0.0)) {
4308     return det;
4309   }
4310
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)) {
4315     return det;
4316   }
4317
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]);
4321   u[3] = u3;
4322   C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
4323
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]);
4327   u[3] = u3;
4328   C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
4329
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]);
4333   u[3] = u3;
4334   Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
4335
4336   return(D[Dlength - 1]);
4337 }
4338
4339 REAL counterclockwise(pa, pb, pc)
4340 point pa;
4341 point pb;
4342 point pc;
4343 {
4344   REAL detleft, detright, det;
4345   REAL detsum, errbound;
4346
4347   counterclockcount++;
4348
4349   detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
4350   detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
4351   det = detleft - detright;
4352
4353   if (noexact) {
4354     return det;
4355   }
4356
4357   if (detleft > 0.0) {
4358     if (detright <= 0.0) {
4359       return det;
4360     } else {
4361       detsum = detleft + detright;
4362     }
4363   } else if (detleft < 0.0) {
4364     if (detright >= 0.0) {
4365       return det;
4366     } else {
4367       detsum = -detleft - detright;
4368     }
4369   } else {
4370     return det;
4371   }
4372
4373   errbound = ccwerrboundA * detsum;
4374   if ((det >= errbound) || (-det >= errbound)) {
4375     return det;
4376   }
4377
4378   return counterclockwiseadapt(pa, pb, pc, detsum);
4379 }
4380
4381 /*****************************************************************************/
4382 /*                                                                           */
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.          */
4388 /*                                                                           */
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.           */
4395 /*                                                                           */
4396 /*  See my Robust Predicates paper for details.                              */
4397 /*                                                                           */
4398 /*****************************************************************************/
4399
4400 REAL incircleadapt(pa, pb, pc, pd, permanent)
4401 point pa;
4402 point pb;
4403 point pc;
4404 point pd;
4405 REAL permanent;
4406 {
4407   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
4408   REAL det, errbound;
4409
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;
4420   REAL abdet[64];
4421   int ablen;
4422   REAL fin1[1152], fin2[1152];
4423   REAL *finnow, *finother, *finswap;
4424   int finlength;
4425
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;
4432   REAL ti0, tj0;
4433   REAL u[4], v[4];
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;
4457   REAL negate;
4458
4459   INEXACT REAL bvirt;
4460   REAL avirt, bround, around;
4461   INEXACT REAL c;
4462   INEXACT REAL abig;
4463   REAL ahi, alo, bhi, blo;
4464   REAL err1, err2, err3;
4465   INEXACT REAL _i, _j;
4466   REAL _0;
4467
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]);
4474
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]);
4478   bc[3] = bc3;
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);
4484
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]);
4488   ca[3] = ca3;
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);
4494
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]);
4498   ab[3] = ab3;
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);
4504
4505   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
4506   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
4507
4508   det = estimate(finlength, fin1);
4509   errbound = (REAL)(iccerrboundB * permanent);
4510   if ((det >= errbound) || (-det >= errbound)) {
4511     return det;
4512   }
4513
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)) {
4522     return det;
4523   }
4524
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)) {
4536     return det;
4537   }
4538
4539   finnow = fin1;
4540   finother = fin2;
4541
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]);
4547     aa[3] = aa3;
4548   }
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]);
4554     bb[3] = bb3;
4555   }
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]);
4561     cc[3] = cc3;
4562   }
4563
4564   if (adxtail != 0.0) {
4565     axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
4566     temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
4567                                           temp16a);
4568
4569     axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
4570     temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
4571
4572     axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
4573     temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
4574
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,
4580                                             temp48, finother);
4581     finswap = finnow; finnow = finother; finother = finswap;
4582   }
4583   if (adytail != 0.0) {
4584     aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
4585     temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
4586                                           temp16a);
4587
4588     aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
4589     temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
4590
4591     aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
4592     temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
4593
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,
4599                                             temp48, finother);
4600     finswap = finnow; finnow = finother; finother = finswap;
4601   }
4602   if (bdxtail != 0.0) {
4603     bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
4604     temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
4605                                           temp16a);
4606
4607     bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
4608     temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
4609
4610     bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
4611     temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
4612
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,
4618                                             temp48, finother);
4619     finswap = finnow; finnow = finother; finother = finswap;
4620   }
4621   if (bdytail != 0.0) {
4622     bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
4623     temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
4624                                           temp16a);
4625
4626     bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
4627     temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
4628
4629     bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
4630     temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
4631
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,
4637                                             temp48, finother);
4638     finswap = finnow; finnow = finother; finother = finswap;
4639   }
4640   if (cdxtail != 0.0) {
4641     cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
4642     temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
4643                                           temp16a);
4644
4645     cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
4646     temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
4647
4648     cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
4649     temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
4650
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,
4656                                             temp48, finother);
4657     finswap = finnow; finnow = finother; finother = finswap;
4658   }
4659   if (cdytail != 0.0) {
4660     cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
4661     temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
4662                                           temp16a);
4663
4664     cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
4665     temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
4666
4667     cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
4668     temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
4669
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,
4675                                             temp48, finother);
4676     finswap = finnow; finnow = finother; finother = finswap;
4677   }
4678
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]);
4685       u[3] = u3;
4686       negate = -bdy;
4687       Two_Product(cdxtail, negate, ti1, ti0);
4688       negate = -bdytail;
4689       Two_Product(cdx, negate, tj1, tj0);
4690       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
4691       v[3] = v3;
4692       bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
4693
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]);
4697       bctt[3] = bctt3;
4698       bcttlen = 4;
4699     } else {
4700       bct[0] = 0.0;
4701       bctlen = 1;
4702       bctt[0] = 0.0;
4703       bcttlen = 1;
4704     }
4705
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,
4710                                             temp32a);
4711       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4712                                               temp32alen, temp32a, temp48);
4713       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4714                                               temp48, finother);
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,
4719                                               temp16a);
4720         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4721                                                 temp16a, finother);
4722         finswap = finnow; finnow = finother; finother = finswap;
4723       }
4724       if (cdytail != 0.0) {
4725         temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
4726         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
4727                                               temp16a);
4728         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4729                                                 temp16a, finother);
4730         finswap = finnow; finnow = finother; finother = finswap;
4731       }
4732
4733       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
4734                                             temp32a);
4735       axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
4736       temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
4737                                             temp16a);
4738       temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
4739                                             temp16b);
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,
4745                                               temp64, finother);
4746       finswap = finnow; finnow = finother; finother = finswap;
4747     }
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,
4752                                             temp32a);
4753       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4754                                               temp32alen, temp32a, temp48);
4755       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4756                                               temp48, finother);
4757       finswap = finnow; finnow = finother; finother = finswap;
4758
4759
4760       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
4761                                             temp32a);
4762       aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
4763       temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
4764                                             temp16a);
4765       temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
4766                                             temp16b);
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,
4772                                               temp64, finother);
4773       finswap = finnow; finnow = finother; finother = finswap;
4774     }
4775   }
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]);
4782       u[3] = u3;
4783       negate = -cdy;
4784       Two_Product(adxtail, negate, ti1, ti0);
4785       negate = -cdytail;
4786       Two_Product(adx, negate, tj1, tj0);
4787       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
4788       v[3] = v3;
4789       catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
4790
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]);
4794       catt[3] = catt3;
4795       cattlen = 4;
4796     } else {
4797       cat[0] = 0.0;
4798       catlen = 1;
4799       catt[0] = 0.0;
4800       cattlen = 1;
4801     }
4802
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,
4807                                             temp32a);
4808       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4809                                               temp32alen, temp32a, temp48);
4810       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4811                                               temp48, finother);
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,
4816                                               temp16a);
4817         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4818                                                 temp16a, finother);
4819         finswap = finnow; finnow = finother; finother = finswap;
4820       }
4821       if (adytail != 0.0) {
4822         temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
4823         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
4824                                               temp16a);
4825         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4826                                                 temp16a, finother);
4827         finswap = finnow; finnow = finother; finother = finswap;
4828       }
4829
4830       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
4831                                             temp32a);
4832       bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
4833       temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
4834                                             temp16a);
4835       temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
4836                                             temp16b);
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,
4842                                               temp64, finother);
4843       finswap = finnow; finnow = finother; finother = finswap;
4844     }
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,
4849                                             temp32a);
4850       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4851                                               temp32alen, temp32a, temp48);
4852       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4853                                               temp48, finother);
4854       finswap = finnow; finnow = finother; finother = finswap;
4855
4856
4857       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
4858                                             temp32a);
4859       bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
4860       temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
4861                                             temp16a);
4862       temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
4863                                             temp16b);
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,
4869                                               temp64, finother);
4870       finswap = finnow; finnow = finother; finother = finswap;
4871     }
4872   }
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]);
4879       u[3] = u3;
4880       negate = -ady;
4881       Two_Product(bdxtail, negate, ti1, ti0);
4882       negate = -adytail;
4883       Two_Product(bdx, negate, tj1, tj0);
4884       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
4885       v[3] = v3;
4886       abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
4887
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]);
4891       abtt[3] = abtt3;
4892       abttlen = 4;
4893     } else {
4894       abt[0] = 0.0;
4895       abtlen = 1;
4896       abtt[0] = 0.0;
4897       abttlen = 1;
4898     }
4899
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,
4904                                             temp32a);
4905       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4906                                               temp32alen, temp32a, temp48);
4907       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4908                                               temp48, finother);
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,
4913                                               temp16a);
4914         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4915                                                 temp16a, finother);
4916         finswap = finnow; finnow = finother; finother = finswap;
4917       }
4918       if (bdytail != 0.0) {
4919         temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
4920         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
4921                                               temp16a);
4922         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
4923                                                 temp16a, finother);
4924         finswap = finnow; finnow = finother; finother = finswap;
4925       }
4926
4927       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
4928                                             temp32a);
4929       cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
4930       temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
4931                                             temp16a);
4932       temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
4933                                             temp16b);
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,
4939                                               temp64, finother);
4940       finswap = finnow; finnow = finother; finother = finswap;
4941     }
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,
4946                                             temp32a);
4947       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
4948                                               temp32alen, temp32a, temp48);
4949       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
4950                                               temp48, finother);
4951       finswap = finnow; finnow = finother; finother = finswap;
4952
4953
4954       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
4955                                             temp32a);
4956       cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
4957       temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
4958                                             temp16a);
4959       temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
4960                                             temp16b);
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,
4966                                               temp64, finother);
4967       finswap = finnow; finnow = finother; finother = finswap;
4968     }
4969   }
4970
4971   return finnow[finlength - 1];
4972 }
4973
4974 REAL incircle(pa, pb, pc, pd)
4975 point pa;
4976 point pb;
4977 point pc;
4978 point pd;
4979 {
4980   REAL adx, bdx, cdx, ady, bdy, cdy;
4981   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
4982   REAL alift, blift, clift;
4983   REAL det;
4984   REAL permanent, errbound;
4985
4986   incirclecount++;
4987
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];
4994
4995   bdxcdy = bdx * cdy;
4996   cdxbdy = cdx * bdy;
4997   alift = adx * adx + ady * ady;
4998
4999   cdxady = cdx * ady;
5000   adxcdy = adx * cdy;
5001   blift = bdx * bdx + bdy * bdy;
5002
5003   adxbdy = adx * bdy;
5004   bdxady = bdx * ady;
5005   clift = cdx * cdx + cdy * cdy;
5006
5007   det = alift * (bdxcdy - cdxbdy)
5008       + blift * (cdxady - adxcdy)
5009       + clift * (adxbdy - bdxady);
5010
5011   if (noexact) {
5012     return det;
5013   }
5014
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)) {
5020     return det;
5021   }
5022
5023   return incircleadapt(pa, pb, pc, pd, permanent);
5024 }
5025
5026 /**                                                                         **/
5027 /**                                                                         **/
5028 /********* Determinant evaluation routines end here                  *********/
5029
5030 /*****************************************************************************/
5031 /*                                                                           */
5032 /*  triangleinit()   Initialize some variables.                              */
5033 /*                                                                           */
5034 /*****************************************************************************/
5035
5036 void triangleinit()
5037 {
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;
5047   randomseed = 1;
5048
5049   exactinit();                     /* Initialize exact arithmetic constants. */
5050 }
5051
5052 /*****************************************************************************/
5053 /*                                                                           */
5054 /*  randomnation()   Generate a random number between 0 and `choices' - 1.   */
5055 /*                                                                           */
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.                                                    */
5059 /*                                                                           */
5060 /*****************************************************************************/
5061
5062 unsigned long randomnation(choices)
5063 unsigned int choices;
5064 {
5065   randomseed = (randomseed * 1366l + 150889l) % 714025l;
5066   return randomseed / (714025l / choices + 1);
5067 }
5068
5069 /********* Mesh quality testing routines begin here                  *********/
5070 /**                                                                         **/
5071 /**                                                                         **/
5072
5073 /*****************************************************************************/
5074 /*                                                                           */
5075 /*  checkmesh()   Test the mesh for topological consistency.                 */
5076 /*                                                                           */
5077 /*****************************************************************************/
5078
5079 #ifndef REDUCED
5080
5081 void checkmesh()
5082 {
5083   struct triedge triangleloop;
5084   struct triedge oppotri, oppooppotri;
5085   point triorg, tridest, triapex;
5086   point oppoorg, oppodest;
5087   int horrors;
5088   int saveexact;
5089   triangle ptr;                         /* Temporary variable used by sym(). */
5090
5091   /* Temporarily turn on exact arithmetic if it's off. */
5092   saveexact = noexact;
5093   noexact = 0;
5094   if (!quiet) {
5095     printf("  Checking consistency of mesh...\n");
5096   }
5097   horrors = 0;
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);
5113           horrors++;
5114         }
5115       }
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");
5126           }
5127           printf("    First ");
5128           printtriangle(&triangleloop);
5129           printf("    Second (nonreciprocating) ");
5130           printtriangle(&oppotri);
5131           horrors++;
5132         }
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"
5139                  );
5140           printf("    First mismatched ");
5141           printtriangle(&triangleloop);
5142           printf("    Second mismatched ");
5143           printtriangle(&oppotri);
5144           horrors++;
5145         }
5146       }
5147     }
5148     triangleloop.tri = triangletraverse();
5149   }
5150   if (horrors == 0) {
5151     if (!quiet) {
5152       printf("  In my studied opinion, the mesh appears to be consistent.\n");
5153     }
5154   } else if (horrors == 1) {
5155     printf("  !! !! !! !! Precisely one festering wound discovered.\n");
5156   } else {
5157     printf("  !! !! !! !! %d abominations witnessed.\n", horrors);
5158   }
5159   /* Restore the status of exact arithmetic. */
5160   noexact = saveexact;
5161 }
5162
5163 #endif /* not REDUCED */
5164
5165 /*****************************************************************************/
5166 /*                                                                           */
5167 /*  checkdelaunay()   Ensure that the mesh is (constrained) Delaunay.        */
5168 /*                                                                           */
5169 /*****************************************************************************/
5170
5171 #ifndef REDUCED
5172
5173 void checkdelaunay()
5174 {
5175   struct triedge triangleloop;
5176   struct triedge oppotri;
5177   struct edge opposhelle;
5178   point triorg, tridest, triapex;
5179   point oppoapex;
5180   int shouldbedelaunay;
5181   int horrors;
5182   int saveexact;
5183   triangle ptr;                         /* Temporary variable used by sym(). */
5184   shelle sptr;                      /* Temporary variable used by tspivot(). */
5185
5186   /* Temporarily turn on exact arithmetic if it's off. */
5187   saveexact = noexact;
5188   noexact = 0;
5189   if (!quiet) {
5190     printf("  Checking Delaunay property of mesh...\n");
5191   }
5192   horrors = 0;
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;
5217         }
5218       }
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);
5226           horrors++;
5227         }
5228       }
5229     }
5230     triangleloop.tri = triangletraverse();
5231   }
5232   if (horrors == 0) {
5233     if (!quiet) {
5234       printf(
5235   "  By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
5236     }
5237   } else if (horrors == 1) {
5238     printf(
5239          "  !! !! !! !! Precisely one terrifying transgression identified.\n");
5240   } else {
5241     printf("  !! !! !! !! %d obscenities viewed with horror.\n", horrors);
5242   }
5243   /* Restore the status of exact arithmetic. */
5244   noexact = saveexact;
5245 }
5246
5247 #endif /* not REDUCED */
5248
5249 /*****************************************************************************/
5250 /*                                                                           */
5251 /*  enqueuebadtri()   Add a bad triangle to the end of a queue.              */
5252 /*                                                                           */
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.                                 */
5256 /*                                                                           */
5257 /*****************************************************************************/
5258
5259 #ifndef CDT_ONLY
5260
5261 void enqueuebadtri(instri, angle, insapex, insorg, insdest)
5262 struct triedge *instri;
5263 REAL angle;
5264 point insapex;
5265 point insorg;
5266 point insdest;
5267 {
5268   struct badface *newface;
5269   int queuenumber;
5270
5271   if (verbose > 2) {
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]);
5275   }
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. */
5285   if (angle > 0.6) {
5286     queuenumber = (int) (160.0 * (angle - 0.6));
5287     if (queuenumber > 63) {
5288       queuenumber = 63;
5289     }
5290   } else {
5291     /* It's not a bad angle; put the triangle in the lowest-priority queue. */
5292     queuenumber = 0;
5293   }
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;
5298 }
5299
5300 #endif /* not CDT_ONLY */
5301
5302 /*****************************************************************************/
5303 /*                                                                           */
5304 /*  dequeuebadtri()   Remove a triangle from the front of the queue.         */
5305 /*                                                                           */
5306 /*****************************************************************************/
5307
5308 #ifndef CDT_ONLY
5309
5310 struct badface *dequeuebadtri()
5311 {
5312   struct badface *result;
5313   int queuenumber;
5314
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];
5324       }
5325       return result;
5326     }
5327   }
5328   return (struct badface *) NULL;
5329 }
5330
5331 #endif /* not CDT_ONLY */
5332
5333 /*****************************************************************************/
5334 /*                                                                           */
5335 /*  checkedge4encroach()   Check a segment to see if it is encroached; add   */
5336 /*                         it to the list if it is.                          */
5337 /*                                                                           */
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.                                       */
5341 /*                                                                           */
5342 /*  Returns a nonzero value if the edge is encroached.                       */
5343 /*                                                                           */
5344 /*****************************************************************************/
5345
5346 #ifndef CDT_ONLY
5347
5348 int checkedge4encroach(testedge)
5349 struct edge *testedge;
5350 {
5351   struct triedge neighbortri;
5352   struct edge testsym;
5353   struct edge *badedge;
5354   int addtolist;
5355   int sides;
5356   point eorg, edest, eapex;
5357   triangle ptr;                     /* Temporary variable used by stpivot(). */
5358
5359   addtolist = 0;
5360   sides = 0;
5361
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) {
5368     sides++;
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]) {
5377       addtolist = 1;
5378     }
5379   }
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) {
5385     sides++;
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]) {
5395       addtolist += 2;
5396     }
5397   }
5398
5399   if (addtolist && (!nobisect || ((nobisect == 1) && (sides == 2)))) {
5400     if (verbose > 2) {
5401       printf("  Queueing encroached segment (%.12g, %.12g) (%.12g, %.12g).\n",
5402              eorg[0], eorg[1], edest[0], edest[1]);
5403     }
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);
5409     } else {
5410       shellecopy(testsym, *badedge);
5411     }
5412   }
5413   return addtolist;
5414 }
5415
5416 #endif /* not CDT_ONLY */
5417
5418 /*****************************************************************************/
5419 /*                                                                           */
5420 /*  testtriangle()   Test a face for quality measures.                       */
5421 /*                                                                           */
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.                                               */
5425 /*                                                                           */
5426 /*****************************************************************************/
5427
5428 #ifndef CDT_ONLY
5429
5430 void testtriangle(testtri)
5431 struct triedge *testtri;
5432 {
5433   struct triedge sametesttri;
5434   struct edge edge1, edge2;
5435   point torg, tdest, tapex;
5436   point anglevertex;
5437   REAL dxod, dyod, dxda, dyda, dxao, dyao;
5438   REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
5439   REAL apexlen, orglen, destlen;
5440   REAL angle;
5441   REAL area;
5442   shelle sptr;                      /* Temporary variable used by tspivot(). */
5443
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);
5478     anglevertex = torg;
5479     tspivot(*testtri, edge1);
5480     lprev(*testtri, sametesttri);
5481     tspivot(sametesttri, edge2);
5482   } else {
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);
5491   }
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. */
5496       if (angle > 1.0) {
5497         /* Beware of a floating exception in acos(). */
5498         angle = 1.0;
5499       }
5500       /* Find the actual angle in degrees, for printing. */
5501       angle = acos(sqrt(angle)) * (180.0 / PI);
5502       printf(
5503       "Warning:  Small angle (%.4g degrees) between segments at point\n",
5504              angle);
5505       printf("  (%.12g, %.12g)\n", anglevertex[0], anglevertex[1]);
5506     }
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.       */
5509     angle = 0.0;
5510   }
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);
5515     return;
5516   }
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);
5528       }
5529     }
5530   }
5531 }
5532
5533 #endif /* not CDT_ONLY */
5534
5535 /**                                                                         **/
5536 /**                                                                         **/
5537 /********* Mesh quality testing routines end here                    *********/
5538
5539 /********* Point location routines begin here                        *********/
5540 /**                                                                         **/
5541 /**                                                                         **/
5542
5543 /*****************************************************************************/
5544 /*                                                                           */
5545 /*  makepointmap()   Construct a mapping from points to triangles to improve  */
5546 /*                  the speed of point location for segment insertion.       */
5547 /*                                                                           */
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.                                               */
5553 /*                                                                           */
5554 /*****************************************************************************/
5555
5556 void makepointmap()
5557 {
5558   struct triedge triangleloop;
5559   point triorg;
5560
5561   if (verbose) {
5562     printf("    Constructing mapping from points to triangles.\n");
5563   }
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));
5572     }
5573     triangleloop.tri = triangletraverse();
5574   }
5575 }
5576
5577 /*****************************************************************************/
5578 /*                                                                           */
5579 /*  preciselocate()   Find a triangle or edge containing a given point.      */
5580 /*                                                                           */
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.)                              */
5586 /*                                                                           */
5587 /*  These conditions are imposed because preciselocate() is normally used in */
5588 /*  one of two situations:                                                   */
5589 /*                                                                           */
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.                                                  */
5596 /*                                                                           */
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.                      */
5601 /*                                                                           */
5602 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
5603 /*                                                                           */
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.                                        */
5613 /*                                                                           */
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.                                                    */
5617 /*                                                                           */
5618 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
5619 /*  is a handle whose origin is the existing vertex.                         */
5620 /*                                                                           */
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.           */
5623 /*                                                                           */
5624 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
5625 /*  `searchtri' is a handle on the triangle that contains the point.         */
5626 /*                                                                           */
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    */
5632 /*  the mesh.                                                                */
5633 /*                                                                           */
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.               */
5638 /*                                                                           */
5639 /*****************************************************************************/
5640
5641 enum locateresult preciselocate(searchpoint, searchtri)
5642 point searchpoint;
5643 struct triedge *searchtri;
5644 {
5645   struct triedge backtracktri;
5646   point forg, fdest, fapex;
5647   point swappoint;
5648   REAL orgorient, destorient;
5649   int moveleft;
5650   triangle ptr;                         /* Temporary variable used by sym(). */
5651
5652   if (verbose > 2) {
5653     printf("  Searching for point (%.12g, %.12g).\n",
5654            searchpoint[0], searchpoint[1]);
5655   }
5656   /* Where are we? */
5657   org(*searchtri, forg);
5658   dest(*searchtri, fdest);
5659   apex(*searchtri, fapex);
5660   while (1) {
5661     if (verbose > 2) {
5662       printf("    At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
5663              forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
5664     }
5665     /* Check whether the apex is the point we seek. */
5666     if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
5667       lprevself(*searchtri);
5668       return ONVERTEX;
5669     }
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;
5685       } else {
5686         moveleft = 1;
5687       }
5688     } else {
5689       if (orgorient > 0.0) {
5690         moveleft = 0;
5691       } else {
5692         /* The point we seek must be on the boundary of or inside this */
5693         /*   triangle.                                                 */
5694         if (destorient == 0.0) {
5695           lprevself(*searchtri);
5696           return ONEDGE;
5697         }
5698         if (orgorient == 0.0) {
5699           lnextself(*searchtri);
5700           return ONEDGE;
5701         }
5702         return INTRIANGLE;
5703       }
5704     }
5705
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.                   */
5710     if (moveleft) {
5711       lprev(*searchtri, backtracktri);
5712       fdest = fapex;
5713     } else {
5714       lnext(*searchtri, backtracktri);
5715       forg = fapex;
5716     }
5717     sym(backtracktri, *searchtri);
5718
5719     /* Check for walking off the edge. */
5720     if (searchtri->tri == dummytri) {
5721       /* Turn around. */
5722       triedgecopy(backtracktri, *searchtri);
5723       swappoint = forg;
5724       forg = fdest;
5725       fdest = swappoint;
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)) {
5731         return OUTSIDE;
5732       }
5733     } else {
5734       apex(*searchtri, fapex);
5735     }
5736   }
5737 }
5738
5739 /*****************************************************************************/
5740 /*                                                                           */
5741 /*  locate()   Find a triangle or edge containing a given point.             */
5742 /*                                                                           */
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.  */
5748 /*                                                                           */
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.                          */
5751 /*                                                                           */
5752 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
5753 /*                                                                           */
5754 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
5755 /*  is a handle whose origin is the existing vertex.                         */
5756 /*                                                                           */
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.           */
5759 /*                                                                           */
5760 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
5761 /*  `searchtri' is a handle on the triangle that contains the point.         */
5762 /*                                                                           */
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    */
5768 /*  the mesh.                                                                */
5769 /*                                                                           */
5770 /*  WARNING:  This routine is designed for convex triangulations, and will   */
5771 /*  not generally work after the holes and concavities have been carved.     */
5772 /*                                                                           */
5773 /*****************************************************************************/
5774
5775 enum locateresult locate(searchpoint, searchtri)
5776 point searchpoint;
5777 struct triedge *searchtri;
5778 {
5779   VOID **sampleblock;
5780   triangle *firsttri;
5781   struct triedge sampletri;
5782   point torg, tdest;
5783   unsigned long alignptr;
5784   REAL searchdist, dist;
5785   REAL ahead;
5786   long sampleblocks, samplesperblock, samplenum;
5787   long triblocks;
5788   long i, j;
5789   triangle ptr;                         /* Temporary variable used by sym(). */
5790
5791   if (verbose > 2) {
5792     printf("  Randomly sampling for a triangle near point (%.12g, %.12g).\n",
5793            searchpoint[0], searchpoint[1]);
5794   }
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]);
5800   if (verbose > 2) {
5801     printf("    Boundary triangle has origin (%.12g, %.12g).\n",
5802            torg[0], torg[1]);
5803   }
5804
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);
5812         return ONVERTEX;
5813       }
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);
5818         searchdist = dist;
5819         if (verbose > 2) {
5820           printf("    Choosing recent triangle with origin (%.12g, %.12g).\n",
5821                  torg[0], torg[1]);
5822         }
5823       }
5824     }
5825   }
5826
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) {
5831     samples++;
5832   }
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)));
5846       } else {
5847         samplenum = randomnation(TRIPERBLOCK);
5848       }
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);
5857           searchdist = dist;
5858           if (verbose > 2) {
5859             printf("    Choosing triangle with origin (%.12g, %.12g).\n",
5860                    torg[0], torg[1]);
5861           }
5862         }
5863       }
5864     }
5865     sampleblock = (VOID **) *sampleblock;
5866   }
5867   /* Where are we? */
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])) {
5872     return ONVERTEX;
5873   }
5874   if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
5875     lnextself(*searchtri);
5876     return ONVERTEX;
5877   }
5878   /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
5879   ahead = counterclockwise(torg, tdest, searchpoint);
5880   if (ahead < 0.0) {
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]))) {
5888       return ONEDGE;
5889     }
5890   }
5891   return preciselocate(searchpoint, searchtri);
5892 }
5893
5894 /**                                                                         **/
5895 /**                                                                         **/
5896 /********* Point location routines end here                          *********/
5897
5898 /********* Mesh transformation routines begin here                   *********/
5899 /**                                                                         **/
5900 /**                                                                         **/
5901
5902 /*****************************************************************************/
5903 /*                                                                           */
5904 /*  insertshelle()   Create a new shell edge and insert it between two       */
5905 /*                   triangles.                                              */
5906 /*                                                                           */
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.          */
5910 /*                                                                           */
5911 /*****************************************************************************/
5912
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. */
5916 {
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(). */
5922
5923   /* Mark points if possible. */
5924   org(*tri, triorg);
5925   dest(*tri, tridest);
5926   if (pointmark(triorg) == 0) {
5927     setpointmark(triorg, shellemark);
5928   }
5929   if (pointmark(tridest) == 0) {
5930     setpointmark(tridest, shellemark);
5931   }
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 */
5942     /*   all the same.                                                    */
5943     tsbond(*tri, newshelle);
5944     sym(*tri, oppotri);
5945     ssymself(newshelle);
5946     tsbond(oppotri, newshelle);
5947     setmark(newshelle, shellemark);
5948     if (verbose > 2) {
5949       printf("  Inserting new ");
5950       printshelle(&newshelle);
5951     }
5952   } else {
5953     if (mark(newshelle) == 0) {
5954       setmark(newshelle, shellemark);
5955     }
5956   }
5957 }
5958
5959 /*****************************************************************************/
5960 /*                                                                           */
5961 /*  Terminology                                                              */
5962 /*                                                                           */
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   */
5965 /*  point.                                                                   */
5966 /*                                                                           */
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.                                              */
5973 /*                                                                           */
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.                                       */
5978 /*                                                                           */
5979 /*****************************************************************************/
5980
5981 /*****************************************************************************/
5982 /*                                                                           */
5983 /*  flip()   Transform two triangles to two different triangles by flipping  */
5984 /*           an edge within a quadrilateral.                                 */
5985 /*                                                                           */
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.        */
5991 /*                                                                           */
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.                                            */
5997 /*                                                                           */
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.)                */
6001 /*                                                                           */
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.                                                       */
6009 /*                                                                           */
6010 /*****************************************************************************/
6011
6012 void flip(flipedge)
6013 struct triedge *flipedge;                    /* Handle for the triangle abc. */
6014 {
6015   struct triedge botleft, botright;
6016   struct triedge topleft, topright;
6017   struct triedge top;
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;
6023   point farpoint;
6024   triangle ptr;                         /* Temporary variable used by sym(). */
6025   shelle sptr;                      /* Temporary variable used by tspivot(). */
6026
6027   /* Identify the vertices of the quadrilateral. */
6028   org(*flipedge, rightpoint);
6029   dest(*flipedge, leftpoint);
6030   apex(*flipedge, botpoint);
6031   sym(*flipedge, top);
6032 #ifdef SELF_CHECK
6033   if (top.tri == dummytri) {
6034     printf("Internal error in flip():  Attempt to flip on boundary.\n");
6035     lnextself(*flipedge);
6036     return;
6037   }
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);
6043       return;
6044     }
6045   }
6046 #endif /* SELF_CHECK */
6047   apex(top, farpoint);
6048
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);
6063
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);
6072     } else {
6073       tsbond(topright, toplshelle);
6074     }
6075     if (botlshelle.sh == dummysh) {
6076       tsdissolve(topleft);
6077     } else {
6078       tsbond(topleft, botlshelle);
6079     }
6080     if (botrshelle.sh == dummysh) {
6081       tsdissolve(botleft);
6082     } else {
6083       tsbond(botleft, botrshelle);
6084     }
6085     if (toprshelle.sh == dummysh) {
6086       tsdissolve(botright);
6087     } else {
6088       tsbond(botright, toprshelle);
6089     }
6090   }
6091
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);
6099   if (verbose > 2) {
6100     printf("  Edge flip results in left ");
6101     lnextself(topleft);
6102     printtriangle(&topleft);
6103     printf("  and right ");
6104     printtriangle(flipedge);
6105   }
6106 }
6107
6108 /*****************************************************************************/
6109 /*                                                                           */
6110 /*  insertsite()   Insert a vertex into a Delaunay triangulation,            */
6111 /*                 performing flips as necessary to maintain the Delaunay    */
6112 /*                 property.                                                 */
6113 /*                                                                           */
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.                                                         */
6124 /*                                                                           */
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.                                                 */
6130 /*                                                                           */
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.                                      */
6135 /*                                                                           */
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.                                       */
6142 /*                                                                           */
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.                        */
6148 /*                                                                           */
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.                                                */
6152 /*                                                                           */
6153 /*****************************************************************************/
6154
6155 enum insertsiteresult insertsite(insertpoint, searchtri, splitedge,
6156                                  segmentflaws, triflaws)
6157 point insertpoint;
6158 struct triedge *searchtri;
6159 struct edge *splitedge;
6160 int segmentflaws;
6161 int triflaws;
6162 {
6163   struct triedge horiz;
6164   struct triedge top;
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;
6179   point first;
6180   point leftpoint, rightpoint, botpoint, toppoint, farpoint;
6181   REAL attrib;
6182   REAL area;
6183   enum insertsiteresult success;
6184   enum locateresult intersect;
6185   int doflip;
6186   int mirrorflag;
6187   int i;
6188   triangle ptr;                         /* Temporary variable used by sym(). */
6189   shelle sptr;         /* Temporary variable used by spivot() and tspivot(). */
6190
6191   if (verbose > 1) {
6192     printf("  Inserting (%.12g, %.12g).\n", insertpoint[0], insertpoint[1]);
6193   }
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;
6200       horiz.orient = 0;
6201       symself(horiz);
6202       /* Search for a triangle containing `insertpoint'. */
6203       intersect = locate(insertpoint, &horiz);
6204     } else {
6205       /* Start searching from the triangle provided by the caller. */
6206       triedgecopy(*searchtri, horiz);
6207       intersect = preciselocate(insertpoint, &horiz);
6208     }
6209   } else {
6210     /* The calling routine provides the edge in which the point is inserted. */
6211     triedgecopy(*searchtri, horiz);
6212     intersect = ONEDGE;
6213   }
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;
6220   }
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. */
6228         if (segmentflaws) {
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);
6240             }
6241           }
6242         }
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;
6248       }
6249     }
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;
6257     if (mirrorflag) {
6258       lnextself(topright);
6259       sym(topright, toprcasing);
6260       maketriangle(&newtopright);
6261     } else {
6262       /* Splitting the boundary edge increases the number of boundary edges. */
6263       hullsize++;
6264     }
6265     maketriangle(&newbotright);
6266
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));
6278     }
6279     if (vararea) {
6280       /* Set the area constraint of a new triangle. */
6281       setareabound(newbotright, areabound(botright));
6282     }
6283     if (mirrorflag) {
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));
6292       }
6293       if (vararea) {
6294         /* Set the area constraint of another new triangle. */
6295         setareabound(newtopright, areabound(topright));
6296       }
6297     }
6298
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);
6306       }
6307       if (mirrorflag) {
6308         tspivot(topright, toprshelle);
6309         if (toprshelle.sh != dummysh) {
6310           tsdissolve(topright);
6311           tsbond(newtopright, toprshelle);
6312         }
6313       }
6314     }
6315
6316     /* Bond the new triangle(s) to the surrounding triangles. */
6317     bond(newbotright, botrcasing);
6318     lprevself(newbotright);
6319     bond(newbotright, botright);
6320     lprevself(newbotright);
6321     if (mirrorflag) {
6322       bond(newtopright, toprcasing);
6323       lnextself(newtopright);
6324       bond(newtopright, topright);
6325       lnextself(newtopright);
6326       bond(newtopright, newbotright);
6327     }
6328
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);
6337       ssymself(newedge);
6338       sbond(newedge, rightedge);
6339       ssymself(*splitedge);
6340     }
6341
6342 #ifdef SELF_CHECK
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");
6346     }
6347     if (mirrorflag) {
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");
6351       }
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"
6355                );
6356       }
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"
6360                );
6361       }
6362     }
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"
6366              );
6367     }
6368     if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
6369       printf("Internal error in insertsite():\n");
6370       printf(
6371         "  Clockwise triangle after edge point insertion (bottom right).\n");
6372     }
6373 #endif /* SELF_CHECK */
6374     if (verbose > 2) {
6375       printf("  Updating bottom left ");
6376       printtriangle(&botright);
6377       if (mirrorflag) {
6378         printf("  Updating top left ");
6379         printtriangle(&topright);
6380         printf("  Creating top right ");
6381         printtriangle(&newtopright);
6382       }
6383       printf("  Creating bottom right ");
6384       printtriangle(&newbotright);
6385     }
6386
6387     /* Position `horiz' on the first edge to check for */
6388     /*   the Delaunay property.                        */
6389     lnextself(horiz);
6390   } else {
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);
6398
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);
6415     }
6416     if (vararea) {
6417       /* Set the area constraint of the new triangles. */
6418       area = areabound(horiz);
6419       setareabound(newbotleft, area);
6420       setareabound(newbotright, area);
6421     }
6422
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);
6430       }
6431       tspivot(botright, botrshelle);
6432       if (botrshelle.sh != dummysh) {
6433         tsdissolve(botright);
6434         tsbond(newbotright, botrshelle);
6435       }
6436     }
6437
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);
6448
6449 #ifdef SELF_CHECK
6450     if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) {
6451       printf("Internal error in insertsite():\n");
6452       printf("  Clockwise triangle prior to point insertion.\n");
6453     }
6454     if (counterclockwise(rightpoint, leftpoint, insertpoint) < 0.0) {
6455       printf("Internal error in insertsite():\n");
6456       printf("  Clockwise triangle after point insertion (top).\n");
6457     }
6458     if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) {
6459       printf("Internal error in insertsite():\n");
6460       printf("  Clockwise triangle after point insertion (left).\n");
6461     }
6462     if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
6463       printf("Internal error in insertsite():\n");
6464       printf("  Clockwise triangle after point insertion (right).\n");
6465     }
6466 #endif /* SELF_CHECK */
6467     if (verbose > 2) {
6468       printf("  Updating top ");
6469       printtriangle(&horiz);
6470       printf("  Creating left ");
6471       printtriangle(&newbotleft);
6472       printf("  Creating right ");
6473       printtriangle(&newbotright);
6474     }
6475   }
6476
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.                                                     */
6484   org(horiz, first);
6485   rightpoint = first;
6486   dest(horiz, leftpoint);
6487   /* Circle until finished. */
6488   while (1) {
6489     /* By default, the edge will be flipped. */
6490     doflip = 1;
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. */
6496         doflip = 0;
6497 #ifndef CDT_ONLY
6498         if (segmentflaws) {
6499           /* Does the new point encroach upon this segment? */
6500           if (checkedge4encroach(&checkshelle)) {
6501             success = ENCROACHINGPOINT;
6502           }
6503         }
6504 #endif /* not CDT_ONLY */
6505       }
6506     }
6507     if (doflip) {
6508       /* Check if the edge is a boundary edge. */
6509       sym(horiz, top);
6510       if (top.tri == dummytri) {
6511         /* The edge is a boundary edge and cannot be flipped. */
6512         doflip = 0;
6513       } else {
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'.           */
6539           doflip = 0;
6540         } else {
6541           /* Test whether the edge is locally Delaunay. */
6542           doflip = incircle(leftpoint, insertpoint, rightpoint, farpoint)
6543                    > 0.0;
6544         }
6545         if (doflip) {
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);
6570             } else {
6571               tsbond(topright, toplshelle);
6572             }
6573             if (botlshelle.sh == dummysh) {
6574               tsdissolve(topleft);
6575             } else {
6576               tsbond(topleft, botlshelle);
6577             }
6578             if (botrshelle.sh == dummysh) {
6579               tsdissolve(botleft);
6580             } else {
6581               tsbond(botleft, botrshelle);
6582             }
6583             if (toprshelle.sh == dummysh) {
6584               tsdissolve(botright);
6585             } else {
6586               tsbond(botright, toprshelle);
6587             }
6588           }
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);
6601           }
6602           if (vararea) {
6603             if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
6604               area = -1.0;
6605             } else {
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)));
6610             }
6611             setareabound(top, area);
6612             setareabound(horiz, area);
6613           }
6614 #ifdef SELF_CHECK
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");
6619             }
6620             /* The following test has been removed because constrainededge() */
6621             /*   sometimes generates inverted triangles that insertsite()    */
6622             /*   removes.                                                    */
6623 /*
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");
6627             }
6628 */
6629             if (counterclockwise(farpoint, leftpoint, insertpoint) < 0.0) {
6630               printf("Internal error in insertsite():\n");
6631               printf("  Clockwise triangle after edge flip (left).\n");
6632             }
6633             if (counterclockwise(insertpoint, rightpoint, farpoint) < 0.0) {
6634               printf("Internal error in insertsite():\n");
6635               printf("  Clockwise triangle after edge flip (right).\n");
6636             }
6637           }
6638 #endif /* SELF_CHECK */
6639           if (verbose > 2) {
6640             printf("  Edge flip results in left ");
6641             lnextself(topleft);
6642             printtriangle(&topleft);
6643             printf("  and right ");
6644             printtriangle(&horiz);
6645           }
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.                                */
6649           lprevself(horiz);
6650           leftpoint = farpoint;
6651         }
6652       }
6653     }
6654     if (!doflip) {
6655       /* The handle `horiz' is accepted as locally Delaunay. */
6656 #ifndef CDT_ONLY
6657       if (triflaws) {
6658         /* Check the triangle `horiz' for quality. */
6659         testtriangle(&horiz);
6660       }
6661 #endif /* not CDT_ONLY */
6662       /* Look for the next edge around the newly inserted point. */
6663       lnextself(horiz);
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);
6672         return success;
6673       }
6674       /* Finish finding the next edge around the newly inserted point. */
6675       lnext(testtri, horiz);
6676       rightpoint = leftpoint;
6677       dest(horiz, leftpoint);
6678     }
6679   }
6680 }
6681
6682 /*****************************************************************************/
6683 /*                                                                           */
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.                           */
6688 /*                                                                           */
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 */
6692 /*  be.                                                                      */
6693 /*                                                                           */
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.                               */
6705 /*                                                                           */
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'.                       */
6710 /*                                                                           */
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.                                         */
6721 /*                                                                           */
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.             */
6727 /*                                                                           */
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.                                            */
6738 /*                                                                           */
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     */
6742 /*  bad.                                                                     */
6743 /*                                                                           */
6744 /*****************************************************************************/
6745
6746 void triangulatepolygon(firstedge, lastedge, edgecount, doflip, triflaws)
6747 struct triedge *firstedge;
6748 struct triedge *lastedge;
6749 int edgecount;
6750 int doflip;
6751 int triflaws;
6752 {
6753   struct triedge testtri;
6754   struct triedge besttri;
6755   struct triedge tempedge;
6756   point leftbasepoint, rightbasepoint;
6757   point testpoint;
6758   point bestpoint;
6759   int bestnumber;
6760   int i;
6761   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
6762
6763   /* Identify the base vertices. */
6764   apex(*lastedge, leftbasepoint);
6765   dest(*firstedge, rightbasepoint);
6766   if (verbose > 2) {
6767     printf("  Triangulating interior polygon at edge\n");
6768     printf("    (%.12g, %.12g) (%.12g, %.12g)\n", leftbasepoint[0],
6769            leftbasepoint[1], rightbasepoint[0], rightbasepoint[1]);
6770   }
6771   /* Find the best vertex to connect the base to. */
6772   onext(*firstedge, besttri);
6773   dest(besttri, bestpoint);
6774   triedgecopy(besttri, testtri);
6775   bestnumber = 1;
6776   for (i = 2; i <= edgecount - 2; i++) {
6777     onextself(testtri);
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;
6783       bestnumber = i;
6784     }
6785   }
6786   if (verbose > 2) {
6787     printf("    Connecting edge to (%.12g, %.12g)\n", bestpoint[0],
6788            bestpoint[1]);
6789   }
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);
6794   }
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,
6799                        triflaws);
6800     /* Find `besttri' again; it may have been lost to edge flips. */
6801     sym(tempedge, besttri);
6802   }
6803   if (doflip) {
6804     /* Do one final edge flip. */
6805     flip(&besttri);
6806 #ifndef CDT_ONLY
6807     if (triflaws) {
6808       /* Check the quality of the newly committed triangle. */
6809       sym(besttri, testtri);
6810       testtriangle(&testtri);
6811     }
6812 #endif /* not CDT_ONLY */
6813   }
6814   /* Return the base triangle. */
6815   triedgecopy(besttri, *lastedge);
6816 }
6817
6818 /*****************************************************************************/
6819 /*                                                                           */
6820 /*  deletesite()   Delete a vertex from a Delaunay triangulation, ensuring   */
6821 /*                 that the triangulation remains Delaunay.                  */
6822 /*                                                                           */
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.                         */
6826 /*                                                                           */
6827 /*  Only interior points that do not lie on segments (shell edges) or        */
6828 /*  boundaries may be deleted.                                               */
6829 /*                                                                           */
6830 /*****************************************************************************/
6831
6832 #ifndef CDT_ONLY
6833
6834 void deletesite(deltri)
6835 struct triedge *deltri;
6836 {
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;
6843   point delpoint;
6844   point neworg;
6845   int edgecount;
6846   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
6847   shelle sptr;                      /* Temporary variable used by tspivot(). */
6848
6849   org(*deltri, delpoint);
6850   if (verbose > 1) {
6851     printf("  Deleting (%.12g, %.12g).\n", delpoint[0], delpoint[1]);
6852   }
6853   pointdealloc(delpoint);
6854
6855   /* Count the degree of the point being deleted. */
6856   onext(*deltri, countingtri);
6857   edgecount = 1;
6858   while (!triedgeequal(*deltri, countingtri)) {
6859 #ifdef SELF_CHECK
6860     if (countingtri.tri == dummytri) {
6861       printf("Internal error in deletesite():\n");
6862       printf("  Attempt to delete boundary point.\n");
6863       internalerror();
6864     }
6865 #endif /* SELF_CHECK */
6866     edgecount++;
6867     onextself(countingtri);
6868   }
6869
6870 #ifdef SELF_CHECK
6871   if (edgecount < 3) {
6872     printf("Internal error in deletesite():\n  Point has degree %d.\n",
6873            edgecount);
6874     internalerror();
6875   }
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);
6884   }
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);
6896   }
6897   tspivot(righttri, rightshelle);
6898   if (rightshelle.sh != dummysh) {
6899     tsbond(deltriright, rightshelle);
6900   }
6901
6902   /* Set the new origin of `deltri' and check its quality. */
6903   org(lefttri, neworg);
6904   setorg(*deltri, neworg);
6905   if (!nobisect) {
6906     testtriangle(deltri);
6907   }
6908
6909   /* Delete the two spliced-out triangles. */
6910   triangledealloc(lefttri.tri);
6911   triangledealloc(righttri.tri);
6912 }
6913
6914 #endif /* not CDT_ONLY */
6915
6916 /**                                                                         **/
6917 /**                                                                         **/
6918 /********* Mesh transformation routines end here                     *********/
6919
6920 /********* Divide-and-conquer Delaunay triangulation begins here     *********/
6921 /**                                                                         **/
6922 /**                                                                         **/
6923
6924 /*****************************************************************************/
6925 /*                                                                           */
6926 /*  The divide-and-conquer bounding box                                      */
6927 /*                                                                           */
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.                                     */
6933 /*                                                                           */
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.      */
6943 /*                                                                           */
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  */
6948 /*  vertex.                                                                  */
6949 /*                                                                           */
6950 /*  The bounding box also makes it easy to traverse the convex hull, as the  */
6951 /*  divide-and-conquer algorithm needs to do.                                */
6952 /*                                                                           */
6953 /*****************************************************************************/
6954
6955 /*****************************************************************************/
6956 /*                                                                           */
6957 /*  pointsort()   Sort an array of points by x-coordinate, using the         */
6958 /*                y-coordinate as a secondary key.                           */
6959 /*                                                                           */
6960 /*  Uses quicksort.  Randomized O(n log n) time.  No, I did not make any of  */
6961 /*  the usual quicksort mistakes.                                            */
6962 /*                                                                           */
6963 /*****************************************************************************/
6964
6965 void pointsort(sortarray, arraysize)
6966 point *sortarray;
6967 int arraysize;
6968 {
6969   int left, right;
6970   int pivot;
6971   REAL pivotx, pivoty;
6972   point temp;
6973
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;
6982     }
6983     return;
6984   }
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. */
6990   left = -1;
6991   right = arraysize;
6992   while (left < right) {
6993     /* Search for a point whose x-coordinate is too large for the left. */
6994     do {
6995       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. */
7000     do {
7001       right--;
7002     } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
7003                                  ((sortarray[right][0] == pivotx) &&
7004                                   (sortarray[right][1] > pivoty))));
7005     if (left < right) {
7006       /* Swap the left and right points. */
7007       temp = sortarray[left];
7008       sortarray[left] = sortarray[right];
7009       sortarray[right] = temp;
7010     }
7011   }
7012   if (left > 1) {
7013     /* Recursively sort the left subset. */
7014     pointsort(sortarray, left);
7015   }
7016   if (right < arraysize - 2) {
7017     /* Recursively sort the right subset. */
7018     pointsort(&sortarray[right + 1], arraysize - right - 1);
7019   }
7020 }
7021
7022 /*****************************************************************************/
7023 /*                                                                           */
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.           */
7027 /*                                                                           */
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.                                                  */
7031 /*                                                                           */
7032 /*****************************************************************************/
7033
7034 void pointmedian(sortarray, arraysize, median, axis)
7035 point *sortarray;
7036 int arraysize;
7037 int median;
7038 int axis;
7039 {
7040   int left, right;
7041   int pivot;
7042   REAL pivot1, pivot2;
7043   point temp;
7044
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;
7053     }
7054     return;
7055   }
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. */
7061   left = -1;
7062   right = arraysize;
7063   while (left < right) {
7064     /* Search for a point whose x-coordinate is too large for the left. */
7065     do {
7066       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. */
7071     do {
7072       right--;
7073     } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
7074                                  ((sortarray[right][axis] == pivot1) &&
7075                                   (sortarray[right][1 - axis] > pivot2))));
7076     if (left < right) {
7077       /* Swap the left and right points. */
7078       temp = sortarray[left];
7079       sortarray[left] = sortarray[right];
7080       sortarray[right] = temp;
7081     }
7082   }
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);
7088   }
7089   if (right < median - 1) {
7090     /* Recursively shuffle the right subset. */
7091     pointmedian(&sortarray[right + 1], arraysize - right - 1,
7092                 median - right - 1, axis);
7093   }
7094 }
7095
7096 /*****************************************************************************/
7097 /*                                                                           */
7098 /*  alternateaxes()   Sorts the points as appropriate for the divide-and-    */
7099 /*                    conquer algorithm with alternating cuts.               */
7100 /*                                                                           */
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.                                           */
7104 /*                                                                           */
7105 /*****************************************************************************/
7106
7107 void alternateaxes(sortarray, arraysize, axis)
7108 point *sortarray;
7109 int arraysize;
7110 int axis;
7111 {
7112   int divider;
7113
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. */
7118     axis = 0;
7119   }
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) {
7124     if (divider >= 2) {
7125       alternateaxes(sortarray, divider, 1 - axis);
7126     }
7127     alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
7128   }
7129 }
7130
7131 /*****************************************************************************/
7132 /*                                                                           */
7133 /*  mergehulls()   Merge two adjacent Delaunay triangulations into a         */
7134 /*                 single Delaunay triangulation.                            */
7135 /*                                                                           */
7136 /*  This is similar to the algorithm given by Guibas and Stolfi, but uses    */
7137 /*  a triangle-based, rather than edge-based, data structure.                */
7138 /*                                                                           */
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.                                       */
7147 /*                                                                           */
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.                                  */
7152 /*                                                                           */
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.       */
7159 /*                                                                           */
7160 /*  On completion, the origin of `farleft' is the leftmost vertex of the     */
7161 /*  merged triangulation, and the destination of `farright' is the rightmost */
7162 /*  vertex.                                                                  */
7163 /*                                                                           */
7164 /*****************************************************************************/
7165
7166 void mergehulls(farleft, innerleft, innerright, farright, axis)
7167 struct triedge *farleft;
7168 struct triedge *innerleft;
7169 struct triedge *innerright;
7170 struct triedge *farright;
7171 int axis;
7172 {
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;
7185   point nextapex;
7186   point checkvertex;
7187   int changemade;
7188   int badedge;
7189   int leftfinished, rightfinished;
7190   triangle ptr;                         /* Temporary variable used by sym(). */
7191
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);
7207       symself(*farleft);
7208       farleftpt = farleftapex;
7209       apex(*farleft, farleftapex);
7210     }
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);
7219     }
7220     while (innerrightapex[1] < innerrightorg[1]) {
7221       lnextself(*innerright);
7222       symself(*innerright);
7223       innerrightorg = innerrightapex;
7224       apex(*innerright, innerrightapex);
7225     }
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);
7234     }
7235   }
7236   /* Find a line tangent to and below both hulls. */
7237   do {
7238     changemade = 0;
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);
7245       changemade = 1;
7246     }
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);
7253       changemade = 1;
7254     }
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. */
7269   if (verbose > 2) {
7270     printf("  Creating base bounding ");
7271     printtriangle(&baseedge);
7272   }
7273   /* Fix the extreme triangles if necessary. */
7274   org(*farleft, farleftpt);
7275   if (innerleftdest == farleftpt) {
7276     lnext(baseedge, *farleft);
7277   }
7278   dest(*farright, farrightpt);
7279   if (innerrightorg == farrightpt) {
7280     lprev(baseedge, *farright);
7281   }
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. */
7289   while (1) {
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);
7308       if (verbose > 2) {
7309         printf("  Creating top bounding ");
7310         printtriangle(&baseedge);
7311       }
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);
7328         }
7329         while (farrightapex[0] > farrightpt[0]) {
7330           lprevself(*farright);
7331           symself(*farright);
7332           farrightpt = farrightapex;
7333           apex(*farright, farrightapex);
7334         }
7335       }
7336       return;
7337     }
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);
7342       symself(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;
7349         while (badedge) {
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)
7377                       > 0.0;
7378           } else {
7379             /* Avoid eating right through the triangulation. */
7380             badedge = 0;
7381           }
7382         }
7383       }
7384     }
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);
7389       symself(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;
7396         while (badedge) {
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)
7424                       > 0.0;
7425           } else {
7426             /* Avoid eating right through the triangulation. */
7427             badedge = 0;
7428           }
7429         }
7430       }
7431     }
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);
7442     } else {
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);
7451     }
7452     if (verbose > 2) {
7453       printf("  Connecting ");
7454       printtriangle(&baseedge);
7455     }
7456   }
7457 }
7458
7459 /*****************************************************************************/
7460 /*                                                                           */
7461 /*  divconqrecurse()   Recursively form a Delaunay triangulation by the      */
7462 /*                     divide-and-conquer method.                            */
7463 /*                                                                           */
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.                                */
7467 /*                                                                           */
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).                                                */
7473 /*                                                                           */
7474 /*****************************************************************************/
7475
7476 void divconqrecurse(sortarray, vertices, axis, farleft, farright)
7477 point *sortarray;
7478 int vertices;
7479 int axis;
7480 struct triedge *farleft;
7481 struct triedge *farright;
7482 {
7483   struct triedge midtri, tri1, tri2, tri3;
7484   struct triedge innerleft, innerright;
7485   REAL area;
7486   int divider;
7487
7488   if (verbose > 2) {
7489     printf("  Triangulating %d points.\n", vertices);
7490   }
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);
7509     if (verbose > 2) {
7510       printf("  Creating ");
7511       printtriangle(farleft);
7512       printf("  Creating ");
7513       printtriangle(farright);
7514     }
7515     /* Ensure that the origin of `farleft' is sortarray[0]. */
7516     lprev(*farright, *farleft);
7517     return;
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]);
7527     if (area == 0.0) {
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. */
7538       bond(midtri, tri1);
7539       bond(tri2, tri3);
7540       lnextself(midtri);
7541       lprevself(tri1);
7542       lnextself(tri2);
7543       lprevself(tri3);
7544       bond(midtri, tri3);
7545       bond(tri1, tri2);
7546       lnextself(midtri);
7547       lprevself(tri1);
7548       lnextself(tri2);
7549       lprevself(tri3);
7550       bond(midtri, tri1);
7551       bond(tri2, tri3);
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);
7556     } else {
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. */
7563       if (area > 0.0) {
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]);
7571       } else {
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]);
7579       }
7580       /* The topology does not depend on how the vertices are ordered. */
7581       bond(midtri, tri1);
7582       lnextself(midtri);
7583       bond(midtri, tri2);
7584       lnextself(midtri);
7585       bond(midtri, tri3);
7586       lprevself(tri1);
7587       lnextself(tri2);
7588       bond(tri1, tri2);
7589       lprevself(tri1);
7590       lprevself(tri3);
7591       bond(tri1, tri3);
7592       lnextself(tri2);
7593       lprevself(tri3);
7594       bond(tri2, tri3);
7595       /* Ensure that the origin of `farleft' is sortarray[0]. */
7596       triedgecopy(tri1, *farleft);
7597       /* Ensure that the destination of `farright' is sortarray[2]. */
7598       if (area > 0.0) {
7599         triedgecopy(tri2, *farright);
7600       } else {
7601         lnext(*farleft, *farright);
7602       }
7603     }
7604     if (verbose > 2) {
7605       printf("  Creating ");
7606       printtriangle(&midtri);
7607       printf("  Creating ");
7608       printtriangle(&tri1);
7609       printf("  Creating ");
7610       printtriangle(&tri2);
7611       printf("  Creating ");
7612       printtriangle(&tri3);
7613     }
7614     return;
7615   } else {
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);
7622     if (verbose > 1) {
7623       printf("  Joining triangulations with %d and %d vertices.\n", divider,
7624              vertices - divider);
7625     }
7626     /* Merge the two triangulations into one. */
7627     mergehulls(farleft, &innerleft, &innerright, farright, axis);
7628   }
7629 }
7630
7631 long removeghosts(startghost)
7632 struct triedge *startghost;
7633 {
7634   struct triedge searchedge;
7635   struct triedge dissolveedge;
7636   struct triedge deadtri;
7637   point markorg;
7638   long hullsize;
7639   triangle ptr;                         /* Temporary variable used by sym(). */
7640
7641   if (verbose) {
7642     printf("  Removing ghost triangles.\n");
7643   }
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);
7650   hullsize = 0;
7651   do {
7652     hullsize++;
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. */
7658     if (!poly) {
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);
7664         }
7665       }
7666     }
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));
7674   return hullsize;
7675 }
7676
7677 /*****************************************************************************/
7678 /*                                                                           */
7679 /*  divconqdelaunay()   Form a Delaunay triangulation by the divide-and-     */
7680 /*                      conquer method.                                      */
7681 /*                                                                           */
7682 /*  Sorts the points, calls a recursive procedure to triangulate them, and   */
7683 /*  removes the bounding box, setting boundary markers as appropriate.       */
7684 /*                                                                           */
7685 /*****************************************************************************/
7686
7687 long divconqdelaunay()
7688 {
7689   point *sortarray;
7690   struct triedge hullleft, hullright;
7691   int divider;
7692   int i, j;
7693
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");
7698     exit(1);
7699   }
7700   traversalinit(&points);
7701   for (i = 0; i < inpoints; i++) {
7702     sortarray[i] = pointtraverse();
7703   }
7704   if (verbose) {
7705     printf("  Sorting points.\n");
7706   }
7707   /* Sort the points. */
7708   pointsort(sortarray, inpoints);
7709   /* Discard duplicate points, which can really mess up the algorithm. */
7710   i = 0;
7711   for (j = 1; j < inpoints; j++) {
7712     if ((sortarray[i][0] == sortarray[j][0])
7713         && (sortarray[i][1] == sortarray[j][1])) {
7714       if (!quiet) {
7715         printf(
7716 "Warning:  A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
7717                sortarray[j][0], sortarray[j][1]);
7718       }
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);
7722 */
7723     } else {
7724       i++;
7725       sortarray[i] = sortarray[j];
7726     }
7727   }
7728   i++;
7729   if (dwyer) {
7730     /* Re-sort the array of points to accommodate alternating cuts. */
7731     divider = i >> 1;
7732     if (i - divider >= 2) {
7733       if (divider >= 2) {
7734         alternateaxes(sortarray, divider, 1);
7735       }
7736       alternateaxes(&sortarray[divider], i - divider, 1);
7737     }
7738   }
7739   if (verbose) {
7740     printf("  Forming triangulation.\n");
7741   }
7742   /* Form the Delaunay triangulation. */
7743   divconqrecurse(sortarray, i, 0, &hullleft, &hullright);
7744   free(sortarray);
7745
7746   return removeghosts(&hullleft);
7747 }
7748
7749 /**                                                                         **/
7750 /**                                                                         **/
7751 /********* Divide-and-conquer Delaunay triangulation ends here       *********/
7752
7753 /********* Incremental Delaunay triangulation begins here            *********/
7754 /**                                                                         **/
7755 /**                                                                         **/
7756
7757 /*****************************************************************************/
7758 /*                                                                           */
7759 /*  boundingbox()   Form an "infinite" bounding triangle to insert points    */
7760 /*                  into.                                                    */
7761 /*                                                                           */
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.                                                      */
7765 /*                                                                           */
7766 /*****************************************************************************/
7767
7768 #ifndef REDUCED
7769
7770 void boundingbox()
7771 {
7772   struct triedge inftri;          /* Handle for the triangular bounding box. */
7773   REAL width;
7774
7775   if (verbose) {
7776     printf("  Creating triangular bounding box.\n");
7777   }
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;
7782   }
7783   if (width == 0.0) {
7784     width = 1.0;
7785   }
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");
7793     exit(1);
7794   }
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;
7801
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;
7810   if (verbose > 2) {
7811     printf("  Creating ");
7812     printtriangle(&inftri);
7813   }
7814 }
7815
7816 #endif /* not REDUCED */
7817
7818 /*****************************************************************************/
7819 /*                                                                           */
7820 /*  removebox()   Remove the "infinite" bounding triangle, setting boundary  */
7821 /*                markers as appropriate.                                    */
7822 /*                                                                           */
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.   */
7827 /*                                                                           */
7828 /*****************************************************************************/
7829
7830 #ifndef REDUCED
7831
7832 long removebox()
7833 {
7834   struct triedge deadtri;
7835   struct triedge searchedge;
7836   struct triedge checkedge;
7837   struct triedge nextedge, finaledge, dissolveedge;
7838   point markorg;
7839   long hullsize;
7840   triangle ptr;                         /* Temporary variable used by sym(). */
7841
7842   if (verbose) {
7843     printf("  Removing triangular bounding box.\n");
7844   }
7845   /* Find a boundary triangle. */
7846   nextedge.tri = dummytri;
7847   nextedge.orient = 0;
7848   symself(nextedge);
7849   /* Mark a place to stop. */
7850   lprev(nextedge, finaledge);
7851   lnextself(nextedge);
7852   symself(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);
7860   symself(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);
7867   }
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);
7871   hullsize = -2l;
7872   while (!triedgeequal(nextedge, finaledge)) {
7873     hullsize++;
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.)        */
7878     if (!poly) {
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);
7887         }
7888       }
7889     }
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);
7900     }
7901   }
7902   triangledealloc(finaledge.tri);
7903
7904   free(infpoint1);                  /* Deallocate the bounding box vertices. */
7905   free(infpoint2);
7906   free(infpoint3);
7907
7908   return hullsize;
7909 }
7910
7911 #endif /* not REDUCED */
7912
7913 /*****************************************************************************/
7914 /*                                                                           */
7915 /*  incrementaldelaunay()   Form a Delaunay triangulation by incrementally   */
7916 /*                          adding vertices.                                 */
7917 /*                                                                           */
7918 /*****************************************************************************/
7919
7920 #ifndef REDUCED
7921
7922 long incrementaldelaunay()
7923 {
7924   struct triedge starttri;
7925   point pointloop;
7926   int i;
7927
7928   /* Create a triangular bounding box. */
7929   boundingbox();
7930   if (verbose) {
7931     printf("  Incrementally inserting points.\n");
7932   }
7933   traversalinit(&points);
7934   pointloop = pointtraverse();
7935   i = 1;
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) ==
7940         DUPLICATEPOINT) {
7941       if (!quiet) {
7942         printf(
7943 "Warning:  A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
7944                pointloop[0], pointloop[1]);
7945       }
7946 /*  Commented out - would eliminate point from output .node file.
7947       setpointmark(pointloop, DEADPOINT);
7948 */
7949     }
7950     pointloop = pointtraverse();
7951     i++;
7952   }
7953   /* Remove the bounding box. */
7954   return removebox();
7955 }
7956
7957 #endif /* not REDUCED */
7958
7959 /**                                                                         **/
7960 /**                                                                         **/
7961 /********* Incremental Delaunay triangulation ends here              *********/
7962
7963 /********* Sweepline Delaunay triangulation begins here              *********/
7964 /**                                                                         **/
7965 /**                                                                         **/
7966
7967 #ifndef REDUCED
7968
7969 void eventheapinsert(heap, heapsize, newevent)
7970 struct event **heap;
7971 int heapsize;
7972 struct event *newevent;
7973 {
7974   REAL eventx, eventy;
7975   int eventnum;
7976   int parent;
7977   int notdone;
7978
7979   eventx = newevent->xkey;
7980   eventy = newevent->ykey;
7981   eventnum = heapsize;
7982   notdone = eventnum > 0;
7983   while (notdone) {
7984     parent = (eventnum - 1) >> 1;
7985     if ((heap[parent]->ykey < eventy) ||
7986         ((heap[parent]->ykey == eventy)
7987          && (heap[parent]->xkey <= eventx))) {
7988       notdone = 0;
7989     } else {
7990       heap[eventnum] = heap[parent];
7991       heap[eventnum]->heapposition = eventnum;
7992
7993       eventnum = parent;
7994       notdone = eventnum > 0;
7995     }
7996   }
7997   heap[eventnum] = newevent;
7998   newevent->heapposition = eventnum;
7999 }
8000
8001 #endif /* not REDUCED */
8002
8003 #ifndef REDUCED
8004
8005 void eventheapify(heap, heapsize, eventnum)
8006 struct event **heap;
8007 int heapsize;
8008 int eventnum;
8009 {
8010   struct event *thisevent;
8011   REAL eventx, eventy;
8012   int leftchild, rightchild;
8013   int smallest;
8014   int notdone;
8015
8016   thisevent = heap[eventnum];
8017   eventx = thisevent->xkey;
8018   eventy = thisevent->ykey;
8019   leftchild = 2 * eventnum + 1;
8020   notdone = leftchild < heapsize;
8021   while (notdone) {
8022     if ((heap[leftchild]->ykey < eventy) ||
8023         ((heap[leftchild]->ykey == eventy)
8024          && (heap[leftchild]->xkey < eventx))) {
8025       smallest = leftchild;
8026     } else {
8027       smallest = eventnum;
8028     }
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;
8035       }
8036     }
8037     if (smallest == eventnum) {
8038       notdone = 0;
8039     } else {
8040       heap[eventnum] = heap[smallest];
8041       heap[eventnum]->heapposition = eventnum;
8042       heap[smallest] = thisevent;
8043       thisevent->heapposition = smallest;
8044
8045       eventnum = smallest;
8046       leftchild = 2 * eventnum + 1;
8047       notdone = leftchild < heapsize;
8048     }
8049   }
8050 }
8051
8052 #endif /* not REDUCED */
8053
8054 #ifndef REDUCED
8055
8056 void eventheapdelete(heap, heapsize, eventnum)
8057 struct event **heap;
8058 int heapsize;
8059 int eventnum;
8060 {
8061   struct event *moveevent;
8062   REAL eventx, eventy;
8063   int parent;
8064   int notdone;
8065
8066   moveevent = heap[heapsize - 1];
8067   if (eventnum > 0) {
8068     eventx = moveevent->xkey;
8069     eventy = moveevent->ykey;
8070     do {
8071       parent = (eventnum - 1) >> 1;
8072       if ((heap[parent]->ykey < eventy) ||
8073           ((heap[parent]->ykey == eventy)
8074            && (heap[parent]->xkey <= eventx))) {
8075         notdone = 0;
8076       } else {
8077         heap[eventnum] = heap[parent];
8078         heap[eventnum]->heapposition = eventnum;
8079
8080         eventnum = parent;
8081         notdone = eventnum > 0;
8082       }
8083     } while (notdone);
8084   }
8085   heap[eventnum] = moveevent;
8086   moveevent->heapposition = eventnum;
8087   eventheapify(heap, heapsize - 1, eventnum);
8088 }
8089
8090 #endif /* not REDUCED */
8091
8092 #ifndef REDUCED
8093
8094 void createeventheap(eventheap, events, freeevents)
8095 struct event ***eventheap;
8096 struct event **events;
8097 struct event **freeevents;
8098 {
8099   point thispoint;
8100   int maxevents;
8101   int i;
8102
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");
8107     exit(1);
8108   }
8109   *events = (struct event *) malloc(maxevents * sizeof(struct event));
8110   if (*events == (struct event *) NULL) {
8111     printf("Error:  Out of memory.\n");
8112     exit(1);
8113   }
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);
8121   }
8122   *freeevents = (struct event *) NULL;
8123   for (i = maxevents - 1; i >= inpoints; i--) {
8124     (*events)[i].eventptr = (VOID *) *freeevents;
8125     *freeevents = *events + i;
8126   }
8127 }
8128
8129 #endif /* not REDUCED */
8130
8131 #ifndef REDUCED
8132
8133 int rightofhyperbola(fronttri, newsite)
8134 struct triedge *fronttri;
8135 point newsite;
8136 {
8137   point leftpoint, rightpoint;
8138   REAL dxa, dya, dxb, dyb;
8139
8140   hyperbolacount++;
8141
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]) {
8147       return 1;
8148     }
8149   } else {
8150     if (newsite[0] <= leftpoint[0]) {
8151       return 0;
8152     }
8153   }
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);
8159 }
8160
8161 #endif /* not REDUCED */
8162
8163 #ifndef REDUCED
8164
8165 REAL circletop(pa, pb, pc, ccwabc)
8166 point pa;
8167 point pb;
8168 point pc;
8169 REAL ccwabc;
8170 {
8171   REAL xac, yac, xbc, ybc, xab, yab;
8172   REAL aclen2, bclen2, ablen2;
8173
8174   circletopcount++;
8175
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))
8186                / (2.0 * ccwabc);
8187 }
8188
8189 #endif /* not REDUCED */
8190
8191 #ifndef REDUCED
8192
8193 void check4deadevent(checktri, freeevents, eventheap, heapsize)
8194 struct triedge *checktri;
8195 struct event **freeevents;
8196 struct event **eventheap;
8197 int *heapsize;
8198 {
8199   struct event *deadevent;
8200   point eventpoint;
8201   int eventnum;
8202
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);
8210     (*heapsize)--;
8211     setorg(*checktri, NULL);
8212   }
8213 }
8214
8215 #endif /* not REDUCED */
8216
8217 #ifndef REDUCED
8218
8219 struct splaynode *splay(splaytree, searchpoint, searchtri)
8220 struct splaynode *splaytree;
8221 point searchpoint;
8222 struct triedge *searchtri;
8223 {
8224   struct splaynode *child, *grandchild;
8225   struct splaynode *lefttree, *righttree;
8226   struct splaynode *leftright;
8227   point checkpoint;
8228   int rightofroot, rightofchild;
8229
8230   if (splaytree == (struct splaynode *) NULL) {
8231     return (struct splaynode *) NULL;
8232   }
8233   dest(splaytree->keyedge, checkpoint);
8234   if (checkpoint == splaytree->keydest) {
8235     rightofroot = rightofhyperbola(&splaytree->keyedge, searchpoint);
8236     if (rightofroot) {
8237       triedgecopy(splaytree->keyedge, *searchtri);
8238       child = splaytree->rchild;
8239     } else {
8240       child = splaytree->lchild;
8241     }
8242     if (child == (struct splaynode *) NULL) {
8243       return splaytree;
8244     }
8245     dest(child->keyedge, checkpoint);
8246     if (checkpoint != child->keydest) {
8247       child = splay(child, searchpoint, searchtri);
8248       if (child == (struct splaynode *) NULL) {
8249         if (rightofroot) {
8250           splaytree->rchild = (struct splaynode *) NULL;
8251         } else {
8252           splaytree->lchild = (struct splaynode *) NULL;
8253         }
8254         return splaytree;
8255       }
8256     }
8257     rightofchild = rightofhyperbola(&child->keyedge, searchpoint);
8258     if (rightofchild) {
8259       triedgecopy(child->keyedge, *searchtri);
8260       grandchild = splay(child->rchild, searchpoint, searchtri);
8261       child->rchild = grandchild;
8262     } else {
8263       grandchild = splay(child->lchild, searchpoint, searchtri);
8264       child->lchild = grandchild;
8265     }
8266     if (grandchild == (struct splaynode *) NULL) {
8267       if (rightofroot) {
8268         splaytree->rchild = child->lchild;
8269         child->lchild = splaytree;
8270       } else {
8271         splaytree->lchild = child->rchild;
8272         child->rchild = splaytree;
8273       }
8274       return child;
8275     }
8276     if (rightofchild) {
8277       if (rightofroot) {
8278         splaytree->rchild = child->lchild;
8279         child->lchild = splaytree;
8280       } else {
8281         splaytree->lchild = grandchild->rchild;
8282         grandchild->rchild = splaytree;
8283       }
8284       child->rchild = grandchild->lchild;
8285       grandchild->lchild = child;
8286     } else {
8287       if (rightofroot) {
8288         splaytree->rchild = grandchild->lchild;
8289         grandchild->lchild = splaytree;
8290       } else {
8291         splaytree->lchild = child->rchild;
8292         child->rchild = splaytree;
8293       }
8294       child->lchild = grandchild->rchild;
8295       grandchild->rchild = child;
8296     }
8297     return grandchild;
8298   } else {
8299     lefttree = splay(splaytree->lchild, searchpoint, searchtri);
8300     righttree = splay(splaytree->rchild, searchpoint, searchtri);
8301
8302     pooldealloc(&splaynodes, (VOID *) splaytree);
8303     if (lefttree == (struct splaynode *) NULL) {
8304       return righttree;
8305     } else if (righttree == (struct splaynode *) NULL) {
8306       return lefttree;
8307     } else if (lefttree->rchild == (struct splaynode *) NULL) {
8308       lefttree->rchild = righttree->lchild;
8309       righttree->lchild = lefttree;
8310       return righttree;
8311     } else if (righttree->lchild == (struct splaynode *) NULL) {
8312       righttree->lchild = lefttree->rchild;
8313       lefttree->rchild = righttree;
8314       return lefttree;
8315     } else {
8316 /*      printf("Holy Toledo!!!\n"); */
8317       leftright = lefttree->rchild;
8318       while (leftright->rchild != (struct splaynode *) NULL) {
8319         leftright = leftright->rchild;
8320       }
8321       leftright->rchild = righttree;
8322       return lefttree;
8323     }
8324   }
8325 }
8326
8327 #endif /* not REDUCED */
8328
8329 #ifndef REDUCED
8330
8331 struct splaynode *splayinsert(splayroot, newkey, searchpoint)
8332 struct splaynode *splayroot;
8333 struct triedge *newkey;
8334 point searchpoint;
8335 {
8336   struct splaynode *newsplaynode;
8337
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;
8348   } else {
8349     newsplaynode->lchild = splayroot->lchild;
8350     newsplaynode->rchild = splayroot;
8351     splayroot->lchild = (struct splaynode *) NULL;
8352   }
8353   return newsplaynode;
8354 }
8355
8356 #endif /* not REDUCED */
8357
8358 #ifndef REDUCED
8359
8360 struct splaynode *circletopinsert(splayroot, newkey, pa, pb, pc, topy)
8361 struct splaynode *splayroot;
8362 struct triedge *newkey;
8363 point pa;
8364 point pb;
8365 point pc;
8366 REAL topy;
8367 {
8368   REAL ccwabc;
8369   REAL xac, yac, xbc, ybc;
8370   REAL aclen2, bclen2;
8371   REAL searchpoint[2];
8372   struct triedge dummytri;
8373
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);
8385 }
8386
8387 #endif /* not REDUCED */
8388
8389 #ifndef REDUCED
8390
8391 struct splaynode *frontlocate(splayroot, bottommost, searchpoint, searchtri,
8392                               farright)
8393 struct splaynode *splayroot;
8394 struct triedge *bottommost;
8395 point searchpoint;
8396 struct triedge *searchtri;
8397 int *farright;
8398 {
8399   int farrightflag;
8400   triangle ptr;                       /* Temporary variable used by onext(). */
8401
8402   triedgecopy(*bottommost, *searchtri);
8403   splayroot = splay(splayroot, searchpoint, searchtri);
8404
8405   farrightflag = 0;
8406   while (!farrightflag && rightofhyperbola(searchtri, searchpoint)) {
8407     onextself(*searchtri);
8408     farrightflag = triedgeequal(*searchtri, *bottommost);
8409   }
8410   *farright = farrightflag;
8411   return splayroot;
8412 }
8413
8414 #endif /* not REDUCED */
8415
8416 #ifndef REDUCED
8417
8418 long sweeplinedelaunay()
8419 {
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;
8433   point connectpoint;
8434   point leftpoint, midpoint, rightpoint;
8435   REAL lefttest, righttest;
8436   int heapsize;
8437   int check4events, farrightflag;
8438   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8439
8440   poolinit(&splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK, POINTER,
8441            0);
8442   splayroot = (struct splaynode *) NULL;
8443
8444   if (verbose) {
8445     printf("  Placing points in event heap.\n");
8446   }
8447   createeventheap(&eventheap, &events, &freeevents);
8448   heapsize = inpoints;
8449
8450   if (verbose) {
8451     printf("  Forming triangulation.\n");
8452   }
8453   maketriangle(&lefttri);
8454   maketriangle(&righttri);
8455   bond(lefttri, righttri);
8456   lnextself(lefttri);
8457   lprevself(righttri);
8458   bond(lefttri, righttri);
8459   lnextself(lefttri);
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);
8466   heapsize--;
8467   do {
8468     if (heapsize == 0) {
8469       printf("Error:  Input points are all identical.\n");
8470       exit(1);
8471     }
8472     secondpoint = (point) eventheap[0]->eventptr;
8473     eventheap[0]->eventptr = (VOID *) freeevents;
8474     freeevents = eventheap[0];
8475     eventheapdelete(eventheap, heapsize, 0);
8476     heapsize--;
8477     if ((firstpoint[0] == secondpoint[0])
8478         && (firstpoint[1] == secondpoint[1])) {
8479       printf(
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);
8484 */
8485     }
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);
8497     heapsize--;
8498     check4events = 1;
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);
8505
8506       if (triedgeequal(farlefttri, bottommost)) {
8507         lprev(fliptri, bottommost);
8508       }
8509       flip(&fliptri);
8510       setapex(fliptri, NULL);
8511       lprev(fliptri, lefttri);
8512       lnext(fliptri, righttri);
8513       sym(lefttri, farlefttri);
8514
8515       if (randomnation(SAMPLERATE) == 0) {
8516         symself(fliptri);
8517         dest(fliptri, leftpoint);
8518         apex(fliptri, midpoint);
8519         org(fliptri, rightpoint);
8520         splayroot = circletopinsert(splayroot, &lefttri, leftpoint, midpoint,
8521                                     rightpoint, nextevent->ykey);
8522       }
8523     } else {
8524       nextpoint = (point) nextevent->eventptr;
8525       if ((nextpoint[0] == lastpoint[0]) && (nextpoint[1] == lastpoint[1])) {
8526         printf(
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);
8531 */
8532         check4events = 0;
8533       } else {
8534         lastpoint = nextpoint;
8535
8536         splayroot = frontlocate(splayroot, &bottommost, nextpoint, &searchtri,
8537                                 &farrightflag);
8538 /*
8539         triedgecopy(bottommost, searchtri);
8540         farrightflag = 0;
8541         while (!farrightflag && rightofhyperbola(&searchtri, nextpoint)) {
8542           onextself(searchtri);
8543           farrightflag = triedgeequal(searchtri, bottommost);
8544         }
8545 */
8546
8547         check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
8548
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);
8559         lnextself(lefttri);
8560         lprevself(righttri);
8561         bond(lefttri, righttri);
8562         lnextself(lefttri);
8563         lprevself(righttri);
8564         bond(lefttri, farlefttri);
8565         bond(righttri, farrighttri);
8566         if (!farrightflag && triedgeequal(farrighttri, bottommost)) {
8567           triedgecopy(lefttri, bottommost);
8568         }
8569
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);
8575         }
8576       }
8577     }
8578     nextevent->eventptr = (VOID *) freeevents;
8579     freeevents = nextevent;
8580
8581     if (check4events) {
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,
8591                                    lefttest);
8592         newevent->eventptr = (VOID *) encode(lefttri);
8593         eventheapinsert(eventheap, heapsize, newevent);
8594         heapsize++;
8595         setorg(lefttri, newevent);
8596       }
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,
8606                                    righttest);
8607         newevent->eventptr = (VOID *) encode(farrighttri);
8608         eventheapinsert(eventheap, heapsize, newevent);
8609         heapsize++;
8610         setorg(farrighttri, newevent);
8611       }
8612     }
8613   }
8614
8615   pooldeinit(&splaynodes);
8616   lprevself(bottommost);
8617   return removeghosts(&bottommost);
8618 }
8619
8620 #endif /* not REDUCED */
8621
8622 /**                                                                         **/
8623 /**                                                                         **/
8624 /********* Sweepline Delaunay triangulation ends here                *********/
8625
8626 /********* General mesh construction routines begin here             *********/
8627 /**                                                                         **/
8628 /**                                                                         **/
8629
8630 /*****************************************************************************/
8631 /*                                                                           */
8632 /*  delaunay()   Form a Delaunay triangulation.                              */
8633 /*                                                                           */
8634 /*****************************************************************************/
8635
8636 long delaunay()
8637 {
8638   eextras = 0;
8639   initializetrisegpools();
8640
8641 #ifdef REDUCED
8642   if (!quiet) {
8643     printf(
8644       "Constructing Delaunay triangulation by divide-and-conquer method.\n");
8645   }
8646   return divconqdelaunay();
8647 #else /* not REDUCED */
8648   if (!quiet) {
8649     printf("Constructing Delaunay triangulation ");
8650     if (incremental) {
8651       printf("by incremental method.\n");
8652     } else if (sweepline) {
8653       printf("by sweepline method.\n");
8654     } else {
8655       printf("by divide-and-conquer method.\n");
8656     }
8657   }
8658   if (incremental) {
8659     return incrementaldelaunay();
8660   } else if (sweepline) {
8661     return sweeplinedelaunay();
8662   } else {
8663     return divconqdelaunay();
8664   }
8665 #endif /* not REDUCED */
8666 }
8667
8668 /*****************************************************************************/
8669 /*                                                                           */
8670 /*  reconstruct()   Reconstruct a triangulation from its .ele (and possibly  */
8671 /*                  .poly) file.  Used when the -r switch is used.           */
8672 /*                                                                           */
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.                                                        */
8678 /*                                                                           */
8679 /*  Points that are not corners of triangles, such as nodes on edges of      */
8680 /*  subparametric elements, are discarded.                                   */
8681 /*                                                                           */
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.                                     */
8690 /*                                                                           */
8691 /*****************************************************************************/
8692
8693 #ifndef CDT_ONLY
8694
8695 #ifdef TRILIBRARY
8696
8697 int reconstruct(trianglelist, triangleattriblist, trianglearealist, elements,
8698                 corners, attribs, segmentlist, segmentmarkerlist,
8699                 numberofsegments)
8700 int *trianglelist;
8701 REAL *triangleattriblist;
8702 REAL *trianglearealist;
8703 int elements;
8704 int corners;
8705 int attribs;
8706 int *segmentlist;
8707 int *segmentmarkerlist;
8708 int numberofsegments;
8709
8710 #else /* not TRILIBRARY */
8711
8712 long reconstruct(elefilename, areafilename, polyfilename, polyfile)
8713 char *elefilename;
8714 char *areafilename;
8715 char *polyfilename;
8716 FILE *polyfile;
8717
8718 #endif /* not TRILIBRARY */
8719
8720 {
8721 #ifdef TRILIBRARY
8722   int pointindex;
8723   int attribindex;
8724 #else /* not TRILIBRARY */
8725   FILE *elefile;
8726   FILE *areafile;
8727   char inputline[INPUTLINESIZE];
8728   char *stringptr;
8729   int areaelements;
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;
8738   triangle *prevlink;
8739   triangle nexttri;
8740   point tdest, tapex;
8741   point checkdest, checkapex;
8742   point shorg;
8743   point killpoint;
8744   REAL area;
8745   int corner[3];
8746   int end[2];
8747   int killpointindex;
8748   int incorners;
8749   int segmentmarkers;
8750   int boundmarker;
8751   int aroundpoint;
8752   long hullsize;
8753   int notfound;
8754   int elementnumber, segmentnumber;
8755   int i, j;
8756   triangle ptr;                         /* Temporary variable used by sym(). */
8757
8758 #ifdef TRILIBRARY
8759   inelements = elements;
8760   incorners = corners;
8761   if (incorners < 3) {
8762     printf("Error:  Triangles must have at least 3 points.\n");
8763     exit(1);
8764   }
8765   eextras = attribs;
8766 #else /* not TRILIBRARY */
8767   /* Read the triangles from an .ele file. */
8768   if (!quiet) {
8769     printf("Opening %s.\n", elefilename);
8770   }
8771   elefile = fopen(elefilename, "r");
8772   if (elefile == (FILE *) NULL) {
8773     printf("  Error:  Cannot access file %s.\n", elefilename);
8774     exit(1);
8775   }
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') {
8782     incorners = 3;
8783   } else {
8784     incorners = (int) strtol (stringptr, &stringptr, 0);
8785     if (incorners < 3) {
8786       printf("Error:  Triangles in %s must have at least 3 points.\n",
8787              elefilename);
8788       exit(1);
8789     }
8790   }
8791   stringptr = findfield(stringptr);
8792   if (*stringptr == '\0') {
8793     eextras = 0;
8794   } else {
8795     eextras = (int) strtol (stringptr, &stringptr, 0);
8796   }
8797 #endif /* not TRILIBRARY */
8798
8799   initializetrisegpools();
8800
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;
8806   }
8807
8808   if (poly) {
8809 #ifdef TRILIBRARY
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') {
8819       segmentmarkers = 0;
8820     } else {
8821       segmentmarkers = (int) strtol (stringptr, &stringptr, 0);
8822     }
8823 #endif /* not TRILIBRARY */
8824
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;
8830     }
8831   }
8832
8833 #ifdef TRILIBRARY
8834   pointindex = 0;
8835   attribindex = 0;
8836 #else /* not TRILIBRARY */
8837   if (vararea) {
8838     /* Open an .area file, check for consistency with the .ele file. */
8839     if (!quiet) {
8840       printf("Opening %s.\n", areafilename);
8841     }
8842     areafile = fopen(areafilename, "r");
8843     if (areafile == (FILE *) NULL) {
8844       printf("  Error:  Cannot access file %s.\n", areafilename);
8845       exit(1);
8846     }
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);
8852       exit(1);
8853     }
8854   }
8855 #endif /* not TRILIBRARY */
8856
8857   if (!quiet) {
8858     printf("Reconstructing mesh.\n");
8859   }
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");
8866     exit(1);
8867   }
8868   /* Each point is initially unrepresented. */
8869   for (i = 0; i < points.items; i++) {
8870     vertexarray[i] = (triangle) dummytri;
8871   }
8872
8873   if (verbose) {
8874     printf("  Assembling triangles.\n");
8875   }
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) {
8882 #ifdef TRILIBRARY
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",
8888                elementnumber);
8889         exit(1);
8890       }
8891     }
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);
8900         exit(1);
8901       } else {
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",
8906                  elementnumber);
8907           exit(1);
8908         }
8909       }
8910     }
8911 #endif /* not TRILIBRARY */
8912
8913     /* Find out about (and throw away) extra nodes. */
8914     for (j = 3; j < incorners; j++) {
8915 #ifdef TRILIBRARY
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);
8928           }
8929         }
8930 #ifndef TRILIBRARY
8931       }
8932 #endif /* not TRILIBRARY */
8933     }
8934
8935     /* Read the triangle's attributes. */
8936     for (j = 0; j < eextras; j++) {
8937 #ifdef TRILIBRARY
8938       setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
8939 #else /* not TRILIBRARY */
8940       stringptr = findfield(stringptr);
8941       if (*stringptr == '\0') {
8942         setelemattribute(triangleloop, j, 0);
8943       } else {
8944         setelemattribute(triangleloop, j,
8945                          (REAL) strtod (stringptr, &stringptr));
8946       }
8947 #endif /* not TRILIBRARY */
8948     }
8949
8950     if (vararea) {
8951 #ifdef 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. */
8959       } else {
8960         area = (REAL) strtod(stringptr, &stringptr);
8961       }
8962 #endif /* not TRILIBRARY */
8963       setareabound(triangleloop, area);
8964     }
8965
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. */
8987         do {
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);
8994           }
8995           if (tdest == checkapex) {
8996             /* The two triangles share an edge; bond them together. */
8997             lprev(checktri, checkleft);
8998             bond(triangleloop, checkleft);
8999           }
9000           /* Find the next triangle in the stack. */
9001           nexttri = checktri.tri[6 + checktri.orient];
9002           decode(nexttri, checktri);
9003         } while (checktri.tri != dummytri);
9004       }
9005     }
9006     triangleloop.tri = triangletraverse();
9007     elementnumber++;
9008   }
9009
9010 #ifdef TRILIBRARY
9011   pointindex = 0;
9012 #else /* not TRILIBRARY */
9013   fclose(elefile);
9014   if (vararea) {
9015     fclose(areafile);
9016   }
9017 #endif /* not TRILIBRARY */
9018
9019   hullsize = 0;                      /* Prepare to count the boundary edges. */
9020   if (poly) {
9021     if (verbose) {
9022       printf("  Marking segments in triangulation.\n");
9023     }
9024     /* Read the segments from the .poly file, and link them */
9025     /*   to their neighboring triangles.                    */
9026     boundmarker = 0;
9027     traversalinit(&shelles);
9028     shelleloop.sh = shelletraverse();
9029     segmentnumber = firstnumber;
9030     while (shelleloop.sh != (shelle *) NULL) {
9031 #ifdef TRILIBRARY
9032       end[0] = segmentlist[pointindex++];
9033       end[1] = segmentlist[pointindex++];
9034       if (segmentmarkers) {
9035         boundmarker = segmentmarkerlist[segmentnumber - firstnumber];
9036       }
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,
9044                polyfilename);
9045         exit(1);
9046       } else {
9047         end[0] = (int) strtol (stringptr, &stringptr, 0);
9048       }
9049       stringptr = findfield(stringptr);
9050       if (*stringptr == '\0') {
9051         printf("Error:  Segment %d is missing its second endpoint in %s.\n",
9052                segmentnumber, polyfilename);
9053         exit(1);
9054       } else {
9055         end[1] = (int) strtol (stringptr, &stringptr, 0);
9056       }
9057       if (segmentmarkers) {
9058         stringptr = findfield(stringptr);
9059         if (*stringptr == '\0') {
9060           boundmarker = 0;
9061         } else {
9062           boundmarker = (int) strtol (stringptr, &stringptr, 0);
9063         }
9064       }
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", 
9069                  segmentnumber);
9070           exit(1);
9071         }
9072       }
9073
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);
9089         notfound = 1;
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);
9111               hullsize++;
9112             }
9113             notfound = 0;
9114           }
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);
9119         }
9120       }
9121       shelleloop.sh = shelletraverse();
9122       segmentnumber++;
9123     }
9124   }
9125
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);
9141         hullsize++;
9142       }
9143       decode(nexttri, checktri);
9144     }
9145   }
9146
9147   free(vertexarray);
9148   return hullsize;
9149 }
9150
9151 #endif /* not CDT_ONLY */
9152
9153 /**                                                                         **/
9154 /**                                                                         **/
9155 /********* General mesh construction routines end here               *********/
9156
9157 /********* Segment (shell edge) insertion begins here                *********/
9158 /**                                                                         **/
9159 /**                                                                         **/
9160
9161 /*****************************************************************************/
9162 /*                                                                           */
9163 /*  finddirection()   Find the first triangle on the path from one point     */
9164 /*                    to another.                                            */
9165 /*                                                                           */
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        */
9171 /*  another.                                                                 */
9172 /*                                                                           */
9173 /*  The return value notes whether the destination or apex of the found      */
9174 /*  triangle is collinear with the two points in question.                   */
9175 /*                                                                           */
9176 /*****************************************************************************/
9177
9178 enum finddirectionresult finddirection(searchtri, endpoint)
9179 struct triedge *searchtri;
9180 point endpoint;
9181 {
9182   struct triedge checktri;
9183   point startpoint;
9184   point leftpoint, rightpoint;
9185   REAL leftccw, rightccw;
9186   int leftflag, rightflag;
9187   triangle ptr;           /* Temporary variable used by onext() and oprev(). */
9188
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   */
9201     /*   on the left.                                                */
9202     onext(*searchtri, checktri);
9203     if (checktri.tri == dummytri) {
9204       leftflag = 0;
9205     } else {
9206       rightflag = 0;
9207     }
9208   }
9209   while (leftflag) {
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],
9215              startpoint[1]);
9216       printf("  (%.12g, %.12g).\n", endpoint[0], endpoint[1]);
9217       internalerror();
9218     }
9219     apex(*searchtri, leftpoint);
9220     rightccw = leftccw;
9221     leftccw = counterclockwise(endpoint, startpoint, leftpoint);
9222     leftflag = leftccw > 0.0;
9223   }
9224   while (rightflag) {
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],
9230              startpoint[1]);
9231       printf("  (%.12g, %.12g).\n", endpoint[0], endpoint[1]);
9232       internalerror();
9233     }
9234     dest(*searchtri, rightpoint);
9235     leftccw = rightccw;
9236     rightccw = counterclockwise(startpoint, endpoint, rightpoint);
9237     rightflag = rightccw > 0.0;
9238   }
9239   if (leftccw == 0.0) {
9240     return LEFTCOLLINEAR;
9241   } else if (rightccw == 0.0) {
9242     return RIGHTCOLLINEAR;
9243   } else {
9244     return WITHIN;
9245   }
9246 }
9247
9248 /*****************************************************************************/
9249 /*                                                                           */
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.                             */
9254 /*                                                                           */
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.                                                 */
9259 /*                                                                           */
9260 /*  On completion, splittri is a handle having the newly inserted            */
9261 /*  intersection point as its origin, and endpoint1 as its destination.      */
9262 /*                                                                           */
9263 /*****************************************************************************/
9264
9265 void segmentintersection(splittri, splitshelle, endpoint2)
9266 struct triedge *splittri;
9267 struct edge *splitshelle;
9268 point endpoint2;
9269 {
9270   point endpoint1;
9271   point torg, tdest;
9272   point leftpoint, rightpoint;
9273   point newpoint;
9274   enum insertsiteresult success;
9275   enum finddirectionresult collinear;
9276   REAL ex, ey;
9277   REAL tx, ty;
9278   REAL etx, ety;
9279   REAL split, denom;
9280   int i;
9281   triangle ptr;                       /* Temporary variable used by onext(). */
9282
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;
9295   if (denom == 0.0) {
9296     printf("Internal error in segmentintersection():");
9297     printf("  Attempt to find intersection of parallel segments.\n");
9298     internalerror();
9299   }
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]);
9306   }
9307   setpointmark(newpoint, mark(*splitshelle));
9308   if (verbose > 1) {
9309     printf(
9310     "  Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
9311            torg[0], torg[1], tdest[0], tdest[1], newpoint[0], newpoint[1]);
9312   }
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");
9318     internalerror();
9319   }
9320   if (steinerleft > 0) {
9321     steinerleft--;
9322   }
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");
9334     internalerror();
9335   }
9336   /* `splittri' should have destination endpoint1. */
9337 }
9338
9339 /*****************************************************************************/
9340 /*                                                                           */
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.                           */
9345 /*                                                                           */
9346 /*  Returns one if the entire segment is successfully inserted, and zero if  */
9347 /*  the job must be finished by conformingedge() or constrainededge().       */
9348 /*                                                                           */
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.       */
9351 /*                                                                           */
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      */
9355 /*  point.                                                                   */
9356 /*                                                                           */
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.          */
9360 /*                                                                           */
9361 /*  Otherwise, return zero.                                                  */
9362 /*                                                                           */
9363 /*****************************************************************************/
9364
9365 int scoutsegment(searchtri, endpoint2, newmark)
9366 struct triedge *searchtri;
9367 point endpoint2;
9368 int newmark;
9369 {
9370   struct triedge crosstri;
9371   struct edge crossedge;
9372   point leftpoint, rightpoint;
9373   point endpoint1;
9374   enum finddirectionresult collinear;
9375   shelle sptr;                      /* Temporary variable used by tspivot(). */
9376
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);
9385     }
9386     /* Insert a shell edge, if there isn't already one there. */
9387     insertshelle(searchtri, newmark);
9388     return 1;
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);
9403   } else {
9404     lnext(*searchtri, crosstri);
9405     tspivot(crosstri, crossedge);
9406     /* Check for a crossing segment. */
9407     if (crossedge.sh == dummysh) {
9408       return 0;
9409     } else {
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);
9417     }
9418   }
9419 }
9420
9421 /*****************************************************************************/
9422 /*                                                                           */
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   */
9426 /*                     necessary.                                            */
9427 /*                                                                           */
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.                                          */
9431 /*                                                                           */
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.           */
9437 /*                                                                           */
9438 /*****************************************************************************/
9439
9440 #ifndef REDUCED
9441 #ifndef CDT_ONLY
9442
9443 void conformingedge(endpoint1, endpoint2, newmark)
9444 point endpoint1;
9445 point endpoint2;
9446 int newmark;
9447 {
9448   struct triedge searchtri1, searchtri2;
9449   struct edge brokenshelle;
9450   point newpoint;
9451   point midpoint1, midpoint2;
9452   enum insertsiteresult success;
9453   int result1, result2;
9454   int i;
9455   shelle sptr;                      /* Temporary variable used by tspivot(). */
9456
9457   if (verbose > 2) {
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]);
9461   }
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]);
9467   }
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) {
9474     if (verbose > 2) {
9475       printf("  Segment intersects existing point (%.12g, %.12g).\n",
9476              newpoint[0], newpoint[1]);
9477     }
9478     /* Use the point that's already there. */
9479     pointdealloc(newpoint);
9480     org(searchtri1, newpoint);
9481   } else {
9482     if (success == VIOLATINGPOINT) {
9483       if (verbose > 2) {
9484         printf("  Two segments intersect at (%.12g, %.12g).\n",
9485                newpoint[0], newpoint[1]);
9486       }
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");
9493         internalerror();
9494       }
9495     }
9496     /* The point has been inserted successfully. */
9497     if (steinerleft > 0) {
9498       steinerleft--;
9499     }
9500   }
9501   triedgecopy(searchtri1, searchtri2);
9502   result1 = scoutsegment(&searchtri1, endpoint1, newmark);
9503   result2 = scoutsegment(&searchtri2, endpoint2, newmark);
9504   if (!result1) {
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);
9509   }
9510   if (!result2) {
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);
9515   }
9516 }
9517
9518 #endif /* not CDT_ONLY */
9519 #endif /* not REDUCED */
9520
9521 /*****************************************************************************/
9522 /*                                                                           */
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.              */
9526 /*                                                                           */
9527 /*  This is a support routine for inserting segments into a constrained      */
9528 /*  Delaunay triangulation.                                                  */
9529 /*                                                                           */
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          */
9533 /*  fixuptri.                                                                */
9534 /*                                                                           */
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.)                                               */
9542 /*                                                                           */
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.              */
9548 /*                                                                           */
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.  */
9552 /*                                                                           */
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.)                                                 */
9556 /*                                                                           */
9557 /*****************************************************************************/
9558
9559 void delaunayfixup(fixuptri, leftside)
9560 struct triedge *fixuptri;
9561 int leftside;
9562 {
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(). */
9569
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) {
9574     return;
9575   }
9576   tspivot(neartri, faredge);
9577   if (faredge.sh != dummysh) {
9578     return;
9579   }
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. */
9586   if (leftside) {
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.     */
9590       return;
9591     }
9592   } else {
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.      */
9596       return;
9597     }
9598   }
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) {
9605       return;
9606     }
9607     /* Not locally Delaunay; go on to an edge flip. */
9608   }        /* else fartri is inverted; remove it from the stack by flipping. */
9609   flip(&neartri);
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);
9614 }
9615
9616 /*****************************************************************************/
9617 /*                                                                           */
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.                             */
9622 /*                                                                           */
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.                                          */
9626 /*                                                                           */
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.            */
9632 /*                                                                           */
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.      */
9643 /*                                                                           */
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).                                                    */
9650 /*                                                                           */
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   */
9660 /*  later.                                                                   */
9661 /*                                                                           */
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.                                    */
9667 /*                                                                           */
9668 /*****************************************************************************/
9669
9670 void constrainededge(starttri, endpoint2, newmark)
9671 struct triedge *starttri;
9672 point endpoint2;
9673 int newmark;
9674 {
9675   struct triedge fixuptri, fixuptri2;
9676   struct edge fixupedge;
9677   point endpoint1;
9678   point farpoint;
9679   REAL area;
9680   int collision;
9681   int done;
9682   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
9683   shelle sptr;                      /* Temporary variable used by tspivot(). */
9684
9685   org(*starttri, endpoint1);
9686   lnext(*starttri, fixuptri);
9687   flip(&fixuptri);
9688   /* `collision' indicates whether we have found a point directly */
9689   /*   between endpoint1 and endpoint2.                           */
9690   collision = 0;
9691   done = 0;
9692   do {
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);
9701       done = 1;
9702     } else {
9703       /* Check whether farpoint is to the left or right of the segment */
9704       /*   being inserted, to decide which edge of fixuptri to dig     */
9705       /*   through next.                                               */
9706       area = counterclockwise(endpoint1, endpoint2, farpoint);
9707       if (area == 0.0) {
9708         /* We've collided with a point between endpoint1 and endpoint2. */
9709         collision = 1;
9710         oprev(fixuptri, fixuptri2);
9711         /* Enforce the Delaunay condition around farpoint. */
9712         delaunayfixup(&fixuptri, 0);
9713         delaunayfixup(&fixuptri2, 1);
9714         done = 1;
9715       } else {
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);
9731         }
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. */
9736         } else {
9737           /* We've collided with a segment between endpoint1 and endpoint2. */
9738           collision = 1;
9739           /* Insert a point at the intersection. */
9740           segmentintersection(&fixuptri, &fixupedge, endpoint2);
9741           done = 1;
9742         }
9743       }
9744     }
9745   } while (!done);
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.                     */
9750   if (collision) {
9751     /* Insert the remainder of the segment. */
9752     if (!scoutsegment(&fixuptri, endpoint2, newmark)) {
9753       constrainededge(&fixuptri, endpoint2, newmark);
9754     }
9755   }
9756 }
9757
9758 /*****************************************************************************/
9759 /*                                                                           */
9760 /*  insertsegment()   Insert a PSLG segment into a triangulation.            */
9761 /*                                                                           */
9762 /*****************************************************************************/
9763
9764 void insertsegment(endpoint1, endpoint2, newmark)
9765 point endpoint1;
9766 point endpoint2;
9767 int newmark;
9768 {
9769   struct triedge searchtri1, searchtri2;
9770   triangle encodedtri;
9771   point checkpoint;
9772   triangle ptr;                         /* Temporary variable used by sym(). */
9773
9774   if (verbose > 1) {
9775     printf("  Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
9776            endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
9777   }
9778
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);
9785   }
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) {
9793       printf(
9794         "Internal error in insertsegment():  Unable to locate PSLG point\n");
9795       printf("  (%.12g, %.12g) in triangulation.\n",
9796              endpoint1[0], endpoint1[1]);
9797       internalerror();
9798     }
9799   }
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. */
9806     return;
9807   }
9808   /* The first endpoint may have changed if a collision with an intervening */
9809   /*   vertex on the segment occurred.                                      */
9810   org(searchtri1, endpoint1);
9811
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);
9818   }
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) {
9826       printf(
9827         "Internal error in insertsegment():  Unable to locate PSLG point\n");
9828       printf("  (%.12g, %.12g) in triangulation.\n",
9829              endpoint2[0], endpoint2[1]);
9830       internalerror();
9831     }
9832   }
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. */
9839     return;
9840   }
9841   /* The second endpoint may have changed if a collision with an intervening */
9842   /*   vertex on the segment occurred.                                       */
9843   org(searchtri2, endpoint2);
9844
9845 #ifndef REDUCED
9846 #ifndef CDT_ONLY
9847   if (splitseg) {
9848     /* Insert vertices to force the segment into the triangulation. */
9849     conformingedge(endpoint1, endpoint2, newmark);
9850   } else {
9851 #endif /* not CDT_ONLY */
9852 #endif /* not REDUCED */
9853     /* Insert the segment directly into the triangulation. */
9854     constrainededge(&searchtri1, endpoint2, newmark);
9855 #ifndef REDUCED
9856 #ifndef CDT_ONLY
9857   }
9858 #endif /* not CDT_ONLY */
9859 #endif /* not REDUCED */
9860 }
9861
9862 /*****************************************************************************/
9863 /*                                                                           */
9864 /*  markhull()   Cover the convex hull of a triangulation with shell edges.  */
9865 /*                                                                           */
9866 /*****************************************************************************/
9867
9868 void markhull()
9869 {
9870   struct triedge hulltri;
9871   struct triedge nexttri;
9872   struct triedge starttri;
9873   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
9874
9875   /* Find a triangle handle on the hull. */
9876   hulltri.tri = dummytri;
9877   hulltri.orient = 0;
9878   symself(hulltri);
9879   /* Remember where we started so we know when to stop. */
9880   triedgecopy(hulltri, starttri);
9881   /* Go once counterclockwise around the convex hull. */
9882   do {
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. */
9886     lnextself(hulltri);
9887     oprev(hulltri, nexttri);
9888     while (nexttri.tri != dummytri) {
9889       triedgecopy(nexttri, hulltri);
9890       oprev(hulltri, nexttri);
9891     }
9892   } while (!triedgeequal(hulltri, starttri));
9893 }
9894
9895 /*****************************************************************************/
9896 /*                                                                           */
9897 /*  formskeleton()   Create the shell edges of a triangulation, including    */
9898 /*                   PSLG edges and edges on the convex hull.                */
9899 /*                                                                           */
9900 /*  The PSLG edges are read from a .poly file.  The return value is the      */
9901 /*  number of segments in the file.                                          */
9902 /*                                                                           */
9903 /*****************************************************************************/
9904
9905 #ifdef TRILIBRARY
9906
9907 int formskeleton(segmentlist, segmentmarkerlist, numberofsegments)
9908 int *segmentlist;
9909 int *segmentmarkerlist;
9910 int numberofsegments;
9911
9912 #else /* not TRILIBRARY */
9913
9914 int formskeleton(polyfile, polyfilename)
9915 FILE *polyfile;
9916 char *polyfilename;
9917
9918 #endif /* not TRILIBRARY */
9919
9920 {
9921 #ifdef TRILIBRARY
9922   char polyfilename[6];
9923   int index;
9924 #else /* not TRILIBRARY */
9925   char inputline[INPUTLINESIZE];
9926   char *stringptr;
9927 #endif /* not TRILIBRARY */
9928   point endpoint1, endpoint2;
9929   int segments;
9930   int segmentmarkers;
9931   int end1, end2;
9932   int boundmarker;
9933   int i;
9934
9935   if (poly) {
9936     if (!quiet) {
9937       printf("Inserting segments into Delaunay triangulation.\n");
9938     }
9939 #ifdef TRILIBRARY
9940     strcpy(polyfilename, "input");
9941     segments = numberofsegments;
9942     segmentmarkers = segmentmarkerlist != (int *) NULL;
9943     index = 0;
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') {
9951       segmentmarkers = 0;
9952     } else {
9953       segmentmarkers = (int) strtol (stringptr, &stringptr, 0);
9954     }
9955 #endif /* not TRILIBRARY */
9956     /* If segments are to be inserted, compute a mapping */
9957     /*   from points to triangles.                       */
9958     if (segments > 0) {
9959       if (verbose) {
9960         printf("  Inserting PSLG segments.\n");
9961       }
9962       makepointmap();
9963     }
9964
9965     boundmarker = 0;
9966     /* Read and insert the segments. */
9967     for (i = 1; i <= segments; i++) {
9968 #ifdef TRILIBRARY
9969       end1 = segmentlist[index++];
9970       end2 = segmentlist[index++];
9971       if (segmentmarkers) {
9972         boundmarker = segmentmarkerlist[i - 1];
9973       }
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,
9979                polyfilename);
9980         exit(1);
9981       } else {
9982         end1 = (int) strtol (stringptr, &stringptr, 0);
9983       }
9984       stringptr = findfield(stringptr);
9985       if (*stringptr == '\0') {
9986         printf("Error:  Segment %d is missing its second endpoint in %s.\n", i,
9987                polyfilename);
9988         exit(1);
9989       } else {
9990         end2 = (int) strtol (stringptr, &stringptr, 0);
9991       }
9992       if (segmentmarkers) {
9993         stringptr = findfield(stringptr);
9994         if (*stringptr == '\0') {
9995           boundmarker = 0;
9996         } else {
9997           boundmarker = (int) strtol (stringptr, &stringptr, 0);
9998         }
9999       }
10000 #endif /* not TRILIBRARY */
10001       if ((end1 < firstnumber) || (end1 >= firstnumber + inpoints)) {
10002         if (!quiet) {
10003           printf("Warning:  Invalid first endpoint of segment %d in %s.\n", i,
10004                  polyfilename);
10005         }
10006       } else if ((end2 < firstnumber) || (end2 >= firstnumber + inpoints)) {
10007         if (!quiet) {
10008           printf("Warning:  Invalid second endpoint of segment %d in %s.\n", i,
10009                  polyfilename);
10010         }
10011       } else {
10012         endpoint1 = getpoint(end1);
10013         endpoint2 = getpoint(end2);
10014         if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
10015           if (!quiet) {
10016             printf("Warning:  Endpoints of segment %d are coincident in %s.\n",
10017                    i, polyfilename);
10018           }
10019         } else {
10020           insertsegment(endpoint1, endpoint2, boundmarker);
10021         }
10022       }
10023     }
10024   } else {
10025     segments = 0;
10026   }
10027   if (convex || !poly) {
10028     /* Enclose the convex hull with shell edges. */
10029     if (verbose) {
10030       printf("  Enclosing convex hull with segments.\n");
10031     }
10032     markhull();
10033   }
10034   return segments;
10035 }
10036
10037 /**                                                                         **/
10038 /**                                                                         **/
10039 /********* Segment (shell edge) insertion ends here                  *********/
10040
10041 /********* Carving out holes and concavities begins here             *********/
10042 /**                                                                         **/
10043 /**                                                                         **/
10044
10045 /*****************************************************************************/
10046 /*                                                                           */
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.         */
10050 /*                                                                           */
10051 /*****************************************************************************/
10052
10053 void infecthull()
10054 {
10055   struct triedge hulltri;
10056   struct triedge nexttri;
10057   struct triedge starttri;
10058   struct edge hulledge;
10059   triangle **deadtri;
10060   point horg, hdest;
10061   triangle ptr;                         /* Temporary variable used by sym(). */
10062   shelle sptr;                      /* Temporary variable used by tspivot(). */
10063
10064   if (verbose) {
10065     printf("  Marking concavities (external triangles) for elimination.\n");
10066   }
10067   /* Find a triangle handle on the hull. */
10068   hulltri.tri = dummytri;
10069   hulltri.orient = 0;
10070   symself(hulltri);
10071   /* Remember where we started so we know when to stop. */
10072   triedgecopy(hulltri, starttri);
10073   /* Go once counterclockwise around the convex hull. */
10074   do {
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. */
10081         infect(hulltri);
10082         deadtri = (triangle **) poolalloc(&viri);
10083         *deadtri = hulltri.tri;
10084       } else {
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);
10092           }
10093           if (pointmark(hdest) == 0) {
10094             setpointmark(hdest, 1);
10095           }
10096         }
10097       }
10098     }
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);
10105     }
10106   } while (!triedgeequal(hulltri, starttri));
10107 }
10108
10109 /*****************************************************************************/
10110 /*                                                                           */
10111 /*  plague()   Spread the virus from all infected triangles to any neighbors */
10112 /*             not protected by shell edges.  Delete all infected triangles. */
10113 /*                                                                           */
10114 /*  This is the procedure that actually creates holes and concavities.       */
10115 /*                                                                           */
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.                                   */
10120 /*                                                                           */
10121 /*  The second phase actually eliminates the infected triangles.  It also    */
10122 /*  eliminates orphaned points.                                              */
10123 /*                                                                           */
10124 /*****************************************************************************/
10125
10126 void plague()
10127 {
10128   struct triedge testtri;
10129   struct triedge neighbor;
10130   triangle **virusloop;
10131   triangle **deadtri;
10132   struct edge neighborshelle;
10133   point testpoint;
10134   point norg, ndest;
10135   point deadorg, deaddest, deadapex;
10136   int killorg;
10137   triangle ptr;             /* Temporary variable used by sym() and onext(). */
10138   shelle sptr;                      /* Temporary variable used by tspivot(). */
10139
10140   if (verbose) {
10141     printf("  Marking neighbors of marked triangles.\n");
10142   }
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.                                           */
10153     uninfect(testtri);
10154     if (verbose > 2) {
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]);
10164     }
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);
10183             infect(neighbor);
10184           }
10185         }
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.                   */
10190           if (verbose > 2) {
10191             org(neighbor, deadorg);
10192             dest(neighbor, deaddest);
10193             apex(neighbor, deadapex);
10194             printf(
10195               "    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
10196                    deadorg[0], deadorg[1], deaddest[0], deaddest[1],
10197                    deadapex[0], deadapex[1]);
10198           }
10199           infect(neighbor);
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);
10209           }
10210           org(neighbor, norg);
10211           dest(neighbor, ndest);
10212           if (pointmark(norg) == 0) {
10213             setpointmark(norg, 1);
10214           }
10215           if (pointmark(ndest) == 0) {
10216             setpointmark(ndest, 1);
10217           }
10218         }
10219       }
10220     }
10221     /* Remark the triangle as infected, so it doesn't get added to the */
10222     /*   virus pool again.                                             */
10223     infect(testtri);
10224     virusloop = (triangle **) traverse(&viri);
10225   }
10226
10227   if (verbose) {
10228     printf("  Deleting marked triangles.\n");
10229   }
10230   traversalinit(&viri);
10231   virusloop = (triangle **) traverse(&viri);
10232   while (virusloop != (triangle **) NULL) {
10233     testtri.tri = *virusloop;
10234
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) {
10242         killorg = 1;
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);
10253           } else {
10254             /* A live triangle.  The point survives. */
10255             killorg = 0;
10256           }
10257           /* Walk counterclockwise about the point. */
10258           onextself(neighbor);
10259         }
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);
10269             } else {
10270               /* A live triangle.  The point survives. */
10271               killorg = 0;
10272             }
10273             /* Walk clockwise about the point. */
10274             oprevself(neighbor);
10275           }
10276         }
10277         if (killorg) {
10278           if (verbose > 1) {
10279             printf("    Deleting point (%.12g, %.12g)\n",
10280                    testpoint[0], testpoint[1]);
10281           }
10282           pointdealloc(testpoint);
10283         }
10284       }
10285     }
10286
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.                                    */
10295         hullsize--;
10296       } else {
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.   */
10301         hullsize++;
10302       }
10303     }
10304     /* Return the dead triangle to the pool of triangles. */
10305     triangledealloc(testtri.tri);
10306     virusloop = (triangle **) traverse(&viri);
10307   }
10308   /* Empty the virus pool. */
10309   poolrestart(&viri);
10310 }
10311
10312 /*****************************************************************************/
10313 /*                                                                           */
10314 /*  regionplague()   Spread regional attributes and/or area constraints      */
10315 /*                   (from a .poly file) throughout the mesh.                */
10316 /*                                                                           */
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.                   */
10321 /*                                                                           */
10322 /*  The second phase uninfects all infected triangles, returning them to     */
10323 /*  normal.                                                                  */
10324 /*                                                                           */
10325 /*****************************************************************************/
10326
10327 void regionplague(attribute, area)
10328 REAL attribute;
10329 REAL area;
10330 {
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(). */
10339
10340   if (verbose > 1) {
10341     printf("  Marking neighbors of marked triangles.\n");
10342   }
10343   /* Loop through all the infected triangles, spreading the attribute      */
10344   /*   and/or area constraint to their neighbors, then to their neighbors' */
10345   /*   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.                                           */
10354     uninfect(testtri);
10355     if (regionattrib) {
10356       /* Set an attribute. */
10357       setelemattribute(testtri, eextras, attribute);
10358     }
10359     if (vararea) {
10360       /* Set an area constraint. */
10361       setareabound(testtri, area);
10362     }
10363     if (verbose > 2) {
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]);
10373     }
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)) {
10384         if (verbose > 2) {
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]);
10391         }
10392         /* Infect the neighbor. */
10393         infect(neighbor);
10394         /* Ensure that the neighbor's neighbors will be infected. */
10395         regiontri = (triangle **) poolalloc(&viri);
10396         *regiontri = neighbor.tri;
10397       }
10398     }
10399     /* Remark the triangle as infected, so it doesn't get added to the */
10400     /*   virus pool again.                                             */
10401     infect(testtri);
10402     virusloop = (triangle **) traverse(&viri);
10403   }
10404
10405   /* Uninfect all triangles. */
10406   if (verbose > 1) {
10407     printf("  Unmarking marked triangles.\n");
10408   }
10409   traversalinit(&viri);
10410   virusloop = (triangle **) traverse(&viri);
10411   while (virusloop != (triangle **) NULL) {
10412     testtri.tri = *virusloop;
10413     uninfect(testtri);
10414     virusloop = (triangle **) traverse(&viri);
10415   }
10416   /* Empty the virus pool. */
10417   poolrestart(&viri);
10418 }
10419
10420 /*****************************************************************************/
10421 /*                                                                           */
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.                                         */
10426 /*                                                                           */
10427 /*  This routine mainly calls other routines to carry out all these          */
10428 /*  functions.                                                               */
10429 /*                                                                           */
10430 /*****************************************************************************/
10431
10432 void carveholes(holelist, holes, regionlist, regions)
10433 REAL *holelist;
10434 int holes;
10435 REAL *regionlist;
10436 int regions;
10437 {
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;
10445   int i;
10446   triangle ptr;                         /* Temporary variable used by sym(). */
10447
10448   if (!(quiet || (noholes && convex))) {
10449     printf("Removing unwanted triangles.\n");
10450     if (verbose && (holes > 0)) {
10451       printf("  Marking holes for elimination.\n");
10452     }
10453   }
10454
10455   if (regions > 0) {
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");
10460       exit(1);
10461     }
10462   }
10463
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);
10468   }
10469
10470   if (!convex) {
10471     /* Mark as infected any unprotected triangles on the boundary. */
10472     /*   This is one way by which concavities are created.         */
10473     infecthull();
10474   }
10475
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.  */
10497             infect(searchtri);
10498             holetri = (triangle **) poolalloc(&viri);
10499             *holetri = searchtri.tri;
10500           }
10501         }
10502       }
10503     }
10504   }
10505
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.)                                                   */
10512   if (regions > 0) {
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, &regionlist[4 * i]) >
10529             0.0) {
10530           /* Find a triangle that contains the region point. */
10531           intersect = locate(&regionlist[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]);
10536           }
10537         }
10538       }
10539     }
10540   }
10541
10542   if (viri.items > 0) {
10543     /* Carve the holes and concavities. */
10544     plague();
10545   }
10546   /* The virus pool should be empty now. */
10547
10548   if (regions > 0) {
10549     if (!quiet) {
10550       if (regionattrib) {
10551         if (vararea) {
10552           printf("Spreading regional attributes and area constraints.\n");
10553         } else {
10554           printf("Spreading regional attributes.\n");
10555         }
10556       } else { 
10557         printf("Spreading regional area constraints.\n");
10558       }
10559     }
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();
10568       }
10569     }
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. */
10582         }
10583       }
10584     }
10585     if (regionattrib && !refine) {
10586       /* Note the fact that each triangle has an additional attribute. */
10587       eextras++;
10588     }
10589   }
10590
10591   /* Free up memory. */
10592   if (((holes > 0) && !noholes) || !convex || (regions > 0)) {
10593     pooldeinit(&viri);
10594   }
10595   if (regions > 0) {
10596     free(regiontris);
10597   }
10598 }
10599
10600 /**                                                                         **/
10601 /**                                                                         **/
10602 /********* Carving out holes and concavities ends here               *********/
10603
10604 /********* Mesh quality maintenance begins here                      *********/
10605 /**                                                                         **/
10606 /**                                                                         **/
10607
10608 /*****************************************************************************/
10609 /*                                                                           */
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.    */
10612 /*                                                                           */
10613 /*****************************************************************************/
10614
10615 #ifndef CDT_ONLY
10616
10617 void tallyencs()
10618 {
10619   struct edge edgeloop;
10620   int dummy;
10621
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();
10629   }
10630 }
10631
10632 #endif /* not CDT_ONLY */
10633
10634 /*****************************************************************************/
10635 /*                                                                           */
10636 /*  precisionerror()  Print an error message for precision problems.         */
10637 /*                                                                           */
10638 /*****************************************************************************/
10639
10640 #ifndef CDT_ONLY
10641
10642 void precisionerror()
10643 {
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");
10646 #ifdef SINGLE
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 */
10651 }
10652
10653 #endif /* not CDT_ONLY */
10654
10655 /*****************************************************************************/
10656 /*                                                                           */
10657 /*  repairencs()   Find and repair all the encroached segments.              */
10658 /*                                                                           */
10659 /*  Encroached segments are repaired by splitting them by inserting a point  */
10660 /*  at or near their centers.                                                */
10661 /*                                                                           */
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.                                  */
10665 /*                                                                           */
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       */
10668 /*  of `flaws'.                                                              */
10669 /*                                                                           */
10670 /*****************************************************************************/
10671
10672 #ifndef CDT_ONLY
10673
10674 void repairencs(flaws)
10675 int flaws;
10676 {
10677   struct triedge enctri;
10678   struct triedge testtri;
10679   struct edge *encloop;
10680   struct edge testsh;
10681   point eorg, edest;
10682   point newpoint;
10683   enum insertsiteresult success;
10684   REAL segmentlength, nearestpoweroftwo;
10685   REAL split;
10686   int acuteorg, acutedest;
10687   int dummy;
10688   int i;
10689   triangle ptr;                     /* Temporary variable used by stpivot(). */
10690   shelle sptr;                        /* Temporary variable used by snext(). */
10691
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.)                  */
10710
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 */
10721       /*   there.                                                        */
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);
10732       }
10733
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;
10745         }
10746         while (segmentlength < (0.5 * SQUAREROOTTWO) * nearestpoweroftwo) {
10747           nearestpoweroftwo *= 0.5;
10748         }
10749         /* Where do we split the segment? */
10750         split = 0.5 * nearestpoweroftwo / segmentlength;
10751         if (acutedest) {
10752           split = 1.0 - split;
10753         }
10754       } else {
10755         /* If we're not worried about adjacent segments, split */
10756         /*   this segment in the middle.                       */
10757         split = 0.5;
10758       }
10759
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];
10765       }
10766       setpointmark(newpoint, mark(*encloop));
10767       if (verbose > 1) {
10768         printf(
10769         "  Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
10770                eorg[0], eorg[1], edest[0], edest[1], newpoint[0], newpoint[1]);
10771       }
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"
10779                );
10780         printf("  arithmetic.\n");
10781         precisionerror();
10782         exit(1);
10783       }
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");
10789         internalerror();
10790       }
10791       if (steinerleft > 0) {
10792         steinerleft--;
10793       }
10794       /* Check the two new subsegments to see if they're encroached. */
10795       dummy = checkedge4encroach(encloop);
10796       snextself(*encloop);
10797       dummy = checkedge4encroach(encloop);
10798
10799       badsegmentdealloc(encloop);
10800       encloop = badsegmenttraverse();
10801     }
10802   }
10803 }
10804
10805 #endif /* not CDT_ONLY */
10806
10807 /*****************************************************************************/
10808 /*                                                                           */
10809 /*  tallyfaces()   Test every triangle in the mesh for quality measures.     */
10810 /*                                                                           */
10811 /*****************************************************************************/
10812
10813 #ifndef CDT_ONLY
10814
10815 void tallyfaces()
10816 {
10817   struct triedge triangleloop;
10818
10819   if (verbose) {
10820     printf("  Making a list of bad triangles.\n");
10821   }
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();
10829   }
10830 }
10831
10832 #endif /* not CDT_ONLY */
10833
10834 /*****************************************************************************/
10835 /*                                                                           */
10836 /*  findcircumcenter()   Find the circumcenter of a triangle.                */
10837 /*                                                                           */
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.             */
10843 /*                                                                           */
10844 /*  The return value indicates which edge of the triangle is shortest.       */
10845 /*                                                                           */
10846 /*****************************************************************************/
10847
10848 enum circumcenterresult findcircumcenter(torg, tdest, tapex, circumcenter,
10849                                          xi, eta)
10850 point torg;
10851 point tdest;
10852 point tapex;
10853 point circumcenter;
10854 REAL *xi;
10855 REAL *eta;
10856 {
10857   REAL xdo, ydo, xao, yao, xad, yad;
10858   REAL dodist, aodist, addist;
10859   REAL denominator;
10860   REAL dx, dy;
10861
10862   circumcentercount++;
10863
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;
10871   if (noexact) {
10872     denominator = (REAL)(0.5 / (xdo * yao - xao * ydo));
10873   } else {
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--;
10880   }
10881   circumcenter[0] = torg[0] - (ydo * aodist - yao * dodist) * denominator;  
10882   circumcenter[1] = torg[1] + (xdo * aodist - xao * dodist) * denominator;  
10883
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));
10893
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;
10901   } else {
10902     return OPPOSITEDEST;
10903   }
10904 }
10905
10906 /*****************************************************************************/
10907 /*                                                                           */
10908 /*  splittriangle()   Inserts a point at the circumcenter of a triangle.     */
10909 /*                    Deletes the newly inserted point if it encroaches upon */
10910 /*                    a segment.                                             */
10911 /*                                                                           */
10912 /*****************************************************************************/
10913
10914 #ifndef CDT_ONLY
10915
10916 void splittriangle(badtri)
10917 struct badface *badtri;
10918 {
10919   point borg, bdest, bapex;
10920   point newpoint;
10921   REAL xi, eta;
10922   enum insertsiteresult success;
10923   enum circumcenterresult shortedge;
10924   int errorflag;
10925   int i;
10926
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)) {
10935     if (verbose > 1) {
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]);
10939     }
10940     errorflag = 0;
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]))) {
10948       if (!quiet) {
10949         printf("Warning:  New point (%.12g, %.12g) falls on existing vertex.\n"
10950                , newpoint[0], newpoint[1]);
10951         errorflag = 1;
10952       }
10953       pointdealloc(newpoint);
10954     } else {
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]);
10959       }
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);
10969       }
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) {
10976           steinerleft--;
10977         }
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. */
10987         if (!quiet) {
10988           printf(
10989             "Warning:  New point (%.12g, %.12g) falls on existing vertex.\n"
10990                  , newpoint[0], newpoint[1]);
10991           errorflag = 1;
10992         }
10993         pointdealloc(newpoint);
10994       }
10995     }
10996     if (errorflag) {
10997       if (verbose) {
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]);
11001       }
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");
11006       precisionerror();
11007     }
11008   }
11009   /* Return the bad triangle to the pool. */
11010   pooldealloc(&badtriangles, (VOID *) badtri);
11011 }
11012
11013 #endif /* not CDT_ONLY */
11014
11015 /*****************************************************************************/
11016 /*                                                                           */
11017 /*  enforcequality()   Remove all the encroached edges and bad triangles     */
11018 /*                     from the triangulation.                               */
11019 /*                                                                           */
11020 /*****************************************************************************/
11021
11022 #ifndef CDT_ONLY
11023
11024 void enforcequality()
11025 {
11026   int i;
11027
11028   if (!quiet) {
11029     printf("Adding Steiner points to enforce quality.\n");
11030   }
11031   /* Initialize the pool of encroached segments. */
11032   poolinit(&badsegments, sizeof(struct edge), BADSEGMENTPERBLOCK, POINTER, 0);
11033   if (verbose) {
11034     printf("  Looking for encroached segments.\n");
11035   }
11036   /* Test all segments to see if they're encroached. */
11037   tallyencs();
11038   if (verbose && (badsegments.items > 0)) {
11039     printf("  Splitting encroached segments.\n");
11040   }
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.          */
11049     repairencs(0);
11050     /* Now, find all the segments that became encroached while adding */
11051     /*   points to split encroached segments.                         */
11052     tallyencs();
11053   }
11054   /* At this point, if we haven't run out of Steiner points, the */
11055   /*   triangulation should be (conforming) Delaunay.            */
11056
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,
11061              0);
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];
11066     }
11067     /* Test all triangles to see if they're bad. */
11068     tallyfaces();
11069     if (verbose) {
11070       printf("  Splitting bad triangles.\n");
11071     }
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) {
11078         repairencs(1);
11079       }
11080     }
11081   }
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.                                    */
11085
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");
11091     } else {
11092       printf("  %ld encroached segments, and therefore might not be truly\n",
11093              badsegments.items);
11094     }
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");
11098   }
11099 }
11100
11101 #endif /* not CDT_ONLY */
11102
11103 /**                                                                         **/
11104 /**                                                                         **/
11105 /********* Mesh quality maintenance ends here                        *********/
11106
11107 /*****************************************************************************/
11108 /*                                                                           */
11109 /*  highorder()   Create extra nodes for quadratic subparametric elements.   */
11110 /*                                                                           */
11111 /*****************************************************************************/
11112
11113 void highorder()
11114 {
11115   struct triedge triangleloop, trisym;
11116   struct edge checkmark;
11117   point newpoint;
11118   point torg, tdest;
11119   int i;
11120   triangle ptr;                         /* Temporary variable used by sym(). */
11121   shelle sptr;                      /* Temporary variable used by tspivot(). */
11122
11123   if (!quiet) {
11124     printf("Adding vertices for second-order triangles.\n");
11125   }
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;
11132
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]));
11153         }
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);
11157         if (useshelles) {
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));
11162           }
11163         }
11164         if (verbose > 1) {
11165           printf("  Creating (%.12g, %.12g).\n", newpoint[0], newpoint[1]);
11166         }
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;
11172         }
11173       }
11174     }
11175     triangleloop.tri = triangletraverse();
11176   }
11177 }
11178
11179 /********* File I/O routines begin here                              *********/
11180 /**                                                                         **/
11181 /**                                                                         **/
11182
11183 /*****************************************************************************/
11184 /*                                                                           */
11185 /*  readline()   Read a nonempty line from a file.                           */
11186 /*                                                                           */
11187 /*  A line is considered "nonempty" if it contains something that looks like */
11188 /*  a number.                                                                */
11189 /*                                                                           */
11190 /*****************************************************************************/
11191
11192 #ifndef TRILIBRARY
11193
11194 char *readline(string, infile, infilename)
11195 char *string;
11196 FILE *infile;
11197 char *infilename;
11198 {
11199   char *result;
11200
11201   /* Search for something that looks like a number. */
11202   do {
11203     result = fgets(string, INPUTLINESIZE, infile);
11204     if (result == (char *) NULL) {
11205       printf("  Error:  Unexpected end of file in %s.\n", infilename);
11206       exit(1);
11207     }
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'))) {
11213       result++;
11214     }
11215   /* If it's a comment or end of line, read another line and try again. */
11216   } while ((*result == '#') || (*result == '\0'));
11217   return result;
11218 }
11219
11220 #endif /* not TRILIBRARY */
11221
11222 /*****************************************************************************/
11223 /*                                                                           */
11224 /*  findfield()   Find the next field of a string.                           */
11225 /*                                                                           */
11226 /*  Jumps past the current field by searching for whitespace, then jumps     */
11227 /*  past the whitespace to find the next field.                              */
11228 /*                                                                           */
11229 /*****************************************************************************/
11230
11231 #ifndef TRILIBRARY
11232
11233 char *findfield(string)
11234 char *string;
11235 {
11236   char *result;
11237
11238   result = string;
11239   /* Skip the current field.  Stop upon reaching whitespace. */
11240   while ((*result != '\0') && (*result != '#')
11241          && (*result != ' ') && (*result != '\t')) {
11242     result++;
11243   }
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'))) {
11249     result++;
11250   }
11251   /* Check for a comment (prefixed with `#'). */
11252   if (*result == '#') {
11253     *result = '\0';
11254   }
11255   return result;
11256 }
11257
11258 #endif /* not TRILIBRARY */
11259
11260 /*****************************************************************************/
11261 /*                                                                           */
11262 /*  readnodes()   Read the points from a file, which may be a .node or .poly */
11263 /*                file.                                                      */
11264 /*                                                                           */
11265 /*****************************************************************************/
11266
11267 #ifndef TRILIBRARY
11268
11269 void readnodes(nodefilename, polyfilename, polyfile)
11270 char *nodefilename;
11271 char *polyfilename;
11272 FILE **polyfile;
11273 {
11274   FILE *infile;
11275   point pointloop;
11276   char inputline[INPUTLINESIZE];
11277   char *stringptr;
11278   char *infilename;
11279   REAL x, y;
11280   int firstnode;
11281   int nodemarkers;
11282   int currentmarker;
11283   int i, j;
11284
11285   if (poly) {
11286     /* Read the points from a .poly file. */
11287     if (!quiet) {
11288       printf("Opening %s.\n", polyfilename);
11289     }
11290     *polyfile = fopen(polyfilename, "r");
11291     if (*polyfile == (FILE *) NULL) {
11292       printf("  Error:  Cannot access file %s.\n", polyfilename);
11293       exit(1);
11294     }
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') {
11301       mesh_dim = 2;
11302     } else {
11303       mesh_dim = (int) strtol (stringptr, &stringptr, 0);
11304     }
11305     stringptr = findfield(stringptr);
11306     if (*stringptr == '\0') {
11307       nextras = 0;
11308     } else {
11309       nextras = (int) strtol (stringptr, &stringptr, 0);
11310     }
11311     stringptr = findfield(stringptr);
11312     if (*stringptr == '\0') {
11313       nodemarkers = 0;
11314     } else {
11315       nodemarkers = (int) strtol (stringptr, &stringptr, 0);
11316     }
11317     if (inpoints > 0) {
11318       infile = *polyfile;
11319       infilename = polyfilename;
11320       readnodefile = 0;
11321     } else {
11322       /* If the .poly file claims there are zero points, that means that */
11323       /*   the points should be read from a separate .node file.         */
11324       readnodefile = 1;
11325       infilename = innodefilename;
11326     }
11327   } else {
11328     readnodefile = 1;
11329     infilename = innodefilename;
11330     *polyfile = (FILE *) NULL;
11331   }
11332
11333   if (readnodefile) {
11334     /* Read the points from a .node file. */
11335     if (!quiet) {
11336       printf("Opening %s.\n", innodefilename);
11337     }
11338     infile = fopen(innodefilename, "r");
11339     if (infile == (FILE *) NULL) {
11340       printf("  Error:  Cannot access file %s.\n", innodefilename);
11341       exit(1);
11342     }
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') {
11349       mesh_dim = 2;
11350     } else {
11351       mesh_dim = (int) strtol (stringptr, &stringptr, 0);
11352     }
11353     stringptr = findfield(stringptr);
11354     if (*stringptr == '\0') {
11355       nextras = 0;
11356     } else {
11357       nextras = (int) strtol (stringptr, &stringptr, 0);
11358     }
11359     stringptr = findfield(stringptr);
11360     if (*stringptr == '\0') {
11361       nodemarkers = 0;
11362     } else {
11363       nodemarkers = (int) strtol (stringptr, &stringptr, 0);
11364     }
11365   }
11366
11367   if (inpoints < 3) {
11368     printf("Error:  Input must have at least three input points.\n");
11369     exit(1);
11370   }
11371   if (mesh_dim != 2) {
11372     printf("Error:  Triangle only works with two-dimensional meshes.\n");
11373     exit(1);
11374   }
11375
11376   initializepointpool();
11377
11378   /* Read the points. */
11379   for (i = 0; i < inpoints; i++) {
11380     pointloop = (point) poolalloc(&points);
11381     stringptr = readline(inputline, infile, infilename);
11382     if (i == 0) {
11383       firstnode = (int) strtol (stringptr, &stringptr, 0);
11384       if ((firstnode == 0) || (firstnode == 1)) {
11385         firstnumber = firstnode;
11386       }
11387     }
11388     stringptr = findfield(stringptr);
11389     if (*stringptr == '\0') {
11390       printf("Error:  Point %d has no x coordinate.\n", firstnumber + i);
11391       exit(1);
11392     }
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);
11397       exit(1);
11398     }
11399     y = (REAL) strtod(stringptr, &stringptr);
11400     pointloop[0] = x;
11401     pointloop[1] = y;
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;
11407       } else {
11408         pointloop[j] = (REAL) strtod(stringptr, &stringptr);
11409       }
11410     }
11411     if (nodemarkers) {
11412       /* Read a point marker. */
11413       stringptr = findfield(stringptr);
11414       if (*stringptr == '\0') {
11415         setpointmark(pointloop, 0);
11416       } else {
11417         currentmarker = (int) strtol (stringptr, &stringptr, 0);
11418         setpointmark(pointloop, currentmarker);
11419       }
11420     } else {
11421       /* If no markers are specified in the file, they default to zero. */
11422       setpointmark(pointloop, 0);
11423     }
11424     /* Determine the smallest and largest x and y coordinates. */
11425     if (i == 0) {
11426       xmin = xmax = x;
11427       ymin = ymax = y;
11428     } else {
11429       xmin = (x < xmin) ? x : xmin;
11430       xmax = (x > xmax) ? x : xmax;
11431       ymin = (y < ymin) ? y : ymin;
11432       ymax = (y > ymax) ? y : ymax;
11433     }
11434   }
11435   if (readnodefile) {
11436     fclose(infile);
11437   }
11438
11439   /* Nonexistent x value used as a flag to mark circle events in sweepline */
11440   /*   Delaunay algorithm.                                                 */
11441   xminextreme = 10 * xmin - 9 * xmax;
11442 }
11443
11444 #endif /* not TRILIBRARY */
11445
11446 /*****************************************************************************/
11447 /*                                                                           */
11448 /*  transfernodes()   Read the points from memory.                           */
11449 /*                                                                           */
11450 /*****************************************************************************/
11451
11452 #ifdef TRILIBRARY
11453
11454 void transfernodes(pointlist, pointattriblist, pointmarkerlist, numberofpoints,
11455                    numberofpointattribs)
11456 REAL *pointlist;
11457 REAL *pointattriblist;
11458 int *pointmarkerlist;
11459 int numberofpoints;
11460 int numberofpointattribs;
11461 {
11462   point pointloop;
11463   REAL x, y;
11464   int i, j;
11465   int coordindex;
11466   int attribindex;
11467
11468   inpoints = numberofpoints;
11469   mesh_dim = 2;
11470   nextras = numberofpointattribs;
11471   readnodefile = 0;
11472   if (inpoints < 3) {
11473     printf("Error:  Input must have at least three input points.\n");
11474     exit(1);
11475   }
11476
11477   initializepointpool();
11478
11479   /* Read the points. */
11480   coordindex = 0;
11481   attribindex = 0;
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++];
11490     }
11491     if (pointmarkerlist != (int *) NULL) {
11492       /* Read a point marker. */
11493       setpointmark(pointloop, pointmarkerlist[i]);
11494     } else {
11495       /* If no markers are specified, they default to zero. */
11496       setpointmark(pointloop, 0);
11497     }
11498     x = pointloop[0];
11499     y = pointloop[1];
11500     /* Determine the smallest and largest x and y coordinates. */
11501     if (i == 0) {
11502       xmin = xmax = x;
11503       ymin = ymax = y;
11504     } else {
11505       xmin = (x < xmin) ? x : xmin;
11506       xmax = (x > xmax) ? x : xmax;
11507       ymin = (y < ymin) ? y : ymin;
11508       ymax = (y > ymax) ? y : ymax;
11509     }
11510   }
11511
11512   /* Nonexistent x value used as a flag to mark circle events in sweepline */
11513   /*   Delaunay algorithm.                                                 */
11514   xminextreme = 10 * xmin - 9 * xmax;
11515 }
11516
11517 #endif /* TRILIBRARY */
11518
11519 /*****************************************************************************/
11520 /*                                                                           */
11521 /*  readholes()   Read the holes, and possibly regional attributes and area  */
11522 /*                constraints, from a .poly file.                            */
11523 /*                                                                           */
11524 /*****************************************************************************/
11525
11526 #ifndef TRILIBRARY
11527
11528 void readholes(polyfile, polyfilename, hlist, holes, rlist, regions)
11529 FILE *polyfile;
11530 char *polyfilename;
11531 REAL **hlist;
11532 int *holes;
11533 REAL **rlist;
11534 int *regions;
11535 {
11536   REAL *holelist;
11537   REAL *regionlist;
11538   char inputline[INPUTLINESIZE];
11539   char *stringptr;
11540   int index;
11541   int i;
11542
11543   /* Read the holes. */
11544   stringptr = readline(inputline, polyfile, polyfilename);
11545   *holes = (int) strtol (stringptr, &stringptr, 0);
11546   if (*holes > 0) {
11547     holelist = (REAL *) malloc(2 * *holes * sizeof(REAL));
11548     *hlist = holelist;
11549     if (holelist == (REAL *) NULL) {
11550       printf("Error:  Out of memory.\n");
11551       exit(1);
11552     }
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));
11559         exit(1);
11560       } else {
11561         holelist[i] = (REAL) strtod(stringptr, &stringptr);
11562       }
11563       stringptr = findfield(stringptr);
11564       if (*stringptr == '\0') {
11565         printf("Error:  Hole %d has no y coordinate.\n",
11566                firstnumber + (i >> 1));
11567         exit(1);
11568       } else {
11569         holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
11570       }
11571     }
11572   } else {
11573     *hlist = (REAL *) NULL;
11574   }
11575
11576 #ifndef CDT_ONLY
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");
11586         exit(1);
11587       }
11588       index = 0;
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",
11594                  firstnumber + i);
11595           exit(1);
11596         } else {
11597           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
11598         }
11599         stringptr = findfield(stringptr);
11600         if (*stringptr == '\0') {
11601           printf("Error:  Region %d has no y coordinate.\n",
11602                  firstnumber + i);
11603           exit(1);
11604         } else {
11605           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
11606         }
11607         stringptr = findfield(stringptr);
11608         if (*stringptr == '\0') {
11609           printf(
11610             "Error:  Region %d has no region attribute or area constraint.\n",
11611                  firstnumber + i);
11612           exit(1);
11613         } else {
11614           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
11615         }
11616         stringptr = findfield(stringptr);
11617         if (*stringptr == '\0') {
11618           regionlist[index] = regionlist[index - 1];
11619         } else {
11620           regionlist[index] = (REAL) strtod(stringptr, &stringptr);
11621         }
11622         index++;
11623       }
11624     }
11625   } else {
11626     /* Set `*regions' to zero to avoid an accidental free() later. */
11627     *regions = 0;
11628     *rlist = (REAL *) NULL;
11629   }
11630 #endif /* not CDT_ONLY */
11631
11632   fclose(polyfile);
11633 }
11634
11635 #endif /* not TRILIBRARY */
11636
11637 /*****************************************************************************/
11638 /*                                                                           */
11639 /*  finishfile()   Write the command line to the output file so the user     */
11640 /*                 can remember how the file was generated.  Close the file. */
11641 /*                                                                           */
11642 /*****************************************************************************/
11643
11644 #ifndef TRILIBRARY
11645
11646 void finishfile(outfile, argc, argv)
11647 FILE *outfile;
11648 int argc;
11649 char **argv;
11650 {
11651   int i;
11652
11653   fprintf(outfile, "# Generated by");
11654   for (i = 0; i < argc; i++) {
11655     fprintf(outfile, " ");
11656     fputs(argv[i], outfile);
11657   }
11658   fprintf(outfile, "\n");
11659   fclose(outfile);
11660 }
11661
11662 #endif /* not TRILIBRARY */
11663
11664 /*****************************************************************************/
11665 /*                                                                           */
11666 /*  writenodes()   Number the points and write them to a .node file.         */
11667 /*                                                                           */
11668 /*  To save memory, the point numbers are written over the shell markers     */
11669 /*  after the points are written to a file.                                  */
11670 /*                                                                           */
11671 /*****************************************************************************/
11672
11673 #ifdef TRILIBRARY
11674
11675 void writenodes(pointlist, pointattriblist, pointmarkerlist)
11676 REAL **pointlist;
11677 REAL **pointattriblist;
11678 int **pointmarkerlist;
11679
11680 #else /* not TRILIBRARY */
11681
11682 void writenodes(nodefilename, argc, argv)
11683 char *nodefilename;
11684 int argc;
11685 char **argv;
11686
11687 #endif /* not TRILIBRARY */
11688
11689 {
11690 #ifdef TRILIBRARY
11691   REAL *plist;
11692   REAL *palist;
11693   int *pmlist;
11694   int coordindex;
11695   int attribindex;
11696 #else /* not TRILIBRARY */
11697   FILE *outfile;
11698 #endif /* not TRILIBRARY */
11699   point pointloop;
11700   int pointnumber;
11701   int i;
11702
11703 #ifdef TRILIBRARY
11704   if (!quiet) {
11705     printf("Writing points.\n");
11706   }
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");
11712       exit(1);
11713     }
11714   }
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");
11720       exit(1);
11721     }
11722   }
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");
11728       exit(1);
11729     }
11730   }
11731   plist = *pointlist;
11732   palist = *pointattriblist;
11733   pmlist = *pointmarkerlist;
11734   coordindex = 0;
11735   attribindex = 0;
11736 #else /* not TRILIBRARY */
11737   if (!quiet) {
11738     printf("Writing %s.\n", nodefilename);
11739   }
11740   outfile = fopen(nodefilename, "w");
11741   if (outfile == (FILE *) NULL) {
11742     printf("  Error:  Cannot create file %s.\n", nodefilename);
11743     exit(1);
11744   }
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,
11748           1 - nobound);
11749 #endif /* not TRILIBRARY */
11750
11751   traversalinit(&points);
11752   pointloop = pointtraverse();
11753   pointnumber = firstnumber;
11754   while (pointloop != (point) NULL) {
11755 #ifdef TRILIBRARY
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];
11762     }
11763     if (!nobound) {
11764       /* Copy the boundary marker. */
11765       pmlist[pointnumber - firstnumber] = pointmark(pointloop);
11766     }
11767 #else /* not TRILIBRARY */
11768     /* Point number, x and y coordinates. */
11769     fprintf(outfile, "%4d    %.17g  %.17g", pointnumber, pointloop[0],
11770             pointloop[1]);
11771     for (i = 0; i < nextras; i++) {
11772       /* Write an attribute. */
11773       fprintf(outfile, "  %.17g", pointloop[i + 2]);
11774     }
11775     if (nobound) {
11776       fprintf(outfile, "\n");
11777     } else {
11778       /* Write the boundary marker. */
11779       fprintf(outfile, "    %d\n", pointmark(pointloop));
11780     }
11781 #endif /* not TRILIBRARY */
11782
11783     setpointmark(pointloop, pointnumber);
11784     pointloop = pointtraverse();
11785     pointnumber++;
11786   }
11787
11788 #ifndef TRILIBRARY
11789   finishfile(outfile, argc, argv);
11790 #endif /* not TRILIBRARY */
11791 }
11792
11793 /*****************************************************************************/
11794 /*                                                                           */
11795 /*  numbernodes()   Number the points.                                       */
11796 /*                                                                           */
11797 /*  Each point is assigned a marker equal to its number.                     */
11798 /*                                                                           */
11799 /*  Used when writenodes() is not called because no .node file is written.   */
11800 /*                                                                           */
11801 /*****************************************************************************/
11802
11803 void numbernodes()
11804 {
11805   point pointloop;
11806   int pointnumber;
11807
11808   traversalinit(&points);
11809   pointloop = pointtraverse();
11810   pointnumber = firstnumber;
11811   while (pointloop != (point) NULL) {
11812     setpointmark(pointloop, pointnumber);
11813     pointloop = pointtraverse();
11814     pointnumber++;
11815   }
11816 }
11817
11818 /*****************************************************************************/
11819 /*                                                                           */
11820 /*  writeelements()   Write the triangles to an .ele file.                   */
11821 /*                                                                           */
11822 /*****************************************************************************/
11823
11824 #ifdef TRILIBRARY
11825
11826 void writeelements(trianglelist, triangleattriblist)
11827 int **trianglelist;
11828 REAL **triangleattriblist;
11829
11830 #else /* not TRILIBRARY */
11831
11832 void writeelements(elefilename, argc, argv)
11833 char *elefilename;
11834 int argc;
11835 char **argv;
11836
11837 #endif /* not TRILIBRARY */
11838
11839 {
11840 #ifdef TRILIBRARY
11841   int *tlist;
11842   REAL *talist;
11843   int pointindex;
11844   int attribindex;
11845 #else /* not TRILIBRARY */
11846   FILE *outfile;
11847 #endif /* not TRILIBRARY */
11848   struct triedge triangleloop;
11849   point p1, p2, p3;
11850   point mid1, mid2, mid3;
11851   int elementnumber;
11852   int i;
11853
11854 #ifdef TRILIBRARY
11855   if (!quiet) {
11856     printf("Writing triangles.\n");
11857   }
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");
11864       exit(1);
11865     }
11866   }
11867   /* Allocate memory for output triangle attributes if necessary. */
11868   if ((eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
11869     *triangleattriblist = (REAL *) malloc(triangles.items * eextras *
11870                                           sizeof(REAL));
11871     if (*triangleattriblist == (REAL *) NULL) {
11872       printf("Error:  Out of memory.\n");
11873       exit(1);
11874     }
11875   }
11876   tlist = *trianglelist;
11877   talist = *triangleattriblist;
11878   pointindex = 0;
11879   attribindex = 0;
11880 #else /* not TRILIBRARY */
11881   if (!quiet) {
11882     printf("Writing %s.\n", elefilename);
11883   }
11884   outfile = fopen(elefilename, "w");
11885   if (outfile == (FILE *) NULL) {
11886     printf("  Error:  Cannot create file %s.\n", elefilename);
11887     exit(1);
11888   }
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 */
11893
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);
11902     if (order == 1) {
11903 #ifdef TRILIBRARY
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 */
11912     } else {
11913       mid1 = (point) triangleloop.tri[highorderindex + 1];
11914       mid2 = (point) triangleloop.tri[highorderindex + 2];
11915       mid3 = (point) triangleloop.tri[highorderindex];
11916 #ifdef TRILIBRARY
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 */
11929     }
11930
11931 #ifdef TRILIBRARY
11932     for (i = 0; i < eextras; i++) {
11933       talist[attribindex++] = elemattribute(triangleloop, i);
11934     }
11935 #else /* not TRILIBRARY */
11936     for (i = 0; i < eextras; i++) {
11937       fprintf(outfile, "  %.17g", elemattribute(triangleloop, i));
11938     }
11939     fprintf(outfile, "\n");
11940 #endif /* not TRILIBRARY */
11941
11942     triangleloop.tri = triangletraverse();
11943     elementnumber++;
11944   }
11945
11946 #ifndef TRILIBRARY
11947   finishfile(outfile, argc, argv);
11948 #endif /* not TRILIBRARY */
11949 }
11950
11951 /*****************************************************************************/
11952 /*                                                                           */
11953 /*  writepoly()   Write the segments and holes to a .poly file.              */
11954 /*                                                                           */
11955 /*****************************************************************************/
11956
11957 #ifdef TRILIBRARY
11958
11959 void writepoly(segmentlist, segmentmarkerlist)
11960 int **segmentlist;
11961 int **segmentmarkerlist;
11962
11963 #else /* not TRILIBRARY */
11964
11965 void writepoly(polyfilename, holelist, holes, regionlist, regions, argc, argv)
11966 char *polyfilename;
11967 REAL *holelist;
11968 int holes;
11969 REAL *regionlist;
11970 int regions;
11971 int argc;
11972 char **argv;
11973
11974 #endif /* not TRILIBRARY */
11975
11976 {
11977 #ifdef TRILIBRARY
11978   int *slist;
11979   int *smlist;
11980   int index;
11981 #else /* not TRILIBRARY */
11982   FILE *outfile;
11983   int i;
11984 #endif /* not TRILIBRARY */
11985   struct edge shelleloop;
11986   point endpoint1, endpoint2;
11987   int shellenumber;
11988
11989 #ifdef TRILIBRARY
11990   if (!quiet) {
11991     printf("Writing segments.\n");
11992   }
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");
11998       exit(1);
11999     }
12000   }
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");
12006       exit(1);
12007     }
12008   }
12009   slist = *segmentlist;
12010   smlist = *segmentmarkerlist;
12011   index = 0;
12012 #else /* not TRILIBRARY */
12013   if (!quiet) {
12014     printf("Writing %s.\n", polyfilename);
12015   }
12016   outfile = fopen(polyfilename, "w");
12017   if (outfile == (FILE *) NULL) {
12018     printf("  Error:  Cannot create file %s.\n", polyfilename);
12019     exit(1);
12020   }
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 */
12028
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);
12036 #ifdef TRILIBRARY
12037     /* Copy indices of the segment's two endpoints. */
12038     slist[index++] = pointmark(endpoint1);
12039     slist[index++] = pointmark(endpoint2);
12040     if (!nobound) {
12041       /* Copy the boundary marker. */
12042       smlist[shellenumber - firstnumber] = mark(shelleloop);
12043     }
12044 #else /* not TRILIBRARY */
12045     /* Segment number, indices of its two endpoints, and possibly a marker. */
12046     if (nobound) {
12047       fprintf(outfile, "%4d    %4d  %4d\n", shellenumber,
12048               pointmark(endpoint1), pointmark(endpoint2));
12049     } else {
12050       fprintf(outfile, "%4d    %4d  %4d    %4d\n", shellenumber,
12051               pointmark(endpoint1), pointmark(endpoint2), mark(shelleloop));
12052     }
12053 #endif /* not TRILIBRARY */
12054
12055     shelleloop.sh = shelletraverse();
12056     shellenumber++;
12057   }
12058
12059 #ifndef TRILIBRARY
12060 #ifndef CDT_ONLY
12061   fprintf(outfile, "%d\n", holes);
12062   if (holes > 0) {
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]);
12067     }
12068   }
12069   if (regions > 0) {
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]);
12076     }
12077   }
12078 #endif /* not CDT_ONLY */
12079
12080   finishfile(outfile, argc, argv);
12081 #endif /* not TRILIBRARY */
12082 }
12083
12084 /*****************************************************************************/
12085 /*                                                                           */
12086 /*  writeedges()   Write the edges to a .edge file.                          */
12087 /*                                                                           */
12088 /*****************************************************************************/
12089
12090 #ifdef TRILIBRARY
12091
12092 void writeedges(edgelist, edgemarkerlist)
12093 int **edgelist;
12094 int **edgemarkerlist;
12095
12096 #else /* not TRILIBRARY */
12097
12098 void writeedges(edgefilename, argc, argv)
12099 char *edgefilename;
12100 int argc;
12101 char **argv;
12102
12103 #endif /* not TRILIBRARY */
12104
12105 {
12106 #ifdef TRILIBRARY
12107   int *elist;
12108   int *emlist;
12109   int index;
12110 #else /* not TRILIBRARY */
12111   FILE *outfile;
12112 #endif /* not TRILIBRARY */
12113   struct triedge triangleloop, trisym;
12114   struct edge checkmark;
12115   point p1, p2;
12116   int edgenumber;
12117   triangle ptr;                         /* Temporary variable used by sym(). */
12118   shelle sptr;                      /* Temporary variable used by tspivot(). */
12119
12120 #ifdef TRILIBRARY
12121   if (!quiet) {
12122     printf("Writing edges.\n");
12123   }
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");
12129       exit(1);
12130     }
12131   }
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");
12137       exit(1);
12138     }
12139   }
12140   elist = *edgelist;
12141   emlist = *edgemarkerlist;
12142   index = 0;
12143 #else /* not TRILIBRARY */
12144   if (!quiet) {
12145     printf("Writing %s.\n", edgefilename);
12146   }
12147   outfile = fopen(edgefilename, "w");
12148   if (outfile == (FILE *) NULL) {
12149     printf("  Error:  Cannot create file %s.\n", edgefilename);
12150     exit(1);
12151   }
12152   /* Number of edges, number of boundary markers (zero or one). */
12153   fprintf(outfile, "%ld  %d\n", edges, 1 - nobound);
12154 #endif /* not TRILIBRARY */
12155
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);
12172 #ifdef TRILIBRARY
12173         elist[index++] = pointmark(p1);
12174         elist[index++] = pointmark(p2);
12175 #endif /* TRILIBRARY */
12176         if (nobound) {
12177 #ifndef 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 */
12182         } else {
12183           /* Edge number, indices of two endpoints, and a boundary marker. */
12184           /*   If there's no shell edge, the boundary marker is zero.      */
12185           if (useshelles) {
12186             tspivot(triangleloop, checkmark);
12187             if (checkmark.sh == dummysh) {
12188 #ifdef TRILIBRARY
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 */
12194             } else {
12195 #ifdef 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 */
12201             }
12202           } else {
12203 #ifdef 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 */
12209           }
12210         }
12211         edgenumber++;
12212       }
12213     }
12214     triangleloop.tri = triangletraverse();
12215   }
12216
12217 #ifndef TRILIBRARY
12218   finishfile(outfile, argc, argv);
12219 #endif /* not TRILIBRARY */
12220 }
12221
12222 /*****************************************************************************/
12223 /*                                                                           */
12224 /*  writevoronoi()   Write the Voronoi diagram to a .v.node and .v.edge      */
12225 /*                   file.                                                   */
12226 /*                                                                           */
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   */
12230 /*  edges.                                                                   */
12231 /*                                                                           */
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.                    */
12235 /*                                                                           */
12236 /*****************************************************************************/
12237
12238 #ifdef TRILIBRARY
12239
12240 void writevoronoi(vpointlist, vpointattriblist, vpointmarkerlist, vedgelist,
12241                   vedgemarkerlist, vnormlist)
12242 REAL **vpointlist;
12243 REAL **vpointattriblist;
12244 int **vpointmarkerlist;
12245 int **vedgelist;
12246 int **vedgemarkerlist;
12247 REAL **vnormlist;
12248
12249 #else /* not TRILIBRARY */
12250
12251 void writevoronoi(vnodefilename, vedgefilename, argc, argv)
12252 char *vnodefilename;
12253 char *vedgefilename;
12254 int argc;
12255 char **argv;
12256
12257 #endif /* not TRILIBRARY */
12258
12259 {
12260 #ifdef TRILIBRARY
12261   REAL *plist;
12262   REAL *palist;
12263   int *elist;
12264   REAL *normlist;
12265   int coordindex;
12266   int attribindex;
12267 #else /* not TRILIBRARY */
12268   FILE *outfile;
12269 #endif /* not TRILIBRARY */
12270   struct triedge triangleloop, trisym;
12271   point torg, tdest, tapex;
12272   REAL circumcenter[2];
12273   REAL xi, eta;
12274   int vnodenumber, vedgenumber;
12275   int p1, p2;
12276   int i;
12277   triangle ptr;                         /* Temporary variable used by sym(). */
12278
12279 #ifdef TRILIBRARY
12280   if (!quiet) {
12281     printf("Writing Voronoi vertices.\n");
12282   }
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");
12288       exit(1);
12289     }
12290   }
12291   /* Allocate memory for Voronoi vertex attributes if necessary. */
12292   if (*vpointattriblist == (REAL *) NULL) {
12293     *vpointattriblist = (REAL *) malloc(triangles.items * nextras *
12294                                         sizeof(REAL));
12295     if (*vpointattriblist == (REAL *) NULL) {
12296       printf("Error:  Out of memory.\n");
12297       exit(1);
12298     }
12299   }
12300   *vpointmarkerlist = (int *) NULL;
12301   plist = *vpointlist;
12302   palist = *vpointattriblist;
12303   coordindex = 0;
12304   attribindex = 0;
12305 #else /* not TRILIBRARY */
12306   if (!quiet) {
12307     printf("Writing %s.\n", vnodefilename);
12308   }
12309   outfile = fopen(vnodefilename, "w");
12310   if (outfile == (FILE *) NULL) {
12311     printf("  Error:  Cannot create file %s.\n", vnodefilename);
12312     exit(1);
12313   }
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 */
12318
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);
12328 #ifdef TRILIBRARY
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]);
12336     }
12337 #else /* not TRILIBRARY */
12338     /* Voronoi vertex number, x and y coordinates. */
12339     fprintf(outfile, "%4d    %.17g  %.17g", vnodenumber, circumcenter[0],
12340             circumcenter[1]);
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]));
12345     }
12346     fprintf(outfile, "\n");
12347 #endif /* not TRILIBRARY */
12348
12349     * (int *) (triangleloop.tri + 6) = vnodenumber;
12350     triangleloop.tri = triangletraverse();
12351     vnodenumber++;
12352   }
12353
12354 #ifndef TRILIBRARY
12355   finishfile(outfile, argc, argv);
12356 #endif /* not TRILIBRARY */
12357
12358 #ifdef TRILIBRARY
12359   if (!quiet) {
12360     printf("Writing Voronoi edges.\n");
12361   }
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");
12367       exit(1);
12368     }
12369   }
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");
12376       exit(1);
12377     }
12378   }
12379   elist = *vedgelist;
12380   normlist = *vnormlist;
12381   coordindex = 0;
12382 #else /* not TRILIBRARY */
12383   if (!quiet) {
12384     printf("Writing %s.\n", vedgefilename);
12385   }
12386   outfile = fopen(vedgefilename, "w");
12387   if (outfile == (FILE *) NULL) {
12388     printf("  Error:  Cannot create file %s.\n", vedgefilename);
12389     exit(1);
12390   }
12391   /* Number of edges, zero boundary markers. */
12392   fprintf(outfile, "%ld  %d\n", edges, 0);
12393 #endif /* not TRILIBRARY */
12394
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);
12414 #ifdef TRILIBRARY
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 */
12427         } else {
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. */
12431 #ifdef TRILIBRARY
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 */
12439         }
12440         vedgenumber++;
12441       }
12442     }
12443     triangleloop.tri = triangletraverse();
12444   }
12445
12446 #ifndef TRILIBRARY
12447   finishfile(outfile, argc, argv);
12448 #endif /* not TRILIBRARY */
12449 }
12450
12451 #ifdef TRILIBRARY
12452
12453 void writeneighbors(neighborlist)
12454 int **neighborlist;
12455
12456 #else /* not TRILIBRARY */
12457
12458 void writeneighbors(neighborfilename, argc, argv)
12459 char *neighborfilename;
12460 int argc;
12461 char **argv;
12462
12463 #endif /* not TRILIBRARY */
12464
12465 {
12466 #ifdef TRILIBRARY
12467   int *nlist;
12468   int index;
12469 #else /* not TRILIBRARY */
12470   FILE *outfile;
12471 #endif /* not TRILIBRARY */
12472   struct triedge triangleloop, trisym;
12473   int elementnumber;
12474   int neighbor1, neighbor2, neighbor3;
12475   triangle ptr;                         /* Temporary variable used by sym(). */
12476
12477 #ifdef TRILIBRARY
12478   if (!quiet) {
12479     printf("Writing neighbors.\n");
12480   }
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");
12486       exit(1);
12487     }
12488   }
12489   nlist = *neighborlist;
12490   index = 0;
12491 #else /* not TRILIBRARY */
12492   if (!quiet) {
12493     printf("Writing %s.\n", neighborfilename);
12494   }
12495   outfile = fopen(neighborfilename, "w");
12496   if (outfile == (FILE *) NULL) {
12497     printf("  Error:  Cannot create file %s.\n", neighborfilename);
12498     exit(1);
12499   }
12500   /* Number of triangles, three edges per triangle. */
12501   fprintf(outfile, "%ld  %d\n", triangles.items, 3);
12502 #endif /* not TRILIBRARY */
12503
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();
12511     elementnumber++;
12512   }
12513   * (int *) (dummytri + 6) = -1;
12514
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);
12528 #ifdef TRILIBRARY
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 */
12537
12538     triangleloop.tri = triangletraverse();
12539     elementnumber++;
12540   }
12541
12542 #ifndef TRILIBRARY
12543   finishfile(outfile, argc, argv);
12544 #endif /* TRILIBRARY */
12545 }
12546
12547 /*****************************************************************************/
12548 /*                                                                           */
12549 /*  writeoff()   Write the triangulation to an .off file.                    */
12550 /*                                                                           */
12551 /*  OFF stands for the Object File Format, a format used by the Geometry     */
12552 /*  Center's Geomview package.                                               */
12553 /*                                                                           */
12554 /*****************************************************************************/
12555
12556 #ifndef TRILIBRARY
12557
12558 void writeoff(offfilename, argc, argv)
12559 char *offfilename;
12560 int argc;
12561 char **argv;
12562 {
12563   FILE *outfile;
12564   struct triedge triangleloop;
12565   point pointloop;
12566   point p1, p2, p3;
12567
12568   if (!quiet) {
12569     printf("Writing %s.\n", offfilename);
12570   }
12571   outfile = fopen(offfilename, "w");
12572   if (outfile == (FILE *) NULL) {
12573     printf("  Error:  Cannot create file %s.\n", offfilename);
12574     exit(1);
12575   }
12576   /* Number of points, triangles, and edges. */
12577   fprintf(outfile, "OFF\n%ld  %ld  %ld\n", points.items, triangles.items,
12578           edges);
12579
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();
12588   }
12589
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();
12602   }
12603   finishfile(outfile, argc, argv);
12604 }
12605
12606 #endif /* not TRILIBRARY */
12607
12608 /**                                                                         **/
12609 /**                                                                         **/
12610 /********* File I/O routines end here                                *********/
12611
12612 /*****************************************************************************/
12613 /*                                                                           */
12614 /*  quality_statistics()   Print statistics about the quality of the mesh.   */
12615 /*                                                                           */
12616 /*****************************************************************************/
12617
12618 void quality_statistics()
12619 {
12620   struct triedge triangleloop;
12621   point p[3];
12622   REAL cossquaretable[8];
12623   REAL ratiotable[16];
12624   REAL dx[3], dy[3];
12625   REAL edgelength[3];
12626   REAL dotproduct;
12627   REAL cossquare;
12628   REAL triarea;
12629   REAL shortest, longest;
12630   REAL trilongest2;
12631   REAL smallestarea, biggestarea;
12632   REAL triminaltitude2;
12633   REAL minaltitude;
12634   REAL triaspect2;
12635   REAL worstaspect;
12636   REAL smallestangle, biggestangle;
12637   REAL radconst, degconst;
12638   int angletable[18];
12639   int aspecttable[16];
12640   int aspectindex;
12641   int tendegree;
12642   int acutebiggest;
12643   int i, ii, j, k;
12644
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];
12651   }
12652   for (i = 0; i < 18; i++) {
12653     angletable[i] = 0;
12654   }
12655
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;
12666   }
12667
12668   worstaspect = 0.0;
12669   minaltitude = xmax - xmin + ymax - ymin;
12670   minaltitude = minaltitude * minaltitude;
12671   shortest = minaltitude;
12672   longest = 0.0;
12673   smallestarea = minaltitude;
12674   biggestarea = 0.0;
12675   worstaspect = 0.0;
12676   smallestangle = 0.0;
12677   biggestangle = 2.0;
12678   acutebiggest = 1;
12679
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]);
12687     trilongest2 = 0.0;
12688
12689     for (i = 0; i < 3; i++) {
12690       j = plus1mod3[i];
12691       k = minus1mod3[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];
12697       }
12698       if (edgelength[i] > longest) {
12699         longest = edgelength[i];
12700       }
12701       if (edgelength[i] < shortest) {
12702         shortest = edgelength[i];
12703       }
12704     }
12705
12706     triarea = counterclockwise(p[0], p[1], p[2]);
12707     if (triarea < smallestarea) {
12708       smallestarea = triarea;
12709     }
12710     if (triarea > biggestarea) {
12711       biggestarea = triarea;
12712     }
12713     triminaltitude2 = triarea * triarea / trilongest2;
12714     if (triminaltitude2 < minaltitude) {
12715       minaltitude = triminaltitude2;
12716     }
12717     triaspect2 = trilongest2 / triminaltitude2;
12718     if (triaspect2 > worstaspect) {
12719       worstaspect = triaspect2;
12720     }
12721     aspectindex = 0;
12722     while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
12723            && (aspectindex < 15)) {
12724       aspectindex++;
12725     }
12726     aspecttable[aspectindex]++;
12727
12728     for (i = 0; i < 3; i++) {
12729       j = plus1mod3[i];
12730       k = minus1mod3[i];
12731       dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
12732       cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
12733       tendegree = 8;
12734       for (ii = 7; ii >= 0; ii--) {
12735         if (cossquare > cossquaretable[ii]) {
12736           tendegree = ii;
12737         }
12738       }
12739       if (dotproduct <= 0.0) {
12740         angletable[tendegree]++;
12741         if (cossquare > smallestangle) {
12742           smallestangle = cossquare;
12743         }
12744         if (acutebiggest && (cossquare < biggestangle)) {
12745           biggestangle = cossquare;
12746         }
12747       } else {
12748         angletable[17 - tendegree]++;
12749         if (acutebiggest || (cossquare > biggestangle)) {
12750           biggestangle = cossquare;
12751           acutebiggest = 0;
12752         }
12753       }
12754     }
12755     triangleloop.tri = triangletraverse();
12756   }
12757
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;
12766   } else {
12767     smallestangle = (REAL)(degconst * acos(sqrt(smallestangle)));
12768   }
12769   if (biggestangle >= 1.0) {
12770     biggestangle = 180.0;
12771   } else {
12772     if (acutebiggest) {
12773       biggestangle = (REAL)(degconst * acos(sqrt(biggestangle)));
12774     } else {
12775       biggestangle = (REAL)(180.0 - degconst * acos(sqrt(biggestangle)));
12776     }
12777   }
12778
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],
12788          aspecttable[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]);
12793   }
12794   printf("  %6.6g - %-6.6g    :  %8d    | %6.6g -            :  %8d\n",
12795          ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
12796          aspecttable[15]);
12797   printf(
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]);
12806   }
12807   printf("\n");
12808 }
12809
12810 /*****************************************************************************/
12811 /*                                                                           */
12812 /*  statistics()   Print all sorts of cool facts.                            */
12813 /*                                                                           */
12814 /*****************************************************************************/
12815
12816 void statistics()
12817 {
12818   printf("\nStatistics:\n\n");
12819   printf("  Input points: %d\n", inpoints);
12820   if (refine) {
12821     printf("  Input triangles: %d\n", inelements);
12822   }
12823   if (poly) {
12824     printf("  Input segments: %d\n", insegments);
12825     if (!refine) {
12826       printf("  Input holes: %d\n", holes);
12827     }
12828   }
12829
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);
12836   } else {
12837     printf("  Mesh convex hull edges: %ld\n\n", hullsize);
12838   }
12839   if (verbose) {
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);
12846     }
12847     if (viri.maxitems > 0) {
12848       printf("  Maximum number of viri: %ld\n", viri.maxitems);
12849     }
12850     if (badsegments.maxitems > 0) {
12851       printf("  Maximum number of encroached segments: %ld\n",
12852              badsegments.maxitems);
12853     }
12854     if (badtriangles.maxitems > 0) {
12855       printf("  Maximum number of bad triangles: %ld\n",
12856              badtriangles.maxitems);
12857     }
12858     if (splaynodes.maxitems > 0) {
12859       printf("  Maximum number of splay tree nodes: %ld\n",
12860              splaynodes.maxitems);
12861     }
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);
12870
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",
12876              hyperbolacount);
12877     }
12878     if (circumcentercount > 0) {
12879       printf("  Number of circumcenter computations: %ld\n",
12880              circumcentercount);
12881     }
12882     if (circletopcount > 0) {
12883       printf("  Number of circle top computations: %ld\n",
12884              circletopcount);
12885     }
12886     printf("\n");
12887   }
12888 }
12889
12890 /*****************************************************************************/
12891 /*                                                                           */
12892 /*  main() or triangulate()   Gosh, do everything.                           */
12893 /*                                                                           */
12894 /*  The sequence is roughly as follows.  Many of these steps can be skipped, */
12895 /*  depending on the command line switches.                                  */
12896 /*                                                                           */
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     */
12902 /*      hull (-c).                                                           */
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).          */
12912 /*                                                                           */
12913 /*****************************************************************************/
12914
12915 #ifdef TRILIBRARY
12916
12917 void triangulate(triswitches, in, out, vorout)
12918 char *triswitches;
12919 struct triangulateio *in;
12920 struct triangulateio *out;
12921 struct triangulateio *vorout;
12922
12923 #else /* not TRILIBRARY */
12924
12925 int main(argc, argv)
12926 int argc;
12927 char **argv;
12928
12929 #endif /* not TRILIBRARY */
12930
12931 {
12932   REAL *holearray;                                        /* Array of holes. */
12933   REAL *regionarray;   /* Array of regional attributes and area constraints. */
12934 #ifndef TRILIBRARY
12935   FILE *polyfile;
12936 #endif /* not TRILIBRARY */
12937 #ifndef NO_TIMER
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 */
12943
12944 #ifndef NO_TIMER
12945   gettimeofday(&tv0, &tz);
12946 #endif /* NO_TIMER */
12947
12948   triangleinit();
12949 #ifdef TRILIBRARY
12950   parsecommandline(1, &triswitches);
12951 #else /* not TRILIBRARY */
12952   parsecommandline(argc, argv);
12953 #endif /* not TRILIBRARY */
12954
12955 #ifdef 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 */
12961
12962 #ifndef NO_TIMER
12963   if (!quiet) {
12964     gettimeofday(&tv1, &tz);
12965   }
12966 #endif /* NO_TIMER */
12967
12968 #ifdef CDT_ONLY
12969   hullsize = delaunay();                          /* Triangulate the points. */
12970 #else /* not CDT_ONLY */
12971   if (refine) {
12972     /* Read and reconstruct a mesh. */
12973 #ifdef TRILIBRARY
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,
12981                            polyfile);
12982 #endif /* not TRILIBRARY */
12983   } else {
12984     hullsize = delaunay();                        /* Triangulate the points. */
12985   }
12986 #endif /* not CDT_ONLY */
12987
12988 #ifndef NO_TIMER
12989   if (!quiet) {
12990     gettimeofday(&tv2, &tz);
12991     if (refine) {
12992       printf("Mesh reconstruction");
12993     } else {
12994       printf("Delaunay");
12995     }
12996     printf(" milliseconds:  %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec)
12997            + (tv2.tv_usec - tv1.tv_usec) / 1000l);
12998   }
12999 #endif /* NO_TIMER */
13000
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;
13006
13007   if (useshelles) {
13008     checksegments = 1;                  /* Segments will be introduced next. */
13009     if (!refine) {
13010       /* Insert PSLG segments and/or convex hull segments. */
13011 #ifdef TRILIBRARY
13012       insegments = formskeleton(in->segmentlist, in->segmentmarkerlist,
13013                                 in->numberofsegments);
13014 #else /* not TRILIBRARY */
13015       insegments = formskeleton(polyfile, inpolyfilename);
13016 #endif /* not TRILIBRARY */
13017     }
13018   }
13019
13020 #ifndef NO_TIMER
13021   if (!quiet) {
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);
13027     }
13028   }
13029 #endif /* NO_TIMER */
13030
13031   if (poly) {
13032 #ifdef TRILIBRARY
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               &regionarray, &regions);
13040 #endif /* not TRILIBRARY */
13041     if (!refine) {
13042       /* Carve out holes and concavities. */
13043       carveholes(holearray, holes, regionarray, regions);
13044     }
13045   } else {
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.                                  */
13049     holes = 0;
13050     regions = 0;
13051   }
13052
13053 #ifndef NO_TIMER
13054   if (!quiet) {
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);
13059     }
13060   }
13061 #endif /* NO_TIMER */
13062
13063 #ifndef CDT_ONLY
13064   if (quality) {
13065     enforcequality();                 /* Enforce angle and area constraints. */
13066   }
13067 #endif /* not CDT_ONLY */
13068
13069 #ifndef NO_TIMER
13070   if (!quiet) {
13071     gettimeofday(&tv5, &tz);
13072 #ifndef CDT_ONLY
13073     if (quality) {
13074       printf("Quality milliseconds:  %ld\n",
13075              1000l * (tv5.tv_sec - tv4.tv_sec)
13076              + (tv5.tv_usec - tv4.tv_usec) / 1000l);
13077     }
13078 #endif /* not CDT_ONLY */
13079   }
13080 #endif /* NO_TIMER */
13081
13082   /* Compute the number of edges. */
13083   edges = (3l * triangles.items + hullsize) / 2l;
13084
13085   if (order > 1) {
13086     highorder();             /* Promote elements to higher polynomial order. */
13087   }
13088   if (!quiet) {
13089     printf("\n");
13090   }
13091
13092 #ifdef TRILIBRARY
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;
13099   if (useshelles) {
13100     out->numberofsegments = shelles.items;
13101   } else {
13102     out->numberofsegments = hullsize;
13103   }
13104   if (vorout != (struct triangulateio *) NULL) {
13105     vorout->numberofpoints = triangles.items;
13106     vorout->numberofpointattributes = nextras;
13107     vorout->numberofedges = edges;
13108   }
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)) {
13113     if (!quiet) {
13114 #ifdef TRILIBRARY
13115       printf("NOT writing points.\n");
13116 #else /* not TRILIBRARY */
13117       printf("NOT writing a .node file.\n");
13118 #endif /* not TRILIBRARY */
13119     }
13120     numbernodes();                 /* We must remember to number the points. */
13121   } else {
13122 #ifdef TRILIBRARY
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 */
13128   }
13129   if (noelewritten) {
13130     if (!quiet) {
13131 #ifdef TRILIBRARY
13132       printf("NOT writing triangles.\n");
13133 #else /* not TRILIBRARY */
13134       printf("NOT writing an .ele file.\n");
13135 #endif /* not TRILIBRARY */
13136     }
13137   } else {
13138 #ifdef TRILIBRARY
13139     writeelements(&out->trianglelist, &out->triangleattributelist);
13140 #else /* not TRILIBRARY */
13141     writeelements(outelefilename, argc, argv);
13142 #endif /* not TRILIBRARY */
13143   }
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) {
13149       if (!quiet) {
13150 #ifdef TRILIBRARY
13151         printf("NOT writing segments.\n");
13152 #else /* not TRILIBRARY */
13153         printf("NOT writing a .poly file.\n");
13154 #endif /* not TRILIBRARY */
13155       }
13156     } else {
13157 #ifdef TRILIBRARY
13158       writepoly(&out->segmentlist, &out->segmentmarkerlist);
13159       out->numberofholes = holes;
13160       out->numberofregions = regions;
13161       if (poly) {
13162         out->holelist = in->holelist;
13163         out->regionlist = in->regionlist;
13164       } else {
13165         out->holelist = (REAL *) NULL;
13166         out->regionlist = (REAL *) NULL;
13167       }
13168 #else /* not TRILIBRARY */
13169       writepoly(outpolyfilename, holearray, holes, regionarray, regions,
13170                 argc, argv);
13171 #endif /* not TRILIBRARY */
13172     }
13173   }
13174 #ifndef TRILIBRARY
13175 #ifndef CDT_ONLY
13176   if (regions > 0) {
13177     free(regionarray);
13178   }
13179 #endif /* not CDT_ONLY */
13180   if (holes > 0) {
13181     free(holearray);
13182   }
13183   if (geomview) {
13184     writeoff(offfilename, argc, argv);
13185   }
13186 #endif /* not TRILIBRARY */
13187   if (edgesout) {
13188 #ifdef TRILIBRARY
13189     writeedges(&out->edgelist, &out->edgemarkerlist);
13190 #else /* not TRILIBRARY */
13191     writeedges(edgefilename, argc, argv);
13192 #endif /* not TRILIBRARY */
13193   }
13194   if (voronoi) {
13195 #ifdef 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 */
13202   }
13203   if (neighbors) {
13204 #ifdef TRILIBRARY
13205     writeneighbors(&out->neighborlist);
13206 #else /* not TRILIBRARY */
13207     writeneighbors(neighborfilename, argc, argv);
13208 #endif /* not TRILIBRARY */
13209   }
13210
13211   if (!quiet) {
13212 #ifndef NO_TIMER
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 */
13221
13222     statistics();
13223   }
13224
13225 #ifndef REDUCED
13226   if (docheck) {
13227     checkmesh();
13228     checkdelaunay();
13229   }
13230 #endif /* not REDUCED */
13231
13232   triangledeinit();
13233 #ifndef TRILIBRARY
13234   return 0;
13235 #endif /* not TRILIBRARY */
13236 }