1 /*****************************************************************************/
2 /*                                                                           */
3 /*      888888888        ,o,                          / 888                  */
4 /*         888    88o88o  "    o8888o  88o8888o o88888o 888  o88888o         */
5 /*         888    888    888       88b 888  888 888 888 888 d888  88b        */
6 /*         888    888    888  o88^o888 888  888 "88888" 888 8888oo888        */
7 /*         888    888    888 C888  888 888  888  /      888 q888             */
8 /*         888    888    888  "88o^888 888  888 Cb      888  "88oooo"        */
9 /*                                              "8oo8D                       */
10 /*                                                                           */
11 /*  A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.      */
12 /*  (triangle.c)                                                             */
13 /*                                                                           */
14 /*  Version 1.6                                                              */
15 /*  July 28, 2005                                                            */
16 /*                                                                           */
17 /*  Copyright 1993, 1995, 1997, 1998, 2002, 2005                             */
18 /*  Jonathan Richard Shewchuk                                                */
19 /*  2360 Woolsey #H                                                          */
20 /*  Berkeley, California  94705-1927                                         */
21 /*  jrs@cs.berkeley.edu                                                      */
22 /*                                                                           */
23 /*  This program may be freely redistributed under the condition that the    */
24 /*    copyright notices (including this entire header and the copyright      */
25 /*    notice printed when the `-h' switch is selected) are not removed, and  */
26 /*    no compensation is received.  Private, research, and institutional     */
27 /*    use is free.  You may distribute modified versions of this code UNDER  */
28 /*    THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE   */
29 /*    SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE   */
30 /*    AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR    */
31 /*    NOTICE IS GIVEN OF THE MODIFICATIONS.  Distribution of this code as    */
32 /*    part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT  */
33 /*    WITH THE AUTHOR.  (If you are not directly supplying this code to a    */
34 /*    customer, and you are instead telling them how they can obtain it for  */
35 /*    free, then you are not required to make any arrangement with me.)      */
36 /*                                                                           */
37 /*  Hypertext instructions for Triangle are available on the Web at          */
38 /*                                                                           */
39 /*      http://www.cs.cmu.edu/~quake/triangle.html                           */
40 /*                                                                           */
41 /*  Disclaimer:  Neither I nor Carnegie Mellon warrant this code in any way  */
42 /*    whatsoever.  This code is provided "as-is".  Use at your own risk.     */
43 /*                                                                           */
44 /*  Some of the references listed below are marked with an asterisk.  [*]    */
45 /*    These references are available for downloading from the Web page       */
46 /*                                                                           */
47 /*      http://www.cs.cmu.edu/~quake/triangle.research.html                  */
48 /*                                                                           */
49 /*  Three papers discussing aspects of Triangle are available.  A short      */
50 /*    overview appears in "Triangle:  Engineering a 2D Quality Mesh          */
51 /*    Generator and Delaunay Triangulator," in Applied Computational         */
52 /*    Geometry:  Towards Geometric Engineering, Ming C. Lin and Dinesh       */
53 /*    Manocha, editors, Lecture Notes in Computer Science volume 1148,       */
54 /*    pages 203-222, Springer-Verlag, Berlin, May 1996 (from the First ACM   */
55 /*    Workshop on Applied Computational Geometry).  [*]                      */
56 /*                                                                           */
57 /*    The algorithms are discussed in the greatest detail in "Delaunay       */
58 /*    Refinement Algorithms for Triangular Mesh Generation," Computational   */
59 /*    Geometry:  Theory and Applications 22(1-3):21-74, May 2002.  [*]       */
60 /*                                                                           */
61 /*    More detail about the data structures may be found in my dissertation: */
62 /*    "Delaunay Refinement Mesh Generation," Ph.D. thesis, Technical Report  */
63 /*    CMU-CS-97-137, School of Computer Science, Carnegie Mellon University, */
64 /*    Pittsburgh, Pennsylvania, 18 May 1997.  [*]                            */
65 /*                                                                           */
66 /*  Triangle was created as part of the Quake Project in the School of       */
67 /*    Computer Science at Carnegie Mellon University.  For further           */
68 /*    information, see Hesheng Bao, Jacobo Bielak, Omar Ghattas, Loukas F.   */
69 /*    Kallivokas, David R. O'Hallaron, Jonathan R. Shewchuk, and Jifeng Xu,  */
70 /*    "Large-scale Simulation of Elastic Wave Propagation in Heterogeneous   */
71 /*    Media on Parallel Computers," Computer Methods in Applied Mechanics    */
72 /*    and Engineering 152(1-2):85-102, 22 January 1998.                      */
73 /*                                                                           */
74 /*  Triangle's Delaunay refinement algorithm for quality mesh generation is  */
75 /*    a hybrid of one due to Jim Ruppert, "A Delaunay Refinement Algorithm   */
76 /*    for Quality 2-Dimensional Mesh Generation," Journal of Algorithms      */
77 /*    18(3):548-585, May 1995 [*], and one due to L. Paul Chew, "Guaranteed- */
78 /*    Quality Mesh Generation for Curved Surfaces," Proceedings of the Ninth */
79 /*    Annual Symposium on Computational Geometry (San Diego, California),    */
80 /*    pages 274-280, Association for Computing Machinery, May 1993,          */
81 /*    http://portal.acm.org/citation.cfm?id=161150 .                         */
82 /*                                                                           */
83 /*  The Delaunay refinement algorithm has been modified so that it meshes    */
84 /*    domains with small input angles well, as described in Gary L. Miller,  */
85 /*    Steven E. Pav, and Noel J. Walkington, "When and Why Ruppert's         */
86 /*    Algorithm Works," Twelfth International Meshing Roundtable, pages      */
87 /*    91-102, Sandia National Laboratories, September 2003.  [*]             */
88 /*                                                                           */
89 /*  My implementation of the divide-and-conquer and incremental Delaunay     */
90 /*    triangulation algorithms follows closely the presentation of Guibas    */
91 /*    and Stolfi, even though I use a triangle-based data structure instead  */
92 /*    of their quad-edge data structure.  (In fact, I originally implemented */
93 /*    Triangle using the quad-edge data structure, but the switch to a       */
94 /*    triangle-based data structure sped Triangle by a factor of two.)  The  */
95 /*    mesh manipulation primitives and the two aforementioned Delaunay       */
96 /*    triangulation algorithms are described by Leonidas J. Guibas and Jorge */
97 /*    Stolfi, "Primitives for the Manipulation of General Subdivisions and   */
98 /*    the Computation of Voronoi Diagrams," ACM Transactions on Graphics     */
99 /*    4(2):74-123, April 1985, http://portal.acm.org/citation.cfm?id=282923 .*/
100 /*                                                                           */
101 /*  Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai   */
102 /*    Lee and Bruce J. Schachter, "Two Algorithms for Constructing the       */
103 /*    Delaunay Triangulation," International Journal of Computer and         */
104 /*    Information Science 9(3):219-242, 1980.  Triangle's improvement of the */
105 /*    divide-and-conquer algorithm by alternating between vertical and       */
106 /*    horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and-  */
107 /*    Conquer Algorithm for Constructing Delaunay Triangulations,"           */
108 /*    Algorithmica 2(2):137-151, 1987.                                       */
109 /*                                                                           */
110 /*  The incremental insertion algorithm was first proposed by C. L. Lawson,  */
111 /*    "Software for C1 Surface Interpolation," in Mathematical Software III, */
112 /*    John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977.     */
113 /*    For point location, I use the algorithm of Ernst P. Mucke, Isaac       */
114 /*    Saias, and Binhai Zhu, "Fast Randomized Point Location Without         */
115 /*    Preprocessing in Two- and Three-Dimensional Delaunay Triangulations,"  */
116 /*    Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
117 /*    ACM, May 1996.  [*]  If I were to randomize the order of vertex        */
118 /*    insertion (I currently don't bother), their result combined with the   */
119 /*    result of Kenneth L. Clarkson and Peter W. Shor, "Applications of      */
120 /*    Random Sampling in Computational Geometry II," Discrete &              */
121 /*    Computational Geometry 4(1):387-421, 1989, would yield an expected     */
122 /*    O(n^{4/3}) bound on running time.                                      */
123 /*                                                                           */
124 /*  The O(n log n) sweepline Delaunay triangulation algorithm is taken from  */
125 /*    Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams",          */
126 /*    Algorithmica 2(2):153-174, 1987.  A random sample of edges on the      */
127 /*    boundary of the triangulation are maintained in a splay tree for the   */
128 /*    purpose of point location.  Splay trees are described by Daniel        */
129 /*    Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
130 /*    Trees," Journal of the ACM 32(3):652-686, July 1985,                   */
131 /*    http://portal.acm.org/citation.cfm?id=3835 .                           */
132 /*                                                                           */
133 /*  The algorithms for exact computation of the signs of determinants are    */
134 /*    described in Jonathan Richard Shewchuk, "Adaptive Precision Floating-  */
135 /*    Point Arithmetic and Fast Robust Geometric Predicates," Discrete &     */
136 /*    Computational Geometry 18(3):305-363, October 1997.  (Also available   */
137 /*    as Technical Report CMU-CS-96-140, School of Computer Science,         */
138 /*    Carnegie Mellon University, Pittsburgh, Pennsylvania, May 1996.)  [*]  */
139 /*    An abbreviated version appears as Jonathan Richard Shewchuk, "Robust   */
140 /*    Adaptive Floating-Point Geometric Predicates," Proceedings of the      */
141 /*    Twelfth Annual Symposium on Computational Geometry, ACM, May 1996. [*] */
142 /*    Many of the ideas for my exact arithmetic routines originate with      */
143 /*    Douglas M. Priest, "Algorithms for Arbitrary Precision Floating Point  */
144 /*    Arithmetic," Tenth Symposium on Computer Arithmetic, pp. 132-143, IEEE */
145 /*    Computer Society Press, 1991.  [*]  Many of the ideas for the correct  */
146 /*    evaluation of the signs of determinants are taken from Steven Fortune  */
147 /*    and Christopher J. Van Wyk, "Efficient Exact Arithmetic for Computa-   */
148 /*    tional Geometry," Proceedings of the Ninth Annual Symposium on         */
149 /*    Computational Geometry, ACM, pp. 163-172, May 1993, and from Steven    */
150 /*    Fortune, "Numerical Stability of Algorithms for 2D Delaunay Triangu-   */
151 /*    lations," International Journal of Computational Geometry & Applica-   */
152 /*    tions 5(1-2):193-213, March-June 1995.                                 */
153 /*                                                                           */
154 /*  The method of inserting new vertices off-center (not precisely at the    */
155 /*    circumcenter of every poor-quality triangle) is from Alper Ungor,      */
156 /*    "Off-centers:  A New Type of Steiner Points for Computing Size-Optimal */
157 /*    Quality-Guaranteed Delaunay Triangulations," Proceedings of LATIN      */
158 /*    2004 (Buenos Aires, Argentina), April 2004.                            */
159 /*                                                                           */
160 /*  For definitions of and results involving Delaunay triangulations,        */
161 /*    constrained and conforming versions thereof, and other aspects of      */
162 /*    triangular mesh generation, see the excellent survey by Marshall Bern  */
163 /*    and David Eppstein, "Mesh Generation and Optimal Triangulation," in    */
164 /*    Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang,         */
165 /*    editors, World Scientific, Singapore, pp. 23-90, 1992.  [*]            */
166 /*                                                                           */
167 /*  The time for incrementally adding PSLG (planar straight line graph)      */
168 /*    segments to create a constrained Delaunay triangulation is probably    */
169 /*    O(t^2) per segment in the worst case and O(t) per segment in the       */
170 /*    common case, where t is the number of triangles that intersect the     */
171 /*    segment before it is inserted.  This doesn't count point location,     */
172 /*    which can be much more expensive.  I could improve this to O(d log d)  */
173 /*    time, but d is usually quite small, so it's not worth the bother.      */
174 /*    (This note does not apply when the -s switch is used, invoking a       */
175 /*    different method is used to insert segments.)                          */
176 /*                                                                           */
177 /*  The time for deleting a vertex from a Delaunay triangulation is O(d^2)   */
178 /*    in the worst case and O(d) in the common case, where d is the degree   */
179 /*    of the vertex being deleted.  I could improve this to O(d log d) time, */
180 /*    but d is usually quite small, so it's not worth the bother.            */
181 /*                                                                           */
182 /*  Ruppert's Delaunay refinement algorithm typically generates triangles    */
183 /*    at a linear rate (constant time per triangle) after the initial        */
184 /*    triangulation is formed.  There may be pathological cases where        */
185 /*    quadratic time is required, but these never arise in practice.         */
186 /*                                                                           */
187 /*  The geometric predicates (circumcenter calculations, segment             */
188 /*    intersection formulae, etc.) appear in my "Lecture Notes on Geometric  */
189 /*    Robustness" at http://www.cs.berkeley.edu/~jrs/mesh .                  */
190 /*                                                                           */
191 /*  If you make any improvements to this code, please please please let me   */
192 /*    know, so that I may obtain the improvements.  Even if you don't change */
193 /*    the code, I'd still love to hear what it's being used for.             */
194 /*                                                                           */
195 /*****************************************************************************/
196 
197 /* For single precision (which will save some memory and reduce paging),     */
198 /*   define the symbol SINGLE by using the -DSINGLE compiler switch or by    */
199 /*   writing "#define SINGLE" below.                                         */
200 /*                                                                           */
201 /* For double precision (which will allow you to refine meshes to a smaller  */
202 /*   edge length), leave SINGLE undefined.                                   */
203 /*                                                                           */
204 /* Double precision uses more memory, but improves the resolution of the     */
205 /*   meshes you can generate with Triangle.  It also reduces the likelihood  */
206 /*   of a floating exception due to overflow.  Finally, it is much faster    */
207 /*   than single precision on 64-bit architectures like the DEC Alpha.  I    */
208 /*   recommend double precision unless you want to generate a mesh for which */
209 /*   you do not have enough memory.                                          */
210 
211 /* #define SINGLE */
212 
213 #if 0
214 #ifdef SINGLE
215 #define REAL float
216 #else /* not SINGLE */
217 #define REAL double
218 #endif /* not SINGLE */
219 #endif
220 
221 /* If yours is not a Unix system, define the NO_TIMER compiler switch to     */
222 /*   remove the Unix-specific timing code.                                   */
223 
224 #define NO_TIMER
225 
226 /* To insert lots of self-checks for internal errors, define the SELF_CHECK  */
227 /*   symbol.  This will slow down the program significantly.  It is best to  */
228 /*   define the symbol using the -DSELF_CHECK compiler switch, but you could */
229 /*   write "#define SELF_CHECK" below.  If you are modifying this code, I    */
230 /*   recommend you turn self-checks on until your work is debugged.          */
231 
232 /* #define SELF_CHECK */
233 
234 /* To compile Triangle as a callable object library (triangle.o), define the */
235 /*   TRILIBRARY symbol.  Read the file triangle.h for details on how to call */
236 /*   the procedure triangulate() that results.                               */
237 
238 #define TRILIBRARY
239 
240 /* It is possible to generate a smaller version of Triangle using one or     */
241 /*   both of the following symbols.  Define the REDUCED symbol to eliminate  */
242 /*   all features that are primarily of research interest; specifically, the */
243 /*   -i, -F, -s, and -C switches.  Define the CDT_ONLY symbol to eliminate   */
244 /*   all meshing algorithms above and beyond constrained Delaunay            */
245 /*   triangulation; specifically, the -r, -q, -a, -u, -D, -S, and -s         */
246 /*   switches.  These reductions are most likely to be useful when           */
247 /*   generating an object library (triangle.o) by defining the TRILIBRARY    */
248 /*   symbol.                                                                 */
249 
250 /* #define REDUCED */
251 /* #define CDT_ONLY */
252 
253 /* On some machines, my exact arithmetic routines might be defeated by the   */
254 /*   use of internal extended precision floating-point registers.  The best  */
255 /*   way to solve this problem is to set the floating-point registers to use */
256 /*   single or double precision internally.  On 80x86 processors, this may   */
257 /*   be accomplished by setting the CPU86 symbol for the Microsoft C         */
258 /*   compiler, or the LINUX symbol for the gcc compiler running on Linux.    */
259 /*                                                                           */
260 /* An inferior solution is to declare certain values as `volatile', thus     */
261 /*   forcing them to be stored to memory and rounded off.  Unfortunately,    */
262 /*   this solution might slow Triangle down quite a bit.  To use volatile    */
263 /*   values, write "#define INEXACT volatile" below.  Normally, however,     */
264 /*   INEXACT should be defined to be nothing.  ("#define INEXACT".)          */
265 /*                                                                           */
266 /* For more discussion, see http://www.cs.cmu.edu/~quake/robust.pc.html .    */
267 /*   For yet more discussion, see Section 5 of my paper, "Adaptive Precision */
268 /*   Floating-Point Arithmetic and Fast Robust Geometric Predicates" (also   */
269 /*   available as Section 6.6 of my dissertation).                           */
270 
271 /* #define CPU86 */
272 /* #define LINUX */
273 
274 /* INEXACT is provided by "vpred.h" */
275 /* #define INEXACT */ /* Nothing */
276 /* #define INEXACT volatile */
277 
278 /* Maximum number of characters in a file name (including the null).         */
279 
280 #define FILENAMESIZE 2048
281 
282 /* Maximum number of characters in a line read from a file (including the    */
283 /*   null).                                                                  */
284 
285 #define INPUTLINESIZE 1024
286 
287 /* For efficiency, a variety of data structures are allocated in bulk.  The  */
288 /*   following constants determine how many of each structure is allocated   */
289 /*   at once.                                                                */
290 
291 #define TRIPERBLOCK 4092           /* Number of triangles allocated at once. */
292 #define SUBSEGPERBLOCK 508       /* Number of subsegments allocated at once. */
293 #define VERTEXPERBLOCK 4092         /* Number of vertices allocated at once. */
294 #define VIRUSPERBLOCK 1020   /* Number of virus triangles allocated at once. */
295 /* Number of encroached subsegments allocated at once. */
296 #define BADSUBSEGPERBLOCK 252
297 /* Number of skinny triangles allocated at once. */
298 #define BADTRIPERBLOCK 4092
299 /* Number of flipped triangles allocated at once. */
300 #define FLIPSTACKERPERBLOCK 252
301 /* Number of splay tree nodes allocated at once. */
302 #define SPLAYNODEPERBLOCK 508
303 
304 /* The vertex types.   A DEADVERTEX has been deleted entirely.  An           */
305 /*   UNDEADVERTEX is not part of the mesh, but is written to the output      */
306 /*   .node file and affects the node indexing in the other output files.     */
307 
308 #define INPUTVERTEX 0
309 #define SEGMENTVERTEX 1
310 #define FREEVERTEX 2
311 #define DEADVERTEX -32768
312 #define UNDEADVERTEX -32767
313 
314 /* The next line is used to outsmart some very stupid compilers.  If your    */
315 /*   compiler is smarter, feel free to replace the "int" with "void".        */
316 /*   Not that it matters.                                                    */
317 
318 /* #define VOID int */
319 
320 /* Two constants for algorithms based on random sampling.  Both constants    */
321 /*   have been chosen empirically to optimize their respective algorithms.   */
322 
323 /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide    */
324 /*   how large a random sample of triangles to inspect.                      */
325 
326 #define SAMPLEFACTOR 11
327 
328 /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
329 /*   of boundary edges should be maintained in the splay tree for point      */
330 /*   location on the front.                                                  */
331 
332 #define SAMPLERATE 10
333 
334 /* A number that speaks for itself, every kissable digit.                    */
335 
336 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
337 
338 /* Another fave.                                                             */
339 
340 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
341 
342 /* And here's one for those of you who are intimidated by math.              */
343 
344 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
345 
346 #if 0
347 #include <stdio.h>
348 #include <stdlib.h>
349 #include <string.h>
350 #include <math.h>
351 #ifndef NO_TIMER
352 #include <sys/time.h>
353 #endif /* not NO_TIMER */
354 #ifdef CPU86
355 #include <float.h>
356 #endif /* CPU86 */
357 #ifdef LINUX
358 #include <fpu_control.h>
359 #endif /* LINUX */
360 #ifdef TRILIBRARY
361 #include "triangle.h"
362 #endif /* TRILIBRARY */
363 #endif
364 
365 #include "triangle_p.h"
366 
367 /* A few forward declarations.                                               */
368 
369 #ifndef TRILIBRARY
370 char *readline();
371 char *findfield();
372 #endif /* not TRILIBRARY */
373 
374 /* Labels that signify the result of point location.  The result of a        */
375 /*   search indicates that the point falls in the interior of a triangle, on */
376 /*   an edge, on a vertex, or outside the mesh.                              */
377 
378 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
379 
380 /* Labels that signify the result of vertex insertion.  The result indicates */
381 /*   that the vertex was inserted with complete success, was inserted but    */
382 /*   encroaches upon a subsegment, was not inserted because it lies on a     */
383 /*   segment, or was not inserted because another vertex occupies the same   */
384 /*   location.                                                               */
385 
386 enum insertvertexresult {SUCCESSFULVERTEX, ENCROACHINGVERTEX, VIOLATINGVERTEX,
387                          DUPLICATEVERTEX};
388 
389 /* Labels that signify the result of direction finding.  The result          */
390 /*   indicates that a segment connecting the two query points falls within   */
391 /*   the direction triangle, along the left edge of the direction triangle,  */
392 /*   or along the right edge of the direction triangle.                      */
393 
394 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
395 
396 /*****************************************************************************/
397 /*                                                                           */
398 /*  The basic mesh data structures                                           */
399 /*                                                                           */
400 /*  There are three:  vertices, triangles, and subsegments (abbreviated      */
401 /*  `subseg').  These three data structures, linked by pointers, comprise    */
402 /*  the mesh.  A vertex simply represents a mesh vertex and its properties.  */
403 /*  A triangle is a triangle.  A subsegment is a special data structure used */
404 /*  to represent an impenetrable edge of the mesh (perhaps on the outer      */
405 /*  boundary, on the boundary of a hole, or part of an internal boundary     */
406 /*  separating two triangulated regions).  Subsegments represent boundaries, */
407 /*  defined by the user, that triangles may not lie across.                  */
408 /*                                                                           */
409 /*  A triangle consists of a list of three vertices, a list of three         */
410 /*  adjoining triangles, a list of three adjoining subsegments (when         */
411 /*  segments exist), an arbitrary number of optional user-defined            */
412 /*  floating-point attributes, and an optional area constraint.  The latter  */
413 /*  is an upper bound on the permissible area of each triangle in a region,  */
414 /*  used for mesh refinement.                                                */
415 /*                                                                           */
416 /*  For a triangle on a boundary of the mesh, some or all of the neighboring */
417 /*  triangles may not be present.  For a triangle in the interior of the     */
418 /*  mesh, often no neighboring subsegments are present.  Such absent         */
419 /*  triangles and subsegments are never represented by NULL pointers; they   */
420 /*  are represented by two special records:  `dummytri', the triangle that   */
421 /*  fills "outer space", and `dummysub', the omnipresent subsegment.         */
422 /*  `dummytri' and `dummysub' are used for several reasons; for instance,    */
423 /*  they can be dereferenced and their contents examined without violating   */
424 /*  protected memory.                                                        */
425 /*                                                                           */
426 /*  However, it is important to understand that a triangle includes other    */
427 /*  information as well.  The pointers to adjoining vertices, triangles, and */
428 /*  subsegments are ordered in a way that indicates their geometric relation */
429 /*  to each other.  Furthermore, each of these pointers contains orientation */
430 /*  information.  Each pointer to an adjoining triangle indicates which face */
431 /*  of that triangle is contacted.  Similarly, each pointer to an adjoining  */
432 /*  subsegment indicates which side of that subsegment is contacted, and how */
433 /*  the subsegment is oriented relative to the triangle.                     */
434 /*                                                                           */
435 /*  The data structure representing a subsegment may be thought to be        */
436 /*  abutting the edge of one or two triangle data structures:  either        */
437 /*  sandwiched between two triangles, or resting against one triangle on an  */
438 /*  exterior boundary or hole boundary.                                      */
439 /*                                                                           */
440 /*  A subsegment consists of a list of four vertices--the vertices of the    */
441 /*  subsegment, and the vertices of the segment it is a part of--a list of   */
442 /*  two adjoining subsegments, and a list of two adjoining triangles.  One   */
443 /*  of the two adjoining triangles may not be present (though there should   */
444 /*  always be one), and neighboring subsegments might not be present.        */
445 /*  Subsegments also store a user-defined integer "boundary marker".         */
446 /*  Typically, this integer is used to indicate what boundary conditions are */
447 /*  to be applied at that location in a finite element simulation.           */
448 /*                                                                           */
449 /*  Like triangles, subsegments maintain information about the relative      */
450 /*  orientation of neighboring objects.                                      */
451 /*                                                                           */
452 /*  Vertices are relatively simple.  A vertex is a list of floating-point    */
453 /*  numbers, starting with the x, and y coordinates, followed by an          */
454 /*  arbitrary number of optional user-defined floating-point attributes,     */
455 /*  followed by an integer boundary marker.  During the segment insertion    */
456 /*  phase, there is also a pointer from each vertex to a triangle that may   */
457 /*  contain it.  Each pointer is not always correct, but when one is, it     */
458 /*  speeds up segment insertion.  These pointers are assigned values once    */
459 /*  at the beginning of the segment insertion phase, and are not used or     */
460 /*  updated except during this phase.  Edge flipping during segment          */
461 /*  insertion will render some of them incorrect.  Hence, don't rely upon    */
462 /*  them for anything.                                                       */
463 /*                                                                           */
464 /*  Other than the exception mentioned above, vertices have no information   */
465 /*  about what triangles, subfacets, or subsegments they are linked to.      */
466 /*                                                                           */
467 /*****************************************************************************/
468 
469 /*****************************************************************************/
470 /*                                                                           */
471 /*  Handles                                                                  */
472 /*                                                                           */
473 /*  The oriented triangle (`otri') and oriented subsegment (`osub') data     */
474 /*  structures defined below do not themselves store any part of the mesh.   */
475 /*  The mesh itself is made of `triangle's, `subseg's, and `vertex's.        */
476 /*                                                                           */
477 /*  Oriented triangles and oriented subsegments will usually be referred to  */
478 /*  as "handles."  A handle is essentially a pointer into the mesh; it       */
479 /*  allows you to "hold" one particular part of the mesh.  Handles are used  */
480 /*  to specify the regions in which one is traversing and modifying the mesh.*/
481 /*  A single `triangle' may be held by many handles, or none at all.  (The   */
482 /*  latter case is not a memory leak, because the triangle is still          */
483 /*  connected to other triangles in the mesh.)                               */
484 /*                                                                           */
485 /*  An `otri' is a handle that holds a triangle.  It holds a specific edge   */
486 /*  of the triangle.  An `osub' is a handle that holds a subsegment.  It     */
487 /*  holds either the left or right side of the subsegment.                   */
488 /*                                                                           */
489 /*  Navigation about the mesh is accomplished through a set of mesh          */
490 /*  manipulation primitives, further below.  Many of these primitives take   */
491 /*  a handle and produce a new handle that holds the mesh near the first     */
492 /*  handle.  Other primitives take two handles and glue the corresponding    */
493 /*  parts of the mesh together.  The orientation of the handles is           */
494 /*  important.  For instance, when two triangles are glued together by the   */
495 /*  bond() primitive, they are glued at the edges on which the handles lie.  */
496 /*                                                                           */
497 /*  Because vertices have no information about which triangles they are      */
498 /*  attached to, I commonly represent a vertex by use of a handle whose      */
499 /*  origin is the vertex.  A single handle can simultaneously represent a    */
500 /*  triangle, an edge, and a vertex.                                         */
501 /*                                                                           */
502 /*****************************************************************************/
503 
504 /* The triangle data structure.  Each triangle contains three pointers to    */
505 /*   adjoining triangles, plus three pointers to vertices, plus three        */
506 /*   pointers to subsegments (declared below; these pointers are usually     */
507 /*   `dummysub').  It may or may not also contain user-defined attributes    */
508 /*   and/or a floating-point "area constraint."  It may also contain extra   */
509 /*   pointers for nodes, when the user asks for high-order elements.         */
510 /*   Because the size and structure of a `triangle' is not decided until     */
511 /*   runtime, I haven't simply declared the type `triangle' as a struct.     */
512 
513 typedef REAL **triangle;            /* Really:  typedef triangle *triangle   */
514 
515 /* An oriented triangle:  includes a pointer to a triangle and orientation.  */
516 /*   The orientation denotes an edge of the triangle.  Hence, there are      */
517 /*   three possible orientations.  By convention, each edge always points    */
518 /*   counterclockwise about the corresponding triangle.                      */
519 
520 struct otri {
521   triangle *tri;
522   int orient;                                         /* Ranges from 0 to 2. */
523 };
524 
525 /* The subsegment data structure.  Each subsegment contains two pointers to  */
526 /*   adjoining subsegments, plus four pointers to vertices, plus two         */
527 /*   pointers to adjoining triangles, plus one boundary marker, plus one     */
528 /*   segment number.                                                         */
529 
530 typedef REAL **subseg;                  /* Really:  typedef subseg *subseg   */
531 
532 /* An oriented subsegment:  includes a pointer to a subsegment and an        */
533 /*   orientation.  The orientation denotes a side of the edge.  Hence, there */
534 /*   are two possible orientations.  By convention, the edge is always       */
535 /*   directed so that the "side" denoted is the right side of the edge.      */
536 
537 struct osub {
538   subseg *ss;
539   int ssorient;                                       /* Ranges from 0 to 1. */
540 };
541 
542 /* The vertex data structure.  Each vertex is actually an array of REALs.    */
543 /*   The number of REALs is unknown until runtime.  An integer boundary      */
544 /*   marker, and sometimes a pointer to a triangle, is appended after the    */
545 /*   REALs.                                                                  */
546 
547 typedef REAL *vertex;
548 
549 /* A queue used to store encroached subsegments.  Each subsegment's vertices */
550 /*   are stored so that we can check whether a subsegment is still the same. */
551 
552 struct badsubseg {
553   subseg encsubseg;                             /* An encroached subsegment. */
554   vertex subsegorg, subsegdest;                         /* Its two vertices. */
555 };
556 
557 /* A queue used to store bad triangles.  The key is the square of the cosine */
558 /*   of the smallest angle of the triangle.  Each triangle's vertices are    */
559 /*   stored so that one can check whether a triangle is still the same.      */
560 
561 struct badtriang {
562   triangle poortri;                       /* A skinny or too-large triangle. */
563   REAL key;                             /* cos^2 of smallest (apical) angle. */
564   vertex triangorg, triangdest, triangapex;           /* Its three vertices. */
565   struct badtriang *nexttriang;             /* Pointer to next bad triangle. */
566 };
567 
568 /* A stack of triangles flipped during the most recent vertex insertion.     */
569 /*   The stack is used to undo the vertex insertion if the vertex encroaches */
570 /*   upon a subsegment.                                                      */
571 
572 struct flipstacker {
573   triangle flippedtri;                       /* A recently flipped triangle. */
574   struct flipstacker *prevflip;               /* Previous flip in the stack. */
575 };
576 
577 /* A node in a heap used to store events for the sweepline Delaunay          */
578 /*   algorithm.  Nodes do not point directly to their parents or children in */
579 /*   the heap.  Instead, each node knows its position in the heap, and can   */
580 /*   look up its parent and children in a separate array.  The `eventptr'    */
581 /*   points either to a `vertex' or to a triangle (in encoded format, so     */
582 /*   that an orientation is included).  In the latter case, the origin of    */
583 /*   the oriented triangle is the apex of a "circle event" of the sweepline  */
584 /*   algorithm.  To distinguish site events from circle events, all circle   */
585 /*   events are given an invalid (smaller than `xmin') x-coordinate `xkey'.  */
586 
587 struct event {
588   REAL xkey, ykey;                              /* Coordinates of the event. */
589   VOID *eventptr;      /* Can be a vertex or the location of a circle event. */
590   int heapposition;              /* Marks this event's position in the heap. */
591 };
592 
593 /* A node in the splay tree.  Each node holds an oriented ghost triangle     */
594 /*   that represents a boundary edge of the growing triangulation.  When a   */
595 /*   circle event covers two boundary edges with a triangle, so that they    */
596 /*   are no longer boundary edges, those edges are not immediately deleted   */
597 /*   from the tree; rather, they are lazily deleted when they are next       */
598 /*   encountered.  (Since only a random sample of boundary edges are kept    */
599 /*   in the tree, lazy deletion is faster.)  `keydest' is used to verify     */
600 /*   that a triangle is still the same as when it entered the splay tree; if */
601 /*   it has been rotated (due to a circle event), it no longer represents a  */
602 /*   boundary edge and should be deleted.                                    */
603 
604 struct splaynode {
605   struct otri keyedge;                     /* Lprev of an edge on the front. */
606   vertex keydest;           /* Used to verify that splay node is still live. */
607   struct splaynode *lchild, *rchild;              /* Children in splay tree. */
608 };
609 
610 /* A type used to allocate memory.  firstblock is the first block of items.  */
611 /*   nowblock is the block from which items are currently being allocated.   */
612 /*   nextitem points to the next slab of free memory for an item.            */
613 /*   deaditemstack is the head of a linked list (stack) of deallocated items */
614 /*   that can be recycled.  unallocateditems is the number of items that     */
615 /*   remain to be allocated from nowblock.                                   */
616 /*                                                                           */
617 /* Traversal is the process of walking through the entire list of items, and */
618 /*   is separate from allocation.  Note that a traversal will visit items on */
619 /*   the "deaditemstack" stack as well as live items.  pathblock points to   */
620 /*   the block currently being traversed.  pathitem points to the next item  */
621 /*   to be traversed.  pathitemsleft is the number of items that remain to   */
622 /*   be traversed in pathblock.                                              */
623 /*                                                                           */
624 /* alignbytes determines how new records should be aligned in memory.        */
625 /*   itembytes is the length of a record in bytes (after rounding up).       */
626 /*   itemsperblock is the number of items allocated at once in a single      */
627 /*   block.  itemsfirstblock is the number of items in the first block,      */
628 /*   which can vary from the others.  items is the number of currently       */
629 /*   allocated items.  maxitems is the maximum number of items that have     */
630 /*   been allocated at once; it is the current number of items plus the      */
631 /*   number of records kept on deaditemstack.                                */
632 
633 struct memorypool {
634   VOID **firstblock, **nowblock;
635   VOID *nextitem;
636   VOID *deaditemstack;
637   VOID **pathblock;
638   VOID *pathitem;
639   int alignbytes;
640   int itembytes;
641   int itemsperblock;
642   int itemsfirstblock;
643   long items, maxitems;
644   int unallocateditems;
645   int pathitemsleft;
646 };
647 
648 
649 /* Global constants.                                                         */
650 
651 REAL splitter;       /* Used to split REAL factors for exact multiplication. */
652 REAL epsilon;                             /* Floating-point machine epsilon. */
653 REAL resulterrbound;
654 REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
655 REAL iccerrboundA, iccerrboundB, iccerrboundC;
656 REAL o3derrboundA, o3derrboundB, o3derrboundC;
657 
658 /* Random number seed is not constant, but I've made it global anyway.       */
659 
660 unsigned long randomseed;                     /* Current random number seed. */
661 
662 
663 /* Mesh data structure.  Triangle operates on only one mesh, but the mesh    */
664 /*   structure is used (instead of global variables) to allow reentrancy.    */
665 
666 struct mesh {
667 
668 /* Variables used to allocate memory for triangles, subsegments, vertices,   */
669 /*   viri (triangles being eaten), encroached segments, bad (skinny or too   */
670 /*   large) triangles, and splay tree nodes.                                 */
671 
672   struct memorypool triangles;
673   struct memorypool subsegs;
674   struct memorypool vertices;
675   struct memorypool viri;
676   struct memorypool badsubsegs;
677   struct memorypool badtriangles;
678   struct memorypool flipstackers;
679   struct memorypool splaynodes;
680 
681 /* Variables that maintain the bad triangle queues.  The queues are          */
682 /*   ordered from 4095 (highest priority) to 0 (lowest priority).            */
683 
684   struct badtriang *queuefront[4096];
685   struct badtriang *queuetail[4096];
686   int nextnonemptyq[4096];
687   int firstnonemptyq;
688 
689 /* Variable that maintains the stack of recently flipped triangles.          */
690 
691   struct flipstacker *lastflip;
692 
693 /* Other variables. */
694 
695   REAL xmin, xmax, ymin, ymax;                            /* x and y bounds. */
696   REAL xminextreme;      /* Nonexistent x value used as a flag in sweepline. */
697   int invertices;                               /* Number of input vertices. */
698   int inelements;                              /* Number of input triangles. */
699   int insegments;                               /* Number of input segments. */
700   int holes;                                       /* Number of input holes. */
701   int regions;                                   /* Number of input regions. */
702   int undeads;    /* Number of input vertices that don't appear in the mesh. */
703   long edges;                                     /* Number of output edges. */
704   int mesh_dim;                                /* Dimension (ought to be 2). */
705   int nextras;                           /* Number of attributes per vertex. */
706   int eextras;                         /* Number of attributes per triangle. */
707   long hullsize;                          /* Number of edges in convex hull. */
708   int steinerleft;                 /* Number of Steiner points not yet used. */
709   int vertexmarkindex;         /* Index to find boundary marker of a vertex. */
710   int vertex2triindex;     /* Index to find a triangle adjacent to a vertex. */
711   int highorderindex;  /* Index to find extra nodes for high-order elements. */
712   int elemattribindex;            /* Index to find attributes of a triangle. */
713   int areaboundindex;             /* Index to find area bound of a triangle. */
714   int checksegments;         /* Are there segments in the triangulation yet? */
715   int checkquality;                  /* Has quality triangulation begun yet? */
716   int readnodefile;                           /* Has a .node file been read? */
717   long samples;              /* Number of random samples for point location. */
718 
719   long incirclecount;                 /* Number of incircle tests performed. */
720   long counterclockcount;     /* Number of counterclockwise tests performed. */
721   long orient3dcount;           /* Number of 3D orientation tests performed. */
722   long hyperbolacount;      /* Number of right-of-hyperbola tests performed. */
723   long circumcentercount;  /* Number of circumcenter calculations performed. */
724   long circletopcount;       /* Number of circle top calculations performed. */
725 
726 /* Triangular bounding box vertices.                                         */
727 
728   vertex infvertex1, infvertex2, infvertex3;
729 
730 /* Pointer to the `triangle' that occupies all of "outer space."             */
731 
732   triangle *dummytri;
733   triangle *dummytribase;    /* Keep base address so we can free() it later. */
734 
735 /* Pointer to the omnipresent subsegment.  Referenced by any triangle or     */
736 /*   subsegment that isn't really connected to a subsegment at that          */
737 /*   location.                                                               */
738 
739   subseg *dummysub;
740   subseg *dummysubbase;      /* Keep base address so we can free() it later. */
741 
742 /* Pointer to a recently visited triangle.  Improves point location if       */
743 /*   proximate vertices are inserted sequentially.                           */
744 
745   struct otri recenttri;
746 
747 };                                                  /* End of `struct mesh'. */
748 
749 
750 /* Data structure for command line switches and file names.  This structure  */
751 /*   is used (instead of global variables) to allow reentrancy.              */
752 
753 struct behavior {
754 
755 /* Switches for the triangulator.                                            */
756 /*   poly: -p switch.  refine: -r switch.                                    */
757 /*   quality: -q switch.                                                     */
758 /*     minangle: minimum angle bound, specified after -q switch.             */
759 /*     goodangle: cosine squared of minangle.                                */
760 /*     offconstant: constant used to place off-center Steiner points.        */
761 /*   vararea: -a switch without number.                                      */
762 /*   fixedarea: -a switch with number.                                       */
763 /*     maxarea: maximum area bound, specified after -a switch.               */
764 /*   usertest: -u switch.                                                    */
765 /*   regionattrib: -A switch.  convex: -c switch.                            */
766 /*   weighted: 1 for -w switch, 2 for -W switch.  jettison: -j switch        */
767 /*   firstnumber: inverse of -z switch.  All items are numbered starting     */
768 /*     from `firstnumber'.                                                   */
769 /*   edgesout: -e switch.  voronoi: -v switch.                               */
770 /*   neighbors: -n switch.  geomview: -g switch.                             */
771 /*   nobound: -B switch.  nopolywritten: -P switch.                          */
772 /*   nonodewritten: -N switch.  noelewritten: -E switch.                     */
773 /*   noiterationnum: -I switch.  noholes: -O switch.                         */
774 /*   noexact: -X switch.                                                     */
775 /*   order: element order, specified after -o switch.                        */
776 /*   nobisect: count of how often -Y switch is selected.                     */
777 /*   steiner: maximum number of Steiner points, specified after -S switch.   */
778 /*   incremental: -i switch.  sweepline: -F switch.                          */
779 /*   dwyer: inverse of -l switch.                                            */
780 /*   splitseg: -s switch.                                                    */
781 /*   conformdel: -D switch.  docheck: -C switch.                             */
782 /*   quiet: -Q switch.  verbose: count of how often -V switch is selected.   */
783 /*   usesegments: -p, -r, -q, or -c switch; determines whether segments are  */
784 /*     used at all.                                                          */
785 /*                                                                           */
786 /* Read the instructions to find out the meaning of these switches.          */
787 
788   int poly, refine, quality, vararea, fixedarea, usertest;
789   int regionattrib, convex, weighted, jettison;
790   int firstnumber;
791   int edgesout, voronoi, neighbors, geomview;
792   int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
793   int noholes, noexact, conformdel;
794   int incremental, sweepline, dwyer;
795   int splitseg;
796   int docheck;
797   int quiet, verbose;
798   int usesegments;
799   int order;
800   int nobisect;
801   int steiner;
802   REAL minangle, goodangle, offconstant;
803   REAL maxarea;
804 
805 /* Variables for file names.                                                 */
806 
807 #ifndef TRILIBRARY
808   char innodefilename[FILENAMESIZE];
809   char inelefilename[FILENAMESIZE];
810   char inpolyfilename[FILENAMESIZE];
811   char areafilename[FILENAMESIZE];
812   char outnodefilename[FILENAMESIZE];
813   char outelefilename[FILENAMESIZE];
814   char outpolyfilename[FILENAMESIZE];
815   char edgefilename[FILENAMESIZE];
816   char vnodefilename[FILENAMESIZE];
817   char vedgefilename[FILENAMESIZE];
818   char neighborfilename[FILENAMESIZE];
819   char offfilename[FILENAMESIZE];
820 #endif /* not TRILIBRARY */
821 
822 };                                              /* End of `struct behavior'. */
823 
824 
825 /*****************************************************************************/
826 /*                                                                           */
827 /*  Mesh manipulation primitives.  Each triangle contains three pointers to  */
828 /*  other triangles, with orientations.  Each pointer points not to the      */
829 /*  first byte of a triangle, but to one of the first three bytes of a       */
830 /*  triangle.  It is necessary to extract both the triangle itself and the   */
831 /*  orientation.  To save memory, I keep both pieces of information in one   */
832 /*  pointer.  To make this possible, I assume that all triangles are aligned */
833 /*  to four-byte boundaries.  The decode() routine below decodes a pointer,  */
834 /*  extracting an orientation (in the range 0 to 2) and a pointer to the     */
835 /*  beginning of a triangle.  The encode() routine compresses a pointer to a */
836 /*  triangle and an orientation into a single pointer.  My assumptions that  */
837 /*  triangles are four-byte-aligned and that the `unsigned long' type is     */
838 /*  long enough to hold a pointer are two of the few kludges in this program.*/
839 /*                                                                           */
840 /*  Subsegments are manipulated similarly.  A pointer to a subsegment        */
841 /*  carries both an address and an orientation in the range 0 to 1.          */
842 /*                                                                           */
843 /*  The other primitives take an oriented triangle or oriented subsegment,   */
844 /*  and return an oriented triangle or oriented subsegment or vertex; or     */
845 /*  they change the connections in the data structure.                       */
846 /*                                                                           */
847 /*  Below, triangles and subsegments are denoted by their vertices.  The     */
848 /*  triangle abc has origin (org) a, destination (dest) b, and apex (apex)   */
849 /*  c.  These vertices occur in counterclockwise order about the triangle.   */
850 /*  The handle abc may simultaneously denote vertex a, edge ab, and triangle */
851 /*  abc.                                                                     */
852 /*                                                                           */
853 /*  Similarly, the subsegment ab has origin (sorg) a and destination (sdest) */
854 /*  b.  If ab is thought to be directed upward (with b directly above a),    */
855 /*  then the handle ab is thought to grasp the right side of ab, and may     */
856 /*  simultaneously denote vertex a and edge ab.                              */
857 /*                                                                           */
858 /*  An asterisk (*) denotes a vertex whose identity is unknown.              */
859 /*                                                                           */
860 /*  Given this notation, a partial list of mesh manipulation primitives      */
861 /*  follows.                                                                 */
862 /*                                                                           */
863 /*                                                                           */
864 /*  For triangles:                                                           */
865 /*                                                                           */
866 /*  sym:  Find the abutting triangle; same edge.                             */
867 /*  sym(abc) -> ba*                                                          */
868 /*                                                                           */
869 /*  lnext:  Find the next edge (counterclockwise) of a triangle.             */
870 /*  lnext(abc) -> bca                                                        */
871 /*                                                                           */
872 /*  lprev:  Find the previous edge (clockwise) of a triangle.                */
873 /*  lprev(abc) -> cab                                                        */
874 /*                                                                           */
875 /*  onext:  Find the next edge counterclockwise with the same origin.        */
876 /*  onext(abc) -> ac*                                                        */
877 /*                                                                           */
878 /*  oprev:  Find the next edge clockwise with the same origin.               */
879 /*  oprev(abc) -> a*b                                                        */
880 /*                                                                           */
881 /*  dnext:  Find the next edge counterclockwise with the same destination.   */
882 /*  dnext(abc) -> *ba                                                        */
883 /*                                                                           */
884 /*  dprev:  Find the next edge clockwise with the same destination.          */
885 /*  dprev(abc) -> cb*                                                        */
886 /*                                                                           */
887 /*  rnext:  Find the next edge (counterclockwise) of the adjacent triangle.  */
888 /*  rnext(abc) -> *a*                                                        */
889 /*                                                                           */
890 /*  rprev:  Find the previous edge (clockwise) of the adjacent triangle.     */
891 /*  rprev(abc) -> b**                                                        */
892 /*                                                                           */
893 /*  org:  Origin          dest:  Destination          apex:  Apex            */
894 /*  org(abc) -> a         dest(abc) -> b              apex(abc) -> c         */
895 /*                                                                           */
896 /*  bond:  Bond two triangles together at the resepective handles.           */
897 /*  bond(abc, bad)                                                           */
898 /*                                                                           */
899 /*                                                                           */
900 /*  For subsegments:                                                         */
901 /*                                                                           */
902 /*  ssym:  Reverse the orientation of a subsegment.                          */
903 /*  ssym(ab) -> ba                                                           */
904 /*                                                                           */
905 /*  spivot:  Find adjoining subsegment with the same origin.                 */
906 /*  spivot(ab) -> a*                                                         */
907 /*                                                                           */
908 /*  snext:  Find next subsegment in sequence.                                */
909 /*  snext(ab) -> b*                                                          */
910 /*                                                                           */
911 /*  sorg:  Origin                      sdest:  Destination                   */
912 /*  sorg(ab) -> a                      sdest(ab) -> b                        */
913 /*                                                                           */
914 /*  sbond:  Bond two subsegments together at the respective origins.         */
915 /*  sbond(ab, ac)                                                            */
916 /*                                                                           */
917 /*                                                                           */
918 /*  For interacting tetrahedra and subfacets:                                */
919 /*                                                                           */
920 /*  tspivot:  Find a subsegment abutting a triangle.                         */
921 /*  tspivot(abc) -> ba                                                       */
922 /*                                                                           */
923 /*  stpivot:  Find a triangle abutting a subsegment.                         */
924 /*  stpivot(ab) -> ba*                                                       */
925 /*                                                                           */
926 /*  tsbond:  Bond a triangle to a subsegment.                                */
927 /*  tsbond(abc, ba)                                                          */
928 /*                                                                           */
929 /*****************************************************************************/
930 
931 /********* Mesh manipulation primitives begin here                   *********/
932 /**                                                                         **/
933 /**                                                                         **/
934 
935 /* Fast lookup arrays to speed some of the mesh manipulation primitives.     */
936 
937 int plus1mod3[3] = {1, 2, 0};
938 int minus1mod3[3] = {2, 0, 1};
939 
940 /********* Primitives for triangles                                  *********/
941 /*                                                                           */
942 /*                                                                           */
943 
944 /* decode() converts a pointer to an oriented triangle.  The orientation is  */
945 /*   extracted from the two least significant bits of the pointer.           */
946 
947 #define decode(ptr, otri)                                                     \
948   (otri).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l);         \
949   (otri).tri = (triangle *)                                                   \
950                   ((unsigned long) (ptr) ^ (unsigned long) (otri).orient)
951 
952 /* encode() compresses an oriented triangle into a single pointer.  It       */
953 /*   relies on the assumption that all triangles are aligned to four-byte    */
954 /*   boundaries, so the two least significant bits of (otri).tri are zero.   */
955 
956 #define encode(otri)                                                          \
957   (triangle) ((unsigned long) (otri).tri | (unsigned long) (otri).orient)
958 
959 /* The following handle manipulation primitives are all described by Guibas  */
960 /*   and Stolfi.  However, Guibas and Stolfi use an edge-based data          */
961 /*   structure, whereas I use a triangle-based data structure.               */
962 
963 /* sym() finds the abutting triangle, on the same edge.  Note that the edge  */
964 /*   direction is necessarily reversed, because the handle specified by an   */
965 /*   oriented triangle is directed counterclockwise around the triangle.     */
966 
967 #define sym(otri1, otri2)                                                     \
968   ptr = (otri1).tri[(otri1).orient];                                          \
969   decode(ptr, otri2);
970 
971 #define symself(otri)                                                         \
972   ptr = (otri).tri[(otri).orient];                                            \
973   decode(ptr, otri);
974 
975 /* lnext() finds the next edge (counterclockwise) of a triangle.             */
976 
977 #define lnext(otri1, otri2)                                                   \
978   (otri2).tri = (otri1).tri;                                                  \
979   (otri2).orient = plus1mod3[(otri1).orient]
980 
981 #define lnextself(otri)                                                       \
982   (otri).orient = plus1mod3[(otri).orient]
983 
984 /* lprev() finds the previous edge (clockwise) of a triangle.                */
985 
986 #define lprev(otri1, otri2)                                                   \
987   (otri2).tri = (otri1).tri;                                                  \
988   (otri2).orient = minus1mod3[(otri1).orient]
989 
990 #define lprevself(otri)                                                       \
991   (otri).orient = minus1mod3[(otri).orient]
992 
993 /* onext() spins counterclockwise around a vertex; that is, it finds the     */
994 /*   next edge with the same origin in the counterclockwise direction.  This */
995 /*   edge is part of a different triangle.                                   */
996 
997 #define onext(otri1, otri2)                                                   \
998   lprev(otri1, otri2);                                                        \
999   symself(otri2);
1000 
1001 #define onextself(otri)                                                       \
1002   lprevself(otri);                                                            \
1003   symself(otri);
1004 
1005 /* oprev() spins clockwise around a vertex; that is, it finds the next edge  */
1006 /*   with the same origin in the clockwise direction.  This edge is part of  */
1007 /*   a different triangle.                                                   */
1008 
1009 #define oprev(otri1, otri2)                                                   \
1010   sym(otri1, otri2);                                                          \
1011   lnextself(otri2);
1012 
1013 #define oprevself(otri)                                                       \
1014   symself(otri);                                                              \
1015   lnextself(otri);
1016 
1017 /* dnext() spins counterclockwise around a vertex; that is, it finds the     */
1018 /*   next edge with the same destination in the counterclockwise direction.  */
1019 /*   This edge is part of a different triangle.                              */
1020 
1021 #define dnext(otri1, otri2)                                                   \
1022   sym(otri1, otri2);                                                          \
1023   lprevself(otri2);
1024 
1025 #define dnextself(otri)                                                       \
1026   symself(otri);                                                              \
1027   lprevself(otri);
1028 
1029 /* dprev() spins clockwise around a vertex; that is, it finds the next edge  */
1030 /*   with the same destination in the clockwise direction.  This edge is     */
1031 /*   part of a different triangle.                                           */
1032 
1033 #define dprev(otri1, otri2)                                                   \
1034   lnext(otri1, otri2);                                                        \
1035   symself(otri2);
1036 
1037 #define dprevself(otri)                                                       \
1038   lnextself(otri);                                                            \
1039   symself(otri);
1040 
1041 /* rnext() moves one edge counterclockwise about the adjacent triangle.      */
1042 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1043 /*   changing triangles twice.)                                              */
1044 
1045 #define rnext(otri1, otri2)                                                   \
1046   sym(otri1, otri2);                                                          \
1047   lnextself(otri2);                                                           \
1048   symself(otri2);
1049 
1050 #define rnextself(otri)                                                       \
1051   symself(otri);                                                              \
1052   lnextself(otri);                                                            \
1053   symself(otri);
1054 
1055 /* rprev() moves one edge clockwise about the adjacent triangle.             */
1056 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
1057 /*   changing triangles twice.)                                              */
1058 
1059 #define rprev(otri1, otri2)                                                   \
1060   sym(otri1, otri2);                                                          \
1061   lprevself(otri2);                                                           \
1062   symself(otri2);
1063 
1064 #define rprevself(otri)                                                       \
1065   symself(otri);                                                              \
1066   lprevself(otri);                                                            \
1067   symself(otri);
1068 
1069 /* These primitives determine or set the origin, destination, or apex of a   */
1070 /* triangle.                                                                 */
1071 
1072 #define org(otri, vertexptr)                                                  \
1073   vertexptr = (vertex) (otri).tri[plus1mod3[(otri).orient] + 3]
1074 
1075 #define dest(otri, vertexptr)                                                 \
1076   vertexptr = (vertex) (otri).tri[minus1mod3[(otri).orient] + 3]
1077 
1078 #define apex(otri, vertexptr)                                                 \
1079   vertexptr = (vertex) (otri).tri[(otri).orient + 3]
1080 
1081 #define setorg(otri, vertexptr)                                               \
1082   (otri).tri[plus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1083 
1084 #define setdest(otri, vertexptr)                                              \
1085   (otri).tri[minus1mod3[(otri).orient] + 3] = (triangle) vertexptr
1086 
1087 #define setapex(otri, vertexptr)                                              \
1088   (otri).tri[(otri).orient + 3] = (triangle) vertexptr
1089 
1090 /* Bond two triangles together.                                              */
1091 
1092 #define bond(otri1, otri2)                                                    \
1093   (otri1).tri[(otri1).orient] = encode(otri2);                                \
1094   (otri2).tri[(otri2).orient] = encode(otri1)
1095 
1096 /* Dissolve a bond (from one side).  Note that the other triangle will still */
1097 /*   think it's connected to this triangle.  Usually, however, the other     */
1098 /*   triangle is being deleted entirely, or bonded to another triangle, so   */
1099 /*   it doesn't matter.                                                      */
1100 
1101 #define dissolve(otri)                                                        \
1102   (otri).tri[(otri).orient] = (triangle) m->dummytri
1103 
1104 /* Copy an oriented triangle.                                                */
1105 
1106 #define otricopy(otri1, otri2)                                                \
1107   (otri2).tri = (otri1).tri;                                                  \
1108   (otri2).orient = (otri1).orient
1109 
1110 /* Test for equality of oriented triangles.                                  */
1111 
1112 #define otriequal(otri1, otri2)                                               \
1113   (((otri1).tri == (otri2).tri) &&                                            \
1114    ((otri1).orient == (otri2).orient))
1115 
1116 /* Primitives to infect or cure a triangle with the virus.  These rely on    */
1117 /*   the assumption that all subsegments are aligned to four-byte boundaries.*/
1118 
1119 #define infect(otri)                                                          \
1120   (otri).tri[6] = (triangle)                                                  \
1121                     ((unsigned long) (otri).tri[6] | (unsigned long) 2l)
1122 
1123 #define uninfect(otri)                                                        \
1124   (otri).tri[6] = (triangle)                                                  \
1125                     ((unsigned long) (otri).tri[6] & ~ (unsigned long) 2l)
1126 
1127 /* Test a triangle for viral infection.                                      */
1128 
1129 #define infected(otri)                                                        \
1130   (((unsigned long) (otri).tri[6] & (unsigned long) 2l) != 0l)
1131 
1132 /* Check or set a triangle's attributes.                                     */
1133 
1134 #define elemattribute(otri, attnum)                                           \
1135   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)]
1136 
1137 #define setelemattribute(otri, attnum, value)                                 \
1138   ((REAL *) (otri).tri)[m->elemattribindex + (attnum)] = value
1139 
1140 /* Check or set a triangle's maximum area bound.                             */
1141 
1142 #define areabound(otri)  ((REAL *) (otri).tri)[m->areaboundindex]
1143 
1144 #define setareabound(otri, value)                                             \
1145   ((REAL *) (otri).tri)[m->areaboundindex] = value
1146 
1147 /* Check or set a triangle's deallocation.  Its second pointer is set to     */
1148 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1149 /*   for the stack of dead items.)  Its fourth pointer (its first vertex)    */
1150 /*   is set to NULL in case a `badtriang' structure points to it.            */
1151 
1152 #define deadtri(tria)  ((tria)[1] == (triangle) NULL)
1153 
1154 #define killtri(tria)                                                         \
1155   (tria)[1] = (triangle) NULL;                                                \
1156   (tria)[3] = (triangle) NULL
1157 
1158 /********* Primitives for subsegments                                *********/
1159 /*                                                                           */
1160 /*                                                                           */
1161 
1162 /* sdecode() converts a pointer to an oriented subsegment.  The orientation  */
1163 /*   is extracted from the least significant bit of the pointer.  The two    */
1164 /*   least significant bits (one for orientation, one for viral infection)   */
1165 /*   are masked out to produce the real pointer.                             */
1166 
1167 #define sdecode(sptr, osub)                                                   \
1168   (osub).ssorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l);      \
1169   (osub).ss = (subseg *)                                                      \
1170               ((unsigned long) (sptr) & ~ (unsigned long) 3l)
1171 
1172 /* sencode() compresses an oriented subsegment into a single pointer.  It    */
1173 /*   relies on the assumption that all subsegments are aligned to two-byte   */
1174 /*   boundaries, so the least significant bit of (osub).ss is zero.          */
1175 
1176 #define sencode(osub)                                                         \
1177   (subseg) ((unsigned long) (osub).ss | (unsigned long) (osub).ssorient)
1178 
1179 /* ssym() toggles the orientation of a subsegment.                           */
1180 
1181 #define ssym(osub1, osub2)                                                    \
1182   (osub2).ss = (osub1).ss;                                                    \
1183   (osub2).ssorient = 1 - (osub1).ssorient
1184 
1185 #define ssymself(osub)                                                        \
1186   (osub).ssorient = 1 - (osub).ssorient
1187 
1188 /* spivot() finds the other subsegment (from the same segment) that shares   */
1189 /*   the same origin.                                                        */
1190 
1191 #define spivot(osub1, osub2)                                                  \
1192   sptr = (osub1).ss[(osub1).ssorient];                                        \
1193   sdecode(sptr, osub2)
1194 
1195 #define spivotself(osub)                                                      \
1196   sptr = (osub).ss[(osub).ssorient];                                          \
1197   sdecode(sptr, osub)
1198 
1199 /* snext() finds the next subsegment (from the same segment) in sequence;    */
1200 /*   one whose origin is the input subsegment's destination.                 */
1201 
1202 #define snext(osub1, osub2)                                                   \
1203   sptr = (osub1).ss[1 - (osub1).ssorient];                                    \
1204   sdecode(sptr, osub2)
1205 
1206 #define snextself(osub)                                                       \
1207   sptr = (osub).ss[1 - (osub).ssorient];                                      \
1208   sdecode(sptr, osub)
1209 
1210 /* These primitives determine or set the origin or destination of a          */
1211 /*   subsegment or the segment that includes it.                             */
1212 
1213 #define sorg(osub, vertexptr)                                                 \
1214   vertexptr = (vertex) (osub).ss[2 + (osub).ssorient]
1215 
1216 #define sdest(osub, vertexptr)                                                \
1217   vertexptr = (vertex) (osub).ss[3 - (osub).ssorient]
1218 
1219 #define setsorg(osub, vertexptr)                                              \
1220   (osub).ss[2 + (osub).ssorient] = (subseg) vertexptr
1221 
1222 #define setsdest(osub, vertexptr)                                             \
1223   (osub).ss[3 - (osub).ssorient] = (subseg) vertexptr
1224 
1225 #define segorg(osub, vertexptr)                                               \
1226   vertexptr = (vertex) (osub).ss[4 + (osub).ssorient]
1227 
1228 #define segdest(osub, vertexptr)                                              \
1229   vertexptr = (vertex) (osub).ss[5 - (osub).ssorient]
1230 
1231 #define setsegorg(osub, vertexptr)                                            \
1232   (osub).ss[4 + (osub).ssorient] = (subseg) vertexptr
1233 
1234 #define setsegdest(osub, vertexptr)                                           \
1235   (osub).ss[5 - (osub).ssorient] = (subseg) vertexptr
1236 
1237 /* These primitives read or set a boundary marker.  Boundary markers are     */
1238 /*   used to hold user-defined tags for setting boundary conditions in       */
1239 /*   finite element solvers.                                                 */
1240 
1241 #define mark(osub)  (* (int *) ((osub).ss + 8))
1242 
1243 #define setmark(osub, value)                                                  \
1244   * (int *) ((osub).ss + 8) = value
1245 
1246 /* Bond two subsegments together.                                            */
1247 
1248 #define sbond(osub1, osub2)                                                   \
1249   (osub1).ss[(osub1).ssorient] = sencode(osub2);                              \
1250   (osub2).ss[(osub2).ssorient] = sencode(osub1)
1251 
1252 /* Dissolve a subsegment bond (from one side).  Note that the other          */
1253 /*   subsegment will still think it's connected to this subsegment.          */
1254 
1255 #define sdissolve(osub)                                                       \
1256   (osub).ss[(osub).ssorient] = (subseg) m->dummysub
1257 
1258 /* Copy a subsegment.                                                        */
1259 
1260 #define subsegcopy(osub1, osub2)                                              \
1261   (osub2).ss = (osub1).ss;                                                    \
1262   (osub2).ssorient = (osub1).ssorient
1263 
1264 /* Test for equality of subsegments.                                         */
1265 
1266 #define subsegequal(osub1, osub2)                                             \
1267   (((osub1).ss == (osub2).ss) &&                                              \
1268    ((osub1).ssorient == (osub2).ssorient))
1269 
1270 /* Check or set a subsegment's deallocation.  Its second pointer is set to   */
1271 /*   NULL to indicate that it is not allocated.  (Its first pointer is used  */
1272 /*   for the stack of dead items.)  Its third pointer (its first vertex)     */
1273 /*   is set to NULL in case a `badsubseg' structure points to it.            */
1274 
1275 #define deadsubseg(sub)  ((sub)[1] == (subseg) NULL)
1276 
1277 #define killsubseg(sub)                                                       \
1278   (sub)[1] = (subseg) NULL;                                                   \
1279   (sub)[2] = (subseg) NULL
1280 
1281 /********* Primitives for interacting triangles and subsegments      *********/
1282 /*                                                                           */
1283 /*                                                                           */
1284 
1285 /* tspivot() finds a subsegment abutting a triangle.                         */
1286 
1287 #define tspivot(otri, osub)                                                   \
1288   sptr = (subseg) (otri).tri[6 + (otri).orient];                              \
1289   sdecode(sptr, osub)
1290 
1291 /* stpivot() finds a triangle abutting a subsegment.  It requires that the   */
1292 /*   variable `ptr' of type `triangle' be defined.                           */
1293 
1294 #define stpivot(osub, otri)                                                   \
1295   ptr = (triangle) (osub).ss[6 + (osub).ssorient];                            \
1296   decode(ptr, otri)
1297 
1298 /* Bond a triangle to a subsegment.                                          */
1299 
1300 #define tsbond(otri, osub)                                                    \
1301   (otri).tri[6 + (otri).orient] = (triangle) sencode(osub);                   \
1302   (osub).ss[6 + (osub).ssorient] = (subseg) encode(otri)
1303 
1304 /* Dissolve a bond (from the triangle side).                                 */
1305 
1306 #define tsdissolve(otri)                                                      \
1307   (otri).tri[6 + (otri).orient] = (triangle) m->dummysub
1308 
1309 /* Dissolve a bond (from the subsegment side).                               */
1310 
1311 #define stdissolve(osub)                                                      \
1312   (osub).ss[6 + (osub).ssorient] = (subseg) m->dummytri
1313 
1314 /********* Primitives for vertices                                   *********/
1315 /*                                                                           */
1316 /*                                                                           */
1317 
1318 #define vertexmark(vx)  ((int *) (vx))[m->vertexmarkindex]
1319 
1320 #define setvertexmark(vx, value)                                              \
1321   ((int *) (vx))[m->vertexmarkindex] = value
1322 
1323 #define vertextype(vx)  ((int *) (vx))[m->vertexmarkindex + 1]
1324 
1325 #define setvertextype(vx, value)                                              \
1326   ((int *) (vx))[m->vertexmarkindex + 1] = value
1327 
1328 #define vertex2tri(vx)  ((triangle *) (vx))[m->vertex2triindex]
1329 
1330 #define setvertex2tri(vx, value)                                              \
1331   ((triangle *) (vx))[m->vertex2triindex] = value
1332 
1333 /**                                                                         **/
1334 /**                                                                         **/
1335 /********* Mesh manipulation primitives end here                     *********/
1336 
1337 /********* User-defined triangle evaluation routine begins here      *********/
1338 /**                                                                         **/
1339 /**                                                                         **/
1340 
1341 /*****************************************************************************/
1342 /*                                                                           */
1343 /*  triunsuitable()   Determine if a triangle is unsuitable, and thus must   */
1344 /*                    be further refined.                                    */
1345 /*                                                                           */
1346 /*  You may write your own procedure that decides whether or not a selected  */
1347 /*  triangle is too big (and needs to be refined).  There are two ways to do */
1348 /*  this.                                                                    */
1349 /*                                                                           */
1350 /*  (1)  Modify the procedure `triunsuitable' below, then recompile          */
1351 /*  Triangle.                                                                */
1352 /*                                                                           */
1353 /*  (2)  Define the symbol EXTERNAL_TEST (either by adding the definition    */
1354 /*  to this file, or by using the appropriate compiler switch).  This way,   */
1355 /*  you can compile triangle.c separately from your test.  Write your own    */
1356 /*  `triunsuitable' procedure in a separate C file (using the same prototype */
1357 /*  as below).  Compile it and link the object code with triangle.o.         */
1358 /*                                                                           */
1359 /*  This procedure returns 1 if the triangle is too large and should be      */
1360 /*  refined; 0 otherwise.                                                    */
1361 /*                                                                           */
1362 /*****************************************************************************/
1363 
1364 #ifdef EXTERNAL_TEST
1365 
1366 int triunsuitable();
1367 
1368 #else /* not EXTERNAL_TEST */
1369 
1370 #ifdef ANSI_DECLARATORS
1371 int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area)
1372 #else /* not ANSI_DECLARATORS */
1373 int triunsuitable(triorg, tridest, triapex, area)
1374 vertex triorg;                              /* The triangle's origin vertex. */
1375 vertex tridest;                        /* The triangle's destination vertex. */
1376 vertex triapex;                               /* The triangle's apex vertex. */
1377 REAL area;                                      /* The area of the triangle. */
1378 #endif /* not ANSI_DECLARATORS */
1379 
1380 {
1381   REAL dxoa, dxda, dxod;
1382   REAL dyoa, dyda, dyod;
1383   REAL oalen, dalen, odlen;
1384   REAL maxlen;
1385 
1386   dxoa = triorg[0] - triapex[0];
1387   dyoa = triorg[1] - triapex[1];
1388   dxda = tridest[0] - triapex[0];
1389   dyda = tridest[1] - triapex[1];
1390   dxod = triorg[0] - tridest[0];
1391   dyod = triorg[1] - tridest[1];
1392   /* Find the squares of the lengths of the triangle's three edges. */
1393   oalen = dxoa * dxoa + dyoa * dyoa;
1394   dalen = dxda * dxda + dyda * dyda;
1395   odlen = dxod * dxod + dyod * dyod;
1396   /* Find the square of the length of the longest edge. */
1397   maxlen = (dalen > oalen) ? dalen : oalen;
1398   maxlen = (odlen > maxlen) ? odlen : maxlen;
1399 
1400   if (maxlen > 0.05 * (triorg[0] * triorg[0] + triorg[1] * triorg[1]) + 0.02) {
1401     return 1;
1402   } else {
1403     return 0;
1404   }
1405 }
1406 
1407 #endif /* not EXTERNAL_TEST */
1408 
1409 /**                                                                         **/
1410 /**                                                                         **/
1411 /********* User-defined triangle evaluation routine ends here        *********/
1412 
1413 /********* Memory allocation and program exit wrappers begin here    *********/
1414 /**                                                                         **/
1415 /**                                                                         **/
1416 
1417 #ifdef ANSI_DECLARATORS
1418 void triexit(int status)
1419 #else /* not ANSI_DECLARATORS */
1420 void triexit(status)
1421 int status;
1422 #endif /* not ANSI_DECLARATORS */
1423 
1424 {
1425   exit(status);
1426 }
1427 
1428 #ifdef ANSI_DECLARATORS
1429 VOID *trimalloc(int size)
1430 #else /* not ANSI_DECLARATORS */
1431 VOID *trimalloc(size)
1432 int size;
1433 #endif /* not ANSI_DECLARATORS */
1434 
1435 {
1436   VOID *memptr;
1437 
1438   memptr = (VOID *) malloc((unsigned int) size);
1439   if (memptr == (VOID *) NULL) {
1440     printf("Error:  Out of memory.\n");
1441     triexit(1);
1442   }
1443   return(memptr);
1444 }
1445 
1446 #ifdef ANSI_DECLARATORS
1447 void trifree(VOID *memptr)
1448 #else /* not ANSI_DECLARATORS */
1449 void trifree(memptr)
1450 VOID *memptr;
1451 #endif /* not ANSI_DECLARATORS */
1452 
1453 {
1454   free(memptr);
1455 }
1456 
1457 /**                                                                         **/
1458 /**                                                                         **/
1459 /********* Memory allocation and program exit wrappers end here      *********/
1460 
1461 /********* User interaction routines begin here                      *********/
1462 /**                                                                         **/
1463 /**                                                                         **/
1464 
1465 /*****************************************************************************/
1466 /*                                                                           */
1467 /*  syntax()   Print list of command line switches.                          */
1468 /*                                                                           */
1469 /*****************************************************************************/
1470 
1471 #ifndef TRILIBRARY
1472 
syntax()1473 void syntax()
1474 {
1475 #ifdef CDT_ONLY
1476 #ifdef REDUCED
1477   printf("triangle [-pAcjevngBPNEIOXzo_lQVh] input_file\n");
1478 #else /* not REDUCED */
1479   printf("triangle [-pAcjevngBPNEIOXzo_iFlCQVh] input_file\n");
1480 #endif /* not REDUCED */
1481 #else /* not CDT_ONLY */
1482 #ifdef REDUCED
1483   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__lQVh] input_file\n");
1484 #else /* not REDUCED */
1485   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
1486 #endif /* not REDUCED */
1487 #endif /* not CDT_ONLY */
1488 
1489   printf("    -p  Triangulates a Planar Straight Line Graph (.poly file).\n");
1490 #ifndef CDT_ONLY
1491   printf("    -r  Refines a previously generated mesh.\n");
1492   printf(
1493     "    -q  Quality mesh generation.  A minimum angle may be specified.\n");
1494   printf("    -a  Applies a maximum triangle area constraint.\n");
1495   printf("    -u  Applies a user-defined triangle constraint.\n");
1496 #endif /* not CDT_ONLY */
1497   printf(
1498     "    -A  Applies attributes to identify triangles in certain regions.\n");
1499   printf("    -c  Encloses the convex hull with segments.\n");
1500 #ifndef CDT_ONLY
1501   printf("    -D  Conforming Delaunay:  all triangles are truly Delaunay.\n");
1502 #endif /* not CDT_ONLY */
1503 /*
1504   printf("    -w  Weighted Delaunay triangulation.\n");
1505   printf("    -W  Regular triangulation (lower hull of a height field).\n");
1506 */
1507   printf("    -j  Jettison unused vertices from output .node file.\n");
1508   printf("    -e  Generates an edge list.\n");
1509   printf("    -v  Generates a Voronoi diagram.\n");
1510   printf("    -n  Generates a list of triangle neighbors.\n");
1511   printf("    -g  Generates an .off file for Geomview.\n");
1512   printf("    -B  Suppresses output of boundary information.\n");
1513   printf("    -P  Suppresses output of .poly file.\n");
1514   printf("    -N  Suppresses output of .node file.\n");
1515   printf("    -E  Suppresses output of .ele file.\n");
1516   printf("    -I  Suppresses mesh iteration numbers.\n");
1517   printf("    -O  Ignores holes in .poly file.\n");
1518   printf("    -X  Suppresses use of exact arithmetic.\n");
1519   printf("    -z  Numbers all items starting from zero (rather than one).\n");
1520   printf("    -o2 Generates second-order subparametric elements.\n");
1521 #ifndef CDT_ONLY
1522   printf("    -Y  Suppresses boundary segment splitting.\n");
1523   printf("    -S  Specifies maximum number of added Steiner points.\n");
1524 #endif /* not CDT_ONLY */
1525 #ifndef REDUCED
1526   printf("    -i  Uses incremental method, rather than divide-and-conquer.\n");
1527   printf("    -F  Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
1528 #endif /* not REDUCED */
1529   printf("    -l  Uses vertical cuts only, rather than alternating cuts.\n");
1530 #ifndef REDUCED
1531 #ifndef CDT_ONLY
1532   printf(
1533     "    -s  Force segments into mesh by splitting (instead of using CDT).\n");
1534 #endif /* not CDT_ONLY */
1535   printf("    -C  Check consistency of final mesh.\n");
1536 #endif /* not REDUCED */
1537   printf("    -Q  Quiet:  No terminal output except errors.\n");
1538   printf("    -V  Verbose:  Detailed information on what I'm doing.\n");
1539   printf("    -h  Help:  Detailed instructions for Triangle.\n");
1540   triexit(0);
1541 }
1542 
1543 #endif /* not TRILIBRARY */
1544 
1545 /*****************************************************************************/
1546 /*                                                                           */
1547 /*  info()   Print out complete instructions.                                */
1548 /*                                                                           */
1549 /*****************************************************************************/
1550 
1551 #ifndef TRILIBRARY
1552 
info()1553 void info()
1554 {
1555   printf("Triangle\n");
1556   printf(
1557 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
1558   printf("Version 1.6\n\n");
1559   printf(
1560 "Copyright 1993, 1995, 1997, 1998, 2002, 2005 Jonathan Richard Shewchuk\n");
1561   printf("2360 Woolsey #H / Berkeley, California 94705-1927\n");
1562   printf("Bugs/comments to jrs@cs.berkeley.edu\n");
1563   printf(
1564 "Created as part of the Quake project (tools for earthquake simulation).\n");
1565   printf(
1566 "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
1567   printf("There is no warranty whatsoever.  Use at your own risk.\n");
1568 #ifdef SINGLE
1569   printf("This executable is compiled for single precision arithmetic.\n\n\n");
1570 #else /* not SINGLE */
1571   printf("This executable is compiled for double precision arithmetic.\n\n\n");
1572 #endif /* not SINGLE */
1573   printf(
1574 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
1575   printf(
1576 "triangulations, conforming Delaunay triangulations, Voronoi diagrams, and\n");
1577   printf(
1578 "high-quality triangular meshes.  The latter can be generated with no small\n"
1579 );
1580   printf(
1581 "or large angles, and are thus suitable for finite element analysis.  If no\n"
1582 );
1583   printf(
1584 "command line switch is specified, your .node input file is read, and the\n");
1585   printf(
1586 "Delaunay triangulation is returned in .node and .ele output files.  The\n");
1587   printf("command syntax is:\n\n");
1588   printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
1589   printf(
1590 "Underscores indicate that numbers may optionally follow certain switches.\n");
1591   printf(
1592 "Do not leave any space between a switch and its numeric parameter.\n");
1593   printf(
1594 "input_file must be a file with extension .node, or extension .poly if the\n");
1595   printf(
1596 "-p switch is used.  If -r is used, you must supply .node and .ele files,\n");
1597   printf(
1598 "and possibly a .poly file and an .area file as well.  The formats of these\n"
1599 );
1600   printf("files are described below.\n\n");
1601   printf("Command Line Switches:\n\n");
1602   printf(
1603 "    -p  Reads a Planar Straight Line Graph (.poly file), which can specify\n"
1604 );
1605   printf(
1606 "        vertices, segments, holes, regional attributes, and regional area\n");
1607   printf(
1608 "        constraints.  Generates a constrained Delaunay triangulation (CDT)\n"
1609 );
1610   printf(
1611 "        fitting the input; or, if -s, -q, -a, or -u is used, a conforming\n");
1612   printf(
1613 "        constrained Delaunay triangulation (CCDT).  If you want a truly\n");
1614   printf(
1615 "        Delaunay (not just constrained Delaunay) triangulation, use -D as\n");
1616   printf(
1617 "        well.  When -p is not used, Triangle reads a .node file by default.\n"
1618 );
1619   printf(
1620 "    -r  Refines a previously generated mesh.  The mesh is read from a .node\n"
1621 );
1622   printf(
1623 "        file and an .ele file.  If -p is also used, a .poly file is read\n");
1624   printf(
1625 "        and used to constrain segments in the mesh.  If -a is also used\n");
1626   printf(
1627 "        (with no number following), an .area file is read and used to\n");
1628   printf(
1629 "        impose area constraints on the mesh.  Further details on refinement\n"
1630 );
1631   printf("        appear below.\n");
1632   printf(
1633 "    -q  Quality mesh generation by Delaunay refinement (a hybrid of Paul\n");
1634   printf(
1635 "        Chew's and Jim Ruppert's algorithms).  Adds vertices to the mesh to\n"
1636 );
1637   printf(
1638 "        ensure that all angles are between 20 and 140 degrees.  An\n");
1639   printf(
1640 "        alternative bound on the minimum angle, replacing 20 degrees, may\n");
1641   printf(
1642 "        be specified after the `q'.  The specified angle may include a\n");
1643   printf(
1644 "        decimal point, but not exponential notation.  Note that a bound of\n"
1645 );
1646   printf(
1647 "        theta degrees on the smallest angle also implies a bound of\n");
1648   printf(
1649 "        (180 - 2 theta) on the largest angle.  If the minimum angle is 28.6\n"
1650 );
1651   printf(
1652 "        degrees or smaller, Triangle is mathematically guaranteed to\n");
1653   printf(
1654 "        terminate (assuming infinite precision arithmetic--Triangle may\n");
1655   printf(
1656 "        fail to terminate if you run out of precision).  In practice,\n");
1657   printf(
1658 "        Triangle often succeeds for minimum angles up to 34 degrees.  For\n");
1659   printf(
1660 "        some meshes, however, you might need to reduce the minimum angle to\n"
1661 );
1662   printf(
1663 "        avoid problems associated with insufficient floating-point\n");
1664   printf("        precision.\n");
1665   printf(
1666 "    -a  Imposes a maximum triangle area.  If a number follows the `a', no\n");
1667   printf(
1668 "        triangle is generated whose area is larger than that number.  If no\n"
1669 );
1670   printf(
1671 "        number is specified, an .area file (if -r is used) or .poly file\n");
1672   printf(
1673 "        (if -r is not used) specifies a set of maximum area constraints.\n");
1674   printf(
1675 "        An .area file contains a separate area constraint for each\n");
1676   printf(
1677 "        triangle, and is useful for refining a finite element mesh based on\n"
1678 );
1679   printf(
1680 "        a posteriori error estimates.  A .poly file can optionally contain\n"
1681 );
1682   printf(
1683 "        an area constraint for each segment-bounded region, thereby\n");
1684   printf(
1685 "        controlling triangle densities in a first triangulation of a PSLG.\n"
1686 );
1687   printf(
1688 "        You can impose both a fixed area constraint and a varying area\n");
1689   printf(
1690 "        constraint by invoking the -a switch twice, once with and once\n");
1691   printf(
1692 "        without a number following.  Each area specified may include a\n");
1693   printf("        decimal point.\n");
1694   printf(
1695 "    -u  Imposes a user-defined constraint on triangle size.  There are two\n"
1696 );
1697   printf(
1698 "        ways to use this feature.  One is to edit the triunsuitable()\n");
1699   printf(
1700 "        procedure in triangle.c to encode any constraint you like, then\n");
1701   printf(
1702 "        recompile Triangle.  The other is to compile triangle.c with the\n");
1703   printf(
1704 "        EXTERNAL_TEST symbol set (compiler switch -DEXTERNAL_TEST), then\n");
1705   printf(
1706 "        link Triangle with a separate object file that implements\n");
1707   printf(
1708 "        triunsuitable().  In either case, the -u switch causes the user-\n");
1709   printf("        defined test to be applied to every triangle.\n");
1710   printf(
1711 "    -A  Assigns an additional floating-point attribute to each triangle\n");
1712   printf(
1713 "        that identifies what segment-bounded region each triangle belongs\n");
1714   printf(
1715 "        to.  Attributes are assigned to regions by the .poly file.  If a\n");
1716   printf(
1717 "        region is not explicitly marked by the .poly file, triangles in\n");
1718   printf(
1719 "        that region are assigned an attribute of zero.  The -A switch has\n");
1720   printf(
1721 "        an effect only when the -p switch is used and the -r switch is not.\n"
1722 );
1723   printf(
1724 "    -c  Creates segments on the convex hull of the triangulation.  If you\n");
1725   printf(
1726 "        are triangulating a vertex set, this switch causes a .poly file to\n"
1727 );
1728   printf(
1729 "        be written, containing all edges of the convex hull.  If you are\n");
1730   printf(
1731 "        triangulating a PSLG, this switch specifies that the whole convex\n");
1732   printf(
1733 "        hull of the PSLG should be triangulated, regardless of what\n");
1734   printf(
1735 "        segments the PSLG has.  If you do not use this switch when\n");
1736   printf(
1737 "        triangulating a PSLG, Triangle assumes that you have identified the\n"
1738 );
1739   printf(
1740 "        region to be triangulated by surrounding it with segments of the\n");
1741   printf(
1742 "        input PSLG.  Beware:  if you are not careful, this switch can cause\n"
1743 );
1744   printf(
1745 "        the introduction of an extremely thin angle between a PSLG segment\n"
1746 );
1747   printf(
1748 "        and a convex hull segment, which can cause overrefinement (and\n");
1749   printf(
1750 "        possibly failure if Triangle runs out of precision).  If you are\n");
1751   printf(
1752 "        refining a mesh, the -c switch works differently:  it causes a\n");
1753   printf(
1754 "        .poly file to be written containing the boundary edges of the mesh\n"
1755 );
1756   printf("        (useful if no .poly file was read).\n");
1757   printf(
1758 "    -D  Conforming Delaunay triangulation:  use this switch if you want to\n"
1759 );
1760   printf(
1761 "        ensure that all the triangles in the mesh are Delaunay, and not\n");
1762   printf(
1763 "        merely constrained Delaunay; or if you want to ensure that all the\n"
1764 );
1765   printf(
1766 "        Voronoi vertices lie within the triangulation.  (Some finite volume\n"
1767 );
1768   printf(
1769 "        methods have this requirement.)  This switch invokes Ruppert's\n");
1770   printf(
1771 "        original algorithm, which splits every subsegment whose diametral\n");
1772   printf(
1773 "        circle is encroached.  It usually increases the number of vertices\n"
1774 );
1775   printf("        and triangles.\n");
1776   printf(
1777 "    -j  Jettisons vertices that are not part of the final triangulation\n");
1778   printf(
1779 "        from the output .node file.  By default, Triangle copies all\n");
1780   printf(
1781 "        vertices in the input .node file to the output .node file, in the\n");
1782   printf(
1783 "        same order, so their indices do not change.  The -j switch prevents\n"
1784 );
1785   printf(
1786 "        duplicated input vertices, or vertices `eaten' by holes, from\n");
1787   printf(
1788 "        appearing in the output .node file.  Thus, if two input vertices\n");
1789   printf(
1790 "        have exactly the same coordinates, only the first appears in the\n");
1791   printf(
1792 "        output.  If any vertices are jettisoned, the vertex numbering in\n");
1793   printf(
1794 "        the output .node file differs from that of the input .node file.\n");
1795   printf(
1796 "    -e  Outputs (to an .edge file) a list of edges of the triangulation.\n");
1797   printf(
1798 "    -v  Outputs the Voronoi diagram associated with the triangulation.\n");
1799   printf(
1800 "        Does not attempt to detect degeneracies, so some Voronoi vertices\n");
1801   printf(
1802 "        may be duplicated.  See the discussion of Voronoi diagrams below.\n");
1803   printf(
1804 "    -n  Outputs (to a .neigh file) a list of triangles neighboring each\n");
1805   printf("        triangle.\n");
1806   printf(
1807 "    -g  Outputs the mesh to an Object File Format (.off) file, suitable for\n"
1808 );
1809   printf("        viewing with the Geometry Center's Geomview package.\n");
1810   printf(
1811 "    -B  No boundary markers in the output .node, .poly, and .edge output\n");
1812   printf(
1813 "        files.  See the detailed discussion of boundary markers below.\n");
1814   printf(
1815 "    -P  No output .poly file.  Saves disk space, but you lose the ability\n");
1816   printf(
1817 "        to maintain constraining segments on later refinements of the mesh.\n"
1818 );
1819   printf("    -N  No output .node file.\n");
1820   printf("    -E  No output .ele file.\n");
1821   printf(
1822 "    -I  No iteration numbers.  Suppresses the output of .node and .poly\n");
1823   printf(
1824 "        files, so your input files won't be overwritten.  (If your input is\n"
1825 );
1826   printf(
1827 "        a .poly file only, a .node file is written.)  Cannot be used with\n");
1828   printf(
1829 "        the -r switch, because that would overwrite your input .ele file.\n");
1830   printf(
1831 "        Shouldn't be used with the -q, -a, -u, or -s switch if you are\n");
1832   printf(
1833 "        using a .node file for input, because no .node file is written, so\n"
1834 );
1835   printf("        there is no record of any added Steiner points.\n");
1836   printf("    -O  No holes.  Ignores the holes in the .poly file.\n");
1837   printf(
1838 "    -X  No exact arithmetic.  Normally, Triangle uses exact floating-point\n"
1839 );
1840   printf(
1841 "        arithmetic for certain tests if it thinks the inexact tests are not\n"
1842 );
1843   printf(
1844 "        accurate enough.  Exact arithmetic ensures the robustness of the\n");
1845   printf(
1846 "        triangulation algorithms, despite floating-point roundoff error.\n");
1847   printf(
1848 "        Disabling exact arithmetic with the -X switch causes a small\n");
1849   printf(
1850 "        improvement in speed and creates the possibility that Triangle will\n"
1851 );
1852   printf("        fail to produce a valid mesh.  Not recommended.\n");
1853   printf(
1854 "    -z  Numbers all items starting from zero (rather than one).  Note that\n"
1855 );
1856   printf(
1857 "        this switch is normally overridden by the value used to number the\n"
1858 );
1859   printf(
1860 "        first vertex of the input .node or .poly file.  However, this\n");
1861   printf(
1862 "        switch is useful when calling Triangle from another program.\n");
1863   printf(
1864 "    -o2 Generates second-order subparametric elements with six nodes each.\n"
1865 );
1866   printf(
1867 "    -Y  No new vertices on the boundary.  This switch is useful when the\n");
1868   printf(
1869 "        mesh boundary must be preserved so that it conforms to some\n");
1870   printf(
1871 "        adjacent mesh.  Be forewarned that you will probably sacrifice much\n"
1872 );
1873   printf(
1874 "        of the quality of the mesh; Triangle will try, but the resulting\n");
1875   printf(
1876 "        mesh may contain poorly shaped triangles.  Works well if all the\n");
1877   printf(
1878 "        boundary vertices are closely spaced.  Specify this switch twice\n");
1879   printf(
1880 "        (`-YY') to prevent all segment splitting, including internal\n");
1881   printf("        boundaries.\n");
1882   printf(
1883 "    -S  Specifies the maximum number of Steiner points (vertices that are\n");
1884   printf(
1885 "        not in the input, but are added to meet the constraints on minimum\n"
1886 );
1887   printf(
1888 "        angle and maximum area).  The default is to allow an unlimited\n");
1889   printf(
1890 "        number.  If you specify this switch with no number after it,\n");
1891   printf(
1892 "        the limit is set to zero.  Triangle always adds vertices at segment\n"
1893 );
1894   printf(
1895 "        intersections, even if it needs to use more vertices than the limit\n"
1896 );
1897   printf(
1898 "        you set.  When Triangle inserts segments by splitting (-s), it\n");
1899   printf(
1900 "        always adds enough vertices to ensure that all the segments of the\n"
1901 );
1902   printf("        PLSG are recovered, ignoring the limit if necessary.\n");
1903   printf(
1904 "    -i  Uses an incremental rather than a divide-and-conquer algorithm to\n");
1905   printf(
1906 "        construct a Delaunay triangulation.  Try it if the divide-and-\n");
1907   printf("        conquer algorithm fails.\n");
1908   printf(
1909 "    -F  Uses Steven Fortune's sweepline algorithm to construct a Delaunay\n");
1910   printf(
1911 "        triangulation.  Warning:  does not use exact arithmetic for all\n");
1912   printf("        calculations.  An exact result is not guaranteed.\n");
1913   printf(
1914 "    -l  Uses only vertical cuts in the divide-and-conquer algorithm.  By\n");
1915   printf(
1916 "        default, Triangle alternates between vertical and horizontal cuts,\n"
1917 );
1918   printf(
1919 "        which usually improve the speed except with vertex sets that are\n");
1920   printf(
1921 "        small or short and wide.  This switch is primarily of theoretical\n");
1922   printf("        interest.\n");
1923   printf(
1924 "    -s  Specifies that segments should be forced into the triangulation by\n"
1925 );
1926   printf(
1927 "        recursively splitting them at their midpoints, rather than by\n");
1928   printf(
1929 "        generating a constrained Delaunay triangulation.  Segment splitting\n"
1930 );
1931   printf(
1932 "        is true to Ruppert's original algorithm, but can create needlessly\n"
1933 );
1934   printf(
1935 "        small triangles.  This switch is primarily of theoretical interest.\n"
1936 );
1937   printf(
1938 "    -C  Check the consistency of the final mesh.  Uses exact arithmetic for\n"
1939 );
1940   printf(
1941 "        checking, even if the -X switch is used.  Useful if you suspect\n");
1942   printf("        Triangle is buggy.\n");
1943   printf(
1944 "    -Q  Quiet:  Suppresses all explanation of what Triangle is doing,\n");
1945   printf("        unless an error occurs.\n");
1946   printf(
1947 "    -V  Verbose:  Gives detailed information about what Triangle is doing.\n"
1948 );
1949   printf(
1950 "        Add more `V's for increasing amount of detail.  `-V' is most\n");
1951   printf(
1952 "        useful; itgives information on algorithmic progress and much more\n");
1953   printf(
1954 "        detailed statistics.  `-VV' gives vertex-by-vertex details, and\n");
1955   printf(
1956 "        prints so much that Triangle runs much more slowly.  `-VVVV' gives\n"
1957 );
1958   printf("        information only a debugger could love.\n");
1959   printf("    -h  Help:  Displays these instructions.\n");
1960   printf("\n");
1961   printf("Definitions:\n");
1962   printf("\n");
1963   printf(
1964 "  A Delaunay triangulation of a vertex set is a triangulation whose\n");
1965   printf(
1966 "  vertices are the vertex set, that covers the convex hull of the vertex\n");
1967   printf(
1968 "  set.  A Delaunay triangulation has the property that no vertex lies\n");
1969   printf(
1970 "  inside the circumscribing circle (circle that passes through all three\n");
1971   printf("  vertices) of any triangle in the triangulation.\n\n");
1972   printf(
1973 "  A Voronoi diagram of a vertex set is a subdivision of the plane into\n");
1974   printf(
1975 "  polygonal cells (some of which may be unbounded, meaning infinitely\n");
1976   printf(
1977 "  large), where each cell is the set of points in the plane that are closer\n"
1978 );
1979   printf(
1980 "  to some input vertex than to any other input vertex.  The Voronoi diagram\n"
1981 );
1982   printf("  is a geometric dual of the Delaunay triangulation.\n\n");
1983   printf(
1984 "  A Planar Straight Line Graph (PSLG) is a set of vertices and segments.\n");
1985   printf(
1986 "  Segments are simply edges, whose endpoints are all vertices in the PSLG.\n"
1987 );
1988   printf(
1989 "  Segments may intersect each other only at their endpoints.  The file\n");
1990   printf("  format for PSLGs (.poly files) is described below.\n\n");
1991   printf(
1992 "  A constrained Delaunay triangulation (CDT) of a PSLG is similar to a\n");
1993   printf(
1994 "  Delaunay triangulation, but each PSLG segment is present as a single edge\n"
1995 );
1996   printf(
1997 "  of the CDT.  (A constrained Delaunay triangulation is not truly a\n");
1998   printf(
1999 "  Delaunay triangulation, because some of its triangles might not be\n");
2000   printf(
2001 "  Delaunay.)  By definition, a CDT does not have any vertices other than\n");
2002   printf(
2003 "  those specified in the input PSLG.  Depending on context, a CDT might\n");
2004   printf(
2005 "  cover the convex hull of the PSLG, or it might cover only a segment-\n");
2006   printf("  bounded region (e.g. a polygon).\n\n");
2007   printf(
2008 "  A conforming Delaunay triangulation of a PSLG is a triangulation in which\n"
2009 );
2010   printf(
2011 "  each triangle is truly Delaunay, and each PSLG segment is represented by\n"
2012 );
2013   printf(
2014 "  a linear contiguous sequence of edges of the triangulation.  New vertices\n"
2015 );
2016   printf(
2017 "  (not part of the PSLG) may appear, and each input segment may have been\n");
2018   printf(
2019 "  subdivided into shorter edges (subsegments) by these additional vertices.\n"
2020 );
2021   printf(
2022 "  The new vertices are frequently necessary to maintain the Delaunay\n");
2023   printf("  property while ensuring that every segment is represented.\n\n");
2024   printf(
2025 "  A conforming constrained Delaunay triangulation (CCDT) of a PSLG is a\n");
2026   printf(
2027 "  triangulation of a PSLG whose triangles are constrained Delaunay.  New\n");
2028   printf("  vertices may appear, and input segments may be subdivided into\n");
2029   printf(
2030 "  subsegments, but not to guarantee that segments are respected; rather, to\n"
2031 );
2032   printf(
2033 "  improve the quality of the triangles.  The high-quality meshes produced\n");
2034   printf(
2035 "  by the -q switch are usually CCDTs, but can be made conforming Delaunay\n");
2036   printf("  with the -D switch.\n\n");
2037   printf("File Formats:\n\n");
2038   printf(
2039 "  All files may contain comments prefixed by the character '#'.  Vertices,\n"
2040 );
2041   printf(
2042 "  triangles, edges, holes, and maximum area constraints must be numbered\n");
2043   printf(
2044 "  consecutively, starting from either 1 or 0.  Whichever you choose, all\n");
2045   printf(
2046 "  input files must be consistent; if the vertices are numbered from 1, so\n");
2047   printf(
2048 "  must be all other objects.  Triangle automatically detects your choice\n");
2049   printf(
2050 "  while reading the .node (or .poly) file.  (When calling Triangle from\n");
2051   printf(
2052 "  another program, use the -z switch if you wish to number objects from\n");
2053   printf("  zero.)  Examples of these file formats are given below.\n\n");
2054   printf("  .node files:\n");
2055   printf(
2056 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2057 );
2058   printf(
2059 "                                           <# of boundary markers (0 or 1)>\n"
2060 );
2061   printf(
2062 "    Remaining lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2063   printf("\n");
2064   printf(
2065 "    The attributes, which are typically floating-point values of physical\n");
2066   printf(
2067 "    quantities (such as mass or conductivity) associated with the nodes of\n"
2068 );
2069   printf(
2070 "    a finite element mesh, are copied unchanged to the output mesh.  If -q,\n"
2071 );
2072   printf(
2073 "    -a, -u, -D, or -s is selected, each new Steiner point added to the mesh\n"
2074 );
2075   printf("    has attributes assigned to it by linear interpolation.\n\n");
2076   printf(
2077 "    If the fourth entry of the first line is `1', the last column of the\n");
2078   printf(
2079 "    remainder of the file is assumed to contain boundary markers.  Boundary\n"
2080 );
2081   printf(
2082 "    markers are used to identify boundary vertices and vertices resting on\n"
2083 );
2084   printf(
2085 "    PSLG segments; a complete description appears in a section below.  The\n"
2086 );
2087   printf(
2088 "    .node file produced by Triangle contains boundary markers in the last\n");
2089   printf("    column unless they are suppressed by the -B switch.\n\n");
2090   printf("  .ele files:\n");
2091   printf(
2092 "    First line:  <# of triangles> <nodes per triangle> <# of attributes>\n");
2093   printf(
2094 "    Remaining lines:  <triangle #> <node> <node> <node> ... [attributes]\n");
2095   printf("\n");
2096   printf(
2097 "    Nodes are indices into the corresponding .node file.  The first three\n");
2098   printf(
2099 "    nodes are the corner vertices, and are listed in counterclockwise order\n"
2100 );
2101   printf(
2102 "    around each triangle.  (The remaining nodes, if any, depend on the type\n"
2103 );
2104   printf("    of finite element used.)\n\n");
2105   printf(
2106 "    The attributes are just like those of .node files.  Because there is no\n"
2107 );
2108   printf(
2109 "    simple mapping from input to output triangles, Triangle attempts to\n");
2110   printf(
2111 "    interpolate attributes, and may cause a lot of diffusion of attributes\n"
2112 );
2113   printf(
2114 "    among nearby triangles as the triangulation is refined.  Attributes do\n"
2115 );
2116   printf("    not diffuse across segments, so attributes used to identify\n");
2117   printf("    segment-bounded regions remain intact.\n\n");
2118   printf(
2119 "    In .ele files produced by Triangle, each triangular element has three\n");
2120   printf(
2121 "    nodes (vertices) unless the -o2 switch is used, in which case\n");
2122   printf(
2123 "    subparametric quadratic elements with six nodes each are generated.\n");
2124   printf(
2125 "    The first three nodes are the corners in counterclockwise order, and\n");
2126   printf(
2127 "    the fourth, fifth, and sixth nodes lie on the midpoints of the edges\n");
2128   printf(
2129 "    opposite the first, second, and third vertices, respectively.\n");
2130   printf("\n");
2131   printf("  .poly files:\n");
2132   printf(
2133 "    First line:  <# of vertices> <dimension (must be 2)> <# of attributes>\n"
2134 );
2135   printf(
2136 "                                           <# of boundary markers (0 or 1)>\n"
2137 );
2138   printf(
2139 "    Following lines:  <vertex #> <x> <y> [attributes] [boundary marker]\n");
2140   printf("    One line:  <# of segments> <# of boundary markers (0 or 1)>\n");
2141   printf(
2142 "    Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]\n");
2143   printf("    One line:  <# of holes>\n");
2144   printf("    Following lines:  <hole #> <x> <y>\n");
2145   printf(
2146 "    Optional line:  <# of regional attributes and/or area constraints>\n");
2147   printf(
2148 "    Optional following lines:  <region #> <x> <y> <attribute> <max area>\n");
2149   printf("\n");
2150   printf(
2151 "    A .poly file represents a PSLG, as well as some additional information.\n"
2152 );
2153   printf(
2154 "    The first section lists all the vertices, and is identical to the\n");
2155   printf(
2156 "    format of .node files.  <# of vertices> may be set to zero to indicate\n"
2157 );
2158   printf(
2159 "    that the vertices are listed in a separate .node file; .poly files\n");
2160   printf(
2161 "    produced by Triangle always have this format.  A vertex set represented\n"
2162 );
2163   printf(
2164 "    this way has the advantage that it may easily be triangulated with or\n");
2165   printf(
2166 "    without segments (depending on whether the -p switch is invoked).\n");
2167   printf("\n");
2168   printf(
2169 "    The second section lists the segments.  Segments are edges whose\n");
2170   printf(
2171 "    presence in the triangulation is enforced.  (Depending on the choice of\n"
2172 );
2173   printf(
2174 "    switches, segment might be subdivided into smaller edges).  Each\n");
2175   printf(
2176 "    segment is specified by listing the indices of its two endpoints.  This\n"
2177 );
2178   printf(
2179 "    means that you must include its endpoints in the vertex list.  Each\n");
2180   printf("    segment, like each point, may have a boundary marker.\n\n");
2181   printf(
2182 "    If -q, -a, -u, and -s are not selected, Triangle produces a constrained\n"
2183 );
2184   printf(
2185 "    Delaunay triangulation (CDT), in which each segment appears as a single\n"
2186 );
2187   printf(
2188 "    edge in the triangulation.  If -q, -a, -u, or -s is selected, Triangle\n"
2189 );
2190   printf(
2191 "    produces a conforming constrained Delaunay triangulation (CCDT), in\n");
2192   printf(
2193 "    which segments may be subdivided into smaller edges.  If -D is\n");
2194   printf(
2195 "    selected, Triangle produces a conforming Delaunay triangulation, so\n");
2196   printf(
2197 "    that every triangle is Delaunay, and not just constrained Delaunay.\n");
2198   printf("\n");
2199   printf(
2200 "    The third section lists holes (and concavities, if -c is selected) in\n");
2201   printf(
2202 "    the triangulation.  Holes are specified by identifying a point inside\n");
2203   printf(
2204 "    each hole.  After the triangulation is formed, Triangle creates holes\n");
2205   printf(
2206 "    by eating triangles, spreading out from each hole point until its\n");
2207   printf(
2208 "    progress is blocked by segments in the PSLG.  You must be careful to\n");
2209   printf(
2210 "    enclose each hole in segments, or your whole triangulation might be\n");
2211   printf(
2212 "    eaten away.  If the two triangles abutting a segment are eaten, the\n");
2213   printf(
2214 "    segment itself is also eaten.  Do not place a hole directly on a\n");
2215   printf("    segment; if you do, Triangle chooses one side of the segment\n");
2216   printf("    arbitrarily.\n\n");
2217   printf(
2218 "    The optional fourth section lists regional attributes (to be assigned\n");
2219   printf(
2220 "    to all triangles in a region) and regional constraints on the maximum\n");
2221   printf(
2222 "    triangle area.  Triangle reads this section only if the -A switch is\n");
2223   printf(
2224 "    used or the -a switch is used without a number following it, and the -r\n"
2225 );
2226   printf(
2227 "    switch is not used.  Regional attributes and area constraints are\n");
2228   printf(
2229 "    propagated in the same manner as holes:  you specify a point for each\n");
2230   printf(
2231 "    attribute and/or constraint, and the attribute and/or constraint\n");
2232   printf(
2233 "    affects the whole region (bounded by segments) containing the point.\n");
2234   printf(
2235 "    If two values are written on a line after the x and y coordinate, the\n");
2236   printf(
2237 "    first such value is assumed to be a regional attribute (but is only\n");
2238   printf(
2239 "    applied if the -A switch is selected), and the second value is assumed\n"
2240 );
2241   printf(
2242 "    to be a regional area constraint (but is only applied if the -a switch\n"
2243 );
2244   printf(
2245 "    is selected).  You may specify just one value after the coordinates,\n");
2246   printf(
2247 "    which can serve as both an attribute and an area constraint, depending\n"
2248 );
2249   printf(
2250 "    on the choice of switches.  If you are using the -A and -a switches\n");
2251   printf(
2252 "    simultaneously and wish to assign an attribute to some region without\n");
2253   printf("    imposing an area constraint, use a negative maximum area.\n\n");
2254   printf(
2255 "    When a triangulation is created from a .poly file, you must either\n");
2256   printf(
2257 "    enclose the entire region to be triangulated in PSLG segments, or\n");
2258   printf(
2259 "    use the -c switch, which automatically creates extra segments that\n");
2260   printf(
2261 "    enclose the convex hull of the PSLG.  If you do not use the -c switch,\n"
2262 );
2263   printf(
2264 "    Triangle eats all triangles that are not enclosed by segments; if you\n");
2265   printf(
2266 "    are not careful, your whole triangulation may be eaten away.  If you do\n"
2267 );
2268   printf(
2269 "    use the -c switch, you can still produce concavities by the appropriate\n"
2270 );
2271   printf(
2272 "    placement of holes just inside the boundary of the convex hull.\n");
2273   printf("\n");
2274   printf(
2275 "    An ideal PSLG has no intersecting segments, nor any vertices that lie\n");
2276   printf(
2277 "    upon segments (except, of course, the endpoints of each segment).  You\n"
2278 );
2279   printf(
2280 "    aren't required to make your .poly files ideal, but you should be aware\n"
2281 );
2282   printf(
2283 "    of what can go wrong.  Segment intersections are relatively safe--\n");
2284   printf(
2285 "    Triangle calculates the intersection points for you and adds them to\n");
2286   printf(
2287 "    the triangulation--as long as your machine's floating-point precision\n");
2288   printf(
2289 "    doesn't become a problem.  You are tempting the fates if you have three\n"
2290 );
2291   printf(
2292 "    segments that cross at the same location, and expect Triangle to figure\n"
2293 );
2294   printf(
2295 "    out where the intersection point is.  Thanks to floating-point roundoff\n"
2296 );
2297   printf(
2298 "    error, Triangle will probably decide that the three segments intersect\n"
2299 );
2300   printf(
2301 "    at three different points, and you will find a minuscule triangle in\n");
2302   printf(
2303 "    your output--unless Triangle tries to refine the tiny triangle, uses\n");
2304   printf(
2305 "    up the last bit of machine precision, and fails to terminate at all.\n");
2306   printf(
2307 "    You're better off putting the intersection point in the input files,\n");
2308   printf(
2309 "    and manually breaking up each segment into two.  Similarly, if you\n");
2310   printf(
2311 "    place a vertex at the middle of a segment, and hope that Triangle will\n"
2312 );
2313   printf(
2314 "    break up the segment at that vertex, you might get lucky.  On the other\n"
2315 );
2316   printf(
2317 "    hand, Triangle might decide that the vertex doesn't lie precisely on\n");
2318   printf(
2319 "    the segment, and you'll have a needle-sharp triangle in your output--or\n"
2320 );
2321   printf("    a lot of tiny triangles if you're generating a quality mesh.\n");
2322   printf("\n");
2323   printf(
2324 "    When Triangle reads a .poly file, it also writes a .poly file, which\n");
2325   printf(
2326 "    includes all the subsegments--the edges that are parts of input\n");
2327   printf(
2328 "    segments.  If the -c switch is used, the output .poly file also\n");
2329   printf(
2330 "    includes all of the edges on the convex hull.  Hence, the output .poly\n"
2331 );
2332   printf(
2333 "    file is useful for finding edges associated with input segments and for\n"
2334 );
2335   printf(
2336 "    setting boundary conditions in finite element simulations.  Moreover,\n");
2337   printf(
2338 "    you will need the output .poly file if you plan to refine the output\n");
2339   printf(
2340 "    mesh, and don't want segments to be missing in later triangulations.\n");
2341   printf("\n");
2342   printf("  .area files:\n");
2343   printf("    First line:  <# of triangles>\n");
2344   printf("    Following lines:  <triangle #> <maximum area>\n");
2345   printf("\n");
2346   printf(
2347 "    An .area file associates with each triangle a maximum area that is used\n"
2348 );
2349   printf(
2350 "    for mesh refinement.  As with other file formats, every triangle must\n");
2351   printf(
2352 "    be represented, and the triangles must be numbered consecutively.  A\n");
2353   printf(
2354 "    triangle may be left unconstrained by assigning it a negative maximum\n");
2355   printf("    area.\n\n");
2356   printf("  .edge files:\n");
2357   printf("    First line:  <# of edges> <# of boundary markers (0 or 1)>\n");
2358   printf(
2359 "    Following lines:  <edge #> <endpoint> <endpoint> [boundary marker]\n");
2360   printf("\n");
2361   printf(
2362 "    Endpoints are indices into the corresponding .node file.  Triangle can\n"
2363 );
2364   printf(
2365 "    produce .edge files (use the -e switch), but cannot read them.  The\n");
2366   printf(
2367 "    optional column of boundary markers is suppressed by the -B switch.\n");
2368   printf("\n");
2369   printf(
2370 "    In Voronoi diagrams, one also finds a special kind of edge that is an\n");
2371   printf(
2372 "    infinite ray with only one endpoint.  For these edges, a different\n");
2373   printf("    format is used:\n\n");
2374   printf("        <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
2375   printf(
2376 "    The `direction' is a floating-point vector that indicates the direction\n"
2377 );
2378   printf("    of the infinite ray.\n\n");
2379   printf("  .neigh files:\n");
2380   printf(
2381 "    First line:  <# of triangles> <# of neighbors per triangle (always 3)>\n"
2382 );
2383   printf(
2384 "    Following lines:  <triangle #> <neighbor> <neighbor> <neighbor>\n");
2385   printf("\n");
2386   printf(
2387 "    Neighbors are indices into the corresponding .ele file.  An index of -1\n"
2388 );
2389   printf(
2390 "    indicates no neighbor (because the triangle is on an exterior\n");
2391   printf(
2392 "    boundary).  The first neighbor of triangle i is opposite the first\n");
2393   printf("    corner of triangle i, and so on.\n\n");
2394   printf(
2395 "    Triangle can produce .neigh files (use the -n switch), but cannot read\n"
2396 );
2397   printf("    them.\n\n");
2398   printf("Boundary Markers:\n\n");
2399   printf(
2400 "  Boundary markers are tags used mainly to identify which output vertices\n");
2401   printf(
2402 "  and edges are associated with which PSLG segment, and to identify which\n");
2403   printf(
2404 "  vertices and edges occur on a boundary of the triangulation.  A common\n");
2405   printf(
2406 "  use is to determine where boundary conditions should be applied to a\n");
2407   printf(
2408 "  finite element mesh.  You can prevent boundary markers from being written\n"
2409 );
2410   printf("  into files produced by Triangle by using the -B switch.\n\n");
2411   printf(
2412 "  The boundary marker associated with each segment in an output .poly file\n"
2413 );
2414   printf("  and each edge in an output .edge file is chosen as follows:\n");
2415   printf(
2416 "    - If an output edge is part or all of a PSLG segment with a nonzero\n");
2417   printf(
2418 "      boundary marker, then the edge is assigned the same marker.\n");
2419   printf(
2420 "    - Otherwise, if the edge lies on a boundary of the triangulation\n");
2421   printf(
2422 "      (even the boundary of a hole), then the edge is assigned the marker\n");
2423   printf("      one (1).\n");
2424   printf("    - Otherwise, the edge is assigned the marker zero (0).\n");
2425   printf(
2426 "  The boundary marker associated with each vertex in an output .node file\n");
2427   printf("  is chosen as follows:\n");
2428   printf(
2429 "    - If a vertex is assigned a nonzero boundary marker in the input file,\n"
2430 );
2431   printf(
2432 "      then it is assigned the same marker in the output .node file.\n");
2433   printf(
2434 "    - Otherwise, if the vertex lies on a PSLG segment (even if it is an\n");
2435   printf(
2436 "      endpoint of the segment) with a nonzero boundary marker, then the\n");
2437   printf(
2438 "      vertex is assigned the same marker.  If the vertex lies on several\n");
2439   printf("      such segments, one of the markers is chosen arbitrarily.\n");
2440   printf(
2441 "    - Otherwise, if the vertex occurs on a boundary of the triangulation,\n");
2442   printf("      then the vertex is assigned the marker one (1).\n");
2443   printf("    - Otherwise, the vertex is assigned the marker zero (0).\n");
2444   printf("\n");
2445   printf(
2446 "  If you want Triangle to determine for you which vertices and edges are on\n"
2447 );
2448   printf(
2449 "  the boundary, assign them the boundary marker zero (or use no markers at\n"
2450 );
2451   printf(
2452 "  all) in your input files.  In the output files, all boundary vertices,\n");
2453   printf("  edges, and segments will be assigned the value one.\n\n");
2454   printf("Triangulation Iteration Numbers:\n\n");
2455   printf(
2456 "  Because Triangle can read and refine its own triangulations, input\n");
2457   printf(
2458 "  and output files have iteration numbers.  For instance, Triangle might\n");
2459   printf(
2460 "  read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
2461   printf(
2462 "  triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
2463   printf("  mesh.4.poly.  Files with no iteration number are treated as if\n");
2464   printf(
2465 "  their iteration number is zero; hence, Triangle might read the file\n");
2466   printf(
2467 "  points.node, triangulate it, and produce the files points.1.node and\n");
2468   printf("  points.1.ele.\n\n");
2469   printf(
2470 "  Iteration numbers allow you to create a sequence of successively finer\n");
2471   printf(
2472 "  meshes suitable for multigrid methods.  They also allow you to produce a\n"
2473 );
2474   printf(
2475 "  sequence of meshes using error estimate-driven mesh refinement.\n");
2476   printf("\n");
2477   printf(
2478 "  If you're not using refinement or quality meshing, and you don't like\n");
2479   printf(
2480 "  iteration numbers, use the -I switch to disable them.  This switch also\n");
2481   printf(
2482 "  disables output of .node and .poly files to prevent your input files from\n"
2483 );
2484   printf(
2485 "  being overwritten.  (If the input is a .poly file that contains its own\n");
2486   printf(
2487 "  points, a .node file is written.  This can be quite convenient for\n");
2488   printf("  computing CDTs or quality meshes.)\n\n");
2489   printf("Examples of How to Use Triangle:\n\n");
2490   printf(
2491 "  `triangle dots' reads vertices from dots.node, and writes their Delaunay\n"
2492 );
2493   printf(
2494 "  triangulation to dots.1.node and dots.1.ele.  (dots.1.node is identical\n");
2495   printf(
2496 "  to dots.node.)  `triangle -I dots' writes the triangulation to dots.ele\n");
2497   printf(
2498 "  instead.  (No additional .node file is needed, so none is written.)\n");
2499   printf("\n");
2500   printf(
2501 "  `triangle -pe object.1' reads a PSLG from object.1.poly (and possibly\n");
2502   printf(
2503 "  object.1.node, if the vertices are omitted from object.1.poly) and writes\n"
2504 );
2505   printf(
2506 "  its constrained Delaunay triangulation to object.2.node and object.2.ele.\n"
2507 );
2508   printf(
2509 "  The segments are copied to object.2.poly, and all edges are written to\n");
2510   printf("  object.2.edge.\n\n");
2511   printf(
2512 "  `triangle -pq31.5a.1 object' reads a PSLG from object.poly (and possibly\n"
2513 );
2514   printf(
2515 "  object.node), generates a mesh whose angles are all between 31.5 and 117\n"
2516 );
2517   printf(
2518 "  degrees and whose triangles all have areas of 0.1 or less, and writes the\n"
2519 );
2520   printf(
2521 "  mesh to object.1.node and object.1.ele.  Each segment may be broken up\n");
2522   printf("  into multiple subsegments; these are written to object.1.poly.\n");
2523   printf("\n");
2524   printf(
2525 "  Here is a sample file `box.poly' describing a square with a square hole:\n"
2526 );
2527   printf("\n");
2528   printf(
2529 "    # A box with eight vertices in 2D, no attributes, one boundary marker.\n"
2530 );
2531   printf("    8 2 0 1\n");
2532   printf("     # Outer box has these vertices:\n");
2533   printf("     1   0 0   0\n");
2534   printf("     2   0 3   0\n");
2535   printf("     3   3 0   0\n");
2536   printf("     4   3 3   33     # A special marker for this vertex.\n");
2537   printf("     # Inner square has these vertices:\n");
2538   printf("     5   1 1   0\n");
2539   printf("     6   1 2   0\n");
2540   printf("     7   2 1   0\n");
2541   printf("     8   2 2   0\n");
2542   printf("    # Five segments with boundary markers.\n");
2543   printf("    5 1\n");
2544   printf("     1   1 2   5      # Left side of outer box.\n");
2545   printf("     # Square hole has these segments:\n");
2546   printf("     2   5 7   0\n");
2547   printf("     3   7 8   0\n");
2548   printf("     4   8 6   10\n");
2549   printf("     5   6 5   0\n");
2550   printf("    # One hole in the middle of the inner square.\n");
2551   printf("    1\n");
2552   printf("     1   1.5 1.5\n");
2553   printf("\n");
2554   printf(
2555 "  Note that some segments are missing from the outer square, so you must\n");
2556   printf(
2557 "  use the `-c' switch.  After `triangle -pqc box.poly', here is the output\n"
2558 );
2559   printf(
2560 "  file `box.1.node', with twelve vertices.  The last four vertices were\n");
2561   printf(
2562 "  added to meet the angle constraint.  Vertices 1, 2, and 9 have markers\n");
2563   printf(
2564 "  from segment 1.  Vertices 6 and 8 have markers from segment 4.  All the\n");
2565   printf(
2566 "  other vertices but 4 have been marked to indicate that they lie on a\n");
2567   printf("  boundary.\n\n");
2568   printf("    12  2  0  1\n");
2569   printf("       1    0   0      5\n");
2570   printf("       2    0   3      5\n");
2571   printf("       3    3   0      1\n");
2572   printf("       4    3   3     33\n");
2573   printf("       5    1   1      1\n");
2574   printf("       6    1   2     10\n");
2575   printf("       7    2   1      1\n");
2576   printf("       8    2   2     10\n");
2577   printf("       9    0   1.5    5\n");
2578   printf("      10    1.5   0    1\n");
2579   printf("      11    3   1.5    1\n");
2580   printf("      12    1.5   3    1\n");
2581   printf("    # Generated by triangle -pqc box.poly\n");
2582   printf("\n");
2583   printf("  Here is the output file `box.1.ele', with twelve triangles.\n");
2584   printf("\n");
2585   printf("    12  3  0\n");
2586   printf("       1     5   6   9\n");
2587   printf("       2    10   3   7\n");
2588   printf("       3     6   8  12\n");
2589   printf("       4     9   1   5\n");
2590   printf("       5     6   2   9\n");
2591   printf("       6     7   3  11\n");
2592   printf("       7    11   4   8\n");
2593   printf("       8     7   5  10\n");
2594   printf("       9    12   2   6\n");
2595   printf("      10     8   7  11\n");
2596   printf("      11     5   1  10\n");
2597   printf("      12     8   4  12\n");
2598   printf("    # Generated by triangle -pqc box.poly\n\n");
2599   printf(
2600 "  Here is the output file `box.1.poly'.  Note that segments have been added\n"
2601 );
2602   printf(
2603 "  to represent the convex hull, and some segments have been subdivided by\n");
2604   printf(
2605 "  newly added vertices.  Note also that <# of vertices> is set to zero to\n");
2606   printf("  indicate that the vertices should be read from the .node file.\n");
2607   printf("\n");
2608   printf("    0  2  0  1\n");
2609   printf("    12  1\n");
2610   printf("       1     1   9     5\n");
2611   printf("       2     5   7     1\n");
2612   printf("       3     8   7     1\n");
2613   printf("       4     6   8    10\n");
2614   printf("       5     5   6     1\n");
2615   printf("       6     3  10     1\n");
2616   printf("       7     4  11     1\n");
2617   printf("       8     2  12     1\n");
2618   printf("       9     9   2     5\n");
2619   printf("      10    10   1     1\n");
2620   printf("      11    11   3     1\n");
2621   printf("      12    12   4     1\n");
2622   printf("    1\n");
2623   printf("       1   1.5 1.5\n");
2624   printf("    # Generated by triangle -pqc box.poly\n");
2625   printf("\n");
2626   printf("Refinement and Area Constraints:\n");
2627   printf("\n");
2628   printf(
2629 "  The -r switch causes a mesh (.node and .ele files) to be read and\n");
2630   printf(
2631 "  refined.  If the -p switch is also used, a .poly file is read and used to\n"
2632 );
2633   printf(
2634 "  specify edges that are constrained and cannot be eliminated (although\n");
2635   printf(
2636 "  they can be subdivided into smaller edges) by the refinement process.\n");
2637   printf("\n");
2638   printf(
2639 "  When you refine a mesh, you generally want to impose tighter constraints.\n"
2640 );
2641   printf(
2642 "  One way to accomplish this is to use -q with a larger angle, or -a\n");
2643   printf(
2644 "  followed by a smaller area than you used to generate the mesh you are\n");
2645   printf(
2646 "  refining.  Another way to do this is to create an .area file, which\n");
2647   printf(
2648 "  specifies a maximum area for each triangle, and use the -a switch\n");
2649   printf(
2650 "  (without a number following).  Each triangle's area constraint is applied\n"
2651 );
2652   printf(
2653 "  to that triangle.  Area constraints tend to diffuse as the mesh is\n");
2654   printf(
2655 "  refined, so if there are large variations in area constraint between\n");
2656   printf(
2657 "  adjacent triangles, you may not get the results you want.  In that case,\n"
2658 );
2659   printf(
2660 "  consider instead using the -u switch and writing a C procedure that\n");
2661   printf("  determines which triangles are too large.\n\n");
2662   printf(
2663 "  If you are refining a mesh composed of linear (three-node) elements, the\n"
2664 );
2665   printf(
2666 "  output mesh contains all the nodes present in the input mesh, in the same\n"
2667 );
2668   printf(
2669 "  order, with new nodes added at the end of the .node file.  However, the\n");
2670   printf(
2671 "  refinement is not hierarchical: there is no guarantee that each output\n");
2672   printf(
2673 "  element is contained in a single input element.  Often, an output element\n"
2674 );
2675   printf(
2676 "  can overlap two or three input elements, and some input edges are not\n");
2677   printf(
2678 "  present in the output mesh.  Hence, a sequence of refined meshes forms a\n"
2679 );
2680   printf(
2681 "  hierarchy of nodes, but not a hierarchy of elements.  If you refine a\n");
2682   printf(
2683 "  mesh of higher-order elements, the hierarchical property applies only to\n"
2684 );
2685   printf(
2686 "  the nodes at the corners of an element; the midpoint nodes on each edge\n");
2687   printf("  are discarded before the mesh is refined.\n\n");
2688   printf(
2689 "  Maximum area constraints in .poly files operate differently from those in\n"
2690 );
2691   printf(
2692 "  .area files.  A maximum area in a .poly file applies to the whole\n");
2693   printf(
2694 "  (segment-bounded) region in which a point falls, whereas a maximum area\n");
2695   printf(
2696 "  in an .area file applies to only one triangle.  Area constraints in .poly\n"
2697 );
2698   printf(
2699 "  files are used only when a mesh is first generated, whereas area\n");
2700   printf(
2701 "  constraints in .area files are used only to refine an existing mesh, and\n"
2702 );
2703   printf(
2704 "  are typically based on a posteriori error estimates resulting from a\n");
2705   printf("  finite element simulation on that mesh.\n\n");
2706   printf(
2707 "  `triangle -rq25 object.1' reads object.1.node and object.1.ele, then\n");
2708   printf(
2709 "  refines the triangulation to enforce a 25 degree minimum angle, and then\n"
2710 );
2711   printf(
2712 "  writes the refined triangulation to object.2.node and object.2.ele.\n");
2713   printf("\n");
2714   printf(
2715 "  `triangle -rpaa6.2 z.3' reads z.3.node, z.3.ele, z.3.poly, and z.3.area.\n"
2716 );
2717   printf(
2718 "  After reconstructing the mesh and its subsegments, Triangle refines the\n");
2719   printf(
2720 "  mesh so that no triangle has area greater than 6.2, and furthermore the\n");
2721   printf(
2722 "  triangles satisfy the maximum area constraints in z.3.area.  No angle\n");
2723   printf(
2724 "  bound is imposed at all.  The output is written to z.4.node, z.4.ele, and\n"
2725 );
2726   printf("  z.4.poly.\n\n");
2727   printf(
2728 "  The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
2729   printf(
2730 "  x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
2731   printf("  suitable for multigrid.\n\n");
2732   printf("Convex Hulls and Mesh Boundaries:\n\n");
2733   printf(
2734 "  If the input is a vertex set (not a PSLG), Triangle produces its convex\n");
2735   printf(
2736 "  hull as a by-product in the output .poly file if you use the -c switch.\n");
2737   printf(
2738 "  There are faster algorithms for finding a two-dimensional convex hull\n");
2739   printf("  than triangulation, of course, but this one comes for free.\n\n");
2740   printf(
2741 "  If the input is an unconstrained mesh (you are using the -r switch but\n");
2742   printf(
2743 "  not the -p switch), Triangle produces a list of its boundary edges\n");
2744   printf(
2745 "  (including hole boundaries) as a by-product when you use the -c switch.\n");
2746   printf(
2747 "  If you also use the -p switch, the output .poly file contains all the\n");
2748   printf("  segments from the input .poly file as well.\n\n");
2749   printf("Voronoi Diagrams:\n\n");
2750   printf(
2751 "  The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
2752   printf(
2753 "  .v.edge.  For example, `triangle -v points' reads points.node, produces\n");
2754   printf(
2755 "  its Delaunay triangulation in points.1.node and points.1.ele, and\n");
2756   printf(
2757 "  produces its Voronoi diagram in points.1.v.node and points.1.v.edge.  The\n"
2758 );
2759   printf(
2760 "  .v.node file contains a list of all Voronoi vertices, and the .v.edge\n");
2761   printf(
2762 "  file contains a list of all Voronoi edges, some of which may be infinite\n"
2763 );
2764   printf(
2765 "  rays.  (The choice of filenames makes it easy to run the set of Voronoi\n");
2766   printf("  vertices through Triangle, if so desired.)\n\n");
2767   printf(
2768 "  This implementation does not use exact arithmetic to compute the Voronoi\n"
2769 );
2770   printf(
2771 "  vertices, and does not check whether neighboring vertices are identical.\n"
2772 );
2773   printf(
2774 "  Be forewarned that if the Delaunay triangulation is degenerate or\n");
2775   printf(
2776 "  near-degenerate, the Voronoi diagram may have duplicate vertices or\n");
2777   printf("  crossing edges.\n\n");
2778   printf(
2779 "  The result is a valid Voronoi diagram only if Triangle's output is a true\n"
2780 );
2781   printf(
2782 "  Delaunay triangulation.  The Voronoi output is usually meaningless (and\n");
2783   printf(
2784 "  may contain crossing edges and other pathology) if the output is a CDT or\n"
2785 );
2786   printf(
2787 "  CCDT, or if it has holes or concavities.  If the triangulated domain is\n");
2788   printf(
2789 "  convex and has no holes, you can use -D switch to force Triangle to\n");
2790   printf(
2791 "  construct a conforming Delaunay triangulation instead of a CCDT, so the\n");
2792   printf("  Voronoi diagram will be valid.\n\n");
2793   printf("Mesh Topology:\n\n");
2794   printf(
2795 "  You may wish to know which triangles are adjacent to a certain Delaunay\n");
2796   printf(
2797 "  edge in an .edge file, which Voronoi cells are adjacent to a certain\n");
2798   printf(
2799 "  Voronoi edge in a .v.edge file, or which Voronoi cells are adjacent to\n");
2800   printf(
2801 "  each other.  All of this information can be found by cross-referencing\n");
2802   printf(
2803 "  output files with the recollection that the Delaunay triangulation and\n");
2804   printf("  the Voronoi diagram are planar duals.\n\n");
2805   printf(
2806 "  Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
2807   printf(
2808 "  the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
2809   printf(
2810 "  wise from the Voronoi edge.  Triangle j of an .ele file is the dual of\n");
2811   printf(
2812 "  vertex j of the corresponding .v.node file.  Voronoi cell k is the dual\n");
2813   printf("  of vertex k of the corresponding .node file.\n\n");
2814   printf(
2815 "  Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
2816   printf(
2817 "  vertices of the corresponding Voronoi edge.  If the endpoints of a\n");
2818   printf(
2819 "  Voronoi edge are Voronoi vertices 2 and 6 respectively, then triangles 2\n"
2820 );
2821   printf(
2822 "  and 6 adjoin the left and right sides of the corresponding Delaunay edge,\n"
2823 );
2824   printf(
2825 "  respectively.  To find the Voronoi cells adjacent to a Voronoi edge, look\n"
2826 );
2827   printf(
2828 "  at the endpoints of the corresponding Delaunay edge.  If the endpoints of\n"
2829 );
2830   printf(
2831 "  a Delaunay edge are input vertices 7 and 12, then Voronoi cells 7 and 12\n"
2832 );
2833   printf(
2834 "  adjoin the right and left sides of the corresponding Voronoi edge,\n");
2835   printf(
2836 "  respectively.  To find which Voronoi cells are adjacent to each other,\n");
2837   printf("  just read the list of Delaunay edges.\n\n");
2838   printf(
2839 "  Triangle does not write a list of the edges adjoining each Voronoi cell,\n"
2840 );
2841   printf(
2842 "  but you can reconstructed it straightforwardly.  For instance, to find\n");
2843   printf(
2844 "  all the edges of Voronoi cell 1, search the output .edge file for every\n");
2845   printf(
2846 "  edge that has input vertex 1 as an endpoint.  The corresponding dual\n");
2847   printf(
2848 "  edges in the output .v.edge file form the boundary of Voronoi cell 1.\n");
2849   printf("\n");
2850   printf(
2851 "  For each Voronoi vertex, the .neigh file gives a list of the three\n");
2852   printf(
2853 "  Voronoi vertices attached to it.  You might find this more convenient\n");
2854   printf("  than the .v.edge file.\n\n");
2855   printf("Quadratic Elements:\n\n");
2856   printf(
2857 "  Triangle generates meshes with subparametric quadratic elements if the\n");
2858   printf(
2859 "  -o2 switch is specified.  Quadratic elements have six nodes per element,\n"
2860 );
2861   printf(
2862 "  rather than three.  `Subparametric' means that the edges of the triangles\n"
2863 );
2864   printf(
2865 "  are always straight, so that subparametric quadratic elements are\n");
2866   printf(
2867 "  geometrically identical to linear elements, even though they can be used\n"
2868 );
2869   printf(
2870 "  with quadratic interpolating functions.  The three extra nodes of an\n");
2871   printf(
2872 "  element fall at the midpoints of the three edges, with the fourth, fifth,\n"
2873 );
2874   printf(
2875 "  and sixth nodes appearing opposite the first, second, and third corners\n");
2876   printf("  respectively.\n\n");
2877   printf("Domains with Small Angles:\n\n");
2878   printf(
2879 "  If two input segments adjoin each other at a small angle, clearly the -q\n"
2880 );
2881   printf(
2882 "  switch cannot remove the small angle.  Moreover, Triangle may have no\n");
2883   printf(
2884 "  choice but to generate additional triangles whose smallest angles are\n");
2885   printf(
2886 "  smaller than the specified bound.  However, these triangles only appear\n");
2887   printf(
2888 "  between input segments separated by small angles.  Moreover, if you\n");
2889   printf(
2890 "  request a minimum angle of theta degrees, Triangle will generally produce\n"
2891 );
2892   printf(
2893 "  no angle larger than 180 - 2 theta, even if it is forced to compromise on\n"
2894 );
2895   printf("  the minimum angle.\n\n");
2896   printf("Statistics:\n\n");
2897   printf(
2898 "  After generating a mesh, Triangle prints a count of entities in the\n");
2899   printf(
2900 "  output mesh, including the number of vertices, triangles, edges, exterior\n"
2901 );
2902   printf(
2903 "  boundary edges (i.e. subsegments on the boundary of the triangulation,\n");
2904   printf(
2905 "  including hole boundaries), interior boundary edges (i.e. subsegments of\n"
2906 );
2907   printf(
2908 "  input segments not on the boundary), and total subsegments.  If you've\n");
2909   printf(
2910 "  forgotten the statistics for an existing mesh, run Triangle on that mesh\n"
2911 );
2912   printf(
2913 "  with the -rNEP switches to read the mesh and print the statistics without\n"
2914 );
2915   printf(
2916 "  writing any files.  Use -rpNEP if you've got a .poly file for the mesh.\n");
2917   printf("\n");
2918   printf(
2919 "  The -V switch produces extended statistics, including a rough estimate\n");
2920   printf(
2921 "  of memory use, the number of calls to geometric predicates, and\n");
2922   printf(
2923 "  histograms of the angles and the aspect ratios of the triangles in the\n");
2924   printf("  mesh.\n\n");
2925   printf("Exact Arithmetic:\n\n");
2926   printf(
2927 "  Triangle uses adaptive exact arithmetic to perform what computational\n");
2928   printf(
2929 "  geometers call the `orientation' and `incircle' tests.  If the floating-\n"
2930 );
2931   printf(
2932 "  point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
2933   printf(
2934 "  most workstations do), and does not use extended precision internal\n");
2935   printf(
2936 "  floating-point registers, then your output is guaranteed to be an\n");
2937   printf(
2938 "  absolutely true Delaunay or constrained Delaunay triangulation, roundoff\n"
2939 );
2940   printf(
2941 "  error notwithstanding.  The word `adaptive' implies that these arithmetic\n"
2942 );
2943   printf(
2944 "  routines compute the result only to the precision necessary to guarantee\n"
2945 );
2946   printf(
2947 "  correctness, so they are usually nearly as fast as their approximate\n");
2948   printf("  counterparts.\n\n");
2949   printf(
2950 "  May CPUs, including Intel x86 processors, have extended precision\n");
2951   printf(
2952 "  floating-point registers.  These must be reconfigured so their precision\n"
2953 );
2954   printf(
2955 "  is reduced to memory precision.  Triangle does this if it is compiled\n");
2956   printf("  correctly.  See the makefile for details.\n\n");
2957   printf(
2958 "  The exact tests can be disabled with the -X switch.  On most inputs, this\n"
2959 );
2960   printf(
2961 "  switch reduces the computation time by about eight percent--it's not\n");
2962   printf(
2963 "  worth the risk.  There are rare difficult inputs (having many collinear\n");
2964   printf(
2965 "  and cocircular vertices), however, for which the difference in speed\n");
2966   printf(
2967 "  could be a factor of two.  Be forewarned that these are precisely the\n");
2968   printf(
2969 "  inputs most likely to cause errors if you use the -X switch.  Hence, the\n"
2970 );
2971   printf("  -X switch is not recommended.\n\n");
2972   printf(
2973 "  Unfortunately, the exact tests don't solve every numerical problem.\n");
2974   printf(
2975 "  Exact arithmetic is not used to compute the positions of new vertices,\n");
2976   printf(
2977 "  because the bit complexity of vertex coordinates would grow without\n");
2978   printf(
2979 "  bound.  Hence, segment intersections aren't computed exactly; in very\n");
2980   printf(
2981 "  unusual cases, roundoff error in computing an intersection point might\n");
2982   printf(
2983 "  actually lead to an inverted triangle and an invalid triangulation.\n");
2984   printf(
2985 "  (This is one reason to specify your own intersection points in your .poly\n"
2986 );
2987   printf(
2988 "  files.)  Similarly, exact arithmetic is not used to compute the vertices\n"
2989 );
2990   printf("  of the Voronoi diagram.\n\n");
2991   printf(
2992 "  Another pair of problems not solved by the exact arithmetic routines is\n");
2993   printf(
2994 "  underflow and overflow.  If Triangle is compiled for double precision\n");
2995   printf(
2996 "  arithmetic, I believe that Triangle's geometric predicates work correctly\n"
2997 );
2998   printf(
2999 "  if the exponent of every input coordinate falls in the range [-148, 201].\n"
3000 );
3001   printf(
3002 "  Underflow can silently prevent the orientation and incircle tests from\n");
3003   printf(
3004 "  being performed exactly, while overflow typically causes a floating\n");
3005   printf("  exception.\n\n");
3006   printf("Calling Triangle from Another Program:\n\n");
3007   printf("  Read the file triangle.h for details.\n\n");
3008   printf("Troubleshooting:\n\n");
3009   printf("  Please read this section before mailing me bugs.\n\n");
3010   printf("  `My output mesh has no triangles!'\n\n");
3011   printf(
3012 "    If you're using a PSLG, you've probably failed to specify a proper set\n"
3013 );
3014   printf(
3015 "    of bounding segments, or forgotten to use the -c switch.  Or you may\n");
3016   printf(
3017 "    have placed a hole badly, thereby eating all your triangles.  To test\n");
3018   printf("    these possibilities, try again with the -c and -O switches.\n");
3019   printf(
3020 "    Alternatively, all your input vertices may be collinear, in which case\n"
3021 );
3022   printf("    you can hardly expect to triangulate them.\n\n");
3023   printf("  `Triangle doesn't terminate, or just crashes.'\n\n");
3024   printf(
3025 "    Bad things can happen when triangles get so small that the distance\n");
3026   printf(
3027 "    between their vertices isn't much larger than the precision of your\n");
3028   printf(
3029 "    machine's arithmetic.  If you've compiled Triangle for single-precision\n"
3030 );
3031   printf(
3032 "    arithmetic, you might do better by recompiling it for double-precision.\n"
3033 );
3034   printf(
3035 "    Then again, you might just have to settle for more lenient constraints\n"
3036 );
3037   printf(
3038 "    on the minimum angle and the maximum area than you had planned.\n");
3039   printf("\n");
3040   printf(
3041 "    You can minimize precision problems by ensuring that the origin lies\n");
3042   printf(
3043 "    inside your vertex set, or even inside the densest part of your\n");
3044   printf(
3045 "    mesh.  If you're triangulating an object whose x-coordinates all fall\n");
3046   printf(
3047 "    between 6247133 and 6247134, you're not leaving much floating-point\n");
3048   printf("    precision for Triangle to work with.\n\n");
3049   printf(
3050 "    Precision problems can occur covertly if the input PSLG contains two\n");
3051   printf(
3052 "    segments that meet (or intersect) at an extremely small angle, or if\n");
3053   printf(
3054 "    such an angle is introduced by the -c switch.  If you don't realize\n");
3055   printf(
3056 "    that a tiny angle is being formed, you might never discover why\n");
3057   printf(
3058 "    Triangle is crashing.  To check for this possibility, use the -S switch\n"
3059 );
3060   printf(
3061 "    (with an appropriate limit on the number of Steiner points, found by\n");
3062   printf(
3063 "    trial-and-error) to stop Triangle early, and view the output .poly file\n"
3064 );
3065   printf(
3066 "    with Show Me (described below).  Look carefully for regions where dense\n"
3067 );
3068   printf(
3069 "    clusters of vertices are forming and for small angles between segments.\n"
3070 );
3071   printf(
3072 "    Zoom in closely, as such segments might look like a single segment from\n"
3073 );
3074   printf("    a distance.\n\n");
3075   printf(
3076 "    If some of the input values are too large, Triangle may suffer a\n");
3077   printf(
3078 "    floating exception due to overflow when attempting to perform an\n");
3079   printf(
3080 "    orientation or incircle test.  (Read the section on exact arithmetic\n");
3081   printf(
3082 "    above.)  Again, I recommend compiling Triangle for double (rather\n");
3083   printf("    than single) precision arithmetic.\n\n");
3084   printf(
3085 "    Unexpected problems can arise if you use quality meshing (-q, -a, or\n");
3086   printf(
3087 "    -u) with an input that is not segment-bounded--that is, if your input\n");
3088   printf(
3089 "    is a vertex set, or you're using the -c switch.  If the convex hull of\n"
3090 );
3091   printf(
3092 "    your input vertices has collinear vertices on its boundary, an input\n");
3093   printf(
3094 "    vertex that you think lies on the convex hull might actually lie just\n");
3095   printf(
3096 "    inside the convex hull.  If so, the vertex and the nearby convex hull\n");
3097   printf(
3098 "    edge form an extremely thin triangle.  When Triangle tries to refine\n");
3099   printf(
3100 "    the mesh to enforce angle and area constraints, Triangle might generate\n"
3101 );
3102   printf(
3103 "    extremely tiny triangles, or it might fail because of insufficient\n");
3104   printf("    floating-point precision.\n\n");
3105   printf(
3106 "  `The numbering of the output vertices doesn't match the input vertices.'\n"
3107 );
3108   printf("\n");
3109   printf(
3110 "    You may have had duplicate input vertices, or you may have eaten some\n");
3111   printf(
3112 "    of your input vertices with a hole, or by placing them outside the area\n"
3113 );
3114   printf(
3115 "    enclosed by segments.  In any case, you can solve the problem by not\n");
3116   printf("    using the -j switch.\n\n");
3117   printf(
3118 "  `Triangle executes without incident, but when I look at the resulting\n");
3119   printf(
3120 "  mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
3121   printf("\n");
3122   printf(
3123 "    If you select the -X switch, Triangle occasionally makes mistakes due\n");
3124   printf(
3125 "    to floating-point roundoff error.  Although these errors are rare,\n");
3126   printf(
3127 "    don't use the -X switch.  If you still have problems, please report the\n"
3128 );
3129   printf("    bug.\n\n");
3130   printf(
3131 "  `Triangle executes without incident, but when I look at the resulting\n");
3132   printf("  Voronoi diagram, it has overlapping edges or other geometric\n");
3133   printf("  inconsistencies.'\n");
3134   printf("\n");
3135   printf(
3136 "    If your input is a PSLG (-p), you can only expect a meaningful Voronoi\n"
3137 );
3138   printf(
3139 "    diagram if the domain you are triangulating is convex and free of\n");
3140   printf(
3141 "    holes, and you use the -D switch to construct a conforming Delaunay\n");
3142   printf("    triangulation (instead of a CDT or CCDT).\n\n");
3143   printf(
3144 "  Strange things can happen if you've taken liberties with your PSLG.  Do\n");
3145   printf(
3146 "  you have a vertex lying in the middle of a segment?  Triangle sometimes\n");
3147   printf(
3148 "  copes poorly with that sort of thing.  Do you want to lay out a collinear\n"
3149 );
3150   printf(
3151 "  row of evenly spaced, segment-connected vertices?  Have you simply\n");
3152   printf(
3153 "  defined one long segment connecting the leftmost vertex to the rightmost\n"
3154 );
3155   printf(
3156 "  vertex, and a bunch of vertices lying along it?  This method occasionally\n"
3157 );
3158   printf(
3159 "  works, especially with horizontal and vertical lines, but often it\n");
3160   printf(
3161 "  doesn't, and you'll have to connect each adjacent pair of vertices with a\n"
3162 );
3163   printf("  separate segment.  If you don't like it, tough.\n\n");
3164   printf(
3165 "  Furthermore, if you have segments that intersect other than at their\n");
3166   printf(
3167 "  endpoints, try not to let the intersections fall extremely close to PSLG\n"
3168 );
3169   printf("  vertices or each other.\n\n");
3170   printf(
3171 "  If you have problems refining a triangulation not produced by Triangle:\n");
3172   printf(
3173 "  Are you sure the triangulation is geometrically valid?  Is it formatted\n");
3174   printf(
3175 "  correctly for Triangle?  Are the triangles all listed so the first three\n"
3176 );
3177   printf(
3178 "  vertices are their corners in counterclockwise order?  Are all of the\n");
3179   printf(
3180 "  triangles constrained Delaunay?  Triangle's Delaunay refinement algorithm\n"
3181 );
3182   printf("  assumes that it starts with a CDT.\n\n");
3183   printf("Show Me:\n\n");
3184   printf(
3185 "  Triangle comes with a separate program named `Show Me', whose primary\n");
3186   printf(
3187 "  purpose is to draw meshes on your screen or in PostScript.  Its secondary\n"
3188 );
3189   printf(
3190 "  purpose is to check the validity of your input files, and do so more\n");
3191   printf(
3192 "  thoroughly than Triangle does.  Unlike Triangle, Show Me requires that\n");
3193   printf(
3194 "  you have the X Windows system.  Sorry, Microsoft Windows users.\n");
3195   printf("\n");
3196   printf("Triangle on the Web:\n");
3197   printf("\n");
3198   printf("  To see an illustrated version of these instructions, check out\n");
3199   printf("\n");
3200   printf("    http://www.cs.cmu.edu/~quake/triangle.html\n");
3201   printf("\n");
3202   printf("A Brief Plea:\n");
3203   printf("\n");
3204   printf(
3205 "  If you use Triangle, and especially if you use it to accomplish real\n");
3206   printf(
3207 "  work, I would like very much to hear from you.  A short letter or email\n");
3208   printf(
3209 "  (to jrs@cs.berkeley.edu) describing how you use Triangle will mean a lot\n"
3210 );
3211   printf(
3212 "  to me.  The more people I know are using this program, the more easily I\n"
3213 );
3214   printf(
3215 "  can justify spending time on improvements, which in turn will benefit\n");
3216   printf(
3217 "  you.  Also, I can put you on a list to receive email whenever a new\n");
3218   printf("  version of Triangle is available.\n\n");
3219   printf(
3220 "  If you use a mesh generated by Triangle in a publication, please include\n"
3221 );
3222   printf(
3223 "  an acknowledgment as well.  And please spell Triangle with a capital `T'!\n"
3224 );
3225   printf(
3226 "  If you want to include a citation, use `Jonathan Richard Shewchuk,\n");
3227   printf(
3228 "  ``Triangle: Engineering a 2D Quality Mesh Generator and Delaunay\n");
3229   printf(
3230 "  Triangulator,'' in Applied Computational Geometry:  Towards Geometric\n");
3231   printf(
3232 "  Engineering (Ming C. Lin and Dinesh Manocha, editors), volume 1148 of\n");
3233   printf(
3234 "  Lecture Notes in Computer Science, pages 203-222, Springer-Verlag,\n");
3235   printf(
3236 "  Berlin, May 1996.  (From the First ACM Workshop on Applied Computational\n"
3237 );
3238   printf("  Geometry.)'\n\n");
3239   printf("Research credit:\n\n");
3240   printf(
3241 "  Of course, I can take credit for only a fraction of the ideas that made\n");
3242   printf(
3243 "  this mesh generator possible.  Triangle owes its existence to the efforts\n"
3244 );
3245   printf(
3246 "  of many fine computational geometers and other researchers, including\n");
3247   printf(
3248 "  Marshall Bern, L. Paul Chew, Kenneth L. Clarkson, Boris Delaunay, Rex A.\n"
3249 );
3250   printf(
3251 "  Dwyer, David Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E.\n");
3252   printf(
3253 "  Knuth, Charles L. Lawson, Der-Tsai Lee, Gary L. Miller, Ernst P. Mucke,\n");
3254   printf(
3255 "  Steven E. Pav, Douglas M. Priest, Jim Ruppert, Isaac Saias, Bruce J.\n");
3256   printf(
3257 "  Schachter, Micha Sharir, Peter W. Shor, Daniel D. Sleator, Jorge Stolfi,\n"
3258 );
3259   printf("  Robert E. Tarjan, Alper Ungor, Christopher J. Van Wyk, Noel J.\n");
3260   printf(
3261 "  Walkington, and Binhai Zhu.  See the comments at the beginning of the\n");
3262   printf("  source code for references.\n\n");
3263   triexit(0);
3264 }
3265 
3266 #endif /* not TRILIBRARY */
3267 
3268 /*****************************************************************************/
3269 /*                                                                           */
3270 /*  internalerror()   Ask the user to send me the defective product.  Exit.  */
3271 /*                                                                           */
3272 /*****************************************************************************/
3273 
internalerror()3274 void internalerror()
3275 {
3276   printf("  Please report this bug to jrs@cs.berkeley.edu\n");
3277   printf("  Include the message above, your input data set, and the exact\n");
3278   printf("    command line you used to run Triangle.\n");
3279   triexit(1);
3280 }
3281 
3282 /*****************************************************************************/
3283 /*                                                                           */
3284 /*  parsecommandline()   Read the command line, identify switches, and set   */
3285 /*                       up options and file names.                          */
3286 /*                                                                           */
3287 /*****************************************************************************/
3288 
3289 #ifdef ANSI_DECLARATORS
3290 void parsecommandline(int argc, char **argv, struct behavior *b)
3291 #else /* not ANSI_DECLARATORS */
3292 void parsecommandline(argc, argv, b)
3293 int argc;
3294 char **argv;
3295 struct behavior *b;
3296 #endif /* not ANSI_DECLARATORS */
3297 
3298 {
3299 #ifdef TRILIBRARY
3300 #define STARTINDEX 0
3301 #else /* not TRILIBRARY */
3302 #define STARTINDEX 1
3303   int increment;
3304   int meshnumber;
3305 #endif /* not TRILIBRARY */
3306   int i, j, k;
3307   char workstring[FILENAMESIZE];
3308 
3309   b->poly = b->refine = b->quality = 0;
3310   b->vararea = b->fixedarea = b->usertest = 0;
3311   b->regionattrib = b->convex = b->weighted = b->jettison = 0;
3312   b->firstnumber = 1;
3313   b->edgesout = b->voronoi = b->neighbors = b->geomview = 0;
3314   b->nobound = b->nopolywritten = b->nonodewritten = b->noelewritten = 0;
3315   b->noiterationnum = 0;
3316   b->noholes = b->noexact = 0;
3317   b->incremental = b->sweepline = 0;
3318   b->dwyer = 1;
3319   b->splitseg = 0;
3320   b->docheck = 0;
3321   b->nobisect = 0;
3322   b->conformdel = 0;
3323   b->steiner = -1;
3324   b->order = 1;
3325   b->minangle = 0.0;
3326   b->maxarea = -1.0;
3327   b->quiet = b->verbose = 0;
3328 #ifndef TRILIBRARY
3329   b->innodefilename[0] = '\0';
3330 #endif /* not TRILIBRARY */
3331 
3332   for (i = STARTINDEX; i < argc; i++) {
3333 #ifndef TRILIBRARY
3334     if (argv[i][0] == '-') {
3335 #endif /* not TRILIBRARY */
3336       for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
3337         if (argv[i][j] == 'p') {
3338           b->poly = 1;
3339 	}
3340 #ifndef CDT_ONLY
3341         if (argv[i][j] == 'r') {
3342           b->refine = 1;
3343 	}
3344         if (argv[i][j] == 'q') {
3345           b->quality = 1;
3346           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3347               (argv[i][j + 1] == '.')) {
3348             k = 0;
3349             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3350                    (argv[i][j + 1] == '.')) {
3351               j++;
3352               workstring[k] = argv[i][j];
3353               k++;
3354             }
3355             workstring[k] = '\0';
3356             b->minangle = (REAL) strtod(workstring, (char **) NULL);
3357 	  } else {
3358             b->minangle = 20.0;
3359 	  }
3360 	}
3361         if (argv[i][j] == 'a') {
3362           b->quality = 1;
3363           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3364               (argv[i][j + 1] == '.')) {
3365             b->fixedarea = 1;
3366             k = 0;
3367             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3368                    (argv[i][j + 1] == '.')) {
3369               j++;
3370               workstring[k] = argv[i][j];
3371               k++;
3372             }
3373             workstring[k] = '\0';
3374             b->maxarea = (REAL) strtod(workstring, (char **) NULL);
3375             if (b->maxarea <= 0.0) {
3376               printf("Error:  Maximum area must be greater than zero.\n");
3377               triexit(1);
3378 	    }
3379 	  } else {
3380             b->vararea = 1;
3381 	  }
3382 	}
3383         if (argv[i][j] == 'u') {
3384           b->quality = 1;
3385           b->usertest = 1;
3386         }
3387 #endif /* not CDT_ONLY */
3388         if (argv[i][j] == 'A') {
3389           b->regionattrib = 1;
3390         }
3391         if (argv[i][j] == 'c') {
3392           b->convex = 1;
3393         }
3394         if (argv[i][j] == 'w') {
3395           b->weighted = 1;
3396         }
3397         if (argv[i][j] == 'W') {
3398           b->weighted = 2;
3399         }
3400         if (argv[i][j] == 'j') {
3401           b->jettison = 1;
3402         }
3403         if (argv[i][j] == 'z') {
3404           b->firstnumber = 0;
3405         }
3406         if (argv[i][j] == 'e') {
3407           b->edgesout = 1;
3408 	}
3409         if (argv[i][j] == 'v') {
3410           b->voronoi = 1;
3411 	}
3412         if (argv[i][j] == 'n') {
3413           b->neighbors = 1;
3414 	}
3415         if (argv[i][j] == 'g') {
3416           b->geomview = 1;
3417 	}
3418         if (argv[i][j] == 'B') {
3419           b->nobound = 1;
3420 	}
3421         if (argv[i][j] == 'P') {
3422           b->nopolywritten = 1;
3423 	}
3424         if (argv[i][j] == 'N') {
3425           b->nonodewritten = 1;
3426 	}
3427         if (argv[i][j] == 'E') {
3428           b->noelewritten = 1;
3429 	}
3430 #ifndef TRILIBRARY
3431         if (argv[i][j] == 'I') {
3432           b->noiterationnum = 1;
3433 	}
3434 #endif /* not TRILIBRARY */
3435         if (argv[i][j] == 'O') {
3436           b->noholes = 1;
3437 	}
3438         if (argv[i][j] == 'X') {
3439           b->noexact = 1;
3440 	}
3441         if (argv[i][j] == 'o') {
3442           if (argv[i][j + 1] == '2') {
3443             j++;
3444             b->order = 2;
3445           }
3446 	}
3447 #ifndef CDT_ONLY
3448         if (argv[i][j] == 'Y') {
3449           b->nobisect++;
3450 	}
3451         if (argv[i][j] == 'S') {
3452           b->steiner = 0;
3453           while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
3454             j++;
3455             b->steiner = b->steiner * 10 + (int) (argv[i][j] - '0');
3456           }
3457         }
3458 #endif /* not CDT_ONLY */
3459 #ifndef REDUCED
3460         if (argv[i][j] == 'i') {
3461           b->incremental = 1;
3462         }
3463         if (argv[i][j] == 'F') {
3464           b->sweepline = 1;
3465         }
3466 #endif /* not REDUCED */
3467         if (argv[i][j] == 'l') {
3468           b->dwyer = 0;
3469         }
3470 #ifndef REDUCED
3471 #ifndef CDT_ONLY
3472         if (argv[i][j] == 's') {
3473           b->splitseg = 1;
3474         }
3475         if ((argv[i][j] == 'D') || (argv[i][j] == 'L')) {
3476           b->quality = 1;
3477           b->conformdel = 1;
3478         }
3479 #endif /* not CDT_ONLY */
3480         if (argv[i][j] == 'C') {
3481           b->docheck = 1;
3482         }
3483 #endif /* not REDUCED */
3484         if (argv[i][j] == 'Q') {
3485           b->quiet = 1;
3486         }
3487         if (argv[i][j] == 'V') {
3488           b->verbose++;
3489         }
3490 #ifndef TRILIBRARY
3491         if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
3492             (argv[i][j] == '?')) {
3493           info();
3494 	}
3495 #endif /* not TRILIBRARY */
3496       }
3497 #ifndef TRILIBRARY
3498     } else {
3499       strncpy(b->innodefilename, argv[i], FILENAMESIZE - 1);
3500       b->innodefilename[FILENAMESIZE - 1] = '\0';
3501     }
3502 #endif /* not TRILIBRARY */
3503   }
3504 #ifndef TRILIBRARY
3505   if (b->innodefilename[0] == '\0') {
3506     syntax();
3507   }
3508   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".node")) {
3509     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3510   }
3511   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".poly")) {
3512     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3513     b->poly = 1;
3514   }
3515 #ifndef CDT_ONLY
3516   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 4], ".ele")) {
3517     b->innodefilename[strlen(b->innodefilename) - 4] = '\0';
3518     b->refine = 1;
3519   }
3520   if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".area")) {
3521     b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
3522     b->refine = 1;
3523     b->quality = 1;
3524     b->vararea = 1;
3525   }
3526 #endif /* not CDT_ONLY */
3527 #endif /* not TRILIBRARY */
3528   b->usesegments = b->poly || b->refine || b->quality || b->convex;
3529   b->goodangle = cos(b->minangle * PI / 180.0);
3530   if (b->goodangle == 1.0) {
3531     b->offconstant = 0.0;
3532   } else {
3533     b->offconstant = 0.475 * sqrt((1.0 + b->goodangle) / (1.0 - b->goodangle));
3534   }
3535   b->goodangle *= b->goodangle;
3536   if (b->refine && b->noiterationnum) {
3537     printf(
3538       "Error:  You cannot use the -I switch when refining a triangulation.\n");
3539     triexit(1);
3540   }
3541   /* Be careful not to allocate space for element area constraints that */
3542   /*   will never be assigned any value (other than the default -1.0).  */
3543   if (!b->refine && !b->poly) {
3544     b->vararea = 0;
3545   }
3546   /* Be careful not to add an extra attribute to each element unless the */
3547   /*   input supports it (PSLG in, but not refining a preexisting mesh). */
3548   if (b->refine || !b->poly) {
3549     b->regionattrib = 0;
3550   }
3551   /* Regular/weighted triangulations are incompatible with PSLGs */
3552   /*   and meshing.                                              */
3553   if (b->weighted && (b->poly || b->quality)) {
3554     b->weighted = 0;
3555     if (!b->quiet) {
3556       printf("Warning:  weighted triangulations (-w, -W) are incompatible\n");
3557       printf("  with PSLGs (-p) and meshing (-q, -a, -u).  Weights ignored.\n"
3558              );
3559     }
3560   }
3561   if (b->jettison && b->nonodewritten && !b->quiet) {
3562     printf("Warning:  -j and -N switches are somewhat incompatible.\n");
3563     printf("  If any vertices are jettisoned, you will need the output\n");
3564     printf("  .node file to reconstruct the new node indices.");
3565   }
3566 
3567 #ifndef TRILIBRARY
3568   strcpy(b->inpolyfilename, b->innodefilename);
3569   strcpy(b->inelefilename, b->innodefilename);
3570   strcpy(b->areafilename, b->innodefilename);
3571   increment = 0;
3572   strcpy(workstring, b->innodefilename);
3573   j = 1;
3574   while (workstring[j] != '\0') {
3575     if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
3576       increment = j + 1;
3577     }
3578     j++;
3579   }
3580   meshnumber = 0;
3581   if (increment > 0) {
3582     j = increment;
3583     do {
3584       if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
3585         meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
3586       } else {
3587         increment = 0;
3588       }
3589       j++;
3590     } while (workstring[j] != '\0');
3591   }
3592   if (b->noiterationnum) {
3593     strcpy(b->outnodefilename, b->innodefilename);
3594     strcpy(b->outelefilename, b->innodefilename);
3595     strcpy(b->edgefilename, b->innodefilename);
3596     strcpy(b->vnodefilename, b->innodefilename);
3597     strcpy(b->vedgefilename, b->innodefilename);
3598     strcpy(b->neighborfilename, b->innodefilename);
3599     strcpy(b->offfilename, b->innodefilename);
3600     strcat(b->outnodefilename, ".node");
3601     strcat(b->outelefilename, ".ele");
3602     strcat(b->edgefilename, ".edge");
3603     strcat(b->vnodefilename, ".v.node");
3604     strcat(b->vedgefilename, ".v.edge");
3605     strcat(b->neighborfilename, ".neigh");
3606     strcat(b->offfilename, ".off");
3607   } else if (increment == 0) {
3608     strcpy(b->outnodefilename, b->innodefilename);
3609     strcpy(b->outpolyfilename, b->innodefilename);
3610     strcpy(b->outelefilename, b->innodefilename);
3611     strcpy(b->edgefilename, b->innodefilename);
3612     strcpy(b->vnodefilename, b->innodefilename);
3613     strcpy(b->vedgefilename, b->innodefilename);
3614     strcpy(b->neighborfilename, b->innodefilename);
3615     strcpy(b->offfilename, b->innodefilename);
3616     strcat(b->outnodefilename, ".1.node");
3617     strcat(b->outpolyfilename, ".1.poly");
3618     strcat(b->outelefilename, ".1.ele");
3619     strcat(b->edgefilename, ".1.edge");
3620     strcat(b->vnodefilename, ".1.v.node");
3621     strcat(b->vedgefilename, ".1.v.edge");
3622     strcat(b->neighborfilename, ".1.neigh");
3623     strcat(b->offfilename, ".1.off");
3624   } else {
3625     workstring[increment] = '%';
3626     workstring[increment + 1] = 'd';
3627     workstring[increment + 2] = '\0';
3628     sprintf(b->outnodefilename, workstring, meshnumber + 1);
3629     strcpy(b->outpolyfilename, b->outnodefilename);
3630     strcpy(b->outelefilename, b->outnodefilename);
3631     strcpy(b->edgefilename, b->outnodefilename);
3632     strcpy(b->vnodefilename, b->outnodefilename);
3633     strcpy(b->vedgefilename, b->outnodefilename);
3634     strcpy(b->neighborfilename, b->outnodefilename);
3635     strcpy(b->offfilename, b->outnodefilename);
3636     strcat(b->outnodefilename, ".node");
3637     strcat(b->outpolyfilename, ".poly");
3638     strcat(b->outelefilename, ".ele");
3639     strcat(b->edgefilename, ".edge");
3640     strcat(b->vnodefilename, ".v.node");
3641     strcat(b->vedgefilename, ".v.edge");
3642     strcat(b->neighborfilename, ".neigh");
3643     strcat(b->offfilename, ".off");
3644   }
3645   strcat(b->innodefilename, ".node");
3646   strcat(b->inpolyfilename, ".poly");
3647   strcat(b->inelefilename, ".ele");
3648   strcat(b->areafilename, ".area");
3649 #endif /* not TRILIBRARY */
3650 }
3651 
3652 /**                                                                         **/
3653 /**                                                                         **/
3654 /********* User interaction routines begin here                      *********/
3655 
3656 /********* Debugging routines begin here                             *********/
3657 /**                                                                         **/
3658 /**                                                                         **/
3659 
3660 /*****************************************************************************/
3661 /*                                                                           */
3662 /*  printtriangle()   Print out the details of an oriented triangle.         */
3663 /*                                                                           */
3664 /*  I originally wrote this procedure to simplify debugging; it can be       */
3665 /*  called directly from the debugger, and presents information about an     */
3666 /*  oriented triangle in digestible form.  It's also used when the           */
3667 /*  highest level of verbosity (`-VVV') is specified.                        */
3668 /*                                                                           */
3669 /*****************************************************************************/
3670 
3671 #ifdef ANSI_DECLARATORS
3672 void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
3673 #else /* not ANSI_DECLARATORS */
3674 void printtriangle(m, b, t)
3675 struct mesh *m;
3676 struct behavior *b;
3677 struct otri *t;
3678 #endif /* not ANSI_DECLARATORS */
3679 
3680 {
3681   struct otri printtri;
3682   struct osub printsh;
3683   vertex printvertex;
3684 
3685   printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
3686          t->orient);
3687   decode(t->tri[0], printtri);
3688   if (printtri.tri == m->dummytri) {
3689     printf("    [0] = Outer space\n");
3690   } else {
3691     printf("    [0] = x%lx  %d\n", (unsigned long) printtri.tri,
3692            printtri.orient);
3693   }
3694   decode(t->tri[1], printtri);
3695   if (printtri.tri == m->dummytri) {
3696     printf("    [1] = Outer space\n");
3697   } else {
3698     printf("    [1] = x%lx  %d\n", (unsigned long) printtri.tri,
3699            printtri.orient);
3700   }
3701   decode(t->tri[2], printtri);
3702   if (printtri.tri == m->dummytri) {
3703     printf("    [2] = Outer space\n");
3704   } else {
3705     printf("    [2] = x%lx  %d\n", (unsigned long) printtri.tri,
3706            printtri.orient);
3707   }
3708 
3709   org(*t, printvertex);
3710   if (printvertex == (vertex) NULL)
3711     printf("    Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
3712   else
3713     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
3714            (t->orient + 1) % 3 + 3, (unsigned long) printvertex,
3715            printvertex[0], printvertex[1]);
3716   dest(*t, printvertex);
3717   if (printvertex == (vertex) NULL)
3718     printf("    Dest  [%d] = NULL\n", (t->orient + 2) % 3 + 3);
3719   else
3720     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
3721            (t->orient + 2) % 3 + 3, (unsigned long) printvertex,
3722            printvertex[0], printvertex[1]);
3723   apex(*t, printvertex);
3724   if (printvertex == (vertex) NULL)
3725     printf("    Apex  [%d] = NULL\n", t->orient + 3);
3726   else
3727     printf("    Apex  [%d] = x%lx  (%.12g, %.12g)\n",
3728            t->orient + 3, (unsigned long) printvertex,
3729            printvertex[0], printvertex[1]);
3730 
3731   if (b->usesegments) {
3732     sdecode(t->tri[6], printsh);
3733     if (printsh.ss != m->dummysub) {
3734       printf("    [6] = x%lx  %d\n", (unsigned long) printsh.ss,
3735              printsh.ssorient);
3736     }
3737     sdecode(t->tri[7], printsh);
3738     if (printsh.ss != m->dummysub) {
3739       printf("    [7] = x%lx  %d\n", (unsigned long) printsh.ss,
3740              printsh.ssorient);
3741     }
3742     sdecode(t->tri[8], printsh);
3743     if (printsh.ss != m->dummysub) {
3744       printf("    [8] = x%lx  %d\n", (unsigned long) printsh.ss,
3745              printsh.ssorient);
3746     }
3747   }
3748 
3749   if (b->vararea) {
3750     printf("    Area constraint:  %.4g\n", areabound(*t));
3751   }
3752 }
3753 
3754 /*****************************************************************************/
3755 /*                                                                           */
3756 /*  printsubseg()   Print out the details of an oriented subsegment.         */
3757 /*                                                                           */
3758 /*  I originally wrote this procedure to simplify debugging; it can be       */
3759 /*  called directly from the debugger, and presents information about an     */
3760 /*  oriented subsegment in digestible form.  It's also used when the highest */
3761 /*  level of verbosity (`-VVV') is specified.                                */
3762 /*                                                                           */
3763 /*****************************************************************************/
3764 
3765 #ifdef ANSI_DECLARATORS
3766 void printsubseg(struct mesh *m, struct behavior *b, struct osub *s)
3767 #else /* not ANSI_DECLARATORS */
3768 void printsubseg(m, b, s)
3769 struct mesh *m;
3770 struct behavior *b;
3771 struct osub *s;
3772 #endif /* not ANSI_DECLARATORS */
3773 
3774 {
3775   struct osub printsh;
3776   struct otri printtri;
3777   vertex printvertex;
3778 
3779   printf("subsegment x%lx with orientation %d and mark %d:\n",
3780          (unsigned long) s->ss, s->ssorient, mark(*s));
3781   sdecode(s->ss[0], printsh);
3782   if (printsh.ss == m->dummysub) {
3783     printf("    [0] = No subsegment\n");
3784   } else {
3785     printf("    [0] = x%lx  %d\n", (unsigned long) printsh.ss,
3786            printsh.ssorient);
3787   }
3788   sdecode(s->ss[1], printsh);
3789   if (printsh.ss == m->dummysub) {
3790     printf("    [1] = No subsegment\n");
3791   } else {
3792     printf("    [1] = x%lx  %d\n", (unsigned long) printsh.ss,
3793            printsh.ssorient);
3794   }
3795 
3796   sorg(*s, printvertex);
3797   if (printvertex == (vertex) NULL)
3798     printf("    Origin[%d] = NULL\n", 2 + s->ssorient);
3799   else
3800     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
3801            2 + s->ssorient, (unsigned long) printvertex,
3802            printvertex[0], printvertex[1]);
3803   sdest(*s, printvertex);
3804   if (printvertex == (vertex) NULL)
3805     printf("    Dest  [%d] = NULL\n", 3 - s->ssorient);
3806   else
3807     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
3808            3 - s->ssorient, (unsigned long) printvertex,
3809            printvertex[0], printvertex[1]);
3810 
3811   decode(s->ss[6], printtri);
3812   if (printtri.tri == m->dummytri) {
3813     printf("    [6] = Outer space\n");
3814   } else {
3815     printf("    [6] = x%lx  %d\n", (unsigned long) printtri.tri,
3816            printtri.orient);
3817   }
3818   decode(s->ss[7], printtri);
3819   if (printtri.tri == m->dummytri) {
3820     printf("    [7] = Outer space\n");
3821   } else {
3822     printf("    [7] = x%lx  %d\n", (unsigned long) printtri.tri,
3823            printtri.orient);
3824   }
3825 
3826   segorg(*s, printvertex);
3827   if (printvertex == (vertex) NULL)
3828     printf("    Segment origin[%d] = NULL\n", 4 + s->ssorient);
3829   else
3830     printf("    Segment origin[%d] = x%lx  (%.12g, %.12g)\n",
3831            4 + s->ssorient, (unsigned long) printvertex,
3832            printvertex[0], printvertex[1]);
3833   segdest(*s, printvertex);
3834   if (printvertex == (vertex) NULL)
3835     printf("    Segment dest  [%d] = NULL\n", 5 - s->ssorient);
3836   else
3837     printf("    Segment dest  [%d] = x%lx  (%.12g, %.12g)\n",
3838            5 - s->ssorient, (unsigned long) printvertex,
3839            printvertex[0], printvertex[1]);
3840 }
3841 
3842 /**                                                                         **/
3843 /**                                                                         **/
3844 /********* Debugging routines end here                               *********/
3845 
3846 /********* Memory management routines begin here                     *********/
3847 /**                                                                         **/
3848 /**                                                                         **/
3849 
3850 /*****************************************************************************/
3851 /*                                                                           */
3852 /*  poolzero()   Set all of a pool's fields to zero.                         */
3853 /*                                                                           */
3854 /*  This procedure should never be called on a pool that has any memory      */
3855 /*  allocated to it, as that memory would leak.                              */
3856 /*                                                                           */
3857 /*****************************************************************************/
3858 
3859 #ifdef ANSI_DECLARATORS
3860 void poolzero(struct memorypool *pool)
3861 #else /* not ANSI_DECLARATORS */
3862 void poolzero(pool)
3863 struct memorypool *pool;
3864 #endif /* not ANSI_DECLARATORS */
3865 
3866 {
3867   pool->firstblock = (VOID **) NULL;
3868   pool->nowblock = (VOID **) NULL;
3869   pool->nextitem = (VOID *) NULL;
3870   pool->deaditemstack = (VOID *) NULL;
3871   pool->pathblock = (VOID **) NULL;
3872   pool->pathitem = (VOID *) NULL;
3873   pool->alignbytes = 0;
3874   pool->itembytes = 0;
3875   pool->itemsperblock = 0;
3876   pool->itemsfirstblock = 0;
3877   pool->items = 0;
3878   pool->maxitems = 0;
3879   pool->unallocateditems = 0;
3880   pool->pathitemsleft = 0;
3881 }
3882 
3883 /*****************************************************************************/
3884 /*                                                                           */
3885 /*  poolrestart()   Deallocate all items in a pool.                          */
3886 /*                                                                           */
3887 /*  The pool is returned to its starting state, except that no memory is     */
3888 /*  freed to the operating system.  Rather, the previously allocated blocks  */
3889 /*  are ready to be reused.                                                  */
3890 /*                                                                           */
3891 /*****************************************************************************/
3892 
3893 #ifdef ANSI_DECLARATORS
3894 void poolrestart(struct memorypool *pool)
3895 #else /* not ANSI_DECLARATORS */
3896 void poolrestart(pool)
3897 struct memorypool *pool;
3898 #endif /* not ANSI_DECLARATORS */
3899 
3900 {
3901   unsigned long alignptr;
3902 
3903   pool->items = 0;
3904   pool->maxitems = 0;
3905 
3906   /* Set the currently active block. */
3907   pool->nowblock = pool->firstblock;
3908   /* Find the first item in the pool.  Increment by the size of (VOID *). */
3909   alignptr = (unsigned long) (pool->nowblock + 1);
3910   /* Align the item on an `alignbytes'-byte boundary. */
3911   pool->nextitem = (VOID *)
3912     (alignptr + (unsigned long) pool->alignbytes -
3913      (alignptr % (unsigned long) pool->alignbytes));
3914   /* There are lots of unallocated items left in this block. */
3915   pool->unallocateditems = pool->itemsfirstblock;
3916   /* The stack of deallocated items is empty. */
3917   pool->deaditemstack = (VOID *) NULL;
3918 }
3919 
3920 /*****************************************************************************/
3921 /*                                                                           */
3922 /*  poolinit()   Initialize a pool of memory for allocation of items.        */
3923 /*                                                                           */
3924 /*  This routine initializes the machinery for allocating items.  A `pool'   */
3925 /*  is created whose records have size at least `bytecount'.  Items will be  */
3926 /*  allocated in `itemcount'-item blocks.  Each item is assumed to be a      */
3927 /*  collection of words, and either pointers or floating-point values are    */
3928 /*  assumed to be the "primary" word type.  (The "primary" word type is used */
3929 /*  to determine alignment of items.)  If `alignment' isn't zero, all items  */
3930 /*  will be `alignment'-byte aligned in memory.  `alignment' must be either  */
3931 /*  a multiple or a factor of the primary word size; powers of two are safe. */
3932 /*  `alignment' is normally used to create a few unused bits at the bottom   */
3933 /*  of each item's pointer, in which information may be stored.              */
3934 /*                                                                           */
3935 /*  Don't change this routine unless you understand it.                      */
3936 /*                                                                           */
3937 /*****************************************************************************/
3938 
3939 #ifdef ANSI_DECLARATORS
3940 void poolinit(struct memorypool *pool, int bytecount, int itemcount,
3941               int firstitemcount, int alignment)
3942 #else /* not ANSI_DECLARATORS */
3943 void poolinit(pool, bytecount, itemcount, firstitemcount, alignment)
3944 struct memorypool *pool;
3945 int bytecount;
3946 int itemcount;
3947 int firstitemcount;
3948 int alignment;
3949 #endif /* not ANSI_DECLARATORS */
3950 
3951 {
3952   /* Find the proper alignment, which must be at least as large as:   */
3953   /*   - The parameter `alignment'.                                   */
3954   /*   - sizeof(VOID *), so the stack of dead items can be maintained */
3955   /*       without unaligned accesses.                                */
3956   if (alignment > sizeof(VOID *)) {
3957     pool->alignbytes = alignment;
3958   } else {
3959     pool->alignbytes = sizeof(VOID *);
3960   }
3961   pool->itembytes = ((bytecount - 1) / pool->alignbytes + 1) *
3962                     pool->alignbytes;
3963   pool->itemsperblock = itemcount;
3964   if (firstitemcount == 0) {
3965     pool->itemsfirstblock = itemcount;
3966   } else {
3967     pool->itemsfirstblock = firstitemcount;
3968   }
3969 
3970   /* Allocate a block of items.  Space for `itemsfirstblock' items and one  */
3971   /*   pointer (to point to the next block) are allocated, as well as space */
3972   /*   to ensure alignment of the items.                                    */
3973   pool->firstblock = (VOID **)
3974     trimalloc(pool->itemsfirstblock * pool->itembytes + (int) sizeof(VOID *) +
3975               pool->alignbytes);
3976   /* Set the next block pointer to NULL. */
3977   *(pool->firstblock) = (VOID *) NULL;
3978   poolrestart(pool);
3979 }
3980 
3981 /*****************************************************************************/
3982 /*                                                                           */
3983 /*  pooldeinit()   Free to the operating system all memory taken by a pool.  */
3984 /*                                                                           */
3985 /*****************************************************************************/
3986 
3987 #ifdef ANSI_DECLARATORS
3988 void pooldeinit(struct memorypool *pool)
3989 #else /* not ANSI_DECLARATORS */
3990 void pooldeinit(pool)
3991 struct memorypool *pool;
3992 #endif /* not ANSI_DECLARATORS */
3993 
3994 {
3995   while (pool->firstblock != (VOID **) NULL) {
3996     pool->nowblock = (VOID **) *(pool->firstblock);
3997     trifree((VOID *) pool->firstblock);
3998     pool->firstblock = pool->nowblock;
3999   }
4000 }
4001 
4002 /*****************************************************************************/
4003 /*                                                                           */
4004 /*  poolalloc()   Allocate space for an item.                                */
4005 /*                                                                           */
4006 /*****************************************************************************/
4007 
4008 #ifdef ANSI_DECLARATORS
4009 VOID *poolalloc(struct memorypool *pool)
4010 #else /* not ANSI_DECLARATORS */
4011 VOID *poolalloc(pool)
4012 struct memorypool *pool;
4013 #endif /* not ANSI_DECLARATORS */
4014 
4015 {
4016   VOID *newitem;
4017   VOID **newblock;
4018   unsigned long alignptr;
4019 
4020   /* First check the linked list of dead items.  If the list is not   */
4021   /*   empty, allocate an item from the list rather than a fresh one. */
4022   if (pool->deaditemstack != (VOID *) NULL) {
4023     newitem = pool->deaditemstack;               /* Take first item in list. */
4024     pool->deaditemstack = * (VOID **) pool->deaditemstack;
4025   } else {
4026     /* Check if there are any free items left in the current block. */
4027     if (pool->unallocateditems == 0) {
4028       /* Check if another block must be allocated. */
4029       if (*(pool->nowblock) == (VOID *) NULL) {
4030         /* Allocate a new block of items, pointed to by the previous block. */
4031         newblock = (VOID **) trimalloc(pool->itemsperblock * pool->itembytes +
4032                                        (int) sizeof(VOID *) +
4033                                        pool->alignbytes);
4034         *(pool->nowblock) = (VOID *) newblock;
4035         /* The next block pointer is NULL. */
4036         *newblock = (VOID *) NULL;
4037       }
4038 
4039       /* Move to the new block. */
4040       pool->nowblock = (VOID **) *(pool->nowblock);
4041       /* Find the first item in the block.    */
4042       /*   Increment by the size of (VOID *). */
4043       alignptr = (unsigned long) (pool->nowblock + 1);
4044       /* Align the item on an `alignbytes'-byte boundary. */
4045       pool->nextitem = (VOID *)
4046         (alignptr + (unsigned long) pool->alignbytes -
4047          (alignptr % (unsigned long) pool->alignbytes));
4048       /* There are lots of unallocated items left in this block. */
4049       pool->unallocateditems = pool->itemsperblock;
4050     }
4051 
4052     /* Allocate a new item. */
4053     newitem = pool->nextitem;
4054     /* Advance `nextitem' pointer to next free item in block. */
4055     pool->nextitem = (VOID *) ((char *) pool->nextitem + pool->itembytes);
4056     pool->unallocateditems--;
4057     pool->maxitems++;
4058   }
4059   pool->items++;
4060   return newitem;
4061 }
4062 
4063 /*****************************************************************************/
4064 /*                                                                           */
4065 /*  pooldealloc()   Deallocate space for an item.                            */
4066 /*                                                                           */
4067 /*  The deallocated space is stored in a queue for later reuse.              */
4068 /*                                                                           */
4069 /*****************************************************************************/
4070 
4071 #ifdef ANSI_DECLARATORS
4072 void pooldealloc(struct memorypool *pool, VOID *dyingitem)
4073 #else /* not ANSI_DECLARATORS */
4074 void pooldealloc(pool, dyingitem)
4075 struct memorypool *pool;
4076 VOID *dyingitem;
4077 #endif /* not ANSI_DECLARATORS */
4078 
4079 {
4080   /* Push freshly killed item onto stack. */
4081   *((VOID **) dyingitem) = pool->deaditemstack;
4082   pool->deaditemstack = dyingitem;
4083   pool->items--;
4084 }
4085 
4086 /*****************************************************************************/
4087 /*                                                                           */
4088 /*  traversalinit()   Prepare to traverse the entire list of items.          */
4089 /*                                                                           */
4090 /*  This routine is used in conjunction with traverse().                     */
4091 /*                                                                           */
4092 /*****************************************************************************/
4093 
4094 #ifdef ANSI_DECLARATORS
4095 void traversalinit(struct memorypool *pool)
4096 #else /* not ANSI_DECLARATORS */
4097 void traversalinit(pool)
4098 struct memorypool *pool;
4099 #endif /* not ANSI_DECLARATORS */
4100 
4101 {
4102   unsigned long alignptr;
4103 
4104   /* Begin the traversal in the first block. */
4105   pool->pathblock = pool->firstblock;
4106   /* Find the first item in the block.  Increment by the size of (VOID *). */
4107   alignptr = (unsigned long) (pool->pathblock + 1);
4108   /* Align with item on an `alignbytes'-byte boundary. */
4109   pool->pathitem = (VOID *)
4110     (alignptr + (unsigned long) pool->alignbytes -
4111      (alignptr % (unsigned long) pool->alignbytes));
4112   /* Set the number of items left in the current block. */
4113   pool->pathitemsleft = pool->itemsfirstblock;
4114 }
4115 
4116 /*****************************************************************************/
4117 /*                                                                           */
4118 /*  traverse()   Find the next item in the list.                             */
4119 /*                                                                           */
4120 /*  This routine is used in conjunction with traversalinit().  Be forewarned */
4121 /*  that this routine successively returns all items in the list, including  */
4122 /*  deallocated ones on the deaditemqueue.  It's up to you to figure out     */
4123 /*  which ones are actually dead.  Why?  I don't want to allocate extra      */
4124 /*  space just to demarcate dead items.  It can usually be done more         */
4125 /*  space-efficiently by a routine that knows something about the structure  */
4126 /*  of the item.                                                             */
4127 /*                                                                           */
4128 /*****************************************************************************/
4129 
4130 #ifdef ANSI_DECLARATORS
4131 VOID *traverse(struct memorypool *pool)
4132 #else /* not ANSI_DECLARATORS */
4133 VOID *traverse(pool)
4134 struct memorypool *pool;
4135 #endif /* not ANSI_DECLARATORS */
4136 
4137 {
4138   VOID *newitem;
4139   unsigned long alignptr;
4140 
4141   /* Stop upon exhausting the list of items. */
4142   if (pool->pathitem == pool->nextitem) {
4143     return (VOID *) NULL;
4144   }
4145 
4146   /* Check whether any untraversed items remain in the current block. */
4147   if (pool->pathitemsleft == 0) {
4148     /* Find the next block. */
4149     pool->pathblock = (VOID **) *(pool->pathblock);
4150     /* Find the first item in the block.  Increment by the size of (VOID *). */
4151     alignptr = (unsigned long) (pool->pathblock + 1);
4152     /* Align with item on an `alignbytes'-byte boundary. */
4153     pool->pathitem = (VOID *)
4154       (alignptr + (unsigned long) pool->alignbytes -
4155        (alignptr % (unsigned long) pool->alignbytes));
4156     /* Set the number of items left in the current block. */
4157     pool->pathitemsleft = pool->itemsperblock;
4158   }
4159 
4160   newitem = pool->pathitem;
4161   /* Find the next item in the block. */
4162   pool->pathitem = (VOID *) ((char *) pool->pathitem + pool->itembytes);
4163   pool->pathitemsleft--;
4164   return newitem;
4165 }
4166 
4167 /*****************************************************************************/
4168 /*                                                                           */
4169 /*  dummyinit()   Initialize the triangle that fills "outer space" and the   */
4170 /*                omnipresent subsegment.                                    */
4171 /*                                                                           */
4172 /*  The triangle that fills "outer space," called `dummytri', is pointed to  */
4173 /*  by every triangle and subsegment on a boundary (be it outer or inner) of */
4174 /*  the triangulation.  Also, `dummytri' points to one of the triangles on   */
4175 /*  the convex hull (until the holes and concavities are carved), making it  */
4176 /*  possible to find a starting triangle for point location.                 */
4177 /*                                                                           */
4178 /*  The omnipresent subsegment, `dummysub', is pointed to by every triangle  */
4179 /*  or subsegment that doesn't have a full complement of real subsegments    */
4180 /*  to point to.                                                             */
4181 /*                                                                           */
4182 /*  `dummytri' and `dummysub' are generally required to fulfill only a few   */
4183 /*  invariants:  their vertices must remain NULL and `dummytri' must always  */
4184 /*  be bonded (at offset zero) to some triangle on the convex hull of the    */
4185 /*  mesh, via a boundary edge.  Otherwise, the connections of `dummytri' and */
4186 /*  `dummysub' may change willy-nilly.  This makes it possible to avoid      */
4187 /*  writing a good deal of special-case code (in the edge flip, for example) */
4188 /*  for dealing with the boundary of the mesh, places where no subsegment is */
4189 /*  present, and so forth.  Other entities are frequently bonded to          */
4190 /*  `dummytri' and `dummysub' as if they were real mesh entities, with no    */
4191 /*  harm done.                                                               */
4192 /*                                                                           */
4193 /*****************************************************************************/
4194 
4195 #ifdef ANSI_DECLARATORS
4196 void dummyinit(struct mesh *m, struct behavior *b, int trianglebytes,
4197                int subsegbytes)
4198 #else /* not ANSI_DECLARATORS */
4199 void dummyinit(m, b, trianglebytes, subsegbytes)
4200 struct mesh *m;
4201 struct behavior *b;
4202 int trianglebytes;
4203 int subsegbytes;
4204 #endif /* not ANSI_DECLARATORS */
4205 
4206 {
4207   unsigned long alignptr;
4208 
4209   /* Set up `dummytri', the `triangle' that occupies "outer space." */
4210   m->dummytribase = (triangle *) trimalloc(trianglebytes +
4211                                            m->triangles.alignbytes);
4212   /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
4213   alignptr = (unsigned long) m->dummytribase;
4214   m->dummytri = (triangle *)
4215     (alignptr + (unsigned long) m->triangles.alignbytes -
4216      (alignptr % (unsigned long) m->triangles.alignbytes));
4217   /* Initialize the three adjoining triangles to be "outer space."  These  */
4218   /*   will eventually be changed by various bonding operations, but their */
4219   /*   values don't really matter, as long as they can legally be          */
4220   /*   dereferenced.                                                       */
4221   m->dummytri[0] = (triangle) m->dummytri;
4222   m->dummytri[1] = (triangle) m->dummytri;
4223   m->dummytri[2] = (triangle) m->dummytri;
4224   /* Three NULL vertices. */
4225   m->dummytri[3] = (triangle) NULL;
4226   m->dummytri[4] = (triangle) NULL;
4227   m->dummytri[5] = (triangle) NULL;
4228 
4229   if (b->usesegments) {
4230     /* Set up `dummysub', the omnipresent subsegment pointed to by any */
4231     /*   triangle side or subsegment end that isn't attached to a real */
4232     /*   subsegment.                                                   */
4233     m->dummysubbase = (subseg *) trimalloc(subsegbytes +
4234                                            m->subsegs.alignbytes);
4235     /* Align `dummysub' on a `subsegs.alignbytes'-byte boundary. */
4236     alignptr = (unsigned long) m->dummysubbase;
4237     m->dummysub = (subseg *)
4238       (alignptr + (unsigned long) m->subsegs.alignbytes -
4239        (alignptr % (unsigned long) m->subsegs.alignbytes));
4240     /* Initialize the two adjoining subsegments to be the omnipresent      */
4241     /*   subsegment.  These will eventually be changed by various bonding  */
4242     /*   operations, but their values don't really matter, as long as they */
4243     /*   can legally be dereferenced.                                      */
4244     m->dummysub[0] = (subseg) m->dummysub;
4245     m->dummysub[1] = (subseg) m->dummysub;
4246     /* Four NULL vertices. */
4247     m->dummysub[2] = (subseg) NULL;
4248     m->dummysub[3] = (subseg) NULL;
4249     m->dummysub[4] = (subseg) NULL;
4250     m->dummysub[5] = (subseg) NULL;
4251     /* Initialize the two adjoining triangles to be "outer space." */
4252     m->dummysub[6] = (subseg) m->dummytri;
4253     m->dummysub[7] = (subseg) m->dummytri;
4254     /* Set the boundary marker to zero. */
4255     * (int *) (m->dummysub + 8) = 0;
4256 
4257     /* Initialize the three adjoining subsegments of `dummytri' to be */
4258     /*   the omnipresent subsegment.                                  */
4259     m->dummytri[6] = (triangle) m->dummysub;
4260     m->dummytri[7] = (triangle) m->dummysub;
4261     m->dummytri[8] = (triangle) m->dummysub;
4262   }
4263 }
4264 
4265 /*****************************************************************************/
4266 /*                                                                           */
4267 /*  initializevertexpool()   Calculate the size of the vertex data structure */
4268 /*                           and initialize its memory pool.                 */
4269 /*                                                                           */
4270 /*  This routine also computes the `vertexmarkindex' and `vertex2triindex'   */
4271 /*  indices used to find values within each vertex.                          */
4272 /*                                                                           */
4273 /*****************************************************************************/
4274 
4275 #ifdef ANSI_DECLARATORS
4276 void initializevertexpool(struct mesh *m, struct behavior *b)
4277 #else /* not ANSI_DECLARATORS */
4278 void initializevertexpool(m, b)
4279 struct mesh *m;
4280 struct behavior *b;
4281 #endif /* not ANSI_DECLARATORS */
4282 
4283 {
4284   int vertexsize;
4285 
4286   /* The index within each vertex at which the boundary marker is found,    */
4287   /*   followed by the vertex type.  Ensure the vertex marker is aligned to */
4288   /*   a sizeof(int)-byte address.                                          */
4289   m->vertexmarkindex = ((m->mesh_dim + m->nextras) * sizeof(REAL) +
4290                         sizeof(int) - 1) /
4291                        sizeof(int);
4292   vertexsize = (m->vertexmarkindex + 2) * sizeof(int);
4293   if (b->poly) {
4294     /* The index within each vertex at which a triangle pointer is found.  */
4295     /*   Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
4296     m->vertex2triindex = (vertexsize + sizeof(triangle) - 1) /
4297                          sizeof(triangle);
4298     vertexsize = (m->vertex2triindex + 1) * sizeof(triangle);
4299   }
4300 
4301   /* Initialize the pool of vertices. */
4302   poolinit(&m->vertices, vertexsize, VERTEXPERBLOCK,
4303            m->invertices > VERTEXPERBLOCK ? m->invertices : VERTEXPERBLOCK,
4304            sizeof(REAL));
4305 }
4306 
4307 /*****************************************************************************/
4308 /*                                                                           */
4309 /*  initializetrisubpools()   Calculate the sizes of the triangle and        */
4310 /*                            subsegment data structures and initialize      */
4311 /*                            their memory pools.                            */
4312 /*                                                                           */
4313 /*  This routine also computes the `highorderindex', `elemattribindex', and  */
4314 /*  `areaboundindex' indices used to find values within each triangle.       */
4315 /*                                                                           */
4316 /*****************************************************************************/
4317 
4318 #ifdef ANSI_DECLARATORS
4319 void initializetrisubpools(struct mesh *m, struct behavior *b)
4320 #else /* not ANSI_DECLARATORS */
4321 void initializetrisubpools(m, b)
4322 struct mesh *m;
4323 struct behavior *b;
4324 #endif /* not ANSI_DECLARATORS */
4325 
4326 {
4327   int trisize;
4328 
4329   /* The index within each triangle at which the extra nodes (above three)  */
4330   /*   associated with high order elements are found.  There are three      */
4331   /*   pointers to other triangles, three pointers to corners, and possibly */
4332   /*   three pointers to subsegments before the extra nodes.                */
4333   m->highorderindex = 6 + (b->usesegments * 3);
4334   /* The number of bytes occupied by a triangle. */
4335   trisize = ((b->order + 1) * (b->order + 2) / 2 + (m->highorderindex - 3)) *
4336             sizeof(triangle);
4337   /* The index within each triangle at which its attributes are found, */
4338   /*   where the index is measured in REALs.                           */
4339   m->elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
4340   /* The index within each triangle at which the maximum area constraint  */
4341   /*   is found, where the index is measured in REALs.  Note that if the  */
4342   /*   `regionattrib' flag is set, an additional attribute will be added. */
4343   m->areaboundindex = m->elemattribindex + m->eextras + b->regionattrib;
4344   /* If triangle attributes or an area bound are needed, increase the number */
4345   /*   of bytes occupied by a triangle.                                      */
4346   if (b->vararea) {
4347     trisize = (m->areaboundindex + 1) * sizeof(REAL);
4348   } else if (m->eextras + b->regionattrib > 0) {
4349     trisize = m->areaboundindex * sizeof(REAL);
4350   }
4351   /* If a Voronoi diagram or triangle neighbor graph is requested, make    */
4352   /*   sure there's room to store an integer index in each triangle.  This */
4353   /*   integer index can occupy the same space as the subsegment pointers  */
4354   /*   or attributes or area constraint or extra nodes.                    */
4355   if ((b->voronoi || b->neighbors) &&
4356       (trisize < 6 * sizeof(triangle) + sizeof(int))) {
4357     trisize = 6 * sizeof(triangle) + sizeof(int);
4358   }
4359 
4360   /* Having determined the memory size of a triangle, initialize the pool. */
4361   poolinit(&m->triangles, trisize, TRIPERBLOCK,
4362            (2 * m->invertices - 2) > TRIPERBLOCK ? (2 * m->invertices - 2) :
4363            TRIPERBLOCK, 4);
4364 
4365   if (b->usesegments) {
4366     /* Initialize the pool of subsegments.  Take into account all eight */
4367     /*   pointers and one boundary marker.                              */
4368     poolinit(&m->subsegs, 8 * sizeof(triangle) + sizeof(int),
4369              SUBSEGPERBLOCK, SUBSEGPERBLOCK, 4);
4370 
4371     /* Initialize the "outer space" triangle and omnipresent subsegment. */
4372     dummyinit(m, b, m->triangles.itembytes, m->subsegs.itembytes);
4373   } else {
4374     /* Initialize the "outer space" triangle. */
4375     dummyinit(m, b, m->triangles.itembytes, 0);
4376   }
4377 }
4378 
4379 /*****************************************************************************/
4380 /*                                                                           */
4381 /*  triangledealloc()   Deallocate space for a triangle, marking it dead.    */
4382 /*                                                                           */
4383 /*****************************************************************************/
4384 
4385 #ifdef ANSI_DECLARATORS
4386 void triangledealloc(struct mesh *m, triangle *dyingtriangle)
4387 #else /* not ANSI_DECLARATORS */
4388 void triangledealloc(m, dyingtriangle)
4389 struct mesh *m;
4390 triangle *dyingtriangle;
4391 #endif /* not ANSI_DECLARATORS */
4392 
4393 {
4394   /* Mark the triangle as dead.  This makes it possible to detect dead */
4395   /*   triangles when traversing the list of all triangles.            */
4396   killtri(dyingtriangle);
4397   pooldealloc(&m->triangles, (VOID *) dyingtriangle);
4398 }
4399 
4400 /*****************************************************************************/
4401 /*                                                                           */
4402 /*  triangletraverse()   Traverse the triangles, skipping dead ones.         */
4403 /*                                                                           */
4404 /*****************************************************************************/
4405 
4406 #ifdef ANSI_DECLARATORS
4407 triangle *triangletraverse(struct mesh *m)
4408 #else /* not ANSI_DECLARATORS */
4409 triangle *triangletraverse(m)
4410 struct mesh *m;
4411 #endif /* not ANSI_DECLARATORS */
4412 
4413 {
4414   triangle *newtriangle;
4415 
4416   do {
4417     newtriangle = (triangle *) traverse(&m->triangles);
4418     if (newtriangle == (triangle *) NULL) {
4419       return (triangle *) NULL;
4420     }
4421   } while (deadtri(newtriangle));                         /* Skip dead ones. */
4422   return newtriangle;
4423 }
4424 
4425 /*****************************************************************************/
4426 /*                                                                           */
4427 /*  subsegdealloc()   Deallocate space for a subsegment, marking it dead.    */
4428 /*                                                                           */
4429 /*****************************************************************************/
4430 
4431 #ifdef ANSI_DECLARATORS
4432 void subsegdealloc(struct mesh *m, subseg *dyingsubseg)
4433 #else /* not ANSI_DECLARATORS */
4434 void subsegdealloc(m, dyingsubseg)
4435 struct mesh *m;
4436 subseg *dyingsubseg;
4437 #endif /* not ANSI_DECLARATORS */
4438 
4439 {
4440   /* Mark the subsegment as dead.  This makes it possible to detect dead */
4441   /*   subsegments when traversing the list of all subsegments.          */
4442   killsubseg(dyingsubseg);
4443   pooldealloc(&m->subsegs, (VOID *) dyingsubseg);
4444 }
4445 
4446 /*****************************************************************************/
4447 /*                                                                           */
4448 /*  subsegtraverse()   Traverse the subsegments, skipping dead ones.         */
4449 /*                                                                           */
4450 /*****************************************************************************/
4451 
4452 #ifdef ANSI_DECLARATORS
4453 subseg *subsegtraverse(struct mesh *m)
4454 #else /* not ANSI_DECLARATORS */
4455 subseg *subsegtraverse(m)
4456 struct mesh *m;
4457 #endif /* not ANSI_DECLARATORS */
4458 
4459 {
4460   subseg *newsubseg;
4461 
4462   do {
4463     newsubseg = (subseg *) traverse(&m->subsegs);
4464     if (newsubseg == (subseg *) NULL) {
4465       return (subseg *) NULL;
4466     }
4467   } while (deadsubseg(newsubseg));                        /* Skip dead ones. */
4468   return newsubseg;
4469 }
4470 
4471 /*****************************************************************************/
4472 /*                                                                           */
4473 /*  vertexdealloc()   Deallocate space for a vertex, marking it dead.        */
4474 /*                                                                           */
4475 /*****************************************************************************/
4476 
4477 #ifdef ANSI_DECLARATORS
4478 void vertexdealloc(struct mesh *m, vertex dyingvertex)
4479 #else /* not ANSI_DECLARATORS */
4480 void vertexdealloc(m, dyingvertex)
4481 struct mesh *m;
4482 vertex dyingvertex;
4483 #endif /* not ANSI_DECLARATORS */
4484 
4485 {
4486   /* Mark the vertex as dead.  This makes it possible to detect dead */
4487   /*   vertices when traversing the list of all vertices.            */
4488   setvertextype(dyingvertex, DEADVERTEX);
4489   pooldealloc(&m->vertices, (VOID *) dyingvertex);
4490 }
4491 
4492 /*****************************************************************************/
4493 /*                                                                           */
4494 /*  vertextraverse()   Traverse the vertices, skipping dead ones.            */
4495 /*                                                                           */
4496 /*****************************************************************************/
4497 
4498 #ifdef ANSI_DECLARATORS
4499 vertex vertextraverse(struct mesh *m)
4500 #else /* not ANSI_DECLARATORS */
4501 vertex vertextraverse(m)
4502 struct mesh *m;
4503 #endif /* not ANSI_DECLARATORS */
4504 
4505 {
4506   vertex newvertex;
4507 
4508   do {
4509     newvertex = (vertex) traverse(&m->vertices);
4510     if (newvertex == (vertex) NULL) {
4511       return (vertex) NULL;
4512     }
4513   } while (vertextype(newvertex) == DEADVERTEX);          /* Skip dead ones. */
4514   return newvertex;
4515 }
4516 
4517 /*****************************************************************************/
4518 /*                                                                           */
4519 /*  badsubsegdealloc()   Deallocate space for a bad subsegment, marking it   */
4520 /*                       dead.                                               */
4521 /*                                                                           */
4522 /*****************************************************************************/
4523 
4524 #ifndef CDT_ONLY
4525 
4526 #ifdef ANSI_DECLARATORS
4527 void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg)
4528 #else /* not ANSI_DECLARATORS */
4529 void badsubsegdealloc(m, dyingseg)
4530 struct mesh *m;
4531 struct badsubseg *dyingseg;
4532 #endif /* not ANSI_DECLARATORS */
4533 
4534 {
4535   /* Set subsegment's origin to NULL.  This makes it possible to detect dead */
4536   /*   badsubsegs when traversing the list of all badsubsegs             .   */
4537   dyingseg->subsegorg = (vertex) NULL;
4538   pooldealloc(&m->badsubsegs, (VOID *) dyingseg);
4539 }
4540 
4541 #endif /* not CDT_ONLY */
4542 
4543 /*****************************************************************************/
4544 /*                                                                           */
4545 /*  badsubsegtraverse()   Traverse the bad subsegments, skipping dead ones.  */
4546 /*                                                                           */
4547 /*****************************************************************************/
4548 
4549 #ifndef CDT_ONLY
4550 
4551 #ifdef ANSI_DECLARATORS
4552 struct badsubseg *badsubsegtraverse(struct mesh *m)
4553 #else /* not ANSI_DECLARATORS */
4554 struct badsubseg *badsubsegtraverse(m)
4555 struct mesh *m;
4556 #endif /* not ANSI_DECLARATORS */
4557 
4558 {
4559   struct badsubseg *newseg;
4560 
4561   do {
4562     newseg = (struct badsubseg *) traverse(&m->badsubsegs);
4563     if (newseg == (struct badsubseg *) NULL) {
4564       return (struct badsubseg *) NULL;
4565     }
4566   } while (newseg->subsegorg == (vertex) NULL);           /* Skip dead ones. */
4567   return newseg;
4568 }
4569 
4570 #endif /* not CDT_ONLY */
4571 
4572 /*****************************************************************************/
4573 /*                                                                           */
4574 /*  getvertex()   Get a specific vertex, by number, from the list.           */
4575 /*                                                                           */
4576 /*  The first vertex is number 'firstnumber'.                                */
4577 /*                                                                           */
4578 /*  Note that this takes O(n) time (with a small constant, if VERTEXPERBLOCK */
4579 /*  is large).  I don't care to take the trouble to make it work in constant */
4580 /*  time.                                                                    */
4581 /*                                                                           */
4582 /*****************************************************************************/
4583 
4584 #ifdef ANSI_DECLARATORS
4585 vertex getvertex(struct mesh *m, struct behavior *b, int number)
4586 #else /* not ANSI_DECLARATORS */
4587 vertex getvertex(m, b, number)
4588 struct mesh *m;
4589 struct behavior *b;
4590 int number;
4591 #endif /* not ANSI_DECLARATORS */
4592 
4593 {
4594   VOID **getblock;
4595   char *foundvertex;
4596   unsigned long alignptr;
4597   int current;
4598 
4599   getblock = m->vertices.firstblock;
4600   current = b->firstnumber;
4601 
4602   /* Find the right block. */
4603   if (current + m->vertices.itemsfirstblock <= number) {
4604     getblock = (VOID **) *getblock;
4605     current += m->vertices.itemsfirstblock;
4606     while (current + m->vertices.itemsperblock <= number) {
4607       getblock = (VOID **) *getblock;
4608       current += m->vertices.itemsperblock;
4609     }
4610   }
4611 
4612   /* Now find the right vertex. */
4613   alignptr = (unsigned long) (getblock + 1);
4614   foundvertex = (char *) (alignptr + (unsigned long) m->vertices.alignbytes -
4615                           (alignptr % (unsigned long) m->vertices.alignbytes));
4616   return (vertex) (foundvertex + m->vertices.itembytes * (number - current));
4617 }
4618 
4619 /*****************************************************************************/
4620 /*                                                                           */
4621 /*  triangledeinit()   Free all remaining allocated memory.                  */
4622 /*                                                                           */
4623 /*****************************************************************************/
4624 
4625 #ifdef ANSI_DECLARATORS
4626 void triangledeinit(struct mesh *m, struct behavior *b)
4627 #else /* not ANSI_DECLARATORS */
4628 void triangledeinit(m, b)
4629 struct mesh *m;
4630 struct behavior *b;
4631 #endif /* not ANSI_DECLARATORS */
4632 
4633 {
4634   pooldeinit(&m->triangles);
4635   trifree((VOID *) m->dummytribase);
4636   if (b->usesegments) {
4637     pooldeinit(&m->subsegs);
4638     trifree((VOID *) m->dummysubbase);
4639   }
4640   pooldeinit(&m->vertices);
4641 #ifndef CDT_ONLY
4642   if (b->quality) {
4643     pooldeinit(&m->badsubsegs);
4644     if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
4645       pooldeinit(&m->badtriangles);
4646       pooldeinit(&m->flipstackers);
4647     }
4648   }
4649 #endif /* not CDT_ONLY */
4650 }
4651 
4652 /**                                                                         **/
4653 /**                                                                         **/
4654 /********* Memory management routines end here                       *********/
4655 
4656 /********* Constructors begin here                                   *********/
4657 /**                                                                         **/
4658 /**                                                                         **/
4659 
4660 /*****************************************************************************/
4661 /*                                                                           */
4662 /*  maketriangle()   Create a new triangle with orientation zero.            */
4663 /*                                                                           */
4664 /*****************************************************************************/
4665 
4666 #ifdef ANSI_DECLARATORS
4667 void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri)
4668 #else /* not ANSI_DECLARATORS */
4669 void maketriangle(m, b, newotri)
4670 struct mesh *m;
4671 struct behavior *b;
4672 struct otri *newotri;
4673 #endif /* not ANSI_DECLARATORS */
4674 
4675 {
4676   int i;
4677 
4678   newotri->tri = (triangle *) poolalloc(&m->triangles);
4679   /* Initialize the three adjoining triangles to be "outer space". */
4680   newotri->tri[0] = (triangle) m->dummytri;
4681   newotri->tri[1] = (triangle) m->dummytri;
4682   newotri->tri[2] = (triangle) m->dummytri;
4683   /* Three NULL vertices. */
4684   newotri->tri[3] = (triangle) NULL;
4685   newotri->tri[4] = (triangle) NULL;
4686   newotri->tri[5] = (triangle) NULL;
4687   if (b->usesegments) {
4688     /* Initialize the three adjoining subsegments to be the omnipresent */
4689     /*   subsegment.                                                    */
4690     newotri->tri[6] = (triangle) m->dummysub;
4691     newotri->tri[7] = (triangle) m->dummysub;
4692     newotri->tri[8] = (triangle) m->dummysub;
4693   }
4694   for (i = 0; i < m->eextras; i++) {
4695     setelemattribute(*newotri, i, 0.0);
4696   }
4697   if (b->vararea) {
4698     setareabound(*newotri, -1.0);
4699   }
4700 
4701   newotri->orient = 0;
4702 }
4703 
4704 /*****************************************************************************/
4705 /*                                                                           */
4706 /*  makesubseg()   Create a new subsegment with orientation zero.            */
4707 /*                                                                           */
4708 /*****************************************************************************/
4709 
4710 #ifdef ANSI_DECLARATORS
4711 void makesubseg(struct mesh *m, struct osub *newsubseg)
4712 #else /* not ANSI_DECLARATORS */
4713 void makesubseg(m, newsubseg)
4714 struct mesh *m;
4715 struct osub *newsubseg;
4716 #endif /* not ANSI_DECLARATORS */
4717 
4718 {
4719   newsubseg->ss = (subseg *) poolalloc(&m->subsegs);
4720   /* Initialize the two adjoining subsegments to be the omnipresent */
4721   /*   subsegment.                                                  */
4722   newsubseg->ss[0] = (subseg) m->dummysub;
4723   newsubseg->ss[1] = (subseg) m->dummysub;
4724   /* Four NULL vertices. */
4725   newsubseg->ss[2] = (subseg) NULL;
4726   newsubseg->ss[3] = (subseg) NULL;
4727   newsubseg->ss[4] = (subseg) NULL;
4728   newsubseg->ss[5] = (subseg) NULL;
4729   /* Initialize the two adjoining triangles to be "outer space." */
4730   newsubseg->ss[6] = (subseg) m->dummytri;
4731   newsubseg->ss[7] = (subseg) m->dummytri;
4732   /* Set the boundary marker to zero. */
4733   setmark(*newsubseg, 0);
4734 
4735   newsubseg->ssorient = 0;
4736 }
4737 
4738 /**                                                                         **/
4739 /**                                                                         **/
4740 /********* Constructors end here                                     *********/
4741 
4742 /********* Geometric primitives begin here                           *********/
4743 /**                                                                         **/
4744 /**                                                                         **/
4745 
4746 /* The adaptive exact arithmetic geometric predicates implemented herein are */
4747 /*   described in detail in my paper, "Adaptive Precision Floating-Point     */
4748 /*   Arithmetic and Fast Robust Geometric Predicates."  See the header for a */
4749 /*   full citation.                                                          */
4750 
4751 /* Which of the following two methods of finding the absolute values is      */
4752 /*   fastest is compiler-dependent.  A few compilers can inline and optimize */
4753 /*   the fabs() call; but most will incur the overhead of a function call,   */
4754 /*   which is disastrously slow.  A faster way on IEEE machines might be to  */
4755 /*   mask the appropriate bit, but that's difficult to do in C without       */
4756 /*   forcing the value to be stored to memory (rather than be kept in the    */
4757 /*   register to which the optimizer assigned it).                           */
4758 
4759 #define Absolute(a)  ((a) >= 0.0 ? (a) : -(a))
4760 /* #define Absolute(a)  fabs(a) */
4761 
4762 /* Many of the operations are broken up into two pieces, a main part that    */
4763 /*   performs an approximate operation, and a "tail" that computes the       */
4764 /*   roundoff error of that operation.                                       */
4765 /*                                                                           */
4766 /* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(),    */
4767 /*   Split(), and Two_Product() are all implemented as described in the      */
4768 /*   reference.  Each of these macros requires certain variables to be       */
4769 /*   defined in the calling routine.  The variables `bvirt', `c', `abig',    */
4770 /*   `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because   */
4771 /*   they store the result of an operation that may incur roundoff error.    */
4772 /*   The input parameter `x' (or the highest numbered `x_' parameter) must   */
4773 /*   also be declared `INEXACT'.                                             */
4774 
4775 #define Fast_Two_Sum_Tail(a, b, x, y) \
4776   bvirt = x - a; \
4777   y = b - bvirt
4778 
4779 #define Fast_Two_Sum(a, b, x, y) \
4780   x = (REAL) (a + b); \
4781   Fast_Two_Sum_Tail(a, b, x, y)
4782 
4783 #define Two_Sum_Tail(a, b, x, y) \
4784   bvirt = (REAL) (x - a); \
4785   avirt = x - bvirt; \
4786   bround = b - bvirt; \
4787   around = a - avirt; \
4788   y = around + bround
4789 
4790 #define Two_Sum(a, b, x, y) \
4791   x = (REAL) (a + b); \
4792   Two_Sum_Tail(a, b, x, y)
4793 
4794 #define Two_Diff_Tail(a, b, x, y) \
4795   bvirt = (REAL) (a - x); \
4796   avirt = x + bvirt; \
4797   bround = bvirt - b; \
4798   around = a - avirt; \
4799   y = around + bround
4800 
4801 #define Two_Diff(a, b, x, y) \
4802   x = (REAL) (a - b); \
4803   Two_Diff_Tail(a, b, x, y)
4804 
4805 #define Split(a, ahi, alo) \
4806   c = (REAL) (splitter * a); \
4807   abig = (REAL) (c - a); \
4808   ahi = c - abig; \
4809   alo = a - ahi
4810 
4811 #define Two_Product_Tail(a, b, x, y) \
4812   Split(a, ahi, alo); \
4813   Split(b, bhi, blo); \
4814   err1 = x - (ahi * bhi); \
4815   err2 = err1 - (alo * bhi); \
4816   err3 = err2 - (ahi * blo); \
4817   y = (alo * blo) - err3
4818 
4819 #define Two_Product(a, b, x, y) \
4820   x = (REAL) (a * b); \
4821   Two_Product_Tail(a, b, x, y)
4822 
4823 /* Two_Product_Presplit() is Two_Product() where one of the inputs has       */
4824 /*   already been split.  Avoids redundant splitting.                        */
4825 
4826 #define Two_Product_Presplit(a, b, bhi, blo, x, y) \
4827   x = (REAL) (a * b); \
4828   Split(a, ahi, alo); \
4829   err1 = x - (ahi * bhi); \
4830   err2 = err1 - (alo * bhi); \
4831   err3 = err2 - (ahi * blo); \
4832   y = (alo * blo) - err3
4833 
4834 /* Square() can be done more quickly than Two_Product().                     */
4835 
4836 #define Square_Tail(a, x, y) \
4837   Split(a, ahi, alo); \
4838   err1 = x - (ahi * ahi); \
4839   err3 = err1 - ((ahi + ahi) * alo); \
4840   y = (alo * alo) - err3
4841 
4842 #define Square(a, x, y) \
4843   x = (REAL) (a * a); \
4844   Square_Tail(a, x, y)
4845 
4846 /* Macros for summing expansions of various fixed lengths.  These are all    */
4847 /*   unrolled versions of Expansion_Sum().                                   */
4848 
4849 #define Two_One_Sum(a1, a0, b, x2, x1, x0) \
4850   Two_Sum(a0, b , _i, x0); \
4851   Two_Sum(a1, _i, x2, x1)
4852 
4853 #define Two_One_Diff(a1, a0, b, x2, x1, x0) \
4854   Two_Diff(a0, b , _i, x0); \
4855   Two_Sum( a1, _i, x2, x1)
4856 
4857 #define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
4858   Two_One_Sum(a1, a0, b0, _j, _0, x0); \
4859   Two_One_Sum(_j, _0, b1, x3, x2, x1)
4860 
4861 #define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
4862   Two_One_Diff(a1, a0, b0, _j, _0, x0); \
4863   Two_One_Diff(_j, _0, b1, x3, x2, x1)
4864 
4865 /* Macro for multiplying a two-component expansion by a single component.    */
4866 
4867 #define Two_One_Product(a1, a0, b, x3, x2, x1, x0) \
4868   Split(b, bhi, blo); \
4869   Two_Product_Presplit(a0, b, bhi, blo, _i, x0); \
4870   Two_Product_Presplit(a1, b, bhi, blo, _j, _0); \
4871   Two_Sum(_i, _0, _k, x1); \
4872   Fast_Two_Sum(_j, _k, x3, x2)
4873 
4874 /*****************************************************************************/
4875 /*                                                                           */
4876 /*  exactinit()   Initialize the variables used for exact arithmetic.        */
4877 /*                                                                           */
4878 /*  `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in   */
4879 /*  floating-point arithmetic.  `epsilon' bounds the relative roundoff       */
4880 /*  error.  It is used for floating-point error analysis.                    */
4881 /*                                                                           */
4882 /*  `splitter' is used to split floating-point numbers into two half-        */
4883 /*  length significands for exact multiplication.                            */
4884 /*                                                                           */
4885 /*  I imagine that a highly optimizing compiler might be too smart for its   */
4886 /*  own good, and somehow cause this routine to fail, if it pretends that    */
4887 /*  floating-point arithmetic is too much like real arithmetic.              */
4888 /*                                                                           */
4889 /*  Don't change this routine unless you fully understand it.                */
4890 /*                                                                           */
4891 /*****************************************************************************/
4892 
exactinit()4893 void exactinit()
4894 {
4895   REAL half;
4896   REAL check, lastcheck;
4897   int every_other;
4898 #ifdef LINUX
4899   int cword;
4900 #endif /* LINUX */
4901 
4902 #ifdef CPU86
4903 #ifdef SINGLE
4904   _control87(_PC_24, _MCW_PC); /* Set FPU control word for single precision. */
4905 #else /* not SINGLE */
4906   _control87(_PC_53, _MCW_PC); /* Set FPU control word for double precision. */
4907 #endif /* not SINGLE */
4908 #endif /* CPU86 */
4909 #ifdef LINUX
4910 #ifdef SINGLE
4911   /*  cword = 4223; */
4912   cword = 4210;                 /* set FPU control word for single precision */
4913 #else /* not SINGLE */
4914   /*  cword = 4735; */
4915   cword = 4722;                 /* set FPU control word for double precision */
4916 #endif /* not SINGLE */
4917   _FPU_SETCW(cword);
4918 #endif /* LINUX */
4919 
4920   every_other = 1;
4921   half = 0.5;
4922   epsilon = 1.0;
4923   splitter = 1.0;
4924   check = 1.0;
4925   /* Repeatedly divide `epsilon' by two until it is too small to add to      */
4926   /*   one without causing roundoff.  (Also check if the sum is equal to     */
4927   /*   the previous sum, for machines that round up instead of using exact   */
4928   /*   rounding.  Not that these routines will work on such machines.)       */
4929   do {
4930     lastcheck = check;
4931     epsilon *= half;
4932     if (every_other) {
4933       splitter *= 2.0;
4934     }
4935     every_other = !every_other;
4936     check = 1.0 + epsilon;
4937   } while ((check != 1.0) && (check != lastcheck));
4938   splitter += 1.0;
4939   /* Error bounds for orientation and incircle tests. */
4940   resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
4941   ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
4942   ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
4943   ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
4944   iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
4945   iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
4946   iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
4947   o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon;
4948   o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon;
4949   o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon;
4950 }
4951 
4952 /*****************************************************************************/
4953 /*                                                                           */
4954 /*  fast_expansion_sum_zeroelim()   Sum two expansions, eliminating zero     */
4955 /*                                  components from the output expansion.    */
4956 /*                                                                           */
4957 /*  Sets h = e + f.  See my Robust Predicates paper for details.             */
4958 /*                                                                           */
4959 /*  If round-to-even is used (as with IEEE 754), maintains the strongly      */
4960 /*  nonoverlapping property.  (That is, if e is strongly nonoverlapping, h   */
4961 /*  will be also.)  Does NOT maintain the nonoverlapping or nonadjacent      */
4962 /*  properties.                                                              */
4963 /*                                                                           */
4964 /*****************************************************************************/
4965 
4966 #ifdef ANSI_DECLARATORS
4967 int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h)
4968 #else /* not ANSI_DECLARATORS */
4969 int fast_expansion_sum_zeroelim(elen, e, flen, f, h)  /* h cannot be e or f. */
4970 int elen;
4971 REAL *e;
4972 int flen;
4973 REAL *f;
4974 REAL *h;
4975 #endif /* not ANSI_DECLARATORS */
4976 
4977 {
4978   REAL Q;
4979   INEXACT REAL Qnew;
4980   INEXACT REAL hh;
4981   INEXACT REAL bvirt;
4982   REAL avirt, bround, around;
4983   int eindex, findex, hindex;
4984   REAL enow, fnow;
4985 
4986   enow = e[0];
4987   fnow = f[0];
4988   eindex = findex = 0;
4989   if ((fnow > enow) == (fnow > -enow)) {
4990     Q = enow;
4991     enow = e[++eindex];
4992   } else {
4993     Q = fnow;
4994     fnow = f[++findex];
4995   }
4996   hindex = 0;
4997   if ((eindex < elen) && (findex < flen)) {
4998     if ((fnow > enow) == (fnow > -enow)) {
4999       Fast_Two_Sum(enow, Q, Qnew, hh);
5000       enow = e[++eindex];
5001     } else {
5002       Fast_Two_Sum(fnow, Q, Qnew, hh);
5003       fnow = f[++findex];
5004     }
5005     Q = Qnew;
5006     if (hh != 0.0) {
5007       h[hindex++] = hh;
5008     }
5009     while ((eindex < elen) && (findex < flen)) {
5010       if ((fnow > enow) == (fnow > -enow)) {
5011         Two_Sum(Q, enow, Qnew, hh);
5012         enow = e[++eindex];
5013       } else {
5014         Two_Sum(Q, fnow, Qnew, hh);
5015         fnow = f[++findex];
5016       }
5017       Q = Qnew;
5018       if (hh != 0.0) {
5019         h[hindex++] = hh;
5020       }
5021     }
5022   }
5023   while (eindex < elen) {
5024     Two_Sum(Q, enow, Qnew, hh);
5025     enow = e[++eindex];
5026     Q = Qnew;
5027     if (hh != 0.0) {
5028       h[hindex++] = hh;
5029     }
5030   }
5031   while (findex < flen) {
5032     Two_Sum(Q, fnow, Qnew, hh);
5033     fnow = f[++findex];
5034     Q = Qnew;
5035     if (hh != 0.0) {
5036       h[hindex++] = hh;
5037     }
5038   }
5039   if ((Q != 0.0) || (hindex == 0)) {
5040     h[hindex++] = Q;
5041   }
5042   return hindex;
5043 }
5044 
5045 /*****************************************************************************/
5046 /*                                                                           */
5047 /*  scale_expansion_zeroelim()   Multiply an expansion by a scalar,          */
5048 /*                               eliminating zero components from the        */
5049 /*                               output expansion.                           */
5050 /*                                                                           */
5051 /*  Sets h = be.  See my Robust Predicates paper for details.                */
5052 /*                                                                           */
5053 /*  Maintains the nonoverlapping property.  If round-to-even is used (as     */
5054 /*  with IEEE 754), maintains the strongly nonoverlapping and nonadjacent    */
5055 /*  properties as well.  (That is, if e has one of these properties, so      */
5056 /*  will h.)                                                                 */
5057 /*                                                                           */
5058 /*****************************************************************************/
5059 
5060 #ifdef ANSI_DECLARATORS
5061 int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h)
5062 #else /* not ANSI_DECLARATORS */
5063 int scale_expansion_zeroelim(elen, e, b, h)   /* e and h cannot be the same. */
5064 int elen;
5065 REAL *e;
5066 REAL b;
5067 REAL *h;
5068 #endif /* not ANSI_DECLARATORS */
5069 
5070 {
5071   INEXACT REAL Q, sum;
5072   REAL hh;
5073   INEXACT REAL product1;
5074   REAL product0;
5075   int eindex, hindex;
5076   REAL enow;
5077   INEXACT REAL bvirt;
5078   REAL avirt, bround, around;
5079   INEXACT REAL c;
5080   INEXACT REAL abig;
5081   REAL ahi, alo, bhi, blo;
5082   REAL err1, err2, err3;
5083 
5084   Split(b, bhi, blo);
5085   Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
5086   hindex = 0;
5087   if (hh != 0) {
5088     h[hindex++] = hh;
5089   }
5090   for (eindex = 1; eindex < elen; eindex++) {
5091     enow = e[eindex];
5092     Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
5093     Two_Sum(Q, product0, sum, hh);
5094     if (hh != 0) {
5095       h[hindex++] = hh;
5096     }
5097     Fast_Two_Sum(product1, sum, Q, hh);
5098     if (hh != 0) {
5099       h[hindex++] = hh;
5100     }
5101   }
5102   if ((Q != 0.0) || (hindex == 0)) {
5103     h[hindex++] = Q;
5104   }
5105   return hindex;
5106 }
5107 
5108 /*****************************************************************************/
5109 /*                                                                           */
5110 /*  estimate()   Produce a one-word estimate of an expansion's value.        */
5111 /*                                                                           */
5112 /*  See my Robust Predicates paper for details.                              */
5113 /*                                                                           */
5114 /*****************************************************************************/
5115 
5116 #ifdef ANSI_DECLARATORS
5117 REAL estimate(int elen, REAL *e)
5118 #else /* not ANSI_DECLARATORS */
5119 REAL estimate(elen, e)
5120 int elen;
5121 REAL *e;
5122 #endif /* not ANSI_DECLARATORS */
5123 
5124 {
5125   REAL Q;
5126   int eindex;
5127 
5128   Q = e[0];
5129   for (eindex = 1; eindex < elen; eindex++) {
5130     Q += e[eindex];
5131   }
5132   return Q;
5133 }
5134 
5135 /*****************************************************************************/
5136 /*                                                                           */
5137 /*  counterclockwise()   Return a positive value if the points pa, pb, and   */
5138 /*                       pc occur in counterclockwise order; a negative      */
5139 /*                       value if they occur in clockwise order; and zero    */
5140 /*                       if they are collinear.  The result is also a rough  */
5141 /*                       approximation of twice the signed area of the       */
5142 /*                       triangle defined by the three points.               */
5143 /*                                                                           */
5144 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5145 /*  result returned is the determinant of a matrix.  This determinant is     */
5146 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5147 /*  the degree it is needed to ensure that the returned value has the        */
5148 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5149 /*  more slowly when the input points are collinear or nearly so.            */
5150 /*                                                                           */
5151 /*  See my Robust Predicates paper for details.                              */
5152 /*                                                                           */
5153 /*****************************************************************************/
5154 
5155 #ifdef ANSI_DECLARATORS
5156 REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum)
5157 #else /* not ANSI_DECLARATORS */
5158 REAL counterclockwiseadapt(pa, pb, pc, detsum)
5159 vertex pa;
5160 vertex pb;
5161 vertex pc;
5162 REAL detsum;
5163 #endif /* not ANSI_DECLARATORS */
5164 
5165 {
5166   INEXACT REAL acx, acy, bcx, bcy;
5167   REAL acxtail, acytail, bcxtail, bcytail;
5168   INEXACT REAL detleft, detright;
5169   REAL detlefttail, detrighttail;
5170   REAL det, errbound;
5171   REAL B[4], C1[8], C2[12], D[16];
5172   INEXACT REAL B3;
5173   int C1length, C2length, Dlength;
5174   REAL u[4];
5175   INEXACT REAL u3;
5176   INEXACT REAL s1, t1;
5177   REAL s0, t0;
5178 
5179   INEXACT REAL bvirt;
5180   REAL avirt, bround, around;
5181   INEXACT REAL c;
5182   INEXACT REAL abig;
5183   REAL ahi, alo, bhi, blo;
5184   REAL err1, err2, err3;
5185   INEXACT REAL _i, _j;
5186   REAL _0;
5187 
5188   acx = (REAL) (pa[0] - pc[0]);
5189   bcx = (REAL) (pb[0] - pc[0]);
5190   acy = (REAL) (pa[1] - pc[1]);
5191   bcy = (REAL) (pb[1] - pc[1]);
5192 
5193   Two_Product(acx, bcy, detleft, detlefttail);
5194   Two_Product(acy, bcx, detright, detrighttail);
5195 
5196   Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
5197                B3, B[2], B[1], B[0]);
5198   B[3] = B3;
5199 
5200   det = estimate(4, B);
5201   errbound = ccwerrboundB * detsum;
5202   if ((det >= errbound) || (-det >= errbound)) {
5203     return det;
5204   }
5205 
5206   Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
5207   Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
5208   Two_Diff_Tail(pa[1], pc[1], acy, acytail);
5209   Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
5210 
5211   if ((acxtail == 0.0) && (acytail == 0.0)
5212       && (bcxtail == 0.0) && (bcytail == 0.0)) {
5213     return det;
5214   }
5215 
5216   errbound = ccwerrboundC * detsum + resulterrbound * Absolute(det);
5217   det += (acx * bcytail + bcy * acxtail)
5218        - (acy * bcxtail + bcx * acytail);
5219   if ((det >= errbound) || (-det >= errbound)) {
5220     return det;
5221   }
5222 
5223   Two_Product(acxtail, bcy, s1, s0);
5224   Two_Product(acytail, bcx, t1, t0);
5225   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5226   u[3] = u3;
5227   C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
5228 
5229   Two_Product(acx, bcytail, s1, s0);
5230   Two_Product(acy, bcxtail, t1, t0);
5231   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5232   u[3] = u3;
5233   C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
5234 
5235   Two_Product(acxtail, bcytail, s1, s0);
5236   Two_Product(acytail, bcxtail, t1, t0);
5237   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
5238   u[3] = u3;
5239   Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
5240 
5241   return(D[Dlength - 1]);
5242 }
5243 
5244 #ifdef ANSI_DECLARATORS
5245 REAL counterclockwise(struct mesh *m, struct behavior *b,
5246                       vertex pa, vertex pb, vertex pc)
5247 #else /* not ANSI_DECLARATORS */
5248 REAL counterclockwise(m, b, pa, pb, pc)
5249 struct mesh *m;
5250 struct behavior *b;
5251 vertex pa;
5252 vertex pb;
5253 vertex pc;
5254 #endif /* not ANSI_DECLARATORS */
5255 
5256 {
5257   REAL detleft, detright, det;
5258   REAL detsum, errbound;
5259 
5260   m->counterclockcount++;
5261 
5262   detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
5263   detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
5264   det = detleft - detright;
5265 
5266   if (b->noexact) {
5267     return det;
5268   }
5269 
5270   if (detleft > 0.0) {
5271     if (detright <= 0.0) {
5272       return det;
5273     } else {
5274       detsum = detleft + detright;
5275     }
5276   } else if (detleft < 0.0) {
5277     if (detright >= 0.0) {
5278       return det;
5279     } else {
5280       detsum = -detleft - detright;
5281     }
5282   } else {
5283     return det;
5284   }
5285 
5286   errbound = ccwerrboundA * detsum;
5287   if ((det >= errbound) || (-det >= errbound)) {
5288     return det;
5289   }
5290 
5291   return counterclockwiseadapt(pa, pb, pc, detsum);
5292 }
5293 
5294 /*****************************************************************************/
5295 /*                                                                           */
5296 /*  incircle()   Return a positive value if the point pd lies inside the     */
5297 /*               circle passing through pa, pb, and pc; a negative value if  */
5298 /*               it lies outside; and zero if the four points are cocircular.*/
5299 /*               The points pa, pb, and pc must be in counterclockwise       */
5300 /*               order, or the sign of the result will be reversed.          */
5301 /*                                                                           */
5302 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5303 /*  result returned is the determinant of a matrix.  This determinant is     */
5304 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5305 /*  the degree it is needed to ensure that the returned value has the        */
5306 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5307 /*  more slowly when the input points are cocircular or nearly so.           */
5308 /*                                                                           */
5309 /*  See my Robust Predicates paper for details.                              */
5310 /*                                                                           */
5311 /*****************************************************************************/
5312 
5313 #ifdef ANSI_DECLARATORS
5314 REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent)
5315 #else /* not ANSI_DECLARATORS */
5316 REAL incircleadapt(pa, pb, pc, pd, permanent)
5317 vertex pa;
5318 vertex pb;
5319 vertex pc;
5320 vertex pd;
5321 REAL permanent;
5322 #endif /* not ANSI_DECLARATORS */
5323 
5324 {
5325   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
5326   REAL det, errbound;
5327 
5328   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
5329   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
5330   REAL bc[4], ca[4], ab[4];
5331   INEXACT REAL bc3, ca3, ab3;
5332   REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
5333   int axbclen, axxbclen, aybclen, ayybclen, alen;
5334   REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
5335   int bxcalen, bxxcalen, bycalen, byycalen, blen;
5336   REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
5337   int cxablen, cxxablen, cyablen, cyyablen, clen;
5338   REAL abdet[64];
5339   int ablen;
5340   REAL fin1[1152], fin2[1152];
5341   REAL *finnow, *finother, *finswap;
5342   int finlength;
5343 
5344   REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
5345   INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
5346   REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
5347   REAL aa[4], bb[4], cc[4];
5348   INEXACT REAL aa3, bb3, cc3;
5349   INEXACT REAL ti1, tj1;
5350   REAL ti0, tj0;
5351   REAL u[4], v[4];
5352   INEXACT REAL u3, v3;
5353   REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
5354   REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
5355   int temp8len, temp16alen, temp16blen, temp16clen;
5356   int temp32alen, temp32blen, temp48len, temp64len;
5357   REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
5358   int axtbblen, axtcclen, aytbblen, aytcclen;
5359   REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
5360   int bxtaalen, bxtcclen, bytaalen, bytcclen;
5361   REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
5362   int cxtaalen, cxtbblen, cytaalen, cytbblen;
5363   REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
5364   int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen;
5365   REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
5366   int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
5367   REAL axtbctt[8], aytbctt[8], bxtcatt[8];
5368   REAL bytcatt[8], cxtabtt[8], cytabtt[8];
5369   int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
5370   REAL abt[8], bct[8], cat[8];
5371   int abtlen, bctlen, catlen;
5372   REAL abtt[4], bctt[4], catt[4];
5373   int abttlen, bcttlen, cattlen;
5374   INEXACT REAL abtt3, bctt3, catt3;
5375   REAL negate;
5376 
5377   INEXACT REAL bvirt;
5378   REAL avirt, bround, around;
5379   INEXACT REAL c;
5380   INEXACT REAL abig;
5381   REAL ahi, alo, bhi, blo;
5382   REAL err1, err2, err3;
5383   INEXACT REAL _i, _j;
5384   REAL _0;
5385 
5386   adx = (REAL) (pa[0] - pd[0]);
5387   bdx = (REAL) (pb[0] - pd[0]);
5388   cdx = (REAL) (pc[0] - pd[0]);
5389   ady = (REAL) (pa[1] - pd[1]);
5390   bdy = (REAL) (pb[1] - pd[1]);
5391   cdy = (REAL) (pc[1] - pd[1]);
5392 
5393   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
5394   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
5395   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
5396   bc[3] = bc3;
5397   axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
5398   axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
5399   aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
5400   ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
5401   alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
5402 
5403   Two_Product(cdx, ady, cdxady1, cdxady0);
5404   Two_Product(adx, cdy, adxcdy1, adxcdy0);
5405   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
5406   ca[3] = ca3;
5407   bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
5408   bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
5409   bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
5410   byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
5411   blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
5412 
5413   Two_Product(adx, bdy, adxbdy1, adxbdy0);
5414   Two_Product(bdx, ady, bdxady1, bdxady0);
5415   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
5416   ab[3] = ab3;
5417   cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
5418   cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
5419   cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
5420   cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
5421   clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
5422 
5423   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
5424   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
5425 
5426   det = estimate(finlength, fin1);
5427   errbound = iccerrboundB * permanent;
5428   if ((det >= errbound) || (-det >= errbound)) {
5429     return det;
5430   }
5431 
5432   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
5433   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
5434   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
5435   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
5436   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
5437   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
5438   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
5439       && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
5440     return det;
5441   }
5442 
5443   errbound = iccerrboundC * permanent + resulterrbound * Absolute(det);
5444   det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
5445                                      - (bdy * cdxtail + cdx * bdytail))
5446           + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
5447        + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
5448                                      - (cdy * adxtail + adx * cdytail))
5449           + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
5450        + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
5451                                      - (ady * bdxtail + bdx * adytail))
5452           + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
5453   if ((det >= errbound) || (-det >= errbound)) {
5454     return det;
5455   }
5456 
5457   finnow = fin1;
5458   finother = fin2;
5459 
5460   if ((bdxtail != 0.0) || (bdytail != 0.0)
5461       || (cdxtail != 0.0) || (cdytail != 0.0)) {
5462     Square(adx, adxadx1, adxadx0);
5463     Square(ady, adyady1, adyady0);
5464     Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
5465     aa[3] = aa3;
5466   }
5467   if ((cdxtail != 0.0) || (cdytail != 0.0)
5468       || (adxtail != 0.0) || (adytail != 0.0)) {
5469     Square(bdx, bdxbdx1, bdxbdx0);
5470     Square(bdy, bdybdy1, bdybdy0);
5471     Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
5472     bb[3] = bb3;
5473   }
5474   if ((adxtail != 0.0) || (adytail != 0.0)
5475       || (bdxtail != 0.0) || (bdytail != 0.0)) {
5476     Square(cdx, cdxcdx1, cdxcdx0);
5477     Square(cdy, cdycdy1, cdycdy0);
5478     Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
5479     cc[3] = cc3;
5480   }
5481 
5482   if (adxtail != 0.0) {
5483     axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
5484     temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
5485                                           temp16a);
5486 
5487     axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
5488     temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
5489 
5490     axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
5491     temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
5492 
5493     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5494                                             temp16blen, temp16b, temp32a);
5495     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5496                                             temp32alen, temp32a, temp48);
5497     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5498                                             temp48, finother);
5499     finswap = finnow; finnow = finother; finother = finswap;
5500   }
5501   if (adytail != 0.0) {
5502     aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
5503     temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
5504                                           temp16a);
5505 
5506     aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
5507     temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
5508 
5509     aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
5510     temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
5511 
5512     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5513                                             temp16blen, temp16b, temp32a);
5514     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5515                                             temp32alen, temp32a, temp48);
5516     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5517                                             temp48, finother);
5518     finswap = finnow; finnow = finother; finother = finswap;
5519   }
5520   if (bdxtail != 0.0) {
5521     bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
5522     temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
5523                                           temp16a);
5524 
5525     bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
5526     temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
5527 
5528     bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
5529     temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
5530 
5531     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5532                                             temp16blen, temp16b, temp32a);
5533     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5534                                             temp32alen, temp32a, temp48);
5535     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5536                                             temp48, finother);
5537     finswap = finnow; finnow = finother; finother = finswap;
5538   }
5539   if (bdytail != 0.0) {
5540     bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
5541     temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
5542                                           temp16a);
5543 
5544     bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
5545     temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
5546 
5547     bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
5548     temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
5549 
5550     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5551                                             temp16blen, temp16b, temp32a);
5552     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5553                                             temp32alen, temp32a, temp48);
5554     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5555                                             temp48, finother);
5556     finswap = finnow; finnow = finother; finother = finswap;
5557   }
5558   if (cdxtail != 0.0) {
5559     cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
5560     temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
5561                                           temp16a);
5562 
5563     cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
5564     temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
5565 
5566     cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
5567     temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
5568 
5569     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5570                                             temp16blen, temp16b, temp32a);
5571     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5572                                             temp32alen, temp32a, temp48);
5573     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5574                                             temp48, finother);
5575     finswap = finnow; finnow = finother; finother = finswap;
5576   }
5577   if (cdytail != 0.0) {
5578     cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
5579     temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
5580                                           temp16a);
5581 
5582     cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
5583     temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
5584 
5585     cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
5586     temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
5587 
5588     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5589                                             temp16blen, temp16b, temp32a);
5590     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
5591                                             temp32alen, temp32a, temp48);
5592     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5593                                             temp48, finother);
5594     finswap = finnow; finnow = finother; finother = finswap;
5595   }
5596 
5597   if ((adxtail != 0.0) || (adytail != 0.0)) {
5598     if ((bdxtail != 0.0) || (bdytail != 0.0)
5599         || (cdxtail != 0.0) || (cdytail != 0.0)) {
5600       Two_Product(bdxtail, cdy, ti1, ti0);
5601       Two_Product(bdx, cdytail, tj1, tj0);
5602       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5603       u[3] = u3;
5604       negate = -bdy;
5605       Two_Product(cdxtail, negate, ti1, ti0);
5606       negate = -bdytail;
5607       Two_Product(cdx, negate, tj1, tj0);
5608       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5609       v[3] = v3;
5610       bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
5611 
5612       Two_Product(bdxtail, cdytail, ti1, ti0);
5613       Two_Product(cdxtail, bdytail, tj1, tj0);
5614       Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
5615       bctt[3] = bctt3;
5616       bcttlen = 4;
5617     } else {
5618       bct[0] = 0.0;
5619       bctlen = 1;
5620       bctt[0] = 0.0;
5621       bcttlen = 1;
5622     }
5623 
5624     if (adxtail != 0.0) {
5625       temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
5626       axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
5627       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
5628                                             temp32a);
5629       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5630                                               temp32alen, temp32a, temp48);
5631       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5632                                               temp48, finother);
5633       finswap = finnow; finnow = finother; finother = finswap;
5634       if (bdytail != 0.0) {
5635         temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
5636         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5637                                               temp16a);
5638         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5639                                                 temp16a, finother);
5640         finswap = finnow; finnow = finother; finother = finswap;
5641       }
5642       if (cdytail != 0.0) {
5643         temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
5644         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5645                                               temp16a);
5646         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5647                                                 temp16a, finother);
5648         finswap = finnow; finnow = finother; finother = finswap;
5649       }
5650 
5651       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
5652                                             temp32a);
5653       axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
5654       temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
5655                                             temp16a);
5656       temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
5657                                             temp16b);
5658       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5659                                               temp16blen, temp16b, temp32b);
5660       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5661                                               temp32blen, temp32b, temp64);
5662       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5663                                               temp64, finother);
5664       finswap = finnow; finnow = finother; finother = finswap;
5665     }
5666     if (adytail != 0.0) {
5667       temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
5668       aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
5669       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
5670                                             temp32a);
5671       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5672                                               temp32alen, temp32a, temp48);
5673       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5674                                               temp48, finother);
5675       finswap = finnow; finnow = finother; finother = finswap;
5676 
5677 
5678       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
5679                                             temp32a);
5680       aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
5681       temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
5682                                             temp16a);
5683       temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
5684                                             temp16b);
5685       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5686                                               temp16blen, temp16b, temp32b);
5687       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5688                                               temp32blen, temp32b, temp64);
5689       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5690                                               temp64, finother);
5691       finswap = finnow; finnow = finother; finother = finswap;
5692     }
5693   }
5694   if ((bdxtail != 0.0) || (bdytail != 0.0)) {
5695     if ((cdxtail != 0.0) || (cdytail != 0.0)
5696         || (adxtail != 0.0) || (adytail != 0.0)) {
5697       Two_Product(cdxtail, ady, ti1, ti0);
5698       Two_Product(cdx, adytail, tj1, tj0);
5699       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5700       u[3] = u3;
5701       negate = -cdy;
5702       Two_Product(adxtail, negate, ti1, ti0);
5703       negate = -cdytail;
5704       Two_Product(adx, negate, tj1, tj0);
5705       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5706       v[3] = v3;
5707       catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
5708 
5709       Two_Product(cdxtail, adytail, ti1, ti0);
5710       Two_Product(adxtail, cdytail, tj1, tj0);
5711       Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
5712       catt[3] = catt3;
5713       cattlen = 4;
5714     } else {
5715       cat[0] = 0.0;
5716       catlen = 1;
5717       catt[0] = 0.0;
5718       cattlen = 1;
5719     }
5720 
5721     if (bdxtail != 0.0) {
5722       temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
5723       bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
5724       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
5725                                             temp32a);
5726       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5727                                               temp32alen, temp32a, temp48);
5728       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5729                                               temp48, finother);
5730       finswap = finnow; finnow = finother; finother = finswap;
5731       if (cdytail != 0.0) {
5732         temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
5733         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
5734                                               temp16a);
5735         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5736                                                 temp16a, finother);
5737         finswap = finnow; finnow = finother; finother = finswap;
5738       }
5739       if (adytail != 0.0) {
5740         temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
5741         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5742                                               temp16a);
5743         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5744                                                 temp16a, finother);
5745         finswap = finnow; finnow = finother; finother = finswap;
5746       }
5747 
5748       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
5749                                             temp32a);
5750       bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
5751       temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
5752                                             temp16a);
5753       temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
5754                                             temp16b);
5755       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5756                                               temp16blen, temp16b, temp32b);
5757       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5758                                               temp32blen, temp32b, temp64);
5759       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5760                                               temp64, finother);
5761       finswap = finnow; finnow = finother; finother = finswap;
5762     }
5763     if (bdytail != 0.0) {
5764       temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
5765       bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
5766       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
5767                                             temp32a);
5768       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5769                                               temp32alen, temp32a, temp48);
5770       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5771                                               temp48, finother);
5772       finswap = finnow; finnow = finother; finother = finswap;
5773 
5774 
5775       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
5776                                             temp32a);
5777       bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
5778       temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
5779                                             temp16a);
5780       temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
5781                                             temp16b);
5782       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5783                                               temp16blen, temp16b, temp32b);
5784       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5785                                               temp32blen, temp32b, temp64);
5786       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5787                                               temp64, finother);
5788       finswap = finnow; finnow = finother; finother = finswap;
5789     }
5790   }
5791   if ((cdxtail != 0.0) || (cdytail != 0.0)) {
5792     if ((adxtail != 0.0) || (adytail != 0.0)
5793         || (bdxtail != 0.0) || (bdytail != 0.0)) {
5794       Two_Product(adxtail, bdy, ti1, ti0);
5795       Two_Product(adx, bdytail, tj1, tj0);
5796       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
5797       u[3] = u3;
5798       negate = -ady;
5799       Two_Product(bdxtail, negate, ti1, ti0);
5800       negate = -adytail;
5801       Two_Product(bdx, negate, tj1, tj0);
5802       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
5803       v[3] = v3;
5804       abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
5805 
5806       Two_Product(adxtail, bdytail, ti1, ti0);
5807       Two_Product(bdxtail, adytail, tj1, tj0);
5808       Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
5809       abtt[3] = abtt3;
5810       abttlen = 4;
5811     } else {
5812       abt[0] = 0.0;
5813       abtlen = 1;
5814       abtt[0] = 0.0;
5815       abttlen = 1;
5816     }
5817 
5818     if (cdxtail != 0.0) {
5819       temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
5820       cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
5821       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
5822                                             temp32a);
5823       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5824                                               temp32alen, temp32a, temp48);
5825       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5826                                               temp48, finother);
5827       finswap = finnow; finnow = finother; finother = finswap;
5828       if (adytail != 0.0) {
5829         temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
5830         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
5831                                               temp16a);
5832         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5833                                                 temp16a, finother);
5834         finswap = finnow; finnow = finother; finother = finswap;
5835       }
5836       if (bdytail != 0.0) {
5837         temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
5838         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
5839                                               temp16a);
5840         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
5841                                                 temp16a, finother);
5842         finswap = finnow; finnow = finother; finother = finswap;
5843       }
5844 
5845       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
5846                                             temp32a);
5847       cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
5848       temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
5849                                             temp16a);
5850       temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
5851                                             temp16b);
5852       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5853                                               temp16blen, temp16b, temp32b);
5854       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5855                                               temp32blen, temp32b, temp64);
5856       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5857                                               temp64, finother);
5858       finswap = finnow; finnow = finother; finother = finswap;
5859     }
5860     if (cdytail != 0.0) {
5861       temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
5862       cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
5863       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
5864                                             temp32a);
5865       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5866                                               temp32alen, temp32a, temp48);
5867       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
5868                                               temp48, finother);
5869       finswap = finnow; finnow = finother; finother = finswap;
5870 
5871 
5872       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
5873                                             temp32a);
5874       cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
5875       temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
5876                                             temp16a);
5877       temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
5878                                             temp16b);
5879       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
5880                                               temp16blen, temp16b, temp32b);
5881       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
5882                                               temp32blen, temp32b, temp64);
5883       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
5884                                               temp64, finother);
5885       finswap = finnow; finnow = finother; finother = finswap;
5886     }
5887   }
5888 
5889   return finnow[finlength - 1];
5890 }
5891 
5892 #ifdef ANSI_DECLARATORS
5893 REAL incircle(struct mesh *m, struct behavior *b,
5894               vertex pa, vertex pb, vertex pc, vertex pd)
5895 #else /* not ANSI_DECLARATORS */
5896 REAL incircle(m, b, pa, pb, pc, pd)
5897 struct mesh *m;
5898 struct behavior *b;
5899 vertex pa;
5900 vertex pb;
5901 vertex pc;
5902 vertex pd;
5903 #endif /* not ANSI_DECLARATORS */
5904 
5905 {
5906   REAL adx, bdx, cdx, ady, bdy, cdy;
5907   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
5908   REAL alift, blift, clift;
5909   REAL det;
5910   REAL permanent, errbound;
5911 
5912   m->incirclecount++;
5913 
5914   adx = pa[0] - pd[0];
5915   bdx = pb[0] - pd[0];
5916   cdx = pc[0] - pd[0];
5917   ady = pa[1] - pd[1];
5918   bdy = pb[1] - pd[1];
5919   cdy = pc[1] - pd[1];
5920 
5921   bdxcdy = bdx * cdy;
5922   cdxbdy = cdx * bdy;
5923   alift = adx * adx + ady * ady;
5924 
5925   cdxady = cdx * ady;
5926   adxcdy = adx * cdy;
5927   blift = bdx * bdx + bdy * bdy;
5928 
5929   adxbdy = adx * bdy;
5930   bdxady = bdx * ady;
5931   clift = cdx * cdx + cdy * cdy;
5932 
5933   det = alift * (bdxcdy - cdxbdy)
5934       + blift * (cdxady - adxcdy)
5935       + clift * (adxbdy - bdxady);
5936 
5937   if (b->noexact) {
5938     return det;
5939   }
5940 
5941   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
5942             + (Absolute(cdxady) + Absolute(adxcdy)) * blift
5943             + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
5944   errbound = iccerrboundA * permanent;
5945   if ((det > errbound) || (-det > errbound)) {
5946     return det;
5947   }
5948 
5949   return incircleadapt(pa, pb, pc, pd, permanent);
5950 }
5951 
5952 /*****************************************************************************/
5953 /*                                                                           */
5954 /*  orient3d()   Return a positive value if the point pd lies below the      */
5955 /*               plane passing through pa, pb, and pc; "below" is defined so */
5956 /*               that pa, pb, and pc appear in counterclockwise order when   */
5957 /*               viewed from above the plane.  Returns a negative value if   */
5958 /*               pd lies above the plane.  Returns zero if the points are    */
5959 /*               coplanar.  The result is also a rough approximation of six  */
5960 /*               times the signed volume of the tetrahedron defined by the   */
5961 /*               four points.                                                */
5962 /*                                                                           */
5963 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
5964 /*  result returned is the determinant of a matrix.  This determinant is     */
5965 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
5966 /*  the degree it is needed to ensure that the returned value has the        */
5967 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
5968 /*  more slowly when the input points are coplanar or nearly so.             */
5969 /*                                                                           */
5970 /*  See my Robust Predicates paper for details.                              */
5971 /*                                                                           */
5972 /*****************************************************************************/
5973 
5974 #ifdef ANSI_DECLARATORS
5975 REAL orient3dadapt(vertex pa, vertex pb, vertex pc, vertex pd,
5976                    REAL aheight, REAL bheight, REAL cheight, REAL dheight,
5977                    REAL permanent)
5978 #else /* not ANSI_DECLARATORS */
5979 REAL orient3dadapt(pa, pb, pc, pd,
5980                    aheight, bheight, cheight, dheight, permanent)
5981 vertex pa;
5982 vertex pb;
5983 vertex pc;
5984 vertex pd;
5985 REAL aheight;
5986 REAL bheight;
5987 REAL cheight;
5988 REAL dheight;
5989 REAL permanent;
5990 #endif /* not ANSI_DECLARATORS */
5991 
5992 {
5993   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
5994   REAL det, errbound;
5995 
5996   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
5997   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
5998   REAL bc[4], ca[4], ab[4];
5999   INEXACT REAL bc3, ca3, ab3;
6000   REAL adet[8], bdet[8], cdet[8];
6001   int alen, blen, clen;
6002   REAL abdet[16];
6003   int ablen;
6004   REAL *finnow, *finother, *finswap;
6005   REAL fin1[192], fin2[192];
6006   int finlength;
6007 
6008   REAL adxtail, bdxtail, cdxtail;
6009   REAL adytail, bdytail, cdytail;
6010   REAL adheighttail, bdheighttail, cdheighttail;
6011   INEXACT REAL at_blarge, at_clarge;
6012   INEXACT REAL bt_clarge, bt_alarge;
6013   INEXACT REAL ct_alarge, ct_blarge;
6014   REAL at_b[4], at_c[4], bt_c[4], bt_a[4], ct_a[4], ct_b[4];
6015   int at_blen, at_clen, bt_clen, bt_alen, ct_alen, ct_blen;
6016   INEXACT REAL bdxt_cdy1, cdxt_bdy1, cdxt_ady1;
6017   INEXACT REAL adxt_cdy1, adxt_bdy1, bdxt_ady1;
6018   REAL bdxt_cdy0, cdxt_bdy0, cdxt_ady0;
6019   REAL adxt_cdy0, adxt_bdy0, bdxt_ady0;
6020   INEXACT REAL bdyt_cdx1, cdyt_bdx1, cdyt_adx1;
6021   INEXACT REAL adyt_cdx1, adyt_bdx1, bdyt_adx1;
6022   REAL bdyt_cdx0, cdyt_bdx0, cdyt_adx0;
6023   REAL adyt_cdx0, adyt_bdx0, bdyt_adx0;
6024   REAL bct[8], cat[8], abt[8];
6025   int bctlen, catlen, abtlen;
6026   INEXACT REAL bdxt_cdyt1, cdxt_bdyt1, cdxt_adyt1;
6027   INEXACT REAL adxt_cdyt1, adxt_bdyt1, bdxt_adyt1;
6028   REAL bdxt_cdyt0, cdxt_bdyt0, cdxt_adyt0;
6029   REAL adxt_cdyt0, adxt_bdyt0, bdxt_adyt0;
6030   REAL u[4], v[12], w[16];
6031   INEXACT REAL u3;
6032   int vlength, wlength;
6033   REAL negate;
6034 
6035   INEXACT REAL bvirt;
6036   REAL avirt, bround, around;
6037   INEXACT REAL c;
6038   INEXACT REAL abig;
6039   REAL ahi, alo, bhi, blo;
6040   REAL err1, err2, err3;
6041   INEXACT REAL _i, _j, _k;
6042   REAL _0;
6043 
6044   adx = (REAL) (pa[0] - pd[0]);
6045   bdx = (REAL) (pb[0] - pd[0]);
6046   cdx = (REAL) (pc[0] - pd[0]);
6047   ady = (REAL) (pa[1] - pd[1]);
6048   bdy = (REAL) (pb[1] - pd[1]);
6049   cdy = (REAL) (pc[1] - pd[1]);
6050   adheight = (REAL) (aheight - dheight);
6051   bdheight = (REAL) (bheight - dheight);
6052   cdheight = (REAL) (cheight - dheight);
6053 
6054   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
6055   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
6056   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
6057   bc[3] = bc3;
6058   alen = scale_expansion_zeroelim(4, bc, adheight, adet);
6059 
6060   Two_Product(cdx, ady, cdxady1, cdxady0);
6061   Two_Product(adx, cdy, adxcdy1, adxcdy0);
6062   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
6063   ca[3] = ca3;
6064   blen = scale_expansion_zeroelim(4, ca, bdheight, bdet);
6065 
6066   Two_Product(adx, bdy, adxbdy1, adxbdy0);
6067   Two_Product(bdx, ady, bdxady1, bdxady0);
6068   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
6069   ab[3] = ab3;
6070   clen = scale_expansion_zeroelim(4, ab, cdheight, cdet);
6071 
6072   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
6073   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
6074 
6075   det = estimate(finlength, fin1);
6076   errbound = o3derrboundB * permanent;
6077   if ((det >= errbound) || (-det >= errbound)) {
6078     return det;
6079   }
6080 
6081   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
6082   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
6083   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
6084   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
6085   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
6086   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
6087   Two_Diff_Tail(aheight, dheight, adheight, adheighttail);
6088   Two_Diff_Tail(bheight, dheight, bdheight, bdheighttail);
6089   Two_Diff_Tail(cheight, dheight, cdheight, cdheighttail);
6090 
6091   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) &&
6092       (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0) &&
6093       (adheighttail == 0.0) &&
6094       (bdheighttail == 0.0) &&
6095       (cdheighttail == 0.0)) {
6096     return det;
6097   }
6098 
6099   errbound = o3derrboundC * permanent + resulterrbound * Absolute(det);
6100   det += (adheight * ((bdx * cdytail + cdy * bdxtail) -
6101                       (bdy * cdxtail + cdx * bdytail)) +
6102           adheighttail * (bdx * cdy - bdy * cdx)) +
6103          (bdheight * ((cdx * adytail + ady * cdxtail) -
6104                       (cdy * adxtail + adx * cdytail)) +
6105           bdheighttail * (cdx * ady - cdy * adx)) +
6106          (cdheight * ((adx * bdytail + bdy * adxtail) -
6107                       (ady * bdxtail + bdx * adytail)) +
6108           cdheighttail * (adx * bdy - ady * bdx));
6109   if ((det >= errbound) || (-det >= errbound)) {
6110     return det;
6111   }
6112 
6113   finnow = fin1;
6114   finother = fin2;
6115 
6116   if (adxtail == 0.0) {
6117     if (adytail == 0.0) {
6118       at_b[0] = 0.0;
6119       at_blen = 1;
6120       at_c[0] = 0.0;
6121       at_clen = 1;
6122     } else {
6123       negate = -adytail;
6124       Two_Product(negate, bdx, at_blarge, at_b[0]);
6125       at_b[1] = at_blarge;
6126       at_blen = 2;
6127       Two_Product(adytail, cdx, at_clarge, at_c[0]);
6128       at_c[1] = at_clarge;
6129       at_clen = 2;
6130     }
6131   } else {
6132     if (adytail == 0.0) {
6133       Two_Product(adxtail, bdy, at_blarge, at_b[0]);
6134       at_b[1] = at_blarge;
6135       at_blen = 2;
6136       negate = -adxtail;
6137       Two_Product(negate, cdy, at_clarge, at_c[0]);
6138       at_c[1] = at_clarge;
6139       at_clen = 2;
6140     } else {
6141       Two_Product(adxtail, bdy, adxt_bdy1, adxt_bdy0);
6142       Two_Product(adytail, bdx, adyt_bdx1, adyt_bdx0);
6143       Two_Two_Diff(adxt_bdy1, adxt_bdy0, adyt_bdx1, adyt_bdx0,
6144                    at_blarge, at_b[2], at_b[1], at_b[0]);
6145       at_b[3] = at_blarge;
6146       at_blen = 4;
6147       Two_Product(adytail, cdx, adyt_cdx1, adyt_cdx0);
6148       Two_Product(adxtail, cdy, adxt_cdy1, adxt_cdy0);
6149       Two_Two_Diff(adyt_cdx1, adyt_cdx0, adxt_cdy1, adxt_cdy0,
6150                    at_clarge, at_c[2], at_c[1], at_c[0]);
6151       at_c[3] = at_clarge;
6152       at_clen = 4;
6153     }
6154   }
6155   if (bdxtail == 0.0) {
6156     if (bdytail == 0.0) {
6157       bt_c[0] = 0.0;
6158       bt_clen = 1;
6159       bt_a[0] = 0.0;
6160       bt_alen = 1;
6161     } else {
6162       negate = -bdytail;
6163       Two_Product(negate, cdx, bt_clarge, bt_c[0]);
6164       bt_c[1] = bt_clarge;
6165       bt_clen = 2;
6166       Two_Product(bdytail, adx, bt_alarge, bt_a[0]);
6167       bt_a[1] = bt_alarge;
6168       bt_alen = 2;
6169     }
6170   } else {
6171     if (bdytail == 0.0) {
6172       Two_Product(bdxtail, cdy, bt_clarge, bt_c[0]);
6173       bt_c[1] = bt_clarge;
6174       bt_clen = 2;
6175       negate = -bdxtail;
6176       Two_Product(negate, ady, bt_alarge, bt_a[0]);
6177       bt_a[1] = bt_alarge;
6178       bt_alen = 2;
6179     } else {
6180       Two_Product(bdxtail, cdy, bdxt_cdy1, bdxt_cdy0);
6181       Two_Product(bdytail, cdx, bdyt_cdx1, bdyt_cdx0);
6182       Two_Two_Diff(bdxt_cdy1, bdxt_cdy0, bdyt_cdx1, bdyt_cdx0,
6183                    bt_clarge, bt_c[2], bt_c[1], bt_c[0]);
6184       bt_c[3] = bt_clarge;
6185       bt_clen = 4;
6186       Two_Product(bdytail, adx, bdyt_adx1, bdyt_adx0);
6187       Two_Product(bdxtail, ady, bdxt_ady1, bdxt_ady0);
6188       Two_Two_Diff(bdyt_adx1, bdyt_adx0, bdxt_ady1, bdxt_ady0,
6189                   bt_alarge, bt_a[2], bt_a[1], bt_a[0]);
6190       bt_a[3] = bt_alarge;
6191       bt_alen = 4;
6192     }
6193   }
6194   if (cdxtail == 0.0) {
6195     if (cdytail == 0.0) {
6196       ct_a[0] = 0.0;
6197       ct_alen = 1;
6198       ct_b[0] = 0.0;
6199       ct_blen = 1;
6200     } else {
6201       negate = -cdytail;
6202       Two_Product(negate, adx, ct_alarge, ct_a[0]);
6203       ct_a[1] = ct_alarge;
6204       ct_alen = 2;
6205       Two_Product(cdytail, bdx, ct_blarge, ct_b[0]);
6206       ct_b[1] = ct_blarge;
6207       ct_blen = 2;
6208     }
6209   } else {
6210     if (cdytail == 0.0) {
6211       Two_Product(cdxtail, ady, ct_alarge, ct_a[0]);
6212       ct_a[1] = ct_alarge;
6213       ct_alen = 2;
6214       negate = -cdxtail;
6215       Two_Product(negate, bdy, ct_blarge, ct_b[0]);
6216       ct_b[1] = ct_blarge;
6217       ct_blen = 2;
6218     } else {
6219       Two_Product(cdxtail, ady, cdxt_ady1, cdxt_ady0);
6220       Two_Product(cdytail, adx, cdyt_adx1, cdyt_adx0);
6221       Two_Two_Diff(cdxt_ady1, cdxt_ady0, cdyt_adx1, cdyt_adx0,
6222                    ct_alarge, ct_a[2], ct_a[1], ct_a[0]);
6223       ct_a[3] = ct_alarge;
6224       ct_alen = 4;
6225       Two_Product(cdytail, bdx, cdyt_bdx1, cdyt_bdx0);
6226       Two_Product(cdxtail, bdy, cdxt_bdy1, cdxt_bdy0);
6227       Two_Two_Diff(cdyt_bdx1, cdyt_bdx0, cdxt_bdy1, cdxt_bdy0,
6228                    ct_blarge, ct_b[2], ct_b[1], ct_b[0]);
6229       ct_b[3] = ct_blarge;
6230       ct_blen = 4;
6231     }
6232   }
6233 
6234   bctlen = fast_expansion_sum_zeroelim(bt_clen, bt_c, ct_blen, ct_b, bct);
6235   wlength = scale_expansion_zeroelim(bctlen, bct, adheight, w);
6236   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6237                                           finother);
6238   finswap = finnow; finnow = finother; finother = finswap;
6239 
6240   catlen = fast_expansion_sum_zeroelim(ct_alen, ct_a, at_clen, at_c, cat);
6241   wlength = scale_expansion_zeroelim(catlen, cat, bdheight, w);
6242   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6243                                           finother);
6244   finswap = finnow; finnow = finother; finother = finswap;
6245 
6246   abtlen = fast_expansion_sum_zeroelim(at_blen, at_b, bt_alen, bt_a, abt);
6247   wlength = scale_expansion_zeroelim(abtlen, abt, cdheight, w);
6248   finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6249                                           finother);
6250   finswap = finnow; finnow = finother; finother = finswap;
6251 
6252   if (adheighttail != 0.0) {
6253     vlength = scale_expansion_zeroelim(4, bc, adheighttail, v);
6254     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6255                                             finother);
6256     finswap = finnow; finnow = finother; finother = finswap;
6257   }
6258   if (bdheighttail != 0.0) {
6259     vlength = scale_expansion_zeroelim(4, ca, bdheighttail, v);
6260     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6261                                             finother);
6262     finswap = finnow; finnow = finother; finother = finswap;
6263   }
6264   if (cdheighttail != 0.0) {
6265     vlength = scale_expansion_zeroelim(4, ab, cdheighttail, v);
6266     finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
6267                                             finother);
6268     finswap = finnow; finnow = finother; finother = finswap;
6269   }
6270 
6271   if (adxtail != 0.0) {
6272     if (bdytail != 0.0) {
6273       Two_Product(adxtail, bdytail, adxt_bdyt1, adxt_bdyt0);
6274       Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheight, u3, u[2], u[1], u[0]);
6275       u[3] = u3;
6276       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6277                                               finother);
6278       finswap = finnow; finnow = finother; finother = finswap;
6279       if (cdheighttail != 0.0) {
6280         Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheighttail,
6281                         u3, u[2], u[1], u[0]);
6282         u[3] = u3;
6283         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6284                                                 finother);
6285         finswap = finnow; finnow = finother; finother = finswap;
6286       }
6287     }
6288     if (cdytail != 0.0) {
6289       negate = -adxtail;
6290       Two_Product(negate, cdytail, adxt_cdyt1, adxt_cdyt0);
6291       Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheight, u3, u[2], u[1], u[0]);
6292       u[3] = u3;
6293       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6294                                               finother);
6295       finswap = finnow; finnow = finother; finother = finswap;
6296       if (bdheighttail != 0.0) {
6297         Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheighttail,
6298                         u3, u[2], u[1], u[0]);
6299         u[3] = u3;
6300         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6301                                                 finother);
6302         finswap = finnow; finnow = finother; finother = finswap;
6303       }
6304     }
6305   }
6306   if (bdxtail != 0.0) {
6307     if (cdytail != 0.0) {
6308       Two_Product(bdxtail, cdytail, bdxt_cdyt1, bdxt_cdyt0);
6309       Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheight, u3, u[2], u[1], u[0]);
6310       u[3] = u3;
6311       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6312                                               finother);
6313       finswap = finnow; finnow = finother; finother = finswap;
6314       if (adheighttail != 0.0) {
6315         Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheighttail,
6316                         u3, u[2], u[1], u[0]);
6317         u[3] = u3;
6318         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6319                                                 finother);
6320         finswap = finnow; finnow = finother; finother = finswap;
6321       }
6322     }
6323     if (adytail != 0.0) {
6324       negate = -bdxtail;
6325       Two_Product(negate, adytail, bdxt_adyt1, bdxt_adyt0);
6326       Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheight, u3, u[2], u[1], u[0]);
6327       u[3] = u3;
6328       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6329                                               finother);
6330       finswap = finnow; finnow = finother; finother = finswap;
6331       if (cdheighttail != 0.0) {
6332         Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheighttail,
6333                         u3, u[2], u[1], u[0]);
6334         u[3] = u3;
6335         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6336                                                 finother);
6337         finswap = finnow; finnow = finother; finother = finswap;
6338       }
6339     }
6340   }
6341   if (cdxtail != 0.0) {
6342     if (adytail != 0.0) {
6343       Two_Product(cdxtail, adytail, cdxt_adyt1, cdxt_adyt0);
6344       Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheight, u3, u[2], u[1], u[0]);
6345       u[3] = u3;
6346       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6347                                               finother);
6348       finswap = finnow; finnow = finother; finother = finswap;
6349       if (bdheighttail != 0.0) {
6350         Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheighttail,
6351                         u3, u[2], u[1], u[0]);
6352         u[3] = u3;
6353         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6354                                                 finother);
6355         finswap = finnow; finnow = finother; finother = finswap;
6356       }
6357     }
6358     if (bdytail != 0.0) {
6359       negate = -cdxtail;
6360       Two_Product(negate, bdytail, cdxt_bdyt1, cdxt_bdyt0);
6361       Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheight, u3, u[2], u[1], u[0]);
6362       u[3] = u3;
6363       finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6364                                               finother);
6365       finswap = finnow; finnow = finother; finother = finswap;
6366       if (adheighttail != 0.0) {
6367         Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheighttail,
6368                         u3, u[2], u[1], u[0]);
6369         u[3] = u3;
6370         finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
6371                                                 finother);
6372         finswap = finnow; finnow = finother; finother = finswap;
6373       }
6374     }
6375   }
6376 
6377   if (adheighttail != 0.0) {
6378     wlength = scale_expansion_zeroelim(bctlen, bct, adheighttail, w);
6379     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6380                                             finother);
6381     finswap = finnow; finnow = finother; finother = finswap;
6382   }
6383   if (bdheighttail != 0.0) {
6384     wlength = scale_expansion_zeroelim(catlen, cat, bdheighttail, w);
6385     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6386                                             finother);
6387     finswap = finnow; finnow = finother; finother = finswap;
6388   }
6389   if (cdheighttail != 0.0) {
6390     wlength = scale_expansion_zeroelim(abtlen, abt, cdheighttail, w);
6391     finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
6392                                             finother);
6393     finswap = finnow; finnow = finother; finother = finswap;
6394   }
6395 
6396   return finnow[finlength - 1];
6397 }
6398 
6399 #ifdef ANSI_DECLARATORS
6400 REAL orient3d(struct mesh *m, struct behavior *b,
6401               vertex pa, vertex pb, vertex pc, vertex pd,
6402               REAL aheight, REAL bheight, REAL cheight, REAL dheight)
6403 #else /* not ANSI_DECLARATORS */
6404 REAL orient3d(m, b, pa, pb, pc, pd, aheight, bheight, cheight, dheight)
6405 struct mesh *m;
6406 struct behavior *b;
6407 vertex pa;
6408 vertex pb;
6409 vertex pc;
6410 vertex pd;
6411 REAL aheight;
6412 REAL bheight;
6413 REAL cheight;
6414 REAL dheight;
6415 #endif /* not ANSI_DECLARATORS */
6416 
6417 {
6418   REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
6419   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
6420   REAL det;
6421   REAL permanent, errbound;
6422 
6423   m->orient3dcount++;
6424 
6425   adx = pa[0] - pd[0];
6426   bdx = pb[0] - pd[0];
6427   cdx = pc[0] - pd[0];
6428   ady = pa[1] - pd[1];
6429   bdy = pb[1] - pd[1];
6430   cdy = pc[1] - pd[1];
6431   adheight = aheight - dheight;
6432   bdheight = bheight - dheight;
6433   cdheight = cheight - dheight;
6434 
6435   bdxcdy = bdx * cdy;
6436   cdxbdy = cdx * bdy;
6437 
6438   cdxady = cdx * ady;
6439   adxcdy = adx * cdy;
6440 
6441   adxbdy = adx * bdy;
6442   bdxady = bdx * ady;
6443 
6444   det = adheight * (bdxcdy - cdxbdy)
6445       + bdheight * (cdxady - adxcdy)
6446       + cdheight * (adxbdy - bdxady);
6447 
6448   if (b->noexact) {
6449     return det;
6450   }
6451 
6452   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * Absolute(adheight)
6453             + (Absolute(cdxady) + Absolute(adxcdy)) * Absolute(bdheight)
6454             + (Absolute(adxbdy) + Absolute(bdxady)) * Absolute(cdheight);
6455   errbound = o3derrboundA * permanent;
6456   if ((det > errbound) || (-det > errbound)) {
6457     return det;
6458   }
6459 
6460   return orient3dadapt(pa, pb, pc, pd, aheight, bheight, cheight, dheight,
6461                        permanent);
6462 }
6463 
6464 /*****************************************************************************/
6465 /*                                                                           */
6466 /*  nonregular()   Return a positive value if the point pd is incompatible   */
6467 /*                 with the circle or plane passing through pa, pb, and pc   */
6468 /*                 (meaning that pd is inside the circle or below the        */
6469 /*                 plane); a negative value if it is compatible; and zero if */
6470 /*                 the four points are cocircular/coplanar.  The points pa,  */
6471 /*                 pb, and pc must be in counterclockwise order, or the sign */
6472 /*                 of the result will be reversed.                           */
6473 /*                                                                           */
6474 /*  If the -w switch is used, the points are lifted onto the parabolic       */
6475 /*  lifting map, then they are dropped according to their weights, then the  */
6476 /*  3D orientation test is applied.  If the -W switch is used, the points'   */
6477 /*  heights are already provided, so the 3D orientation test is applied      */
6478 /*  directly.  If neither switch is used, the incircle test is applied.      */
6479 /*                                                                           */
6480 /*****************************************************************************/
6481 
6482 #ifdef ANSI_DECLARATORS
6483 REAL nonregular(struct mesh *m, struct behavior *b,
6484                 vertex pa, vertex pb, vertex pc, vertex pd)
6485 #else /* not ANSI_DECLARATORS */
6486 REAL nonregular(m, b, pa, pb, pc, pd)
6487 struct mesh *m;
6488 struct behavior *b;
6489 vertex pa;
6490 vertex pb;
6491 vertex pc;
6492 vertex pd;
6493 #endif /* not ANSI_DECLARATORS */
6494 
6495 {
6496   if (b->weighted == 0) {
6497     return incircle(m, b, pa, pb, pc, pd);
6498   } else if (b->weighted == 1) {
6499     return orient3d(m, b, pa, pb, pc, pd,
6500                     pa[0] * pa[0] + pa[1] * pa[1] - pa[2],
6501                     pb[0] * pb[0] + pb[1] * pb[1] - pb[2],
6502                     pc[0] * pc[0] + pc[1] * pc[1] - pc[2],
6503                     pd[0] * pd[0] + pd[1] * pd[1] - pd[2]);
6504   } else {
6505     return orient3d(m, b, pa, pb, pc, pd, pa[2], pb[2], pc[2], pd[2]);
6506   }
6507 }
6508 
6509 /*****************************************************************************/
6510 /*                                                                           */
6511 /*  findcircumcenter()   Find the circumcenter of a triangle.                */
6512 /*                                                                           */
6513 /*  The result is returned both in terms of x-y coordinates and xi-eta       */
6514 /*  (barycentric) coordinates.  The xi-eta coordinate system is defined in   */
6515 /*  terms of the triangle:  the origin of the triangle is the origin of the  */
6516 /*  coordinate system; the destination of the triangle is one unit along the */
6517 /*  xi axis; and the apex of the triangle is one unit along the eta axis.    */
6518 /*  This procedure also returns the square of the length of the triangle's   */
6519 /*  shortest edge.                                                           */
6520 /*                                                                           */
6521 /*****************************************************************************/
6522 
6523 #ifdef ANSI_DECLARATORS
6524 void findcircumcenter(struct mesh *m, struct behavior *b,
6525                       vertex torg, vertex tdest, vertex tapex,
6526                       vertex circumcenter, REAL *xi, REAL *eta, int offcenter)
6527 #else /* not ANSI_DECLARATORS */
6528 void findcircumcenter(m, b, torg, tdest, tapex, circumcenter, xi, eta,
6529                       offcenter)
6530 struct mesh *m;
6531 struct behavior *b;
6532 vertex torg;
6533 vertex tdest;
6534 vertex tapex;
6535 vertex circumcenter;
6536 REAL *xi;
6537 REAL *eta;
6538 int offcenter;
6539 #endif /* not ANSI_DECLARATORS */
6540 
6541 {
6542   REAL xdo, ydo, xao, yao;
6543   REAL dodist, aodist, dadist;
6544   REAL denominator;
6545   REAL dx, dy, dxoff, dyoff;
6546 
6547   m->circumcentercount++;
6548 
6549   /* Compute the circumcenter of the triangle. */
6550   xdo = tdest[0] - torg[0];
6551   ydo = tdest[1] - torg[1];
6552   xao = tapex[0] - torg[0];
6553   yao = tapex[1] - torg[1];
6554   dodist = xdo * xdo + ydo * ydo;
6555   aodist = xao * xao + yao * yao;
6556   dadist = (tdest[0] - tapex[0]) * (tdest[0] - tapex[0]) +
6557            (tdest[1] - tapex[1]) * (tdest[1] - tapex[1]);
6558   if (b->noexact) {
6559     denominator = 0.5 / (xdo * yao - xao * ydo);
6560   } else {
6561     /* Use the counterclockwise() routine to ensure a positive (and */
6562     /*   reasonably accurate) result, avoiding any possibility of   */
6563     /*   division by zero.                                          */
6564     denominator = 0.5 / counterclockwise(m, b, tdest, tapex, torg);
6565     /* Don't count the above as an orientation test. */
6566     m->counterclockcount--;
6567   }
6568   dx = (yao * dodist - ydo * aodist) * denominator;
6569   dy = (xdo * aodist - xao * dodist) * denominator;
6570 
6571   /* Find the (squared) length of the triangle's shortest edge.  This   */
6572   /*   serves as a conservative estimate of the insertion radius of the */
6573   /*   circumcenter's parent.  The estimate is used to ensure that      */
6574   /*   the algorithm terminates even if very small angles appear in     */
6575   /*   the input PSLG.                                                  */
6576   if ((dodist < aodist) && (dodist < dadist)) {
6577     if (offcenter && (b->offconstant > 0.0)) {
6578       /* Find the position of the off-center, as described by Alper Ungor. */
6579       dxoff = 0.5 * xdo - b->offconstant * ydo;
6580       dyoff = 0.5 * ydo + b->offconstant * xdo;
6581       /* If the off-center is closer to the origin than the */
6582       /*   circumcenter, use the off-center instead.        */
6583       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6584         dx = dxoff;
6585         dy = dyoff;
6586       }
6587     }
6588   } else if (aodist < dadist) {
6589     if (offcenter && (b->offconstant > 0.0)) {
6590       dxoff = 0.5 * xao + b->offconstant * yao;
6591       dyoff = 0.5 * yao - b->offconstant * xao;
6592       /* If the off-center is closer to the origin than the */
6593       /*   circumcenter, use the off-center instead.        */
6594       if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
6595         dx = dxoff;
6596         dy = dyoff;
6597       }
6598     }
6599   } else {
6600     if (offcenter && (b->offconstant > 0.0)) {
6601       dxoff = 0.5 * (tapex[0] - tdest[0]) -
6602               b->offconstant * (tapex[1] - tdest[1]);
6603       dyoff = 0.5 * (tapex[1] - tdest[1]) +
6604               b->offconstant * (tapex[0] - tdest[0]);
6605       /* If the off-center is closer to the destination than the */
6606       /*   circumcenter, use the off-center instead.             */
6607       if (dxoff * dxoff + dyoff * dyoff <
6608           (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) {
6609         dx = xdo + dxoff;
6610         dy = ydo + dyoff;
6611       }
6612     }
6613   }
6614 
6615   circumcenter[0] = torg[0] + dx;
6616   circumcenter[1] = torg[1] + dy;
6617 
6618   /* To interpolate vertex attributes for the new vertex inserted at */
6619   /*   the circumcenter, define a coordinate system with a xi-axis,  */
6620   /*   directed from the triangle's origin to its destination, and   */
6621   /*   an eta-axis, directed from its origin to its apex.            */
6622   /*   Calculate the xi and eta coordinates of the circumcenter.     */
6623   *xi = (yao * dx - xao * dy) * (2.0 * denominator);
6624   *eta = (xdo * dy - ydo * dx) * (2.0 * denominator);
6625 }
6626 
6627 /**                                                                         **/
6628 /**                                                                         **/
6629 /********* Geometric primitives end here                             *********/
6630 
6631 /*****************************************************************************/
6632 /*                                                                           */
6633 /*  triangleinit()   Initialize some variables.                              */
6634 /*                                                                           */
6635 /*****************************************************************************/
6636 
6637 #ifdef ANSI_DECLARATORS
6638 void triangleinit(struct mesh *m)
6639 #else /* not ANSI_DECLARATORS */
6640 void triangleinit(m)
6641 struct mesh *m;
6642 #endif /* not ANSI_DECLARATORS */
6643 
6644 {
6645   poolzero(&m->vertices);
6646   poolzero(&m->triangles);
6647   poolzero(&m->subsegs);
6648   poolzero(&m->viri);
6649   poolzero(&m->badsubsegs);
6650   poolzero(&m->badtriangles);
6651   poolzero(&m->flipstackers);
6652   poolzero(&m->splaynodes);
6653 
6654   m->recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
6655   m->undeads = 0;                       /* No eliminated input vertices yet. */
6656   m->samples = 1;         /* Point location should take at least one sample. */
6657   m->checksegments = 0;   /* There are no segments in the triangulation yet. */
6658   m->checkquality = 0;     /* The quality triangulation stage has not begun. */
6659   m->incirclecount = m->counterclockcount = m->orient3dcount = 0;
6660   m->hyperbolacount = m->circletopcount = m->circumcentercount = 0;
6661   randomseed = 1;
6662 
6663   exactinit();                     /* Initialize exact arithmetic constants. */
6664 }
6665 
6666 /*****************************************************************************/
6667 /*                                                                           */
6668 /*  randomnation()   Generate a random number between 0 and `choices' - 1.   */
6669 /*                                                                           */
6670 /*  This is a simple linear congruential random number generator.  Hence, it */
6671 /*  is a bad random number generator, but good enough for most randomized    */
6672 /*  geometric algorithms.                                                    */
6673 /*                                                                           */
6674 /*****************************************************************************/
6675 
6676 #ifdef ANSI_DECLARATORS
6677 unsigned long randomnation(unsigned int choices)
6678 #else /* not ANSI_DECLARATORS */
6679 unsigned long randomnation(choices)
6680 unsigned int choices;
6681 #endif /* not ANSI_DECLARATORS */
6682 
6683 {
6684   randomseed = (randomseed * 1366l + 150889l) % 714025l;
6685   return randomseed / (714025l / choices + 1);
6686 }
6687 
6688 /********* Mesh quality testing routines begin here                  *********/
6689 /**                                                                         **/
6690 /**                                                                         **/
6691 
6692 /*****************************************************************************/
6693 /*                                                                           */
6694 /*  checkmesh()   Test the mesh for topological consistency.                 */
6695 /*                                                                           */
6696 /*****************************************************************************/
6697 
6698 #ifndef REDUCED
6699 
6700 #ifdef ANSI_DECLARATORS
6701 void checkmesh(struct mesh *m, struct behavior *b)
6702 #else /* not ANSI_DECLARATORS */
6703 void checkmesh(m, b)
6704 struct mesh *m;
6705 struct behavior *b;
6706 #endif /* not ANSI_DECLARATORS */
6707 
6708 {
6709   struct otri triangleloop;
6710   struct otri oppotri, oppooppotri;
6711   vertex triorg, tridest, triapex;
6712   vertex oppoorg, oppodest;
6713   int horrors;
6714   int saveexact;
6715   triangle ptr;                         /* Temporary variable used by sym(). */
6716 
6717   /* Temporarily turn on exact arithmetic if it's off. */
6718   saveexact = b->noexact;
6719   b->noexact = 0;
6720   if (!b->quiet) {
6721     printf("  Checking consistency of mesh...\n");
6722   }
6723   horrors = 0;
6724   /* Run through the list of triangles, checking each one. */
6725   traversalinit(&m->triangles);
6726   triangleloop.tri = triangletraverse(m);
6727   while (triangleloop.tri != (triangle *) NULL) {
6728     /* Check all three edges of the triangle. */
6729     for (triangleloop.orient = 0; triangleloop.orient < 3;
6730          triangleloop.orient++) {
6731       org(triangleloop, triorg);
6732       dest(triangleloop, tridest);
6733       if (triangleloop.orient == 0) {       /* Only test for inversion once. */
6734         /* Test if the triangle is flat or inverted. */
6735         apex(triangleloop, triapex);
6736         if (counterclockwise(m, b, triorg, tridest, triapex) <= 0.0) {
6737           printf("  !! !! Inverted ");
6738           printtriangle(m, b, &triangleloop);
6739           horrors++;
6740         }
6741       }
6742       /* Find the neighboring triangle on this edge. */
6743       sym(triangleloop, oppotri);
6744       if (oppotri.tri != m->dummytri) {
6745         /* Check that the triangle's neighbor knows it's a neighbor. */
6746         sym(oppotri, oppooppotri);
6747         if ((triangleloop.tri != oppooppotri.tri)
6748             || (triangleloop.orient != oppooppotri.orient)) {
6749           printf("  !! !! Asymmetric triangle-triangle bond:\n");
6750           if (triangleloop.tri == oppooppotri.tri) {
6751             printf("   (Right triangle, wrong orientation)\n");
6752           }
6753           printf("    First ");
6754           printtriangle(m, b, &triangleloop);
6755           printf("    Second (nonreciprocating) ");
6756           printtriangle(m, b, &oppotri);
6757           horrors++;
6758         }
6759         /* Check that both triangles agree on the identities */
6760         /*   of their shared vertices.                       */
6761         org(oppotri, oppoorg);
6762         dest(oppotri, oppodest);
6763         if ((triorg != oppodest) || (tridest != oppoorg)) {
6764           printf("  !! !! Mismatched edge coordinates between two triangles:\n"
6765                  );
6766           printf("    First mismatched ");
6767           printtriangle(m, b, &triangleloop);
6768           printf("    Second mismatched ");
6769           printtriangle(m, b, &oppotri);
6770           horrors++;
6771         }
6772       }
6773     }
6774     triangleloop.tri = triangletraverse(m);
6775   }
6776   if (horrors == 0) {
6777     if (!b->quiet) {
6778       printf("  In my studied opinion, the mesh appears to be consistent.\n");
6779     }
6780   } else if (horrors == 1) {
6781     printf("  !! !! !! !! Precisely one festering wound discovered.\n");
6782   } else {
6783     printf("  !! !! !! !! %d abominations witnessed.\n", horrors);
6784   }
6785   /* Restore the status of exact arithmetic. */
6786   b->noexact = saveexact;
6787 }
6788 
6789 #endif /* not REDUCED */
6790 
6791 /*****************************************************************************/
6792 /*                                                                           */
6793 /*  checkdelaunay()   Ensure that the mesh is (constrained) Delaunay.        */
6794 /*                                                                           */
6795 /*****************************************************************************/
6796 
6797 #ifndef REDUCED
6798 
6799 #ifdef ANSI_DECLARATORS
6800 void checkdelaunay(struct mesh *m, struct behavior *b)
6801 #else /* not ANSI_DECLARATORS */
6802 void checkdelaunay(m, b)
6803 struct mesh *m;
6804 struct behavior *b;
6805 #endif /* not ANSI_DECLARATORS */
6806 
6807 {
6808   struct otri triangleloop;
6809   struct otri oppotri;
6810   struct osub opposubseg;
6811   vertex triorg, tridest, triapex;
6812   vertex oppoapex;
6813   int shouldbedelaunay;
6814   int horrors;
6815   int saveexact;
6816   triangle ptr;                         /* Temporary variable used by sym(). */
6817   subseg sptr;                      /* Temporary variable used by tspivot(). */
6818 
6819   /* Temporarily turn on exact arithmetic if it's off. */
6820   saveexact = b->noexact;
6821   b->noexact = 0;
6822   if (!b->quiet) {
6823     printf("  Checking Delaunay property of mesh...\n");
6824   }
6825   horrors = 0;
6826   /* Run through the list of triangles, checking each one. */
6827   traversalinit(&m->triangles);
6828   triangleloop.tri = triangletraverse(m);
6829   while (triangleloop.tri != (triangle *) NULL) {
6830     /* Check all three edges of the triangle. */
6831     for (triangleloop.orient = 0; triangleloop.orient < 3;
6832          triangleloop.orient++) {
6833       org(triangleloop, triorg);
6834       dest(triangleloop, tridest);
6835       apex(triangleloop, triapex);
6836       sym(triangleloop, oppotri);
6837       apex(oppotri, oppoapex);
6838       /* Only test that the edge is locally Delaunay if there is an   */
6839       /*   adjoining triangle whose pointer is larger (to ensure that */
6840       /*   each pair isn't tested twice).                             */
6841       shouldbedelaunay = (oppotri.tri != m->dummytri) &&
6842             !deadtri(oppotri.tri) && (triangleloop.tri < oppotri.tri) &&
6843             (triorg != m->infvertex1) && (triorg != m->infvertex2) &&
6844             (triorg != m->infvertex3) &&
6845             (tridest != m->infvertex1) && (tridest != m->infvertex2) &&
6846             (tridest != m->infvertex3) &&
6847             (triapex != m->infvertex1) && (triapex != m->infvertex2) &&
6848             (triapex != m->infvertex3) &&
6849             (oppoapex != m->infvertex1) && (oppoapex != m->infvertex2) &&
6850             (oppoapex != m->infvertex3);
6851       if (m->checksegments && shouldbedelaunay) {
6852         /* If a subsegment separates the triangles, then the edge is */
6853         /*   constrained, so no local Delaunay test should be done.  */
6854         tspivot(triangleloop, opposubseg);
6855         if (opposubseg.ss != m->dummysub){
6856           shouldbedelaunay = 0;
6857         }
6858       }
6859       if (shouldbedelaunay) {
6860         if (nonregular(m, b, triorg, tridest, triapex, oppoapex) > 0.0) {
6861           if (!b->weighted) {
6862             printf("  !! !! Non-Delaunay pair of triangles:\n");
6863             printf("    First non-Delaunay ");
6864             printtriangle(m, b, &triangleloop);
6865             printf("    Second non-Delaunay ");
6866           } else {
6867             printf("  !! !! Non-regular pair of triangles:\n");
6868             printf("    First non-regular ");
6869             printtriangle(m, b, &triangleloop);
6870             printf("    Second non-regular ");
6871           }
6872           printtriangle(m, b, &oppotri);
6873           horrors++;
6874         }
6875       }
6876     }
6877     triangleloop.tri = triangletraverse(m);
6878   }
6879   if (horrors == 0) {
6880     if (!b->quiet) {
6881       printf(
6882   "  By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
6883     }
6884   } else if (horrors == 1) {
6885     printf(
6886          "  !! !! !! !! Precisely one terrifying transgression identified.\n");
6887   } else {
6888     printf("  !! !! !! !! %d obscenities viewed with horror.\n", horrors);
6889   }
6890   /* Restore the status of exact arithmetic. */
6891   b->noexact = saveexact;
6892 }
6893 
6894 #endif /* not REDUCED */
6895 
6896 /*****************************************************************************/
6897 /*                                                                           */
6898 /*  enqueuebadtriang()   Add a bad triangle data structure to the end of a   */
6899 /*                       queue.                                              */
6900 /*                                                                           */
6901 /*  The queue is actually a set of 4096 queues.  I use multiple queues to    */
6902 /*  give priority to smaller angles.  I originally implemented a heap, but   */
6903 /*  the queues are faster by a larger margin than I'd suspected.             */
6904 /*                                                                           */
6905 /*****************************************************************************/
6906 
6907 #ifndef CDT_ONLY
6908 
6909 #ifdef ANSI_DECLARATORS
6910 void enqueuebadtriang(struct mesh *m, struct behavior *b,
6911                       struct badtriang *badtri)
6912 #else /* not ANSI_DECLARATORS */
6913 void enqueuebadtriang(m, b, badtri)
6914 struct mesh *m;
6915 struct behavior *b;
6916 struct badtriang *badtri;
6917 #endif /* not ANSI_DECLARATORS */
6918 
6919 {
6920   REAL length, multiplier;
6921   int exponent, expincrement;
6922   int queuenumber;
6923   int posexponent;
6924   int i;
6925 
6926   if (b->verbose > 2) {
6927     printf("  Queueing bad triangle:\n");
6928     printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
6929            badtri->triangorg[0], badtri->triangorg[1],
6930            badtri->triangdest[0], badtri->triangdest[1],
6931            badtri->triangapex[0], badtri->triangapex[1]);
6932   }
6933 
6934   /* Determine the appropriate queue to put the bad triangle into.    */
6935   /*   Recall that the key is the square of its shortest edge length. */
6936   if (badtri->key >= 1.0) {
6937     length = badtri->key;
6938     posexponent = 1;
6939   } else {
6940     /* `badtri->key' is 2.0 to a negative exponent, so we'll record that */
6941     /*   fact and use the reciprocal of `badtri->key', which is > 1.0.   */
6942     length = 1.0 / badtri->key;
6943     posexponent = 0;
6944   }
6945   /* `length' is approximately 2.0 to what exponent?  The following code */
6946   /*   determines the answer in time logarithmic in the exponent.        */
6947   exponent = 0;
6948   while (length > 2.0) {
6949     /* Find an approximation by repeated squaring of two. */
6950     expincrement = 1;
6951     multiplier = 0.5;
6952     while (length * multiplier * multiplier > 1.0) {
6953       expincrement *= 2;
6954       multiplier *= multiplier;
6955     }
6956     /* Reduce the value of `length', then iterate if necessary. */
6957     exponent += expincrement;
6958     length *= multiplier;
6959   }
6960   /* `length' is approximately squareroot(2.0) to what exponent? */
6961   exponent = 2.0 * exponent + (length > SQUAREROOTTWO);
6962   /* `exponent' is now in the range 0...2047 for IEEE double precision.   */
6963   /*   Choose a queue in the range 0...4095.  The shortest edges have the */
6964   /*   highest priority (queue 4095).                                     */
6965   if (posexponent) {
6966     queuenumber = 2047 - exponent;
6967   } else {
6968     queuenumber = 2048 + exponent;
6969   }
6970 
6971   /* Are we inserting into an empty queue? */
6972   if (m->queuefront[queuenumber] == (struct badtriang *) NULL) {
6973     /* Yes, we are inserting into an empty queue.     */
6974     /*   Will this become the highest-priority queue? */
6975     if (queuenumber > m->firstnonemptyq) {
6976       /* Yes, this is the highest-priority queue. */
6977       m->nextnonemptyq[queuenumber] = m->firstnonemptyq;
6978       m->firstnonemptyq = queuenumber;
6979     } else {
6980       /* No, this is not the highest-priority queue. */
6981       /*   Find the queue with next higher priority. */
6982       i = queuenumber + 1;
6983       while (m->queuefront[i] == (struct badtriang *) NULL) {
6984         i++;
6985       }
6986       /* Mark the newly nonempty queue as following a higher-priority queue. */
6987       m->nextnonemptyq[queuenumber] = m->nextnonemptyq[i];
6988       m->nextnonemptyq[i] = queuenumber;
6989     }
6990     /* Put the bad triangle at the beginning of the (empty) queue. */
6991     m->queuefront[queuenumber] = badtri;
6992   } else {
6993     /* Add the bad triangle to the end of an already nonempty queue. */
6994     m->queuetail[queuenumber]->nexttriang = badtri;
6995   }
6996   /* Maintain a pointer to the last triangle of the queue. */
6997   m->queuetail[queuenumber] = badtri;
6998   /* Newly enqueued bad triangle has no successor in the queue. */
6999   badtri->nexttriang = (struct badtriang *) NULL;
7000 }
7001 
7002 #endif /* not CDT_ONLY */
7003 
7004 /*****************************************************************************/
7005 /*                                                                           */
7006 /*  enqueuebadtri()   Add a bad triangle to the end of a queue.              */
7007 /*                                                                           */
7008 /*  Allocates a badtriang data structure for the triangle, then passes it to */
7009 /*  enqueuebadtriang().                                                      */
7010 /*                                                                           */
7011 /*****************************************************************************/
7012 
7013 #ifndef CDT_ONLY
7014 
7015 #ifdef ANSI_DECLARATORS
7016 void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
7017                    REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest)
7018 #else /* not ANSI_DECLARATORS */
7019 void enqueuebadtri(m, b, enqtri, minedge, enqapex, enqorg, enqdest)
7020 struct mesh *m;
7021 struct behavior *b;
7022 struct otri *enqtri;
7023 REAL minedge;
7024 vertex enqapex;
7025 vertex enqorg;
7026 vertex enqdest;
7027 #endif /* not ANSI_DECLARATORS */
7028 
7029 {
7030   struct badtriang *newbad;
7031 
7032   /* Allocate space for the bad triangle. */
7033   newbad = (struct badtriang *) poolalloc(&m->badtriangles);
7034   newbad->poortri = encode(*enqtri);
7035   newbad->key = minedge;
7036   newbad->triangapex = enqapex;
7037   newbad->triangorg = enqorg;
7038   newbad->triangdest = enqdest;
7039   enqueuebadtriang(m, b, newbad);
7040 }
7041 
7042 #endif /* not CDT_ONLY */
7043 
7044 /*****************************************************************************/
7045 /*                                                                           */
7046 /*  dequeuebadtriang()   Remove a triangle from the front of the queue.      */
7047 /*                                                                           */
7048 /*****************************************************************************/
7049 
7050 #ifndef CDT_ONLY
7051 
7052 #ifdef ANSI_DECLARATORS
7053 struct badtriang *dequeuebadtriang(struct mesh *m)
7054 #else /* not ANSI_DECLARATORS */
7055 struct badtriang *dequeuebadtriang(m)
7056 struct mesh *m;
7057 #endif /* not ANSI_DECLARATORS */
7058 
7059 {
7060   struct badtriang *result;
7061 
7062   /* If no queues are nonempty, return NULL. */
7063   if (m->firstnonemptyq < 0) {
7064     return (struct badtriang *) NULL;
7065   }
7066   /* Find the first triangle of the highest-priority queue. */
7067   result = m->queuefront[m->firstnonemptyq];
7068   /* Remove the triangle from the queue. */
7069   m->queuefront[m->firstnonemptyq] = result->nexttriang;
7070   /* If this queue is now empty, note the new highest-priority */
7071   /*   nonempty queue.                                         */
7072   if (result == m->queuetail[m->firstnonemptyq]) {
7073     m->firstnonemptyq = m->nextnonemptyq[m->firstnonemptyq];
7074   }
7075   return result;
7076 }
7077 
7078 #endif /* not CDT_ONLY */
7079 
7080 /*****************************************************************************/
7081 /*                                                                           */
7082 /*  checkseg4encroach()   Check a subsegment to see if it is encroached; add */
7083 /*                        it to the list if it is.                           */
7084 /*                                                                           */
7085 /*  A subsegment is encroached if there is a vertex in its diametral lens.   */
7086 /*  For Ruppert's algorithm (-D switch), the "diametral lens" is the         */
7087 /*  diametral circle.  For Chew's algorithm (default), the diametral lens is */
7088 /*  just big enough to enclose two isosceles triangles whose bases are the   */
7089 /*  subsegment.  Each of the two isosceles triangles has two angles equal    */
7090 /*  to `b->minangle'.                                                        */
7091 /*                                                                           */
7092 /*  Chew's algorithm does not require diametral lenses at all--but they save */
7093 /*  time.  Any vertex inside a subsegment's diametral lens implies that the  */
7094 /*  triangle adjoining the subsegment will be too skinny, so it's only a     */
7095 /*  matter of time before the encroaching vertex is deleted by Chew's        */
7096 /*  algorithm.  It's faster to simply not insert the doomed vertex in the    */
7097 /*  first place, which is why I use diametral lenses with Chew's algorithm.  */
7098 /*                                                                           */
7099 /*  Returns a nonzero value if the subsegment is encroached.                 */
7100 /*                                                                           */
7101 /*****************************************************************************/
7102 
7103 #ifndef CDT_ONLY
7104 
7105 #ifdef ANSI_DECLARATORS
7106 int checkseg4encroach(struct mesh *m, struct behavior *b,
7107                       struct osub *testsubseg)
7108 #else /* not ANSI_DECLARATORS */
7109 int checkseg4encroach(m, b, testsubseg)
7110 struct mesh *m;
7111 struct behavior *b;
7112 struct osub *testsubseg;
7113 #endif /* not ANSI_DECLARATORS */
7114 
7115 {
7116   struct otri neighbortri;
7117   struct osub testsym;
7118   struct badsubseg *encroachedseg;
7119   REAL dotproduct;
7120   int encroached;
7121   int sides;
7122   vertex eorg, edest, eapex;
7123   triangle ptr;                     /* Temporary variable used by stpivot(). */
7124 
7125   encroached = 0;
7126   sides = 0;
7127 
7128   sorg(*testsubseg, eorg);
7129   sdest(*testsubseg, edest);
7130   /* Check one neighbor of the subsegment. */
7131   stpivot(*testsubseg, neighbortri);
7132   /* Does the neighbor exist, or is this a boundary edge? */
7133   if (neighbortri.tri != m->dummytri) {
7134     sides++;
7135     /* Find a vertex opposite this subsegment. */
7136     apex(neighbortri, eapex);
7137     /* Check whether the apex is in the diametral lens of the subsegment */
7138     /*   (the diametral circle if `conformdel' is set).  A dot product   */
7139     /*   of two sides of the triangle is used to check whether the angle */
7140     /*   at the apex is greater than (180 - 2 `minangle') degrees (for   */
7141     /*   lenses; 90 degrees for diametral circles).                      */
7142     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7143                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7144     if (dotproduct < 0.0) {
7145       if (b->conformdel ||
7146           (dotproduct * dotproduct >=
7147            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7148            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7149             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7150            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7151             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7152         encroached = 1;
7153       }
7154     }
7155   }
7156   /* Check the other neighbor of the subsegment. */
7157   ssym(*testsubseg, testsym);
7158   stpivot(testsym, neighbortri);
7159   /* Does the neighbor exist, or is this a boundary edge? */
7160   if (neighbortri.tri != m->dummytri) {
7161     sides++;
7162     /* Find the other vertex opposite this subsegment. */
7163     apex(neighbortri, eapex);
7164     /* Check whether the apex is in the diametral lens of the subsegment */
7165     /*   (or the diametral circle, if `conformdel' is set).              */
7166     dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
7167                  (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
7168     if (dotproduct < 0.0) {
7169       if (b->conformdel ||
7170           (dotproduct * dotproduct >=
7171            (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
7172            ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
7173             (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
7174            ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
7175             (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
7176         encroached += 2;
7177       }
7178     }
7179   }
7180 
7181   if (encroached && (!b->nobisect || ((b->nobisect == 1) && (sides == 2)))) {
7182     if (b->verbose > 2) {
7183       printf(
7184         "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
7185         eorg[0], eorg[1], edest[0], edest[1]);
7186     }
7187     /* Add the subsegment to the list of encroached subsegments. */
7188     /*   Be sure to get the orientation right.                   */
7189     encroachedseg = (struct badsubseg *) poolalloc(&m->badsubsegs);
7190     if (encroached == 1) {
7191       encroachedseg->encsubseg = sencode(*testsubseg);
7192       encroachedseg->subsegorg = eorg;
7193       encroachedseg->subsegdest = edest;
7194     } else {
7195       encroachedseg->encsubseg = sencode(testsym);
7196       encroachedseg->subsegorg = edest;
7197       encroachedseg->subsegdest = eorg;
7198     }
7199   }
7200 
7201   return encroached;
7202 }
7203 
7204 #endif /* not CDT_ONLY */
7205 
7206 /*****************************************************************************/
7207 /*                                                                           */
7208 /*  testtriangle()   Test a triangle for quality and size.                   */
7209 /*                                                                           */
7210 /*  Tests a triangle to see if it satisfies the minimum angle condition and  */
7211 /*  the maximum area condition.  Triangles that aren't up to spec are added  */
7212 /*  to the bad triangle queue.                                               */
7213 /*                                                                           */
7214 /*****************************************************************************/
7215 
7216 #ifndef CDT_ONLY
7217 
7218 #ifdef ANSI_DECLARATORS
7219 void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri)
7220 #else /* not ANSI_DECLARATORS */
7221 void testtriangle(m, b, testtri)
7222 struct mesh *m;
7223 struct behavior *b;
7224 struct otri *testtri;
7225 #endif /* not ANSI_DECLARATORS */
7226 
7227 {
7228   struct otri tri1, tri2;
7229   struct osub testsub;
7230   vertex torg, tdest, tapex;
7231   vertex base1, base2;
7232   vertex org1, dest1, org2, dest2;
7233   vertex joinvertex;
7234   REAL dxod, dyod, dxda, dyda, dxao, dyao;
7235   REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
7236   REAL apexlen, orglen, destlen, minedge;
7237   REAL angle;
7238   REAL area;
7239   REAL dist1, dist2;
7240   subseg sptr;                      /* Temporary variable used by tspivot(). */
7241   triangle ptr;           /* Temporary variable used by oprev() and dnext(). */
7242 
7243   org(*testtri, torg);
7244   dest(*testtri, tdest);
7245   apex(*testtri, tapex);
7246   dxod = torg[0] - tdest[0];
7247   dyod = torg[1] - tdest[1];
7248   dxda = tdest[0] - tapex[0];
7249   dyda = tdest[1] - tapex[1];
7250   dxao = tapex[0] - torg[0];
7251   dyao = tapex[1] - torg[1];
7252   dxod2 = dxod * dxod;
7253   dyod2 = dyod * dyod;
7254   dxda2 = dxda * dxda;
7255   dyda2 = dyda * dyda;
7256   dxao2 = dxao * dxao;
7257   dyao2 = dyao * dyao;
7258   /* Find the lengths of the triangle's three edges. */
7259   apexlen = dxod2 + dyod2;
7260   orglen = dxda2 + dyda2;
7261   destlen = dxao2 + dyao2;
7262 
7263   if ((apexlen < orglen) && (apexlen < destlen)) {
7264     /* The edge opposite the apex is shortest. */
7265     minedge = apexlen;
7266     /* Find the square of the cosine of the angle at the apex. */
7267     angle = dxda * dxao + dyda * dyao;
7268     angle = angle * angle / (orglen * destlen);
7269     base1 = torg;
7270     base2 = tdest;
7271     otricopy(*testtri, tri1);
7272   } else if (orglen < destlen) {
7273     /* The edge opposite the origin is shortest. */
7274     minedge = orglen;
7275     /* Find the square of the cosine of the angle at the origin. */
7276     angle = dxod * dxao + dyod * dyao;
7277     angle = angle * angle / (apexlen * destlen);
7278     base1 = tdest;
7279     base2 = tapex;
7280     lnext(*testtri, tri1);
7281   } else {
7282     /* The edge opposite the destination is shortest. */
7283     minedge = destlen;
7284     /* Find the square of the cosine of the angle at the destination. */
7285     angle = dxod * dxda + dyod * dyda;
7286     angle = angle * angle / (apexlen * orglen);
7287     base1 = tapex;
7288     base2 = torg;
7289     lprev(*testtri, tri1);
7290   }
7291 
7292   if (b->vararea || b->fixedarea || b->usertest) {
7293     /* Check whether the area is larger than permitted. */
7294     area = 0.5 * (dxod * dyda - dyod * dxda);
7295     if (b->fixedarea && (area > b->maxarea)) {
7296       /* Add this triangle to the list of bad triangles. */
7297       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7298       return;
7299     }
7300 
7301     /* Nonpositive area constraints are treated as unconstrained. */
7302     if ((b->vararea) && (area > areabound(*testtri)) &&
7303         (areabound(*testtri) > 0.0)) {
7304       /* Add this triangle to the list of bad triangles. */
7305       enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7306       return;
7307     }
7308 
7309     if (b->usertest) {
7310       /* Check whether the user thinks this triangle is too large. */
7311       if (triunsuitable(torg, tdest, tapex, area)) {
7312         enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7313         return;
7314       }
7315     }
7316   }
7317 
7318   /* Check whether the angle is smaller than permitted. */
7319   if (angle > b->goodangle) {
7320     /* Use the rules of Miller, Pav, and Walkington to decide that certain */
7321     /*   triangles should not be split, even if they have bad angles.      */
7322     /*   A skinny triangle is not split if its shortest edge subtends a    */
7323     /*   small input angle, and both endpoints of the edge lie on a        */
7324     /*   concentric circular shell.  For convenience, I make a small       */
7325     /*   adjustment to that rule:  I check if the endpoints of the edge    */
7326     /*   both lie in segment interiors, equidistant from the apex where    */
7327     /*   the two segments meet.                                            */
7328     /* First, check if both points lie in segment interiors.               */
7329     if ((vertextype(base1) == SEGMENTVERTEX) &&
7330         (vertextype(base2) == SEGMENTVERTEX)) {
7331       /* Check if both points lie in a common segment.  If they do, the */
7332       /*   skinny triangle is enqueued to be split as usual.            */
7333       tspivot(tri1, testsub);
7334       if (testsub.ss == m->dummysub) {
7335         /* No common segment.  Find a subsegment that contains `torg'. */
7336         otricopy(tri1, tri2);
7337         do {
7338           oprevself(tri1);
7339           tspivot(tri1, testsub);
7340         } while (testsub.ss == m->dummysub);
7341         /* Find the endpoints of the containing segment. */
7342         segorg(testsub, org1);
7343         segdest(testsub, dest1);
7344         /* Find a subsegment that contains `tdest'. */
7345         do {
7346           dnextself(tri2);
7347           tspivot(tri2, testsub);
7348         } while (testsub.ss == m->dummysub);
7349         /* Find the endpoints of the containing segment. */
7350         segorg(testsub, org2);
7351         segdest(testsub, dest2);
7352         /* Check if the two containing segments have an endpoint in common. */
7353         joinvertex = (vertex) NULL;
7354         if ((dest1[0] == org2[0]) && (dest1[1] == org2[1])) {
7355           joinvertex = dest1;
7356         } else if ((org1[0] == dest2[0]) && (org1[1] == dest2[1])) {
7357           joinvertex = org1;
7358         }
7359         if (joinvertex != (vertex) NULL) {
7360           /* Compute the distance from the common endpoint (of the two  */
7361           /*   segments) to each of the endpoints of the shortest edge. */
7362           dist1 = ((base1[0] - joinvertex[0]) * (base1[0] - joinvertex[0]) +
7363                    (base1[1] - joinvertex[1]) * (base1[1] - joinvertex[1]));
7364           dist2 = ((base2[0] - joinvertex[0]) * (base2[0] - joinvertex[0]) +
7365                    (base2[1] - joinvertex[1]) * (base2[1] - joinvertex[1]));
7366           /* If the two distances are equal, don't split the triangle. */
7367           if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2)) {
7368             /* Return now to avoid enqueueing the bad triangle. */
7369             return;
7370           }
7371         }
7372       }
7373     }
7374 
7375     /* Add this triangle to the list of bad triangles. */
7376     enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
7377   }
7378 }
7379 
7380 #endif /* not CDT_ONLY */
7381 
7382 /**                                                                         **/
7383 /**                                                                         **/
7384 /********* Mesh quality testing routines end here                    *********/
7385 
7386 /********* Point location routines begin here                        *********/
7387 /**                                                                         **/
7388 /**                                                                         **/
7389 
7390 /*****************************************************************************/
7391 /*                                                                           */
7392 /*  makevertexmap()   Construct a mapping from vertices to triangles to      */
7393 /*                    improve the speed of point location for segment        */
7394 /*                    insertion.                                             */
7395 /*                                                                           */
7396 /*  Traverses all the triangles, and provides each corner of each triangle   */
7397 /*  with a pointer to that triangle.  Of course, pointers will be            */
7398 /*  overwritten by other pointers because (almost) each vertex is a corner   */
7399 /*  of several triangles, but in the end every vertex will point to some     */
7400 /*  triangle that contains it.                                               */
7401 /*                                                                           */
7402 /*****************************************************************************/
7403 
7404 #ifdef ANSI_DECLARATORS
7405 void makevertexmap(struct mesh *m, struct behavior *b)
7406 #else /* not ANSI_DECLARATORS */
7407 void makevertexmap(m, b)
7408 struct mesh *m;
7409 struct behavior *b;
7410 #endif /* not ANSI_DECLARATORS */
7411 
7412 {
7413   struct otri triangleloop;
7414   vertex triorg;
7415 
7416   if (b->verbose) {
7417     printf("    Constructing mapping from vertices to triangles.\n");
7418   }
7419   traversalinit(&m->triangles);
7420   triangleloop.tri = triangletraverse(m);
7421   while (triangleloop.tri != (triangle *) NULL) {
7422     /* Check all three vertices of the triangle. */
7423     for (triangleloop.orient = 0; triangleloop.orient < 3;
7424          triangleloop.orient++) {
7425       org(triangleloop, triorg);
7426       setvertex2tri(triorg, encode(triangleloop));
7427     }
7428     triangleloop.tri = triangletraverse(m);
7429   }
7430 }
7431 
7432 /*****************************************************************************/
7433 /*                                                                           */
7434 /*  preciselocate()   Find a triangle or edge containing a given point.      */
7435 /*                                                                           */
7436 /*  Begins its search from `searchtri'.  It is important that `searchtri'    */
7437 /*  be a handle with the property that `searchpoint' is strictly to the left */
7438 /*  of the edge denoted by `searchtri', or is collinear with that edge and   */
7439 /*  does not intersect that edge.  (In particular, `searchpoint' should not  */
7440 /*  be the origin or destination of that edge.)                              */
7441 /*                                                                           */
7442 /*  These conditions are imposed because preciselocate() is normally used in */
7443 /*  one of two situations:                                                   */
7444 /*                                                                           */
7445 /*  (1)  To try to find the location to insert a new point.  Normally, we    */
7446 /*       know an edge that the point is strictly to the left of.  In the     */
7447 /*       incremental Delaunay algorithm, that edge is a bounding box edge.   */
7448 /*       In Ruppert's Delaunay refinement algorithm for quality meshing,     */
7449 /*       that edge is the shortest edge of the triangle whose circumcenter   */
7450 /*       is being inserted.                                                  */
7451 /*                                                                           */
7452 /*  (2)  To try to find an existing point.  In this case, any edge on the    */
7453 /*       convex hull is a good starting edge.  You must screen out the       */
7454 /*       possibility that the vertex sought is an endpoint of the starting   */
7455 /*       edge before you call preciselocate().                               */
7456 /*                                                                           */
7457 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7458 /*                                                                           */
7459 /*  This implementation differs from that given by Guibas and Stolfi.  It    */
7460 /*  walks from triangle to triangle, crossing an edge only if `searchpoint'  */
7461 /*  is on the other side of the line containing that edge.  After entering   */
7462 /*  a triangle, there are two edges by which one can leave that triangle.    */
7463 /*  If both edges are valid (`searchpoint' is on the other side of both      */
7464 /*  edges), one of the two is chosen by drawing a line perpendicular to      */
7465 /*  the entry edge (whose endpoints are `forg' and `fdest') passing through  */
7466 /*  `fapex'.  Depending on which side of this perpendicular `searchpoint'    */
7467 /*  falls on, an exit edge is chosen.                                        */
7468 /*                                                                           */
7469 /*  This implementation is empirically faster than the Guibas and Stolfi     */
7470 /*  point location routine (which I originally used), which tends to spiral  */
7471 /*  in toward its target.                                                    */
7472 /*                                                                           */
7473 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7474 /*  is a handle whose origin is the existing vertex.                         */
7475 /*                                                                           */
7476 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7477 /*  handle whose primary edge is the edge on which the point lies.           */
7478 /*                                                                           */
7479 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7480 /*  `searchtri' is a handle on the triangle that contains the point.         */
7481 /*                                                                           */
7482 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7483 /*  handle whose primary edge the point is to the right of.  This might      */
7484 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7485 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7486 /*  seeking a hole or region point that a foolish user has placed outside    */
7487 /*  the mesh.                                                                */
7488 /*                                                                           */
7489 /*  If `stopatsubsegment' is nonzero, the search will stop if it tries to    */
7490 /*  walk through a subsegment, and will return OUTSIDE.                      */
7491 /*                                                                           */
7492 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7493 /*  not generally work after the holes and concavities have been carved.     */
7494 /*  However, it can still be used to find the circumcenter of a triangle, as */
7495 /*  long as the search is begun from the triangle in question.               */
7496 /*                                                                           */
7497 /*****************************************************************************/
7498 
7499 #ifdef ANSI_DECLARATORS
7500 enum locateresult preciselocate(struct mesh *m, struct behavior *b,
7501                                 vertex searchpoint, struct otri *searchtri,
7502                                 int stopatsubsegment)
7503 #else /* not ANSI_DECLARATORS */
7504 enum locateresult preciselocate(m, b, searchpoint, searchtri, stopatsubsegment)
7505 struct mesh *m;
7506 struct behavior *b;
7507 vertex searchpoint;
7508 struct otri *searchtri;
7509 int stopatsubsegment;
7510 #endif /* not ANSI_DECLARATORS */
7511 
7512 {
7513   struct otri backtracktri;
7514   struct osub checkedge;
7515   vertex forg, fdest, fapex;
7516   REAL orgorient, destorient;
7517   int moveleft;
7518   triangle ptr;                         /* Temporary variable used by sym(). */
7519   subseg sptr;                      /* Temporary variable used by tspivot(). */
7520 
7521   if (b->verbose > 2) {
7522     printf("  Searching for point (%.12g, %.12g).\n",
7523            searchpoint[0], searchpoint[1]);
7524   }
7525   /* Where are we? */
7526   org(*searchtri, forg);
7527   dest(*searchtri, fdest);
7528   apex(*searchtri, fapex);
7529   while (1) {
7530     if (b->verbose > 2) {
7531       printf("    At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
7532              forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
7533     }
7534     /* Check whether the apex is the point we seek. */
7535     if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
7536       lprevself(*searchtri);
7537       return ONVERTEX;
7538     }
7539     /* Does the point lie on the other side of the line defined by the */
7540     /*   triangle edge opposite the triangle's destination?            */
7541     destorient = counterclockwise(m, b, forg, fapex, searchpoint);
7542     /* Does the point lie on the other side of the line defined by the */
7543     /*   triangle edge opposite the triangle's origin?                 */
7544     orgorient = counterclockwise(m, b, fapex, fdest, searchpoint);
7545     if (destorient > 0.0) {
7546       if (orgorient > 0.0) {
7547         /* Move left if the inner product of (fapex - searchpoint) and  */
7548         /*   (fdest - forg) is positive.  This is equivalent to drawing */
7549         /*   a line perpendicular to the line (forg, fdest) and passing */
7550         /*   through `fapex', and determining which side of this line   */
7551         /*   `searchpoint' falls on.                                    */
7552         moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
7553                    (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
7554       } else {
7555         moveleft = 1;
7556       }
7557     } else {
7558       if (orgorient > 0.0) {
7559         moveleft = 0;
7560       } else {
7561         /* The point we seek must be on the boundary of or inside this */
7562         /*   triangle.                                                 */
7563         if (destorient == 0.0) {
7564           lprevself(*searchtri);
7565           return ONEDGE;
7566         }
7567         if (orgorient == 0.0) {
7568           lnextself(*searchtri);
7569           return ONEDGE;
7570         }
7571         return INTRIANGLE;
7572       }
7573     }
7574 
7575     /* Move to another triangle.  Leave a trace `backtracktri' in case */
7576     /*   floating-point roundoff or some such bogey causes us to walk  */
7577     /*   off a boundary of the triangulation.                          */
7578     if (moveleft) {
7579       lprev(*searchtri, backtracktri);
7580       fdest = fapex;
7581     } else {
7582       lnext(*searchtri, backtracktri);
7583       forg = fapex;
7584     }
7585     sym(backtracktri, *searchtri);
7586 
7587     if (m->checksegments && stopatsubsegment) {
7588       /* Check for walking through a subsegment. */
7589       tspivot(backtracktri, checkedge);
7590       if (checkedge.ss != m->dummysub) {
7591         /* Go back to the last triangle. */
7592         otricopy(backtracktri, *searchtri);
7593         return OUTSIDE;
7594       }
7595     }
7596     /* Check for walking right out of the triangulation. */
7597     if (searchtri->tri == m->dummytri) {
7598       /* Go back to the last triangle. */
7599       otricopy(backtracktri, *searchtri);
7600       return OUTSIDE;
7601     }
7602 
7603     apex(*searchtri, fapex);
7604   }
7605 }
7606 
7607 /*****************************************************************************/
7608 /*                                                                           */
7609 /*  locate()   Find a triangle or edge containing a given point.             */
7610 /*                                                                           */
7611 /*  Searching begins from one of:  the input `searchtri', a recently         */
7612 /*  encountered triangle `recenttri', or from a triangle chosen from a       */
7613 /*  random sample.  The choice is made by determining which triangle's       */
7614 /*  origin is closest to the point we are searching for.  Normally,          */
7615 /*  `searchtri' should be a handle on the convex hull of the triangulation.  */
7616 /*                                                                           */
7617 /*  Details on the random sampling method can be found in the Mucke, Saias,  */
7618 /*  and Zhu paper cited in the header of this code.                          */
7619 /*                                                                           */
7620 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
7621 /*                                                                           */
7622 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
7623 /*  is a handle whose origin is the existing vertex.                         */
7624 /*                                                                           */
7625 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
7626 /*  handle whose primary edge is the edge on which the point lies.           */
7627 /*                                                                           */
7628 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
7629 /*  `searchtri' is a handle on the triangle that contains the point.         */
7630 /*                                                                           */
7631 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
7632 /*  handle whose primary edge the point is to the right of.  This might      */
7633 /*  occur when the circumcenter of a triangle falls just slightly outside    */
7634 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
7635 /*  seeking a hole or region point that a foolish user has placed outside    */
7636 /*  the mesh.                                                                */
7637 /*                                                                           */
7638 /*  WARNING:  This routine is designed for convex triangulations, and will   */
7639 /*  not generally work after the holes and concavities have been carved.     */
7640 /*                                                                           */
7641 /*****************************************************************************/
7642 
7643 #ifdef ANSI_DECLARATORS
7644 enum locateresult locate(struct mesh *m, struct behavior *b,
7645                          vertex searchpoint, struct otri *searchtri)
7646 #else /* not ANSI_DECLARATORS */
7647 enum locateresult locate(m, b, searchpoint, searchtri)
7648 struct mesh *m;
7649 struct behavior *b;
7650 vertex searchpoint;
7651 struct otri *searchtri;
7652 #endif /* not ANSI_DECLARATORS */
7653 
7654 {
7655   VOID **sampleblock;
7656   char *firsttri;
7657   struct otri sampletri;
7658   vertex torg, tdest;
7659   unsigned long alignptr;
7660   REAL searchdist, dist;
7661   REAL ahead;
7662   long samplesperblock, totalsamplesleft, samplesleft;
7663   long population, totalpopulation;
7664   triangle ptr;                         /* Temporary variable used by sym(). */
7665 
7666   if (b->verbose > 2) {
7667     printf("  Randomly sampling for a triangle near point (%.12g, %.12g).\n",
7668            searchpoint[0], searchpoint[1]);
7669   }
7670   /* Record the distance from the suggested starting triangle to the */
7671   /*   point we seek.                                                */
7672   org(*searchtri, torg);
7673   searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7674                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7675   if (b->verbose > 2) {
7676     printf("    Boundary triangle has origin (%.12g, %.12g).\n",
7677            torg[0], torg[1]);
7678   }
7679 
7680   /* If a recently encountered triangle has been recorded and has not been */
7681   /*   deallocated, test it as a good starting point.                      */
7682   if (m->recenttri.tri != (triangle *) NULL) {
7683     if (!deadtri(m->recenttri.tri)) {
7684       org(m->recenttri, torg);
7685       if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7686         otricopy(m->recenttri, *searchtri);
7687         return ONVERTEX;
7688       }
7689       dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7690              (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7691       if (dist < searchdist) {
7692         otricopy(m->recenttri, *searchtri);
7693         searchdist = dist;
7694         if (b->verbose > 2) {
7695           printf("    Choosing recent triangle with origin (%.12g, %.12g).\n",
7696                  torg[0], torg[1]);
7697         }
7698       }
7699     }
7700   }
7701 
7702   /* The number of random samples taken is proportional to the cube root of */
7703   /*   the number of triangles in the mesh.  The next bit of code assumes   */
7704   /*   that the number of triangles increases monotonically (or at least    */
7705   /*   doesn't decrease enough to matter).                                  */
7706   while (SAMPLEFACTOR * m->samples * m->samples * m->samples <
7707          m->triangles.items) {
7708     m->samples++;
7709   }
7710 
7711   /* We'll draw ceiling(samples * TRIPERBLOCK / maxitems) random samples  */
7712   /*   from each block of triangles (except the first)--until we meet the */
7713   /*   sample quota.  The ceiling means that blocks at the end might be   */
7714   /*   neglected, but I don't care.                                       */
7715   samplesperblock = (m->samples * TRIPERBLOCK - 1) / m->triangles.maxitems + 1;
7716   /* We'll draw ceiling(samples * itemsfirstblock / maxitems) random samples */
7717   /*   from the first block of triangles.                                    */
7718   samplesleft = (m->samples * m->triangles.itemsfirstblock - 1) /
7719                 m->triangles.maxitems + 1;
7720   totalsamplesleft = m->samples;
7721   population = m->triangles.itemsfirstblock;
7722   totalpopulation = m->triangles.maxitems;
7723   sampleblock = m->triangles.firstblock;
7724   sampletri.orient = 0;
7725   while (totalsamplesleft > 0) {
7726     /* If we're in the last block, `population' needs to be corrected. */
7727     if (population > totalpopulation) {
7728       population = totalpopulation;
7729     }
7730     /* Find a pointer to the first triangle in the block. */
7731     alignptr = (unsigned long) (sampleblock + 1);
7732     firsttri = (char *) (alignptr +
7733                          (unsigned long) m->triangles.alignbytes -
7734                          (alignptr %
7735                           (unsigned long) m->triangles.alignbytes));
7736 
7737     /* Choose `samplesleft' randomly sampled triangles in this block. */
7738     do {
7739       sampletri.tri = (triangle *) (firsttri +
7740                                     (randomnation((unsigned int) population) *
7741                                      m->triangles.itembytes));
7742       if (!deadtri(sampletri.tri)) {
7743         org(sampletri, torg);
7744         dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
7745                (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
7746         if (dist < searchdist) {
7747           otricopy(sampletri, *searchtri);
7748           searchdist = dist;
7749           if (b->verbose > 2) {
7750             printf("    Choosing triangle with origin (%.12g, %.12g).\n",
7751                    torg[0], torg[1]);
7752           }
7753         }
7754       }
7755 
7756       samplesleft--;
7757       totalsamplesleft--;
7758     } while ((samplesleft > 0) && (totalsamplesleft > 0));
7759 
7760     if (totalsamplesleft > 0) {
7761       sampleblock = (VOID **) *sampleblock;
7762       samplesleft = samplesperblock;
7763       totalpopulation -= population;
7764       population = TRIPERBLOCK;
7765     }
7766   }
7767 
7768   /* Where are we? */
7769   org(*searchtri, torg);
7770   dest(*searchtri, tdest);
7771   /* Check the starting triangle's vertices. */
7772   if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
7773     return ONVERTEX;
7774   }
7775   if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
7776     lnextself(*searchtri);
7777     return ONVERTEX;
7778   }
7779   /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
7780   ahead = counterclockwise(m, b, torg, tdest, searchpoint);
7781   if (ahead < 0.0) {
7782     /* Turn around so that `searchpoint' is to the left of the */
7783     /*   edge specified by `searchtri'.                        */
7784     symself(*searchtri);
7785   } else if (ahead == 0.0) {
7786     /* Check if `searchpoint' is between `torg' and `tdest'. */
7787     if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) &&
7788         ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
7789       return ONEDGE;
7790     }
7791   }
7792   return preciselocate(m, b, searchpoint, searchtri, 0);
7793 }
7794 
7795 /**                                                                         **/
7796 /**                                                                         **/
7797 /********* Point location routines end here                          *********/
7798 
7799 /********* Mesh transformation routines begin here                   *********/
7800 /**                                                                         **/
7801 /**                                                                         **/
7802 
7803 /*****************************************************************************/
7804 /*                                                                           */
7805 /*  insertsubseg()   Create a new subsegment and insert it between two       */
7806 /*                   triangles.                                              */
7807 /*                                                                           */
7808 /*  The new subsegment is inserted at the edge described by the handle       */
7809 /*  `tri'.  Its vertices are properly initialized.  The marker `subsegmark'  */
7810 /*  is applied to the subsegment and, if appropriate, its vertices.          */
7811 /*                                                                           */
7812 /*****************************************************************************/
7813 
7814 #ifdef ANSI_DECLARATORS
7815 void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
7816                   int subsegmark)
7817 #else /* not ANSI_DECLARATORS */
7818 void insertsubseg(m, b, tri, subsegmark)
7819 struct mesh *m;
7820 struct behavior *b;
7821 struct otri *tri;             /* Edge at which to insert the new subsegment. */
7822 int subsegmark;                            /* Marker for the new subsegment. */
7823 #endif /* not ANSI_DECLARATORS */
7824 
7825 {
7826   struct otri oppotri;
7827   struct osub newsubseg;
7828   vertex triorg, tridest;
7829   triangle ptr;                         /* Temporary variable used by sym(). */
7830   subseg sptr;                      /* Temporary variable used by tspivot(). */
7831 
7832   org(*tri, triorg);
7833   dest(*tri, tridest);
7834   /* Mark vertices if possible. */
7835   if (vertexmark(triorg) == 0) {
7836     setvertexmark(triorg, subsegmark);
7837   }
7838   if (vertexmark(tridest) == 0) {
7839     setvertexmark(tridest, subsegmark);
7840   }
7841   /* Check if there's already a subsegment here. */
7842   tspivot(*tri, newsubseg);
7843   if (newsubseg.ss == m->dummysub) {
7844     /* Make new subsegment and initialize its vertices. */
7845     makesubseg(m, &newsubseg);
7846     setsorg(newsubseg, tridest);
7847     setsdest(newsubseg, triorg);
7848     setsegorg(newsubseg, tridest);
7849     setsegdest(newsubseg, triorg);
7850     /* Bond new subsegment to the two triangles it is sandwiched between. */
7851     /*   Note that the facing triangle `oppotri' might be equal to        */
7852     /*   `dummytri' (outer space), but the new subsegment is bonded to it */
7853     /*   all the same.                                                    */
7854     tsbond(*tri, newsubseg);
7855     sym(*tri, oppotri);
7856     ssymself(newsubseg);
7857     tsbond(oppotri, newsubseg);
7858     setmark(newsubseg, subsegmark);
7859     if (b->verbose > 2) {
7860       printf("  Inserting new ");
7861       printsubseg(m, b, &newsubseg);
7862     }
7863   } else {
7864     if (mark(newsubseg) == 0) {
7865       setmark(newsubseg, subsegmark);
7866     }
7867   }
7868 }
7869 
7870 /*****************************************************************************/
7871 /*                                                                           */
7872 /*  Terminology                                                              */
7873 /*                                                                           */
7874 /*  A "local transformation" replaces a small set of triangles with another  */
7875 /*  set of triangles.  This may or may not involve inserting or deleting a   */
7876 /*  vertex.                                                                  */
7877 /*                                                                           */
7878 /*  The term "casing" is used to describe the set of triangles that are      */
7879 /*  attached to the triangles being transformed, but are not transformed     */
7880 /*  themselves.  Think of the casing as a fixed hollow structure inside      */
7881 /*  which all the action happens.  A "casing" is only defined relative to    */
7882 /*  a single transformation; each occurrence of a transformation will        */
7883 /*  involve a different casing.                                              */
7884 /*                                                                           */
7885 /*****************************************************************************/
7886 
7887 /*****************************************************************************/
7888 /*                                                                           */
7889 /*  flip()   Transform two triangles to two different triangles by flipping  */
7890 /*           an edge counterclockwise within a quadrilateral.                */
7891 /*                                                                           */
7892 /*  Imagine the original triangles, abc and bad, oriented so that the        */
7893 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
7894 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
7895 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
7896 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
7897 /*                                                                           */
7898 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
7899 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
7900 /*  they are reused for dca and cdb, respectively.  Hence, any handles that  */
7901 /*  may have held the original triangles are still valid, although not       */
7902 /*  directed as they were before.                                            */
7903 /*                                                                           */
7904 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
7905 /*  dc of triangle dca, and is directed down, from vertex d to vertex c.     */
7906 /*  (Hence, the two triangles have rotated counterclockwise.)                */
7907 /*                                                                           */
7908 /*  WARNING:  This transformation is geometrically valid only if the         */
7909 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
7910 /*  valid only if there is not a subsegment between the triangles abc and    */
7911 /*  bad.  This routine does not check either of these preconditions, and     */
7912 /*  it is the responsibility of the calling routine to ensure that they are  */
7913 /*  met.  If they are not, the streets shall be filled with wailing and      */
7914 /*  gnashing of teeth.                                                       */
7915 /*                                                                           */
7916 /*****************************************************************************/
7917 
7918 #ifdef ANSI_DECLARATORS
7919 void flip(struct mesh *m, struct behavior *b, struct otri *flipedge)
7920 #else /* not ANSI_DECLARATORS */
7921 void flip(m, b, flipedge)
7922 struct mesh *m;
7923 struct behavior *b;
7924 struct otri *flipedge;                    /* Handle for the triangle abc. */
7925 #endif /* not ANSI_DECLARATORS */
7926 
7927 {
7928   struct otri botleft, botright;
7929   struct otri topleft, topright;
7930   struct otri top;
7931   struct otri botlcasing, botrcasing;
7932   struct otri toplcasing, toprcasing;
7933   struct osub botlsubseg, botrsubseg;
7934   struct osub toplsubseg, toprsubseg;
7935   vertex leftvertex, rightvertex, botvertex;
7936   vertex farvertex;
7937   triangle ptr;                         /* Temporary variable used by sym(). */
7938   subseg sptr;                      /* Temporary variable used by tspivot(). */
7939 
7940   /* Identify the vertices of the quadrilateral. */
7941   org(*flipedge, rightvertex);
7942   dest(*flipedge, leftvertex);
7943   apex(*flipedge, botvertex);
7944   sym(*flipedge, top);
7945 #ifdef SELF_CHECK
7946   if (top.tri == m->dummytri) {
7947     printf("Internal error in flip():  Attempt to flip on boundary.\n");
7948     lnextself(*flipedge);
7949     return;
7950   }
7951   if (m->checksegments) {
7952     tspivot(*flipedge, toplsubseg);
7953     if (toplsubseg.ss != m->dummysub) {
7954       printf("Internal error in flip():  Attempt to flip a segment.\n");
7955       lnextself(*flipedge);
7956       return;
7957     }
7958   }
7959 #endif /* SELF_CHECK */
7960   apex(top, farvertex);
7961 
7962   /* Identify the casing of the quadrilateral. */
7963   lprev(top, topleft);
7964   sym(topleft, toplcasing);
7965   lnext(top, topright);
7966   sym(topright, toprcasing);
7967   lnext(*flipedge, botleft);
7968   sym(botleft, botlcasing);
7969   lprev(*flipedge, botright);
7970   sym(botright, botrcasing);
7971   /* Rotate the quadrilateral one-quarter turn counterclockwise. */
7972   bond(topleft, botlcasing);
7973   bond(botleft, botrcasing);
7974   bond(botright, toprcasing);
7975   bond(topright, toplcasing);
7976 
7977   if (m->checksegments) {
7978     /* Check for subsegments and rebond them to the quadrilateral. */
7979     tspivot(topleft, toplsubseg);
7980     tspivot(botleft, botlsubseg);
7981     tspivot(botright, botrsubseg);
7982     tspivot(topright, toprsubseg);
7983     if (toplsubseg.ss == m->dummysub) {
7984       tsdissolve(topright);
7985     } else {
7986       tsbond(topright, toplsubseg);
7987     }
7988     if (botlsubseg.ss == m->dummysub) {
7989       tsdissolve(topleft);
7990     } else {
7991       tsbond(topleft, botlsubseg);
7992     }
7993     if (botrsubseg.ss == m->dummysub) {
7994       tsdissolve(botleft);
7995     } else {
7996       tsbond(botleft, botrsubseg);
7997     }
7998     if (toprsubseg.ss == m->dummysub) {
7999       tsdissolve(botright);
8000     } else {
8001       tsbond(botright, toprsubseg);
8002     }
8003   }
8004 
8005   /* New vertex assignments for the rotated quadrilateral. */
8006   setorg(*flipedge, farvertex);
8007   setdest(*flipedge, botvertex);
8008   setapex(*flipedge, rightvertex);
8009   setorg(top, botvertex);
8010   setdest(top, farvertex);
8011   setapex(top, leftvertex);
8012   if (b->verbose > 2) {
8013     printf("  Edge flip results in left ");
8014     printtriangle(m, b, &top);
8015     printf("  and right ");
8016     printtriangle(m, b, flipedge);
8017   }
8018 }
8019 
8020 /*****************************************************************************/
8021 /*                                                                           */
8022 /*  unflip()   Transform two triangles to two different triangles by         */
8023 /*             flipping an edge clockwise within a quadrilateral.  Reverses  */
8024 /*             the flip() operation so that the data structures representing */
8025 /*             the triangles are back where they were before the flip().     */
8026 /*                                                                           */
8027 /*  Imagine the original triangles, abc and bad, oriented so that the        */
8028 /*  shared edge ab lies in a horizontal plane, with the vertex b on the left */
8029 /*  and the vertex a on the right.  The vertex c lies below the edge, and    */
8030 /*  the vertex d lies above the edge.  The `flipedge' handle holds the edge  */
8031 /*  ab of triangle abc, and is directed left, from vertex a to vertex b.     */
8032 /*                                                                           */
8033 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
8034 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
8035 /*  they are reused for cdb and dca, respectively.  Hence, any handles that  */
8036 /*  may have held the original triangles are still valid, although not       */
8037 /*  directed as they were before.                                            */
8038 /*                                                                           */
8039 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
8040 /*  cd of triangle cdb, and is directed up, from vertex c to vertex d.       */
8041 /*  (Hence, the two triangles have rotated clockwise.)                       */
8042 /*                                                                           */
8043 /*  WARNING:  This transformation is geometrically valid only if the         */
8044 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
8045 /*  valid only if there is not a subsegment between the triangles abc and    */
8046 /*  bad.  This routine does not check either of these preconditions, and     */
8047 /*  it is the responsibility of the calling routine to ensure that they are  */
8048 /*  met.  If they are not, the streets shall be filled with wailing and      */
8049 /*  gnashing of teeth.                                                       */
8050 /*                                                                           */
8051 /*****************************************************************************/
8052 
8053 #ifdef ANSI_DECLARATORS
8054 void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge)
8055 #else /* not ANSI_DECLARATORS */
8056 void unflip(m, b, flipedge)
8057 struct mesh *m;
8058 struct behavior *b;
8059 struct otri *flipedge;                    /* Handle for the triangle abc. */
8060 #endif /* not ANSI_DECLARATORS */
8061 
8062 {
8063   struct otri botleft, botright;
8064   struct otri topleft, topright;
8065   struct otri top;
8066   struct otri botlcasing, botrcasing;
8067   struct otri toplcasing, toprcasing;
8068   struct osub botlsubseg, botrsubseg;
8069   struct osub toplsubseg, toprsubseg;
8070   vertex leftvertex, rightvertex, botvertex;
8071   vertex farvertex;
8072   triangle ptr;                         /* Temporary variable used by sym(). */
8073   subseg sptr;                      /* Temporary variable used by tspivot(). */
8074 
8075   /* Identify the vertices of the quadrilateral. */
8076   org(*flipedge, rightvertex);
8077   dest(*flipedge, leftvertex);
8078   apex(*flipedge, botvertex);
8079   sym(*flipedge, top);
8080 #ifdef SELF_CHECK
8081   if (top.tri == m->dummytri) {
8082     printf("Internal error in unflip():  Attempt to flip on boundary.\n");
8083     lnextself(*flipedge);
8084     return;
8085   }
8086   if (m->checksegments) {
8087     tspivot(*flipedge, toplsubseg);
8088     if (toplsubseg.ss != m->dummysub) {
8089       printf("Internal error in unflip():  Attempt to flip a subsegment.\n");
8090       lnextself(*flipedge);
8091       return;
8092     }
8093   }
8094 #endif /* SELF_CHECK */
8095   apex(top, farvertex);
8096 
8097   /* Identify the casing of the quadrilateral. */
8098   lprev(top, topleft);
8099   sym(topleft, toplcasing);
8100   lnext(top, topright);
8101   sym(topright, toprcasing);
8102   lnext(*flipedge, botleft);
8103   sym(botleft, botlcasing);
8104   lprev(*flipedge, botright);
8105   sym(botright, botrcasing);
8106   /* Rotate the quadrilateral one-quarter turn clockwise. */
8107   bond(topleft, toprcasing);
8108   bond(botleft, toplcasing);
8109   bond(botright, botlcasing);
8110   bond(topright, botrcasing);
8111 
8112   if (m->checksegments) {
8113     /* Check for subsegments and rebond them to the quadrilateral. */
8114     tspivot(topleft, toplsubseg);
8115     tspivot(botleft, botlsubseg);
8116     tspivot(botright, botrsubseg);
8117     tspivot(topright, toprsubseg);
8118     if (toplsubseg.ss == m->dummysub) {
8119       tsdissolve(botleft);
8120     } else {
8121       tsbond(botleft, toplsubseg);
8122     }
8123     if (botlsubseg.ss == m->dummysub) {
8124       tsdissolve(botright);
8125     } else {
8126       tsbond(botright, botlsubseg);
8127     }
8128     if (botrsubseg.ss == m->dummysub) {
8129       tsdissolve(topright);
8130     } else {
8131       tsbond(topright, botrsubseg);
8132     }
8133     if (toprsubseg.ss == m->dummysub) {
8134       tsdissolve(topleft);
8135     } else {
8136       tsbond(topleft, toprsubseg);
8137     }
8138   }
8139 
8140   /* New vertex assignments for the rotated quadrilateral. */
8141   setorg(*flipedge, botvertex);
8142   setdest(*flipedge, farvertex);
8143   setapex(*flipedge, leftvertex);
8144   setorg(top, farvertex);
8145   setdest(top, botvertex);
8146   setapex(top, rightvertex);
8147   if (b->verbose > 2) {
8148     printf("  Edge unflip results in left ");
8149     printtriangle(m, b, flipedge);
8150     printf("  and right ");
8151     printtriangle(m, b, &top);
8152   }
8153 }
8154 
8155 /*****************************************************************************/
8156 /*                                                                           */
8157 /*  insertvertex()   Insert a vertex into a Delaunay triangulation,          */
8158 /*                   performing flips as necessary to maintain the Delaunay  */
8159 /*                   property.                                               */
8160 /*                                                                           */
8161 /*  The point `insertvertex' is located.  If `searchtri.tri' is not NULL,    */
8162 /*  the search for the containing triangle begins from `searchtri'.  If      */
8163 /*  `searchtri.tri' is NULL, a full point location procedure is called.      */
8164 /*  If `insertvertex' is found inside a triangle, the triangle is split into */
8165 /*  three; if `insertvertex' lies on an edge, the edge is split in two,      */
8166 /*  thereby splitting the two adjacent triangles into four.  Edge flips are  */
8167 /*  used to restore the Delaunay property.  If `insertvertex' lies on an     */
8168 /*  existing vertex, no action is taken, and the value DUPLICATEVERTEX is    */
8169 /*  returned.  On return, `searchtri' is set to a handle whose origin is the */
8170 /*  existing vertex.                                                         */
8171 /*                                                                           */
8172 /*  Normally, the parameter `splitseg' is set to NULL, implying that no      */
8173 /*  subsegment should be split.  In this case, if `insertvertex' is found to */
8174 /*  lie on a segment, no action is taken, and the value VIOLATINGVERTEX is   */
8175 /*  returned.  On return, `searchtri' is set to a handle whose primary edge  */
8176 /*  is the violated subsegment.                                              */
8177 /*                                                                           */
8178 /*  If the calling routine wishes to split a subsegment by inserting a       */
8179 /*  vertex in it, the parameter `splitseg' should be that subsegment.  In    */
8180 /*  this case, `searchtri' MUST be the triangle handle reached by pivoting   */
8181 /*  from that subsegment; no point location is done.                         */
8182 /*                                                                           */
8183 /*  `segmentflaws' and `triflaws' are flags that indicate whether or not     */
8184 /*  there should be checks for the creation of encroached subsegments or bad */
8185 /*  quality triangles.  If a newly inserted vertex encroaches upon           */
8186 /*  subsegments, these subsegments are added to the list of subsegments to   */
8187 /*  be split if `segmentflaws' is set.  If bad triangles are created, these  */
8188 /*  are added to the queue if `triflaws' is set.                             */
8189 /*                                                                           */
8190 /*  If a duplicate vertex or violated segment does not prevent the vertex    */
8191 /*  from being inserted, the return value will be ENCROACHINGVERTEX if the   */
8192 /*  vertex encroaches upon a subsegment (and checking is enabled), or        */
8193 /*  SUCCESSFULVERTEX otherwise.  In either case, `searchtri' is set to a     */
8194 /*  handle whose origin is the newly inserted vertex.                        */
8195 /*                                                                           */
8196 /*  insertvertex() does not use flip() for reasons of speed; some            */
8197 /*  information can be reused from edge flip to edge flip, like the          */
8198 /*  locations of subsegments.                                                */
8199 /*                                                                           */
8200 /*****************************************************************************/
8201 
8202 #ifdef ANSI_DECLARATORS
8203 enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
8204                                      vertex newvertex, struct otri *searchtri,
8205                                      struct osub *splitseg,
8206                                      int segmentflaws, int triflaws)
8207 #else /* not ANSI_DECLARATORS */
8208 enum insertvertexresult insertvertex(m, b, newvertex, searchtri, splitseg,
8209                                      segmentflaws, triflaws)
8210 struct mesh *m;
8211 struct behavior *b;
8212 vertex newvertex;
8213 struct otri *searchtri;
8214 struct osub *splitseg;
8215 int segmentflaws;
8216 int triflaws;
8217 #endif /* not ANSI_DECLARATORS */
8218 
8219 {
8220   struct otri horiz;
8221   struct otri top;
8222   struct otri botleft, botright;
8223   struct otri topleft, topright;
8224   struct otri newbotleft, newbotright;
8225   struct otri newtopright;
8226   struct otri botlcasing, botrcasing;
8227   struct otri toplcasing, toprcasing;
8228   struct otri testtri;
8229   struct osub botlsubseg, botrsubseg;
8230   struct osub toplsubseg, toprsubseg;
8231   struct osub brokensubseg;
8232   struct osub checksubseg;
8233   struct osub rightsubseg;
8234   struct osub newsubseg;
8235   struct badsubseg *encroached;
8236   struct flipstacker *newflip;
8237   vertex first;
8238   vertex leftvertex, rightvertex, botvertex, topvertex, farvertex;
8239   vertex segmentorg, segmentdest;
8240   REAL attrib;
8241   REAL area;
8242   enum insertvertexresult success;
8243   enum locateresult intersect;
8244   int doflip;
8245   int mirrorflag;
8246   int enq;
8247   int i;
8248   triangle ptr;                         /* Temporary variable used by sym(). */
8249   subseg sptr;         /* Temporary variable used by spivot() and tspivot(). */
8250 
8251   if (b->verbose > 1) {
8252     printf("  Inserting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
8253   }
8254 
8255   if (splitseg == (struct osub *) NULL) {
8256     /* Find the location of the vertex to be inserted.  Check if a good */
8257     /*   starting triangle has already been provided by the caller.     */
8258     if (searchtri->tri == m->dummytri) {
8259       /* Find a boundary triangle. */
8260       horiz.tri = m->dummytri;
8261       horiz.orient = 0;
8262       symself(horiz);
8263       /* Search for a triangle containing `newvertex'. */
8264       intersect = locate(m, b, newvertex, &horiz);
8265     } else {
8266       /* Start searching from the triangle provided by the caller. */
8267       otricopy(*searchtri, horiz);
8268       intersect = preciselocate(m, b, newvertex, &horiz, 1);
8269     }
8270   } else {
8271     /* The calling routine provides the subsegment in which */
8272     /*   the vertex is inserted.                             */
8273     otricopy(*searchtri, horiz);
8274     intersect = ONEDGE;
8275   }
8276 
8277   if (intersect == ONVERTEX) {
8278     /* There's already a vertex there.  Return in `searchtri' a triangle */
8279     /*   whose origin is the existing vertex.                            */
8280     otricopy(horiz, *searchtri);
8281     otricopy(horiz, m->recenttri);
8282     return DUPLICATEVERTEX;
8283   }
8284   if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
8285     /* The vertex falls on an edge or boundary. */
8286     if (m->checksegments && (splitseg == (struct osub *) NULL)) {
8287       /* Check whether the vertex falls on a subsegment. */
8288       tspivot(horiz, brokensubseg);
8289       if (brokensubseg.ss != m->dummysub) {
8290         /* The vertex falls on a subsegment, and hence will not be inserted. */
8291         if (segmentflaws) {
8292           enq = b->nobisect != 2;
8293           if (enq && (b->nobisect == 1)) {
8294             /* This subsegment may be split only if it is an */
8295             /*   internal boundary.                          */
8296             sym(horiz, testtri);
8297             enq = testtri.tri != m->dummytri;
8298           }
8299           if (enq) {
8300             /* Add the subsegment to the list of encroached subsegments. */
8301             encroached = (struct badsubseg *) poolalloc(&m->badsubsegs);
8302             encroached->encsubseg = sencode(brokensubseg);
8303             sorg(brokensubseg, encroached->subsegorg);
8304             sdest(brokensubseg, encroached->subsegdest);
8305             if (b->verbose > 2) {
8306               printf(
8307           "  Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
8308                      encroached->subsegorg[0], encroached->subsegorg[1],
8309                      encroached->subsegdest[0], encroached->subsegdest[1]);
8310             }
8311           }
8312         }
8313         /* Return a handle whose primary edge contains the vertex, */
8314         /*   which has not been inserted.                          */
8315         otricopy(horiz, *searchtri);
8316         otricopy(horiz, m->recenttri);
8317         return VIOLATINGVERTEX;
8318       }
8319     }
8320 
8321     /* Insert the vertex on an edge, dividing one triangle into two (if */
8322     /*   the edge lies on a boundary) or two triangles into four.       */
8323     lprev(horiz, botright);
8324     sym(botright, botrcasing);
8325     sym(horiz, topright);
8326     /* Is there a second triangle?  (Or does this edge lie on a boundary?) */
8327     mirrorflag = topright.tri != m->dummytri;
8328     if (mirrorflag) {
8329       lnextself(topright);
8330       sym(topright, toprcasing);
8331       maketriangle(m, b, &newtopright);
8332     } else {
8333       /* Splitting a boundary edge increases the number of boundary edges. */
8334       m->hullsize++;
8335     }
8336     maketriangle(m, b, &newbotright);
8337 
8338     /* Set the vertices of changed and new triangles. */
8339     org(horiz, rightvertex);
8340     dest(horiz, leftvertex);
8341     apex(horiz, botvertex);
8342     setorg(newbotright, botvertex);
8343     setdest(newbotright, rightvertex);
8344     setapex(newbotright, newvertex);
8345     setorg(horiz, newvertex);
8346     for (i = 0; i < m->eextras; i++) {
8347       /* Set the element attributes of a new triangle. */
8348       setelemattribute(newbotright, i, elemattribute(botright, i));
8349     }
8350     if (b->vararea) {
8351       /* Set the area constraint of a new triangle. */
8352       setareabound(newbotright, areabound(botright));
8353     }
8354     if (mirrorflag) {
8355       dest(topright, topvertex);
8356       setorg(newtopright, rightvertex);
8357       setdest(newtopright, topvertex);
8358       setapex(newtopright, newvertex);
8359       setorg(topright, newvertex);
8360       for (i = 0; i < m->eextras; i++) {
8361         /* Set the element attributes of another new triangle. */
8362         setelemattribute(newtopright, i, elemattribute(topright, i));
8363       }
8364       if (b->vararea) {
8365         /* Set the area constraint of another new triangle. */
8366         setareabound(newtopright, areabound(topright));
8367       }
8368     }
8369 
8370     /* There may be subsegments that need to be bonded */
8371     /*   to the new triangle(s).                       */
8372     if (m->checksegments) {
8373       tspivot(botright, botrsubseg);
8374       if (botrsubseg.ss != m->dummysub) {
8375         tsdissolve(botright);
8376         tsbond(newbotright, botrsubseg);
8377       }
8378       if (mirrorflag) {
8379         tspivot(topright, toprsubseg);
8380         if (toprsubseg.ss != m->dummysub) {
8381           tsdissolve(topright);
8382           tsbond(newtopright, toprsubseg);
8383         }
8384       }
8385     }
8386 
8387     /* Bond the new triangle(s) to the surrounding triangles. */
8388     bond(newbotright, botrcasing);
8389     lprevself(newbotright);
8390     bond(newbotright, botright);
8391     lprevself(newbotright);
8392     if (mirrorflag) {
8393       bond(newtopright, toprcasing);
8394       lnextself(newtopright);
8395       bond(newtopright, topright);
8396       lnextself(newtopright);
8397       bond(newtopright, newbotright);
8398     }
8399 
8400     if (splitseg != (struct osub *) NULL) {
8401       /* Split the subsegment into two. */
8402       setsdest(*splitseg, newvertex);
8403       segorg(*splitseg, segmentorg);
8404       segdest(*splitseg, segmentdest);
8405       ssymself(*splitseg);
8406       spivot(*splitseg, rightsubseg);
8407       insertsubseg(m, b, &newbotright, mark(*splitseg));
8408       tspivot(newbotright, newsubseg);
8409       setsegorg(newsubseg, segmentorg);
8410       setsegdest(newsubseg, segmentdest);
8411       sbond(*splitseg, newsubseg);
8412       ssymself(newsubseg);
8413       sbond(newsubseg, rightsubseg);
8414       ssymself(*splitseg);
8415       /* Transfer the subsegment's boundary marker to the vertex */
8416       /*   if required.                                          */
8417       if (vertexmark(newvertex) == 0) {
8418         setvertexmark(newvertex, mark(*splitseg));
8419       }
8420     }
8421 
8422     if (m->checkquality) {
8423       poolrestart(&m->flipstackers);
8424       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8425       m->lastflip->flippedtri = encode(horiz);
8426       m->lastflip->prevflip = (struct flipstacker *) &insertvertex;
8427     }
8428 
8429 #ifdef SELF_CHECK
8430     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8431       printf("Internal error in insertvertex():\n");
8432       printf(
8433             "  Clockwise triangle prior to edge vertex insertion (bottom).\n");
8434     }
8435     if (mirrorflag) {
8436       if (counterclockwise(m, b, leftvertex, rightvertex, topvertex) < 0.0) {
8437         printf("Internal error in insertvertex():\n");
8438         printf("  Clockwise triangle prior to edge vertex insertion (top).\n");
8439       }
8440       if (counterclockwise(m, b, rightvertex, topvertex, newvertex) < 0.0) {
8441         printf("Internal error in insertvertex():\n");
8442         printf(
8443             "  Clockwise triangle after edge vertex insertion (top right).\n");
8444       }
8445       if (counterclockwise(m, b, topvertex, leftvertex, newvertex) < 0.0) {
8446         printf("Internal error in insertvertex():\n");
8447         printf(
8448             "  Clockwise triangle after edge vertex insertion (top left).\n");
8449       }
8450     }
8451     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8452       printf("Internal error in insertvertex():\n");
8453       printf(
8454           "  Clockwise triangle after edge vertex insertion (bottom left).\n");
8455     }
8456     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8457       printf("Internal error in insertvertex():\n");
8458       printf(
8459         "  Clockwise triangle after edge vertex insertion (bottom right).\n");
8460     }
8461 #endif /* SELF_CHECK */
8462     if (b->verbose > 2) {
8463       printf("  Updating bottom left ");
8464       printtriangle(m, b, &botright);
8465       if (mirrorflag) {
8466         printf("  Updating top left ");
8467         printtriangle(m, b, &topright);
8468         printf("  Creating top right ");
8469         printtriangle(m, b, &newtopright);
8470       }
8471       printf("  Creating bottom right ");
8472       printtriangle(m, b, &newbotright);
8473     }
8474 
8475     /* Position `horiz' on the first edge to check for */
8476     /*   the Delaunay property.                        */
8477     lnextself(horiz);
8478   } else {
8479     /* Insert the vertex in a triangle, splitting it into three. */
8480     lnext(horiz, botleft);
8481     lprev(horiz, botright);
8482     sym(botleft, botlcasing);
8483     sym(botright, botrcasing);
8484     maketriangle(m, b, &newbotleft);
8485     maketriangle(m, b, &newbotright);
8486 
8487     /* Set the vertices of changed and new triangles. */
8488     org(horiz, rightvertex);
8489     dest(horiz, leftvertex);
8490     apex(horiz, botvertex);
8491     setorg(newbotleft, leftvertex);
8492     setdest(newbotleft, botvertex);
8493     setapex(newbotleft, newvertex);
8494     setorg(newbotright, botvertex);
8495     setdest(newbotright, rightvertex);
8496     setapex(newbotright, newvertex);
8497     setapex(horiz, newvertex);
8498     for (i = 0; i < m->eextras; i++) {
8499       /* Set the element attributes of the new triangles. */
8500       attrib = elemattribute(horiz, i);
8501       setelemattribute(newbotleft, i, attrib);
8502       setelemattribute(newbotright, i, attrib);
8503     }
8504     if (b->vararea) {
8505       /* Set the area constraint of the new triangles. */
8506       area = areabound(horiz);
8507       setareabound(newbotleft, area);
8508       setareabound(newbotright, area);
8509     }
8510 
8511     /* There may be subsegments that need to be bonded */
8512     /*   to the new triangles.                         */
8513     if (m->checksegments) {
8514       tspivot(botleft, botlsubseg);
8515       if (botlsubseg.ss != m->dummysub) {
8516         tsdissolve(botleft);
8517         tsbond(newbotleft, botlsubseg);
8518       }
8519       tspivot(botright, botrsubseg);
8520       if (botrsubseg.ss != m->dummysub) {
8521         tsdissolve(botright);
8522         tsbond(newbotright, botrsubseg);
8523       }
8524     }
8525 
8526     /* Bond the new triangles to the surrounding triangles. */
8527     bond(newbotleft, botlcasing);
8528     bond(newbotright, botrcasing);
8529     lnextself(newbotleft);
8530     lprevself(newbotright);
8531     bond(newbotleft, newbotright);
8532     lnextself(newbotleft);
8533     bond(botleft, newbotleft);
8534     lprevself(newbotright);
8535     bond(botright, newbotright);
8536 
8537     if (m->checkquality) {
8538       poolrestart(&m->flipstackers);
8539       m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8540       m->lastflip->flippedtri = encode(horiz);
8541       m->lastflip->prevflip = (struct flipstacker *) NULL;
8542     }
8543 
8544 #ifdef SELF_CHECK
8545     if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
8546       printf("Internal error in insertvertex():\n");
8547       printf("  Clockwise triangle prior to vertex insertion.\n");
8548     }
8549     if (counterclockwise(m, b, rightvertex, leftvertex, newvertex) < 0.0) {
8550       printf("Internal error in insertvertex():\n");
8551       printf("  Clockwise triangle after vertex insertion (top).\n");
8552     }
8553     if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
8554       printf("Internal error in insertvertex():\n");
8555       printf("  Clockwise triangle after vertex insertion (left).\n");
8556     }
8557     if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
8558       printf("Internal error in insertvertex():\n");
8559       printf("  Clockwise triangle after vertex insertion (right).\n");
8560     }
8561 #endif /* SELF_CHECK */
8562     if (b->verbose > 2) {
8563       printf("  Updating top ");
8564       printtriangle(m, b, &horiz);
8565       printf("  Creating left ");
8566       printtriangle(m, b, &newbotleft);
8567       printf("  Creating right ");
8568       printtriangle(m, b, &newbotright);
8569     }
8570   }
8571 
8572   /* The insertion is successful by default, unless an encroached */
8573   /*   subsegment is found.                                       */
8574   success = SUCCESSFULVERTEX;
8575   /* Circle around the newly inserted vertex, checking each edge opposite */
8576   /*   it for the Delaunay property.  Non-Delaunay edges are flipped.     */
8577   /*   `horiz' is always the edge being checked.  `first' marks where to  */
8578   /*   stop circling.                                                     */
8579   org(horiz, first);
8580   rightvertex = first;
8581   dest(horiz, leftvertex);
8582   /* Circle until finished. */
8583   while (1) {
8584     /* By default, the edge will be flipped. */
8585     doflip = 1;
8586 
8587     if (m->checksegments) {
8588       /* Check for a subsegment, which cannot be flipped. */
8589       tspivot(horiz, checksubseg);
8590       if (checksubseg.ss != m->dummysub) {
8591         /* The edge is a subsegment and cannot be flipped. */
8592         doflip = 0;
8593 #ifndef CDT_ONLY
8594         if (segmentflaws) {
8595           /* Does the new vertex encroach upon this subsegment? */
8596           if (checkseg4encroach(m, b, &checksubseg)) {
8597             success = ENCROACHINGVERTEX;
8598           }
8599         }
8600 #endif /* not CDT_ONLY */
8601       }
8602     }
8603 
8604     if (doflip) {
8605       /* Check if the edge is a boundary edge. */
8606       sym(horiz, top);
8607       if (top.tri == m->dummytri) {
8608         /* The edge is a boundary edge and cannot be flipped. */
8609         doflip = 0;
8610       } else {
8611         /* Find the vertex on the other side of the edge. */
8612         apex(top, farvertex);
8613         /* In the incremental Delaunay triangulation algorithm, any of      */
8614         /*   `leftvertex', `rightvertex', and `farvertex' could be vertices */
8615         /*   of the triangular bounding box.  These vertices must be        */
8616         /*   treated as if they are infinitely distant, even though their   */
8617         /*   "coordinates" are not.                                         */
8618         if ((leftvertex == m->infvertex1) || (leftvertex == m->infvertex2) ||
8619             (leftvertex == m->infvertex3)) {
8620           /* `leftvertex' is infinitely distant.  Check the convexity of  */
8621           /*   the boundary of the triangulation.  'farvertex' might be   */
8622           /*   infinite as well, but trust me, this same condition should */
8623           /*   be applied.                                                */
8624           doflip = counterclockwise(m, b, newvertex, rightvertex, farvertex)
8625                    > 0.0;
8626         } else if ((rightvertex == m->infvertex1) ||
8627                    (rightvertex == m->infvertex2) ||
8628                    (rightvertex == m->infvertex3)) {
8629           /* `rightvertex' is infinitely distant.  Check the convexity of */
8630           /*   the boundary of the triangulation.  'farvertex' might be   */
8631           /*   infinite as well, but trust me, this same condition should */
8632           /*   be applied.                                                */
8633           doflip = counterclockwise(m, b, farvertex, leftvertex, newvertex)
8634                    > 0.0;
8635         } else if ((farvertex == m->infvertex1) ||
8636                    (farvertex == m->infvertex2) ||
8637                    (farvertex == m->infvertex3)) {
8638           /* `farvertex' is infinitely distant and cannot be inside */
8639           /*   the circumcircle of the triangle `horiz'.            */
8640           doflip = 0;
8641         } else {
8642           /* Test whether the edge is locally Delaunay. */
8643           doflip = incircle(m, b, leftvertex, newvertex, rightvertex,
8644                             farvertex) > 0.0;
8645         }
8646         if (doflip) {
8647           /* We made it!  Flip the edge `horiz' by rotating its containing */
8648           /*   quadrilateral (the two triangles adjacent to `horiz').      */
8649           /* Identify the casing of the quadrilateral. */
8650           lprev(top, topleft);
8651           sym(topleft, toplcasing);
8652           lnext(top, topright);
8653           sym(topright, toprcasing);
8654           lnext(horiz, botleft);
8655           sym(botleft, botlcasing);
8656           lprev(horiz, botright);
8657           sym(botright, botrcasing);
8658           /* Rotate the quadrilateral one-quarter turn counterclockwise. */
8659           bond(topleft, botlcasing);
8660           bond(botleft, botrcasing);
8661           bond(botright, toprcasing);
8662           bond(topright, toplcasing);
8663           if (m->checksegments) {
8664             /* Check for subsegments and rebond them to the quadrilateral. */
8665             tspivot(topleft, toplsubseg);
8666             tspivot(botleft, botlsubseg);
8667             tspivot(botright, botrsubseg);
8668             tspivot(topright, toprsubseg);
8669             if (toplsubseg.ss == m->dummysub) {
8670               tsdissolve(topright);
8671             } else {
8672               tsbond(topright, toplsubseg);
8673             }
8674             if (botlsubseg.ss == m->dummysub) {
8675               tsdissolve(topleft);
8676             } else {
8677               tsbond(topleft, botlsubseg);
8678             }
8679             if (botrsubseg.ss == m->dummysub) {
8680               tsdissolve(botleft);
8681             } else {
8682               tsbond(botleft, botrsubseg);
8683             }
8684             if (toprsubseg.ss == m->dummysub) {
8685               tsdissolve(botright);
8686             } else {
8687               tsbond(botright, toprsubseg);
8688             }
8689           }
8690           /* New vertex assignments for the rotated quadrilateral. */
8691           setorg(horiz, farvertex);
8692           setdest(horiz, newvertex);
8693           setapex(horiz, rightvertex);
8694           setorg(top, newvertex);
8695           setdest(top, farvertex);
8696           setapex(top, leftvertex);
8697           for (i = 0; i < m->eextras; i++) {
8698             /* Take the average of the two triangles' attributes. */
8699             attrib = 0.5 * (elemattribute(top, i) + elemattribute(horiz, i));
8700             setelemattribute(top, i, attrib);
8701             setelemattribute(horiz, i, attrib);
8702           }
8703           if (b->vararea) {
8704             if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
8705               area = -1.0;
8706             } else {
8707               /* Take the average of the two triangles' area constraints.    */
8708               /*   This prevents small area constraints from migrating a     */
8709               /*   long, long way from their original location due to flips. */
8710               area = 0.5 * (areabound(top) + areabound(horiz));
8711             }
8712             setareabound(top, area);
8713             setareabound(horiz, area);
8714           }
8715 
8716           if (m->checkquality) {
8717             newflip = (struct flipstacker *) poolalloc(&m->flipstackers);
8718             newflip->flippedtri = encode(horiz);
8719             newflip->prevflip = m->lastflip;
8720             m->lastflip = newflip;
8721           }
8722 
8723 #ifdef SELF_CHECK
8724           if (newvertex != (vertex) NULL) {
8725             if (counterclockwise(m, b, leftvertex, newvertex, rightvertex) <
8726                 0.0) {
8727               printf("Internal error in insertvertex():\n");
8728               printf("  Clockwise triangle prior to edge flip (bottom).\n");
8729             }
8730             /* The following test has been removed because constrainededge() */
8731             /*   sometimes generates inverted triangles that insertvertex()  */
8732             /*   removes.                                                    */
8733 /*
8734             if (counterclockwise(m, b, rightvertex, farvertex, leftvertex) <
8735                 0.0) {
8736               printf("Internal error in insertvertex():\n");
8737               printf("  Clockwise triangle prior to edge flip (top).\n");
8738             }
8739 */
8740             if (counterclockwise(m, b, farvertex, leftvertex, newvertex) <
8741                 0.0) {
8742               printf("Internal error in insertvertex():\n");
8743               printf("  Clockwise triangle after edge flip (left).\n");
8744             }
8745             if (counterclockwise(m, b, newvertex, rightvertex, farvertex) <
8746                 0.0) {
8747               printf("Internal error in insertvertex():\n");
8748               printf("  Clockwise triangle after edge flip (right).\n");
8749             }
8750           }
8751 #endif /* SELF_CHECK */
8752           if (b->verbose > 2) {
8753             printf("  Edge flip results in left ");
8754             lnextself(topleft);
8755             printtriangle(m, b, &topleft);
8756             printf("  and right ");
8757             printtriangle(m, b, &horiz);
8758           }
8759           /* On the next iterations, consider the two edges that were  */
8760           /*   exposed (this is, are now visible to the newly inserted */
8761           /*   vertex) by the edge flip.                               */
8762           lprevself(horiz);
8763           leftvertex = farvertex;
8764         }
8765       }
8766     }
8767     if (!doflip) {
8768       /* The handle `horiz' is accepted as locally Delaunay. */
8769 #ifndef CDT_ONLY
8770       if (triflaws) {
8771         /* Check the triangle `horiz' for quality. */
8772         testtriangle(m, b, &horiz);
8773       }
8774 #endif /* not CDT_ONLY */
8775       /* Look for the next edge around the newly inserted vertex. */
8776       lnextself(horiz);
8777       sym(horiz, testtri);
8778       /* Check for finishing a complete revolution about the new vertex, or */
8779       /*   falling outside  of the triangulation.  The latter will happen   */
8780       /*   when a vertex is inserted at a boundary.                         */
8781       if ((leftvertex == first) || (testtri.tri == m->dummytri)) {
8782         /* We're done.  Return a triangle whose origin is the new vertex. */
8783         lnext(horiz, *searchtri);
8784         lnext(horiz, m->recenttri);
8785         return success;
8786       }
8787       /* Finish finding the next edge around the newly inserted vertex. */
8788       lnext(testtri, horiz);
8789       rightvertex = leftvertex;
8790       dest(horiz, leftvertex);
8791     }
8792   }
8793 }
8794 
8795 /*****************************************************************************/
8796 /*                                                                           */
8797 /*  triangulatepolygon()   Find the Delaunay triangulation of a polygon that */
8798 /*                         has a certain "nice" shape.  This includes the    */
8799 /*                         polygons that result from deletion of a vertex or */
8800 /*                         insertion of a segment.                           */
8801 /*                                                                           */
8802 /*  This is a conceptually difficult routine.  The starting assumption is    */
8803 /*  that we have a polygon with n sides.  n - 1 of these sides are currently */
8804 /*  represented as edges in the mesh.  One side, called the "base", need not */
8805 /*  be.                                                                      */
8806 /*                                                                           */
8807 /*  Inside the polygon is a structure I call a "fan", consisting of n - 1    */
8808 /*  triangles that share a common origin.  For each of these triangles, the  */
8809 /*  edge opposite the origin is one of the sides of the polygon.  The        */
8810 /*  primary edge of each triangle is the edge directed from the origin to    */
8811 /*  the destination; note that this is not the same edge that is a side of   */
8812 /*  the polygon.  `firstedge' is the primary edge of the first triangle.     */
8813 /*  From there, the triangles follow in counterclockwise order about the     */
8814 /*  polygon, until `lastedge', the primary edge of the last triangle.        */
8815 /*  `firstedge' and `lastedge' are probably connected to other triangles     */
8816 /*  beyond the extremes of the fan, but their identity is not important, as  */
8817 /*  long as the fan remains connected to them.                               */
8818 /*                                                                           */
8819 /*  Imagine the polygon oriented so that its base is at the bottom.  This    */
8820 /*  puts `firstedge' on the far right, and `lastedge' on the far left.       */
8821 /*  The right vertex of the base is the destination of `firstedge', and the  */
8822 /*  left vertex of the base is the apex of `lastedge'.                       */
8823 /*                                                                           */
8824 /*  The challenge now is to find the right sequence of edge flips to         */
8825 /*  transform the fan into a Delaunay triangulation of the polygon.  Each    */
8826 /*  edge flip effectively removes one triangle from the fan, committing it   */
8827 /*  to the polygon.  The resulting polygon has one fewer edge.  If `doflip'  */
8828 /*  is set, the final flip will be performed, resulting in a fan of one      */
8829 /*  (useless?) triangle.  If `doflip' is not set, the final flip is not      */
8830 /*  performed, resulting in a fan of two triangles, and an unfinished        */
8831 /*  triangular polygon that is not yet filled out with a single triangle.    */
8832 /*  On completion of the routine, `lastedge' is the last remaining triangle, */
8833 /*  or the leftmost of the last two.                                         */
8834 /*                                                                           */
8835 /*  Although the flips are performed in the order described above, the       */
8836 /*  decisions about what flips to perform are made in precisely the reverse  */
8837 /*  order.  The recursive triangulatepolygon() procedure makes a decision,   */
8838 /*  uses up to two recursive calls to triangulate the "subproblems"          */
8839 /*  (polygons with fewer edges), and then performs an edge flip.             */
8840 /*                                                                           */
8841 /*  The "decision" it makes is which vertex of the polygon should be         */
8842 /*  connected to the base.  This decision is made by testing every possible  */
8843 /*  vertex.  Once the best vertex is found, the two edges that connect this  */
8844 /*  vertex to the base become the bases for two smaller polygons.  These     */
8845 /*  are triangulated recursively.  Unfortunately, this approach can take     */
8846 /*  O(n^2) time not only in the worst case, but in many common cases.  It's  */
8847 /*  rarely a big deal for vertex deletion, where n is rarely larger than     */
8848 /*  ten, but it could be a big deal for segment insertion, especially if     */
8849 /*  there's a lot of long segments that each cut many triangles.  I ought to */
8850 /*  code a faster algorithm some day.                                        */
8851 /*                                                                           */
8852 /*  The `edgecount' parameter is the number of sides of the polygon,         */
8853 /*  including its base.  `triflaws' is a flag that determines whether the    */
8854 /*  new triangles should be tested for quality, and enqueued if they are     */
8855 /*  bad.                                                                     */
8856 /*                                                                           */
8857 /*****************************************************************************/
8858 
8859 #ifdef ANSI_DECLARATORS
8860 void triangulatepolygon(struct mesh *m, struct behavior *b,
8861                         struct otri *firstedge, struct otri *lastedge,
8862                         int edgecount, int doflip, int triflaws)
8863 #else /* not ANSI_DECLARATORS */
8864 void triangulatepolygon(m, b, firstedge, lastedge, edgecount, doflip, triflaws)
8865 struct mesh *m;
8866 struct behavior *b;
8867 struct otri *firstedge;
8868 struct otri *lastedge;
8869 int edgecount;
8870 int doflip;
8871 int triflaws;
8872 #endif /* not ANSI_DECLARATORS */
8873 
8874 {
8875   struct otri testtri;
8876   struct otri besttri;
8877   struct otri tempedge;
8878   vertex leftbasevertex, rightbasevertex;
8879   vertex testvertex;
8880   vertex bestvertex;
8881   int bestnumber;
8882   int i;
8883   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8884 
8885   /* Identify the base vertices. */
8886   apex(*lastedge, leftbasevertex);
8887   dest(*firstedge, rightbasevertex);
8888   if (b->verbose > 2) {
8889     printf("  Triangulating interior polygon at edge\n");
8890     printf("    (%.12g, %.12g) (%.12g, %.12g)\n", leftbasevertex[0],
8891            leftbasevertex[1], rightbasevertex[0], rightbasevertex[1]);
8892   }
8893   /* Find the best vertex to connect the base to. */
8894   onext(*firstedge, besttri);
8895   dest(besttri, bestvertex);
8896   otricopy(besttri, testtri);
8897   bestnumber = 1;
8898   for (i = 2; i <= edgecount - 2; i++) {
8899     onextself(testtri);
8900     dest(testtri, testvertex);
8901     /* Is this a better vertex? */
8902     if (incircle(m, b, leftbasevertex, rightbasevertex, bestvertex,
8903                  testvertex) > 0.0) {
8904       otricopy(testtri, besttri);
8905       bestvertex = testvertex;
8906       bestnumber = i;
8907     }
8908   }
8909   if (b->verbose > 2) {
8910     printf("    Connecting edge to (%.12g, %.12g)\n", bestvertex[0],
8911            bestvertex[1]);
8912   }
8913   if (bestnumber > 1) {
8914     /* Recursively triangulate the smaller polygon on the right. */
8915     oprev(besttri, tempedge);
8916     triangulatepolygon(m, b, firstedge, &tempedge, bestnumber + 1, 1,
8917                        triflaws);
8918   }
8919   if (bestnumber < edgecount - 2) {
8920     /* Recursively triangulate the smaller polygon on the left. */
8921     sym(besttri, tempedge);
8922     triangulatepolygon(m, b, &besttri, lastedge, edgecount - bestnumber, 1,
8923                        triflaws);
8924     /* Find `besttri' again; it may have been lost to edge flips. */
8925     sym(tempedge, besttri);
8926   }
8927   if (doflip) {
8928     /* Do one final edge flip. */
8929     flip(m, b, &besttri);
8930 #ifndef CDT_ONLY
8931     if (triflaws) {
8932       /* Check the quality of the newly committed triangle. */
8933       sym(besttri, testtri);
8934       testtriangle(m, b, &testtri);
8935     }
8936 #endif /* not CDT_ONLY */
8937   }
8938   /* Return the base triangle. */
8939   otricopy(besttri, *lastedge);
8940 }
8941 
8942 /*****************************************************************************/
8943 /*                                                                           */
8944 /*  deletevertex()   Delete a vertex from a Delaunay triangulation, ensuring */
8945 /*                   that the triangulation remains Delaunay.                */
8946 /*                                                                           */
8947 /*  The origin of `deltri' is deleted.  The union of the triangles adjacent  */
8948 /*  to this vertex is a polygon, for which the Delaunay triangulation is     */
8949 /*  found.  Two triangles are removed from the mesh.                         */
8950 /*                                                                           */
8951 /*  Only interior vertices that do not lie on segments or boundaries may be  */
8952 /*  deleted.                                                                 */
8953 /*                                                                           */
8954 /*****************************************************************************/
8955 
8956 #ifndef CDT_ONLY
8957 
8958 #ifdef ANSI_DECLARATORS
8959 void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri)
8960 #else /* not ANSI_DECLARATORS */
8961 void deletevertex(m, b, deltri)
8962 struct mesh *m;
8963 struct behavior *b;
8964 struct otri *deltri;
8965 #endif /* not ANSI_DECLARATORS */
8966 
8967 {
8968   struct otri countingtri;
8969   struct otri firstedge, lastedge;
8970   struct otri deltriright;
8971   struct otri lefttri, righttri;
8972   struct otri leftcasing, rightcasing;
8973   struct osub leftsubseg, rightsubseg;
8974   vertex delvertex;
8975   vertex neworg;
8976   int edgecount;
8977   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
8978   subseg sptr;                      /* Temporary variable used by tspivot(). */
8979 
8980   org(*deltri, delvertex);
8981   if (b->verbose > 1) {
8982     printf("  Deleting (%.12g, %.12g).\n", delvertex[0], delvertex[1]);
8983   }
8984   vertexdealloc(m, delvertex);
8985 
8986   /* Count the degree of the vertex being deleted. */
8987   onext(*deltri, countingtri);
8988   edgecount = 1;
8989   while (!otriequal(*deltri, countingtri)) {
8990 #ifdef SELF_CHECK
8991     if (countingtri.tri == m->dummytri) {
8992       printf("Internal error in deletevertex():\n");
8993       printf("  Attempt to delete boundary vertex.\n");
8994       internalerror();
8995     }
8996 #endif /* SELF_CHECK */
8997     edgecount++;
8998     onextself(countingtri);
8999   }
9000 
9001 #ifdef SELF_CHECK
9002   if (edgecount < 3) {
9003     printf("Internal error in deletevertex():\n  Vertex has degree %d.\n",
9004            edgecount);
9005     internalerror();
9006   }
9007 #endif /* SELF_CHECK */
9008   if (edgecount > 3) {
9009     /* Triangulate the polygon defined by the union of all triangles */
9010     /*   adjacent to the vertex being deleted.  Check the quality of */
9011     /*   the resulting triangles.                                    */
9012     onext(*deltri, firstedge);
9013     oprev(*deltri, lastedge);
9014     triangulatepolygon(m, b, &firstedge, &lastedge, edgecount, 0,
9015                        !b->nobisect);
9016   }
9017   /* Splice out two triangles. */
9018   lprev(*deltri, deltriright);
9019   dnext(*deltri, lefttri);
9020   sym(lefttri, leftcasing);
9021   oprev(deltriright, righttri);
9022   sym(righttri, rightcasing);
9023   bond(*deltri, leftcasing);
9024   bond(deltriright, rightcasing);
9025   tspivot(lefttri, leftsubseg);
9026   if (leftsubseg.ss != m->dummysub) {
9027     tsbond(*deltri, leftsubseg);
9028   }
9029   tspivot(righttri, rightsubseg);
9030   if (rightsubseg.ss != m->dummysub) {
9031     tsbond(deltriright, rightsubseg);
9032   }
9033 
9034   /* Set the new origin of `deltri' and check its quality. */
9035   org(lefttri, neworg);
9036   setorg(*deltri, neworg);
9037   if (!b->nobisect) {
9038     testtriangle(m, b, deltri);
9039   }
9040 
9041   /* Delete the two spliced-out triangles. */
9042   triangledealloc(m, lefttri.tri);
9043   triangledealloc(m, righttri.tri);
9044 }
9045 
9046 #endif /* not CDT_ONLY */
9047 
9048 /*****************************************************************************/
9049 /*                                                                           */
9050 /*  undovertex()   Undo the most recent vertex insertion.                    */
9051 /*                                                                           */
9052 /*  Walks through the list of transformations (flips and a vertex insertion) */
9053 /*  in the reverse of the order in which they were done, and undoes them.    */
9054 /*  The inserted vertex is removed from the triangulation and deallocated.   */
9055 /*  Two triangles (possibly just one) are also deallocated.                  */
9056 /*                                                                           */
9057 /*****************************************************************************/
9058 
9059 #ifndef CDT_ONLY
9060 
9061 #ifdef ANSI_DECLARATORS
9062 void undovertex(struct mesh *m, struct behavior *b)
9063 #else /* not ANSI_DECLARATORS */
9064 void undovertex(m, b)
9065 struct mesh *m;
9066 struct behavior *b;
9067 #endif /* not ANSI_DECLARATORS */
9068 
9069 {
9070   struct otri fliptri;
9071   struct otri botleft, botright, topright;
9072   struct otri botlcasing, botrcasing, toprcasing;
9073   struct otri gluetri;
9074   struct osub botlsubseg, botrsubseg, toprsubseg;
9075   vertex botvertex, rightvertex;
9076   triangle ptr;                         /* Temporary variable used by sym(). */
9077   subseg sptr;                      /* Temporary variable used by tspivot(). */
9078 
9079   /* Walk through the list of transformations (flips and a vertex insertion) */
9080   /*   in the reverse of the order in which they were done, and undo them.   */
9081   while (m->lastflip != (struct flipstacker *) NULL) {
9082     /* Find a triangle involved in the last unreversed transformation. */
9083     decode(m->lastflip->flippedtri, fliptri);
9084 
9085     /* We are reversing one of three transformations:  a trisection of one */
9086     /*   triangle into three (by inserting a vertex in the triangle), a    */
9087     /*   bisection of two triangles into four (by inserting a vertex in an */
9088     /*   edge), or an edge flip.                                           */
9089     if (m->lastflip->prevflip == (struct flipstacker *) NULL) {
9090       /* Restore a triangle that was split into three triangles, */
9091       /*   so it is again one triangle.                          */
9092       dprev(fliptri, botleft);
9093       lnextself(botleft);
9094       onext(fliptri, botright);
9095       lprevself(botright);
9096       sym(botleft, botlcasing);
9097       sym(botright, botrcasing);
9098       dest(botleft, botvertex);
9099 
9100       setapex(fliptri, botvertex);
9101       lnextself(fliptri);
9102       bond(fliptri, botlcasing);
9103       tspivot(botleft, botlsubseg);
9104       tsbond(fliptri, botlsubseg);
9105       lnextself(fliptri);
9106       bond(fliptri, botrcasing);
9107       tspivot(botright, botrsubseg);
9108       tsbond(fliptri, botrsubseg);
9109 
9110       /* Delete the two spliced-out triangles. */
9111       triangledealloc(m, botleft.tri);
9112       triangledealloc(m, botright.tri);
9113     } else if (m->lastflip->prevflip == (struct flipstacker *) &insertvertex) {
9114       /* Restore two triangles that were split into four triangles, */
9115       /*   so they are again two triangles.                         */
9116       lprev(fliptri, gluetri);
9117       sym(gluetri, botright);
9118       lnextself(botright);
9119       sym(botright, botrcasing);
9120       dest(botright, rightvertex);
9121 
9122       setorg(fliptri, rightvertex);
9123       bond(gluetri, botrcasing);
9124       tspivot(botright, botrsubseg);
9125       tsbond(gluetri, botrsubseg);
9126 
9127       /* Delete the spliced-out triangle. */
9128       triangledealloc(m, botright.tri);
9129 
9130       sym(fliptri, gluetri);
9131       if (gluetri.tri != m->dummytri) {
9132         lnextself(gluetri);
9133         dnext(gluetri, topright);
9134         sym(topright, toprcasing);
9135 
9136         setorg(gluetri, rightvertex);
9137         bond(gluetri, toprcasing);
9138         tspivot(topright, toprsubseg);
9139         tsbond(gluetri, toprsubseg);
9140 
9141         /* Delete the spliced-out triangle. */
9142         triangledealloc(m, topright.tri);
9143       }
9144 
9145       /* This is the end of the list, sneakily encoded. */
9146       m->lastflip->prevflip = (struct flipstacker *) NULL;
9147     } else {
9148       /* Undo an edge flip. */
9149       unflip(m, b, &fliptri);
9150     }
9151 
9152     /* Go on and process the next transformation. */
9153     m->lastflip = m->lastflip->prevflip;
9154   }
9155 }
9156 
9157 #endif /* not CDT_ONLY */
9158 
9159 /**                                                                         **/
9160 /**                                                                         **/
9161 /********* Mesh transformation routines end here                     *********/
9162 
9163 /********* Divide-and-conquer Delaunay triangulation begins here     *********/
9164 /**                                                                         **/
9165 /**                                                                         **/
9166 
9167 /*****************************************************************************/
9168 /*                                                                           */
9169 /*  The divide-and-conquer bounding box                                      */
9170 /*                                                                           */
9171 /*  I originally implemented the divide-and-conquer and incremental Delaunay */
9172 /*  triangulations using the edge-based data structure presented by Guibas   */
9173 /*  and Stolfi.  Switching to a triangle-based data structure doubled the    */
9174 /*  speed.  However, I had to think of a few extra tricks to maintain the    */
9175 /*  elegance of the original algorithms.                                     */
9176 /*                                                                           */
9177 /*  The "bounding box" used by my variant of the divide-and-conquer          */
9178 /*  algorithm uses one triangle for each edge of the convex hull of the      */
9179 /*  triangulation.  These bounding triangles all share a common apical       */
9180 /*  vertex, which is represented by NULL and which represents nothing.       */
9181 /*  The bounding triangles are linked in a circular fan about this NULL      */
9182 /*  vertex, and the edges on the convex hull of the triangulation appear     */
9183 /*  opposite the NULL vertex.  You might find it easiest to imagine that     */
9184 /*  the NULL vertex is a point in 3D space behind the center of the          */
9185 /*  triangulation, and that the bounding triangles form a sort of cone.      */
9186 /*                                                                           */
9187 /*  This bounding box makes it easy to represent degenerate cases.  For      */
9188 /*  instance, the triangulation of two vertices is a single edge.  This edge */
9189 /*  is represented by two bounding box triangles, one on each "side" of the  */
9190 /*  edge.  These triangles are also linked together in a fan about the NULL  */
9191 /*  vertex.                                                                  */
9192 /*                                                                           */
9193 /*  The bounding box also makes it easy to traverse the convex hull, as the  */
9194 /*  divide-and-conquer algorithm needs to do.                                */
9195 /*                                                                           */
9196 /*****************************************************************************/
9197 
9198 /*****************************************************************************/
9199 /*                                                                           */
9200 /*  vertexsort()   Sort an array of vertices by x-coordinate, using the      */
9201 /*                 y-coordinate as a secondary key.                          */
9202 /*                                                                           */
9203 /*  Uses quicksort.  Randomized O(n log n) time.  No, I did not make any of  */
9204 /*  the usual quicksort mistakes.                                            */
9205 /*                                                                           */
9206 /*****************************************************************************/
9207 
9208 #ifdef ANSI_DECLARATORS
9209 void vertexsort(vertex *sortarray, int arraysize)
9210 #else /* not ANSI_DECLARATORS */
9211 void vertexsort(sortarray, arraysize)
9212 vertex *sortarray;
9213 int arraysize;
9214 #endif /* not ANSI_DECLARATORS */
9215 
9216 {
9217   int left, right;
9218   int pivot;
9219   REAL pivotx, pivoty;
9220   vertex temp;
9221 
9222   if (arraysize == 2) {
9223     /* Recursive base case. */
9224     if ((sortarray[0][0] > sortarray[1][0]) ||
9225         ((sortarray[0][0] == sortarray[1][0]) &&
9226          (sortarray[0][1] > sortarray[1][1]))) {
9227       temp = sortarray[1];
9228       sortarray[1] = sortarray[0];
9229       sortarray[0] = temp;
9230     }
9231     return;
9232   }
9233   /* Choose a random pivot to split the array. */
9234   pivot = (int) randomnation((unsigned int) arraysize);
9235   pivotx = sortarray[pivot][0];
9236   pivoty = sortarray[pivot][1];
9237   /* Split the array. */
9238   left = -1;
9239   right = arraysize;
9240   while (left < right) {
9241     /* Search for a vertex whose x-coordinate is too large for the left. */
9242     do {
9243       left++;
9244     } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
9245                                  ((sortarray[left][0] == pivotx) &&
9246                                   (sortarray[left][1] < pivoty))));
9247     /* Search for a vertex whose x-coordinate is too small for the right. */
9248     do {
9249       right--;
9250     } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
9251                                  ((sortarray[right][0] == pivotx) &&
9252                                   (sortarray[right][1] > pivoty))));
9253     if (left < right) {
9254       /* Swap the left and right vertices. */
9255       temp = sortarray[left];
9256       sortarray[left] = sortarray[right];
9257       sortarray[right] = temp;
9258     }
9259   }
9260   if (left > 1) {
9261     /* Recursively sort the left subset. */
9262     vertexsort(sortarray, left);
9263   }
9264   if (right < arraysize - 2) {
9265     /* Recursively sort the right subset. */
9266     vertexsort(&sortarray[right + 1], arraysize - right - 1);
9267   }
9268 }
9269 
9270 /*****************************************************************************/
9271 /*                                                                           */
9272 /*  vertexmedian()   An order statistic algorithm, almost.  Shuffles an      */
9273 /*                   array of vertices so that the first `median' vertices   */
9274 /*                   occur lexicographically before the remaining vertices.  */
9275 /*                                                                           */
9276 /*  Uses the x-coordinate as the primary key if axis == 0; the y-coordinate  */
9277 /*  if axis == 1.  Very similar to the vertexsort() procedure, but runs in   */
9278 /*  randomized linear time.                                                  */
9279 /*                                                                           */
9280 /*****************************************************************************/
9281 
9282 #ifdef ANSI_DECLARATORS
9283 void vertexmedian(vertex *sortarray, int arraysize, int median, int axis)
9284 #else /* not ANSI_DECLARATORS */
9285 void vertexmedian(sortarray, arraysize, median, axis)
9286 vertex *sortarray;
9287 int arraysize;
9288 int median;
9289 int axis;
9290 #endif /* not ANSI_DECLARATORS */
9291 
9292 {
9293   int left, right;
9294   int pivot;
9295   REAL pivot1, pivot2;
9296   vertex temp;
9297 
9298   if (arraysize == 2) {
9299     /* Recursive base case. */
9300     if ((sortarray[0][axis] > sortarray[1][axis]) ||
9301         ((sortarray[0][axis] == sortarray[1][axis]) &&
9302          (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
9303       temp = sortarray[1];
9304       sortarray[1] = sortarray[0];
9305       sortarray[0] = temp;
9306     }
9307     return;
9308   }
9309   /* Choose a random pivot to split the array. */
9310   pivot = (int) randomnation((unsigned int) arraysize);
9311   pivot1 = sortarray[pivot][axis];
9312   pivot2 = sortarray[pivot][1 - axis];
9313   /* Split the array. */
9314   left = -1;
9315   right = arraysize;
9316   while (left < right) {
9317     /* Search for a vertex whose x-coordinate is too large for the left. */
9318     do {
9319       left++;
9320     } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
9321                                  ((sortarray[left][axis] == pivot1) &&
9322                                   (sortarray[left][1 - axis] < pivot2))));
9323     /* Search for a vertex whose x-coordinate is too small for the right. */
9324     do {
9325       right--;
9326     } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
9327                                  ((sortarray[right][axis] == pivot1) &&
9328                                   (sortarray[right][1 - axis] > pivot2))));
9329     if (left < right) {
9330       /* Swap the left and right vertices. */
9331       temp = sortarray[left];
9332       sortarray[left] = sortarray[right];
9333       sortarray[right] = temp;
9334     }
9335   }
9336   /* Unlike in vertexsort(), at most one of the following */
9337   /*   conditionals is true.                             */
9338   if (left > median) {
9339     /* Recursively shuffle the left subset. */
9340     vertexmedian(sortarray, left, median, axis);
9341   }
9342   if (right < median - 1) {
9343     /* Recursively shuffle the right subset. */
9344     vertexmedian(&sortarray[right + 1], arraysize - right - 1,
9345                  median - right - 1, axis);
9346   }
9347 }
9348 
9349 /*****************************************************************************/
9350 /*                                                                           */
9351 /*  alternateaxes()   Sorts the vertices as appropriate for the divide-and-  */
9352 /*                    conquer algorithm with alternating cuts.               */
9353 /*                                                                           */
9354 /*  Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1.   */
9355 /*  For the base case, subsets containing only two or three vertices are     */
9356 /*  always sorted by x-coordinate.                                           */
9357 /*                                                                           */
9358 /*****************************************************************************/
9359 
9360 #ifdef ANSI_DECLARATORS
9361 void alternateaxes(vertex *sortarray, int arraysize, int axis)
9362 #else /* not ANSI_DECLARATORS */
9363 void alternateaxes(sortarray, arraysize, axis)
9364 vertex *sortarray;
9365 int arraysize;
9366 int axis;
9367 #endif /* not ANSI_DECLARATORS */
9368 
9369 {
9370   int divider;
9371 
9372   divider = arraysize >> 1;
9373   if (arraysize <= 3) {
9374     /* Recursive base case:  subsets of two or three vertices will be    */
9375     /*   handled specially, and should always be sorted by x-coordinate. */
9376     axis = 0;
9377   }
9378   /* Partition with a horizontal or vertical cut. */
9379   vertexmedian(sortarray, arraysize, divider, axis);
9380   /* Recursively partition the subsets with a cross cut. */
9381   if (arraysize - divider >= 2) {
9382     if (divider >= 2) {
9383       alternateaxes(sortarray, divider, 1 - axis);
9384     }
9385     alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
9386   }
9387 }
9388 
9389 /*****************************************************************************/
9390 /*                                                                           */
9391 /*  mergehulls()   Merge two adjacent Delaunay triangulations into a         */
9392 /*                 single Delaunay triangulation.                            */
9393 /*                                                                           */
9394 /*  This is similar to the algorithm given by Guibas and Stolfi, but uses    */
9395 /*  a triangle-based, rather than edge-based, data structure.                */
9396 /*                                                                           */
9397 /*  The algorithm walks up the gap between the two triangulations, knitting  */
9398 /*  them together.  As they are merged, some of their bounding triangles     */
9399 /*  are converted into real triangles of the triangulation.  The procedure   */
9400 /*  pulls each hull's bounding triangles apart, then knits them together     */
9401 /*  like the teeth of two gears.  The Delaunay property determines, at each  */
9402 /*  step, whether the next "tooth" is a bounding triangle of the left hull   */
9403 /*  or the right.  When a bounding triangle becomes real, its apex is        */
9404 /*  changed from NULL to a real vertex.                                      */
9405 /*                                                                           */
9406 /*  Only two new triangles need to be allocated.  These become new bounding  */
9407 /*  triangles at the top and bottom of the seam.  They are used to connect   */
9408 /*  the remaining bounding triangles (those that have not been converted     */
9409 /*  into real triangles) into a single fan.                                  */
9410 /*                                                                           */
9411 /*  On entry, `farleft' and `innerleft' are bounding triangles of the left   */
9412 /*  triangulation.  The origin of `farleft' is the leftmost vertex, and      */
9413 /*  the destination of `innerleft' is the rightmost vertex of the            */
9414 /*  triangulation.  Similarly, `innerright' and `farright' are bounding      */
9415 /*  triangles of the right triangulation.  The origin of `innerright' and    */
9416 /*  destination of `farright' are the leftmost and rightmost vertices.       */
9417 /*                                                                           */
9418 /*  On completion, the origin of `farleft' is the leftmost vertex of the     */
9419 /*  merged triangulation, and the destination of `farright' is the rightmost */
9420 /*  vertex.                                                                  */
9421 /*                                                                           */
9422 /*****************************************************************************/
9423 
9424 #ifdef ANSI_DECLARATORS
9425 void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
9426                 struct otri *innerleft, struct otri *innerright,
9427                 struct otri *farright, int axis)
9428 #else /* not ANSI_DECLARATORS */
9429 void mergehulls(m, b, farleft, innerleft, innerright, farright, axis)
9430 struct mesh *m;
9431 struct behavior *b;
9432 struct otri *farleft;
9433 struct otri *innerleft;
9434 struct otri *innerright;
9435 struct otri *farright;
9436 int axis;
9437 #endif /* not ANSI_DECLARATORS */
9438 
9439 {
9440   struct otri leftcand, rightcand;
9441   struct otri baseedge;
9442   struct otri nextedge;
9443   struct otri sidecasing, topcasing, outercasing;
9444   struct otri checkedge;
9445   vertex innerleftdest;
9446   vertex innerrightorg;
9447   vertex innerleftapex, innerrightapex;
9448   vertex farleftpt, farrightpt;
9449   vertex farleftapex, farrightapex;
9450   vertex lowerleft, lowerright;
9451   vertex upperleft, upperright;
9452   vertex nextapex;
9453   vertex checkvertex;
9454   int changemade;
9455   int badedge;
9456   int leftfinished, rightfinished;
9457   triangle ptr;                         /* Temporary variable used by sym(). */
9458 
9459   dest(*innerleft, innerleftdest);
9460   apex(*innerleft, innerleftapex);
9461   org(*innerright, innerrightorg);
9462   apex(*innerright, innerrightapex);
9463   /* Special treatment for horizontal cuts. */
9464   if (b->dwyer && (axis == 1)) {
9465     org(*farleft, farleftpt);
9466     apex(*farleft, farleftapex);
9467     dest(*farright, farrightpt);
9468     apex(*farright, farrightapex);
9469     /* The pointers to the extremal vertices are shifted to point to the */
9470     /*   topmost and bottommost vertex of each hull, rather than the     */
9471     /*   leftmost and rightmost vertices.                                */
9472     while (farleftapex[1] < farleftpt[1]) {
9473       lnextself(*farleft);
9474       symself(*farleft);
9475       farleftpt = farleftapex;
9476       apex(*farleft, farleftapex);
9477     }
9478     sym(*innerleft, checkedge);
9479     apex(checkedge, checkvertex);
9480     while (checkvertex[1] > innerleftdest[1]) {
9481       lnext(checkedge, *innerleft);
9482       innerleftapex = innerleftdest;
9483       innerleftdest = checkvertex;
9484       sym(*innerleft, checkedge);
9485       apex(checkedge, checkvertex);
9486     }
9487     while (innerrightapex[1] < innerrightorg[1]) {
9488       lnextself(*innerright);
9489       symself(*innerright);
9490       innerrightorg = innerrightapex;
9491       apex(*innerright, innerrightapex);
9492     }
9493     sym(*farright, checkedge);
9494     apex(checkedge, checkvertex);
9495     while (checkvertex[1] > farrightpt[1]) {
9496       lnext(checkedge, *farright);
9497       farrightapex = farrightpt;
9498       farrightpt = checkvertex;
9499       sym(*farright, checkedge);
9500       apex(checkedge, checkvertex);
9501     }
9502   }
9503   /* Find a line tangent to and below both hulls. */
9504   do {
9505     changemade = 0;
9506     /* Make innerleftdest the "bottommost" vertex of the left hull. */
9507     if (counterclockwise(m, b, innerleftdest, innerleftapex, innerrightorg) >
9508         0.0) {
9509       lprevself(*innerleft);
9510       symself(*innerleft);
9511       innerleftdest = innerleftapex;
9512       apex(*innerleft, innerleftapex);
9513       changemade = 1;
9514     }
9515     /* Make innerrightorg the "bottommost" vertex of the right hull. */
9516     if (counterclockwise(m, b, innerrightapex, innerrightorg, innerleftdest) >
9517         0.0) {
9518       lnextself(*innerright);
9519       symself(*innerright);
9520       innerrightorg = innerrightapex;
9521       apex(*innerright, innerrightapex);
9522       changemade = 1;
9523     }
9524   } while (changemade);
9525   /* Find the two candidates to be the next "gear tooth." */
9526   sym(*innerleft, leftcand);
9527   sym(*innerright, rightcand);
9528   /* Create the bottom new bounding triangle. */
9529   maketriangle(m, b, &baseedge);
9530   /* Connect it to the bounding boxes of the left and right triangulations. */
9531   bond(baseedge, *innerleft);
9532   lnextself(baseedge);
9533   bond(baseedge, *innerright);
9534   lnextself(baseedge);
9535   setorg(baseedge, innerrightorg);
9536   setdest(baseedge, innerleftdest);
9537   /* Apex is intentionally left NULL. */
9538   if (b->verbose > 2) {
9539     printf("  Creating base bounding ");
9540     printtriangle(m, b, &baseedge);
9541   }
9542   /* Fix the extreme triangles if necessary. */
9543   org(*farleft, farleftpt);
9544   if (innerleftdest == farleftpt) {
9545     lnext(baseedge, *farleft);
9546   }
9547   dest(*farright, farrightpt);
9548   if (innerrightorg == farrightpt) {
9549     lprev(baseedge, *farright);
9550   }
9551   /* The vertices of the current knitting edge. */
9552   lowerleft = innerleftdest;
9553   lowerright = innerrightorg;
9554   /* The candidate vertices for knitting. */
9555   apex(leftcand, upperleft);
9556   apex(rightcand, upperright);
9557   /* Walk up the gap between the two triangulations, knitting them together. */
9558   while (1) {
9559     /* Have we reached the top?  (This isn't quite the right question,       */
9560     /*   because even though the left triangulation might seem finished now, */
9561     /*   moving up on the right triangulation might reveal a new vertex of   */
9562     /*   the left triangulation.  And vice-versa.)                           */
9563     leftfinished = counterclockwise(m, b, upperleft, lowerleft, lowerright) <=
9564                    0.0;
9565     rightfinished = counterclockwise(m, b, upperright, lowerleft, lowerright)
9566                  <= 0.0;
9567     if (leftfinished && rightfinished) {
9568       /* Create the top new bounding triangle. */
9569       maketriangle(m, b, &nextedge);
9570       setorg(nextedge, lowerleft);
9571       setdest(nextedge, lowerright);
9572       /* Apex is intentionally left NULL. */
9573       /* Connect it to the bounding boxes of the two triangulations. */
9574       bond(nextedge, baseedge);
9575       lnextself(nextedge);
9576       bond(nextedge, rightcand);
9577       lnextself(nextedge);
9578       bond(nextedge, leftcand);
9579       if (b->verbose > 2) {
9580         printf("  Creating top bounding ");
9581         printtriangle(m, b, &nextedge);
9582       }
9583       /* Special treatment for horizontal cuts. */
9584       if (b->dwyer && (axis == 1)) {
9585         org(*farleft, farleftpt);
9586         apex(*farleft, farleftapex);
9587         dest(*farright, farrightpt);
9588         apex(*farright, farrightapex);
9589         sym(*farleft, checkedge);
9590         apex(checkedge, checkvertex);
9591         /* The pointers to the extremal vertices are restored to the  */
9592         /*   leftmost and rightmost vertices (rather than topmost and */
9593         /*   bottommost).                                             */
9594         while (checkvertex[0] < farleftpt[0]) {
9595           lprev(checkedge, *farleft);
9596           farleftapex = farleftpt;
9597           farleftpt = checkvertex;
9598           sym(*farleft, checkedge);
9599           apex(checkedge, checkvertex);
9600         }
9601         while (farrightapex[0] > farrightpt[0]) {
9602           lprevself(*farright);
9603           symself(*farright);
9604           farrightpt = farrightapex;
9605           apex(*farright, farrightapex);
9606         }
9607       }
9608       return;
9609     }
9610     /* Consider eliminating edges from the left triangulation. */
9611     if (!leftfinished) {
9612       /* What vertex would be exposed if an edge were deleted? */
9613       lprev(leftcand, nextedge);
9614       symself(nextedge);
9615       apex(nextedge, nextapex);
9616       /* If nextapex is NULL, then no vertex would be exposed; the */
9617       /*   triangulation would have been eaten right through.      */
9618       if (nextapex != (vertex) NULL) {
9619         /* Check whether the edge is Delaunay. */
9620         badedge = incircle(m, b, lowerleft, lowerright, upperleft, nextapex) >
9621                   0.0;
9622         while (badedge) {
9623           /* Eliminate the edge with an edge flip.  As a result, the    */
9624           /*   left triangulation will have one more boundary triangle. */
9625           lnextself(nextedge);
9626           sym(nextedge, topcasing);
9627           lnextself(nextedge);
9628           sym(nextedge, sidecasing);
9629           bond(nextedge, topcasing);
9630           bond(leftcand, sidecasing);
9631           lnextself(leftcand);
9632           sym(leftcand, outercasing);
9633           lprevself(nextedge);
9634           bond(nextedge, outercasing);
9635           /* Correct the vertices to reflect the edge flip. */
9636           setorg(leftcand, lowerleft);
9637           setdest(leftcand, NULL);
9638           setapex(leftcand, nextapex);
9639           setorg(nextedge, NULL);
9640           setdest(nextedge, upperleft);
9641           setapex(nextedge, nextapex);
9642           /* Consider the newly exposed vertex. */
9643           upperleft = nextapex;
9644           /* What vertex would be exposed if another edge were deleted? */
9645           otricopy(sidecasing, nextedge);
9646           apex(nextedge, nextapex);
9647           if (nextapex != (vertex) NULL) {
9648             /* Check whether the edge is Delaunay. */
9649             badedge = incircle(m, b, lowerleft, lowerright, upperleft,
9650                                nextapex) > 0.0;
9651           } else {
9652             /* Avoid eating right through the triangulation. */
9653             badedge = 0;
9654           }
9655         }
9656       }
9657     }
9658     /* Consider eliminating edges from the right triangulation. */
9659     if (!rightfinished) {
9660       /* What vertex would be exposed if an edge were deleted? */
9661       lnext(rightcand, nextedge);
9662       symself(nextedge);
9663       apex(nextedge, nextapex);
9664       /* If nextapex is NULL, then no vertex would be exposed; the */
9665       /*   triangulation would have been eaten right through.      */
9666       if (nextapex != (vertex) NULL) {
9667         /* Check whether the edge is Delaunay. */
9668         badedge = incircle(m, b, lowerleft, lowerright, upperright, nextapex) >
9669                   0.0;
9670         while (badedge) {
9671           /* Eliminate the edge with an edge flip.  As a result, the     */
9672           /*   right triangulation will have one more boundary triangle. */
9673           lprevself(nextedge);
9674           sym(nextedge, topcasing);
9675           lprevself(nextedge);
9676           sym(nextedge, sidecasing);
9677           bond(nextedge, topcasing);
9678           bond(rightcand, sidecasing);
9679           lprevself(rightcand);
9680           sym(rightcand, outercasing);
9681           lnextself(nextedge);
9682           bond(nextedge, outercasing);
9683           /* Correct the vertices to reflect the edge flip. */
9684           setorg(rightcand, NULL);
9685           setdest(rightcand, lowerright);
9686           setapex(rightcand, nextapex);
9687           setorg(nextedge, upperright);
9688           setdest(nextedge, NULL);
9689           setapex(nextedge, nextapex);
9690           /* Consider the newly exposed vertex. */
9691           upperright = nextapex;
9692           /* What vertex would be exposed if another edge were deleted? */
9693           otricopy(sidecasing, nextedge);
9694           apex(nextedge, nextapex);
9695           if (nextapex != (vertex) NULL) {
9696             /* Check whether the edge is Delaunay. */
9697             badedge = incircle(m, b, lowerleft, lowerright, upperright,
9698                                nextapex) > 0.0;
9699           } else {
9700             /* Avoid eating right through the triangulation. */
9701             badedge = 0;
9702           }
9703         }
9704       }
9705     }
9706     if (leftfinished || (!rightfinished &&
9707            (incircle(m, b, upperleft, lowerleft, lowerright, upperright) >
9708             0.0))) {
9709       /* Knit the triangulations, adding an edge from `lowerleft' */
9710       /*   to `upperright'.                                       */
9711       bond(baseedge, rightcand);
9712       lprev(rightcand, baseedge);
9713       setdest(baseedge, lowerleft);
9714       lowerright = upperright;
9715       sym(baseedge, rightcand);
9716       apex(rightcand, upperright);
9717     } else {
9718       /* Knit the triangulations, adding an edge from `upperleft' */
9719       /*   to `lowerright'.                                       */
9720       bond(baseedge, leftcand);
9721       lnext(leftcand, baseedge);
9722       setorg(baseedge, lowerright);
9723       lowerleft = upperleft;
9724       sym(baseedge, leftcand);
9725       apex(leftcand, upperleft);
9726     }
9727     if (b->verbose > 2) {
9728       printf("  Connecting ");
9729       printtriangle(m, b, &baseedge);
9730     }
9731   }
9732 }
9733 
9734 /*****************************************************************************/
9735 /*                                                                           */
9736 /*  divconqrecurse()   Recursively form a Delaunay triangulation by the      */
9737 /*                     divide-and-conquer method.                            */
9738 /*                                                                           */
9739 /*  Recursively breaks down the problem into smaller pieces, which are       */
9740 /*  knitted together by mergehulls().  The base cases (problems of two or    */
9741 /*  three vertices) are handled specially here.                              */
9742 /*                                                                           */
9743 /*  On completion, `farleft' and `farright' are bounding triangles such that */
9744 /*  the origin of `farleft' is the leftmost vertex (breaking ties by         */
9745 /*  choosing the highest leftmost vertex), and the destination of            */
9746 /*  `farright' is the rightmost vertex (breaking ties by choosing the        */
9747 /*  lowest rightmost vertex).                                                */
9748 /*                                                                           */
9749 /*****************************************************************************/
9750 
9751 #ifdef ANSI_DECLARATORS
9752 void divconqrecurse(struct mesh *m, struct behavior *b, vertex *sortarray,
9753                     int vertices, int axis,
9754                     struct otri *farleft, struct otri *farright)
9755 #else /* not ANSI_DECLARATORS */
9756 void divconqrecurse(m, b, sortarray, vertices, axis, farleft, farright)
9757 struct mesh *m;
9758 struct behavior *b;
9759 vertex *sortarray;
9760 int vertices;
9761 int axis;
9762 struct otri *farleft;
9763 struct otri *farright;
9764 #endif /* not ANSI_DECLARATORS */
9765 
9766 {
9767   struct otri midtri, tri1, tri2, tri3;
9768   struct otri innerleft, innerright;
9769   REAL area;
9770   int divider;
9771 
9772   if (b->verbose > 2) {
9773     printf("  Triangulating %d vertices.\n", vertices);
9774   }
9775   if (vertices == 2) {
9776     /* The triangulation of two vertices is an edge.  An edge is */
9777     /*   represented by two bounding triangles.                  */
9778     maketriangle(m, b, farleft);
9779     setorg(*farleft, sortarray[0]);
9780     setdest(*farleft, sortarray[1]);
9781     /* The apex is intentionally left NULL. */
9782     maketriangle(m, b, farright);
9783     setorg(*farright, sortarray[1]);
9784     setdest(*farright, sortarray[0]);
9785     /* The apex is intentionally left NULL. */
9786     bond(*farleft, *farright);
9787     lprevself(*farleft);
9788     lnextself(*farright);
9789     bond(*farleft, *farright);
9790     lprevself(*farleft);
9791     lnextself(*farright);
9792     bond(*farleft, *farright);
9793     if (b->verbose > 2) {
9794       printf("  Creating ");
9795       printtriangle(m, b, farleft);
9796       printf("  Creating ");
9797       printtriangle(m, b, farright);
9798     }
9799     /* Ensure that the origin of `farleft' is sortarray[0]. */
9800     lprev(*farright, *farleft);
9801     return;
9802   } else if (vertices == 3) {
9803     /* The triangulation of three vertices is either a triangle (with */
9804     /*   three bounding triangles) or two edges (with four bounding   */
9805     /*   triangles).  In either case, four triangles are created.     */
9806     maketriangle(m, b, &midtri);
9807     maketriangle(m, b, &tri1);
9808     maketriangle(m, b, &tri2);
9809     maketriangle(m, b, &tri3);
9810     area = counterclockwise(m, b, sortarray[0], sortarray[1], sortarray[2]);
9811     if (area == 0.0) {
9812       /* Three collinear vertices; the triangulation is two edges. */
9813       setorg(midtri, sortarray[0]);
9814       setdest(midtri, sortarray[1]);
9815       setorg(tri1, sortarray[1]);
9816       setdest(tri1, sortarray[0]);
9817       setorg(tri2, sortarray[2]);
9818       setdest(tri2, sortarray[1]);
9819       setorg(tri3, sortarray[1]);
9820       setdest(tri3, sortarray[2]);
9821       /* All apices are intentionally left NULL. */
9822       bond(midtri, tri1);
9823       bond(tri2, tri3);
9824       lnextself(midtri);
9825       lprevself(tri1);
9826       lnextself(tri2);
9827       lprevself(tri3);
9828       bond(midtri, tri3);
9829       bond(tri1, tri2);
9830       lnextself(midtri);
9831       lprevself(tri1);
9832       lnextself(tri2);
9833       lprevself(tri3);
9834       bond(midtri, tri1);
9835       bond(tri2, tri3);
9836       /* Ensure that the origin of `farleft' is sortarray[0]. */
9837       otricopy(tri1, *farleft);
9838       /* Ensure that the destination of `farright' is sortarray[2]. */
9839       otricopy(tri2, *farright);
9840     } else {
9841       /* The three vertices are not collinear; the triangulation is one */
9842       /*   triangle, namely `midtri'.                                   */
9843       setorg(midtri, sortarray[0]);
9844       setdest(tri1, sortarray[0]);
9845       setorg(tri3, sortarray[0]);
9846       /* Apices of tri1, tri2, and tri3 are left NULL. */
9847       if (area > 0.0) {
9848         /* The vertices are in counterclockwise order. */
9849         setdest(midtri, sortarray[1]);
9850         setorg(tri1, sortarray[1]);
9851         setdest(tri2, sortarray[1]);
9852         setapex(midtri, sortarray[2]);
9853         setorg(tri2, sortarray[2]);
9854         setdest(tri3, sortarray[2]);
9855       } else {
9856         /* The vertices are in clockwise order. */
9857         setdest(midtri, sortarray[2]);
9858         setorg(tri1, sortarray[2]);
9859         setdest(tri2, sortarray[2]);
9860         setapex(midtri, sortarray[1]);
9861         setorg(tri2, sortarray[1]);
9862         setdest(tri3, sortarray[1]);
9863       }
9864       /* The topology does not depend on how the vertices are ordered. */
9865       bond(midtri, tri1);
9866       lnextself(midtri);
9867       bond(midtri, tri2);
9868       lnextself(midtri);
9869       bond(midtri, tri3);
9870       lprevself(tri1);
9871       lnextself(tri2);
9872       bond(tri1, tri2);
9873       lprevself(tri1);
9874       lprevself(tri3);
9875       bond(tri1, tri3);
9876       lnextself(tri2);
9877       lprevself(tri3);
9878       bond(tri2, tri3);
9879       /* Ensure that the origin of `farleft' is sortarray[0]. */
9880       otricopy(tri1, *farleft);
9881       /* Ensure that the destination of `farright' is sortarray[2]. */
9882       if (area > 0.0) {
9883         otricopy(tri2, *farright);
9884       } else {
9885         lnext(*farleft, *farright);
9886       }
9887     }
9888     if (b->verbose > 2) {
9889       printf("  Creating ");
9890       printtriangle(m, b, &midtri);
9891       printf("  Creating ");
9892       printtriangle(m, b, &tri1);
9893       printf("  Creating ");
9894       printtriangle(m, b, &tri2);
9895       printf("  Creating ");
9896       printtriangle(m, b, &tri3);
9897     }
9898     return;
9899   } else {
9900     /* Split the vertices in half. */
9901     divider = vertices >> 1;
9902     /* Recursively triangulate each half. */
9903     divconqrecurse(m, b, sortarray, divider, 1 - axis, farleft, &innerleft);
9904     divconqrecurse(m, b, &sortarray[divider], vertices - divider, 1 - axis,
9905                    &innerright, farright);
9906     if (b->verbose > 1) {
9907       printf("  Joining triangulations with %d and %d vertices.\n", divider,
9908              vertices - divider);
9909     }
9910     /* Merge the two triangulations into one. */
9911     mergehulls(m, b, farleft, &innerleft, &innerright, farright, axis);
9912   }
9913 }
9914 
9915 #ifdef ANSI_DECLARATORS
9916 long removeghosts(struct mesh *m, struct behavior *b, struct otri *startghost)
9917 #else /* not ANSI_DECLARATORS */
9918 long removeghosts(m, b, startghost)
9919 struct mesh *m;
9920 struct behavior *b;
9921 struct otri *startghost;
9922 #endif /* not ANSI_DECLARATORS */
9923 
9924 {
9925   struct otri searchedge;
9926   struct otri dissolveedge;
9927   struct otri deadtriangle;
9928   vertex markorg;
9929   long hullsize;
9930   triangle ptr;                         /* Temporary variable used by sym(). */
9931 
9932   if (b->verbose) {
9933     printf("  Removing ghost triangles.\n");
9934   }
9935   /* Find an edge on the convex hull to start point location from. */
9936   lprev(*startghost, searchedge);
9937   symself(searchedge);
9938   m->dummytri[0] = encode(searchedge);
9939   /* Remove the bounding box and count the convex hull edges. */
9940   otricopy(*startghost, dissolveedge);
9941   hullsize = 0;
9942   do {
9943     hullsize++;
9944     lnext(dissolveedge, deadtriangle);
9945     lprevself(dissolveedge);
9946     symself(dissolveedge);
9947     /* If no PSLG is involved, set the boundary markers of all the vertices */
9948     /*   on the convex hull.  If a PSLG is used, this step is done later.   */
9949     if (!b->poly) {
9950       /* Watch out for the case where all the input vertices are collinear. */
9951       if (dissolveedge.tri != m->dummytri) {
9952         org(dissolveedge, markorg);
9953         if (vertexmark(markorg) == 0) {
9954           setvertexmark(markorg, 1);
9955         }
9956       }
9957     }
9958     /* Remove a bounding triangle from a convex hull triangle. */
9959     dissolve(dissolveedge);
9960     /* Find the next bounding triangle. */
9961     sym(deadtriangle, dissolveedge);
9962     /* Delete the bounding triangle. */
9963     triangledealloc(m, deadtriangle.tri);
9964   } while (!otriequal(dissolveedge, *startghost));
9965   return hullsize;
9966 }
9967 
9968 /*****************************************************************************/
9969 /*                                                                           */
9970 /*  divconqdelaunay()   Form a Delaunay triangulation by the divide-and-     */
9971 /*                      conquer method.                                      */
9972 /*                                                                           */
9973 /*  Sorts the vertices, calls a recursive procedure to triangulate them, and */
9974 /*  removes the bounding box, setting boundary markers as appropriate.       */
9975 /*                                                                           */
9976 /*****************************************************************************/
9977 
9978 #ifdef ANSI_DECLARATORS
9979 long divconqdelaunay(struct mesh *m, struct behavior *b)
9980 #else /* not ANSI_DECLARATORS */
9981 long divconqdelaunay(m, b)
9982 struct mesh *m;
9983 struct behavior *b;
9984 #endif /* not ANSI_DECLARATORS */
9985 
9986 {
9987   vertex *sortarray;
9988   struct otri hullleft, hullright;
9989   int divider;
9990   int i, j;
9991 
9992   if (b->verbose) {
9993     printf("  Sorting vertices.\n");
9994   }
9995 
9996   /* Allocate an array of pointers to vertices for sorting. */
9997   sortarray = (vertex *) trimalloc(m->invertices * (int) sizeof(vertex));
9998   traversalinit(&m->vertices);
9999   for (i = 0; i < m->invertices; i++) {
10000     sortarray[i] = vertextraverse(m);
10001   }
10002   /* Sort the vertices. */
10003   vertexsort(sortarray, m->invertices);
10004   /* Discard duplicate vertices, which can really mess up the algorithm. */
10005   i = 0;
10006   for (j = 1; j < m->invertices; j++) {
10007     if ((sortarray[i][0] == sortarray[j][0])
10008         && (sortarray[i][1] == sortarray[j][1])) {
10009       if (!b->quiet) {
10010         printf(
10011 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10012                sortarray[j][0], sortarray[j][1]);
10013       }
10014       setvertextype(sortarray[j], UNDEADVERTEX);
10015       m->undeads++;
10016     } else {
10017       i++;
10018       sortarray[i] = sortarray[j];
10019     }
10020   }
10021   i++;
10022   if (b->dwyer) {
10023     /* Re-sort the array of vertices to accommodate alternating cuts. */
10024     divider = i >> 1;
10025     if (i - divider >= 2) {
10026       if (divider >= 2) {
10027         alternateaxes(sortarray, divider, 1);
10028       }
10029       alternateaxes(&sortarray[divider], i - divider, 1);
10030     }
10031   }
10032 
10033   if (b->verbose) {
10034     printf("  Forming triangulation.\n");
10035   }
10036 
10037   /* Form the Delaunay triangulation. */
10038   divconqrecurse(m, b, sortarray, i, 0, &hullleft, &hullright);
10039   trifree((VOID *) sortarray);
10040 
10041   return removeghosts(m, b, &hullleft);
10042 }
10043 
10044 /**                                                                         **/
10045 /**                                                                         **/
10046 /********* Divide-and-conquer Delaunay triangulation ends here       *********/
10047 
10048 /********* Incremental Delaunay triangulation begins here            *********/
10049 /**                                                                         **/
10050 /**                                                                         **/
10051 
10052 /*****************************************************************************/
10053 /*                                                                           */
10054 /*  boundingbox()   Form an "infinite" bounding triangle to insert vertices  */
10055 /*                  into.                                                    */
10056 /*                                                                           */
10057 /*  The vertices at "infinity" are assigned finite coordinates, which are    */
10058 /*  used by the point location routines, but (mostly) ignored by the         */
10059 /*  Delaunay edge flip routines.                                             */
10060 /*                                                                           */
10061 /*****************************************************************************/
10062 
10063 #ifndef REDUCED
10064 
10065 #ifdef ANSI_DECLARATORS
10066 void boundingbox(struct mesh *m, struct behavior *b)
10067 #else /* not ANSI_DECLARATORS */
10068 void boundingbox(m, b)
10069 struct mesh *m;
10070 struct behavior *b;
10071 #endif /* not ANSI_DECLARATORS */
10072 
10073 {
10074   struct otri inftri;          /* Handle for the triangular bounding box. */
10075   REAL width;
10076 
10077   if (b->verbose) {
10078     printf("  Creating triangular bounding box.\n");
10079   }
10080   /* Find the width (or height, whichever is larger) of the triangulation. */
10081   width = m->xmax - m->xmin;
10082   if (m->ymax - m->ymin > width) {
10083     width = m->ymax - m->ymin;
10084   }
10085   if (width == 0.0) {
10086     width = 1.0;
10087   }
10088   /* Create the vertices of the bounding box. */
10089   m->infvertex1 = (vertex) trimalloc(m->vertices.itembytes);
10090   m->infvertex2 = (vertex) trimalloc(m->vertices.itembytes);
10091   m->infvertex3 = (vertex) trimalloc(m->vertices.itembytes);
10092   m->infvertex1[0] = m->xmin - 50.0 * width;
10093   m->infvertex1[1] = m->ymin - 40.0 * width;
10094   m->infvertex2[0] = m->xmax + 50.0 * width;
10095   m->infvertex2[1] = m->ymin - 40.0 * width;
10096   m->infvertex3[0] = 0.5 * (m->xmin + m->xmax);
10097   m->infvertex3[1] = m->ymax + 60.0 * width;
10098 
10099   /* Create the bounding box. */
10100   maketriangle(m, b, &inftri);
10101   setorg(inftri, m->infvertex1);
10102   setdest(inftri, m->infvertex2);
10103   setapex(inftri, m->infvertex3);
10104   /* Link dummytri to the bounding box so we can always find an */
10105   /*   edge to begin searching (point location) from.           */
10106   m->dummytri[0] = (triangle) inftri.tri;
10107   if (b->verbose > 2) {
10108     printf("  Creating ");
10109     printtriangle(m, b, &inftri);
10110   }
10111 }
10112 
10113 #endif /* not REDUCED */
10114 
10115 /*****************************************************************************/
10116 /*                                                                           */
10117 /*  removebox()   Remove the "infinite" bounding triangle, setting boundary  */
10118 /*                markers as appropriate.                                    */
10119 /*                                                                           */
10120 /*  The triangular bounding box has three boundary triangles (one for each   */
10121 /*  side of the bounding box), and a bunch of triangles fanning out from     */
10122 /*  the three bounding box vertices (one triangle for each edge of the       */
10123 /*  convex hull of the inner mesh).  This routine removes these triangles.   */
10124 /*                                                                           */
10125 /*  Returns the number of edges on the convex hull of the triangulation.     */
10126 /*                                                                           */
10127 /*****************************************************************************/
10128 
10129 #ifndef REDUCED
10130 
10131 #ifdef ANSI_DECLARATORS
10132 long removebox(struct mesh *m, struct behavior *b)
10133 #else /* not ANSI_DECLARATORS */
10134 long removebox(m, b)
10135 struct mesh *m;
10136 struct behavior *b;
10137 #endif /* not ANSI_DECLARATORS */
10138 
10139 {
10140   struct otri deadtriangle;
10141   struct otri searchedge;
10142   struct otri checkedge;
10143   struct otri nextedge, finaledge, dissolveedge;
10144   vertex markorg;
10145   long hullsize;
10146   triangle ptr;                         /* Temporary variable used by sym(). */
10147 
10148   if (b->verbose) {
10149     printf("  Removing triangular bounding box.\n");
10150   }
10151   /* Find a boundary triangle. */
10152   nextedge.tri = m->dummytri;
10153   nextedge.orient = 0;
10154   symself(nextedge);
10155   /* Mark a place to stop. */
10156   lprev(nextedge, finaledge);
10157   lnextself(nextedge);
10158   symself(nextedge);
10159   /* Find a triangle (on the boundary of the vertex set) that isn't */
10160   /*   a bounding box triangle.                                     */
10161   lprev(nextedge, searchedge);
10162   symself(searchedge);
10163   /* Check whether nextedge is another boundary triangle */
10164   /*   adjacent to the first one.                        */
10165   lnext(nextedge, checkedge);
10166   symself(checkedge);
10167   if (checkedge.tri == m->dummytri) {
10168     /* Go on to the next triangle.  There are only three boundary   */
10169     /*   triangles, and this next triangle cannot be the third one, */
10170     /*   so it's safe to stop here.                                 */
10171     lprevself(searchedge);
10172     symself(searchedge);
10173   }
10174   /* Find a new boundary edge to search from, as the current search */
10175   /*   edge lies on a bounding box triangle and will be deleted.    */
10176   m->dummytri[0] = encode(searchedge);
10177   hullsize = -2l;
10178   while (!otriequal(nextedge, finaledge)) {
10179     hullsize++;
10180     lprev(nextedge, dissolveedge);
10181     symself(dissolveedge);
10182     /* If not using a PSLG, the vertices should be marked now. */
10183     /*   (If using a PSLG, markhull() will do the job.)        */
10184     if (!b->poly) {
10185       /* Be careful!  One must check for the case where all the input     */
10186       /*   vertices are collinear, and thus all the triangles are part of */
10187       /*   the bounding box.  Otherwise, the setvertexmark() call below   */
10188       /*   will cause a bad pointer reference.                            */
10189       if (dissolveedge.tri != m->dummytri) {
10190         org(dissolveedge, markorg);
10191         if (vertexmark(markorg) == 0) {
10192           setvertexmark(markorg, 1);
10193         }
10194       }
10195     }
10196     /* Disconnect the bounding box triangle from the mesh triangle. */
10197     dissolve(dissolveedge);
10198     lnext(nextedge, deadtriangle);
10199     sym(deadtriangle, nextedge);
10200     /* Get rid of the bounding box triangle. */
10201     triangledealloc(m, deadtriangle.tri);
10202     /* Do we need to turn the corner? */
10203     if (nextedge.tri == m->dummytri) {
10204       /* Turn the corner. */
10205       otricopy(dissolveedge, nextedge);
10206     }
10207   }
10208   triangledealloc(m, finaledge.tri);
10209 
10210   trifree((VOID *) m->infvertex1);  /* Deallocate the bounding box vertices. */
10211   trifree((VOID *) m->infvertex2);
10212   trifree((VOID *) m->infvertex3);
10213 
10214   return hullsize;
10215 }
10216 
10217 #endif /* not REDUCED */
10218 
10219 /*****************************************************************************/
10220 /*                                                                           */
10221 /*  incrementaldelaunay()   Form a Delaunay triangulation by incrementally   */
10222 /*                          inserting vertices.                              */
10223 /*                                                                           */
10224 /*  Returns the number of edges on the convex hull of the triangulation.     */
10225 /*                                                                           */
10226 /*****************************************************************************/
10227 
10228 #ifndef REDUCED
10229 
10230 #ifdef ANSI_DECLARATORS
10231 long incrementaldelaunay(struct mesh *m, struct behavior *b)
10232 #else /* not ANSI_DECLARATORS */
10233 long incrementaldelaunay(m, b)
10234 struct mesh *m;
10235 struct behavior *b;
10236 #endif /* not ANSI_DECLARATORS */
10237 
10238 {
10239   struct otri starttri;
10240   vertex vertexloop;
10241 
10242   /* Create a triangular bounding box. */
10243   boundingbox(m, b);
10244   if (b->verbose) {
10245     printf("  Incrementally inserting vertices.\n");
10246   }
10247   traversalinit(&m->vertices);
10248   vertexloop = vertextraverse(m);
10249   while (vertexloop != (vertex) NULL) {
10250     starttri.tri = m->dummytri;
10251     if (insertvertex(m, b, vertexloop, &starttri, (struct osub *) NULL, 0, 0)
10252         == DUPLICATEVERTEX) {
10253       if (!b->quiet) {
10254         printf(
10255 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10256                vertexloop[0], vertexloop[1]);
10257       }
10258       setvertextype(vertexloop, UNDEADVERTEX);
10259       m->undeads++;
10260     }
10261     vertexloop = vertextraverse(m);
10262   }
10263   /* Remove the bounding box. */
10264   return removebox(m, b);
10265 }
10266 
10267 #endif /* not REDUCED */
10268 
10269 /**                                                                         **/
10270 /**                                                                         **/
10271 /********* Incremental Delaunay triangulation ends here              *********/
10272 
10273 /********* Sweepline Delaunay triangulation begins here              *********/
10274 /**                                                                         **/
10275 /**                                                                         **/
10276 
10277 #ifndef REDUCED
10278 
10279 #ifdef ANSI_DECLARATORS
10280 void eventheapinsert(struct event **heap, int heapsize, struct event *newevent)
10281 #else /* not ANSI_DECLARATORS */
10282 void eventheapinsert(heap, heapsize, newevent)
10283 struct event **heap;
10284 int heapsize;
10285 struct event *newevent;
10286 #endif /* not ANSI_DECLARATORS */
10287 
10288 {
10289   REAL eventx, eventy;
10290   int eventnum;
10291   int parent;
10292   int notdone;
10293 
10294   eventx = newevent->xkey;
10295   eventy = newevent->ykey;
10296   eventnum = heapsize;
10297   notdone = eventnum > 0;
10298   while (notdone) {
10299     parent = (eventnum - 1) >> 1;
10300     if ((heap[parent]->ykey < eventy) ||
10301         ((heap[parent]->ykey == eventy)
10302          && (heap[parent]->xkey <= eventx))) {
10303       notdone = 0;
10304     } else {
10305       heap[eventnum] = heap[parent];
10306       heap[eventnum]->heapposition = eventnum;
10307 
10308       eventnum = parent;
10309       notdone = eventnum > 0;
10310     }
10311   }
10312   heap[eventnum] = newevent;
10313   newevent->heapposition = eventnum;
10314 }
10315 
10316 #endif /* not REDUCED */
10317 
10318 #ifndef REDUCED
10319 
10320 #ifdef ANSI_DECLARATORS
10321 void eventheapify(struct event **heap, int heapsize, int eventnum)
10322 #else /* not ANSI_DECLARATORS */
10323 void eventheapify(heap, heapsize, eventnum)
10324 struct event **heap;
10325 int heapsize;
10326 int eventnum;
10327 #endif /* not ANSI_DECLARATORS */
10328 
10329 {
10330   struct event *thisevent;
10331   REAL eventx, eventy;
10332   int leftchild, rightchild;
10333   int smallest;
10334   int notdone;
10335 
10336   thisevent = heap[eventnum];
10337   eventx = thisevent->xkey;
10338   eventy = thisevent->ykey;
10339   leftchild = 2 * eventnum + 1;
10340   notdone = leftchild < heapsize;
10341   while (notdone) {
10342     if ((heap[leftchild]->ykey < eventy) ||
10343         ((heap[leftchild]->ykey == eventy)
10344          && (heap[leftchild]->xkey < eventx))) {
10345       smallest = leftchild;
10346     } else {
10347       smallest = eventnum;
10348     }
10349     rightchild = leftchild + 1;
10350     if (rightchild < heapsize) {
10351       if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
10352           ((heap[rightchild]->ykey == heap[smallest]->ykey)
10353            && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
10354         smallest = rightchild;
10355       }
10356     }
10357     if (smallest == eventnum) {
10358       notdone = 0;
10359     } else {
10360       heap[eventnum] = heap[smallest];
10361       heap[eventnum]->heapposition = eventnum;
10362       heap[smallest] = thisevent;
10363       thisevent->heapposition = smallest;
10364 
10365       eventnum = smallest;
10366       leftchild = 2 * eventnum + 1;
10367       notdone = leftchild < heapsize;
10368     }
10369   }
10370 }
10371 
10372 #endif /* not REDUCED */
10373 
10374 #ifndef REDUCED
10375 
10376 #ifdef ANSI_DECLARATORS
10377 void eventheapdelete(struct event **heap, int heapsize, int eventnum)
10378 #else /* not ANSI_DECLARATORS */
10379 void eventheapdelete(heap, heapsize, eventnum)
10380 struct event **heap;
10381 int heapsize;
10382 int eventnum;
10383 #endif /* not ANSI_DECLARATORS */
10384 
10385 {
10386   struct event *moveevent;
10387   REAL eventx, eventy;
10388   int parent;
10389   int notdone;
10390 
10391   moveevent = heap[heapsize - 1];
10392   if (eventnum > 0) {
10393     eventx = moveevent->xkey;
10394     eventy = moveevent->ykey;
10395     do {
10396       parent = (eventnum - 1) >> 1;
10397       if ((heap[parent]->ykey < eventy) ||
10398           ((heap[parent]->ykey == eventy)
10399            && (heap[parent]->xkey <= eventx))) {
10400         notdone = 0;
10401       } else {
10402         heap[eventnum] = heap[parent];
10403         heap[eventnum]->heapposition = eventnum;
10404 
10405         eventnum = parent;
10406         notdone = eventnum > 0;
10407       }
10408     } while (notdone);
10409   }
10410   heap[eventnum] = moveevent;
10411   moveevent->heapposition = eventnum;
10412   eventheapify(heap, heapsize - 1, eventnum);
10413 }
10414 
10415 #endif /* not REDUCED */
10416 
10417 #ifndef REDUCED
10418 
10419 #ifdef ANSI_DECLARATORS
10420 void createeventheap(struct mesh *m, struct event ***eventheap,
10421                      struct event **events, struct event **freeevents)
10422 #else /* not ANSI_DECLARATORS */
10423 void createeventheap(m, eventheap, events, freeevents)
10424 struct mesh *m;
10425 struct event ***eventheap;
10426 struct event **events;
10427 struct event **freeevents;
10428 #endif /* not ANSI_DECLARATORS */
10429 
10430 {
10431   vertex thisvertex;
10432   int maxevents;
10433   int i;
10434 
10435   maxevents = (3 * m->invertices) / 2;
10436   *eventheap = (struct event **) trimalloc(maxevents *
10437                                            (int) sizeof(struct event *));
10438   *events = (struct event *) trimalloc(maxevents * (int) sizeof(struct event));
10439   traversalinit(&m->vertices);
10440   for (i = 0; i < m->invertices; i++) {
10441     thisvertex = vertextraverse(m);
10442     (*events)[i].eventptr = (VOID *) thisvertex;
10443     (*events)[i].xkey = thisvertex[0];
10444     (*events)[i].ykey = thisvertex[1];
10445     eventheapinsert(*eventheap, i, *events + i);
10446   }
10447   *freeevents = (struct event *) NULL;
10448   for (i = maxevents - 1; i >= m->invertices; i--) {
10449     (*events)[i].eventptr = (VOID *) *freeevents;
10450     *freeevents = *events + i;
10451   }
10452 }
10453 
10454 #endif /* not REDUCED */
10455 
10456 #ifndef REDUCED
10457 
10458 #ifdef ANSI_DECLARATORS
10459 int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite)
10460 #else /* not ANSI_DECLARATORS */
10461 int rightofhyperbola(m, fronttri, newsite)
10462 struct mesh *m;
10463 struct otri *fronttri;
10464 vertex newsite;
10465 #endif /* not ANSI_DECLARATORS */
10466 
10467 {
10468   vertex leftvertex, rightvertex;
10469   REAL dxa, dya, dxb, dyb;
10470 
10471   m->hyperbolacount++;
10472 
10473   dest(*fronttri, leftvertex);
10474   apex(*fronttri, rightvertex);
10475   if ((leftvertex[1] < rightvertex[1]) ||
10476       ((leftvertex[1] == rightvertex[1]) &&
10477        (leftvertex[0] < rightvertex[0]))) {
10478     if (newsite[0] >= rightvertex[0]) {
10479       return 1;
10480     }
10481   } else {
10482     if (newsite[0] <= leftvertex[0]) {
10483       return 0;
10484     }
10485   }
10486   dxa = leftvertex[0] - newsite[0];
10487   dya = leftvertex[1] - newsite[1];
10488   dxb = rightvertex[0] - newsite[0];
10489   dyb = rightvertex[1] - newsite[1];
10490   return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
10491 }
10492 
10493 #endif /* not REDUCED */
10494 
10495 #ifndef REDUCED
10496 
10497 #ifdef ANSI_DECLARATORS
10498 REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc)
10499 #else /* not ANSI_DECLARATORS */
10500 REAL circletop(m, pa, pb, pc, ccwabc)
10501 struct mesh *m;
10502 vertex pa;
10503 vertex pb;
10504 vertex pc;
10505 REAL ccwabc;
10506 #endif /* not ANSI_DECLARATORS */
10507 
10508 {
10509   REAL xac, yac, xbc, ybc, xab, yab;
10510   REAL aclen2, bclen2, ablen2;
10511 
10512   m->circletopcount++;
10513 
10514   xac = pa[0] - pc[0];
10515   yac = pa[1] - pc[1];
10516   xbc = pb[0] - pc[0];
10517   ybc = pb[1] - pc[1];
10518   xab = pa[0] - pb[0];
10519   yab = pa[1] - pb[1];
10520   aclen2 = xac * xac + yac * yac;
10521   bclen2 = xbc * xbc + ybc * ybc;
10522   ablen2 = xab * xab + yab * yab;
10523   return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
10524                / (2.0 * ccwabc);
10525 }
10526 
10527 #endif /* not REDUCED */
10528 
10529 #ifndef REDUCED
10530 
10531 #ifdef ANSI_DECLARATORS
10532 void check4deadevent(struct otri *checktri, struct event **freeevents,
10533                      struct event **eventheap, int *heapsize)
10534 #else /* not ANSI_DECLARATORS */
10535 void check4deadevent(checktri, freeevents, eventheap, heapsize)
10536 struct otri *checktri;
10537 struct event **freeevents;
10538 struct event **eventheap;
10539 int *heapsize;
10540 #endif /* not ANSI_DECLARATORS */
10541 
10542 {
10543   struct event *deadevent;
10544   vertex eventvertex;
10545   int eventnum;
10546 
10547   org(*checktri, eventvertex);
10548   if (eventvertex != (vertex) NULL) {
10549     deadevent = (struct event *) eventvertex;
10550     eventnum = deadevent->heapposition;
10551     deadevent->eventptr = (VOID *) *freeevents;
10552     *freeevents = deadevent;
10553     eventheapdelete(eventheap, *heapsize, eventnum);
10554     (*heapsize)--;
10555     setorg(*checktri, NULL);
10556   }
10557 }
10558 
10559 #endif /* not REDUCED */
10560 
10561 #ifndef REDUCED
10562 
10563 #ifdef ANSI_DECLARATORS
10564 struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
10565                         vertex searchpoint, struct otri *searchtri)
10566 #else /* not ANSI_DECLARATORS */
10567 struct splaynode *splay(m, splaytree, searchpoint, searchtri)
10568 struct mesh *m;
10569 struct splaynode *splaytree;
10570 vertex searchpoint;
10571 struct otri *searchtri;
10572 #endif /* not ANSI_DECLARATORS */
10573 
10574 {
10575   struct splaynode *child, *grandchild;
10576   struct splaynode *lefttree, *righttree;
10577   struct splaynode *leftright;
10578   vertex checkvertex;
10579   int rightofroot, rightofchild;
10580 
10581   if (splaytree == (struct splaynode *) NULL) {
10582     return (struct splaynode *) NULL;
10583   }
10584   dest(splaytree->keyedge, checkvertex);
10585   if (checkvertex == splaytree->keydest) {
10586     rightofroot = rightofhyperbola(m, &splaytree->keyedge, searchpoint);
10587     if (rightofroot) {
10588       otricopy(splaytree->keyedge, *searchtri);
10589       child = splaytree->rchild;
10590     } else {
10591       child = splaytree->lchild;
10592     }
10593     if (child == (struct splaynode *) NULL) {
10594       return splaytree;
10595     }
10596     dest(child->keyedge, checkvertex);
10597     if (checkvertex != child->keydest) {
10598       child = splay(m, child, searchpoint, searchtri);
10599       if (child == (struct splaynode *) NULL) {
10600         if (rightofroot) {
10601           splaytree->rchild = (struct splaynode *) NULL;
10602         } else {
10603           splaytree->lchild = (struct splaynode *) NULL;
10604         }
10605         return splaytree;
10606       }
10607     }
10608     rightofchild = rightofhyperbola(m, &child->keyedge, searchpoint);
10609     if (rightofchild) {
10610       otricopy(child->keyedge, *searchtri);
10611       grandchild = splay(m, child->rchild, searchpoint, searchtri);
10612       child->rchild = grandchild;
10613     } else {
10614       grandchild = splay(m, child->lchild, searchpoint, searchtri);
10615       child->lchild = grandchild;
10616     }
10617     if (grandchild == (struct splaynode *) NULL) {
10618       if (rightofroot) {
10619         splaytree->rchild = child->lchild;
10620         child->lchild = splaytree;
10621       } else {
10622         splaytree->lchild = child->rchild;
10623         child->rchild = splaytree;
10624       }
10625       return child;
10626     }
10627     if (rightofchild) {
10628       if (rightofroot) {
10629         splaytree->rchild = child->lchild;
10630         child->lchild = splaytree;
10631       } else {
10632         splaytree->lchild = grandchild->rchild;
10633         grandchild->rchild = splaytree;
10634       }
10635       child->rchild = grandchild->lchild;
10636       grandchild->lchild = child;
10637     } else {
10638       if (rightofroot) {
10639         splaytree->rchild = grandchild->lchild;
10640         grandchild->lchild = splaytree;
10641       } else {
10642         splaytree->lchild = child->rchild;
10643         child->rchild = splaytree;
10644       }
10645       child->lchild = grandchild->rchild;
10646       grandchild->rchild = child;
10647     }
10648     return grandchild;
10649   } else {
10650     lefttree = splay(m, splaytree->lchild, searchpoint, searchtri);
10651     righttree = splay(m, splaytree->rchild, searchpoint, searchtri);
10652 
10653     pooldealloc(&m->splaynodes, (VOID *) splaytree);
10654     if (lefttree == (struct splaynode *) NULL) {
10655       return righttree;
10656     } else if (righttree == (struct splaynode *) NULL) {
10657       return lefttree;
10658     } else if (lefttree->rchild == (struct splaynode *) NULL) {
10659       lefttree->rchild = righttree->lchild;
10660       righttree->lchild = lefttree;
10661       return righttree;
10662     } else if (righttree->lchild == (struct splaynode *) NULL) {
10663       righttree->lchild = lefttree->rchild;
10664       lefttree->rchild = righttree;
10665       return lefttree;
10666     } else {
10667 /*      printf("Holy Toledo!!!\n"); */
10668       leftright = lefttree->rchild;
10669       while (leftright->rchild != (struct splaynode *) NULL) {
10670         leftright = leftright->rchild;
10671       }
10672       leftright->rchild = righttree;
10673       return lefttree;
10674     }
10675   }
10676 }
10677 
10678 #endif /* not REDUCED */
10679 
10680 #ifndef REDUCED
10681 
10682 #ifdef ANSI_DECLARATORS
10683 struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
10684                               struct otri *newkey, vertex searchpoint)
10685 #else /* not ANSI_DECLARATORS */
10686 struct splaynode *splayinsert(m, splayroot, newkey, searchpoint)
10687 struct mesh *m;
10688 struct splaynode *splayroot;
10689 struct otri *newkey;
10690 vertex searchpoint;
10691 #endif /* not ANSI_DECLARATORS */
10692 
10693 {
10694   struct splaynode *newsplaynode;
10695 
10696   newsplaynode = (struct splaynode *) poolalloc(&m->splaynodes);
10697   otricopy(*newkey, newsplaynode->keyedge);
10698   dest(*newkey, newsplaynode->keydest);
10699   if (splayroot == (struct splaynode *) NULL) {
10700     newsplaynode->lchild = (struct splaynode *) NULL;
10701     newsplaynode->rchild = (struct splaynode *) NULL;
10702   } else if (rightofhyperbola(m, &splayroot->keyedge, searchpoint)) {
10703     newsplaynode->lchild = splayroot;
10704     newsplaynode->rchild = splayroot->rchild;
10705     splayroot->rchild = (struct splaynode *) NULL;
10706   } else {
10707     newsplaynode->lchild = splayroot->lchild;
10708     newsplaynode->rchild = splayroot;
10709     splayroot->lchild = (struct splaynode *) NULL;
10710   }
10711   return newsplaynode;
10712 }
10713 
10714 #endif /* not REDUCED */
10715 
10716 #ifndef REDUCED
10717 
10718 #ifdef ANSI_DECLARATORS
10719 struct splaynode *circletopinsert(struct mesh *m, struct behavior *b,
10720                                   struct splaynode *splayroot,
10721                                   struct otri *newkey,
10722                                   vertex pa, vertex pb, vertex pc, REAL topy)
10723 #else /* not ANSI_DECLARATORS */
10724 struct splaynode *circletopinsert(m, b, splayroot, newkey, pa, pb, pc, topy)
10725 struct mesh *m;
10726 struct behavior *b;
10727 struct splaynode *splayroot;
10728 struct otri *newkey;
10729 vertex pa;
10730 vertex pb;
10731 vertex pc;
10732 REAL topy;
10733 #endif /* not ANSI_DECLARATORS */
10734 
10735 {
10736   REAL ccwabc;
10737   REAL xac, yac, xbc, ybc;
10738   REAL aclen2, bclen2;
10739   REAL searchpoint[2];
10740   struct otri dummytri;
10741 
10742   ccwabc = counterclockwise(m, b, pa, pb, pc);
10743   xac = pa[0] - pc[0];
10744   yac = pa[1] - pc[1];
10745   xbc = pb[0] - pc[0];
10746   ybc = pb[1] - pc[1];
10747   aclen2 = xac * xac + yac * yac;
10748   bclen2 = xbc * xbc + ybc * ybc;
10749   searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
10750   searchpoint[1] = topy;
10751   return splayinsert(m, splay(m, splayroot, (vertex) searchpoint, &dummytri),
10752                      newkey, (vertex) searchpoint);
10753 }
10754 
10755 #endif /* not REDUCED */
10756 
10757 #ifndef REDUCED
10758 
10759 #ifdef ANSI_DECLARATORS
10760 struct splaynode *frontlocate(struct mesh *m, struct splaynode *splayroot,
10761                               struct otri *bottommost, vertex searchvertex,
10762                               struct otri *searchtri, int *farright)
10763 #else /* not ANSI_DECLARATORS */
10764 struct splaynode *frontlocate(m, splayroot, bottommost, searchvertex,
10765                               searchtri, farright)
10766 struct mesh *m;
10767 struct splaynode *splayroot;
10768 struct otri *bottommost;
10769 vertex searchvertex;
10770 struct otri *searchtri;
10771 int *farright;
10772 #endif /* not ANSI_DECLARATORS */
10773 
10774 {
10775   int farrightflag;
10776   triangle ptr;                       /* Temporary variable used by onext(). */
10777 
10778   otricopy(*bottommost, *searchtri);
10779   splayroot = splay(m, splayroot, searchvertex, searchtri);
10780 
10781   farrightflag = 0;
10782   while (!farrightflag && rightofhyperbola(m, searchtri, searchvertex)) {
10783     onextself(*searchtri);
10784     farrightflag = otriequal(*searchtri, *bottommost);
10785   }
10786   *farright = farrightflag;
10787   return splayroot;
10788 }
10789 
10790 #endif /* not REDUCED */
10791 
10792 #ifndef REDUCED
10793 
10794 #ifdef ANSI_DECLARATORS
10795 long sweeplinedelaunay(struct mesh *m, struct behavior *b)
10796 #else /* not ANSI_DECLARATORS */
10797 long sweeplinedelaunay(m, b)
10798 struct mesh *m;
10799 struct behavior *b;
10800 #endif /* not ANSI_DECLARATORS */
10801 
10802 {
10803   struct event **eventheap;
10804   struct event *events;
10805   struct event *freeevents;
10806   struct event *nextevent;
10807   struct event *newevent;
10808   struct splaynode *splayroot;
10809   struct otri bottommost;
10810   struct otri searchtri;
10811   struct otri fliptri;
10812   struct otri lefttri, righttri, farlefttri, farrighttri;
10813   struct otri inserttri;
10814   vertex firstvertex, secondvertex;
10815   vertex nextvertex, lastvertex;
10816   vertex connectvertex;
10817   vertex leftvertex, midvertex, rightvertex;
10818   REAL lefttest, righttest;
10819   int heapsize;
10820   int check4events, farrightflag;
10821   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
10822 
10823   poolinit(&m->splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK,
10824            SPLAYNODEPERBLOCK, 0);
10825   splayroot = (struct splaynode *) NULL;
10826 
10827   if (b->verbose) {
10828     printf("  Placing vertices in event heap.\n");
10829   }
10830   createeventheap(m, &eventheap, &events, &freeevents);
10831   heapsize = m->invertices;
10832 
10833   if (b->verbose) {
10834     printf("  Forming triangulation.\n");
10835   }
10836   maketriangle(m, b, &lefttri);
10837   maketriangle(m, b, &righttri);
10838   bond(lefttri, righttri);
10839   lnextself(lefttri);
10840   lprevself(righttri);
10841   bond(lefttri, righttri);
10842   lnextself(lefttri);
10843   lprevself(righttri);
10844   bond(lefttri, righttri);
10845   firstvertex = (vertex) eventheap[0]->eventptr;
10846   eventheap[0]->eventptr = (VOID *) freeevents;
10847   freeevents = eventheap[0];
10848   eventheapdelete(eventheap, heapsize, 0);
10849   heapsize--;
10850   do {
10851     if (heapsize == 0) {
10852       printf("Error:  Input vertices are all identical.\n");
10853       triexit(1);
10854     }
10855     secondvertex = (vertex) eventheap[0]->eventptr;
10856     eventheap[0]->eventptr = (VOID *) freeevents;
10857     freeevents = eventheap[0];
10858     eventheapdelete(eventheap, heapsize, 0);
10859     heapsize--;
10860     if ((firstvertex[0] == secondvertex[0]) &&
10861         (firstvertex[1] == secondvertex[1])) {
10862       if (!b->quiet) {
10863         printf(
10864 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10865                secondvertex[0], secondvertex[1]);
10866       }
10867       setvertextype(secondvertex, UNDEADVERTEX);
10868       m->undeads++;
10869     }
10870   } while ((firstvertex[0] == secondvertex[0]) &&
10871            (firstvertex[1] == secondvertex[1]));
10872   setorg(lefttri, firstvertex);
10873   setdest(lefttri, secondvertex);
10874   setorg(righttri, secondvertex);
10875   setdest(righttri, firstvertex);
10876   lprev(lefttri, bottommost);
10877   lastvertex = secondvertex;
10878   while (heapsize > 0) {
10879     nextevent = eventheap[0];
10880     eventheapdelete(eventheap, heapsize, 0);
10881     heapsize--;
10882     check4events = 1;
10883     if (nextevent->xkey < m->xmin) {
10884       decode(nextevent->eventptr, fliptri);
10885       oprev(fliptri, farlefttri);
10886       check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
10887       onext(fliptri, farrighttri);
10888       check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
10889 
10890       if (otriequal(farlefttri, bottommost)) {
10891         lprev(fliptri, bottommost);
10892       }
10893       flip(m, b, &fliptri);
10894       setapex(fliptri, NULL);
10895       lprev(fliptri, lefttri);
10896       lnext(fliptri, righttri);
10897       sym(lefttri, farlefttri);
10898 
10899       if (randomnation(SAMPLERATE) == 0) {
10900         symself(fliptri);
10901         dest(fliptri, leftvertex);
10902         apex(fliptri, midvertex);
10903         org(fliptri, rightvertex);
10904         splayroot = circletopinsert(m, b, splayroot, &lefttri, leftvertex,
10905                                     midvertex, rightvertex, nextevent->ykey);
10906       }
10907     } else {
10908       nextvertex = (vertex) nextevent->eventptr;
10909       if ((nextvertex[0] == lastvertex[0]) &&
10910           (nextvertex[1] == lastvertex[1])) {
10911         if (!b->quiet) {
10912           printf(
10913 "Warning:  A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
10914                  nextvertex[0], nextvertex[1]);
10915         }
10916         setvertextype(nextvertex, UNDEADVERTEX);
10917         m->undeads++;
10918         check4events = 0;
10919       } else {
10920         lastvertex = nextvertex;
10921 
10922         splayroot = frontlocate(m, splayroot, &bottommost, nextvertex,
10923                                 &searchtri, &farrightflag);
10924 /*
10925         otricopy(bottommost, searchtri);
10926         farrightflag = 0;
10927         while (!farrightflag && rightofhyperbola(m, &searchtri, nextvertex)) {
10928           onextself(searchtri);
10929           farrightflag = otriequal(searchtri, bottommost);
10930         }
10931 */
10932 
10933         check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
10934 
10935         otricopy(searchtri, farrighttri);
10936         sym(searchtri, farlefttri);
10937         maketriangle(m, b, &lefttri);
10938         maketriangle(m, b, &righttri);
10939         dest(farrighttri, connectvertex);
10940         setorg(lefttri, connectvertex);
10941         setdest(lefttri, nextvertex);
10942         setorg(righttri, nextvertex);
10943         setdest(righttri, connectvertex);
10944         bond(lefttri, righttri);
10945         lnextself(lefttri);
10946         lprevself(righttri);
10947         bond(lefttri, righttri);
10948         lnextself(lefttri);
10949         lprevself(righttri);
10950         bond(lefttri, farlefttri);
10951         bond(righttri, farrighttri);
10952         if (!farrightflag && otriequal(farrighttri, bottommost)) {
10953           otricopy(lefttri, bottommost);
10954         }
10955 
10956         if (randomnation(SAMPLERATE) == 0) {
10957           splayroot = splayinsert(m, splayroot, &lefttri, nextvertex);
10958         } else if (randomnation(SAMPLERATE) == 0) {
10959           lnext(righttri, inserttri);
10960           splayroot = splayinsert(m, splayroot, &inserttri, nextvertex);
10961         }
10962       }
10963     }
10964     nextevent->eventptr = (VOID *) freeevents;
10965     freeevents = nextevent;
10966 
10967     if (check4events) {
10968       apex(farlefttri, leftvertex);
10969       dest(lefttri, midvertex);
10970       apex(lefttri, rightvertex);
10971       lefttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
10972       if (lefttest > 0.0) {
10973         newevent = freeevents;
10974         freeevents = (struct event *) freeevents->eventptr;
10975         newevent->xkey = m->xminextreme;
10976         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
10977                                    lefttest);
10978         newevent->eventptr = (VOID *) encode(lefttri);
10979         eventheapinsert(eventheap, heapsize, newevent);
10980         heapsize++;
10981         setorg(lefttri, newevent);
10982       }
10983       apex(righttri, leftvertex);
10984       org(righttri, midvertex);
10985       apex(farrighttri, rightvertex);
10986       righttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
10987       if (righttest > 0.0) {
10988         newevent = freeevents;
10989         freeevents = (struct event *) freeevents->eventptr;
10990         newevent->xkey = m->xminextreme;
10991         newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
10992                                    righttest);
10993         newevent->eventptr = (VOID *) encode(farrighttri);
10994         eventheapinsert(eventheap, heapsize, newevent);
10995         heapsize++;
10996         setorg(farrighttri, newevent);
10997       }
10998     }
10999   }
11000 
11001   pooldeinit(&m->splaynodes);
11002   lprevself(bottommost);
11003   return removeghosts(m, b, &bottommost);
11004 }
11005 
11006 #endif /* not REDUCED */
11007 
11008 /**                                                                         **/
11009 /**                                                                         **/
11010 /********* Sweepline Delaunay triangulation ends here                *********/
11011 
11012 /********* General mesh construction routines begin here             *********/
11013 /**                                                                         **/
11014 /**                                                                         **/
11015 
11016 /*****************************************************************************/
11017 /*                                                                           */
11018 /*  delaunay()   Form a Delaunay triangulation.                              */
11019 /*                                                                           */
11020 /*****************************************************************************/
11021 
11022 #ifdef ANSI_DECLARATORS
11023 long delaunay(struct mesh *m, struct behavior *b)
11024 #else /* not ANSI_DECLARATORS */
11025 long delaunay(m, b)
11026 struct mesh *m;
11027 struct behavior *b;
11028 #endif /* not ANSI_DECLARATORS */
11029 
11030 {
11031   long hulledges;
11032 
11033   m->eextras = 0;
11034   initializetrisubpools(m, b);
11035 
11036 #ifdef REDUCED
11037   if (!b->quiet) {
11038     printf(
11039       "Constructing Delaunay triangulation by divide-and-conquer method.\n");
11040   }
11041   hulledges = divconqdelaunay(m, b);
11042 #else /* not REDUCED */
11043   if (!b->quiet) {
11044     printf("Constructing Delaunay triangulation ");
11045     if (b->incremental) {
11046       printf("by incremental method.\n");
11047     } else if (b->sweepline) {
11048       printf("by sweepline method.\n");
11049     } else {
11050       printf("by divide-and-conquer method.\n");
11051     }
11052   }
11053   if (b->incremental) {
11054     hulledges = incrementaldelaunay(m, b);
11055   } else if (b->sweepline) {
11056     hulledges = sweeplinedelaunay(m, b);
11057   } else {
11058     hulledges = divconqdelaunay(m, b);
11059   }
11060 #endif /* not REDUCED */
11061 
11062   if (m->triangles.items == 0) {
11063     /* The input vertices were all collinear, so there are no triangles. */
11064     return 0l;
11065   } else {
11066     return hulledges;
11067   }
11068 }
11069 
11070 /*****************************************************************************/
11071 /*                                                                           */
11072 /*  reconstruct()   Reconstruct a triangulation from its .ele (and possibly  */
11073 /*                  .poly) file.  Used when the -r switch is used.           */
11074 /*                                                                           */
11075 /*  Reads an .ele file and reconstructs the original mesh.  If the -p switch */
11076 /*  is used, this procedure will also read a .poly file and reconstruct the  */
11077 /*  subsegments of the original mesh.  If the -a switch is used, this        */
11078 /*  procedure will also read an .area file and set a maximum area constraint */
11079 /*  on each triangle.                                                        */
11080 /*                                                                           */
11081 /*  Vertices that are not corners of triangles, such as nodes on edges of    */
11082 /*  subparametric elements, are discarded.                                   */
11083 /*                                                                           */
11084 /*  This routine finds the adjacencies between triangles (and subsegments)   */
11085 /*  by forming one stack of triangles for each vertex.  Each triangle is on  */
11086 /*  three different stacks simultaneously.  Each triangle's subsegment       */
11087 /*  pointers are used to link the items in each stack.  This memory-saving   */
11088 /*  feature makes the code harder to read.  The most important thing to keep */
11089 /*  in mind is that each triangle is removed from a stack precisely when     */
11090 /*  the corresponding pointer is adjusted to refer to a subsegment rather    */
11091 /*  than the next triangle of the stack.                                     */
11092 /*                                                                           */
11093 /*****************************************************************************/
11094 
11095 #ifndef CDT_ONLY
11096 
11097 #ifdef TRILIBRARY
11098 
11099 #ifdef ANSI_DECLARATORS
11100 int reconstruct(struct mesh *m, struct behavior *b, int *trianglelist,
11101                 REAL *triangleattriblist, REAL *trianglearealist,
11102                 int elements, int corners, int attribs,
11103                 int *segmentlist,int *segmentmarkerlist, int numberofsegments)
11104 #else /* not ANSI_DECLARATORS */
11105 int reconstruct(m, b, trianglelist, triangleattriblist, trianglearealist,
11106                 elements, corners, attribs, segmentlist, segmentmarkerlist,
11107                 numberofsegments)
11108 struct mesh *m;
11109 struct behavior *b;
11110 int *trianglelist;
11111 REAL *triangleattriblist;
11112 REAL *trianglearealist;
11113 int elements;
11114 int corners;
11115 int attribs;
11116 int *segmentlist;
11117 int *segmentmarkerlist;
11118 int numberofsegments;
11119 #endif /* not ANSI_DECLARATORS */
11120 
11121 #else /* not TRILIBRARY */
11122 
11123 #ifdef ANSI_DECLARATORS
11124 long reconstruct(struct mesh *m, struct behavior *b, char *elefilename,
11125                  char *areafilename, char *polyfilename, FILE *polyfile)
11126 #else /* not ANSI_DECLARATORS */
11127 long reconstruct(m, b, elefilename, areafilename, polyfilename, polyfile)
11128 struct mesh *m;
11129 struct behavior *b;
11130 char *elefilename;
11131 char *areafilename;
11132 char *polyfilename;
11133 FILE *polyfile;
11134 #endif /* not ANSI_DECLARATORS */
11135 
11136 #endif /* not TRILIBRARY */
11137 
11138 {
11139 #ifdef TRILIBRARY
11140   int vertexindex;
11141   int attribindex;
11142 #else /* not TRILIBRARY */
11143   FILE *elefile;
11144   FILE *areafile;
11145   char inputline[INPUTLINESIZE];
11146   char *stringptr;
11147   int areaelements;
11148 #endif /* not TRILIBRARY */
11149   struct otri triangleloop;
11150   struct otri triangleleft;
11151   struct otri checktri;
11152   struct otri checkleft;
11153   struct otri checkneighbor;
11154   struct osub subsegloop;
11155   triangle *vertexarray;
11156   triangle *prevlink;
11157   triangle nexttri;
11158   vertex tdest, tapex;
11159   vertex checkdest, checkapex;
11160   vertex shorg;
11161   vertex killvertex;
11162   vertex segmentorg, segmentdest;
11163   REAL area;
11164   int corner[3];
11165   int end[2];
11166   int killvertexindex;
11167   int incorners;
11168   int segmentmarkers;
11169   int boundmarker;
11170   int aroundvertex;
11171   long hullsize;
11172   int notfound;
11173   long elementnumber, segmentnumber;
11174   int i, j;
11175   triangle ptr;                         /* Temporary variable used by sym(). */
11176 
11177 #ifdef TRILIBRARY
11178   m->inelements = elements;
11179   incorners = corners;
11180   if (incorners < 3) {
11181     printf("Error:  Triangles must have at least 3 vertices.\n");
11182     triexit(1);
11183   }
11184   m->eextras = attribs;
11185 #else /* not TRILIBRARY */
11186   /* Read the triangles from an .ele file. */
11187   if (!b->quiet) {
11188     printf("Opening %s.\n", elefilename);
11189   }
11190   elefile = fopen(elefilename, "r");
11191   if (elefile == (FILE *) NULL) {
11192     printf("  Error:  Cannot access file %s.\n", elefilename);
11193     triexit(1);
11194   }
11195   /* Read number of triangles, number of vertices per triangle, and */
11196   /*   number of triangle attributes from .ele file.                */
11197   stringptr = readline(inputline, elefile, elefilename);
11198   m->inelements = (int) strtol(stringptr, &stringptr, 0);
11199   stringptr = findfield(stringptr);
11200   if (*stringptr == '\0') {
11201     incorners = 3;
11202   } else {
11203     incorners = (int) strtol(stringptr, &stringptr, 0);
11204     if (incorners < 3) {
11205       printf("Error:  Triangles in %s must have at least 3 vertices.\n",
11206              elefilename);
11207       triexit(1);
11208     }
11209   }
11210   stringptr = findfield(stringptr);
11211   if (*stringptr == '\0') {
11212     m->eextras = 0;
11213   } else {
11214     m->eextras = (int) strtol(stringptr, &stringptr, 0);
11215   }
11216 #endif /* not TRILIBRARY */
11217 
11218   initializetrisubpools(m, b);
11219 
11220   /* Create the triangles. */
11221   for (elementnumber = 1; elementnumber <= m->inelements; elementnumber++) {
11222     maketriangle(m, b, &triangleloop);
11223     /* Mark the triangle as living. */
11224     triangleloop.tri[3] = (triangle) triangleloop.tri;
11225   }
11226 
11227   segmentmarkers = 0;
11228   if (b->poly) {
11229 #ifdef TRILIBRARY
11230     m->insegments = numberofsegments;
11231     segmentmarkers = segmentmarkerlist != (int *) NULL;
11232 #else /* not TRILIBRARY */
11233     /* Read number of segments and number of segment */
11234     /*   boundary markers from .poly file.           */
11235     stringptr = readline(inputline, polyfile, b->inpolyfilename);
11236     m->insegments = (int) strtol(stringptr, &stringptr, 0);
11237     stringptr = findfield(stringptr);
11238     if (*stringptr != '\0') {
11239       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
11240     }
11241 #endif /* not TRILIBRARY */
11242 
11243     /* Create the subsegments. */
11244     for (segmentnumber = 1; segmentnumber <= m->insegments; segmentnumber++) {
11245       makesubseg(m, &subsegloop);
11246       /* Mark the subsegment as living. */
11247       subsegloop.ss[2] = (subseg) subsegloop.ss;
11248     }
11249   }
11250 
11251 #ifdef TRILIBRARY
11252   vertexindex = 0;
11253   attribindex = 0;
11254 #else /* not TRILIBRARY */
11255   if (b->vararea) {
11256     /* Open an .area file, check for consistency with the .ele file. */
11257     if (!b->quiet) {
11258       printf("Opening %s.\n", areafilename);
11259     }
11260     areafile = fopen(areafilename, "r");
11261     if (areafile == (FILE *) NULL) {
11262       printf("  Error:  Cannot access file %s.\n", areafilename);
11263       triexit(1);
11264     }
11265     stringptr = readline(inputline, areafile, areafilename);
11266     areaelements = (int) strtol(stringptr, &stringptr, 0);
11267     if (areaelements != m->inelements) {
11268       printf("Error:  %s and %s disagree on number of triangles.\n",
11269              elefilename, areafilename);
11270       triexit(1);
11271     }
11272   }
11273 #endif /* not TRILIBRARY */
11274 
11275   if (!b->quiet) {
11276     printf("Reconstructing mesh.\n");
11277   }
11278   /* Allocate a temporary array that maps each vertex to some adjacent */
11279   /*   triangle.  I took care to allocate all the permanent memory for */
11280   /*   triangles and subsegments first.                                */
11281   vertexarray = (triangle *) trimalloc(m->vertices.items *
11282                                        (int) sizeof(triangle));
11283   /* Each vertex is initially unrepresented. */
11284   for (i = 0; i < m->vertices.items; i++) {
11285     vertexarray[i] = (triangle) m->dummytri;
11286   }
11287 
11288   if (b->verbose) {
11289     printf("  Assembling triangles.\n");
11290   }
11291   /* Read the triangles from the .ele file, and link */
11292   /*   together those that share an edge.            */
11293   traversalinit(&m->triangles);
11294   triangleloop.tri = triangletraverse(m);
11295   elementnumber = b->firstnumber;
11296   while (triangleloop.tri != (triangle *) NULL) {
11297 #ifdef TRILIBRARY
11298     /* Copy the triangle's three corners. */
11299     for (j = 0; j < 3; j++) {
11300       corner[j] = trianglelist[vertexindex++];
11301       if ((corner[j] < b->firstnumber) ||
11302           (corner[j] >= b->firstnumber + m->invertices)) {
11303         printf("Error:  Triangle %ld has an invalid vertex index.\n",
11304                elementnumber);
11305         triexit(1);
11306       }
11307     }
11308 #else /* not TRILIBRARY */
11309     /* Read triangle number and the triangle's three corners. */
11310     stringptr = readline(inputline, elefile, elefilename);
11311     for (j = 0; j < 3; j++) {
11312       stringptr = findfield(stringptr);
11313       if (*stringptr == '\0') {
11314         printf("Error:  Triangle %ld is missing vertex %d in %s.\n",
11315                elementnumber, j + 1, elefilename);
11316         triexit(1);
11317       } else {
11318         corner[j] = (int) strtol(stringptr, &stringptr, 0);
11319         if ((corner[j] < b->firstnumber) ||
11320             (corner[j] >= b->firstnumber + m->invertices)) {
11321           printf("Error:  Triangle %ld has an invalid vertex index.\n",
11322                  elementnumber);
11323           triexit(1);
11324         }
11325       }
11326     }
11327 #endif /* not TRILIBRARY */
11328 
11329     /* Find out about (and throw away) extra nodes. */
11330     for (j = 3; j < incorners; j++) {
11331 #ifdef TRILIBRARY
11332       killvertexindex = trianglelist[vertexindex++];
11333 #else /* not TRILIBRARY */
11334       stringptr = findfield(stringptr);
11335       if (*stringptr != '\0') {
11336         killvertexindex = (int) strtol(stringptr, &stringptr, 0);
11337 #endif /* not TRILIBRARY */
11338         if ((killvertexindex >= b->firstnumber) &&
11339             (killvertexindex < b->firstnumber + m->invertices)) {
11340           /* Delete the non-corner vertex if it's not already deleted. */
11341           killvertex = getvertex(m, b, killvertexindex);
11342           if (vertextype(killvertex) != DEADVERTEX) {
11343             vertexdealloc(m, killvertex);
11344           }
11345         }
11346 #ifndef TRILIBRARY
11347       }
11348 #endif /* not TRILIBRARY */
11349     }
11350 
11351     /* Read the triangle's attributes. */
11352     for (j = 0; j < m->eextras; j++) {
11353 #ifdef TRILIBRARY
11354       setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
11355 #else /* not TRILIBRARY */
11356       stringptr = findfield(stringptr);
11357       if (*stringptr == '\0') {
11358         setelemattribute(triangleloop, j, 0);
11359       } else {
11360         setelemattribute(triangleloop, j,
11361                          (REAL) strtod(stringptr, &stringptr));
11362       }
11363 #endif /* not TRILIBRARY */
11364     }
11365 
11366     if (b->vararea) {
11367 #ifdef TRILIBRARY
11368       area = trianglearealist[elementnumber - b->firstnumber];
11369 #else /* not TRILIBRARY */
11370       /* Read an area constraint from the .area file. */
11371       stringptr = readline(inputline, areafile, areafilename);
11372       stringptr = findfield(stringptr);
11373       if (*stringptr == '\0') {
11374         area = -1.0;                      /* No constraint on this triangle. */
11375       } else {
11376         area = (REAL) strtod(stringptr, &stringptr);
11377       }
11378 #endif /* not TRILIBRARY */
11379       setareabound(triangleloop, area);
11380     }
11381 
11382     /* Set the triangle's vertices. */
11383     triangleloop.orient = 0;
11384     setorg(triangleloop, getvertex(m, b, corner[0]));
11385     setdest(triangleloop, getvertex(m, b, corner[1]));
11386     setapex(triangleloop, getvertex(m, b, corner[2]));
11387     /* Try linking the triangle to others that share these vertices. */
11388     for (triangleloop.orient = 0; triangleloop.orient < 3;
11389          triangleloop.orient++) {
11390       /* Take the number for the origin of triangleloop. */
11391       aroundvertex = corner[triangleloop.orient];
11392       /* Look for other triangles having this vertex. */
11393       nexttri = vertexarray[aroundvertex - b->firstnumber];
11394       /* Link the current triangle to the next one in the stack. */
11395       triangleloop.tri[6 + triangleloop.orient] = nexttri;
11396       /* Push the current triangle onto the stack. */
11397       vertexarray[aroundvertex - b->firstnumber] = encode(triangleloop);
11398       decode(nexttri, checktri);
11399       if (checktri.tri != m->dummytri) {
11400         dest(triangleloop, tdest);
11401         apex(triangleloop, tapex);
11402         /* Look for other triangles that share an edge. */
11403         do {
11404           dest(checktri, checkdest);
11405           apex(checktri, checkapex);
11406           if (tapex == checkdest) {
11407             /* The two triangles share an edge; bond them together. */
11408             lprev(triangleloop, triangleleft);
11409             bond(triangleleft, checktri);
11410           }
11411           if (tdest == checkapex) {
11412             /* The two triangles share an edge; bond them together. */
11413             lprev(checktri, checkleft);
11414             bond(triangleloop, checkleft);
11415           }
11416           /* Find the next triangle in the stack. */
11417           nexttri = checktri.tri[6 + checktri.orient];
11418           decode(nexttri, checktri);
11419         } while (checktri.tri != m->dummytri);
11420       }
11421     }
11422     triangleloop.tri = triangletraverse(m);
11423     elementnumber++;
11424   }
11425 
11426 #ifdef TRILIBRARY
11427   vertexindex = 0;
11428 #else /* not TRILIBRARY */
11429   fclose(elefile);
11430   if (b->vararea) {
11431     fclose(areafile);
11432   }
11433 #endif /* not TRILIBRARY */
11434 
11435   hullsize = 0;                      /* Prepare to count the boundary edges. */
11436   if (b->poly) {
11437     if (b->verbose) {
11438       printf("  Marking segments in triangulation.\n");
11439     }
11440     /* Read the segments from the .poly file, and link them */
11441     /*   to their neighboring triangles.                    */
11442     boundmarker = 0;
11443     traversalinit(&m->subsegs);
11444     subsegloop.ss = subsegtraverse(m);
11445     segmentnumber = b->firstnumber;
11446     while (subsegloop.ss != (subseg *) NULL) {
11447 #ifdef TRILIBRARY
11448       end[0] = segmentlist[vertexindex++];
11449       end[1] = segmentlist[vertexindex++];
11450       if (segmentmarkers) {
11451         boundmarker = segmentmarkerlist[segmentnumber - b->firstnumber];
11452       }
11453 #else /* not TRILIBRARY */
11454       /* Read the endpoints of each segment, and possibly a boundary marker. */
11455       stringptr = readline(inputline, polyfile, b->inpolyfilename);
11456       /* Skip the first (segment number) field. */
11457       stringptr = findfield(stringptr);
11458       if (*stringptr == '\0') {
11459         printf("Error:  Segment %ld has no endpoints in %s.\n", segmentnumber,
11460                polyfilename);
11461         triexit(1);
11462       } else {
11463         end[0] = (int) strtol(stringptr, &stringptr, 0);
11464       }
11465       stringptr = findfield(stringptr);
11466       if (*stringptr == '\0') {
11467         printf("Error:  Segment %ld is missing its second endpoint in %s.\n",
11468                segmentnumber, polyfilename);
11469         triexit(1);
11470       } else {
11471         end[1] = (int) strtol(stringptr, &stringptr, 0);
11472       }
11473       if (segmentmarkers) {
11474         stringptr = findfield(stringptr);
11475         if (*stringptr == '\0') {
11476           boundmarker = 0;
11477         } else {
11478           boundmarker = (int) strtol(stringptr, &stringptr, 0);
11479         }
11480       }
11481 #endif /* not TRILIBRARY */
11482       for (j = 0; j < 2; j++) {
11483         if ((end[j] < b->firstnumber) ||
11484             (end[j] >= b->firstnumber + m->invertices)) {
11485           printf("Error:  Segment %ld has an invalid vertex index.\n",
11486                  segmentnumber);
11487           triexit(1);
11488         }
11489       }
11490 
11491       /* set the subsegment's vertices. */
11492       subsegloop.ssorient = 0;
11493       segmentorg = getvertex(m, b, end[0]);
11494       segmentdest = getvertex(m, b, end[1]);
11495       setsorg(subsegloop, segmentorg);
11496       setsdest(subsegloop, segmentdest);
11497       setsegorg(subsegloop, segmentorg);
11498       setsegdest(subsegloop, segmentdest);
11499       setmark(subsegloop, boundmarker);
11500       /* Try linking the subsegment to triangles that share these vertices. */
11501       for (subsegloop.ssorient = 0; subsegloop.ssorient < 2;
11502            subsegloop.ssorient++) {
11503         /* Take the number for the destination of subsegloop. */
11504         aroundvertex = end[1 - subsegloop.ssorient];
11505         /* Look for triangles having this vertex. */
11506         prevlink = &vertexarray[aroundvertex - b->firstnumber];
11507         nexttri = vertexarray[aroundvertex - b->firstnumber];
11508         decode(nexttri, checktri);
11509         sorg(subsegloop, shorg);
11510         notfound = 1;
11511         /* Look for triangles having this edge.  Note that I'm only       */
11512         /*   comparing each triangle's destination with the subsegment;   */
11513         /*   each triangle's apex is handled through a different vertex.  */
11514         /*   Because each triangle appears on three vertices' lists, each */
11515         /*   occurrence of a triangle on a list can (and does) represent  */
11516         /*   an edge.  In this way, most edges are represented twice, and */
11517         /*   every triangle-subsegment bond is represented once.          */
11518         while (notfound && (checktri.tri != m->dummytri)) {
11519           dest(checktri, checkdest);
11520           if (shorg == checkdest) {
11521             /* We have a match.  Remove this triangle from the list. */
11522             *prevlink = checktri.tri[6 + checktri.orient];
11523             /* Bond the subsegment to the triangle. */
11524             tsbond(checktri, subsegloop);
11525             /* Check if this is a boundary edge. */
11526             sym(checktri, checkneighbor);
11527             if (checkneighbor.tri == m->dummytri) {
11528               /* The next line doesn't insert a subsegment (because there's */
11529               /*   already one there), but it sets the boundary markers of  */
11530               /*   the existing subsegment and its vertices.                */
11531               insertsubseg(m, b, &checktri, 1);
11532               hullsize++;
11533             }
11534             notfound = 0;
11535           }
11536           /* Find the next triangle in the stack. */
11537           prevlink = &checktri.tri[6 + checktri.orient];
11538           nexttri = checktri.tri[6 + checktri.orient];
11539           decode(nexttri, checktri);
11540         }
11541       }
11542       subsegloop.ss = subsegtraverse(m);
11543       segmentnumber++;
11544     }
11545   }
11546 
11547   /* Mark the remaining edges as not being attached to any subsegment. */
11548   /* Also, count the (yet uncounted) boundary edges.                   */
11549   for (i = 0; i < m->vertices.items; i++) {
11550     /* Search the stack of triangles adjacent to a vertex. */
11551     nexttri = vertexarray[i];
11552     decode(nexttri, checktri);
11553     while (checktri.tri != m->dummytri) {
11554       /* Find the next triangle in the stack before this */
11555       /*   information gets overwritten.                 */
11556       nexttri = checktri.tri[6 + checktri.orient];
11557       /* No adjacent subsegment.  (This overwrites the stack info.) */
11558       tsdissolve(checktri);
11559       sym(checktri, checkneighbor);
11560       if (checkneighbor.tri == m->dummytri) {
11561         insertsubseg(m, b, &checktri, 1);
11562         hullsize++;
11563       }
11564       decode(nexttri, checktri);
11565     }
11566   }
11567 
11568   trifree((VOID *) vertexarray);
11569   return hullsize;
11570 }
11571 
11572 #endif /* not CDT_ONLY */
11573 
11574 /**                                                                         **/
11575 /**                                                                         **/
11576 /********* General mesh construction routines end here               *********/
11577 
11578 /********* Segment insertion begins here                             *********/
11579 /**                                                                         **/
11580 /**                                                                         **/
11581 
11582 /*****************************************************************************/
11583 /*                                                                           */
11584 /*  finddirection()   Find the first triangle on the path from one point     */
11585 /*                    to another.                                            */
11586 /*                                                                           */
11587 /*  Finds the triangle that intersects a line segment drawn from the         */
11588 /*  origin of `searchtri' to the point `searchpoint', and returns the result */
11589 /*  in `searchtri'.  The origin of `searchtri' does not change, even though  */
11590 /*  the triangle returned may differ from the one passed in.  This routine   */
11591 /*  is used to find the direction to move in to get from one point to        */
11592 /*  another.                                                                 */
11593 /*                                                                           */
11594 /*  The return value notes whether the destination or apex of the found      */
11595 /*  triangle is collinear with the two points in question.                   */
11596 /*                                                                           */
11597 /*****************************************************************************/
11598 
11599 #ifdef ANSI_DECLARATORS
11600 enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
11601                                        struct otri *searchtri,
11602                                        vertex searchpoint)
11603 #else /* not ANSI_DECLARATORS */
11604 enum finddirectionresult finddirection(m, b, searchtri, searchpoint)
11605 struct mesh *m;
11606 struct behavior *b;
11607 struct otri *searchtri;
11608 vertex searchpoint;
11609 #endif /* not ANSI_DECLARATORS */
11610 
11611 {
11612   struct otri checktri;
11613   vertex startvertex;
11614   vertex leftvertex, rightvertex;
11615   REAL leftccw, rightccw;
11616   int leftflag, rightflag;
11617   triangle ptr;           /* Temporary variable used by onext() and oprev(). */
11618 
11619   org(*searchtri, startvertex);
11620   dest(*searchtri, rightvertex);
11621   apex(*searchtri, leftvertex);
11622   /* Is `searchpoint' to the left? */
11623   leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11624   leftflag = leftccw > 0.0;
11625   /* Is `searchpoint' to the right? */
11626   rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11627   rightflag = rightccw > 0.0;
11628   if (leftflag && rightflag) {
11629     /* `searchtri' faces directly away from `searchpoint'.  We could go left */
11630     /*   or right.  Ask whether it's a triangle or a boundary on the left.   */
11631     onext(*searchtri, checktri);
11632     if (checktri.tri == m->dummytri) {
11633       leftflag = 0;
11634     } else {
11635       rightflag = 0;
11636     }
11637   }
11638   while (leftflag) {
11639     /* Turn left until satisfied. */
11640     onextself(*searchtri);
11641     if (searchtri->tri == m->dummytri) {
11642       printf("Internal error in finddirection():  Unable to find a\n");
11643       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11644              startvertex[1]);
11645       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11646       internalerror();
11647     }
11648     apex(*searchtri, leftvertex);
11649     rightccw = leftccw;
11650     leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
11651     leftflag = leftccw > 0.0;
11652   }
11653   while (rightflag) {
11654     /* Turn right until satisfied. */
11655     oprevself(*searchtri);
11656     if (searchtri->tri == m->dummytri) {
11657       printf("Internal error in finddirection():  Unable to find a\n");
11658       printf("  triangle leading from (%.12g, %.12g) to", startvertex[0],
11659              startvertex[1]);
11660       printf("  (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
11661       internalerror();
11662     }
11663     dest(*searchtri, rightvertex);
11664     leftccw = rightccw;
11665     rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
11666     rightflag = rightccw > 0.0;
11667   }
11668   if (leftccw == 0.0) {
11669     return LEFTCOLLINEAR;
11670   } else if (rightccw == 0.0) {
11671     return RIGHTCOLLINEAR;
11672   } else {
11673     return WITHIN;
11674   }
11675 }
11676 
11677 /*****************************************************************************/
11678 /*                                                                           */
11679 /*  segmentintersection()   Find the intersection of an existing segment     */
11680 /*                          and a segment that is being inserted.  Insert    */
11681 /*                          a vertex at the intersection, splitting an       */
11682 /*                          existing subsegment.                             */
11683 /*                                                                           */
11684 /*  The segment being inserted connects the apex of splittri to endpoint2.   */
11685 /*  splitsubseg is the subsegment being split, and MUST adjoin splittri.     */
11686 /*  Hence, endpoints of the subsegment being split are the origin and        */
11687 /*  destination of splittri.                                                 */
11688 /*                                                                           */
11689 /*  On completion, splittri is a handle having the newly inserted            */
11690 /*  intersection point as its origin, and endpoint1 as its destination.      */
11691 /*                                                                           */
11692 /*****************************************************************************/
11693 
11694 #ifdef ANSI_DECLARATORS
11695 void segmentintersection(struct mesh *m, struct behavior *b,
11696                          struct otri *splittri, struct osub *splitsubseg,
11697                          vertex endpoint2)
11698 #else /* not ANSI_DECLARATORS */
11699 void segmentintersection(m, b, splittri, splitsubseg, endpoint2)
11700 struct mesh *m;
11701 struct behavior *b;
11702 struct otri *splittri;
11703 struct osub *splitsubseg;
11704 vertex endpoint2;
11705 #endif /* not ANSI_DECLARATORS */
11706 
11707 {
11708   struct osub opposubseg;
11709   vertex endpoint1;
11710   vertex torg, tdest;
11711   vertex leftvertex, rightvertex;
11712   vertex newvertex;
11713   enum insertvertexresult success;
11714   enum finddirectionresult collinear;
11715   REAL ex, ey;
11716   REAL tx, ty;
11717   REAL etx, ety;
11718   REAL split, denom;
11719   int i;
11720   triangle ptr;                       /* Temporary variable used by onext(). */
11721   subseg sptr;                        /* Temporary variable used by snext(). */
11722 
11723   /* Find the other three segment endpoints. */
11724   apex(*splittri, endpoint1);
11725   org(*splittri, torg);
11726   dest(*splittri, tdest);
11727   /* Segment intersection formulae; see the Antonio reference. */
11728   tx = tdest[0] - torg[0];
11729   ty = tdest[1] - torg[1];
11730   ex = endpoint2[0] - endpoint1[0];
11731   ey = endpoint2[1] - endpoint1[1];
11732   etx = torg[0] - endpoint2[0];
11733   ety = torg[1] - endpoint2[1];
11734   denom = ty * ex - tx * ey;
11735   if (denom == 0.0) {
11736     printf("Internal error in segmentintersection():");
11737     printf("  Attempt to find intersection of parallel segments.\n");
11738     internalerror();
11739   }
11740   split = (ey * etx - ex * ety) / denom;
11741   /* Create the new vertex. */
11742   newvertex = (vertex) poolalloc(&m->vertices);
11743   /* Interpolate its coordinate and attributes. */
11744   for (i = 0; i < 2 + m->nextras; i++) {
11745     newvertex[i] = torg[i] + split * (tdest[i] - torg[i]);
11746   }
11747   setvertexmark(newvertex, mark(*splitsubseg));
11748   setvertextype(newvertex, INPUTVERTEX);
11749   if (b->verbose > 1) {
11750     printf(
11751   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
11752            torg[0], torg[1], tdest[0], tdest[1], newvertex[0], newvertex[1]);
11753   }
11754   /* Insert the intersection vertex.  This should always succeed. */
11755   success = insertvertex(m, b, newvertex, splittri, splitsubseg, 0, 0);
11756   if (success != SUCCESSFULVERTEX) {
11757     printf("Internal error in segmentintersection():\n");
11758     printf("  Failure to split a segment.\n");
11759     internalerror();
11760   }
11761   /* Record a triangle whose origin is the new vertex. */
11762   setvertex2tri(newvertex, encode(*splittri));
11763   if (m->steinerleft > 0) {
11764     m->steinerleft--;
11765   }
11766 
11767   /* Divide the segment into two, and correct the segment endpoints. */
11768   ssymself(*splitsubseg);
11769   spivot(*splitsubseg, opposubseg);
11770   sdissolve(*splitsubseg);
11771   sdissolve(opposubseg);
11772   do {
11773     setsegorg(*splitsubseg, newvertex);
11774     snextself(*splitsubseg);
11775   } while (splitsubseg->ss != m->dummysub);
11776   do {
11777     setsegorg(opposubseg, newvertex);
11778     snextself(opposubseg);
11779   } while (opposubseg.ss != m->dummysub);
11780 
11781   /* Inserting the vertex may have caused edge flips.  We wish to rediscover */
11782   /*   the edge connecting endpoint1 to the new intersection vertex.         */
11783   collinear = finddirection(m, b, splittri, endpoint1);
11784   dest(*splittri, rightvertex);
11785   apex(*splittri, leftvertex);
11786   if ((leftvertex[0] == endpoint1[0]) && (leftvertex[1] == endpoint1[1])) {
11787     onextself(*splittri);
11788   } else if ((rightvertex[0] != endpoint1[0]) ||
11789              (rightvertex[1] != endpoint1[1])) {
11790     printf("Internal error in segmentintersection():\n");
11791     printf("  Topological inconsistency after splitting a segment.\n");
11792     internalerror();
11793   }
11794   /* `splittri' should have destination endpoint1. */
11795 }
11796 
11797 /*****************************************************************************/
11798 /*                                                                           */
11799 /*  scoutsegment()   Scout the first triangle on the path from one endpoint  */
11800 /*                   to another, and check for completion (reaching the      */
11801 /*                   second endpoint), a collinear vertex, or the            */
11802 /*                   intersection of two segments.                           */
11803 /*                                                                           */
11804 /*  Returns one if the entire segment is successfully inserted, and zero if  */
11805 /*  the job must be finished by conformingedge() or constrainededge().       */
11806 /*                                                                           */
11807 /*  If the first triangle on the path has the second endpoint as its         */
11808 /*  destination or apex, a subsegment is inserted and the job is done.       */
11809 /*                                                                           */
11810 /*  If the first triangle on the path has a destination or apex that lies on */
11811 /*  the segment, a subsegment is inserted connecting the first endpoint to   */
11812 /*  the collinear vertex, and the search is continued from the collinear     */
11813 /*  vertex.                                                                  */
11814 /*                                                                           */
11815 /*  If the first triangle on the path has a subsegment opposite its origin,  */
11816 /*  then there is a segment that intersects the segment being inserted.      */
11817 /*  Their intersection vertex is inserted, splitting the subsegment.         */
11818 /*                                                                           */
11819 /*****************************************************************************/
11820 
11821 #ifdef ANSI_DECLARATORS
11822 int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
11823                  vertex endpoint2, int newmark)
11824 #else /* not ANSI_DECLARATORS */
11825 int scoutsegment(m, b, searchtri, endpoint2, newmark)
11826 struct mesh *m;
11827 struct behavior *b;
11828 struct otri *searchtri;
11829 vertex endpoint2;
11830 int newmark;
11831 #endif /* not ANSI_DECLARATORS */
11832 
11833 {
11834   struct otri crosstri;
11835   struct osub crosssubseg;
11836   vertex leftvertex, rightvertex;
11837   enum finddirectionresult collinear;
11838   subseg sptr;                      /* Temporary variable used by tspivot(). */
11839 
11840   collinear = finddirection(m, b, searchtri, endpoint2);
11841   dest(*searchtri, rightvertex);
11842   apex(*searchtri, leftvertex);
11843   if (((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) ||
11844       ((rightvertex[0] == endpoint2[0]) && (rightvertex[1] == endpoint2[1]))) {
11845     /* The segment is already an edge in the mesh. */
11846     if ((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) {
11847       lprevself(*searchtri);
11848     }
11849     /* Insert a subsegment, if there isn't already one there. */
11850     insertsubseg(m, b, searchtri, newmark);
11851     return 1;
11852   } else if (collinear == LEFTCOLLINEAR) {
11853     /* We've collided with a vertex between the segment's endpoints. */
11854     /* Make the collinear vertex be the triangle's origin. */
11855     lprevself(*searchtri);
11856     insertsubseg(m, b, searchtri, newmark);
11857     /* Insert the remainder of the segment. */
11858     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11859   } else if (collinear == RIGHTCOLLINEAR) {
11860     /* We've collided with a vertex between the segment's endpoints. */
11861     insertsubseg(m, b, searchtri, newmark);
11862     /* Make the collinear vertex be the triangle's origin. */
11863     lnextself(*searchtri);
11864     /* Insert the remainder of the segment. */
11865     return scoutsegment(m, b, searchtri, endpoint2, newmark);
11866   } else {
11867     lnext(*searchtri, crosstri);
11868     tspivot(crosstri, crosssubseg);
11869     /* Check for a crossing segment. */
11870     if (crosssubseg.ss == m->dummysub) {
11871       return 0;
11872     } else {
11873       /* Insert a vertex at the intersection. */
11874       segmentintersection(m, b, &crosstri, &crosssubseg, endpoint2);
11875       otricopy(crosstri, *searchtri);
11876       insertsubseg(m, b, searchtri, newmark);
11877       /* Insert the remainder of the segment. */
11878       return scoutsegment(m, b, searchtri, endpoint2, newmark);
11879     }
11880   }
11881 }
11882 
11883 /*****************************************************************************/
11884 /*                                                                           */
11885 /*  conformingedge()   Force a segment into a conforming Delaunay            */
11886 /*                     triangulation by inserting a vertex at its midpoint,  */
11887 /*                     and recursively forcing in the two half-segments if   */
11888 /*                     necessary.                                            */
11889 /*                                                                           */
11890 /*  Generates a sequence of subsegments connecting `endpoint1' to            */
11891 /*  `endpoint2'.  `newmark' is the boundary marker of the segment, assigned  */
11892 /*  to each new splitting vertex and subsegment.                             */
11893 /*                                                                           */
11894 /*  Note that conformingedge() does not always maintain the conforming       */
11895 /*  Delaunay property.  Once inserted, segments are locked into place;       */
11896 /*  vertices inserted later (to force other segments in) may render these    */
11897 /*  fixed segments non-Delaunay.  The conforming Delaunay property will be   */
11898 /*  restored by enforcequality() by splitting encroached subsegments.        */
11899 /*                                                                           */
11900 /*****************************************************************************/
11901 
11902 #ifndef REDUCED
11903 #ifndef CDT_ONLY
11904 
11905 #ifdef ANSI_DECLARATORS
11906 void conformingedge(struct mesh *m, struct behavior *b,
11907                     vertex endpoint1, vertex endpoint2, int newmark)
11908 #else /* not ANSI_DECLARATORS */
11909 void conformingedge(m, b, endpoint1, endpoint2, newmark)
11910 struct mesh *m;
11911 struct behavior *b;
11912 vertex endpoint1;
11913 vertex endpoint2;
11914 int newmark;
11915 #endif /* not ANSI_DECLARATORS */
11916 
11917 {
11918   struct otri searchtri1, searchtri2;
11919   struct osub brokensubseg;
11920   vertex newvertex;
11921   vertex midvertex1, midvertex2;
11922   enum insertvertexresult success;
11923   int i;
11924   subseg sptr;                      /* Temporary variable used by tspivot(). */
11925 
11926   if (b->verbose > 2) {
11927     printf("Forcing segment into triangulation by recursive splitting:\n");
11928     printf("  (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
11929            endpoint2[0], endpoint2[1]);
11930   }
11931   /* Create a new vertex to insert in the middle of the segment. */
11932   newvertex = (vertex) poolalloc(&m->vertices);
11933   /* Interpolate coordinates and attributes. */
11934   for (i = 0; i < 2 + m->nextras; i++) {
11935     newvertex[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
11936   }
11937   setvertexmark(newvertex, newmark);
11938   setvertextype(newvertex, SEGMENTVERTEX);
11939   /* No known triangle to search from. */
11940   searchtri1.tri = m->dummytri;
11941   /* Attempt to insert the new vertex. */
11942   success = insertvertex(m, b, newvertex, &searchtri1, (struct osub *) NULL,
11943                          0, 0);
11944   if (success == DUPLICATEVERTEX) {
11945     if (b->verbose > 2) {
11946       printf("  Segment intersects existing vertex (%.12g, %.12g).\n",
11947              newvertex[0], newvertex[1]);
11948     }
11949     /* Use the vertex that's already there. */
11950     vertexdealloc(m, newvertex);
11951     org(searchtri1, newvertex);
11952   } else {
11953     if (success == VIOLATINGVERTEX) {
11954       if (b->verbose > 2) {
11955         printf("  Two segments intersect at (%.12g, %.12g).\n",
11956                newvertex[0], newvertex[1]);
11957       }
11958       /* By fluke, we've landed right on another segment.  Split it. */
11959       tspivot(searchtri1, brokensubseg);
11960       success = insertvertex(m, b, newvertex, &searchtri1, &brokensubseg,
11961                              0, 0);
11962       if (success != SUCCESSFULVERTEX) {
11963         printf("Internal error in conformingedge():\n");
11964         printf("  Failure to split a segment.\n");
11965         internalerror();
11966       }
11967     }
11968     /* The vertex has been inserted successfully. */
11969     if (m->steinerleft > 0) {
11970       m->steinerleft--;
11971     }
11972   }
11973   otricopy(searchtri1, searchtri2);
11974   /* `searchtri1' and `searchtri2' are fastened at their origins to         */
11975   /*   `newvertex', and will be directed toward `endpoint1' and `endpoint2' */
11976   /*   respectively.  First, we must get `searchtri2' out of the way so it  */
11977   /*   won't be invalidated during the insertion of the first half of the   */
11978   /*   segment.                                                             */
11979   finddirection(m, b, &searchtri2, endpoint2);
11980   if (!scoutsegment(m, b, &searchtri1, endpoint1, newmark)) {
11981     /* The origin of searchtri1 may have changed if a collision with an */
11982     /*   intervening vertex on the segment occurred.                    */
11983     org(searchtri1, midvertex1);
11984     conformingedge(m, b, midvertex1, endpoint1, newmark);
11985   }
11986   if (!scoutsegment(m, b, &searchtri2, endpoint2, newmark)) {
11987     /* The origin of searchtri2 may have changed if a collision with an */
11988     /*   intervening vertex on the segment occurred.                    */
11989     org(searchtri2, midvertex2);
11990     conformingedge(m, b, midvertex2, endpoint2, newmark);
11991   }
11992 }
11993 
11994 #endif /* not CDT_ONLY */
11995 #endif /* not REDUCED */
11996 
11997 /*****************************************************************************/
11998 /*                                                                           */
11999 /*  delaunayfixup()   Enforce the Delaunay condition at an edge, fanning out */
12000 /*                    recursively from an existing vertex.  Pay special      */
12001 /*                    attention to stacking inverted triangles.              */
12002 /*                                                                           */
12003 /*  This is a support routine for inserting segments into a constrained      */
12004 /*  Delaunay triangulation.                                                  */
12005 /*                                                                           */
12006 /*  The origin of fixuptri is treated as if it has just been inserted, and   */
12007 /*  the local Delaunay condition needs to be enforced.  It is only enforced  */
12008 /*  in one sector, however, that being the angular range defined by          */
12009 /*  fixuptri.                                                                */
12010 /*                                                                           */
12011 /*  This routine also needs to make decisions regarding the "stacking" of    */
12012 /*  triangles.  (Read the description of constrainededge() below before      */
12013 /*  reading on here, so you understand the algorithm.)  If the position of   */
12014 /*  the new vertex (the origin of fixuptri) indicates that the vertex before */
12015 /*  it on the polygon is a reflex vertex, then "stack" the triangle by       */
12016 /*  doing nothing.  (fixuptri is an inverted triangle, which is how stacked  */
12017 /*  triangles are identified.)                                               */
12018 /*                                                                           */
12019 /*  Otherwise, check whether the vertex before that was a reflex vertex.     */
12020 /*  If so, perform an edge flip, thereby eliminating an inverted triangle    */
12021 /*  (popping it off the stack).  The edge flip may result in the creation    */
12022 /*  of a new inverted triangle, depending on whether or not the new vertex   */
12023 /*  is visible to the vertex three edges behind on the polygon.              */
12024 /*                                                                           */
12025 /*  If neither of the two vertices behind the new vertex are reflex          */
12026 /*  vertices, fixuptri and fartri, the triangle opposite it, are not         */
12027 /*  inverted; hence, ensure that the edge between them is locally Delaunay.  */
12028 /*                                                                           */
12029 /*  `leftside' indicates whether or not fixuptri is to the left of the       */
12030 /*  segment being inserted.  (Imagine that the segment is pointing up from   */
12031 /*  endpoint1 to endpoint2.)                                                 */
12032 /*                                                                           */
12033 /*****************************************************************************/
12034 
12035 #ifdef ANSI_DECLARATORS
12036 void delaunayfixup(struct mesh *m, struct behavior *b,
12037                    struct otri *fixuptri, int leftside)
12038 #else /* not ANSI_DECLARATORS */
12039 void delaunayfixup(m, b, fixuptri, leftside)
12040 struct mesh *m;
12041 struct behavior *b;
12042 struct otri *fixuptri;
12043 int leftside;
12044 #endif /* not ANSI_DECLARATORS */
12045 
12046 {
12047   struct otri neartri;
12048   struct otri fartri;
12049   struct osub faredge;
12050   vertex nearvertex, leftvertex, rightvertex, farvertex;
12051   triangle ptr;                         /* Temporary variable used by sym(). */
12052   subseg sptr;                      /* Temporary variable used by tspivot(). */
12053 
12054   lnext(*fixuptri, neartri);
12055   sym(neartri, fartri);
12056   /* Check if the edge opposite the origin of fixuptri can be flipped. */
12057   if (fartri.tri == m->dummytri) {
12058     return;
12059   }
12060   tspivot(neartri, faredge);
12061   if (faredge.ss != m->dummysub) {
12062     return;
12063   }
12064   /* Find all the relevant vertices. */
12065   apex(neartri, nearvertex);
12066   org(neartri, leftvertex);
12067   dest(neartri, rightvertex);
12068   apex(fartri, farvertex);
12069   /* Check whether the previous polygon vertex is a reflex vertex. */
12070   if (leftside) {
12071     if (counterclockwise(m, b, nearvertex, leftvertex, farvertex) <= 0.0) {
12072       /* leftvertex is a reflex vertex too.  Nothing can */
12073       /*   be done until a convex section is found.      */
12074       return;
12075     }
12076   } else {
12077     if (counterclockwise(m, b, farvertex, rightvertex, nearvertex) <= 0.0) {
12078       /* rightvertex is a reflex vertex too.  Nothing can */
12079       /*   be done until a convex section is found.       */
12080       return;
12081     }
12082   }
12083   if (counterclockwise(m, b, rightvertex, leftvertex, farvertex) > 0.0) {
12084     /* fartri is not an inverted triangle, and farvertex is not a reflex */
12085     /*   vertex.  As there are no reflex vertices, fixuptri isn't an     */
12086     /*   inverted triangle, either.  Hence, test the edge between the    */
12087     /*   triangles to ensure it is locally Delaunay.                     */
12088     if (incircle(m, b, leftvertex, farvertex, rightvertex, nearvertex) <=
12089         0.0) {
12090       return;
12091     }
12092     /* Not locally Delaunay; go on to an edge flip. */
12093   }        /* else fartri is inverted; remove it from the stack by flipping. */
12094   flip(m, b, &neartri);
12095   lprevself(*fixuptri);    /* Restore the origin of fixuptri after the flip. */
12096   /* Recursively process the two triangles that result from the flip. */
12097   delaunayfixup(m, b, fixuptri, leftside);
12098   delaunayfixup(m, b, &fartri, leftside);
12099 }
12100 
12101 /*****************************************************************************/
12102 /*                                                                           */
12103 /*  constrainededge()   Force a segment into a constrained Delaunay          */
12104 /*                      triangulation by deleting the triangles it           */
12105 /*                      intersects, and triangulating the polygons that      */
12106 /*                      form on each side of it.                             */
12107 /*                                                                           */
12108 /*  Generates a single subsegment connecting `endpoint1' to `endpoint2'.     */
12109 /*  The triangle `starttri' has `endpoint1' as its origin.  `newmark' is the */
12110 /*  boundary marker of the segment.                                          */
12111 /*                                                                           */
12112 /*  To insert a segment, every triangle whose interior intersects the        */
12113 /*  segment is deleted.  The union of these deleted triangles is a polygon   */
12114 /*  (which is not necessarily monotone, but is close enough), which is       */
12115 /*  divided into two polygons by the new segment.  This routine's task is    */
12116 /*  to generate the Delaunay triangulation of these two polygons.            */
12117 /*                                                                           */
12118 /*  You might think of this routine's behavior as a two-step process.  The   */
12119 /*  first step is to walk from endpoint1 to endpoint2, flipping each edge    */
12120 /*  encountered.  This step creates a fan of edges connected to endpoint1,   */
12121 /*  including the desired edge to endpoint2.  The second step enforces the   */
12122 /*  Delaunay condition on each side of the segment in an incremental manner: */
12123 /*  proceeding along the polygon from endpoint1 to endpoint2 (this is done   */
12124 /*  independently on each side of the segment), each vertex is "enforced"    */
12125 /*  as if it had just been inserted, but affecting only the previous         */
12126 /*  vertices.  The result is the same as if the vertices had been inserted   */
12127 /*  in the order they appear on the polygon, so the result is Delaunay.      */
12128 /*                                                                           */
12129 /*  In truth, constrainededge() interleaves these two steps.  The procedure  */
12130 /*  walks from endpoint1 to endpoint2, and each time an edge is encountered  */
12131 /*  and flipped, the newly exposed vertex (at the far end of the flipped     */
12132 /*  edge) is "enforced" upon the previously flipped edges, usually affecting */
12133 /*  only one side of the polygon (depending upon which side of the segment   */
12134 /*  the vertex falls on).                                                    */
12135 /*                                                                           */
12136 /*  The algorithm is complicated by the need to handle polygons that are not */
12137 /*  convex.  Although the polygon is not necessarily monotone, it can be     */
12138 /*  triangulated in a manner similar to the stack-based algorithms for       */
12139 /*  monotone polygons.  For each reflex vertex (local concavity) of the      */
12140 /*  polygon, there will be an inverted triangle formed by one of the edge    */
12141 /*  flips.  (An inverted triangle is one with negative area - that is, its   */
12142 /*  vertices are arranged in clockwise order - and is best thought of as a   */
12143 /*  wrinkle in the fabric of the mesh.)  Each inverted triangle can be       */
12144 /*  thought of as a reflex vertex pushed on the stack, waiting to be fixed   */
12145 /*  later.                                                                   */
12146 /*                                                                           */
12147 /*  A reflex vertex is popped from the stack when a vertex is inserted that  */
12148 /*  is visible to the reflex vertex.  (However, if the vertex behind the     */
12149 /*  reflex vertex is not visible to the reflex vertex, a new inverted        */
12150 /*  triangle will take its place on the stack.)  These details are handled   */
12151 /*  by the delaunayfixup() routine above.                                    */
12152 /*                                                                           */
12153 /*****************************************************************************/
12154 
12155 #ifdef ANSI_DECLARATORS
12156 void constrainededge(struct mesh *m, struct behavior *b,
12157                      struct otri *starttri, vertex endpoint2, int newmark)
12158 #else /* not ANSI_DECLARATORS */
12159 void constrainededge(m, b, starttri, endpoint2, newmark)
12160 struct mesh *m;
12161 struct behavior *b;
12162 struct otri *starttri;
12163 vertex endpoint2;
12164 int newmark;
12165 #endif /* not ANSI_DECLARATORS */
12166 
12167 {
12168   struct otri fixuptri, fixuptri2;
12169   struct osub crosssubseg;
12170   vertex endpoint1;
12171   vertex farvertex;
12172   REAL area;
12173   int collision;
12174   int done;
12175   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12176   subseg sptr;                      /* Temporary variable used by tspivot(). */
12177 
12178   org(*starttri, endpoint1);
12179   lnext(*starttri, fixuptri);
12180   flip(m, b, &fixuptri);
12181   /* `collision' indicates whether we have found a vertex directly */
12182   /*   between endpoint1 and endpoint2.                            */
12183   collision = 0;
12184   done = 0;
12185   do {
12186     org(fixuptri, farvertex);
12187     /* `farvertex' is the extreme point of the polygon we are "digging" */
12188     /*   to get from endpoint1 to endpoint2.                           */
12189     if ((farvertex[0] == endpoint2[0]) && (farvertex[1] == endpoint2[1])) {
12190       oprev(fixuptri, fixuptri2);
12191       /* Enforce the Delaunay condition around endpoint2. */
12192       delaunayfixup(m, b, &fixuptri, 0);
12193       delaunayfixup(m, b, &fixuptri2, 1);
12194       done = 1;
12195     } else {
12196       /* Check whether farvertex is to the left or right of the segment */
12197       /*   being inserted, to decide which edge of fixuptri to dig      */
12198       /*   through next.                                                */
12199       area = counterclockwise(m, b, endpoint1, endpoint2, farvertex);
12200       if (area == 0.0) {
12201         /* We've collided with a vertex between endpoint1 and endpoint2. */
12202         collision = 1;
12203         oprev(fixuptri, fixuptri2);
12204         /* Enforce the Delaunay condition around farvertex. */
12205         delaunayfixup(m, b, &fixuptri, 0);
12206         delaunayfixup(m, b, &fixuptri2, 1);
12207         done = 1;
12208       } else {
12209         if (area > 0.0) {        /* farvertex is to the left of the segment. */
12210           oprev(fixuptri, fixuptri2);
12211           /* Enforce the Delaunay condition around farvertex, on the */
12212           /*   left side of the segment only.                        */
12213           delaunayfixup(m, b, &fixuptri2, 1);
12214           /* Flip the edge that crosses the segment.  After the edge is */
12215           /*   flipped, one of its endpoints is the fan vertex, and the */
12216           /*   destination of fixuptri is the fan vertex.               */
12217           lprevself(fixuptri);
12218         } else {                /* farvertex is to the right of the segment. */
12219           delaunayfixup(m, b, &fixuptri, 0);
12220           /* Flip the edge that crosses the segment.  After the edge is */
12221           /*   flipped, one of its endpoints is the fan vertex, and the */
12222           /*   destination of fixuptri is the fan vertex.               */
12223           oprevself(fixuptri);
12224         }
12225         /* Check for two intersecting segments. */
12226         tspivot(fixuptri, crosssubseg);
12227         if (crosssubseg.ss == m->dummysub) {
12228           flip(m, b, &fixuptri);    /* May create inverted triangle at left. */
12229         } else {
12230           /* We've collided with a segment between endpoint1 and endpoint2. */
12231           collision = 1;
12232           /* Insert a vertex at the intersection. */
12233           segmentintersection(m, b, &fixuptri, &crosssubseg, endpoint2);
12234           done = 1;
12235         }
12236       }
12237     }
12238   } while (!done);
12239   /* Insert a subsegment to make the segment permanent. */
12240   insertsubseg(m, b, &fixuptri, newmark);
12241   /* If there was a collision with an interceding vertex, install another */
12242   /*   segment connecting that vertex with endpoint2.                     */
12243   if (collision) {
12244     /* Insert the remainder of the segment. */
12245     if (!scoutsegment(m, b, &fixuptri, endpoint2, newmark)) {
12246       constrainededge(m, b, &fixuptri, endpoint2, newmark);
12247     }
12248   }
12249 }
12250 
12251 /*****************************************************************************/
12252 /*                                                                           */
12253 /*  insertsegment()   Insert a PSLG segment into a triangulation.            */
12254 /*                                                                           */
12255 /*****************************************************************************/
12256 
12257 #ifdef ANSI_DECLARATORS
12258 void insertsegment(struct mesh *m, struct behavior *b,
12259                    vertex endpoint1, vertex endpoint2, int newmark)
12260 #else /* not ANSI_DECLARATORS */
12261 void insertsegment(m, b, endpoint1, endpoint2, newmark)
12262 struct mesh *m;
12263 struct behavior *b;
12264 vertex endpoint1;
12265 vertex endpoint2;
12266 int newmark;
12267 #endif /* not ANSI_DECLARATORS */
12268 
12269 {
12270   struct otri searchtri1, searchtri2;
12271   triangle encodedtri;
12272   vertex checkvertex;
12273   triangle ptr;                         /* Temporary variable used by sym(). */
12274 
12275   if (b->verbose > 1) {
12276     printf("  Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
12277            endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
12278   }
12279 
12280   /* Find a triangle whose origin is the segment's first endpoint. */
12281   checkvertex = (vertex) NULL;
12282   encodedtri = vertex2tri(endpoint1);
12283   if (encodedtri != (triangle) NULL) {
12284     decode(encodedtri, searchtri1);
12285     org(searchtri1, checkvertex);
12286   }
12287   if (checkvertex != endpoint1) {
12288     /* Find a boundary triangle to search from. */
12289     searchtri1.tri = m->dummytri;
12290     searchtri1.orient = 0;
12291     symself(searchtri1);
12292     /* Search for the segment's first endpoint by point location. */
12293     if (locate(m, b, endpoint1, &searchtri1) != ONVERTEX) {
12294       printf(
12295         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12296       printf("  (%.12g, %.12g) in triangulation.\n",
12297              endpoint1[0], endpoint1[1]);
12298       internalerror();
12299     }
12300   }
12301   /* Remember this triangle to improve subsequent point location. */
12302   otricopy(searchtri1, m->recenttri);
12303   /* Scout the beginnings of a path from the first endpoint */
12304   /*   toward the second.                                   */
12305   if (scoutsegment(m, b, &searchtri1, endpoint2, newmark)) {
12306     /* The segment was easily inserted. */
12307     return;
12308   }
12309   /* The first endpoint may have changed if a collision with an intervening */
12310   /*   vertex on the segment occurred.                                      */
12311   org(searchtri1, endpoint1);
12312 
12313   /* Find a triangle whose origin is the segment's second endpoint. */
12314   checkvertex = (vertex) NULL;
12315   encodedtri = vertex2tri(endpoint2);
12316   if (encodedtri != (triangle) NULL) {
12317     decode(encodedtri, searchtri2);
12318     org(searchtri2, checkvertex);
12319   }
12320   if (checkvertex != endpoint2) {
12321     /* Find a boundary triangle to search from. */
12322     searchtri2.tri = m->dummytri;
12323     searchtri2.orient = 0;
12324     symself(searchtri2);
12325     /* Search for the segment's second endpoint by point location. */
12326     if (locate(m, b, endpoint2, &searchtri2) != ONVERTEX) {
12327       printf(
12328         "Internal error in insertsegment():  Unable to locate PSLG vertex\n");
12329       printf("  (%.12g, %.12g) in triangulation.\n",
12330              endpoint2[0], endpoint2[1]);
12331       internalerror();
12332     }
12333   }
12334   /* Remember this triangle to improve subsequent point location. */
12335   otricopy(searchtri2, m->recenttri);
12336   /* Scout the beginnings of a path from the second endpoint */
12337   /*   toward the first.                                     */
12338   if (scoutsegment(m, b, &searchtri2, endpoint1, newmark)) {
12339     /* The segment was easily inserted. */
12340     return;
12341   }
12342   /* The second endpoint may have changed if a collision with an intervening */
12343   /*   vertex on the segment occurred.                                       */
12344   org(searchtri2, endpoint2);
12345 
12346 #ifndef REDUCED
12347 #ifndef CDT_ONLY
12348   if (b->splitseg) {
12349     /* Insert vertices to force the segment into the triangulation. */
12350     conformingedge(m, b, endpoint1, endpoint2, newmark);
12351   } else {
12352 #endif /* not CDT_ONLY */
12353 #endif /* not REDUCED */
12354     /* Insert the segment directly into the triangulation. */
12355     constrainededge(m, b, &searchtri1, endpoint2, newmark);
12356 #ifndef REDUCED
12357 #ifndef CDT_ONLY
12358   }
12359 #endif /* not CDT_ONLY */
12360 #endif /* not REDUCED */
12361 }
12362 
12363 /*****************************************************************************/
12364 /*                                                                           */
12365 /*  markhull()   Cover the convex hull of a triangulation with subsegments.  */
12366 /*                                                                           */
12367 /*****************************************************************************/
12368 
12369 #ifdef ANSI_DECLARATORS
12370 void markhull(struct mesh *m, struct behavior *b)
12371 #else /* not ANSI_DECLARATORS */
12372 void markhull(m, b)
12373 struct mesh *m;
12374 struct behavior *b;
12375 #endif /* not ANSI_DECLARATORS */
12376 
12377 {
12378   struct otri hulltri;
12379   struct otri nexttri;
12380   struct otri starttri;
12381   triangle ptr;             /* Temporary variable used by sym() and oprev(). */
12382 
12383   /* Find a triangle handle on the hull. */
12384   hulltri.tri = m->dummytri;
12385   hulltri.orient = 0;
12386   symself(hulltri);
12387   /* Remember where we started so we know when to stop. */
12388   otricopy(hulltri, starttri);
12389   /* Go once counterclockwise around the convex hull. */
12390   do {
12391     /* Create a subsegment if there isn't already one here. */
12392     insertsubseg(m, b, &hulltri, 1);
12393     /* To find the next hull edge, go clockwise around the next vertex. */
12394     lnextself(hulltri);
12395     oprev(hulltri, nexttri);
12396     while (nexttri.tri != m->dummytri) {
12397       otricopy(nexttri, hulltri);
12398       oprev(hulltri, nexttri);
12399     }
12400   } while (!otriequal(hulltri, starttri));
12401 }
12402 
12403 /*****************************************************************************/
12404 /*                                                                           */
12405 /*  formskeleton()   Create the segments of a triangulation, including PSLG  */
12406 /*                   segments and edges on the convex hull.                  */
12407 /*                                                                           */
12408 /*  The PSLG segments are read from a .poly file.  The return value is the   */
12409 /*  number of segments in the file.                                          */
12410 /*                                                                           */
12411 /*****************************************************************************/
12412 
12413 #ifdef TRILIBRARY
12414 
12415 #ifdef ANSI_DECLARATORS
12416 void formskeleton(struct mesh *m, struct behavior *b, int *segmentlist,
12417                   int *segmentmarkerlist, int numberofsegments)
12418 #else /* not ANSI_DECLARATORS */
12419 void formskeleton(m, b, segmentlist, segmentmarkerlist, numberofsegments)
12420 struct mesh *m;
12421 struct behavior *b;
12422 int *segmentlist;
12423 int *segmentmarkerlist;
12424 int numberofsegments;
12425 #endif /* not ANSI_DECLARATORS */
12426 
12427 #else /* not TRILIBRARY */
12428 
12429 #ifdef ANSI_DECLARATORS
12430 void formskeleton(struct mesh *m, struct behavior *b,
12431                   FILE *polyfile, char *polyfilename)
12432 #else /* not ANSI_DECLARATORS */
12433 void formskeleton(m, b, polyfile, polyfilename)
12434 struct mesh *m;
12435 struct behavior *b;
12436 FILE *polyfile;
12437 char *polyfilename;
12438 #endif /* not ANSI_DECLARATORS */
12439 
12440 #endif /* not TRILIBRARY */
12441 
12442 {
12443 #ifdef TRILIBRARY
12444   char polyfilename[6];
12445   int index;
12446 #else /* not TRILIBRARY */
12447   char inputline[INPUTLINESIZE];
12448   char *stringptr;
12449 #endif /* not TRILIBRARY */
12450   vertex endpoint1, endpoint2;
12451   int segmentmarkers;
12452   int end1, end2;
12453   int boundmarker;
12454   int i;
12455 
12456   if (b->poly) {
12457     if (!b->quiet) {
12458       printf("Recovering segments in Delaunay triangulation.\n");
12459     }
12460 #ifdef TRILIBRARY
12461     strcpy(polyfilename, "input");
12462     m->insegments = numberofsegments;
12463     segmentmarkers = segmentmarkerlist != (int *) NULL;
12464     index = 0;
12465 #else /* not TRILIBRARY */
12466     /* Read the segments from a .poly file. */
12467     /* Read number of segments and number of boundary markers. */
12468     stringptr = readline(inputline, polyfile, polyfilename);
12469     m->insegments = (int) strtol(stringptr, &stringptr, 0);
12470     stringptr = findfield(stringptr);
12471     if (*stringptr == '\0') {
12472       segmentmarkers = 0;
12473     } else {
12474       segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
12475     }
12476 #endif /* not TRILIBRARY */
12477     /* If the input vertices are collinear, there is no triangulation, */
12478     /*   so don't try to insert segments.                              */
12479     if (m->triangles.items == 0) {
12480       return;
12481     }
12482 
12483     /* If segments are to be inserted, compute a mapping */
12484     /*   from vertices to triangles.                     */
12485     if (m->insegments > 0) {
12486       makevertexmap(m, b);
12487       if (b->verbose) {
12488         printf("  Recovering PSLG segments.\n");
12489       }
12490     }
12491 
12492     boundmarker = 0;
12493     /* Read and insert the segments. */
12494     for (i = 0; i < m->insegments; i++) {
12495 #ifdef TRILIBRARY
12496       end1 = segmentlist[index++];
12497       end2 = segmentlist[index++];
12498       if (segmentmarkers) {
12499         boundmarker = segmentmarkerlist[i];
12500       }
12501 #else /* not TRILIBRARY */
12502       stringptr = readline(inputline, polyfile, b->inpolyfilename);
12503       stringptr = findfield(stringptr);
12504       if (*stringptr == '\0') {
12505         printf("Error:  Segment %d has no endpoints in %s.\n",
12506                b->firstnumber + i, polyfilename);
12507         triexit(1);
12508       } else {
12509         end1 = (int) strtol(stringptr, &stringptr, 0);
12510       }
12511       stringptr = findfield(stringptr);
12512       if (*stringptr == '\0') {
12513         printf("Error:  Segment %d is missing its second endpoint in %s.\n",
12514                b->firstnumber + i, polyfilename);
12515         triexit(1);
12516       } else {
12517         end2 = (int) strtol(stringptr, &stringptr, 0);
12518       }
12519       if (segmentmarkers) {
12520         stringptr = findfield(stringptr);
12521         if (*stringptr == '\0') {
12522           boundmarker = 0;
12523         } else {
12524           boundmarker = (int) strtol(stringptr, &stringptr, 0);
12525         }
12526       }
12527 #endif /* not TRILIBRARY */
12528       if ((end1 < b->firstnumber) ||
12529           (end1 >= b->firstnumber + m->invertices)) {
12530         if (!b->quiet) {
12531           printf("Warning:  Invalid first endpoint of segment %d in %s.\n",
12532                  b->firstnumber + i, polyfilename);
12533         }
12534       } else if ((end2 < b->firstnumber) ||
12535                  (end2 >= b->firstnumber + m->invertices)) {
12536         if (!b->quiet) {
12537           printf("Warning:  Invalid second endpoint of segment %d in %s.\n",
12538                  b->firstnumber + i, polyfilename);
12539         }
12540       } else {
12541         /* Find the vertices numbered `end1' and `end2'. */
12542         endpoint1 = getvertex(m, b, end1);
12543         endpoint2 = getvertex(m, b, end2);
12544         if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
12545           if (!b->quiet) {
12546             printf("Warning:  Endpoints of segment %d are coincident in %s.\n",
12547                    b->firstnumber + i, polyfilename);
12548           }
12549         } else {
12550           insertsegment(m, b, endpoint1, endpoint2, boundmarker);
12551         }
12552       }
12553     }
12554   } else {
12555     m->insegments = 0;
12556   }
12557   if (b->convex || !b->poly) {
12558     /* Enclose the convex hull with subsegments. */
12559     if (b->verbose) {
12560       printf("  Enclosing convex hull with segments.\n");
12561     }
12562     markhull(m, b);
12563   }
12564 }
12565 
12566 /**                                                                         **/
12567 /**                                                                         **/
12568 /********* Segment insertion ends here                               *********/
12569 
12570 /********* Carving out holes and concavities begins here             *********/
12571 /**                                                                         **/
12572 /**                                                                         **/
12573 
12574 /*****************************************************************************/
12575 /*                                                                           */
12576 /*  infecthull()   Virally infect all of the triangles of the convex hull    */
12577 /*                 that are not protected by subsegments.  Where there are   */
12578 /*                 subsegments, set boundary markers as appropriate.         */
12579 /*                                                                           */
12580 /*****************************************************************************/
12581 
12582 #ifdef ANSI_DECLARATORS
12583 void infecthull(struct mesh *m, struct behavior *b)
12584 #else /* not ANSI_DECLARATORS */
12585 void infecthull(m, b)
12586 struct mesh *m;
12587 struct behavior *b;
12588 #endif /* not ANSI_DECLARATORS */
12589 
12590 {
12591   struct otri hulltri;
12592   struct otri nexttri;
12593   struct otri starttri;
12594   struct osub hullsubseg;
12595   triangle **deadtriangle;
12596   vertex horg, hdest;
12597   triangle ptr;                         /* Temporary variable used by sym(). */
12598   subseg sptr;                      /* Temporary variable used by tspivot(). */
12599 
12600   if (b->verbose) {
12601     printf("  Marking concavities (external triangles) for elimination.\n");
12602   }
12603   /* Find a triangle handle on the hull. */
12604   hulltri.tri = m->dummytri;
12605   hulltri.orient = 0;
12606   symself(hulltri);
12607   /* Remember where we started so we know when to stop. */
12608   otricopy(hulltri, starttri);
12609   /* Go once counterclockwise around the convex hull. */
12610   do {
12611     /* Ignore triangles that are already infected. */
12612     if (!infected(hulltri)) {
12613       /* Is the triangle protected by a subsegment? */
12614       tspivot(hulltri, hullsubseg);
12615       if (hullsubseg.ss == m->dummysub) {
12616         /* The triangle is not protected; infect it. */
12617         if (!infected(hulltri)) {
12618           infect(hulltri);
12619           deadtriangle = (triangle **) poolalloc(&m->viri);
12620           *deadtriangle = hulltri.tri;
12621         }
12622       } else {
12623         /* The triangle is protected; set boundary markers if appropriate. */
12624         if (mark(hullsubseg) == 0) {
12625           setmark(hullsubseg, 1);
12626           org(hulltri, horg);
12627           dest(hulltri, hdest);
12628           if (vertexmark(horg) == 0) {
12629             setvertexmark(horg, 1);
12630           }
12631           if (vertexmark(hdest) == 0) {
12632             setvertexmark(hdest, 1);
12633           }
12634         }
12635       }
12636     }
12637     /* To find the next hull edge, go clockwise around the next vertex. */
12638     lnextself(hulltri);
12639     oprev(hulltri, nexttri);
12640     while (nexttri.tri != m->dummytri) {
12641       otricopy(nexttri, hulltri);
12642       oprev(hulltri, nexttri);
12643     }
12644   } while (!otriequal(hulltri, starttri));
12645 }
12646 
12647 /*****************************************************************************/
12648 /*                                                                           */
12649 /*  plague()   Spread the virus from all infected triangles to any neighbors */
12650 /*             not protected by subsegments.  Delete all infected triangles. */
12651 /*                                                                           */
12652 /*  This is the procedure that actually creates holes and concavities.       */
12653 /*                                                                           */
12654 /*  This procedure operates in two phases.  The first phase identifies all   */
12655 /*  the triangles that will die, and marks them as infected.  They are       */
12656 /*  marked to ensure that each triangle is added to the virus pool only      */
12657 /*  once, so the procedure will terminate.                                   */
12658 /*                                                                           */
12659 /*  The second phase actually eliminates the infected triangles.  It also    */
12660 /*  eliminates orphaned vertices.                                            */
12661 /*                                                                           */
12662 /*****************************************************************************/
12663 
12664 #ifdef ANSI_DECLARATORS
12665 void plague(struct mesh *m, struct behavior *b)
12666 #else /* not ANSI_DECLARATORS */
12667 void plague(m, b)
12668 struct mesh *m;
12669 struct behavior *b;
12670 #endif /* not ANSI_DECLARATORS */
12671 
12672 {
12673   struct otri testtri;
12674   struct otri neighbor;
12675   triangle **virusloop;
12676   triangle **deadtriangle;
12677   struct osub neighborsubseg;
12678   vertex testvertex;
12679   vertex norg, ndest;
12680   vertex deadorg, deaddest, deadapex;
12681   int killorg;
12682   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12683   subseg sptr;                      /* Temporary variable used by tspivot(). */
12684 
12685   if (b->verbose) {
12686     printf("  Marking neighbors of marked triangles.\n");
12687   }
12688   /* Loop through all the infected triangles, spreading the virus to */
12689   /*   their neighbors, then to their neighbors' neighbors.          */
12690   traversalinit(&m->viri);
12691   virusloop = (triangle **) traverse(&m->viri);
12692   while (virusloop != (triangle **) NULL) {
12693     testtri.tri = *virusloop;
12694     /* A triangle is marked as infected by messing with one of its pointers */
12695     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12696     /*   temporarily uninfect this triangle so that we can examine its      */
12697     /*   adjacent subsegments.                                              */
12698     uninfect(testtri);
12699     if (b->verbose > 2) {
12700       /* Assign the triangle an orientation for convenience in */
12701       /*   checking its vertices.                              */
12702       testtri.orient = 0;
12703       org(testtri, deadorg);
12704       dest(testtri, deaddest);
12705       apex(testtri, deadapex);
12706       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12707              deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12708              deadapex[0], deadapex[1]);
12709     }
12710     /* Check each of the triangle's three neighbors. */
12711     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12712       /* Find the neighbor. */
12713       sym(testtri, neighbor);
12714       /* Check for a subsegment between the triangle and its neighbor. */
12715       tspivot(testtri, neighborsubseg);
12716       /* Check if the neighbor is nonexistent or already infected. */
12717       if ((neighbor.tri == m->dummytri) || infected(neighbor)) {
12718         if (neighborsubseg.ss != m->dummysub) {
12719           /* There is a subsegment separating the triangle from its      */
12720           /*   neighbor, but both triangles are dying, so the subsegment */
12721           /*   dies too.                                                 */
12722           subsegdealloc(m, neighborsubseg.ss);
12723           if (neighbor.tri != m->dummytri) {
12724             /* Make sure the subsegment doesn't get deallocated again */
12725             /*   later when the infected neighbor is visited.         */
12726             uninfect(neighbor);
12727             tsdissolve(neighbor);
12728             infect(neighbor);
12729           }
12730         }
12731       } else {                   /* The neighbor exists and is not infected. */
12732         if (neighborsubseg.ss == m->dummysub) {
12733           /* There is no subsegment protecting the neighbor, so */
12734           /*   the neighbor becomes infected.                   */
12735           if (b->verbose > 2) {
12736             org(neighbor, deadorg);
12737             dest(neighbor, deaddest);
12738             apex(neighbor, deadapex);
12739             printf(
12740               "    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12741                    deadorg[0], deadorg[1], deaddest[0], deaddest[1],
12742                    deadapex[0], deadapex[1]);
12743           }
12744           infect(neighbor);
12745           /* Ensure that the neighbor's neighbors will be infected. */
12746           deadtriangle = (triangle **) poolalloc(&m->viri);
12747           *deadtriangle = neighbor.tri;
12748         } else {               /* The neighbor is protected by a subsegment. */
12749           /* Remove this triangle from the subsegment. */
12750           stdissolve(neighborsubseg);
12751           /* The subsegment becomes a boundary.  Set markers accordingly. */
12752           if (mark(neighborsubseg) == 0) {
12753             setmark(neighborsubseg, 1);
12754           }
12755           org(neighbor, norg);
12756           dest(neighbor, ndest);
12757           if (vertexmark(norg) == 0) {
12758             setvertexmark(norg, 1);
12759           }
12760           if (vertexmark(ndest) == 0) {
12761             setvertexmark(ndest, 1);
12762           }
12763         }
12764       }
12765     }
12766     /* Remark the triangle as infected, so it doesn't get added to the */
12767     /*   virus pool again.                                             */
12768     infect(testtri);
12769     virusloop = (triangle **) traverse(&m->viri);
12770   }
12771 
12772   if (b->verbose) {
12773     printf("  Deleting marked triangles.\n");
12774   }
12775 
12776   traversalinit(&m->viri);
12777   virusloop = (triangle **) traverse(&m->viri);
12778   while (virusloop != (triangle **) NULL) {
12779     testtri.tri = *virusloop;
12780 
12781     /* Check each of the three corners of the triangle for elimination. */
12782     /*   This is done by walking around each vertex, checking if it is  */
12783     /*   still connected to at least one live triangle.                 */
12784     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12785       org(testtri, testvertex);
12786       /* Check if the vertex has already been tested. */
12787       if (testvertex != (vertex) NULL) {
12788         killorg = 1;
12789         /* Mark the corner of the triangle as having been tested. */
12790         setorg(testtri, NULL);
12791         /* Walk counterclockwise about the vertex. */
12792         onext(testtri, neighbor);
12793         /* Stop upon reaching a boundary or the starting triangle. */
12794         while ((neighbor.tri != m->dummytri) &&
12795                (!otriequal(neighbor, testtri))) {
12796           if (infected(neighbor)) {
12797             /* Mark the corner of this triangle as having been tested. */
12798             setorg(neighbor, NULL);
12799           } else {
12800             /* A live triangle.  The vertex survives. */
12801             killorg = 0;
12802           }
12803           /* Walk counterclockwise about the vertex. */
12804           onextself(neighbor);
12805         }
12806         /* If we reached a boundary, we must walk clockwise as well. */
12807         if (neighbor.tri == m->dummytri) {
12808           /* Walk clockwise about the vertex. */
12809           oprev(testtri, neighbor);
12810           /* Stop upon reaching a boundary. */
12811           while (neighbor.tri != m->dummytri) {
12812             if (infected(neighbor)) {
12813             /* Mark the corner of this triangle as having been tested. */
12814               setorg(neighbor, NULL);
12815             } else {
12816               /* A live triangle.  The vertex survives. */
12817               killorg = 0;
12818             }
12819             /* Walk clockwise about the vertex. */
12820             oprevself(neighbor);
12821           }
12822         }
12823         if (killorg) {
12824           if (b->verbose > 1) {
12825             printf("    Deleting vertex (%.12g, %.12g)\n",
12826                    testvertex[0], testvertex[1]);
12827           }
12828           setvertextype(testvertex, UNDEADVERTEX);
12829           m->undeads++;
12830         }
12831       }
12832     }
12833 
12834     /* Record changes in the number of boundary edges, and disconnect */
12835     /*   dead triangles from their neighbors.                         */
12836     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12837       sym(testtri, neighbor);
12838       if (neighbor.tri == m->dummytri) {
12839         /* There is no neighboring triangle on this edge, so this edge    */
12840         /*   is a boundary edge.  This triangle is being deleted, so this */
12841         /*   boundary edge is deleted.                                    */
12842         m->hullsize--;
12843       } else {
12844         /* Disconnect the triangle from its neighbor. */
12845         dissolve(neighbor);
12846         /* There is a neighboring triangle on this edge, so this edge */
12847         /*   becomes a boundary edge when this triangle is deleted.   */
12848         m->hullsize++;
12849       }
12850     }
12851     /* Return the dead triangle to the pool of triangles. */
12852     triangledealloc(m, testtri.tri);
12853     virusloop = (triangle **) traverse(&m->viri);
12854   }
12855   /* Empty the virus pool. */
12856   poolrestart(&m->viri);
12857 }
12858 
12859 /*****************************************************************************/
12860 /*                                                                           */
12861 /*  regionplague()   Spread regional attributes and/or area constraints      */
12862 /*                   (from a .poly file) throughout the mesh.                */
12863 /*                                                                           */
12864 /*  This procedure operates in two phases.  The first phase spreads an       */
12865 /*  attribute and/or an area constraint through a (segment-bounded) region.  */
12866 /*  The triangles are marked to ensure that each triangle is added to the    */
12867 /*  virus pool only once, so the procedure will terminate.                   */
12868 /*                                                                           */
12869 /*  The second phase uninfects all infected triangles, returning them to     */
12870 /*  normal.                                                                  */
12871 /*                                                                           */
12872 /*****************************************************************************/
12873 
12874 #ifdef ANSI_DECLARATORS
12875 void regionplague(struct mesh *m, struct behavior *b,
12876                   REAL attribute, REAL area)
12877 #else /* not ANSI_DECLARATORS */
12878 void regionplague(m, b, attribute, area)
12879 struct mesh *m;
12880 struct behavior *b;
12881 REAL attribute;
12882 REAL area;
12883 #endif /* not ANSI_DECLARATORS */
12884 
12885 {
12886   struct otri testtri;
12887   struct otri neighbor;
12888   triangle **virusloop;
12889   triangle **regiontri;
12890   struct osub neighborsubseg;
12891   vertex regionorg, regiondest, regionapex;
12892   triangle ptr;             /* Temporary variable used by sym() and onext(). */
12893   subseg sptr;                      /* Temporary variable used by tspivot(). */
12894 
12895   if (b->verbose > 1) {
12896     printf("  Marking neighbors of marked triangles.\n");
12897   }
12898   /* Loop through all the infected triangles, spreading the attribute      */
12899   /*   and/or area constraint to their neighbors, then to their neighbors' */
12900   /*   neighbors.                                                          */
12901   traversalinit(&m->viri);
12902   virusloop = (triangle **) traverse(&m->viri);
12903   while (virusloop != (triangle **) NULL) {
12904     testtri.tri = *virusloop;
12905     /* A triangle is marked as infected by messing with one of its pointers */
12906     /*   to subsegments, setting it to an illegal value.  Hence, we have to */
12907     /*   temporarily uninfect this triangle so that we can examine its      */
12908     /*   adjacent subsegments.                                              */
12909     uninfect(testtri);
12910     if (b->regionattrib) {
12911       /* Set an attribute. */
12912       setelemattribute(testtri, m->eextras, attribute);
12913     }
12914     if (b->vararea) {
12915       /* Set an area constraint. */
12916       setareabound(testtri, area);
12917     }
12918     if (b->verbose > 2) {
12919       /* Assign the triangle an orientation for convenience in */
12920       /*   checking its vertices.                              */
12921       testtri.orient = 0;
12922       org(testtri, regionorg);
12923       dest(testtri, regiondest);
12924       apex(testtri, regionapex);
12925       printf("    Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12926              regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12927              regionapex[0], regionapex[1]);
12928     }
12929     /* Check each of the triangle's three neighbors. */
12930     for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
12931       /* Find the neighbor. */
12932       sym(testtri, neighbor);
12933       /* Check for a subsegment between the triangle and its neighbor. */
12934       tspivot(testtri, neighborsubseg);
12935       /* Make sure the neighbor exists, is not already infected, and */
12936       /*   isn't protected by a subsegment.                          */
12937       if ((neighbor.tri != m->dummytri) && !infected(neighbor)
12938           && (neighborsubseg.ss == m->dummysub)) {
12939         if (b->verbose > 2) {
12940           org(neighbor, regionorg);
12941           dest(neighbor, regiondest);
12942           apex(neighbor, regionapex);
12943           printf("    Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
12944                  regionorg[0], regionorg[1], regiondest[0], regiondest[1],
12945                  regionapex[0], regionapex[1]);
12946         }
12947         /* Infect the neighbor. */
12948         infect(neighbor);
12949         /* Ensure that the neighbor's neighbors will be infected. */
12950         regiontri = (triangle **) poolalloc(&m->viri);
12951         *regiontri = neighbor.tri;
12952       }
12953     }
12954     /* Remark the triangle as infected, so it doesn't get added to the */
12955     /*   virus pool again.                                             */
12956     infect(testtri);
12957     virusloop = (triangle **) traverse(&m->viri);
12958   }
12959 
12960   /* Uninfect all triangles. */
12961   if (b->verbose > 1) {
12962     printf("  Unmarking marked triangles.\n");
12963   }
12964   traversalinit(&m->viri);
12965   virusloop = (triangle **) traverse(&m->viri);
12966   while (virusloop != (triangle **) NULL) {
12967     testtri.tri = *virusloop;
12968     uninfect(testtri);
12969     virusloop = (triangle **) traverse(&m->viri);
12970   }
12971   /* Empty the virus pool. */
12972   poolrestart(&m->viri);
12973 }
12974 
12975 /*****************************************************************************/
12976 /*                                                                           */
12977 /*  carveholes()   Find the holes and infect them.  Find the area            */
12978 /*                 constraints and infect them.  Infect the convex hull.     */
12979 /*                 Spread the infection and kill triangles.  Spread the      */
12980 /*                 area constraints.                                         */
12981 /*                                                                           */
12982 /*  This routine mainly calls other routines to carry out all these          */
12983 /*  functions.                                                               */
12984 /*                                                                           */
12985 /*****************************************************************************/
12986 
12987 #ifdef ANSI_DECLARATORS
12988 void carveholes(struct mesh *m, struct behavior *b, REAL *holelist, int holes,
12989                 REAL *regionlist, int regions)
12990 #else /* not ANSI_DECLARATORS */
12991 void carveholes(m, b, holelist, holes, regionlist, regions)
12992 struct mesh *m;
12993 struct behavior *b;
12994 REAL *holelist;
12995 int holes;
12996 REAL *regionlist;
12997 int regions;
12998 #endif /* not ANSI_DECLARATORS */
12999 
13000 {
13001   struct otri searchtri;
13002   struct otri triangleloop;
13003   struct otri *regiontris;
13004   triangle **holetri;
13005   triangle **regiontri;
13006   vertex searchorg, searchdest;
13007   enum locateresult intersect;
13008   int i;
13009   triangle ptr;                         /* Temporary variable used by sym(). */
13010 
13011   if (!(b->quiet || (b->noholes && b->convex))) {
13012     printf("Removing unwanted triangles.\n");
13013     if (b->verbose && (holes > 0)) {
13014       printf("  Marking holes for elimination.\n");
13015     }
13016   }
13017 
13018   if (regions > 0) {
13019     /* Allocate storage for the triangles in which region points fall. */
13020     regiontris = (struct otri *) trimalloc(regions *
13021                                            (int) sizeof(struct otri));
13022   } else {
13023     regiontris = (struct otri *) NULL;
13024   }
13025 
13026   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13027     /* Initialize a pool of viri to be used for holes, concavities, */
13028     /*   regional attributes, and/or regional area constraints.     */
13029     poolinit(&m->viri, sizeof(triangle *), VIRUSPERBLOCK, VIRUSPERBLOCK, 0);
13030   }
13031 
13032   if (!b->convex) {
13033     /* Mark as infected any unprotected triangles on the boundary. */
13034     /*   This is one way by which concavities are created.         */
13035     infecthull(m, b);
13036   }
13037 
13038   if ((holes > 0) && !b->noholes) {
13039     /* Infect each triangle in which a hole lies. */
13040     for (i = 0; i < 2 * holes; i += 2) {
13041       /* Ignore holes that aren't within the bounds of the mesh. */
13042       if ((holelist[i] >= m->xmin) && (holelist[i] <= m->xmax)
13043           && (holelist[i + 1] >= m->ymin) && (holelist[i + 1] <= m->ymax)) {
13044         /* Start searching from some triangle on the outer boundary. */
13045         searchtri.tri = m->dummytri;
13046         searchtri.orient = 0;
13047         symself(searchtri);
13048         /* Ensure that the hole is to the left of this boundary edge; */
13049         /*   otherwise, locate() will falsely report that the hole    */
13050         /*   falls within the starting triangle.                      */
13051         org(searchtri, searchorg);
13052         dest(searchtri, searchdest);
13053         if (counterclockwise(m, b, searchorg, searchdest, &holelist[i]) >
13054             0.0) {
13055           /* Find a triangle that contains the hole. */
13056           intersect = locate(m, b, &holelist[i], &searchtri);
13057           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13058             /* Infect the triangle.  This is done by marking the triangle  */
13059             /*   as infected and including the triangle in the virus pool. */
13060             infect(searchtri);
13061             holetri = (triangle **) poolalloc(&m->viri);
13062             *holetri = searchtri.tri;
13063           }
13064         }
13065       }
13066     }
13067   }
13068 
13069   /* Now, we have to find all the regions BEFORE we carve the holes, because */
13070   /*   locate() won't work when the triangulation is no longer convex.       */
13071   /*   (Incidentally, this is the reason why regional attributes and area    */
13072   /*   constraints can't be used when refining a preexisting mesh, which     */
13073   /*   might not be convex; they can only be used with a freshly             */
13074   /*   triangulated PSLG.)                                                   */
13075   if (regions > 0) {
13076     /* Find the starting triangle for each region. */
13077     for (i = 0; i < regions; i++) {
13078       regiontris[i].tri = m->dummytri;
13079       /* Ignore region points that aren't within the bounds of the mesh. */
13080       if ((regionlist[4 * i] >= m->xmin) && (regionlist[4 * i] <= m->xmax) &&
13081           (regionlist[4 * i + 1] >= m->ymin) &&
13082           (regionlist[4 * i + 1] <= m->ymax)) {
13083         /* Start searching from some triangle on the outer boundary. */
13084         searchtri.tri = m->dummytri;
13085         searchtri.orient = 0;
13086         symself(searchtri);
13087         /* Ensure that the region point is to the left of this boundary */
13088         /*   edge; otherwise, locate() will falsely report that the     */
13089         /*   region point falls within the starting triangle.           */
13090         org(searchtri, searchorg);
13091         dest(searchtri, searchdest);
13092         if (counterclockwise(m, b, searchorg, searchdest, &regionlist[4 * i]) >
13093             0.0) {
13094           /* Find a triangle that contains the region point. */
13095           intersect = locate(m, b, &regionlist[4 * i], &searchtri);
13096           if ((intersect != OUTSIDE) && (!infected(searchtri))) {
13097             /* Record the triangle for processing after the */
13098             /*   holes have been carved.                    */
13099             otricopy(searchtri, regiontris[i]);
13100           }
13101         }
13102       }
13103     }
13104   }
13105 
13106   if (m->viri.items > 0) {
13107     /* Carve the holes and concavities. */
13108     plague(m, b);
13109   }
13110   /* The virus pool should be empty now. */
13111 
13112   if (regions > 0) {
13113     if (!b->quiet) {
13114       if (b->regionattrib) {
13115         if (b->vararea) {
13116           printf("Spreading regional attributes and area constraints.\n");
13117         } else {
13118           printf("Spreading regional attributes.\n");
13119         }
13120       } else {
13121         printf("Spreading regional area constraints.\n");
13122       }
13123     }
13124     if (b->regionattrib && !b->refine) {
13125       /* Assign every triangle a regional attribute of zero. */
13126       traversalinit(&m->triangles);
13127       triangleloop.orient = 0;
13128       triangleloop.tri = triangletraverse(m);
13129       while (triangleloop.tri != (triangle *) NULL) {
13130         setelemattribute(triangleloop, m->eextras, 0.0);
13131         triangleloop.tri = triangletraverse(m);
13132       }
13133     }
13134     for (i = 0; i < regions; i++) {
13135       if (regiontris[i].tri != m->dummytri) {
13136         /* Make sure the triangle under consideration still exists. */
13137         /*   It may have been eaten by the virus.                   */
13138         if (!deadtri(regiontris[i].tri)) {
13139           /* Put one triangle in the virus pool. */
13140           infect(regiontris[i]);
13141           regiontri = (triangle **) poolalloc(&m->viri);
13142           *regiontri = regiontris[i].tri;
13143           /* Apply one region's attribute and/or area constraint. */
13144           regionplague(m, b, regionlist[4 * i + 2], regionlist[4 * i + 3]);
13145           /* The virus pool should be empty now. */
13146         }
13147       }
13148     }
13149     if (b->regionattrib && !b->refine) {
13150       /* Note the fact that each triangle has an additional attribute. */
13151       m->eextras++;
13152     }
13153   }
13154 
13155   /* Free up memory. */
13156   if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
13157     pooldeinit(&m->viri);
13158   }
13159   if (regions > 0) {
13160     trifree((VOID *) regiontris);
13161   }
13162 }
13163 
13164 /**                                                                         **/
13165 /**                                                                         **/
13166 /********* Carving out holes and concavities ends here               *********/
13167 
13168 /********* Mesh quality maintenance begins here                      *********/
13169 /**                                                                         **/
13170 /**                                                                         **/
13171 
13172 /*****************************************************************************/
13173 /*                                                                           */
13174 /*  tallyencs()   Traverse the entire list of subsegments, and check each    */
13175 /*                to see if it is encroached.  If so, add it to the list.    */
13176 /*                                                                           */
13177 /*****************************************************************************/
13178 
13179 #ifndef CDT_ONLY
13180 
13181 #ifdef ANSI_DECLARATORS
13182 void tallyencs(struct mesh *m, struct behavior *b)
13183 #else /* not ANSI_DECLARATORS */
13184 void tallyencs(m, b)
13185 struct mesh *m;
13186 struct behavior *b;
13187 #endif /* not ANSI_DECLARATORS */
13188 
13189 {
13190   struct osub subsegloop;
13191   int dummy;
13192 
13193   traversalinit(&m->subsegs);
13194   subsegloop.ssorient = 0;
13195   subsegloop.ss = subsegtraverse(m);
13196   while (subsegloop.ss != (subseg *) NULL) {
13197     /* If the segment is encroached, add it to the list. */
13198     dummy = checkseg4encroach(m, b, &subsegloop);
13199     subsegloop.ss = subsegtraverse(m);
13200   }
13201 }
13202 
13203 #endif /* not CDT_ONLY */
13204 
13205 /*****************************************************************************/
13206 /*                                                                           */
13207 /*  precisionerror()  Print an error message for precision problems.         */
13208 /*                                                                           */
13209 /*****************************************************************************/
13210 
13211 #ifndef CDT_ONLY
13212 
13213 void precisionerror()
13214 {
13215   printf("Try increasing the area criterion and/or reducing the minimum\n");
13216   printf("  allowable angle so that tiny triangles are not created.\n");
13217 #ifdef SINGLE
13218   printf("Alternatively, try recompiling me with double precision\n");
13219   printf("  arithmetic (by removing \"#define SINGLE\" from the\n");
13220   printf("  source file or \"-DSINGLE\" from the makefile).\n");
13221 #endif /* SINGLE */
13222 }
13223 
13224 #endif /* not CDT_ONLY */
13225 
13226 /*****************************************************************************/
13227 /*                                                                           */
13228 /*  splitencsegs()   Split all the encroached subsegments.                   */
13229 /*                                                                           */
13230 /*  Each encroached subsegment is repaired by splitting it - inserting a     */
13231 /*  vertex at or near its midpoint.  Newly inserted vertices may encroach    */
13232 /*  upon other subsegments; these are also repaired.                         */
13233 /*                                                                           */
13234 /*  `triflaws' is a flag that specifies whether one should take note of new  */
13235 /*  bad triangles that result from inserting vertices to repair encroached   */
13236 /*  subsegments.                                                             */
13237 /*                                                                           */
13238 /*****************************************************************************/
13239 
13240 #ifndef CDT_ONLY
13241 
13242 #ifdef ANSI_DECLARATORS
13243 void splitencsegs(struct mesh *m, struct behavior *b, int triflaws)
13244 #else /* not ANSI_DECLARATORS */
13245 void splitencsegs(m, b, triflaws)
13246 struct mesh *m;
13247 struct behavior *b;
13248 int triflaws;
13249 #endif /* not ANSI_DECLARATORS */
13250 
13251 {
13252   struct otri enctri;
13253   struct otri testtri;
13254   struct osub testsh;
13255   struct osub currentenc;
13256   struct badsubseg *encloop;
13257   vertex eorg, edest, eapex;
13258   vertex newvertex;
13259   enum insertvertexresult success;
13260   REAL segmentlength, nearestpoweroftwo;
13261   REAL split;
13262   REAL multiplier, divisor;
13263   int acuteorg, acuteorg2, acutedest, acutedest2;
13264   int dummy;
13265   int i;
13266   triangle ptr;                     /* Temporary variable used by stpivot(). */
13267   subseg sptr;                        /* Temporary variable used by snext(). */
13268 
13269   /* Note that steinerleft == -1 if an unlimited number */
13270   /*   of Steiner points is allowed.                    */
13271   while ((m->badsubsegs.items > 0) && (m->steinerleft != 0)) {
13272     traversalinit(&m->badsubsegs);
13273     encloop = badsubsegtraverse(m);
13274     while ((encloop != (struct badsubseg *) NULL) && (m->steinerleft != 0)) {
13275       sdecode(encloop->encsubseg, currentenc);
13276       sorg(currentenc, eorg);
13277       sdest(currentenc, edest);
13278       /* Make sure that this segment is still the same segment it was   */
13279       /*   when it was determined to be encroached.  If the segment was */
13280       /*   enqueued multiple times (because several newly inserted      */
13281       /*   vertices encroached it), it may have already been split.     */
13282       if (!deadsubseg(currentenc.ss) &&
13283           (eorg == encloop->subsegorg) && (edest == encloop->subsegdest)) {
13284         /* To decide where to split a segment, we need to know if the   */
13285         /*   segment shares an endpoint with an adjacent segment.       */
13286         /*   The concern is that, if we simply split every encroached   */
13287         /*   segment in its center, two adjacent segments with a small  */
13288         /*   angle between them might lead to an infinite loop; each    */
13289         /*   vertex added to split one segment will encroach upon the   */
13290         /*   other segment, which must then be split with a vertex that */
13291         /*   will encroach upon the first segment, and so on forever.   */
13292         /* To avoid this, imagine a set of concentric circles, whose    */
13293         /*   radii are powers of two, about each segment endpoint.      */
13294         /*   These concentric circles determine where the segment is    */
13295         /*   split.  (If both endpoints are shared with adjacent        */
13296         /*   segments, split the segment in the middle, and apply the   */
13297         /*   concentric circles for later splittings.)                  */
13298 
13299         /* Is the origin shared with another segment? */
13300         stpivot(currentenc, enctri);
13301         lnext(enctri, testtri);
13302         tspivot(testtri, testsh);
13303         acuteorg = testsh.ss != m->dummysub;
13304         /* Is the destination shared with another segment? */
13305         lnextself(testtri);
13306         tspivot(testtri, testsh);
13307         acutedest = testsh.ss != m->dummysub;
13308 
13309         /* If we're using Chew's algorithm (rather than Ruppert's) */
13310         /*   to define encroachment, delete free vertices from the */
13311         /*   subsegment's diametral circle.                        */
13312         if (!b->conformdel && !acuteorg && !acutedest) {
13313           apex(enctri, eapex);
13314           while ((vertextype(eapex) == FREEVERTEX) &&
13315                  ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13316                   (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13317             deletevertex(m, b, &testtri);
13318             stpivot(currentenc, enctri);
13319             apex(enctri, eapex);
13320             lprev(enctri, testtri);
13321           }
13322         }
13323 
13324         /* Now, check the other side of the segment, if there's a triangle */
13325         /*   there.                                                        */
13326         sym(enctri, testtri);
13327         if (testtri.tri != m->dummytri) {
13328           /* Is the destination shared with another segment? */
13329           lnextself(testtri);
13330           tspivot(testtri, testsh);
13331           acutedest2 = testsh.ss != m->dummysub;
13332           acutedest = acutedest || acutedest2;
13333           /* Is the origin shared with another segment? */
13334           lnextself(testtri);
13335           tspivot(testtri, testsh);
13336           acuteorg2 = testsh.ss != m->dummysub;
13337           acuteorg = acuteorg || acuteorg2;
13338 
13339           /* Delete free vertices from the subsegment's diametral circle. */
13340           if (!b->conformdel && !acuteorg2 && !acutedest2) {
13341             org(testtri, eapex);
13342             while ((vertextype(eapex) == FREEVERTEX) &&
13343                    ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
13344                     (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
13345               deletevertex(m, b, &testtri);
13346               sym(enctri, testtri);
13347               apex(testtri, eapex);
13348               lprevself(testtri);
13349             }
13350           }
13351         }
13352 
13353         /* Use the concentric circles if exactly one endpoint is shared */
13354         /*   with another adjacent segment.                             */
13355         if (acuteorg || acutedest) {
13356           segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) +
13357                                (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
13358           /* Find the power of two that most evenly splits the segment.  */
13359           /*   The worst case is a 2:1 ratio between subsegment lengths. */
13360           nearestpoweroftwo = 1.0;
13361           while (segmentlength > 3.0 * nearestpoweroftwo) {
13362             nearestpoweroftwo *= 2.0;
13363           }
13364           while (segmentlength < 1.5 * nearestpoweroftwo) {
13365             nearestpoweroftwo *= 0.5;
13366           }
13367           /* Where do we split the segment? */
13368           split = nearestpoweroftwo / segmentlength;
13369           if (acutedest) {
13370             split = 1.0 - split;
13371           }
13372         } else {
13373           /* If we're not worried about adjacent segments, split */
13374           /*   this segment in the middle.                       */
13375           split = 0.5;
13376         }
13377 
13378         /* Create the new vertex. */
13379         newvertex = (vertex) poolalloc(&m->vertices);
13380         /* Interpolate its coordinate and attributes. */
13381         for (i = 0; i < 2 + m->nextras; i++) {
13382           newvertex[i] = eorg[i] + split * (edest[i] - eorg[i]);
13383         }
13384 
13385         if (!b->noexact) {
13386           /* Roundoff in the above calculation may yield a `newvertex'   */
13387           /*   that is not precisely collinear with `eorg' and `edest'.  */
13388           /*   Improve collinearity by one step of iterative refinement. */
13389           multiplier = counterclockwise(m, b, eorg, edest, newvertex);
13390           divisor = ((eorg[0] - edest[0]) * (eorg[0] - edest[0]) +
13391                      (eorg[1] - edest[1]) * (eorg[1] - edest[1]));
13392           if ((multiplier != 0.0) && (divisor != 0.0)) {
13393             multiplier = multiplier / divisor;
13394             /* Watch out for NANs. */
13395             if (multiplier == multiplier) {
13396               newvertex[0] += multiplier * (edest[1] - eorg[1]);
13397               newvertex[1] += multiplier * (eorg[0] - edest[0]);
13398             }
13399           }
13400         }
13401 
13402         setvertexmark(newvertex, mark(currentenc));
13403         setvertextype(newvertex, SEGMENTVERTEX);
13404         if (b->verbose > 1) {
13405           printf(
13406   "  Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
13407                  eorg[0], eorg[1], edest[0], edest[1],
13408                  newvertex[0], newvertex[1]);
13409         }
13410         /* Check whether the new vertex lies on an endpoint. */
13411         if (((newvertex[0] == eorg[0]) && (newvertex[1] == eorg[1])) ||
13412             ((newvertex[0] == edest[0]) && (newvertex[1] == edest[1]))) {
13413           printf("Error:  Ran out of precision at (%.12g, %.12g).\n",
13414                  newvertex[0], newvertex[1]);
13415           printf("I attempted to split a segment to a smaller size than\n");
13416           printf("  can be accommodated by the finite precision of\n");
13417           printf("  floating point arithmetic.\n");
13418           precisionerror();
13419           triexit(1);
13420         }
13421         /* Insert the splitting vertex.  This should always succeed. */
13422         success = insertvertex(m, b, newvertex, &enctri, &currentenc,
13423                                1, triflaws);
13424         if ((success != SUCCESSFULVERTEX) && (success != ENCROACHINGVERTEX)) {
13425           printf("Internal error in splitencsegs():\n");
13426           printf("  Failure to split a segment.\n");
13427           internalerror();
13428         }
13429         if (m->steinerleft > 0) {
13430           m->steinerleft--;
13431         }
13432         /* Check the two new subsegments to see if they're encroached. */
13433         dummy = checkseg4encroach(m, b, &currentenc);
13434         snextself(currentenc);
13435         dummy = checkseg4encroach(m, b, &currentenc);
13436       }
13437 
13438       badsubsegdealloc(m, encloop);
13439       encloop = badsubsegtraverse(m);
13440     }
13441   }
13442 }
13443 
13444 #endif /* not CDT_ONLY */
13445 
13446 /*****************************************************************************/
13447 /*                                                                           */
13448 /*  tallyfaces()   Test every triangle in the mesh for quality measures.     */
13449 /*                                                                           */
13450 /*****************************************************************************/
13451 
13452 #ifndef CDT_ONLY
13453 
13454 #ifdef ANSI_DECLARATORS
13455 void tallyfaces(struct mesh *m, struct behavior *b)
13456 #else /* not ANSI_DECLARATORS */
13457 void tallyfaces(m, b)
13458 struct mesh *m;
13459 struct behavior *b;
13460 #endif /* not ANSI_DECLARATORS */
13461 
13462 {
13463   struct otri triangleloop;
13464 
13465   if (b->verbose) {
13466     printf("  Making a list of bad triangles.\n");
13467   }
13468   traversalinit(&m->triangles);
13469   triangleloop.orient = 0;
13470   triangleloop.tri = triangletraverse(m);
13471   while (triangleloop.tri != (triangle *) NULL) {
13472     /* If the triangle is bad, enqueue it. */
13473     testtriangle(m, b, &triangleloop);
13474     triangleloop.tri = triangletraverse(m);
13475   }
13476 }
13477 
13478 #endif /* not CDT_ONLY */
13479 
13480 /*****************************************************************************/
13481 /*                                                                           */
13482 /*  splittriangle()   Inserts a vertex at the circumcenter of a triangle.    */
13483 /*                    Deletes the newly inserted vertex if it encroaches     */
13484 /*                    upon a segment.                                        */
13485 /*                                                                           */
13486 /*****************************************************************************/
13487 
13488 #ifndef CDT_ONLY
13489 
13490 #ifdef ANSI_DECLARATORS
13491 void splittriangle(struct mesh *m, struct behavior *b,
13492                    struct badtriang *badtri)
13493 #else /* not ANSI_DECLARATORS */
13494 void splittriangle(m, b, badtri)
13495 struct mesh *m;
13496 struct behavior *b;
13497 struct badtriang *badtri;
13498 #endif /* not ANSI_DECLARATORS */
13499 
13500 {
13501   struct otri badotri;
13502   vertex borg, bdest, bapex;
13503   vertex newvertex;
13504   REAL xi, eta;
13505   enum insertvertexresult success;
13506   int errorflag;
13507   int i;
13508 
13509   decode(badtri->poortri, badotri);
13510   org(badotri, borg);
13511   dest(badotri, bdest);
13512   apex(badotri, bapex);
13513   /* Make sure that this triangle is still the same triangle it was      */
13514   /*   when it was tested and determined to be of bad quality.           */
13515   /*   Subsequent transformations may have made it a different triangle. */
13516   if (!deadtri(badotri.tri) && (borg == badtri->triangorg) &&
13517       (bdest == badtri->triangdest) && (bapex == badtri->triangapex)) {
13518     if (b->verbose > 1) {
13519       printf("  Splitting this triangle at its circumcenter:\n");
13520       printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
13521              borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13522     }
13523 
13524     errorflag = 0;
13525     /* Create a new vertex at the triangle's circumcenter. */
13526     newvertex = (vertex) poolalloc(&m->vertices);
13527     findcircumcenter(m, b, borg, bdest, bapex, newvertex, &xi, &eta, 1);
13528 
13529     /* Check whether the new vertex lies on a triangle vertex. */
13530     if (((newvertex[0] == borg[0]) && (newvertex[1] == borg[1])) ||
13531         ((newvertex[0] == bdest[0]) && (newvertex[1] == bdest[1])) ||
13532         ((newvertex[0] == bapex[0]) && (newvertex[1] == bapex[1]))) {
13533       if (!b->quiet) {
13534         printf(
13535              "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13536                newvertex[0], newvertex[1]);
13537         errorflag = 1;
13538       }
13539       vertexdealloc(m, newvertex);
13540     } else {
13541       for (i = 2; i < 2 + m->nextras; i++) {
13542         /* Interpolate the vertex attributes at the circumcenter. */
13543         newvertex[i] = borg[i] + xi * (bdest[i] - borg[i])
13544                               + eta * (bapex[i] - borg[i]);
13545       }
13546       /* The new vertex must be in the interior, and therefore is a */
13547       /*   free vertex with a marker of zero.                       */
13548       setvertexmark(newvertex, 0);
13549       setvertextype(newvertex, FREEVERTEX);
13550 
13551       /* Ensure that the handle `badotri' does not represent the longest  */
13552       /*   edge of the triangle.  This ensures that the circumcenter must */
13553       /*   fall to the left of this edge, so point location will work.    */
13554       /*   (If the angle org-apex-dest exceeds 90 degrees, then the       */
13555       /*   circumcenter lies outside the org-dest edge, and eta is        */
13556       /*   negative.  Roundoff error might prevent eta from being         */
13557       /*   negative when it should be, so I test eta against xi.)         */
13558       if (eta < xi) {
13559         lprevself(badotri);
13560       }
13561 
13562       /* Insert the circumcenter, searching from the edge of the triangle, */
13563       /*   and maintain the Delaunay property of the triangulation.        */
13564       success = insertvertex(m, b, newvertex, &badotri, (struct osub *) NULL,
13565                              1, 1);
13566       if (success == SUCCESSFULVERTEX) {
13567         if (m->steinerleft > 0) {
13568           m->steinerleft--;
13569         }
13570       } else if (success == ENCROACHINGVERTEX) {
13571         /* If the newly inserted vertex encroaches upon a subsegment, */
13572         /*   delete the new vertex.                                   */
13573         undovertex(m, b);
13574         if (b->verbose > 1) {
13575           printf("  Rejecting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13576         }
13577         vertexdealloc(m, newvertex);
13578       } else if (success == VIOLATINGVERTEX) {
13579         /* Failed to insert the new vertex, but some subsegment was */
13580         /*   marked as being encroached.                            */
13581         vertexdealloc(m, newvertex);
13582       } else {                                 /* success == DUPLICATEVERTEX */
13583         /* Couldn't insert the new vertex because a vertex is already there. */
13584         if (!b->quiet) {
13585           printf(
13586             "Warning:  New vertex (%.12g, %.12g) falls on existing vertex.\n",
13587                  newvertex[0], newvertex[1]);
13588           errorflag = 1;
13589         }
13590         vertexdealloc(m, newvertex);
13591       }
13592     }
13593     if (errorflag) {
13594       if (b->verbose) {
13595         printf("  The new vertex is at the circumcenter of triangle\n");
13596         printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
13597                borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
13598       }
13599       printf("This probably means that I am trying to refine triangles\n");
13600       printf("  to a smaller size than can be accommodated by the finite\n");
13601       printf("  precision of floating point arithmetic.  (You can be\n");
13602       printf("  sure of this if I fail to terminate.)\n");
13603       precisionerror();
13604     }
13605   }
13606 }
13607 
13608 #endif /* not CDT_ONLY */
13609 
13610 /*****************************************************************************/
13611 /*                                                                           */
13612 /*  enforcequality()   Remove all the encroached subsegments and bad         */
13613 /*                     triangles from the triangulation.                     */
13614 /*                                                                           */
13615 /*****************************************************************************/
13616 
13617 #ifndef CDT_ONLY
13618 
13619 #ifdef ANSI_DECLARATORS
13620 void enforcequality(struct mesh *m, struct behavior *b)
13621 #else /* not ANSI_DECLARATORS */
13622 void enforcequality(m, b)
13623 struct mesh *m;
13624 struct behavior *b;
13625 #endif /* not ANSI_DECLARATORS */
13626 
13627 {
13628   struct badtriang *badtri;
13629   int i;
13630 
13631   if (!b->quiet) {
13632     printf("Adding Steiner points to enforce quality.\n");
13633   }
13634   /* Initialize the pool of encroached subsegments. */
13635   poolinit(&m->badsubsegs, sizeof(struct badsubseg), BADSUBSEGPERBLOCK,
13636            BADSUBSEGPERBLOCK, 0);
13637   if (b->verbose) {
13638     printf("  Looking for encroached subsegments.\n");
13639   }
13640   /* Test all segments to see if they're encroached. */
13641   tallyencs(m, b);
13642   if (b->verbose && (m->badsubsegs.items > 0)) {
13643     printf("  Splitting encroached subsegments.\n");
13644   }
13645   /* Fix encroached subsegments without noting bad triangles. */
13646   splitencsegs(m, b, 0);
13647   /* At this point, if we haven't run out of Steiner points, the */
13648   /*   triangulation should be (conforming) Delaunay.            */
13649 
13650   /* Next, we worry about enforcing triangle quality. */
13651   if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
13652     /* Initialize the pool of bad triangles. */
13653     poolinit(&m->badtriangles, sizeof(struct badtriang), BADTRIPERBLOCK,
13654              BADTRIPERBLOCK, 0);
13655     /* Initialize the queues of bad triangles. */
13656     for (i = 0; i < 4096; i++) {
13657       m->queuefront[i] = (struct badtriang *) NULL;
13658     }
13659     m->firstnonemptyq = -1;
13660     /* Test all triangles to see if they're bad. */
13661     tallyfaces(m, b);
13662     /* Initialize the pool of recently flipped triangles. */
13663     poolinit(&m->flipstackers, sizeof(struct flipstacker), FLIPSTACKERPERBLOCK,
13664              FLIPSTACKERPERBLOCK, 0);
13665     m->checkquality = 1;
13666     if (b->verbose) {
13667       printf("  Splitting bad triangles.\n");
13668     }
13669     while ((m->badtriangles.items > 0) && (m->steinerleft != 0)) {
13670       /* Fix one bad triangle by inserting a vertex at its circumcenter. */
13671       badtri = dequeuebadtriang(m);
13672       splittriangle(m, b, badtri);
13673       if (m->badsubsegs.items > 0) {
13674         /* Put bad triangle back in queue for another try later. */
13675         enqueuebadtriang(m, b, badtri);
13676         /* Fix any encroached subsegments that resulted. */
13677         /*   Record any new bad triangles that result.   */
13678         splitencsegs(m, b, 1);
13679       } else {
13680         /* Return the bad triangle to the pool. */
13681         pooldealloc(&m->badtriangles, (VOID *) badtri);
13682       }
13683     }
13684   }
13685   /* At this point, if the "-D" switch was selected and we haven't run out  */
13686   /*   of Steiner points, the triangulation should be (conforming) Delaunay */
13687   /*   and have no low-quality triangles.                                   */
13688 
13689   /* Might we have run out of Steiner points too soon? */
13690   if (!b->quiet && b->conformdel && (m->badsubsegs.items > 0) &&
13691       (m->steinerleft == 0)) {
13692     printf("\nWarning:  I ran out of Steiner points, but the mesh has\n");
13693     if (m->badsubsegs.items == 1) {
13694       printf("  one encroached subsegment, and therefore might not be truly\n"
13695              );
13696     } else {
13697       printf("  %ld encroached subsegments, and therefore might not be truly\n"
13698              , m->badsubsegs.items);
13699     }
13700     printf("  Delaunay.  If the Delaunay property is important to you,\n");
13701     printf("  try increasing the number of Steiner points (controlled by\n");
13702     printf("  the -S switch) slightly and try again.\n\n");
13703   }
13704 }
13705 
13706 #endif /* not CDT_ONLY */
13707 
13708 /**                                                                         **/
13709 /**                                                                         **/
13710 /********* Mesh quality maintenance ends here                        *********/
13711 
13712 /*****************************************************************************/
13713 /*                                                                           */
13714 /*  highorder()   Create extra nodes for quadratic subparametric elements.   */
13715 /*                                                                           */
13716 /*****************************************************************************/
13717 
13718 #ifdef ANSI_DECLARATORS
13719 void highorder(struct mesh *m, struct behavior *b)
13720 #else /* not ANSI_DECLARATORS */
13721 void highorder(m, b)
13722 struct mesh *m;
13723 struct behavior *b;
13724 #endif /* not ANSI_DECLARATORS */
13725 
13726 {
13727   struct otri triangleloop, trisym;
13728   struct osub checkmark;
13729   vertex newvertex;
13730   vertex torg, tdest;
13731   int i;
13732   triangle ptr;                         /* Temporary variable used by sym(). */
13733   subseg sptr;                      /* Temporary variable used by tspivot(). */
13734 
13735   if (!b->quiet) {
13736     printf("Adding vertices for second-order triangles.\n");
13737   }
13738   /* The following line ensures that dead items in the pool of nodes    */
13739   /*   cannot be allocated for the extra nodes associated with high     */
13740   /*   order elements.  This ensures that the primary nodes (at the     */
13741   /*   corners of elements) will occur earlier in the output files, and */
13742   /*   have lower indices, than the extra nodes.                        */
13743   m->vertices.deaditemstack = (VOID *) NULL;
13744 
13745   traversalinit(&m->triangles);
13746   triangleloop.tri = triangletraverse(m);
13747   /* To loop over the set of edges, loop over all triangles, and look at   */
13748   /*   the three edges of each triangle.  If there isn't another triangle  */
13749   /*   adjacent to the edge, operate on the edge.  If there is another     */
13750   /*   adjacent triangle, operate on the edge only if the current triangle */
13751   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
13752   /*   considered only once.                                               */
13753   while (triangleloop.tri != (triangle *) NULL) {
13754     for (triangleloop.orient = 0; triangleloop.orient < 3;
13755          triangleloop.orient++) {
13756       sym(triangleloop, trisym);
13757       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
13758         org(triangleloop, torg);
13759         dest(triangleloop, tdest);
13760         /* Create a new node in the middle of the edge.  Interpolate */
13761         /*   its attributes.                                         */
13762         newvertex = (vertex) poolalloc(&m->vertices);
13763         for (i = 0; i < 2 + m->nextras; i++) {
13764           newvertex[i] = 0.5 * (torg[i] + tdest[i]);
13765         }
13766         /* Set the new node's marker to zero or one, depending on */
13767         /*   whether it lies on a boundary.                       */
13768         setvertexmark(newvertex, trisym.tri == m->dummytri);
13769         setvertextype(newvertex,
13770                       trisym.tri == m->dummytri ? FREEVERTEX : SEGMENTVERTEX);
13771         if (b->usesegments) {
13772           tspivot(triangleloop, checkmark);
13773           /* If this edge is a segment, transfer the marker to the new node. */
13774           if (checkmark.ss != m->dummysub) {
13775             setvertexmark(newvertex, mark(checkmark));
13776             setvertextype(newvertex, SEGMENTVERTEX);
13777           }
13778         }
13779         if (b->verbose > 1) {
13780           printf("  Creating (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
13781         }
13782         /* Record the new node in the (one or two) adjacent elements. */
13783         triangleloop.tri[m->highorderindex + triangleloop.orient] =
13784                 (triangle) newvertex;
13785         if (trisym.tri != m->dummytri) {
13786           trisym.tri[m->highorderindex + trisym.orient] = (triangle) newvertex;
13787         }
13788       }
13789     }
13790     triangleloop.tri = triangletraverse(m);
13791   }
13792 }
13793 
13794 /********* File I/O routines begin here                              *********/
13795 /**                                                                         **/
13796 /**                                                                         **/
13797 
13798 /*****************************************************************************/
13799 /*                                                                           */
13800 /*  readline()   Read a nonempty line from a file.                           */
13801 /*                                                                           */
13802 /*  A line is considered "nonempty" if it contains something that looks like */
13803 /*  a number.  Comments (prefaced by `#') are ignored.                       */
13804 /*                                                                           */
13805 /*****************************************************************************/
13806 
13807 #ifndef TRILIBRARY
13808 
13809 #ifdef ANSI_DECLARATORS
13810 char *readline(char *string, FILE *infile, char *infilename)
13811 #else /* not ANSI_DECLARATORS */
13812 char *readline(string, infile, infilename)
13813 char *string;
13814 FILE *infile;
13815 char *infilename;
13816 #endif /* not ANSI_DECLARATORS */
13817 
13818 {
13819   char *result;
13820 
13821   /* Search for something that looks like a number. */
13822   do {
13823     result = fgets(string, INPUTLINESIZE, infile);
13824     if (result == (char *) NULL) {
13825       printf("  Error:  Unexpected end of file in %s.\n", infilename);
13826       triexit(1);
13827     }
13828     /* Skip anything that doesn't look like a number, a comment, */
13829     /*   or the end of a line.                                   */
13830     while ((*result != '\0') && (*result != '#')
13831            && (*result != '.') && (*result != '+') && (*result != '-')
13832            && ((*result < '0') || (*result > '9'))) {
13833       result++;
13834     }
13835   /* If it's a comment or end of line, read another line and try again. */
13836   } while ((*result == '#') || (*result == '\0'));
13837   return result;
13838 }
13839 
13840 #endif /* not TRILIBRARY */
13841 
13842 /*****************************************************************************/
13843 /*                                                                           */
13844 /*  findfield()   Find the next field of a string.                           */
13845 /*                                                                           */
13846 /*  Jumps past the current field by searching for whitespace, then jumps     */
13847 /*  past the whitespace to find the next field.                              */
13848 /*                                                                           */
13849 /*****************************************************************************/
13850 
13851 #ifndef TRILIBRARY
13852 
13853 #ifdef ANSI_DECLARATORS
13854 char *findfield(char *string)
13855 #else /* not ANSI_DECLARATORS */
13856 char *findfield(string)
13857 char *string;
13858 #endif /* not ANSI_DECLARATORS */
13859 
13860 {
13861   char *result;
13862 
13863   result = string;
13864   /* Skip the current field.  Stop upon reaching whitespace. */
13865   while ((*result != '\0') && (*result != '#')
13866          && (*result != ' ') && (*result != '\t')) {
13867     result++;
13868   }
13869   /* Now skip the whitespace and anything else that doesn't look like a */
13870   /*   number, a comment, or the end of a line.                         */
13871   while ((*result != '\0') && (*result != '#')
13872          && (*result != '.') && (*result != '+') && (*result != '-')
13873          && ((*result < '0') || (*result > '9'))) {
13874     result++;
13875   }
13876   /* Check for a comment (prefixed with `#'). */
13877   if (*result == '#') {
13878     *result = '\0';
13879   }
13880   return result;
13881 }
13882 
13883 #endif /* not TRILIBRARY */
13884 
13885 /*****************************************************************************/
13886 /*                                                                           */
13887 /*  readnodes()   Read the vertices from a file, which may be a .node or     */
13888 /*                .poly file.                                                */
13889 /*                                                                           */
13890 /*****************************************************************************/
13891 
13892 #ifndef TRILIBRARY
13893 
13894 #ifdef ANSI_DECLARATORS
13895 void readnodes(struct mesh *m, struct behavior *b, char *nodefilename,
13896                char *polyfilename, FILE **polyfile)
13897 #else /* not ANSI_DECLARATORS */
13898 void readnodes(m, b, nodefilename, polyfilename, polyfile)
13899 struct mesh *m;
13900 struct behavior *b;
13901 char *nodefilename;
13902 char *polyfilename;
13903 FILE **polyfile;
13904 #endif /* not ANSI_DECLARATORS */
13905 
13906 {
13907   FILE *infile;
13908   vertex vertexloop;
13909   char inputline[INPUTLINESIZE];
13910   char *stringptr;
13911   char *infilename;
13912   REAL x, y;
13913   int firstnode;
13914   int nodemarkers;
13915   int currentmarker;
13916   int i, j;
13917 
13918   if (b->poly) {
13919     /* Read the vertices from a .poly file. */
13920     if (!b->quiet) {
13921       printf("Opening %s.\n", polyfilename);
13922     }
13923     *polyfile = fopen(polyfilename, "r");
13924     if (*polyfile == (FILE *) NULL) {
13925       printf("  Error:  Cannot access file %s.\n", polyfilename);
13926       triexit(1);
13927     }
13928     /* Read number of vertices, number of dimensions, number of vertex */
13929     /*   attributes, and number of boundary markers.                   */
13930     stringptr = readline(inputline, *polyfile, polyfilename);
13931     m->invertices = (int) strtol(stringptr, &stringptr, 0);
13932     stringptr = findfield(stringptr);
13933     if (*stringptr == '\0') {
13934       m->mesh_dim = 2;
13935     } else {
13936       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
13937     }
13938     stringptr = findfield(stringptr);
13939     if (*stringptr == '\0') {
13940       m->nextras = 0;
13941     } else {
13942       m->nextras = (int) strtol(stringptr, &stringptr, 0);
13943     }
13944     stringptr = findfield(stringptr);
13945     if (*stringptr == '\0') {
13946       nodemarkers = 0;
13947     } else {
13948       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
13949     }
13950     if (m->invertices > 0) {
13951       infile = *polyfile;
13952       infilename = polyfilename;
13953       m->readnodefile = 0;
13954     } else {
13955       /* If the .poly file claims there are zero vertices, that means that */
13956       /*   the vertices should be read from a separate .node file.         */
13957       m->readnodefile = 1;
13958       infilename = nodefilename;
13959     }
13960   } else {
13961     m->readnodefile = 1;
13962     infilename = nodefilename;
13963     *polyfile = (FILE *) NULL;
13964   }
13965 
13966   if (m->readnodefile) {
13967     /* Read the vertices from a .node file. */
13968     if (!b->quiet) {
13969       printf("Opening %s.\n", nodefilename);
13970     }
13971     infile = fopen(nodefilename, "r");
13972     if (infile == (FILE *) NULL) {
13973       printf("  Error:  Cannot access file %s.\n", nodefilename);
13974       triexit(1);
13975     }
13976     /* Read number of vertices, number of dimensions, number of vertex */
13977     /*   attributes, and number of boundary markers.                   */
13978     stringptr = readline(inputline, infile, nodefilename);
13979     m->invertices = (int) strtol(stringptr, &stringptr, 0);
13980     stringptr = findfield(stringptr);
13981     if (*stringptr == '\0') {
13982       m->mesh_dim = 2;
13983     } else {
13984       m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
13985     }
13986     stringptr = findfield(stringptr);
13987     if (*stringptr == '\0') {
13988       m->nextras = 0;
13989     } else {
13990       m->nextras = (int) strtol(stringptr, &stringptr, 0);
13991     }
13992     stringptr = findfield(stringptr);
13993     if (*stringptr == '\0') {
13994       nodemarkers = 0;
13995     } else {
13996       nodemarkers = (int) strtol(stringptr, &stringptr, 0);
13997     }
13998   }
13999 
14000   if (m->invertices < 3) {
14001     printf("Error:  Input must have at least three input vertices.\n");
14002     triexit(1);
14003   }
14004   if (m->mesh_dim != 2) {
14005     printf("Error:  Triangle only works with two-dimensional meshes.\n");
14006     triexit(1);
14007   }
14008   if (m->nextras == 0) {
14009     b->weighted = 0;
14010   }
14011 
14012   initializevertexpool(m, b);
14013 
14014   /* Read the vertices. */
14015   for (i = 0; i < m->invertices; i++) {
14016     vertexloop = (vertex) poolalloc(&m->vertices);
14017     stringptr = readline(inputline, infile, infilename);
14018     if (i == 0) {
14019       firstnode = (int) strtol(stringptr, &stringptr, 0);
14020       if ((firstnode == 0) || (firstnode == 1)) {
14021         b->firstnumber = firstnode;
14022       }
14023     }
14024     stringptr = findfield(stringptr);
14025     if (*stringptr == '\0') {
14026       printf("Error:  Vertex %d has no x coordinate.\n", b->firstnumber + i);
14027       triexit(1);
14028     }
14029     x = (REAL) strtod(stringptr, &stringptr);
14030     stringptr = findfield(stringptr);
14031     if (*stringptr == '\0') {
14032       printf("Error:  Vertex %d has no y coordinate.\n", b->firstnumber + i);
14033       triexit(1);
14034     }
14035     y = (REAL) strtod(stringptr, &stringptr);
14036     vertexloop[0] = x;
14037     vertexloop[1] = y;
14038     /* Read the vertex attributes. */
14039     for (j = 2; j < 2 + m->nextras; j++) {
14040       stringptr = findfield(stringptr);
14041       if (*stringptr == '\0') {
14042         vertexloop[j] = 0.0;
14043       } else {
14044         vertexloop[j] = (REAL) strtod(stringptr, &stringptr);
14045       }
14046     }
14047     if (nodemarkers) {
14048       /* Read a vertex marker. */
14049       stringptr = findfield(stringptr);
14050       if (*stringptr == '\0') {
14051         setvertexmark(vertexloop, 0);
14052       } else {
14053         currentmarker = (int) strtol(stringptr, &stringptr, 0);
14054         setvertexmark(vertexloop, currentmarker);
14055       }
14056     } else {
14057       /* If no markers are specified in the file, they default to zero. */
14058       setvertexmark(vertexloop, 0);
14059     }
14060     setvertextype(vertexloop, INPUTVERTEX);
14061     /* Determine the smallest and largest x and y coordinates. */
14062     if (i == 0) {
14063       m->xmin = m->xmax = x;
14064       m->ymin = m->ymax = y;
14065     } else {
14066       m->xmin = (x < m->xmin) ? x : m->xmin;
14067       m->xmax = (x > m->xmax) ? x : m->xmax;
14068       m->ymin = (y < m->ymin) ? y : m->ymin;
14069       m->ymax = (y > m->ymax) ? y : m->ymax;
14070     }
14071   }
14072   if (m->readnodefile) {
14073     fclose(infile);
14074   }
14075 
14076   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14077   /*   Delaunay algorithm.                                                 */
14078   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14079 }
14080 
14081 #endif /* not TRILIBRARY */
14082 
14083 /*****************************************************************************/
14084 /*                                                                           */
14085 /*  transfernodes()   Read the vertices from memory.                         */
14086 /*                                                                           */
14087 /*****************************************************************************/
14088 
14089 #ifdef TRILIBRARY
14090 
14091 #ifdef ANSI_DECLARATORS
14092 void transfernodes(struct mesh *m, struct behavior *b, REAL *pointlist,
14093                    REAL *pointattriblist, int *pointmarkerlist,
14094                    int numberofpoints, int numberofpointattribs)
14095 #else /* not ANSI_DECLARATORS */
14096 void transfernodes(m, b, pointlist, pointattriblist, pointmarkerlist,
14097                    numberofpoints, numberofpointattribs)
14098 struct mesh *m;
14099 struct behavior *b;
14100 REAL *pointlist;
14101 REAL *pointattriblist;
14102 int *pointmarkerlist;
14103 int numberofpoints;
14104 int numberofpointattribs;
14105 #endif /* not ANSI_DECLARATORS */
14106 
14107 {
14108   vertex vertexloop;
14109   REAL x, y;
14110   int i, j;
14111   int coordindex;
14112   int attribindex;
14113 
14114   m->invertices = numberofpoints;
14115   m->mesh_dim = 2;
14116   m->nextras = numberofpointattribs;
14117   m->readnodefile = 0;
14118   if (m->invertices < 3) {
14119     printf("Error:  Input must have at least three input vertices.\n");
14120     triexit(1);
14121   }
14122   if (m->nextras == 0) {
14123     b->weighted = 0;
14124   }
14125 
14126   initializevertexpool(m, b);
14127 
14128   /* Read the vertices. */
14129   coordindex = 0;
14130   attribindex = 0;
14131   for (i = 0; i < m->invertices; i++) {
14132     vertexloop = (vertex) poolalloc(&m->vertices);
14133     /* Read the vertex coordinates. */
14134     x = vertexloop[0] = pointlist[coordindex++];
14135     y = vertexloop[1] = pointlist[coordindex++];
14136     /* Read the vertex attributes. */
14137     for (j = 0; j < numberofpointattribs; j++) {
14138       vertexloop[2 + j] = pointattriblist[attribindex++];
14139     }
14140     if (pointmarkerlist != (int *) NULL) {
14141       /* Read a vertex marker. */
14142       setvertexmark(vertexloop, pointmarkerlist[i]);
14143     } else {
14144       /* If no markers are specified, they default to zero. */
14145       setvertexmark(vertexloop, 0);
14146     }
14147     setvertextype(vertexloop, INPUTVERTEX);
14148     /* Determine the smallest and largest x and y coordinates. */
14149     if (i == 0) {
14150       m->xmin = m->xmax = x;
14151       m->ymin = m->ymax = y;
14152     } else {
14153       m->xmin = (x < m->xmin) ? x : m->xmin;
14154       m->xmax = (x > m->xmax) ? x : m->xmax;
14155       m->ymin = (y < m->ymin) ? y : m->ymin;
14156       m->ymax = (y > m->ymax) ? y : m->ymax;
14157     }
14158   }
14159 
14160   /* Nonexistent x value used as a flag to mark circle events in sweepline */
14161   /*   Delaunay algorithm.                                                 */
14162   m->xminextreme = 10 * m->xmin - 9 * m->xmax;
14163 }
14164 
14165 #endif /* TRILIBRARY */
14166 
14167 /*****************************************************************************/
14168 /*                                                                           */
14169 /*  readholes()   Read the holes, and possibly regional attributes and area  */
14170 /*                constraints, from a .poly file.                            */
14171 /*                                                                           */
14172 /*****************************************************************************/
14173 
14174 #ifndef TRILIBRARY
14175 
14176 #ifdef ANSI_DECLARATORS
14177 void readholes(struct mesh *m, struct behavior *b,
14178                FILE *polyfile, char *polyfilename, REAL **hlist, int *holes,
14179                REAL **rlist, int *regions)
14180 #else /* not ANSI_DECLARATORS */
14181 void readholes(m, b, polyfile, polyfilename, hlist, holes, rlist, regions)
14182 struct mesh *m;
14183 struct behavior *b;
14184 FILE *polyfile;
14185 char *polyfilename;
14186 REAL **hlist;
14187 int *holes;
14188 REAL **rlist;
14189 int *regions;
14190 #endif /* not ANSI_DECLARATORS */
14191 
14192 {
14193   REAL *holelist;
14194   REAL *regionlist;
14195   char inputline[INPUTLINESIZE];
14196   char *stringptr;
14197   int index;
14198   int i;
14199 
14200   /* Read the holes. */
14201   stringptr = readline(inputline, polyfile, polyfilename);
14202   *holes = (int) strtol(stringptr, &stringptr, 0);
14203   if (*holes > 0) {
14204     holelist = (REAL *) trimalloc(2 * *holes * (int) sizeof(REAL));
14205     *hlist = holelist;
14206     for (i = 0; i < 2 * *holes; i += 2) {
14207       stringptr = readline(inputline, polyfile, polyfilename);
14208       stringptr = findfield(stringptr);
14209       if (*stringptr == '\0') {
14210         printf("Error:  Hole %d has no x coordinate.\n",
14211                b->firstnumber + (i >> 1));
14212         triexit(1);
14213       } else {
14214         holelist[i] = (REAL) strtod(stringptr, &stringptr);
14215       }
14216       stringptr = findfield(stringptr);
14217       if (*stringptr == '\0') {
14218         printf("Error:  Hole %d has no y coordinate.\n",
14219                b->firstnumber + (i >> 1));
14220         triexit(1);
14221       } else {
14222         holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
14223       }
14224     }
14225   } else {
14226     *hlist = (REAL *) NULL;
14227   }
14228 
14229 #ifndef CDT_ONLY
14230   if ((b->regionattrib || b->vararea) && !b->refine) {
14231     /* Read the area constraints. */
14232     stringptr = readline(inputline, polyfile, polyfilename);
14233     *regions = (int) strtol(stringptr, &stringptr, 0);
14234     if (*regions > 0) {
14235       regionlist = (REAL *) trimalloc(4 * *regions * (int) sizeof(REAL));
14236       *rlist = regionlist;
14237       index = 0;
14238       for (i = 0; i < *regions; i++) {
14239         stringptr = readline(inputline, polyfile, polyfilename);
14240         stringptr = findfield(stringptr);
14241         if (*stringptr == '\0') {
14242           printf("Error:  Region %d has no x coordinate.\n",
14243                  b->firstnumber + i);
14244           triexit(1);
14245         } else {
14246           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14247         }
14248         stringptr = findfield(stringptr);
14249         if (*stringptr == '\0') {
14250           printf("Error:  Region %d has no y coordinate.\n",
14251                  b->firstnumber + i);
14252           triexit(1);
14253         } else {
14254           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14255         }
14256         stringptr = findfield(stringptr);
14257         if (*stringptr == '\0') {
14258           printf(
14259             "Error:  Region %d has no region attribute or area constraint.\n",
14260                  b->firstnumber + i);
14261           triexit(1);
14262         } else {
14263           regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
14264         }
14265         stringptr = findfield(stringptr);
14266         if (*stringptr == '\0') {
14267           regionlist[index] = regionlist[index - 1];
14268         } else {
14269           regionlist[index] = (REAL) strtod(stringptr, &stringptr);
14270         }
14271         index++;
14272       }
14273     }
14274   } else {
14275     /* Set `*regions' to zero to avoid an accidental free() later. */
14276     *regions = 0;
14277     *rlist = (REAL *) NULL;
14278   }
14279 #endif /* not CDT_ONLY */
14280 
14281   fclose(polyfile);
14282 }
14283 
14284 #endif /* not TRILIBRARY */
14285 
14286 /*****************************************************************************/
14287 /*                                                                           */
14288 /*  finishfile()   Write the command line to the output file so the user     */
14289 /*                 can remember how the file was generated.  Close the file. */
14290 /*                                                                           */
14291 /*****************************************************************************/
14292 
14293 #ifndef TRILIBRARY
14294 
14295 #ifdef ANSI_DECLARATORS
14296 void finishfile(FILE *outfile, int argc, char **argv)
14297 #else /* not ANSI_DECLARATORS */
14298 void finishfile(outfile, argc, argv)
14299 FILE *outfile;
14300 int argc;
14301 char **argv;
14302 #endif /* not ANSI_DECLARATORS */
14303 
14304 {
14305   int i;
14306 
14307   fprintf(outfile, "# Generated by");
14308   for (i = 0; i < argc; i++) {
14309     fprintf(outfile, " ");
14310     fputs(argv[i], outfile);
14311   }
14312   fprintf(outfile, "\n");
14313   fclose(outfile);
14314 }
14315 
14316 #endif /* not TRILIBRARY */
14317 
14318 /*****************************************************************************/
14319 /*                                                                           */
14320 /*  writenodes()   Number the vertices and write them to a .node file.       */
14321 /*                                                                           */
14322 /*  To save memory, the vertex numbers are written over the boundary markers */
14323 /*  after the vertices are written to a file.                                */
14324 /*                                                                           */
14325 /*****************************************************************************/
14326 
14327 #ifdef TRILIBRARY
14328 
14329 #ifdef ANSI_DECLARATORS
14330 void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
14331                 REAL **pointattriblist, int **pointmarkerlist)
14332 #else /* not ANSI_DECLARATORS */
14333 void writenodes(m, b, pointlist, pointattriblist, pointmarkerlist)
14334 struct mesh *m;
14335 struct behavior *b;
14336 REAL **pointlist;
14337 REAL **pointattriblist;
14338 int **pointmarkerlist;
14339 #endif /* not ANSI_DECLARATORS */
14340 
14341 #else /* not TRILIBRARY */
14342 
14343 #ifdef ANSI_DECLARATORS
14344 void writenodes(struct mesh *m, struct behavior *b, char *nodefilename,
14345                 int argc, char **argv)
14346 #else /* not ANSI_DECLARATORS */
14347 void writenodes(m, b, nodefilename, argc, argv)
14348 struct mesh *m;
14349 struct behavior *b;
14350 char *nodefilename;
14351 int argc;
14352 char **argv;
14353 #endif /* not ANSI_DECLARATORS */
14354 
14355 #endif /* not TRILIBRARY */
14356 
14357 {
14358 #ifdef TRILIBRARY
14359   REAL *plist;
14360   REAL *palist;
14361   int *pmlist;
14362   int coordindex;
14363   int attribindex;
14364 #else /* not TRILIBRARY */
14365   FILE *outfile;
14366 #endif /* not TRILIBRARY */
14367   vertex vertexloop;
14368   long outvertices;
14369   int vertexnumber;
14370   int i;
14371 
14372   if (b->jettison) {
14373     outvertices = m->vertices.items - m->undeads;
14374   } else {
14375     outvertices = m->vertices.items;
14376   }
14377 
14378 #ifdef TRILIBRARY
14379   if (!b->quiet) {
14380     printf("Writing vertices.\n");
14381   }
14382   /* Allocate memory for output vertices if necessary. */
14383   if (*pointlist == (REAL *) NULL) {
14384     *pointlist = (REAL *) trimalloc((int) (outvertices * 2 * sizeof(REAL)));
14385   }
14386   /* Allocate memory for output vertex attributes if necessary. */
14387   if ((m->nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
14388     *pointattriblist = (REAL *) trimalloc((int) (outvertices * m->nextras *
14389                                                  sizeof(REAL)));
14390   }
14391   /* Allocate memory for output vertex markers if necessary. */
14392   if (!b->nobound && (*pointmarkerlist == (int *) NULL)) {
14393     *pointmarkerlist = (int *) trimalloc((int) (outvertices * sizeof(int)));
14394   }
14395   plist = *pointlist;
14396   palist = *pointattriblist;
14397   pmlist = *pointmarkerlist;
14398   coordindex = 0;
14399   attribindex = 0;
14400 #else /* not TRILIBRARY */
14401   if (!b->quiet) {
14402     printf("Writing %s.\n", nodefilename);
14403   }
14404   outfile = fopen(nodefilename, "w");
14405   if (outfile == (FILE *) NULL) {
14406     printf("  Error:  Cannot create file %s.\n", nodefilename);
14407     triexit(1);
14408   }
14409   /* Number of vertices, number of dimensions, number of vertex attributes, */
14410   /*   and number of boundary markers (zero or one).                        */
14411   fprintf(outfile, "%ld  %d  %d  %d\n", outvertices, m->mesh_dim,
14412           m->nextras, 1 - b->nobound);
14413 #endif /* not TRILIBRARY */
14414 
14415   traversalinit(&m->vertices);
14416   vertexnumber = b->firstnumber;
14417   vertexloop = vertextraverse(m);
14418   while (vertexloop != (vertex) NULL) {
14419     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14420 #ifdef TRILIBRARY
14421       /* X and y coordinates. */
14422       plist[coordindex++] = vertexloop[0];
14423       plist[coordindex++] = vertexloop[1];
14424       /* Vertex attributes. */
14425       for (i = 0; i < m->nextras; i++) {
14426         palist[attribindex++] = vertexloop[2 + i];
14427       }
14428       if (!b->nobound) {
14429         /* Copy the boundary marker. */
14430         pmlist[vertexnumber - b->firstnumber] = vertexmark(vertexloop);
14431       }
14432 #else /* not TRILIBRARY */
14433       /* Vertex number, x and y coordinates. */
14434       fprintf(outfile, "%4d    %.17g  %.17g", vertexnumber, vertexloop[0],
14435               vertexloop[1]);
14436       for (i = 0; i < m->nextras; i++) {
14437         /* Write an attribute. */
14438         fprintf(outfile, "  %.17g", vertexloop[i + 2]);
14439       }
14440       if (b->nobound) {
14441         fprintf(outfile, "\n");
14442       } else {
14443         /* Write the boundary marker. */
14444         fprintf(outfile, "    %d\n", vertexmark(vertexloop));
14445       }
14446 #endif /* not TRILIBRARY */
14447 
14448       setvertexmark(vertexloop, vertexnumber);
14449       vertexnumber++;
14450     }
14451     vertexloop = vertextraverse(m);
14452   }
14453 
14454 #ifndef TRILIBRARY
14455   finishfile(outfile, argc, argv);
14456 #endif /* not TRILIBRARY */
14457 }
14458 
14459 /*****************************************************************************/
14460 /*                                                                           */
14461 /*  numbernodes()   Number the vertices.                                     */
14462 /*                                                                           */
14463 /*  Each vertex is assigned a marker equal to its number.                    */
14464 /*                                                                           */
14465 /*  Used when writenodes() is not called because no .node file is written.   */
14466 /*                                                                           */
14467 /*****************************************************************************/
14468 
14469 #ifdef ANSI_DECLARATORS
14470 void numbernodes(struct mesh *m, struct behavior *b)
14471 #else /* not ANSI_DECLARATORS */
14472 void numbernodes(m, b)
14473 struct mesh *m;
14474 struct behavior *b;
14475 #endif /* not ANSI_DECLARATORS */
14476 
14477 {
14478   vertex vertexloop;
14479   int vertexnumber;
14480 
14481   traversalinit(&m->vertices);
14482   vertexnumber = b->firstnumber;
14483   vertexloop = vertextraverse(m);
14484   while (vertexloop != (vertex) NULL) {
14485     setvertexmark(vertexloop, vertexnumber);
14486     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
14487       vertexnumber++;
14488     }
14489     vertexloop = vertextraverse(m);
14490   }
14491 }
14492 
14493 /*****************************************************************************/
14494 /*                                                                           */
14495 /*  writeelements()   Write the triangles to an .ele file.                   */
14496 /*                                                                           */
14497 /*****************************************************************************/
14498 
14499 #ifdef TRILIBRARY
14500 
14501 #ifdef ANSI_DECLARATORS
14502 void writeelements(struct mesh *m, struct behavior *b,
14503                    int **trianglelist, REAL **triangleattriblist)
14504 #else /* not ANSI_DECLARATORS */
14505 void writeelements(m, b, trianglelist, triangleattriblist)
14506 struct mesh *m;
14507 struct behavior *b;
14508 int **trianglelist;
14509 REAL **triangleattriblist;
14510 #endif /* not ANSI_DECLARATORS */
14511 
14512 #else /* not TRILIBRARY */
14513 
14514 #ifdef ANSI_DECLARATORS
14515 void writeelements(struct mesh *m, struct behavior *b, char *elefilename,
14516                    int argc, char **argv)
14517 #else /* not ANSI_DECLARATORS */
14518 void writeelements(m, b, elefilename, argc, argv)
14519 struct mesh *m;
14520 struct behavior *b;
14521 char *elefilename;
14522 int argc;
14523 char **argv;
14524 #endif /* not ANSI_DECLARATORS */
14525 
14526 #endif /* not TRILIBRARY */
14527 
14528 {
14529 #ifdef TRILIBRARY
14530   int *tlist;
14531   REAL *talist;
14532   int vertexindex;
14533   int attribindex;
14534 #else /* not TRILIBRARY */
14535   FILE *outfile;
14536 #endif /* not TRILIBRARY */
14537   struct otri triangleloop;
14538   vertex p1, p2, p3;
14539   vertex mid1, mid2, mid3;
14540   long elementnumber;
14541   int i;
14542 
14543 #ifdef TRILIBRARY
14544   if (!b->quiet) {
14545     printf("Writing triangles.\n");
14546   }
14547   /* Allocate memory for output triangles if necessary. */
14548   if (*trianglelist == (int *) NULL) {
14549     *trianglelist = (int *) trimalloc((int) (m->triangles.items *
14550                                              ((b->order + 1) * (b->order + 2) /
14551                                               2) * sizeof(int)));
14552   }
14553   /* Allocate memory for output triangle attributes if necessary. */
14554   if ((m->eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
14555     *triangleattriblist = (REAL *) trimalloc((int) (m->triangles.items *
14556                                                     m->eextras *
14557                                                     sizeof(REAL)));
14558   }
14559   tlist = *trianglelist;
14560   talist = *triangleattriblist;
14561   vertexindex = 0;
14562   attribindex = 0;
14563 #else /* not TRILIBRARY */
14564   if (!b->quiet) {
14565     printf("Writing %s.\n", elefilename);
14566   }
14567   outfile = fopen(elefilename, "w");
14568   if (outfile == (FILE *) NULL) {
14569     printf("  Error:  Cannot create file %s.\n", elefilename);
14570     triexit(1);
14571   }
14572   /* Number of triangles, vertices per triangle, attributes per triangle. */
14573   fprintf(outfile, "%ld  %d  %d\n", m->triangles.items,
14574           (b->order + 1) * (b->order + 2) / 2, m->eextras);
14575 #endif /* not TRILIBRARY */
14576 
14577   traversalinit(&m->triangles);
14578   triangleloop.tri = triangletraverse(m);
14579   triangleloop.orient = 0;
14580   elementnumber = b->firstnumber;
14581   while (triangleloop.tri != (triangle *) NULL) {
14582     org(triangleloop, p1);
14583     dest(triangleloop, p2);
14584     apex(triangleloop, p3);
14585     if (b->order == 1) {
14586 #ifdef TRILIBRARY
14587       tlist[vertexindex++] = vertexmark(p1);
14588       tlist[vertexindex++] = vertexmark(p2);
14589       tlist[vertexindex++] = vertexmark(p3);
14590 #else /* not TRILIBRARY */
14591       /* Triangle number, indices for three vertices. */
14592       fprintf(outfile, "%4ld    %4d  %4d  %4d", elementnumber,
14593               vertexmark(p1), vertexmark(p2), vertexmark(p3));
14594 #endif /* not TRILIBRARY */
14595     } else {
14596       mid1 = (vertex) triangleloop.tri[m->highorderindex + 1];
14597       mid2 = (vertex) triangleloop.tri[m->highorderindex + 2];
14598       mid3 = (vertex) triangleloop.tri[m->highorderindex];
14599 #ifdef TRILIBRARY
14600       tlist[vertexindex++] = vertexmark(p1);
14601       tlist[vertexindex++] = vertexmark(p2);
14602       tlist[vertexindex++] = vertexmark(p3);
14603       tlist[vertexindex++] = vertexmark(mid1);
14604       tlist[vertexindex++] = vertexmark(mid2);
14605       tlist[vertexindex++] = vertexmark(mid3);
14606 #else /* not TRILIBRARY */
14607       /* Triangle number, indices for six vertices. */
14608       fprintf(outfile, "%4ld    %4d  %4d  %4d  %4d  %4d  %4d", elementnumber,
14609               vertexmark(p1), vertexmark(p2), vertexmark(p3), vertexmark(mid1),
14610               vertexmark(mid2), vertexmark(mid3));
14611 #endif /* not TRILIBRARY */
14612     }
14613 
14614 #ifdef TRILIBRARY
14615     for (i = 0; i < m->eextras; i++) {
14616       talist[attribindex++] = elemattribute(triangleloop, i);
14617     }
14618 #else /* not TRILIBRARY */
14619     for (i = 0; i < m->eextras; i++) {
14620       fprintf(outfile, "  %.17g", elemattribute(triangleloop, i));
14621     }
14622     fprintf(outfile, "\n");
14623 #endif /* not TRILIBRARY */
14624 
14625     triangleloop.tri = triangletraverse(m);
14626     elementnumber++;
14627   }
14628 
14629 #ifndef TRILIBRARY
14630   finishfile(outfile, argc, argv);
14631 #endif /* not TRILIBRARY */
14632 }
14633 
14634 /*****************************************************************************/
14635 /*                                                                           */
14636 /*  writepoly()   Write the segments and holes to a .poly file.              */
14637 /*                                                                           */
14638 /*****************************************************************************/
14639 
14640 #ifdef TRILIBRARY
14641 
14642 #ifdef ANSI_DECLARATORS
14643 void writepoly(struct mesh *m, struct behavior *b,
14644                int **segmentlist, int **segmentmarkerlist)
14645 #else /* not ANSI_DECLARATORS */
14646 void writepoly(m, b, segmentlist, segmentmarkerlist)
14647 struct mesh *m;
14648 struct behavior *b;
14649 int **segmentlist;
14650 int **segmentmarkerlist;
14651 #endif /* not ANSI_DECLARATORS */
14652 
14653 #else /* not TRILIBRARY */
14654 
14655 #ifdef ANSI_DECLARATORS
14656 void writepoly(struct mesh *m, struct behavior *b, char *polyfilename,
14657                REAL *holelist, int holes, REAL *regionlist, int regions,
14658                int argc, char **argv)
14659 #else /* not ANSI_DECLARATORS */
14660 void writepoly(m, b, polyfilename, holelist, holes, regionlist, regions,
14661                argc, argv)
14662 struct mesh *m;
14663 struct behavior *b;
14664 char *polyfilename;
14665 REAL *holelist;
14666 int holes;
14667 REAL *regionlist;
14668 int regions;
14669 int argc;
14670 char **argv;
14671 #endif /* not ANSI_DECLARATORS */
14672 
14673 #endif /* not TRILIBRARY */
14674 
14675 {
14676 #ifdef TRILIBRARY
14677   int *slist;
14678   int *smlist;
14679   int index;
14680 #else /* not TRILIBRARY */
14681   FILE *outfile;
14682   long holenumber, regionnumber;
14683 #endif /* not TRILIBRARY */
14684   struct osub subsegloop;
14685   vertex endpoint1, endpoint2;
14686   long subsegnumber;
14687 
14688 #ifdef TRILIBRARY
14689   if (!b->quiet) {
14690     printf("Writing segments.\n");
14691   }
14692   /* Allocate memory for output segments if necessary. */
14693   if (*segmentlist == (int *) NULL) {
14694     *segmentlist = (int *) trimalloc((int) (m->subsegs.items * 2 *
14695                                             sizeof(int)));
14696   }
14697   /* Allocate memory for output segment markers if necessary. */
14698   if (!b->nobound && (*segmentmarkerlist == (int *) NULL)) {
14699     *segmentmarkerlist = (int *) trimalloc((int) (m->subsegs.items *
14700                                                   sizeof(int)));
14701   }
14702   slist = *segmentlist;
14703   smlist = *segmentmarkerlist;
14704   index = 0;
14705 #else /* not TRILIBRARY */
14706   if (!b->quiet) {
14707     printf("Writing %s.\n", polyfilename);
14708   }
14709   outfile = fopen(polyfilename, "w");
14710   if (outfile == (FILE *) NULL) {
14711     printf("  Error:  Cannot create file %s.\n", polyfilename);
14712     triexit(1);
14713   }
14714   /* The zero indicates that the vertices are in a separate .node file. */
14715   /*   Followed by number of dimensions, number of vertex attributes,   */
14716   /*   and number of boundary markers (zero or one).                    */
14717   fprintf(outfile, "%d  %d  %d  %d\n", 0, m->mesh_dim, m->nextras,
14718           1 - b->nobound);
14719   /* Number of segments, number of boundary markers (zero or one). */
14720   fprintf(outfile, "%ld  %d\n", m->subsegs.items, 1 - b->nobound);
14721 #endif /* not TRILIBRARY */
14722 
14723   traversalinit(&m->subsegs);
14724   subsegloop.ss = subsegtraverse(m);
14725   subsegloop.ssorient = 0;
14726   subsegnumber = b->firstnumber;
14727   while (subsegloop.ss != (subseg *) NULL) {
14728     sorg(subsegloop, endpoint1);
14729     sdest(subsegloop, endpoint2);
14730 #ifdef TRILIBRARY
14731     /* Copy indices of the segment's two endpoints. */
14732     slist[index++] = vertexmark(endpoint1);
14733     slist[index++] = vertexmark(endpoint2);
14734     if (!b->nobound) {
14735       /* Copy the boundary marker. */
14736       smlist[subsegnumber - b->firstnumber] = mark(subsegloop);
14737     }
14738 #else /* not TRILIBRARY */
14739     /* Segment number, indices of its two endpoints, and possibly a marker. */
14740     if (b->nobound) {
14741       fprintf(outfile, "%4ld    %4d  %4d\n", subsegnumber,
14742               vertexmark(endpoint1), vertexmark(endpoint2));
14743     } else {
14744       fprintf(outfile, "%4ld    %4d  %4d    %4d\n", subsegnumber,
14745               vertexmark(endpoint1), vertexmark(endpoint2), mark(subsegloop));
14746     }
14747 #endif /* not TRILIBRARY */
14748 
14749     subsegloop.ss = subsegtraverse(m);
14750     subsegnumber++;
14751   }
14752 
14753 #ifndef TRILIBRARY
14754 #ifndef CDT_ONLY
14755   fprintf(outfile, "%d\n", holes);
14756   if (holes > 0) {
14757     for (holenumber = 0; holenumber < holes; holenumber++) {
14758       /* Hole number, x and y coordinates. */
14759       fprintf(outfile, "%4ld   %.17g  %.17g\n", b->firstnumber + holenumber,
14760               holelist[2 * holenumber], holelist[2 * holenumber + 1]);
14761     }
14762   }
14763   if (regions > 0) {
14764     fprintf(outfile, "%d\n", regions);
14765     for (regionnumber = 0; regionnumber < regions; regionnumber++) {
14766       /* Region number, x and y coordinates, attribute, maximum area. */
14767       fprintf(outfile, "%4ld   %.17g  %.17g  %.17g  %.17g\n",
14768               b->firstnumber + regionnumber,
14769               regionlist[4 * regionnumber], regionlist[4 * regionnumber + 1],
14770               regionlist[4 * regionnumber + 2],
14771               regionlist[4 * regionnumber + 3]);
14772     }
14773   }
14774 #endif /* not CDT_ONLY */
14775 
14776   finishfile(outfile, argc, argv);
14777 #endif /* not TRILIBRARY */
14778 }
14779 
14780 /*****************************************************************************/
14781 /*                                                                           */
14782 /*  writeedges()   Write the edges to an .edge file.                         */
14783 /*                                                                           */
14784 /*****************************************************************************/
14785 
14786 #ifdef TRILIBRARY
14787 
14788 #ifdef ANSI_DECLARATORS
14789 void writeedges(struct mesh *m, struct behavior *b,
14790                 int **edgelist, int **edgemarkerlist)
14791 #else /* not ANSI_DECLARATORS */
14792 void writeedges(m, b, edgelist, edgemarkerlist)
14793 struct mesh *m;
14794 struct behavior *b;
14795 int **edgelist;
14796 int **edgemarkerlist;
14797 #endif /* not ANSI_DECLARATORS */
14798 
14799 #else /* not TRILIBRARY */
14800 
14801 #ifdef ANSI_DECLARATORS
14802 void writeedges(struct mesh *m, struct behavior *b, char *edgefilename,
14803                 int argc, char **argv)
14804 #else /* not ANSI_DECLARATORS */
14805 void writeedges(m, b, edgefilename, argc, argv)
14806 struct mesh *m;
14807 struct behavior *b;
14808 char *edgefilename;
14809 int argc;
14810 char **argv;
14811 #endif /* not ANSI_DECLARATORS */
14812 
14813 #endif /* not TRILIBRARY */
14814 
14815 {
14816 #ifdef TRILIBRARY
14817   int *elist;
14818   int *emlist;
14819   int index;
14820 #else /* not TRILIBRARY */
14821   FILE *outfile;
14822 #endif /* not TRILIBRARY */
14823   struct otri triangleloop, trisym;
14824   struct osub checkmark;
14825   vertex p1, p2;
14826   long edgenumber;
14827   triangle ptr;                         /* Temporary variable used by sym(). */
14828   subseg sptr;                      /* Temporary variable used by tspivot(). */
14829 
14830 #ifdef TRILIBRARY
14831   if (!b->quiet) {
14832     printf("Writing edges.\n");
14833   }
14834   /* Allocate memory for edges if necessary. */
14835   if (*edgelist == (int *) NULL) {
14836     *edgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
14837   }
14838   /* Allocate memory for edge markers if necessary. */
14839   if (!b->nobound && (*edgemarkerlist == (int *) NULL)) {
14840     *edgemarkerlist = (int *) trimalloc((int) (m->edges * sizeof(int)));
14841   }
14842   elist = *edgelist;
14843   emlist = *edgemarkerlist;
14844   index = 0;
14845 #else /* not TRILIBRARY */
14846   if (!b->quiet) {
14847     printf("Writing %s.\n", edgefilename);
14848   }
14849   outfile = fopen(edgefilename, "w");
14850   if (outfile == (FILE *) NULL) {
14851     printf("  Error:  Cannot create file %s.\n", edgefilename);
14852     triexit(1);
14853   }
14854   /* Number of edges, number of boundary markers (zero or one). */
14855   fprintf(outfile, "%ld  %d\n", m->edges, 1 - b->nobound);
14856 #endif /* not TRILIBRARY */
14857 
14858   traversalinit(&m->triangles);
14859   triangleloop.tri = triangletraverse(m);
14860   edgenumber = b->firstnumber;
14861   /* To loop over the set of edges, loop over all triangles, and look at   */
14862   /*   the three edges of each triangle.  If there isn't another triangle  */
14863   /*   adjacent to the edge, operate on the edge.  If there is another     */
14864   /*   adjacent triangle, operate on the edge only if the current triangle */
14865   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
14866   /*   considered only once.                                               */
14867   while (triangleloop.tri != (triangle *) NULL) {
14868     for (triangleloop.orient = 0; triangleloop.orient < 3;
14869          triangleloop.orient++) {
14870       sym(triangleloop, trisym);
14871       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
14872         org(triangleloop, p1);
14873         dest(triangleloop, p2);
14874 #ifdef TRILIBRARY
14875         elist[index++] = vertexmark(p1);
14876         elist[index++] = vertexmark(p2);
14877 #endif /* TRILIBRARY */
14878         if (b->nobound) {
14879 #ifndef TRILIBRARY
14880           /* Edge number, indices of two endpoints. */
14881           fprintf(outfile, "%4ld   %d  %d\n", edgenumber,
14882                   vertexmark(p1), vertexmark(p2));
14883 #endif /* not TRILIBRARY */
14884         } else {
14885           /* Edge number, indices of two endpoints, and a boundary marker. */
14886           /*   If there's no subsegment, the boundary marker is zero.      */
14887           if (b->usesegments) {
14888             tspivot(triangleloop, checkmark);
14889             if (checkmark.ss == m->dummysub) {
14890 #ifdef TRILIBRARY
14891               emlist[edgenumber - b->firstnumber] = 0;
14892 #else /* not TRILIBRARY */
14893               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14894                       vertexmark(p1), vertexmark(p2), 0);
14895 #endif /* not TRILIBRARY */
14896             } else {
14897 #ifdef TRILIBRARY
14898               emlist[edgenumber - b->firstnumber] = mark(checkmark);
14899 #else /* not TRILIBRARY */
14900               fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14901                       vertexmark(p1), vertexmark(p2), mark(checkmark));
14902 #endif /* not TRILIBRARY */
14903             }
14904           } else {
14905 #ifdef TRILIBRARY
14906             emlist[edgenumber - b->firstnumber] = trisym.tri == m->dummytri;
14907 #else /* not TRILIBRARY */
14908             fprintf(outfile, "%4ld   %d  %d  %d\n", edgenumber,
14909                     vertexmark(p1), vertexmark(p2), trisym.tri == m->dummytri);
14910 #endif /* not TRILIBRARY */
14911           }
14912         }
14913         edgenumber++;
14914       }
14915     }
14916     triangleloop.tri = triangletraverse(m);
14917   }
14918 
14919 #ifndef TRILIBRARY
14920   finishfile(outfile, argc, argv);
14921 #endif /* not TRILIBRARY */
14922 }
14923 
14924 /*****************************************************************************/
14925 /*                                                                           */
14926 /*  writevoronoi()   Write the Voronoi diagram to a .v.node and .v.edge      */
14927 /*                   file.                                                   */
14928 /*                                                                           */
14929 /*  The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
14930 /*  Hence, the Voronoi vertices are listed by traversing the Delaunay        */
14931 /*  triangles, and the Voronoi edges are listed by traversing the Delaunay   */
14932 /*  edges.                                                                   */
14933 /*                                                                           */
14934 /*  WARNING:  In order to assign numbers to the Voronoi vertices, this       */
14935 /*  procedure messes up the subsegments or the extra nodes of every          */
14936 /*  element.  Hence, you should call this procedure last.                    */
14937 /*                                                                           */
14938 /*****************************************************************************/
14939 
14940 #ifdef TRILIBRARY
14941 
14942 #ifdef ANSI_DECLARATORS
14943 void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
14944                   REAL **vpointattriblist, int **vpointmarkerlist,
14945                   int **vedgelist, int **vedgemarkerlist, REAL **vnormlist)
14946 #else /* not ANSI_DECLARATORS */
14947 void writevoronoi(m, b, vpointlist, vpointattriblist, vpointmarkerlist,
14948                   vedgelist, vedgemarkerlist, vnormlist)
14949 struct mesh *m;
14950 struct behavior *b;
14951 REAL **vpointlist;
14952 REAL **vpointattriblist;
14953 int **vpointmarkerlist;
14954 int **vedgelist;
14955 int **vedgemarkerlist;
14956 REAL **vnormlist;
14957 #endif /* not ANSI_DECLARATORS */
14958 
14959 #else /* not TRILIBRARY */
14960 
14961 #ifdef ANSI_DECLARATORS
14962 void writevoronoi(struct mesh *m, struct behavior *b, char *vnodefilename,
14963                   char *vedgefilename, int argc, char **argv)
14964 #else /* not ANSI_DECLARATORS */
14965 void writevoronoi(m, b, vnodefilename, vedgefilename, argc, argv)
14966 struct mesh *m;
14967 struct behavior *b;
14968 char *vnodefilename;
14969 char *vedgefilename;
14970 int argc;
14971 char **argv;
14972 #endif /* not ANSI_DECLARATORS */
14973 
14974 #endif /* not TRILIBRARY */
14975 
14976 {
14977 #ifdef TRILIBRARY
14978   REAL *plist;
14979   REAL *palist;
14980   int *elist;
14981   REAL *normlist;
14982   int coordindex;
14983   int attribindex;
14984 #else /* not TRILIBRARY */
14985   FILE *outfile;
14986 #endif /* not TRILIBRARY */
14987   struct otri triangleloop, trisym;
14988   vertex torg, tdest, tapex;
14989   REAL circumcenter[2];
14990   REAL xi, eta;
14991   long vnodenumber, vedgenumber;
14992   int p1, p2;
14993   int i;
14994   triangle ptr;                         /* Temporary variable used by sym(). */
14995 
14996 #ifdef TRILIBRARY
14997   if (!b->quiet) {
14998     printf("Writing Voronoi vertices.\n");
14999   }
15000   /* Allocate memory for Voronoi vertices if necessary. */
15001   if (*vpointlist == (REAL *) NULL) {
15002     *vpointlist = (REAL *) trimalloc((int) (m->triangles.items * 2 *
15003                                             sizeof(REAL)));
15004   }
15005   /* Allocate memory for Voronoi vertex attributes if necessary. */
15006   if (*vpointattriblist == (REAL *) NULL) {
15007     *vpointattriblist = (REAL *) trimalloc((int) (m->triangles.items *
15008                                                   m->nextras * sizeof(REAL)));
15009   }
15010   *vpointmarkerlist = (int *) NULL;
15011   plist = *vpointlist;
15012   palist = *vpointattriblist;
15013   coordindex = 0;
15014   attribindex = 0;
15015 #else /* not TRILIBRARY */
15016   if (!b->quiet) {
15017     printf("Writing %s.\n", vnodefilename);
15018   }
15019   outfile = fopen(vnodefilename, "w");
15020   if (outfile == (FILE *) NULL) {
15021     printf("  Error:  Cannot create file %s.\n", vnodefilename);
15022     triexit(1);
15023   }
15024   /* Number of triangles, two dimensions, number of vertex attributes, */
15025   /*   no markers.                                                     */
15026   fprintf(outfile, "%ld  %d  %d  %d\n", m->triangles.items, 2, m->nextras, 0);
15027 #endif /* not TRILIBRARY */
15028 
15029   traversalinit(&m->triangles);
15030   triangleloop.tri = triangletraverse(m);
15031   triangleloop.orient = 0;
15032   vnodenumber = b->firstnumber;
15033   while (triangleloop.tri != (triangle *) NULL) {
15034     org(triangleloop, torg);
15035     dest(triangleloop, tdest);
15036     apex(triangleloop, tapex);
15037     findcircumcenter(m, b, torg, tdest, tapex, circumcenter, &xi, &eta, 0);
15038 #ifdef TRILIBRARY
15039     /* X and y coordinates. */
15040     plist[coordindex++] = circumcenter[0];
15041     plist[coordindex++] = circumcenter[1];
15042     for (i = 2; i < 2 + m->nextras; i++) {
15043       /* Interpolate the vertex attributes at the circumcenter. */
15044       palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
15045                                      + eta * (tapex[i] - torg[i]);
15046     }
15047 #else /* not TRILIBRARY */
15048     /* Voronoi vertex number, x and y coordinates. */
15049     fprintf(outfile, "%4ld    %.17g  %.17g", vnodenumber, circumcenter[0],
15050             circumcenter[1]);
15051     for (i = 2; i < 2 + m->nextras; i++) {
15052       /* Interpolate the vertex attributes at the circumcenter. */
15053       fprintf(outfile, "  %.17g", torg[i] + xi * (tdest[i] - torg[i])
15054                                          + eta * (tapex[i] - torg[i]));
15055     }
15056     fprintf(outfile, "\n");
15057 #endif /* not TRILIBRARY */
15058 
15059     * (int *) (triangleloop.tri + 6) = (int) vnodenumber;
15060     triangleloop.tri = triangletraverse(m);
15061     vnodenumber++;
15062   }
15063 
15064 #ifndef TRILIBRARY
15065   finishfile(outfile, argc, argv);
15066 #endif /* not TRILIBRARY */
15067 
15068 #ifdef TRILIBRARY
15069   if (!b->quiet) {
15070     printf("Writing Voronoi edges.\n");
15071   }
15072   /* Allocate memory for output Voronoi edges if necessary. */
15073   if (*vedgelist == (int *) NULL) {
15074     *vedgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
15075   }
15076   *vedgemarkerlist = (int *) NULL;
15077   /* Allocate memory for output Voronoi norms if necessary. */
15078   if (*vnormlist == (REAL *) NULL) {
15079     *vnormlist = (REAL *) trimalloc((int) (m->edges * 2 * sizeof(REAL)));
15080   }
15081   elist = *vedgelist;
15082   normlist = *vnormlist;
15083   coordindex = 0;
15084 #else /* not TRILIBRARY */
15085   if (!b->quiet) {
15086     printf("Writing %s.\n", vedgefilename);
15087   }
15088   outfile = fopen(vedgefilename, "w");
15089   if (outfile == (FILE *) NULL) {
15090     printf("  Error:  Cannot create file %s.\n", vedgefilename);
15091     triexit(1);
15092   }
15093   /* Number of edges, zero boundary markers. */
15094   fprintf(outfile, "%ld  %d\n", m->edges, 0);
15095 #endif /* not TRILIBRARY */
15096 
15097   traversalinit(&m->triangles);
15098   triangleloop.tri = triangletraverse(m);
15099   vedgenumber = b->firstnumber;
15100   /* To loop over the set of edges, loop over all triangles, and look at   */
15101   /*   the three edges of each triangle.  If there isn't another triangle  */
15102   /*   adjacent to the edge, operate on the edge.  If there is another     */
15103   /*   adjacent triangle, operate on the edge only if the current triangle */
15104   /*   has a smaller pointer than its neighbor.  This way, each edge is    */
15105   /*   considered only once.                                               */
15106   while (triangleloop.tri != (triangle *) NULL) {
15107     for (triangleloop.orient = 0; triangleloop.orient < 3;
15108          triangleloop.orient++) {
15109       sym(triangleloop, trisym);
15110       if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
15111         /* Find the number of this triangle (and Voronoi vertex). */
15112         p1 = * (int *) (triangleloop.tri + 6);
15113         if (trisym.tri == m->dummytri) {
15114           org(triangleloop, torg);
15115           dest(triangleloop, tdest);
15116 #ifdef TRILIBRARY
15117           /* Copy an infinite ray.  Index of one endpoint, and -1. */
15118           elist[coordindex] = p1;
15119           normlist[coordindex++] = tdest[1] - torg[1];
15120           elist[coordindex] = -1;
15121           normlist[coordindex++] = torg[0] - tdest[0];
15122 #else /* not TRILIBRARY */
15123           /* Write an infinite ray.  Edge number, index of one endpoint, -1, */
15124           /*   and x and y coordinates of a vector representing the          */
15125           /*   direction of the ray.                                         */
15126           fprintf(outfile, "%4ld   %d  %d   %.17g  %.17g\n", vedgenumber,
15127                   p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
15128 #endif /* not TRILIBRARY */
15129         } else {
15130           /* Find the number of the adjacent triangle (and Voronoi vertex). */
15131           p2 = * (int *) (trisym.tri + 6);
15132           /* Finite edge.  Write indices of two endpoints. */
15133 #ifdef TRILIBRARY
15134           elist[coordindex] = p1;
15135           normlist[coordindex++] = 0.0;
15136           elist[coordindex] = p2;
15137           normlist[coordindex++] = 0.0;
15138 #else /* not TRILIBRARY */
15139           fprintf(outfile, "%4ld   %d  %d\n", vedgenumber, p1, p2);
15140 #endif /* not TRILIBRARY */
15141         }
15142         vedgenumber++;
15143       }
15144     }
15145     triangleloop.tri = triangletraverse(m);
15146   }
15147 
15148 #ifndef TRILIBRARY
15149   finishfile(outfile, argc, argv);
15150 #endif /* not TRILIBRARY */
15151 }
15152 
15153 #ifdef TRILIBRARY
15154 
15155 #ifdef ANSI_DECLARATORS
15156 void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist)
15157 #else /* not ANSI_DECLARATORS */
15158 void writeneighbors(m, b, neighborlist)
15159 struct mesh *m;
15160 struct behavior *b;
15161 int **neighborlist;
15162 #endif /* not ANSI_DECLARATORS */
15163 
15164 #else /* not TRILIBRARY */
15165 
15166 #ifdef ANSI_DECLARATORS
15167 void writeneighbors(struct mesh *m, struct behavior *b, char *neighborfilename,
15168                     int argc, char **argv)
15169 #else /* not ANSI_DECLARATORS */
15170 void writeneighbors(m, b, neighborfilename, argc, argv)
15171 struct mesh *m;
15172 struct behavior *b;
15173 char *neighborfilename;
15174 int argc;
15175 char **argv;
15176 #endif /* not ANSI_DECLARATORS */
15177 
15178 #endif /* not TRILIBRARY */
15179 
15180 {
15181 #ifdef TRILIBRARY
15182   int *nlist;
15183   int index;
15184 #else /* not TRILIBRARY */
15185   FILE *outfile;
15186 #endif /* not TRILIBRARY */
15187   struct otri triangleloop, trisym;
15188   long elementnumber;
15189   int neighbor1, neighbor2, neighbor3;
15190   triangle ptr;                         /* Temporary variable used by sym(). */
15191 
15192 #ifdef TRILIBRARY
15193   if (!b->quiet) {
15194     printf("Writing neighbors.\n");
15195   }
15196   /* Allocate memory for neighbors if necessary. */
15197   if (*neighborlist == (int *) NULL) {
15198     *neighborlist = (int *) trimalloc((int) (m->triangles.items * 3 *
15199                                              sizeof(int)));
15200   }
15201   nlist = *neighborlist;
15202   index = 0;
15203 #else /* not TRILIBRARY */
15204   if (!b->quiet) {
15205     printf("Writing %s.\n", neighborfilename);
15206   }
15207   outfile = fopen(neighborfilename, "w");
15208   if (outfile == (FILE *) NULL) {
15209     printf("  Error:  Cannot create file %s.\n", neighborfilename);
15210     triexit(1);
15211   }
15212   /* Number of triangles, three neighbors per triangle. */
15213   fprintf(outfile, "%ld  %d\n", m->triangles.items, 3);
15214 #endif /* not TRILIBRARY */
15215 
15216   traversalinit(&m->triangles);
15217   triangleloop.tri = triangletraverse(m);
15218   triangleloop.orient = 0;
15219   elementnumber = b->firstnumber;
15220   while (triangleloop.tri != (triangle *) NULL) {
15221     * (int *) (triangleloop.tri + 6) = (int) elementnumber;
15222     triangleloop.tri = triangletraverse(m);
15223     elementnumber++;
15224   }
15225   * (int *) (m->dummytri + 6) = -1;
15226 
15227   traversalinit(&m->triangles);
15228   triangleloop.tri = triangletraverse(m);
15229   elementnumber = b->firstnumber;
15230   while (triangleloop.tri != (triangle *) NULL) {
15231     triangleloop.orient = 1;
15232     sym(triangleloop, trisym);
15233     neighbor1 = * (int *) (trisym.tri + 6);
15234     triangleloop.orient = 2;
15235     sym(triangleloop, trisym);
15236     neighbor2 = * (int *) (trisym.tri + 6);
15237     triangleloop.orient = 0;
15238     sym(triangleloop, trisym);
15239     neighbor3 = * (int *) (trisym.tri + 6);
15240 #ifdef TRILIBRARY
15241     nlist[index++] = neighbor1;
15242     nlist[index++] = neighbor2;
15243     nlist[index++] = neighbor3;
15244 #else /* not TRILIBRARY */
15245     /* Triangle number, neighboring triangle numbers. */
15246     fprintf(outfile, "%4ld    %d  %d  %d\n", elementnumber,
15247             neighbor1, neighbor2, neighbor3);
15248 #endif /* not TRILIBRARY */
15249 
15250     triangleloop.tri = triangletraverse(m);
15251     elementnumber++;
15252   }
15253 
15254 #ifndef TRILIBRARY
15255   finishfile(outfile, argc, argv);
15256 #endif /* not TRILIBRARY */
15257 }
15258 
15259 /*****************************************************************************/
15260 /*                                                                           */
15261 /*  writeoff()   Write the triangulation to an .off file.                    */
15262 /*                                                                           */
15263 /*  OFF stands for the Object File Format, a format used by the Geometry     */
15264 /*  Center's Geomview package.                                               */
15265 /*                                                                           */
15266 /*****************************************************************************/
15267 
15268 #ifndef TRILIBRARY
15269 
15270 #ifdef ANSI_DECLARATORS
15271 void writeoff(struct mesh *m, struct behavior *b, char *offfilename,
15272               int argc, char **argv)
15273 #else /* not ANSI_DECLARATORS */
15274 void writeoff(m, b, offfilename, argc, argv)
15275 struct mesh *m;
15276 struct behavior *b;
15277 char *offfilename;
15278 int argc;
15279 char **argv;
15280 #endif /* not ANSI_DECLARATORS */
15281 
15282 {
15283   FILE *outfile;
15284   struct otri triangleloop;
15285   vertex vertexloop;
15286   vertex p1, p2, p3;
15287   long outvertices;
15288 
15289   if (!b->quiet) {
15290     printf("Writing %s.\n", offfilename);
15291   }
15292 
15293   if (b->jettison) {
15294     outvertices = m->vertices.items - m->undeads;
15295   } else {
15296     outvertices = m->vertices.items;
15297   }
15298 
15299   outfile = fopen(offfilename, "w");
15300   if (outfile == (FILE *) NULL) {
15301     printf("  Error:  Cannot create file %s.\n", offfilename);
15302     triexit(1);
15303   }
15304   /* Number of vertices, triangles, and edges. */
15305   fprintf(outfile, "OFF\n%ld  %ld  %ld\n", outvertices, m->triangles.items,
15306           m->edges);
15307 
15308   /* Write the vertices. */
15309   traversalinit(&m->vertices);
15310   vertexloop = vertextraverse(m);
15311   while (vertexloop != (vertex) NULL) {
15312     if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
15313       /* The "0.0" is here because the OFF format uses 3D coordinates. */
15314       fprintf(outfile, " %.17g  %.17g  %.17g\n", vertexloop[0], vertexloop[1],
15315               0.0);
15316     }
15317     vertexloop = vertextraverse(m);
15318   }
15319 
15320   /* Write the triangles. */
15321   traversalinit(&m->triangles);
15322   triangleloop.tri = triangletraverse(m);
15323   triangleloop.orient = 0;
15324   while (triangleloop.tri != (triangle *) NULL) {
15325     org(triangleloop, p1);
15326     dest(triangleloop, p2);
15327     apex(triangleloop, p3);
15328     /* The "3" means a three-vertex polygon. */
15329     fprintf(outfile, " 3   %4d  %4d  %4d\n", vertexmark(p1) - b->firstnumber,
15330             vertexmark(p2) - b->firstnumber, vertexmark(p3) - b->firstnumber);
15331     triangleloop.tri = triangletraverse(m);
15332   }
15333   finishfile(outfile, argc, argv);
15334 }
15335 
15336 #endif /* not TRILIBRARY */
15337 
15338 /**                                                                         **/
15339 /**                                                                         **/
15340 /********* File I/O routines end here                                *********/
15341 
15342 /*****************************************************************************/
15343 /*                                                                           */
15344 /*  quality_statistics()   Print statistics about the quality of the mesh.   */
15345 /*                                                                           */
15346 /*****************************************************************************/
15347 
15348 #ifdef ANSI_DECLARATORS
15349 void quality_statistics(struct mesh *m, struct behavior *b)
15350 #else /* not ANSI_DECLARATORS */
15351 void quality_statistics(m, b)
15352 struct mesh *m;
15353 struct behavior *b;
15354 #endif /* not ANSI_DECLARATORS */
15355 
15356 {
15357   struct otri triangleloop;
15358   vertex p[3];
15359   REAL cossquaretable[8];
15360   REAL ratiotable[16];
15361   REAL dx[3], dy[3];
15362   REAL edgelength[3];
15363   REAL dotproduct;
15364   REAL cossquare;
15365   REAL triarea;
15366   REAL shortest, longest;
15367   REAL trilongest2;
15368   REAL smallestarea, biggestarea;
15369   REAL triminaltitude2;
15370   REAL minaltitude;
15371   REAL triaspect2;
15372   REAL worstaspect;
15373   REAL smallestangle, biggestangle;
15374   REAL radconst, degconst;
15375   int angletable[18];
15376   int aspecttable[16];
15377   int aspectindex;
15378   int tendegree;
15379   int acutebiggest;
15380   int i, ii, j, k;
15381 
15382   printf("Mesh quality statistics:\n\n");
15383   radconst = PI / 18.0;
15384   degconst = 180.0 / PI;
15385   for (i = 0; i < 8; i++) {
15386     cossquaretable[i] = cos(radconst * (REAL) (i + 1));
15387     cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
15388   }
15389   for (i = 0; i < 18; i++) {
15390     angletable[i] = 0;
15391   }
15392 
15393   ratiotable[0]  =      1.5;      ratiotable[1]  =     2.0;
15394   ratiotable[2]  =      2.5;      ratiotable[3]  =     3.0;
15395   ratiotable[4]  =      4.0;      ratiotable[5]  =     6.0;
15396   ratiotable[6]  =     10.0;      ratiotable[7]  =    15.0;
15397   ratiotable[8]  =     25.0;      ratiotable[9]  =    50.0;
15398   ratiotable[10] =    100.0;      ratiotable[11] =   300.0;
15399   ratiotable[12] =   1000.0;      ratiotable[13] = 10000.0;
15400   ratiotable[14] = 100000.0;      ratiotable[15] =     0.0;
15401   for (i = 0; i < 16; i++) {
15402     aspecttable[i] = 0;
15403   }
15404 
15405   worstaspect = 0.0;
15406   minaltitude = m->xmax - m->xmin + m->ymax - m->ymin;
15407   minaltitude = minaltitude * minaltitude;
15408   shortest = minaltitude;
15409   longest = 0.0;
15410   smallestarea = minaltitude;
15411   biggestarea = 0.0;
15412   worstaspect = 0.0;
15413   smallestangle = 0.0;
15414   biggestangle = 2.0;
15415   acutebiggest = 1;
15416 
15417   traversalinit(&m->triangles);
15418   triangleloop.tri = triangletraverse(m);
15419   triangleloop.orient = 0;
15420   while (triangleloop.tri != (triangle *) NULL) {
15421     org(triangleloop, p[0]);
15422     dest(triangleloop, p[1]);
15423     apex(triangleloop, p[2]);
15424     trilongest2 = 0.0;
15425 
15426     for (i = 0; i < 3; i++) {
15427       j = plus1mod3[i];
15428       k = minus1mod3[i];
15429       dx[i] = p[j][0] - p[k][0];
15430       dy[i] = p[j][1] - p[k][1];
15431       edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
15432       if (edgelength[i] > trilongest2) {
15433         trilongest2 = edgelength[i];
15434       }
15435       if (edgelength[i] > longest) {
15436         longest = edgelength[i];
15437       }
15438       if (edgelength[i] < shortest) {
15439         shortest = edgelength[i];
15440       }
15441     }
15442 
15443     triarea = counterclockwise(m, b, p[0], p[1], p[2]);
15444     if (triarea < smallestarea) {
15445       smallestarea = triarea;
15446     }
15447     if (triarea > biggestarea) {
15448       biggestarea = triarea;
15449     }
15450     triminaltitude2 = triarea * triarea / trilongest2;
15451     if (triminaltitude2 < minaltitude) {
15452       minaltitude = triminaltitude2;
15453     }
15454     triaspect2 = trilongest2 / triminaltitude2;
15455     if (triaspect2 > worstaspect) {
15456       worstaspect = triaspect2;
15457     }
15458     aspectindex = 0;
15459     while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
15460            && (aspectindex < 15)) {
15461       aspectindex++;
15462     }
15463     aspecttable[aspectindex]++;
15464 
15465     for (i = 0; i < 3; i++) {
15466       j = plus1mod3[i];
15467       k = minus1mod3[i];
15468       dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
15469       cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
15470       tendegree = 8;
15471       for (ii = 7; ii >= 0; ii--) {
15472         if (cossquare > cossquaretable[ii]) {
15473           tendegree = ii;
15474         }
15475       }
15476       if (dotproduct <= 0.0) {
15477         angletable[tendegree]++;
15478         if (cossquare > smallestangle) {
15479           smallestangle = cossquare;
15480         }
15481         if (acutebiggest && (cossquare < biggestangle)) {
15482           biggestangle = cossquare;
15483         }
15484       } else {
15485         angletable[17 - tendegree]++;
15486         if (acutebiggest || (cossquare > biggestangle)) {
15487           biggestangle = cossquare;
15488           acutebiggest = 0;
15489         }
15490       }
15491     }
15492     triangleloop.tri = triangletraverse(m);
15493   }
15494 
15495   shortest = sqrt(shortest);
15496   longest = sqrt(longest);
15497   minaltitude = sqrt(minaltitude);
15498   worstaspect = sqrt(worstaspect);
15499   smallestarea *= 0.5;
15500   biggestarea *= 0.5;
15501   if (smallestangle >= 1.0) {
15502     smallestangle = 0.0;
15503   } else {
15504     smallestangle = degconst * acos(sqrt(smallestangle));
15505   }
15506   if (biggestangle >= 1.0) {
15507     biggestangle = 180.0;
15508   } else {
15509     if (acutebiggest) {
15510       biggestangle = degconst * acos(sqrt(biggestangle));
15511     } else {
15512       biggestangle = 180.0 - degconst * acos(sqrt(biggestangle));
15513     }
15514   }
15515 
15516   printf("  Smallest area: %16.5g   |  Largest area: %16.5g\n",
15517          smallestarea, biggestarea);
15518   printf("  Shortest edge: %16.5g   |  Longest edge: %16.5g\n",
15519          shortest, longest);
15520   printf("  Shortest altitude: %12.5g   |  Largest aspect ratio: %8.5g\n\n",
15521          minaltitude, worstaspect);
15522 
15523   printf("  Triangle aspect ratio histogram:\n");
15524   printf("  1.1547 - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15525          ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
15526          aspecttable[8]);
15527   for (i = 1; i < 7; i++) {
15528     printf("  %6.6g - %-6.6g    :  %8d    | %6.6g - %-6.6g     :  %8d\n",
15529            ratiotable[i - 1], ratiotable[i], aspecttable[i],
15530            ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
15531   }
15532   printf("  %6.6g - %-6.6g    :  %8d    | %6.6g -            :  %8d\n",
15533          ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
15534          aspecttable[15]);
15535   printf("  (Aspect ratio is longest edge divided by shortest altitude)\n\n");
15536 
15537   printf("  Smallest angle: %15.5g   |  Largest angle: %15.5g\n\n",
15538          smallestangle, biggestangle);
15539 
15540   printf("  Angle histogram:\n");
15541   for (i = 0; i < 9; i++) {
15542     printf("    %3d - %3d degrees:  %8d    |    %3d - %3d degrees:  %8d\n",
15543            i * 10, i * 10 + 10, angletable[i],
15544            i * 10 + 90, i * 10 + 100, angletable[i + 9]);
15545   }
15546   printf("\n");
15547 }
15548 
15549 /*****************************************************************************/
15550 /*                                                                           */
15551 /*  statistics()   Print all sorts of cool facts.                            */
15552 /*                                                                           */
15553 /*****************************************************************************/
15554 
15555 #ifdef ANSI_DECLARATORS
15556 void statistics(struct mesh *m, struct behavior *b)
15557 #else /* not ANSI_DECLARATORS */
15558 void statistics(m, b)
15559 struct mesh *m;
15560 struct behavior *b;
15561 #endif /* not ANSI_DECLARATORS */
15562 
15563 {
15564   printf("\nStatistics:\n\n");
15565   printf("  Input vertices: %d\n", m->invertices);
15566   if (b->refine) {
15567     printf("  Input triangles: %d\n", m->inelements);
15568   }
15569   if (b->poly) {
15570     printf("  Input segments: %d\n", m->insegments);
15571     if (!b->refine) {
15572       printf("  Input holes: %d\n", m->holes);
15573     }
15574   }
15575 
15576   printf("\n  Mesh vertices: %ld\n", m->vertices.items - m->undeads);
15577   printf("  Mesh triangles: %ld\n", m->triangles.items);
15578   printf("  Mesh edges: %ld\n", m->edges);
15579   printf("  Mesh exterior boundary edges: %ld\n", m->hullsize);
15580   if (b->poly || b->refine) {
15581     printf("  Mesh interior boundary edges: %ld\n",
15582            m->subsegs.items - m->hullsize);
15583     printf("  Mesh subsegments (constrained edges): %ld\n",
15584            m->subsegs.items);
15585   }
15586   printf("\n");
15587 
15588   if (b->verbose) {
15589     quality_statistics(m, b);
15590     printf("Memory allocation statistics:\n\n");
15591     printf("  Maximum number of vertices: %ld\n", m->vertices.maxitems);
15592     printf("  Maximum number of triangles: %ld\n", m->triangles.maxitems);
15593     if (m->subsegs.maxitems > 0) {
15594       printf("  Maximum number of subsegments: %ld\n", m->subsegs.maxitems);
15595     }
15596     if (m->viri.maxitems > 0) {
15597       printf("  Maximum number of viri: %ld\n", m->viri.maxitems);
15598     }
15599     if (m->badsubsegs.maxitems > 0) {
15600       printf("  Maximum number of encroached subsegments: %ld\n",
15601              m->badsubsegs.maxitems);
15602     }
15603     if (m->badtriangles.maxitems > 0) {
15604       printf("  Maximum number of bad triangles: %ld\n",
15605              m->badtriangles.maxitems);
15606     }
15607     if (m->flipstackers.maxitems > 0) {
15608       printf("  Maximum number of stacked triangle flips: %ld\n",
15609              m->flipstackers.maxitems);
15610     }
15611     if (m->splaynodes.maxitems > 0) {
15612       printf("  Maximum number of splay tree nodes: %ld\n",
15613              m->splaynodes.maxitems);
15614     }
15615     printf("  Approximate heap memory use (bytes): %ld\n\n",
15616            m->vertices.maxitems * m->vertices.itembytes +
15617            m->triangles.maxitems * m->triangles.itembytes +
15618            m->subsegs.maxitems * m->subsegs.itembytes +
15619            m->viri.maxitems * m->viri.itembytes +
15620            m->badsubsegs.maxitems * m->badsubsegs.itembytes +
15621            m->badtriangles.maxitems * m->badtriangles.itembytes +
15622            m->flipstackers.maxitems * m->flipstackers.itembytes +
15623            m->splaynodes.maxitems * m->splaynodes.itembytes);
15624 
15625     printf("Algorithmic statistics:\n\n");
15626     if (!b->weighted) {
15627       printf("  Number of incircle tests: %ld\n", m->incirclecount);
15628     } else {
15629       printf("  Number of 3D orientation tests: %ld\n", m->orient3dcount);
15630     }
15631     printf("  Number of 2D orientation tests: %ld\n", m->counterclockcount);
15632     if (m->hyperbolacount > 0) {
15633       printf("  Number of right-of-hyperbola tests: %ld\n",
15634              m->hyperbolacount);
15635     }
15636     if (m->circletopcount > 0) {
15637       printf("  Number of circle top computations: %ld\n",
15638              m->circletopcount);
15639     }
15640     if (m->circumcentercount > 0) {
15641       printf("  Number of triangle circumcenter computations: %ld\n",
15642              m->circumcentercount);
15643     }
15644     printf("\n");
15645   }
15646 }
15647 
15648 /*****************************************************************************/
15649 /*                                                                           */
15650 /*  main() or triangulate()   Gosh, do everything.                           */
15651 /*                                                                           */
15652 /*  The sequence is roughly as follows.  Many of these steps can be skipped, */
15653 /*  depending on the command line switches.                                  */
15654 /*                                                                           */
15655 /*  - Initialize constants and parse the command line.                       */
15656 /*  - Read the vertices from a file and either                               */
15657 /*    - triangulate them (no -r), or                                         */
15658 /*    - read an old mesh from files and reconstruct it (-r).                 */
15659 /*  - Insert the PSLG segments (-p), and possibly segments on the convex     */
15660 /*      hull (-c).                                                           */
15661 /*  - Read the holes (-p), regional attributes (-pA), and regional area      */
15662 /*      constraints (-pa).  Carve the holes and concavities, and spread the  */
15663 /*      regional attributes and area constraints.                            */
15664 /*  - Enforce the constraints on minimum angle (-q) and maximum area (-a).   */
15665 /*      Also enforce the conforming Delaunay property (-q and -a).           */
15666 /*  - Compute the number of edges in the resulting mesh.                     */
15667 /*  - Promote the mesh's linear triangles to higher order elements (-o).     */
15668 /*  - Write the output files and print the statistics.                       */
15669 /*  - Check the consistency and Delaunay property of the mesh (-C).          */
15670 /*                                                                           */
15671 /*****************************************************************************/
15672 
15673 #ifdef TRILIBRARY
15674 
15675 #ifdef ANSI_DECLARATORS
15676 void triangulate(char *triswitches, struct triangulateio *in,
15677                  struct triangulateio *out, struct triangulateio *vorout)
15678 #else /* not ANSI_DECLARATORS */
15679 void triangulate(triswitches, in, out, vorout)
15680 char *triswitches;
15681 struct triangulateio *in;
15682 struct triangulateio *out;
15683 struct triangulateio *vorout;
15684 #endif /* not ANSI_DECLARATORS */
15685 
15686 #else /* not TRILIBRARY */
15687 
15688 #ifdef ANSI_DECLARATORS
15689 int main(int argc, char **argv)
15690 #else /* not ANSI_DECLARATORS */
15691 int main(argc, argv)
15692 int argc;
15693 char **argv;
15694 #endif /* not ANSI_DECLARATORS */
15695 
15696 #endif /* not TRILIBRARY */
15697 
15698 {
15699   struct mesh m;
15700   struct behavior b;
15701   REAL *holearray;                                        /* Array of holes. */
15702   REAL *regionarray;   /* Array of regional attributes and area constraints. */
15703 #ifndef TRILIBRARY
15704   FILE *polyfile;
15705 #endif /* not TRILIBRARY */
15706 #ifndef NO_TIMER
15707   /* Variables for timing the performance of Triangle.  The types are */
15708   /*   defined in sys/time.h.                                         */
15709   struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
15710   struct timezone tz;
15711 #endif /* not NO_TIMER */
15712 
15713 #ifndef NO_TIMER
15714   gettimeofday(&tv0, &tz);
15715 #endif /* not NO_TIMER */
15716 
15717   triangleinit(&m);
15718 #ifdef TRILIBRARY
15719   parsecommandline(1, &triswitches, &b);
15720 #else /* not TRILIBRARY */
15721   parsecommandline(argc, argv, &b);
15722 #endif /* not TRILIBRARY */
15723   m.steinerleft = b.steiner;
15724 
15725 #ifdef TRILIBRARY
15726   transfernodes(&m, &b, in->pointlist, in->pointattributelist,
15727                 in->pointmarkerlist, in->numberofpoints,
15728                 in->numberofpointattributes);
15729 #else /* not TRILIBRARY */
15730   readnodes(&m, &b, b.innodefilename, b.inpolyfilename, &polyfile);
15731 #endif /* not TRILIBRARY */
15732 
15733 #ifndef NO_TIMER
15734   if (!b.quiet) {
15735     gettimeofday(&tv1, &tz);
15736   }
15737 #endif /* not NO_TIMER */
15738 
15739 #ifdef CDT_ONLY
15740   m.hullsize = delaunay(&m, &b);                /* Triangulate the vertices. */
15741 #else /* not CDT_ONLY */
15742   if (b.refine) {
15743     /* Read and reconstruct a mesh. */
15744 #ifdef TRILIBRARY
15745     m.hullsize = reconstruct(&m, &b, in->trianglelist,
15746                              in->triangleattributelist, in->trianglearealist,
15747                              in->numberoftriangles, in->numberofcorners,
15748                              in->numberoftriangleattributes,
15749                              in->segmentlist, in->segmentmarkerlist,
15750                              in->numberofsegments);
15751 #else /* not TRILIBRARY */
15752     m.hullsize = reconstruct(&m, &b, b.inelefilename, b.areafilename,
15753                              b.inpolyfilename, polyfile);
15754 #endif /* not TRILIBRARY */
15755   } else {
15756     m.hullsize = delaunay(&m, &b);              /* Triangulate the vertices. */
15757   }
15758 #endif /* not CDT_ONLY */
15759 
15760 #ifndef NO_TIMER
15761   if (!b.quiet) {
15762     gettimeofday(&tv2, &tz);
15763     if (b.refine) {
15764       printf("Mesh reconstruction");
15765     } else {
15766       printf("Delaunay");
15767     }
15768     printf(" milliseconds:  %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) +
15769            (tv2.tv_usec - tv1.tv_usec) / 1000l);
15770   }
15771 #endif /* not NO_TIMER */
15772 
15773   /* Ensure that no vertex can be mistaken for a triangular bounding */
15774   /*   box vertex in insertvertex().                                 */
15775   m.infvertex1 = (vertex) NULL;
15776   m.infvertex2 = (vertex) NULL;
15777   m.infvertex3 = (vertex) NULL;
15778 
15779   if (b.usesegments) {
15780     m.checksegments = 1;                /* Segments will be introduced next. */
15781     if (!b.refine) {
15782       /* Insert PSLG segments and/or convex hull segments. */
15783 #ifdef TRILIBRARY
15784       formskeleton(&m, &b, in->segmentlist,
15785                    in->segmentmarkerlist, in->numberofsegments);
15786 #else /* not TRILIBRARY */
15787       formskeleton(&m, &b, polyfile, b.inpolyfilename);
15788 #endif /* not TRILIBRARY */
15789     }
15790   }
15791 
15792 #ifndef NO_TIMER
15793   if (!b.quiet) {
15794     gettimeofday(&tv3, &tz);
15795     if (b.usesegments && !b.refine) {
15796       printf("Segment milliseconds:  %ld\n",
15797              1000l * (tv3.tv_sec - tv2.tv_sec) +
15798              (tv3.tv_usec - tv2.tv_usec) / 1000l);
15799     }
15800   }
15801 #endif /* not NO_TIMER */
15802 
15803   if (b.poly && (m.triangles.items > 0)) {
15804 #ifdef TRILIBRARY
15805     holearray = in->holelist;
15806     m.holes = in->numberofholes;
15807     regionarray = in->regionlist;
15808     m.regions = in->numberofregions;
15809 #else /* not TRILIBRARY */
15810     readholes(&m, &b, polyfile, b.inpolyfilename, &holearray, &m.holes,
15811               &regionarray, &m.regions);
15812 #endif /* not TRILIBRARY */
15813     if (!b.refine) {
15814       /* Carve out holes and concavities. */
15815       carveholes(&m, &b, holearray, m.holes, regionarray, m.regions);
15816     }
15817   } else {
15818     /* Without a PSLG, there can be no holes or regional attributes   */
15819     /*   or area constraints.  The following are set to zero to avoid */
15820     /*   an accidental free() later.                                  */
15821     m.holes = 0;
15822     m.regions = 0;
15823   }
15824 
15825 #ifndef NO_TIMER
15826   if (!b.quiet) {
15827     gettimeofday(&tv4, &tz);
15828     if (b.poly && !b.refine) {
15829       printf("Hole milliseconds:  %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) +
15830              (tv4.tv_usec - tv3.tv_usec) / 1000l);
15831     }
15832   }
15833 #endif /* not NO_TIMER */
15834 
15835 #ifndef CDT_ONLY
15836   if (b.quality && (m.triangles.items > 0)) {
15837     enforcequality(&m, &b);           /* Enforce angle and area constraints. */
15838   }
15839 #endif /* not CDT_ONLY */
15840 
15841 #ifndef NO_TIMER
15842   if (!b.quiet) {
15843     gettimeofday(&tv5, &tz);
15844 #ifndef CDT_ONLY
15845     if (b.quality) {
15846       printf("Quality milliseconds:  %ld\n",
15847              1000l * (tv5.tv_sec - tv4.tv_sec) +
15848              (tv5.tv_usec - tv4.tv_usec) / 1000l);
15849     }
15850 #endif /* not CDT_ONLY */
15851   }
15852 #endif /* not NO_TIMER */
15853 
15854   /* Calculate the number of edges. */
15855   m.edges = (3l * m.triangles.items + m.hullsize) / 2l;
15856 
15857   if (b.order > 1) {
15858     highorder(&m, &b);       /* Promote elements to higher polynomial order. */
15859   }
15860   if (!b.quiet) {
15861     printf("\n");
15862   }
15863 
15864 #ifdef TRILIBRARY
15865   if (b.jettison) {
15866     out->numberofpoints = m.vertices.items - m.undeads;
15867   } else {
15868     out->numberofpoints = m.vertices.items;
15869   }
15870   out->numberofpointattributes = m.nextras;
15871   out->numberoftriangles = m.triangles.items;
15872   out->numberofcorners = (b.order + 1) * (b.order + 2) / 2;
15873   out->numberoftriangleattributes = m.eextras;
15874   out->numberofedges = m.edges;
15875   if (b.usesegments) {
15876     out->numberofsegments = m.subsegs.items;
15877   } else {
15878     out->numberofsegments = m.hullsize;
15879   }
15880   if (vorout != (struct triangulateio *) NULL) {
15881     vorout->numberofpoints = m.triangles.items;
15882     vorout->numberofpointattributes = m.nextras;
15883     vorout->numberofedges = m.edges;
15884   }
15885 #endif /* TRILIBRARY */
15886   /* If not using iteration numbers, don't write a .node file if one was */
15887   /*   read, because the original one would be overwritten!              */
15888   if (b.nonodewritten || (b.noiterationnum && m.readnodefile)) {
15889     if (!b.quiet) {
15890 #ifdef TRILIBRARY
15891       printf("NOT writing vertices.\n");
15892 #else /* not TRILIBRARY */
15893       printf("NOT writing a .node file.\n");
15894 #endif /* not TRILIBRARY */
15895     }
15896     numbernodes(&m, &b);         /* We must remember to number the vertices. */
15897   } else {
15898     /* writenodes() numbers the vertices too. */
15899 #ifdef TRILIBRARY
15900     writenodes(&m, &b, &out->pointlist, &out->pointattributelist,
15901                &out->pointmarkerlist);
15902 #else /* not TRILIBRARY */
15903     writenodes(&m, &b, b.outnodefilename, argc, argv);
15904 #endif /* TRILIBRARY */
15905   }
15906   if (b.noelewritten) {
15907     if (!b.quiet) {
15908 #ifdef TRILIBRARY
15909       printf("NOT writing triangles.\n");
15910 #else /* not TRILIBRARY */
15911       printf("NOT writing an .ele file.\n");
15912 #endif /* not TRILIBRARY */
15913     }
15914   } else {
15915 #ifdef TRILIBRARY
15916     writeelements(&m, &b, &out->trianglelist, &out->triangleattributelist);
15917 #else /* not TRILIBRARY */
15918     writeelements(&m, &b, b.outelefilename, argc, argv);
15919 #endif /* not TRILIBRARY */
15920   }
15921   /* The -c switch (convex switch) causes a PSLG to be written */
15922   /*   even if none was read.                                  */
15923   if (b.poly || b.convex) {
15924     /* If not using iteration numbers, don't overwrite the .poly file. */
15925     if (b.nopolywritten || b.noiterationnum) {
15926       if (!b.quiet) {
15927 #ifdef TRILIBRARY
15928         printf("NOT writing segments.\n");
15929 #else /* not TRILIBRARY */
15930         printf("NOT writing a .poly file.\n");
15931 #endif /* not TRILIBRARY */
15932       }
15933     } else {
15934 #ifdef TRILIBRARY
15935       writepoly(&m, &b, &out->segmentlist, &out->segmentmarkerlist);
15936       out->numberofholes = m.holes;
15937       out->numberofregions = m.regions;
15938       if (b.poly) {
15939         out->holelist = in->holelist;
15940         out->regionlist = in->regionlist;
15941       } else {
15942         out->holelist = (REAL *) NULL;
15943         out->regionlist = (REAL *) NULL;
15944       }
15945 #else /* not TRILIBRARY */
15946       writepoly(&m, &b, b.outpolyfilename, holearray, m.holes, regionarray,
15947                 m.regions, argc, argv);
15948 #endif /* not TRILIBRARY */
15949     }
15950   }
15951 #ifndef TRILIBRARY
15952 #ifndef CDT_ONLY
15953   if (m.regions > 0) {
15954     trifree((VOID *) regionarray);
15955   }
15956 #endif /* not CDT_ONLY */
15957   if (m.holes > 0) {
15958     trifree((VOID *) holearray);
15959   }
15960   if (b.geomview) {
15961     writeoff(&m, &b, b.offfilename, argc, argv);
15962   }
15963 #endif /* not TRILIBRARY */
15964   if (b.edgesout) {
15965 #ifdef TRILIBRARY
15966     writeedges(&m, &b, &out->edgelist, &out->edgemarkerlist);
15967 #else /* not TRILIBRARY */
15968     writeedges(&m, &b, b.edgefilename, argc, argv);
15969 #endif /* not TRILIBRARY */
15970   }
15971   if (b.voronoi) {
15972 #ifdef TRILIBRARY
15973     writevoronoi(&m, &b, &vorout->pointlist, &vorout->pointattributelist,
15974                  &vorout->pointmarkerlist, &vorout->edgelist,
15975                  &vorout->edgemarkerlist, &vorout->normlist);
15976 #else /* not TRILIBRARY */
15977     writevoronoi(&m, &b, b.vnodefilename, b.vedgefilename, argc, argv);
15978 #endif /* not TRILIBRARY */
15979   }
15980   if (b.neighbors) {
15981 #ifdef TRILIBRARY
15982     writeneighbors(&m, &b, &out->neighborlist);
15983 #else /* not TRILIBRARY */
15984     writeneighbors(&m, &b, b.neighborfilename, argc, argv);
15985 #endif /* not TRILIBRARY */
15986   }
15987 
15988   if (!b.quiet) {
15989 #ifndef NO_TIMER
15990     gettimeofday(&tv6, &tz);
15991     printf("\nOutput milliseconds:  %ld\n",
15992            1000l * (tv6.tv_sec - tv5.tv_sec) +
15993            (tv6.tv_usec - tv5.tv_usec) / 1000l);
15994     printf("Total running milliseconds:  %ld\n",
15995            1000l * (tv6.tv_sec - tv0.tv_sec) +
15996            (tv6.tv_usec - tv0.tv_usec) / 1000l);
15997 #endif /* not NO_TIMER */
15998 
15999     statistics(&m, &b);
16000   }
16001 
16002 #ifndef REDUCED
16003   if (b.docheck) {
16004     checkmesh(&m, &b);
16005     checkdelaunay(&m, &b);
16006   }
16007 #endif /* not REDUCED */
16008 
16009   triangledeinit(&m, &b);
16010 #ifndef TRILIBRARY
16011   return 0;
16012 #endif /* not TRILIBRARY */
16013 }
16014