TINA_tools  5
TINAmachinevisionlibraries
tlvisTrn_triangle.c
Go to the documentation of this file.
00001 /*****************************************************************************/
00002 /*                                                                           */
00003 /*      888888888        ,o,                          / 888                  */
00004 /*         888    88o88o  "    o8888o  88o8888o o88888o 888  o88888o         */
00005 /*         888    888    888       88b 888  888 888 888 888 d888  88b        */
00006 /*         888    888    888  o88^o888 888  888 "88888" 888 8888oo888        */
00007 /*         888    888    888 C888  888 888  888  /      888 q888             */
00008 /*         888    888    888  "88o^888 888  888 Cb      888  "88oooo"        */
00009 /*                                              "8oo8D                       */
00010 /*                                                                           */
00011 /*  A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.      */
00012 /*  (triangle.c)                                                             */
00013 /*                                                                           */
00014 /*  Version 1.3                                                              */
00015 /*  July 19, 1996                                                            */
00016 /*                                                                           */
00017 /*  Copyright 1996                                                           */
00018 /*  Jonathan Richard Shewchuk                                                */
00019 /*  School of Computer Science                                               */
00020 /*  Carnegie Mellon University                                               */
00021 /*  5000 Forbes Avenue                                                       */
00022 /*  Pittsburgh, Pennsylvania  15213-3891                                     */
00023 /*  jrs@cs.cmu.edu                                                           */
00024 /*                                                                           */
00025 /*  This program may be freely redistributed under the condition that the    */
00026 /*    copyright notices (including this entire header and the copyright      */
00027 /*    notice printed when the `-h' switch is selected) are not removed, and  */
00028 /*    no compensation is received.  Private, research, and institutional     */
00029 /*    use is free.  You may distribute modified versions of this code UNDER  */
00030 /*    THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE   */
00031 /*    SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE   */
00032 /*    AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR    */
00033 /*    NOTICE IS GIVEN OF THE MODIFICATIONS.  Distribution of this code as    */
00034 /*    part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT  */
00035 /*    WITH THE AUTHOR.  (If you are not directly supplying this code to a    */
00036 /*    customer, and you are instead telling them how they can obtain it for  */
00037 /*    free, then you are not required to make any arrangement with me.)      */
00038 /*                                                                           */
00039 /*  Hypertext instructions for Triangle are available on the Web at          */
00040 /*                                                                           */
00041 /*      http://www.cs.cmu.edu/~quake/triangle.html                           */
00042 /*                                                                           */
00043 /*  Some of the references listed below are marked [*].  These are available */
00044 /*    for downloading from the Web page                                      */
00045 /*                                                                           */
00046 /*      http://www.cs.cmu.edu/~quake/triangle.research.html                  */
00047 /*                                                                           */
00048 /*  A paper discussing some aspects of Triangle is available.  See Jonathan  */
00049 /*    Richard Shewchuk, "Triangle:  Engineering a 2D Quality Mesh Generator  */
00050 /*    and Delaunay Triangulator," First Workshop on Applied Computational    */
00051 /*    Geometry, ACM, May 1996.  [*]                                          */
00052 /*                                                                           */
00053 /*  Triangle was created as part of the Archimedes project in the School of  */
00054 /*    Computer Science at Carnegie Mellon University.  Archimedes is a       */
00055 /*    system for compiling parallel finite element solvers.  For further     */
00056 /*    information, see Anja Feldmann, Omar Ghattas, John R. Gilbert, Gary L. */
00057 /*    Miller, David R. O'Hallaron, Eric J. Schwabe, Jonathan R. Shewchuk,    */
00058 /*    and Shang-Hua Teng, "Automated Parallel Solution of Unstructured PDE   */
00059 /*    Problems."  To appear in Communications of the ACM, we hope.           */
00060 /*                                                                           */
00061 /*  The quality mesh generation algorithm is due to Jim Ruppert, "A          */
00062 /*    Delaunay Refinement Algorithm for Quality 2-Dimensional Mesh           */
00063 /*    Generation," Journal of Algorithms 18(3):548-585, May 1995.  [*]       */
00064 /*                                                                           */
00065 /*  My implementation of the divide-and-conquer and incremental Delaunay     */
00066 /*    triangulation algorithms follows closely the presentation of Guibas    */
00067 /*    and Stolfi, even though I use a triangle-based data structure instead  */
00068 /*    of their quad-edge data structure.  (In fact, I originally implemented */
00069 /*    Triangle using the quad-edge data structure, but switching to a        */
00070 /*    triangle-based data structure sped Triangle by a factor of two.)  The  */
00071 /*    mesh manipulation primitives and the two aforementioned Delaunay       */
00072 /*    triangulation algorithms are described by Leonidas J. Guibas and Jorge */
00073 /*    Stolfi, "Primitives for the Manipulation of General Subdivisions and   */
00074 /*    the Computation of Voronoi Diagrams," ACM Transactions on Graphics     */
00075 /*    4(2):74-123, April 1985.                                               */
00076 /*                                                                           */
00077 /*  Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai   */
00078 /*    Lee and Bruce J. Schachter, "Two Algorithms for Constructing the       */
00079 /*    Delaunay Triangulation," International Journal of Computer and         */
00080 /*    Information Science 9(3):219-242, 1980.  The idea to improve the       */
00081 /*    divide-and-conquer algorithm by alternating between vertical and       */
00082 /*    horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and-  */
00083 /*    Conquer Algorithm for Constructing Delaunay Triangulations,"           */
00084 /*    Algorithmica 2(2):137-151, 1987.                                       */
00085 /*                                                                           */
00086 /*  The incremental insertion algorithm was first proposed by C. L. Lawson,  */
00087 /*    "Software for C1 Surface Interpolation," in Mathematical Software III, */
00088 /*    John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977.     */
00089 /*    For point location, I use the algorithm of Ernst P. Mucke, Isaac       */
00090 /*    Saias, and Binhai Zhu, "Fast Randomized Point Location Without         */
00091 /*    Preprocessing in Two- and Three-dimensional Delaunay Triangulations,"  */
00092 /*    Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
00093 /*    ACM, May 1996.  [*]  If I were to randomize the order of point         */
00094 /*    insertion (I currently don't bother), their result combined with the   */
00095 /*    result of Leonidas J. Guibas, Donald E. Knuth, and Micha Sharir,       */
00096 /*    "Randomized Incremental Construction of Delaunay and Voronoi           */
00097 /*    Diagrams," Algorithmica 7(4):381-413, 1992, would yield an expected    */
00098 /*    O(n^{4/3}) bound on running time.                                      */
00099 /*                                                                           */
00100 /*  The O(n log n) sweepline Delaunay triangulation algorithm is taken from  */
00101 /*    Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams",          */
00102 /*    Algorithmica 2(2):153-174, 1987.  A random sample of edges on the      */
00103 /*    boundary of the triangulation are maintained in a splay tree for the   */
00104 /*    purpose of point location.  Splay trees are described by Daniel        */
00105 /*    Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
00106 /*    Trees," Journal of the ACM 32(3):652-686, July 1985.                   */
00107 /*                                                                           */
00108 /*  The algorithms for exact computation of the signs of determinants are    */
00109 /*    described in Jonathan Richard Shewchuk, "Adaptive Precision Floating-  */
00110 /*    Point Arithmetic and Fast Robust Geometric Predicates," Technical      */
00111 /*    Report CMU-CS-96-140, School of Computer Science, Carnegie Mellon      */
00112 /*    University, Pittsburgh, Pennsylvania, May 1996.  [*]  (Submitted to    */
00113 /*    Discrete & Computational Geometry.)  An abbreviated version appears as */
00114 /*    Jonathan Richard Shewchuk, "Robust Adaptive Floating-Point Geometric   */
00115 /*    Predicates," Proceedings of the Twelfth Annual Symposium on Computa-   */
00116 /*    tional Geometry, ACM, May 1996.  [*]  Many of the ideas for my exact   */
00117 /*    arithmetic routines originate with Douglas M. Priest, "Algorithms for  */
00118 /*    Arbitrary Precision Floating Point Arithmetic," Tenth Symposium on     */
00119 /*    Computer Arithmetic, 132-143, IEEE Computer Society Press, 1991.  [*]  */
00120 /*    Many of the ideas for the correct evaluation of the signs of           */
00121 /*    determinants are taken from Steven Fortune and Christopher J. Van Wyk, */
00122 /*    "Efficient Exact Arithmetic for Computational Geometry," Proceedings   */
00123 /*    of the Ninth Annual Symposium on Computational Geometry, ACM,          */
00124 /*    pp. 163-172, May 1993, and from Steven Fortune, "Numerical Stability   */
00125 /*    of Algorithms for 2D Delaunay Triangulations," International Journal   */
00126 /*    of Computational Geometry & Applications 5(1-2):193-213, March-June    */
00127 /*    1995.                                                                  */
00128 /*                                                                           */
00129 /*  For definitions of and results involving Delaunay triangulations,        */
00130 /*    constrained and conforming versions thereof, and other aspects of      */
00131 /*    triangular mesh generation, see the excellent survey by Marshall Bern  */
00132 /*    and David Eppstein, "Mesh Generation and Optimal Triangulation," in    */
00133 /*    Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang,         */
00134 /*    editors, World Scientific, Singapore, pp. 23-90, 1992.                 */
00135 /*                                                                           */
00136 /*  The time for incrementally adding PSLG (planar straight line graph)      */
00137 /*    segments to create a constrained Delaunay triangulation is probably    */
00138 /*    O(n^2) per segment in the worst case and O(n) per edge in the common   */
00139 /*    case, where n is the number of triangles that intersect the segment    */
00140 /*    before it is inserted.  This doesn't count point location, which can   */
00141 /*    be much more expensive.  (This note does not apply to conforming       */
00142 /*    Delaunay triangulations, for which a different method is used to       */
00143 /*    insert segments.)                                                      */
00144 /*                                                                           */
00145 /*  The time for adding segments to a conforming Delaunay triangulation is   */
00146 /*    not clear, but does not depend upon n alone.  In some cases, very      */
00147 /*    small features (like a point lying next to a segment) can cause a      */
00148 /*    single segment to be split an arbitrary number of times.  Of course,   */
00149 /*    floating-point precision is a practical barrier to how much this can   */
00150 /*    happen.                                                                */
00151 /*                                                                           */
00152 /*  The time for deleting a point from a Delaunay triangulation is O(n^2) in */
00153 /*    the worst case and O(n) in the common case, where n is the degree of   */
00154 /*    the point being deleted.  I could improve this to expected O(n) time   */
00155 /*    by "inserting" the neighboring vertices in random order, but n is      */
00156 /*    usually quite small, so it's not worth the bother.  (The O(n) time     */
00157 /*    for random insertion follows from L. Paul Chew, "Building Voronoi      */
00158 /*    Diagrams for Convex Polygons in Linear Expected Time," Technical       */
00159 /*    Report PCS-TR90-147, Department of Mathematics and Computer Science,   */
00160 /*    Dartmouth College, 1990.                                               */
00161 /*                                                                           */
00162 /*  Ruppert's Delaunay refinement algorithm typically generates triangles    */
00163 /*    at a linear rate (constant time per triangle) after the initial        */
00164 /*    triangulation is formed.  There may be pathological cases where more   */
00165 /*    time is required, but these never arise in practice.                   */
00166 /*                                                                           */
00167 /*  The segment intersection formulae are straightforward.  If you want to   */
00168 /*    see them derived, see Franklin Antonio.  "Faster Line Segment          */
00169 /*    Intersection."  In Graphics Gems III (David Kirk, editor), pp. 199-    */
00170 /*    202.  Academic Press, Boston, 1992.                                    */
00171 /*                                                                           */
00172 /*  If you make any improvements to this code, please please please let me   */
00173 /*    know, so that I may obtain the improvements.  Even if you don't change */
00174 /*    the code, I'd still love to hear what it's being used for.             */
00175 /*                                                                           */
00176 /*  Disclaimer:  Neither I nor Carnegie Mellon warrant this code in any way  */
00177 /*    whatsoever.  This code is provided "as-is".  Use at your own risk.     */
00178 /*                                                                           */
00179 /*****************************************************************************/
00180 
00181 /* For single precision (which will save some memory and reduce paging),     */
00182 /*   define the symbol SINGLE by using the -DSINGLE compiler switch or by    */
00183 /*   writing "#define SINGLE" below.                                         */
00184 /*                                                                           */
00185 /* For double precision (which will allow you to refine meshes to a smaller  */
00186 /*   edge length), leave SINGLE undefined.                                   */
00187 /*                                                                           */
00188 /* Double precision uses more memory, but improves the resolution of the     */
00189 /*   meshes you can generate with Triangle.  It also reduces the likelihood  */
00190 /*   of a floating exception due to overflow.  Finally, it is much faster    */
00191 /*   than single precision on 64-bit architectures like the DEC Alpha.  I    */
00192 /*   recommend double precision unless you want to generate a mesh for which */
00193 /*   you do not have enough memory.                                          */
00194 
00195 /* #define SINGLE */
00196 
00197 #ifdef SINGLE
00198 #define REAL float
00199 #else /* not SINGLE */
00200 #define REAL double
00201 #endif /* not SINGLE */
00202 
00203 /* If yours is not a Unix system, define the NO_TIMER compiler switch to     */
00204 /*   remove the Unix-specific timing code.                                   */
00205 
00206 #define NO_TIMER 1
00207 
00208 /* To insert lots of self-checks for internal errors, define the SELF_CHECK  */
00209 /*   symbol.  This will slow down the program significantly.  It is best to  */
00210 /*   define the symbol using the -DSELF_CHECK compiler switch, but you could */
00211 /*   write "#define SELF_CHECK" below.  If you are modifying this code, I    */
00212 /*   recommend you turn self-checks on.                                      */
00213 
00214 /* #define SELF_CHECK */
00215 
00216 /* To compile Triangle as a callable object library (triangle.o), define the */
00217 /*   TRILIBRARY symbol.  Read the file triangle.h for details on how to call */
00218 /*   the procedure triangulate() that results.                               */
00219 
00220 #define TRILIBRARY
00221 
00222 /* It is possible to generate a smaller version of Triangle using one or     */
00223 /*   both of the following symbols.  Define the REDUCED symbol to eliminate  */
00224 /*   all features that are primarily of research interest; specifically, the */
00225 /*   -i, -F, -s, and -C switches.  Define the CDT_ONLY symbol to eliminate   */
00226 /*   all meshing algorithms above and beyond constrained Delaunay            */
00227 /*   triangulation; specifically, the -r, -q, -a, -S, and -s switches.       */
00228 /*   These reductions are most likely to be useful when generating an object */
00229 /*   library (triangle.o) by defining the TRILIBRARY symbol.                 */
00230 
00231 #define REDUCED
00232 #define CDT_ONLY
00233 
00234 /* On some machines, the exact arithmetic routines might be defeated by the  */
00235 /*   use of internal extended precision floating-point registers.  Sometimes */
00236 /*   this problem can be fixed by defining certain values to be volatile,    */
00237 /*   thus forcing them to be stored to memory and rounded off.  This isn't   */
00238 /*   a great solution, though, as it slows Triangle down.                    */
00239 /*                                                                           */
00240 /* To try this out, write "#define INEXACT volatile" below.  Normally,       */
00241 /*   however, INEXACT should be defined to be nothing.  ("#define INEXACT".) */
00242 
00243 #define INEXACT /* Nothing */
00244 /* #define INEXACT volatile */
00245 
00246 /* Maximum number of characters in a file name (including the null).         */
00247 
00248 #define FILENAMESIZE 512
00249 
00250 /* Maximum number of characters in a line read from a file (including the    */
00251 /*   null).                                                                  */
00252 
00253 #define INPUTLINESIZE 512
00254 
00255 /* For efficiency, a variety of data structures are allocated in bulk.  The  */
00256 /*   following constants determine how many of each structure is allocated   */
00257 /*   at once.                                                                */
00258 
00259 #define TRIPERBLOCK 4092           /* Number of triangles allocated at once. */
00260 #define SHELLEPERBLOCK 508       /* Number of shell edges allocated at once. */
00261 #define POINTPERBLOCK 4092            /* Number of points allocated at once. */
00262 #define VIRUSPERBLOCK 1020   /* Number of virus triangles allocated at once. */
00263 /* Number of encroached segments allocated at once. */
00264 #define BADSEGMENTPERBLOCK 252
00265 /* Number of skinny triangles allocated at once. */
00266 #define BADTRIPERBLOCK 4092
00267 /* Number of splay tree nodes allocated at once. */
00268 #define SPLAYNODEPERBLOCK 508
00269 
00270 /* The point marker DEADPOINT is an arbitrary number chosen large enough to  */
00271 /*   (hopefully) not conflict with user boundary markers.  Make sure that it */
00272 /*   is small enough to fit into your machine's integer size.                */
00273 
00274 #define DEADPOINT -1073741824
00275 
00276 /* The next line is used to outsmart some very stupid compilers.  If your    */
00277 /*   compiler is smarter, feel free to replace the "int" with "void".        */
00278 /*   Not that it matters.                                                    */
00279 
00280 #define VOID int
00281 
00282 /* Two constants for algorithms based on random sampling.  Both constants    */
00283 /*   have been chosen empirically to optimize their respective algorithms.   */
00284 
00285 /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide    */
00286 /*   how large a random sample of triangles to inspect.                      */
00287 #define SAMPLEFACTOR 11
00288 /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
00289 /*   of boundary edges should be maintained in the splay tree for point      */
00290 /*   location on the front.                                                  */
00291 #define SAMPLERATE 10
00292 
00293 /* A number that speaks for itself, every kissable digit.                    */
00294 
00295 #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
00296 
00297 /* Another fave.                                                             */
00298 
00299 #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
00300 
00301 /* And here's one for those of you who are intimidated by math.              */
00302 
00303 #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
00304 
00305 #include <stdio.h>
00306 #include <string.h>
00307 #include <math.h>
00308 #ifndef NO_TIMER
00309 #include <sys/time.h>
00310 #endif /* NO_TIMER */
00311 #ifdef TRILIBRARY
00312 #include <tinatool/tlvision/tlvisTrn_triangle.h>
00313 #endif /* TRILIBRARY */
00314 
00315 /* The following obscenity seems to be necessary to ensure that this program */
00316 /* will port to Dec Alphas running OSF/1, because their stdio.h file commits */
00317 /* the unpardonable sin of including stdlib.h.  Hence, malloc(), free(), and */
00318 /* exit() may or may not already be defined at this point.  I declare these  */
00319 /* functions explicitly because some non-ANSI C compilers lack stdlib.h.     */
00320 
00321 #ifndef _STDLIB_H_
00322 extern void *malloc();
00323 extern void free();
00324 extern void exit();
00325 extern double strtod();
00326 extern long strtol();
00327 #endif /* _STDLIB_H_ */
00328 
00329 /* A few forward declarations.                                               */
00330 
00331 void poolrestart();
00332 #ifndef TRILIBRARY
00333 char *freadline();
00334 char *findfield();
00335 #endif /* not TRILIBRARY */
00336 
00337 /* Labels that signify whether a record consists primarily of pointers or of */
00338 /*   floating-point words.  Used to make decisions about data alignment.     */
00339 
00340 enum wordtype {POINTER, FLOATINGPOINT};
00341 
00342 /* Labels that signify the result of point location.  The result of a        */
00343 /*   search indicates that the point falls in the interior of a triangle, on */
00344 /*   an edge, on a vertex, or outside the mesh.                              */
00345 
00346 enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
00347 
00348 /* Labels that signify the result of site insertion.  The result indicates   */
00349 /*   that the point was inserted with complete success, was inserted but     */
00350 /*   encroaches on a segment, was not inserted because it lies on a segment, */
00351 /*   or was not inserted because another point occupies the same location.   */
00352 
00353 enum insertsiteresult {SUCCESSFULPOINT, ENCROACHINGPOINT, VIOLATINGPOINT,
00354                        DUPLICATEPOINT};
00355 
00356 /* Labels that signify the result of direction finding.  The result          */
00357 /*   indicates that a segment connecting the two query points falls within   */
00358 /*   the direction triangle, along the left edge of the direction triangle,  */
00359 /*   or along the right edge of the direction triangle.                      */
00360 
00361 enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
00362 
00363 /* Labels that signify the result of the circumcenter computation routine.   */
00364 /*   The return value indicates which edge of the triangle is shortest.      */
00365 
00366 enum circumcenterresult {OPPOSITEORG, OPPOSITEDEST, OPPOSITEAPEX};
00367 
00368 /*****************************************************************************/
00369 /*                                                                           */
00370 /*  The basic mesh data structures                                           */
00371 /*                                                                           */
00372 /*  There are three:  points, triangles, and shell edges (abbreviated        */
00373 /*  `shelle').  These three data structures, linked by pointers, comprise    */
00374 /*  the mesh.  A point simply represents a point in space and its properties.*/
00375 /*  A triangle is a triangle.  A shell edge is a special data structure used */
00376 /*  to represent impenetrable segments in the mesh (including the outer      */
00377 /*  boundary, boundaries of holes, and internal boundaries separating two    */
00378 /*  triangulated regions).  Shell edges represent boundaries defined by the  */
00379 /*  user that triangles may not lie across.                                  */
00380 /*                                                                           */
00381 /*  A triangle consists of a list of three vertices, a list of three         */
00382 /*  adjoining triangles, a list of three adjoining shell edges (when shell   */
00383 /*  edges are used), an arbitrary number of optional user-defined floating-  */
00384 /*  point attributes, and an optional area constraint.  The latter is an     */
00385 /*  upper bound on the permissible area of each triangle in a region, used   */
00386 /*  for mesh refinement.                                                     */
00387 /*                                                                           */
00388 /*  For a triangle on a boundary of the mesh, some or all of the neighboring */
00389 /*  triangles may not be present.  For a triangle in the interior of the     */
00390 /*  mesh, often no neighboring shell edges are present.  Such absent         */
00391 /*  triangles and shell edges are never represented by NULL pointers; they   */
00392 /*  are represented by two special records:  `dummytri', the triangle that   */
00393 /*  fills "outer space", and `dummysh', the omnipresent shell edge.          */
00394 /*  `dummytri' and `dummysh' are used for several reasons; for instance,     */
00395 /*  they can be dereferenced and their contents examined without causing the */
00396 /*  memory protection exception that would occur if NULL were dereferenced.  */
00397 /*                                                                           */
00398 /*  However, it is important to understand that a triangle includes other    */
00399 /*  information as well.  The pointers to adjoining vertices, triangles, and */
00400 /*  shell edges are ordered in a way that indicates their geometric relation */
00401 /*  to each other.  Furthermore, each of these pointers contains orientation */
00402 /*  information.  Each pointer to an adjoining triangle indicates which face */
00403 /*  of that triangle is contacted.  Similarly, each pointer to an adjoining  */
00404 /*  shell edge indicates which side of that shell edge is contacted, and how */
00405 /*  the shell edge is oriented relative to the triangle.                     */
00406 /*                                                                           */
00407 /*  Shell edges are found abutting edges of triangles; either sandwiched     */
00408 /*  between two triangles, or resting against one triangle on an exterior    */
00409 /*  boundary or hole boundary.                                               */
00410 /*                                                                           */
00411 /*  A shell edge consists of a list of two vertices, a list of two           */
00412 /*  adjoining shell edges, and a list of two adjoining triangles.  One of    */
00413 /*  the two adjoining triangles may not be present (though there should      */
00414 /*  always be one), and neighboring shell edges might not be present.        */
00415 /*  Shell edges also store a user-defined integer "boundary marker".         */
00416 /*  Typically, this integer is used to indicate what sort of boundary        */
00417 /*  conditions are to be applied at that location in a finite element        */
00418 /*  simulation.                                                              */
00419 /*                                                                           */
00420 /*  Like triangles, shell edges maintain information about the relative      */
00421 /*  orientation of neighboring objects.                                      */
00422 /*                                                                           */
00423 /*  Points are relatively simple.  A point is a list of floating point       */
00424 /*  numbers, starting with the x, and y coordinates, followed by an          */
00425 /*  arbitrary number of optional user-defined floating-point attributes,     */
00426 /*  followed by an integer boundary marker.  During the segment insertion    */
00427 /*  phase, there is also a pointer from each point to a triangle that may    */
00428 /*  contain it.  Each pointer is not always correct, but when one is, it     */
00429 /*  speeds up segment insertion.  These pointers are assigned values once    */
00430 /*  at the beginning of the segment insertion phase, and are not used or     */
00431 /*  updated at any other time.  Edge swapping during segment insertion will  */
00432 /*  render some of them incorrect.  Hence, don't rely upon them for          */
00433 /*  anything.  For the most part, points do not have any information about   */
00434 /*  what triangles or shell edges they are linked to.                        */
00435 /*                                                                           */
00436 /*****************************************************************************/
00437 
00438 /*****************************************************************************/
00439 /*                                                                           */
00440 /*  Handles                                                                  */
00441 /*                                                                           */
00442 /*  The oriented triangle (`triedge') and oriented shell edge (`edge') data  */
00443 /*  structures defined below do not themselves store any part of the mesh.   */
00444 /*  The mesh itself is made of `triangle's, `shelle's, and `point's.         */
00445 /*                                                                           */
00446 /*  Oriented triangles and oriented shell edges will usually be referred to  */
00447 /*  as "handles".  A handle is essentially a pointer into the mesh; it       */
00448 /*  allows you to "hold" one particular part of the mesh.  Handles are used  */
00449 /*  to specify the regions in which one is traversing and modifying the mesh.*/
00450 /*  A single `triangle' may be held by many handles, or none at all.  (The   */
00451 /*  latter case is not a memory leak, because the triangle is still          */
00452 /*  connected to other triangles in the mesh.)                               */
00453 /*                                                                           */
00454 /*  A `triedge' is a handle that holds a triangle.  It holds a specific side */
00455 /*  of the triangle.  An `edge' is a handle that holds a shell edge.  It     */
00456 /*  holds either the left or right side of the edge.                         */
00457 /*                                                                           */
00458 /*  Navigation about the mesh is accomplished through a set of mesh          */
00459 /*  manipulation primitives, further below.  Many of these primitives take   */
00460 /*  a handle and produce a new handle that holds the mesh near the first     */
00461 /*  handle.  Other primitives take two handles and glue the corresponding    */
00462 /*  parts of the mesh together.  The exact position of the handles is        */
00463 /*  important.  For instance, when two triangles are glued together by the   */
00464 /*  bond() primitive, they are glued by the sides on which the handles lie.  */
00465 /*                                                                           */
00466 /*  Because points have no information about which triangles they are        */
00467 /*  attached to, I commonly represent a point by use of a handle whose       */
00468 /*  origin is the point.  A single handle can simultaneously represent a     */
00469 /*  triangle, an edge, and a point.                                          */
00470 /*                                                                           */
00471 /*****************************************************************************/
00472 
00473 /* The triangle data structure.  Each triangle contains three pointers to    */
00474 /*   adjoining triangles, plus three pointers to vertex points, plus three   */
00475 /*   pointers to shell edges (defined below; these pointers are usually      */
00476 /*   `dummysh').  It may or may not also contain user-defined attributes     */
00477 /*   and/or a floating-point "area constraint".  It may also contain extra   */
00478 /*   pointers for nodes, when the user asks for high-order elements.         */
00479 /*   Because the size and structure of a `triangle' is not decided until     */
00480 /*   runtime, I haven't simply defined the type `triangle' to be a struct.   */
00481 
00482 typedef REAL **triangle;            /* Really:  typedef triangle *triangle   */
00483 
00484 /* An oriented triangle:  includes a pointer to a triangle and orientation.  */
00485 /*   The orientation denotes an edge of the triangle.  Hence, there are      */
00486 /*   three possible orientations.  By convention, each edge is always        */
00487 /*   directed to point counterclockwise about the corresponding triangle.    */
00488 
00489 struct triedge {
00490   triangle *tri;
00491   int orient;                                         /* Ranges from 0 to 2. */
00492 };
00493 
00494 /* The shell data structure.  Each shell edge contains two pointers to       */
00495 /*   adjoining shell edges, plus two pointers to vertex points, plus two     */
00496 /*   pointers to adjoining triangles, plus one shell marker.                 */
00497 
00498 typedef REAL **shelle;                  /* Really:  typedef shelle *shelle   */
00499 
00500 /* An oriented shell edge:  includes a pointer to a shell edge and an        */
00501 /*   orientation.  The orientation denotes a side of the edge.  Hence, there */
00502 /*   are two possible orientations.  By convention, the edge is always       */
00503 /*   directed so that the "side" denoted is the right side of the edge.      */
00504 
00505 struct edge {
00506   shelle *sh;
00507   int shorient;                                       /* Ranges from 0 to 1. */
00508 };
00509 
00510 /* The point data structure.  Each point is actually an array of REALs.      */
00511 /*   The number of REALs is unknown until runtime.  An integer boundary      */
00512 /*   marker, and sometimes a pointer to a triangle, is appended after the    */
00513 /*   REALs.                                                                  */
00514 
00515 typedef REAL *point;
00516 
00517 /* A queue used to store encroached segments.  Each segment's vertices are   */
00518 /*   stored so that one can check whether a segment is still the same.       */
00519 
00520 struct badsegment {
00521   struct edge encsegment;                          /* An encroached segment. */
00522   point segorg, segdest;                                /* The two vertices. */
00523   struct badsegment *nextsegment;     /* Pointer to next encroached segment. */
00524 };
00525 
00526 /* A queue used to store bad triangles.  The key is the square of the cosine */
00527 /*   of the smallest angle of the triangle.  Each triangle's vertices are    */
00528 /*   stored so that one can check whether a triangle is still the same.      */
00529 
00530 struct badface {
00531   struct triedge badfacetri;                              /* A bad triangle. */
00532   REAL key;                             /* cos^2 of smallest (apical) angle. */
00533   point faceorg, facedest, faceapex;                  /* The three vertices. */
00534   struct badface *nextface;                 /* Pointer to next bad triangle. */
00535 };
00536 
00537 /* A node in a heap used to store events for the sweepline Delaunay          */
00538 /*   algorithm.  Nodes do not point directly to their parents or children in */
00539 /*   the heap.  Instead, each node knows its position in the heap, and can   */
00540 /*   look up its parent and children in a separate array.  The `eventptr'    */
00541 /*   points either to a `point' or to a triangle (in encoded format, so that */
00542 /*   an orientation is included).  In the latter case, the origin of the     */
00543 /*   oriented triangle is the apex of a "circle event" of the sweepline      */
00544 /*   algorithm.  To distinguish site events from circle events, all circle   */
00545 /*   events are given an invalid (smaller than `xmin') x-coordinate `xkey'.  */
00546 
00547 struct event {
00548   REAL xkey, ykey;                              /* Coordinates of the event. */
00549   VOID *eventptr;       /* Can be a point or the location of a circle event. */
00550   int heapposition;              /* Marks this event's position in the heap. */
00551 };
00552 
00553 /* A node in the splay tree.  Each node holds an oriented ghost triangle     */
00554 /*   that represents a boundary edge of the growing triangulation.  When a   */
00555 /*   circle event covers two boundary edges with a triangle, so that they    */
00556 /*   are no longer boundary edges, those edges are not immediately deleted   */
00557 /*   from the tree; rather, they are lazily deleted when they are next       */
00558 /*   encountered.  (Since only a random sample of boundary edges are kept    */
00559 /*   in the tree, lazy deletion is faster.)  `keydest' is used to verify     */
00560 /*   that a triangle is still the same as when it entered the splay tree; if */
00561 /*   it has been rotated (due to a circle event), it no longer represents a  */
00562 /*   boundary edge and should be deleted.                                    */
00563 
00564 struct splaynode {
00565   struct triedge keyedge;                  /* Lprev of an edge on the front. */
00566   point keydest;            /* Used to verify that splay node is still live. */
00567   struct splaynode *lchild, *rchild;              /* Children in splay tree. */
00568 };
00569 
00570 /* A type used to allocate memory.  firstblock is the first block of items.  */
00571 /*   nowblock is the block from which items are currently being allocated.   */
00572 /*   nextitem points to the next slab of free memory for an item.            */
00573 /*   deaditemstack is the head of a linked list (stack) of deallocated items */
00574 /*   that can be recycled.  unallocateditems is the number of items that     */
00575 /*   remain to be allocated from nowblock.                                   */
00576 /*                                                                           */
00577 /* Traversal is the process of walking through the entire list of items, and */
00578 /*   is separate from allocation.  Note that a traversal will visit items on */
00579 /*   the "deaditemstack" stack as well as live items.  pathblock points to   */
00580 /*   the block currently being traversed.  pathitem points to the next item  */
00581 /*   to be traversed.  pathitemsleft is the number of items that remain to   */
00582 /*   be traversed in pathblock.                                              */
00583 /*                                                                           */
00584 /* itemwordtype is set to POINTER or FLOATINGPOINT, and is used to suggest   */
00585 /*   what sort of word the record is primarily made up of.  alignbytes       */
00586 /*   determines how new records should be aligned in memory.  itembytes and  */
00587 /*   itemwords are the length of a record in bytes (after rounding up) and   */
00588 /*   words.  itemsperblock is the number of items allocated at once in a     */
00589 /*   single block.  items is the number of currently allocated items.        */
00590 /*   maxitems is the maximum number of items that have been allocated at     */
00591 /*   once; it is the current number of items plus the number of records kept */
00592 /*   on deaditemstack.                                                       */
00593 
00594 struct memorypool {
00595   VOID **firstblock, **nowblock;
00596   VOID *nextitem;
00597   VOID *deaditemstack;
00598   VOID **pathblock;
00599   VOID *pathitem;
00600   enum wordtype itemwordtype;
00601   int alignbytes;
00602   int itembytes, itemwords;
00603   int itemsperblock;
00604   long items, maxitems;
00605   int unallocateditems;
00606   int pathitemsleft;
00607 };
00608 
00609 /* Variables used to allocate memory for triangles, shell edges, points,     */
00610 /*   viri (triangles being eaten), bad (encroached) segments, bad (skinny    */
00611 /*   or too large) triangles, and splay tree nodes.                          */
00612 
00613 struct memorypool triangles;
00614 struct memorypool shelles;
00615 struct memorypool points;
00616 struct memorypool viri;
00617 struct memorypool badsegments;
00618 struct memorypool badtriangles;
00619 struct memorypool splaynodes;
00620 
00621 /* Variables that maintain the bad triangle queues.  The tails are pointers  */
00622 /*   to the pointers that have to be filled in to enqueue an item.           */
00623 
00624 struct badface *queuefront[64];
00625 struct badface **queuetail[64];
00626 
00627 REAL xmin, xmax, ymin, ymax;                              /* x and y bounds. */
00628 REAL xminextreme;        /* Nonexistent x value used as a flag in sweepline. */
00629 int inpoints;                                     /* Number of input points. */
00630 int inelements;                                /* Number of input triangles. */
00631 int insegments;                                 /* Number of input segments. */
00632 int holes;                                         /* Number of input holes. */
00633 int regions;                                     /* Number of input regions. */
00634 long edges;                                       /* Number of output edges. */
00635 int mesh_dim;                                  /* Dimension (ought to be 2). */
00636 int nextras;                              /* Number of attributes per point. */
00637 int eextras;                           /* Number of attributes per triangle. */
00638 long hullsize;                            /* Number of edges of convex hull. */
00639 int triwords;                                   /* Total words per triangle. */
00640 int shwords;                                  /* Total words per shell edge. */
00641 int pointmarkindex;             /* Index to find boundary marker of a point. */
00642 int point2triindex;         /* Index to find a triangle adjacent to a point. */
00643 int highorderindex;    /* Index to find extra nodes for high-order elements. */
00644 int elemattribindex;              /* Index to find attributes of a triangle. */
00645 int areaboundindex;               /* Index to find area bound of a triangle. */
00646 int checksegments;           /* Are there segments in the triangulation yet? */
00647 int readnodefile;                             /* Has a .node file been read? */
00648 long samples;                /* Number of random samples for point location. */
00649 unsigned long randomseed;                     /* Current random number seed. */
00650 
00651 REAL splitter;       /* Used to split REAL factors for exact multiplication. */
00652 REAL epsilon;                             /* Floating-point machine epsilon. */
00653 REAL resulterrbound;
00654 REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
00655 REAL iccerrboundA, iccerrboundB, iccerrboundC;
00656 
00657 long incirclecount;                   /* Number of incircle tests performed. */
00658 long counterclockcount;       /* Number of counterclockwise tests performed. */
00659 long hyperbolacount;        /* Number of right-of-hyperbola tests performed. */
00660 long circumcentercount;    /* Number of circumcenter calculations performed. */
00661 long circletopcount;         /* Number of circle top calculations performed. */
00662 
00663 /* Switches for the triangulator.                                            */
00664 /*   poly: -p switch.  refine: -r switch.                                    */
00665 /*   quality: -q switch.                                                     */
00666 /*     minangle: minimum angle bound, specified after -q switch.             */
00667 /*     goodangle: cosine squared of minangle.                                */
00668 /*   vararea: -a switch without number.                                      */
00669 /*   fixedarea: -a switch with number.                                       */
00670 /*     maxarea: maximum area bound, specified after -a switch.               */
00671 /*   regionattrib: -A switch.  convex: -c switch.                            */
00672 /*   firstnumber: inverse of -z switch.  All items are numbered starting     */
00673 /*     from firstnumber.                                                     */
00674 /*   edgesout: -e switch.  voronoi: -v switch.                               */
00675 /*   neighbors: -n switch.  geomview: -g switch.                             */
00676 /*   nobound: -B switch.  nopolywritten: -P switch.                          */
00677 /*   nonodewritten: -N switch.  noelewritten: -E switch.                     */
00678 /*   noiterationnum: -I switch.  noholes: -O switch.                         */
00679 /*   noexact: -X switch.                                                     */
00680 /*   order: element order, specified after -o switch.                        */
00681 /*   nobisect: count of how often -Y switch is selected.                     */
00682 /*   steiner: maximum number of Steiner points, specified after -S switch.   */
00683 /*     steinerleft: number of Steiner points not yet used.                   */
00684 /*   incremental: -i switch.  sweepline: -F switch.                          */
00685 /*   dwyer: inverse of -l switch.                                            */
00686 /*   splitseg: -s switch.                                                    */
00687 /*   docheck: -C switch.                                                     */
00688 /*   quiet: -Q switch.  verbose: count of how often -V switch is selected.   */
00689 /*   useshelles: -p, -r, -q, or -c switch; determines whether shell edges    */
00690 /*     are used at all.                                                      */
00691 /*                                                                           */
00692 /* Read the instructions to find out the meaning of these switches.          */
00693 
00694 int poly, refine, quality, vararea, fixedarea, regionattrib, convex;
00695 int firstnumber;
00696 int edgesout, voronoi, neighbors, geomview;
00697 int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
00698 int noholes, noexact;
00699 int incremental, sweepline, dwyer;
00700 int splitseg;
00701 int docheck;
00702 int quiet, verbose;
00703 int useshelles;
00704 int order;
00705 int nobisect;
00706 int steiner, steinerleft;
00707 REAL minangle, goodangle;
00708 REAL maxarea;
00709 
00710 /* Variables for file names.                                                 */
00711 
00712 #ifndef TRILIBRARY
00713 char innodefilename[FILENAMESIZE];
00714 char inelefilename[FILENAMESIZE];
00715 char inpolyfilename[FILENAMESIZE];
00716 char areafilename[FILENAMESIZE];
00717 char outnodefilename[FILENAMESIZE];
00718 char outelefilename[FILENAMESIZE];
00719 char outpolyfilename[FILENAMESIZE];
00720 char edgefilename[FILENAMESIZE];
00721 char vnodefilename[FILENAMESIZE];
00722 char vedgefilename[FILENAMESIZE];
00723 char neighborfilename[FILENAMESIZE];
00724 char offfilename[FILENAMESIZE];
00725 #endif /* not TRILIBRARY */
00726 
00727 /* Triangular bounding box points.                                           */
00728 
00729 point infpoint1, infpoint2, infpoint3;
00730 
00731 /* Pointer to the `triangle' that occupies all of "outer space".             */
00732 
00733 triangle *dummytri;
00734 triangle *dummytribase;      /* Keep base address so we can free() it later. */
00735 
00736 /* Pointer to the omnipresent shell edge.  Referenced by any triangle or     */
00737 /*   shell edge that isn't really connected to a shell edge at that          */
00738 /*   location.                                                               */
00739 
00740 shelle *dummysh;
00741 shelle *dummyshbase;         /* Keep base address so we can free() it later. */
00742 
00743 /* Pointer to a recently visited triangle.  Improves point location if       */
00744 /*   proximate points are inserted sequentially.                             */
00745 
00746 struct triedge recenttri;
00747 
00748 /*****************************************************************************/
00749 /*                                                                           */
00750 /*  Mesh manipulation primitives.  Each triangle contains three pointers to  */
00751 /*  other triangles, with orientations.  Each pointer points not to the      */
00752 /*  first byte of a triangle, but to one of the first three bytes of a       */
00753 /*  triangle.  It is necessary to extract both the triangle itself and the   */
00754 /*  orientation.  To save memory, I keep both pieces of information in one   */
00755 /*  pointer.  To make this possible, I assume that all triangles are aligned */
00756 /*  to four-byte boundaries.  The `decode' routine below decodes a pointer,  */
00757 /*  extracting an orientation (in the range 0 to 2) and a pointer to the     */
00758 /*  beginning of a triangle.  The `encode' routine compresses a pointer to a */
00759 /*  triangle and an orientation into a single pointer.  My assumptions that  */
00760 /*  triangles are four-byte-aligned and that the `unsigned long' type is     */
00761 /*  long enough to hold a pointer are two of the few kludges in this program.*/
00762 /*                                                                           */
00763 /*  Shell edges are manipulated similarly.  A pointer to a shell edge        */
00764 /*  carries both an address and an orientation in the range 0 to 1.          */
00765 /*                                                                           */
00766 /*  The other primitives take an oriented triangle or oriented shell edge,   */
00767 /*  and return an oriented triangle or oriented shell edge or point; or they */
00768 /*  change the connections in the data structure.                            */
00769 /*                                                                           */
00770 /*****************************************************************************/
00771 
00772 /********* Mesh manipulation primitives begin here                   *********/
00773 /**                                                                         **/
00774 /**                                                                         **/
00775 
00776 /* Fast lookup arrays to speed some of the mesh manipulation primitives.     */
00777 
00778 int plus1mod3[3] = {1, 2, 0};
00779 int minus1mod3[3] = {2, 0, 1};
00780 
00781 /********* Primitives for triangles                                  *********/
00782 /*                                                                           */
00783 /*                                                                           */
00784 
00785 /* decode() converts a pointer to an oriented triangle.  The orientation is  */
00786 /*   extracted from the two least significant bits of the pointer.           */
00787 
00788 #define decode(ptr, triedge)                                                  \
00789   (triedge).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l);      \
00790   (triedge).tri = (triangle *)                                                \
00791                   ((unsigned long) (ptr) ^ (unsigned long) (triedge).orient)
00792 
00793 /* encode() compresses an oriented triangle into a single pointer.  It       */
00794 /*   relies on the assumption that all triangles are aligned to four-byte    */
00795 /*   boundaries, so the two least significant bits of (triedge).tri are zero.*/
00796 
00797 #define encode(triedge)                                                       \
00798   (triangle) ((unsigned long) (triedge).tri | (unsigned long) (triedge).orient)
00799 
00800 /* The following edge manipulation primitives are all described by Guibas    */
00801 /*   and Stolfi.  However, they use an edge-based data structure, whereas I  */
00802 /*   am using a triangle-based data structure.                               */
00803 
00804 /* sym() finds the abutting triangle, on the same edge.  Note that the       */
00805 /*   edge direction is necessarily reversed, because triangle/edge handles   */
00806 /*   are always directed counterclockwise around the triangle.               */
00807 
00808 #define sym(triedge1, triedge2)                                               \
00809   ptr = (triedge1).tri[(triedge1).orient];                                    \
00810   decode(ptr, triedge2);
00811 
00812 #define symself(triedge)                                                      \
00813   ptr = (triedge).tri[(triedge).orient];                                      \
00814   decode(ptr, triedge);
00815 
00816 /* lnext() finds the next edge (counterclockwise) of a triangle.             */
00817 
00818 #define lnext(triedge1, triedge2)                                             \
00819   (triedge2).tri = (triedge1).tri;                                            \
00820   (triedge2).orient = plus1mod3[(triedge1).orient]
00821 
00822 #define lnextself(triedge)                                                    \
00823   (triedge).orient = plus1mod3[(triedge).orient]
00824 
00825 /* lprev() finds the previous edge (clockwise) of a triangle.                */
00826 
00827 #define lprev(triedge1, triedge2)                                             \
00828   (triedge2).tri = (triedge1).tri;                                            \
00829   (triedge2).orient = minus1mod3[(triedge1).orient]
00830 
00831 #define lprevself(triedge)                                                    \
00832   (triedge).orient = minus1mod3[(triedge).orient]
00833 
00834 /* onext() spins counterclockwise around a point; that is, it finds the next */
00835 /*   edge with the same origin in the counterclockwise direction.  This edge */
00836 /*   will be part of a different triangle.                                   */
00837 
00838 #define onext(triedge1, triedge2)                                             \
00839   lprev(triedge1, triedge2);                                                  \
00840   symself(triedge2);
00841 
00842 #define onextself(triedge)                                                    \
00843   lprevself(triedge);                                                         \
00844   symself(triedge);
00845 
00846 /* oprev() spins clockwise around a point; that is, it finds the next edge   */
00847 /*   with the same origin in the clockwise direction.  This edge will be     */
00848 /*   part of a different triangle.                                           */
00849 
00850 #define oprev(triedge1, triedge2)                                             \
00851   sym(triedge1, triedge2);                                                    \
00852   lnextself(triedge2);
00853 
00854 #define oprevself(triedge)                                                    \
00855   symself(triedge);                                                           \
00856   lnextself(triedge);
00857 
00858 /* dnext() spins counterclockwise around a point; that is, it finds the next */
00859 /*   edge with the same destination in the counterclockwise direction.  This */
00860 /*   edge will be part of a different triangle.                              */
00861 
00862 #define dnext(triedge1, triedge2)                                             \
00863   sym(triedge1, triedge2);                                                    \
00864   lprevself(triedge2);
00865 
00866 #define dnextself(triedge)                                                    \
00867   symself(triedge);                                                           \
00868   lprevself(triedge);
00869 
00870 /* dprev() spins clockwise around a point; that is, it finds the next edge   */
00871 /*   with the same destination in the clockwise direction.  This edge will   */
00872 /*   be part of a different triangle.                                        */
00873 
00874 #define dprev(triedge1, triedge2)                                             \
00875   lnext(triedge1, triedge2);                                                  \
00876   symself(triedge2);
00877 
00878 #define dprevself(triedge)                                                    \
00879   lnextself(triedge);                                                         \
00880   symself(triedge);
00881 
00882 /* rnext() moves one edge counterclockwise about the adjacent triangle.      */
00883 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
00884 /*   changing triangles twice.)                                              */
00885 
00886 #define rnext(triedge1, triedge2)                                             \
00887   sym(triedge1, triedge2);                                                    \
00888   lnextself(triedge2);                                                        \
00889   symself(triedge2);
00890 
00891 #define rnextself(triedge)                                                    \
00892   symself(triedge);                                                           \
00893   lnextself(triedge);                                                         \
00894   symself(triedge);
00895 
00896 /* rnext() moves one edge clockwise about the adjacent triangle.             */
00897 /*   (It's best understood by reading Guibas and Stolfi.  It involves        */
00898 /*   changing triangles twice.)                                              */
00899 
00900 #define rprev(triedge1, triedge2)                                             \
00901   sym(triedge1, triedge2);                                                    \
00902   lprevself(triedge2);                                                        \
00903   symself(triedge2);
00904 
00905 #define rprevself(triedge)                                                    \
00906   symself(triedge);                                                           \
00907   lprevself(triedge);                                                         \
00908   symself(triedge);
00909 
00910 /* These primitives determine or set the origin, destination, or apex of a   */
00911 /* triangle.                                                                 */
00912 
00913 #define org(triedge, pointptr)                                                \
00914   pointptr = (point) (triedge).tri[plus1mod3[(triedge).orient] + 3]
00915 
00916 #define dest(triedge, pointptr)                                               \
00917   pointptr = (point) (triedge).tri[minus1mod3[(triedge).orient] + 3]
00918 
00919 #define apex(triedge, pointptr)                                               \
00920   pointptr = (point) (triedge).tri[(triedge).orient + 3]
00921 
00922 #define setorg(triedge, pointptr)                                             \
00923   (triedge).tri[plus1mod3[(triedge).orient] + 3] = (triangle) pointptr
00924 
00925 #define setdest(triedge, pointptr)                                            \
00926   (triedge).tri[minus1mod3[(triedge).orient] + 3] = (triangle) pointptr
00927 
00928 #define setapex(triedge, pointptr)                                            \
00929   (triedge).tri[(triedge).orient + 3] = (triangle) pointptr
00930 
00931 #define setvertices2null(triedge)                                             \
00932   (triedge).tri[3] = (triangle) NULL;                                         \
00933   (triedge).tri[4] = (triangle) NULL;                                         \
00934   (triedge).tri[5] = (triangle) NULL;
00935 
00936 /* Bond two triangles together.                                              */
00937 
00938 #define bond(triedge1, triedge2)                                              \
00939   (triedge1).tri[(triedge1).orient] = encode(triedge2);                       \
00940   (triedge2).tri[(triedge2).orient] = encode(triedge1)
00941 
00942 /* Dissolve a bond (from one side).  Note that the other triangle will still */
00943 /*   think it's connected to this triangle.  Usually, however, the other     */
00944 /*   triangle is being deleted entirely, or bonded to another triangle, so   */
00945 /*   it doesn't matter.                                                      */
00946 
00947 #define dissolve(triedge)                                                     \
00948   (triedge).tri[(triedge).orient] = (triangle) dummytri
00949 
00950 /* Copy a triangle/edge handle.                                              */
00951 
00952 #define triedgecopy(triedge1, triedge2)                                       \
00953   (triedge2).tri = (triedge1).tri;                                            \
00954   (triedge2).orient = (triedge1).orient
00955 
00956 /* Test for equality of triangle/edge handles.                               */
00957 
00958 #define triedgeequal(triedge1, triedge2)                                      \
00959   (((triedge1).tri == (triedge2).tri) &&                                      \
00960    ((triedge1).orient == (triedge2).orient))
00961 
00962 /* Primitives to infect or cure a triangle with the virus.  These rely on    */
00963 /*   the assumption that all shell edges are aligned to four-byte boundaries.*/
00964 
00965 #define infect(triedge)                                                       \
00966   (triedge).tri[6] = (triangle)                                               \
00967                      ((unsigned long) (triedge).tri[6] | (unsigned long) 2l)
00968 
00969 #define uninfect(triedge)                                                     \
00970   (triedge).tri[6] = (triangle)                                               \
00971                      ((unsigned long) (triedge).tri[6] & ~ (unsigned long) 2l)
00972 
00973 /* Test a triangle for viral infection.                                      */
00974 
00975 #define infected(triedge)                                                     \
00976   (((unsigned long) (triedge).tri[6] & (unsigned long) 2l) != 0)
00977 
00978 /* Check or set a triangle's attributes.                                     */
00979 
00980 #define elemattribute(triedge, attnum)                                        \
00981   ((REAL *) (triedge).tri)[elemattribindex + (attnum)]
00982 
00983 #define setelemattribute(triedge, attnum, value)                              \
00984   ((REAL *) (triedge).tri)[elemattribindex + (attnum)] = value
00985 
00986 /* Check or set a triangle's maximum area bound.                             */
00987 
00988 #define areabound(triedge)  ((REAL *) (triedge).tri)[areaboundindex]
00989 
00990 #define setareabound(triedge, value)                                          \
00991   ((REAL *) (triedge).tri)[areaboundindex] = value
00992 
00993 /********* Primitives for shell edges                                *********/
00994 /*                                                                           */
00995 /*                                                                           */
00996 
00997 /* sdecode() converts a pointer to an oriented shell edge.  The orientation  */
00998 /*   is extracted from the least significant bit of the pointer.  The two    */
00999 /*   least significant bits (one for orientation, one for viral infection)   */
01000 /*   are masked out to produce the real pointer.                             */
01001 
01002 #define sdecode(sptr, edge)                                                   \
01003   (edge).shorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l);      \
01004   (edge).sh = (shelle *)                                                      \
01005               ((unsigned long) (sptr) & ~ (unsigned long) 3l)
01006 
01007 /* sencode() compresses an oriented shell edge into a single pointer.  It    */
01008 /*   relies on the assumption that all shell edges are aligned to two-byte   */
01009 /*   boundaries, so the least significant bit of (edge).sh is zero.          */
01010 
01011 #define sencode(edge)                                                         \
01012   (shelle) ((unsigned long) (edge).sh | (unsigned long) (edge).shorient)
01013 
01014 /* ssym() toggles the orientation of a shell edge.                           */
01015 
01016 #define ssym(edge1, edge2)                                                    \
01017   (edge2).sh = (edge1).sh;                                                    \
01018   (edge2).shorient = 1 - (edge1).shorient
01019 
01020 #define ssymself(edge)                                                        \
01021   (edge).shorient = 1 - (edge).shorient
01022 
01023 /* spivot() finds the other shell edge (from the same segment) that shares   */
01024 /*   the same origin.                                                        */
01025 
01026 #define spivot(edge1, edge2)                                                  \
01027   sptr = (edge1).sh[(edge1).shorient];                                        \
01028   sdecode(sptr, edge2)
01029 
01030 #define spivotself(edge)                                                      \
01031   sptr = (edge).sh[(edge).shorient];                                          \
01032   sdecode(sptr, edge)
01033 
01034 /* snext() finds the next shell edge (from the same segment) in sequence;    */
01035 /*   one whose origin is the input shell edge's destination.                 */
01036 
01037 #define snext(edge1, edge2)                                                   \
01038   sptr = (edge1).sh[1 - (edge1).shorient];                                    \
01039   sdecode(sptr, edge2)
01040 
01041 #define snextself(edge)                                                       \
01042   sptr = (edge).sh[1 - (edge).shorient];                                      \
01043   sdecode(sptr, edge)
01044 
01045 /* These primitives determine or set the origin or destination of a shell    */
01046 /*   edge.                                                                   */
01047 
01048 #define sorg(edge, pointptr)                                                  \
01049   pointptr = (point) (edge).sh[2 + (edge).shorient]
01050 
01051 #define sdest(edge, pointptr)                                                 \
01052   pointptr = (point) (edge).sh[3 - (edge).shorient]
01053 
01054 #define setsorg(edge, pointptr)                                               \
01055   (edge).sh[2 + (edge).shorient] = (shelle) pointptr
01056 
01057 #define setsdest(edge, pointptr)                                              \
01058   (edge).sh[3 - (edge).shorient] = (shelle) pointptr
01059 
01060 /* These primitives read or set a shell marker.  Shell markers are used to   */
01061 /*   hold user boundary information.                                         */
01062 
01063 #define mark(edge)  (* (int *) ((edge).sh + 6))
01064 
01065 #define setmark(edge, value)                                                  \
01066   * (int *) ((edge).sh + 6) = value
01067 
01068 /* Bond two shell edges together.                                            */
01069 
01070 #define sbond(edge1, edge2)                                                   \
01071   (edge1).sh[(edge1).shorient] = sencode(edge2);                              \
01072   (edge2).sh[(edge2).shorient] = sencode(edge1)
01073 
01074 /* Dissolve a shell edge bond (from one side).  Note that the other shell    */
01075 /*   edge will still think it's connected to this shell edge.                */
01076 
01077 #define sdissolve(edge)                                                       \
01078   (edge).sh[(edge).shorient] = (shelle) dummysh
01079 
01080 /* Copy a shell edge.                                                        */
01081 
01082 #define shellecopy(edge1, edge2)                                              \
01083   (edge2).sh = (edge1).sh;                                                    \
01084   (edge2).shorient = (edge1).shorient
01085 
01086 /* Test for equality of shell edges.                                         */
01087 
01088 #define shelleequal(edge1, edge2)                                             \
01089   (((edge1).sh == (edge2).sh) &&                                              \
01090    ((edge1).shorient == (edge2).shorient))
01091 
01092 /********* Primitives for interacting triangles and shell edges      *********/
01093 /*                                                                           */
01094 /*                                                                           */
01095 
01096 /* tspivot() finds a shell edge abutting a triangle.                         */
01097 
01098 #define tspivot(triedge, edge)                                                \
01099   sptr = (shelle) (triedge).tri[6 + (triedge).orient];                        \
01100   sdecode(sptr, edge)
01101 
01102 /* stpivot() finds a triangle abutting a shell edge.  It requires that the   */
01103 /*   variable `ptr' of type `triangle' be defined.                           */
01104 
01105 #define stpivot(edge, triedge)                                                \
01106   ptr = (triangle) (edge).sh[4 + (edge).shorient];                            \
01107   decode(ptr, triedge)
01108 
01109 /* Bond a triangle to a shell edge.                                          */
01110 
01111 #define tsbond(triedge, edge)                                                 \
01112   (triedge).tri[6 + (triedge).orient] = (triangle) sencode(edge);             \
01113   (edge).sh[4 + (edge).shorient] = (shelle) encode(triedge)
01114 
01115 /* Dissolve a bond (from the triangle side).                                 */
01116 
01117 #define tsdissolve(triedge)                                                   \
01118   (triedge).tri[6 + (triedge).orient] = (triangle) dummysh
01119 
01120 /* Dissolve a bond (from the shell edge side).                               */
01121 
01122 #define stdissolve(edge)                                                      \
01123   (edge).sh[4 + (edge).shorient] = (shelle) dummytri
01124 
01125 /********* Primitives for points                                     *********/
01126 /*                                                                           */
01127 /*                                                                           */
01128 
01129 #define pointmark(pt)  ((int *) (pt))[pointmarkindex]
01130 
01131 #define setpointmark(pt, value)                                               \
01132   ((int *) (pt))[pointmarkindex] = value
01133 
01134 #define point2tri(pt)  ((triangle *) (pt))[point2triindex]
01135 
01136 #define setpoint2tri(pt, value)                                               \
01137   ((triangle *) (pt))[point2triindex] = value
01138 
01139 /**                                                                         **/
01140 /**                                                                         **/
01141 /********* Mesh manipulation primitives end here                     *********/
01142 
01143 /********* User interaction routines begin here                      *********/
01144 /**                                                                         **/
01145 /**                                                                         **/
01146 
01147 /*****************************************************************************/
01148 /*                                                                           */
01149 /*  syntax()   Print list of command line switches.                          */
01150 /*                                                                           */
01151 /*****************************************************************************/
01152 
01153 #ifndef TRILIBRARY
01154 
01155 void syntax()
01156 {
01157 #ifdef CDT_ONLY
01158 #ifdef REDUCED
01159   printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n");
01160 #else /* not REDUCED */
01161   printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n");
01162 #endif /* not REDUCED */
01163 #else /* not CDT_ONLY */
01164 #ifdef REDUCED
01165   printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n");
01166 #else /* not REDUCED */
01167   printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
01168 #endif /* not REDUCED */
01169 #endif /* not CDT_ONLY */
01170 
01171   printf("    -p  Triangulates a Planar Straight Line Graph (.poly file).\n");
01172 #ifndef CDT_ONLY
01173   printf("    -r  Refines a previously generated mesh.\n");
01174   printf(
01175     "    -q  Quality mesh generation.  A minimum angle may be specified.\n");
01176   printf("    -a  Applies a maximum triangle area constraint.\n");
01177 #endif /* not CDT_ONLY */
01178   printf(
01179     "    -A  Applies attributes to identify elements in certain regions.\n");
01180   printf("    -c  Encloses the convex hull with segments.\n");
01181   printf("    -e  Generates an edge list.\n");
01182   printf("    -v  Generates a Voronoi diagram.\n");
01183   printf("    -n  Generates a list of triangle neighbors.\n");
01184   printf("    -g  Generates an .off file for Geomview.\n");
01185   printf("    -B  Suppresses output of boundary information.\n");
01186   printf("    -P  Suppresses output of .poly file.\n");
01187   printf("    -N  Suppresses output of .node file.\n");
01188   printf("    -E  Suppresses output of .ele file.\n");
01189   printf("    -I  Suppresses mesh iteration numbers.\n");
01190   printf("    -O  Ignores holes in .poly file.\n");
01191   printf("    -X  Suppresses use of exact arithmetic.\n");
01192   printf("    -z  Numbers all items starting from zero (rather than one).\n");
01193   printf("    -o2 Generates second-order subparametric elements.\n");
01194 #ifndef CDT_ONLY
01195   printf("    -Y  Suppresses boundary segment splitting.\n");
01196   printf("    -S  Specifies maximum number of added Steiner points.\n");
01197 #endif /* not CDT_ONLY */
01198 #ifndef REDUCED
01199   printf("    -i  Uses incremental method, rather than divide-and-conquer.\n");
01200   printf("    -F  Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
01201 #endif /* not REDUCED */
01202   printf("    -l  Uses vertical cuts only, rather than alternating cuts.\n");
01203 #ifndef REDUCED
01204 #ifndef CDT_ONLY
01205   printf(
01206     "    -s  Force segments into mesh by splitting (instead of using CDT).\n");
01207 #endif /* not CDT_ONLY */
01208   printf("    -C  Check consistency of final mesh.\n");
01209 #endif /* not REDUCED */
01210   printf("    -Q  Quiet:  No terminal output except errors.\n");
01211   printf("    -V  Verbose:  Detailed information on what I'm doing.\n");
01212   printf("    -h  Help:  Detailed instructions for Triangle.\n");
01213   exit(0);
01214 }
01215 
01216 #endif /* not TRILIBRARY */
01217 
01218 /*****************************************************************************/
01219 /*                                                                           */
01220 /*  info()   Print out complete instructions.                                */
01221 /*                                                                           */
01222 /*****************************************************************************/
01223 
01224 #ifndef TRILIBRARY
01225 
01226 void info()
01227 {
01228   printf("Triangle\n");
01229   printf(
01230 "A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
01231   printf("Version 1.3\n\n");
01232   printf(
01233 "Copyright 1996 Jonathan Richard Shewchuk  (bugs/comments to jrs@cs.cmu.edu)\n"
01234 );
01235   printf("School of Computer Science / Carnegie Mellon University\n");
01236   printf("5000 Forbes Avenue / Pittsburgh, Pennsylvania  15213-3891\n");
01237   printf(
01238 "Created as part of the Archimedes project (tools for parallel FEM).\n");
01239   printf(
01240 "Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
01241   printf("There is no warranty whatsoever.  Use at your own risk.\n");
01242 #ifdef SINGLE
01243   printf("This executable is compiled for single precision arithmetic.\n\n\n");
01244 #else /* not SINGLE */
01245   printf("This executable is compiled for double precision arithmetic.\n\n\n");
01246 #endif /* not SINGLE */
01247   printf(
01248 "Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
01249   printf(
01250 "triangulations, and quality conforming Delaunay triangulations.  The latter\n"
01251 );
01252   printf(
01253 "can be generated with no small angles, and are thus suitable for finite\n");
01254   printf(
01255 "element analysis.  If no command line switches are specified, your .node\n");
01256   printf(
01257 "input file will be read, and the Delaunay triangulation will be returned in\n"
01258 );
01259   printf(".node and .ele output files.  The command syntax is:\n\n");
01260 #ifdef CDT_ONLY
01261 #ifdef REDUCED
01262   printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n\n");
01263 #else /* not REDUCED */
01264   printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n\n");
01265 #endif /* not REDUCED */
01266 #else /* not CDT_ONLY */
01267 #ifdef REDUCED
01268   printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n\n");
01269 #else /* not REDUCED */
01270   printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
01271 #endif /* not REDUCED */
01272 #endif /* not CDT_ONLY */
01273   printf(
01274 "Underscores indicate that numbers may optionally follow certain switches;\n");
01275   printf(
01276 "do not leave any space between a switch and its numeric parameter.\n");
01277   printf(
01278 "input_file must be a file with extension .node, or extension .poly if the\n");
01279   printf(
01280 "-p switch is used.  If -r is used, you must supply .node and .ele files,\n");
01281   printf(
01282 "and possibly a .poly file and .area file as well.  The formats of these\n");
01283   printf("files are described below.\n\n");
01284   printf("Command Line Switches:\n\n");
01285   printf(
01286 "    -p  Reads a Planar Straight Line Graph (.poly file), which can specify\n"
01287 );
01288   printf(
01289 "        points, segments, holes, and regional attributes and area\n");
01290   printf(
01291 "        constraints.  Will generate a constrained Delaunay triangulation\n");
01292   printf(
01293 "        fitting the input; or, if -s, -q, or -a is used, a conforming\n");
01294   printf(
01295 "        Delaunay triangulation.  If -p is not used, Triangle reads a .node\n"
01296 );
01297   printf("        file by default.\n");
01298   printf(
01299 "    -r  Refines a previously generated mesh.  The mesh is read from a .node\n"
01300 );
01301   printf(
01302 "        file and an .ele file.  If -p is also used, a .poly file is read\n");
01303   printf(
01304 "        and used to constrain edges in the mesh.  Further details on\n");
01305   printf("        refinement are given below.\n");
01306   printf(
01307 "    -q  Quality mesh generation by Jim Ruppert's Delaunay refinement\n");
01308   printf(
01309 "        algorithm.  Adds points to the mesh to ensure that no angles\n");
01310   printf(
01311 "        smaller than 20 degrees occur.  An alternative minimum angle may be\n"
01312 );
01313   printf(
01314 "        specified after the `q'.  If the minimum angle is 20.7 degrees or\n");
01315   printf(
01316 "        smaller, the triangulation algorithm is theoretically guaranteed to\n"
01317 );
01318   printf(
01319 "        terminate (assuming infinite precision arithmetic - Triangle may\n");
01320   printf(
01321 "        fail to terminate if you run out of precision).  In practice, the\n");
01322   printf(
01323 "        algorithm often succeeds for minimum angles up to 33.8 degrees.\n");
01324   printf(
01325 "        For highly refined meshes, however, it may be necessary to reduce\n");
01326   printf(
01327 "        the minimum angle to well below 20 to avoid problems associated\n");
01328   printf(
01329 "        with insufficient floating-point precision.  The specified angle\n");
01330   printf("        may include a decimal point.\n");
01331   printf(
01332 "    -a  Imposes a maximum triangle area.  If a number follows the `a', no\n");
01333   printf(
01334 "        triangle will be generated whose area is larger than that number.\n");
01335   printf(
01336 "        If no number is specified, an .area file (if -r is used) or .poly\n");
01337   printf(
01338 "        file (if -r is not used) specifies a number of maximum area\n");
01339   printf(
01340 "        constraints.  An .area file contains a separate area constraint for\n"
01341 );
01342   printf(
01343 "        each triangle, and is useful for refining a finite element mesh\n");
01344   printf(
01345 "        based on a posteriori error estimates.  A .poly file can optionally\n"
01346 );
01347   printf(
01348 "        contain an area constraint for each segment-bounded region, thereby\n"
01349 );
01350   printf(
01351 "        enforcing triangle densities in a first triangulation.  You can\n");
01352   printf(
01353 "        impose both a fixed area constraint and a varying area constraint\n");
01354   printf(
01355 "        by invoking the -a switch twice, once with and once without a\n");
01356   printf(
01357 "        number following.  Each area specified may include a decimal point.\n"
01358 );
01359   printf(
01360 "    -A  Assigns an additional attribute to each triangle that identifies\n");
01361   printf(
01362 "        what segment-bounded region each triangle belongs to.  Attributes\n");
01363   printf(
01364 "        are assigned to regions by the .poly file.  If a region is not\n");
01365   printf(
01366 "        explicitly marked by the .poly file, triangles in that region are\n");
01367   printf(
01368 "        assigned an attribute of zero.  The -A switch has an effect only\n");
01369   printf("        when the -p switch is used and the -r switch is not.\n");
01370   printf(
01371 "    -c  Creates segments on the convex hull of the triangulation.  If you\n");
01372   printf(
01373 "        are triangulating a point set, this switch causes a .poly file to\n");
01374   printf(
01375 "        be written, containing all edges in the convex hull.  (By default,\n"
01376 );
01377   printf(
01378 "        a .poly file is written only if a .poly file is read.)  If you are\n"
01379 );
01380   printf(
01381 "        triangulating a PSLG, this switch specifies that the interior of\n");
01382   printf(
01383 "        the convex hull of the PSLG should be triangulated.  If you do not\n"
01384 );
01385   printf(
01386 "        use this switch when triangulating a PSLG, it is assumed that you\n");
01387   printf(
01388 "        have identified the region to be triangulated by surrounding it\n");
01389   printf(
01390 "        with segments of the input PSLG.  Beware:  if you are not careful,\n"
01391 );
01392   printf(
01393 "        this switch can cause the introduction of an extremely thin angle\n");
01394   printf(
01395 "        between a PSLG segment and a convex hull segment, which can cause\n");
01396   printf(
01397 "        overrefinement or failure if Triangle runs out of precision.  If\n");
01398   printf(
01399 "        you are refining a mesh, the -c switch works differently; it\n");
01400   printf(
01401 "        generates the set of boundary edges of the mesh, rather than the\n");
01402   printf("        convex hull.\n");
01403   printf(
01404 "    -e  Outputs (to an .edge file) a list of edges of the triangulation.\n");
01405   printf(
01406 "    -v  Outputs the Voronoi diagram associated with the triangulation.\n");
01407   printf("        Does not attempt to detect degeneracies.\n");
01408   printf(
01409 "    -n  Outputs (to a .neigh file) a list of triangles neighboring each\n");
01410   printf("        triangle.\n");
01411   printf(
01412 "    -g  Outputs the mesh to an Object File Format (.off) file, suitable for\n"
01413 );
01414   printf("        viewing with the Geometry Center's Geomview package.\n");
01415   printf(
01416 "    -B  No boundary markers in the output .node, .poly, and .edge output\n");
01417   printf(
01418 "        files.  See the detailed discussion of boundary markers below.\n");
01419   printf(
01420 "    -P  No output .poly file.  Saves disk space, but you lose the ability\n");
01421   printf(
01422 "        to impose segment constraints on later refinements of the mesh.\n");
01423   printf("    -N  No output .node file.\n");
01424   printf("    -E  No output .ele file.\n");
01425   printf(
01426 "    -I  No iteration numbers.  Suppresses the output of .node and .poly\n");
01427   printf(
01428 "        files, so your input files won't be overwritten.  (If your input is\n"
01429 );
01430   printf(
01431 "        a .poly file only, a .node file will be written.)  Cannot be used\n");
01432   printf(
01433 "        with the -r switch, because that would overwrite your input .ele\n");
01434   printf(
01435 "        file.  Shouldn't be used with the -s, -q, or -a switch if you are\n");
01436   printf(
01437 "        using a .node file for input, because no .node file will be\n");
01438   printf("        written, so there will be no record of any added points.\n");
01439   printf("    -O  No holes.  Ignores the holes in the .poly file.\n");
01440   printf(
01441 "    -X  No exact arithmetic.  Normally, Triangle uses exact floating-point\n"
01442 );
01443   printf(
01444 "        arithmetic for certain tests if it thinks the inexact tests are not\n"
01445 );
01446   printf(
01447 "        accurate enough.  Exact arithmetic ensures the robustness of the\n");
01448   printf(
01449 "        triangulation algorithms, despite floating-point roundoff error.\n");
01450   printf(
01451 "        Disabling exact arithmetic with the -X switch will cause a small\n");
01452   printf(
01453 "        improvement in speed and create the possibility (albeit small) that\n"
01454 );
01455   printf(
01456 "        Triangle will fail to produce a valid mesh.  Not recommended.\n");
01457   printf(
01458 "    -z  Numbers all items starting from zero (rather than one).  Note that\n"
01459 );
01460   printf(
01461 "        this switch is normally overrided by the value used to number the\n");
01462   printf(
01463 "        first point of the input .node or .poly file.  However, this switch\n"
01464 );
01465   printf("        is useful when calling Triangle from another program.\n");
01466   printf(
01467 "    -o2 Generates second-order subparametric elements with six nodes each.\n"
01468 );
01469   printf(
01470 "    -Y  No new points on the boundary.  This switch is useful when the mesh\n"
01471 );
01472   printf(
01473 "        boundary must be preserved so that it conforms to some adjacent\n");
01474   printf(
01475 "        mesh.  Be forewarned that you will probably sacrifice some of the\n");
01476   printf(
01477 "        quality of the mesh; Triangle will try, but the resulting mesh may\n"
01478 );
01479   printf(
01480 "        contain triangles of poor aspect ratio.  Works well if all the\n");
01481   printf(
01482 "        boundary points are closely spaced.  Specify this switch twice\n");
01483   printf(
01484 "        (`-YY') to prevent all segment splitting, including internal\n");
01485   printf("        boundaries.\n");
01486   printf(
01487 "    -S  Specifies the maximum number of Steiner points (points that are not\n"
01488 );
01489   printf(
01490 "        in the input, but are added to meet the constraints of minimum\n");
01491   printf(
01492 "        angle and maximum area).  The default is to allow an unlimited\n");
01493   printf(
01494 "        number.  If you specify this switch with no number after it,\n");
01495   printf(
01496 "        the limit is set to zero.  Triangle always adds points at segment\n");
01497   printf(
01498 "        intersections, even if it needs to use more points than the limit\n");
01499   printf(
01500 "        you set.  When Triangle inserts segments by splitting (-s), it\n");
01501   printf(
01502 "        always adds enough points to ensure that all the segments appear in\n"
01503 );
01504   printf(
01505 "        the triangulation, again ignoring the limit.  Be forewarned that\n");
01506   printf(
01507 "        the -S switch may result in a conforming triangulation that is not\n"
01508 );
01509   printf(
01510 "        truly Delaunay, because Triangle may be forced to stop adding\n");
01511   printf(
01512 "        points when the mesh is in a state where a segment is non-Delaunay\n"
01513 );
01514   printf(
01515 "        and needs to be split.  If so, Triangle will print a warning.\n");
01516   printf(
01517 "    -i  Uses an incremental rather than divide-and-conquer algorithm to\n");
01518   printf(
01519 "        form a Delaunay triangulation.  Try it if the divide-and-conquer\n");
01520   printf("        algorithm fails.\n");
01521   printf(
01522 "    -F  Uses Steven Fortune's sweepline algorithm to form a Delaunay\n");
01523   printf(
01524 "        triangulation.  Warning:  does not use exact arithmetic for all\n");
01525   printf("        calculations.  An exact result is not guaranteed.\n");
01526   printf(
01527 "    -l  Uses only vertical cuts in the divide-and-conquer algorithm.  By\n");
01528   printf(
01529 "        default, Triangle uses alternating vertical and horizontal cuts,\n");
01530   printf(
01531 "        which usually improve the speed except with point sets that are\n");
01532   printf(
01533 "        small or short and wide.  This switch is primarily of theoretical\n");
01534   printf("        interest.\n");
01535   printf(
01536 "    -s  Specifies that segments should be forced into the triangulation by\n"
01537 );
01538   printf(
01539 "        recursively splitting them at their midpoints, rather than by\n");
01540   printf(
01541 "        generating a constrained Delaunay triangulation.  Segment splitting\n"
01542 );
01543   printf(
01544 "        is true to Ruppert's original algorithm, but can create needlessly\n"
01545 );
01546   printf("        small triangles near external small features.\n");
01547   printf(
01548 "    -C  Check the consistency of the final mesh.  Uses exact arithmetic for\n"
01549 );
01550   printf(
01551 "        checking, even if the -X switch is used.  Useful if you suspect\n");
01552   printf("        Triangle is buggy.\n");
01553   printf(
01554 "    -Q  Quiet: Suppresses all explanation of what Triangle is doing, unless\n"
01555 );
01556   printf("        an error occurs.\n");
01557   printf(
01558 "    -V  Verbose: Gives detailed information about what Triangle is doing.\n");
01559   printf(
01560 "        Add more `V's for increasing amount of detail.  `-V' gives\n");
01561   printf(
01562 "        information on algorithmic progress and more detailed statistics.\n");
01563   printf(
01564 "        `-VV' gives point-by-point details, and will print so much that\n");
01565   printf(
01566 "        Triangle will run much more slowly.  `-VVV' gives information only\n"
01567 );
01568   printf("        a debugger could love.\n");
01569   printf("    -h  Help:  Displays these instructions.\n");
01570   printf("\n");
01571   printf("Definitions:\n");
01572   printf("\n");
01573   printf(
01574 "  A Delaunay triangulation of a point set is a triangulation whose vertices\n"
01575 );
01576   printf(
01577 "  are the point set, having the property that no point in the point set\n");
01578   printf(
01579 "  falls in the interior of the circumcircle (circle that passes through all\n"
01580 );
01581   printf("  three vertices) of any triangle in the triangulation.\n\n");
01582   printf(
01583 "  A Voronoi diagram of a point set is a subdivision of the plane into\n");
01584   printf(
01585 "  polygonal regions (some of which may be infinite), where each region is\n");
01586   printf(
01587 "  the set of points in the plane that are closer to some input point than\n");
01588   printf(
01589 "  to any other input point.  (The Voronoi diagram is the geometric dual of\n"
01590 );
01591   printf("  the Delaunay triangulation.)\n\n");
01592   printf(
01593 "  A Planar Straight Line Graph (PSLG) is a collection of points and\n");
01594   printf(
01595 "  segments.  Segments are simply edges, whose endpoints are points in the\n");
01596   printf(
01597 "  PSLG.  The file format for PSLGs (.poly files) is described below.\n");
01598   printf("\n");
01599   printf(
01600 "  A constrained Delaunay triangulation of a PSLG is similar to a Delaunay\n");
01601   printf(
01602 "  triangulation, but each PSLG segment is present as a single edge in the\n");
01603   printf(
01604 "  triangulation.  (A constrained Delaunay triangulation is not truly a\n");
01605   printf("  Delaunay triangulation.)\n\n");
01606   printf(
01607 "  A conforming Delaunay triangulation of a PSLG is a true Delaunay\n");
01608   printf(
01609 "  triangulation in which each PSLG segment may have been subdivided into\n");
01610   printf(
01611 "  several edges by the insertion of additional points.  These inserted\n");
01612   printf(
01613 "  points are necessary to allow the segments to exist in the mesh while\n");
01614   printf("  maintaining the Delaunay property.\n\n");
01615   printf("File Formats:\n\n");
01616   printf(
01617 "  All files may contain comments prefixed by the character '#'.  Points,\n");
01618   printf(
01619 "  triangles, edges, holes, and maximum area constraints must be numbered\n");
01620   printf(
01621 "  consecutively, starting from either 1 or 0.  Whichever you choose, all\n");
01622   printf(
01623 "  input files must be consistent; if the nodes are numbered from 1, so must\n"
01624 );
01625   printf(
01626 "  be all other objects.  Triangle automatically detects your choice while\n");
01627   printf(
01628 "  reading the .node (or .poly) file.  (When calling Triangle from another\n");
01629   printf(
01630 "  program, use the -z switch if you wish to number objects from zero.)\n");
01631   printf("  Examples of these file formats are given below.\n\n");
01632   printf("  .node files:\n");
01633   printf(
01634 "    First line:  <# of points> <dimension (must be 2)> <# of attributes>\n");
01635   printf(
01636 "                                           <# of boundary markers (0 or 1)>\n"
01637 );
01638   printf(
01639 "    Remaining lines:  <point #> <x> <y> [attributes] [boundary marker]\n");
01640   printf("\n");
01641   printf(
01642 "    The attributes, which are typically floating-point values of physical\n");
01643   printf(
01644 "    quantities (such as mass or conductivity) associated with the nodes of\n"
01645 );
01646   printf(
01647 "    a finite element mesh, are copied unchanged to the output mesh.  If -s,\n"
01648 );
01649   printf(
01650 "    -q, or -a is selected, each new Steiner point added to the mesh will\n");
01651   printf("    have attributes assigned to it by linear interpolation.\n\n");
01652   printf(
01653 "    If the fourth entry of the first line is `1', the last column of the\n");
01654   printf(
01655 "    remainder of the file is assumed to contain boundary markers.  Boundary\n"
01656 );
01657   printf(
01658 "    markers are used to identify boundary points and points resting on PSLG\n"
01659 );
01660   printf(
01661 "    segments; a complete description appears in a section below.  The .node\n"
01662 );
01663   printf(
01664 "    file produced by Triangle will contain boundary markers in the last\n");
01665   printf("    column unless they are suppressed by the -B switch.\n\n");
01666   printf("  .ele files:\n");
01667   printf(
01668 "    First line:  <# of triangles> <points per triangle> <# of attributes>\n");
01669   printf(
01670 "    Remaining lines:  <triangle #> <point> <point> <point> ... [attributes]\n"
01671 );
01672   printf("\n");
01673   printf(
01674 "    Points are indices into the corresponding .node file.  The first three\n"
01675 );
01676   printf(
01677 "    points are the corners, and are listed in counterclockwise order around\n"
01678 );
01679   printf(
01680 "    each triangle.  (The remaining points, if any, depend on the type of\n");
01681   printf(
01682 "    finite element used.)  The attributes are just like those of .node\n");
01683   printf(
01684 "    files.  Because there is no simple mapping from input to output\n");
01685   printf(
01686 "    triangles, an attempt is made to interpolate attributes, which may\n");
01687   printf(
01688 "    result in a good deal of diffusion of attributes among nearby triangles\n"
01689 );
01690   printf(
01691 "    as the triangulation is refined.  Diffusion does not occur across\n");
01692   printf(
01693 "    segments, so attributes used to identify segment-bounded regions remain\n"
01694 );
01695   printf(
01696 "    intact.  In output .ele files, all triangles have three points each\n");
01697   printf(
01698 "    unless the -o2 switch is used, in which case they have six, and the\n");
01699   printf(
01700 "    fourth, fifth, and sixth points lie on the midpoints of the edges\n");
01701   printf("    opposite the first, second, and third corners.\n\n");
01702   printf("  .poly files:\n");
01703   printf(
01704 "    First line:  <# of points> <dimension (must be 2)> <# of attributes>\n");
01705   printf(
01706 "                                           <# of boundary markers (0 or 1)>\n"
01707 );
01708   printf(
01709 "    Following lines:  <point #> <x> <y> [attributes] [boundary marker]\n");
01710   printf("    One line:  <# of segments> <# of boundary markers (0 or 1)>\n");
01711   printf(
01712 "    Following lines:  <segment #> <endpoint> <endpoint> [boundary marker]\n");
01713   printf("    One line:  <# of holes>\n");
01714   printf("    Following lines:  <hole #> <x> <y>\n");
01715   printf(
01716 "    Optional line:  <# of regional attributes and/or area constraints>\n");
01717   printf(
01718 "    Optional following lines:  <constraint #> <x> <y> <attrib> <max area>\n");
01719   printf("\n");
01720   printf(
01721 "    A .poly file represents a PSLG, as well as some additional information.\n"
01722 );
01723   printf(
01724 "    The first section lists all the points, and is identical to the format\n"
01725 );
01726   printf(
01727 "    of .node files.  <# of points> may be set to zero to indicate that the\n"
01728 );
01729   printf(
01730 "    points are listed in a separate .node file; .poly files produced by\n");
01731   printf(
01732 "    Triangle always have this format.  This has the advantage that a point\n"
01733 );
01734   printf(
01735 "    set may easily be triangulated with or without segments.  (The same\n");
01736   printf(
01737 "    effect can be achieved, albeit using more disk space, by making a copy\n"
01738 );
01739   printf(
01740 "    of the .poly file with the extension .node; all sections of the file\n");
01741   printf("    but the first are ignored.)\n\n");
01742   printf(
01743 "    The second section lists the segments.  Segments are edges whose\n");
01744   printf(
01745 "    presence in the triangulation is enforced.  Each segment is specified\n");
01746   printf(
01747 "    by listing the indices of its two endpoints.  This means that you must\n"
01748 );
01749   printf(
01750 "    include its endpoints in the point list.  If -s, -q, and -a are not\n");
01751   printf(
01752 "    selected, Triangle will produce a constrained Delaunay triangulation,\n");
01753   printf(
01754 "    in which each segment appears as a single edge in the triangulation.\n");
01755   printf(
01756 "    If -q or -a is selected, Triangle will produce a conforming Delaunay\n");
01757   printf(
01758 "    triangulation, in which segments may be subdivided into smaller edges.\n"
01759 );
01760   printf("    Each segment, like each point, may have a boundary marker.\n\n");
01761   printf(
01762 "    The third section lists holes (and concavities, if -c is selected) in\n");
01763   printf(
01764 "    the triangulation.  Holes are specified by identifying a point inside\n");
01765   printf(
01766 "    each hole.  After the triangulation is formed, Triangle creates holes\n");
01767   printf(
01768 "    by eating triangles, spreading out from each hole point until its\n");
01769   printf(
01770 "    progress is blocked by PSLG segments; you must be careful to enclose\n");
01771   printf(
01772 "    each hole in segments, or your whole triangulation may be eaten away.\n");
01773   printf(
01774 "    If the two triangles abutting a segment are eaten, the segment itself\n");
01775   printf(
01776 "    is also eaten.  Do not place a hole directly on a segment; if you do,\n");
01777   printf("    Triangle will choose one side of the segment arbitrarily.\n\n");
01778   printf(
01779 "    The optional fourth section lists regional attributes (to be assigned\n");
01780   printf(
01781 "    to all triangles in a region) and regional constraints on the maximum\n");
01782   printf(
01783 "    triangle area.  Triangle will read this section only if the -A switch\n");
01784   printf(
01785 "    is used or the -a switch is used without a number following it, and the\n"
01786 );
01787   printf(
01788 "    -r switch is not used.  Regional attributes and area constraints are\n");
01789   printf(
01790 "    propagated in the same manner as holes; you specify a point for each\n");
01791   printf(
01792 "    attribute and/or constraint, and the attribute and/or constraint will\n");
01793   printf(
01794 "    affect the whole region (bounded by segments) containing the point.  If\n"
01795 );
01796   printf(
01797 "    two values are written on a line after the x and y coordinate, the\n");
01798   printf(
01799 "    former is assumed to be a regional attribute (but will only be applied\n"
01800 );
01801   printf(
01802 "    if the -A switch is selected), and the latter is assumed to be a\n");
01803   printf(
01804 "    regional area constraint (but will only be applied if the -a switch is\n"
01805 );
01806   printf(
01807 "    selected).  You may also specify just one value after the coordinates,\n"
01808 );
01809   printf(
01810 "    which can serve as both an attribute and an area constraint, depending\n"
01811 );
01812   printf(
01813 "    on the choice of switches.  If you are using the -A and -a switches\n");
01814   printf(
01815 "    simultaneously and wish to assign an attribute to some region without\n");
01816   printf("    imposing an area constraint, use a negative maximum area.\n\n");
01817   printf(
01818 "    When a triangulation is created from a .poly file, you must either\n");
01819   printf(
01820 "    enclose the entire region to be triangulated in PSLG segments, or\n");
01821   printf(
01822 "    use the -c switch, which encloses the convex hull of the input point\n");
01823   printf(
01824 "    set.  If you do not use the -c switch, Triangle will eat all triangles\n"
01825 );
01826   printf(
01827 "    on the outer boundary that are not protected by segments; if you are\n");
01828   printf(
01829 "    not careful, your whole triangulation may be eaten away.  If you do\n");
01830   printf(
01831 "    use the -c switch, you can still produce concavities by appropriate\n");
01832   printf("    placement of holes just inside the convex hull.\n\n");
01833   printf(
01834 "    An ideal PSLG has no intersecting segments, nor any points that lie\n");
01835   printf(
01836 "    upon segments (except, of course, the endpoints of each segment.)  You\n"
01837 );
01838   printf(
01839 "    aren't required to make your .poly files ideal, but you should be aware\n"
01840 );
01841   printf(
01842 "    of what can go wrong.  Segment intersections are relatively safe -\n");
01843   printf(
01844 "    Triangle will calculate the intersection points for you and add them to\n"
01845 );
01846   printf(
01847 "    the triangulation - as long as your machine's floating-point precision\n"
01848 );
01849   printf(
01850 "    doesn't become a problem.  You are tempting the fates if you have three\n"
01851 );
01852   printf(
01853 "    segments that cross at the same location, and expect Triangle to figure\n"
01854 );
01855   printf(
01856 "    out where the intersection point is.  Thanks to floating-point roundoff\n"
01857 );
01858   printf(
01859 "    error, Triangle will probably decide that the three segments intersect\n"
01860 );
01861   printf(
01862 "    at three different points, and you will find a minuscule triangle in\n");
01863   printf(
01864 "    your output - unless Triangle tries to refine the tiny triangle, uses\n");
01865   printf(
01866 "    up the last bit of machine precision, and fails to terminate at all.\n");
01867   printf(
01868 "    You're better off putting the intersection point in the input files,\n");
01869   printf(
01870 "    and manually breaking up each segment into two.  Similarly, if you\n");
01871   printf(
01872 "    place a point at the middle of a segment, and hope that Triangle will\n");
01873   printf(
01874 "    break up the segment at that point, you might get lucky.  On the other\n"
01875 );
01876   printf(
01877 "    hand, Triangle might decide that the point doesn't lie precisely on the\n"
01878 );
01879   printf(
01880 "    line, and you'll have a needle-sharp triangle in your output - or a lot\n"
01881 );
01882   printf("    of tiny triangles if you're generating a quality mesh.\n\n");
01883   printf(
01884 "    When Triangle reads a .poly file, it also writes a .poly file, which\n");
01885   printf(
01886 "    includes all edges that are part of input segments.  If the -c switch\n");
01887   printf(
01888 "    is used, the output .poly file will also include all of the edges on\n");
01889   printf(
01890 "    the convex hull.  Hence, the output .poly file is useful for finding\n");
01891   printf(
01892 "    edges associated with input segments and setting boundary conditions in\n"
01893 );
01894   printf(
01895 "    finite element simulations.  More importantly, you will need it if you\n"
01896 );
01897   printf(
01898 "    plan to refine the output mesh, and don't want segments to be missing\n");
01899   printf("    in later triangulations.\n\n");
01900   printf("  .area files:\n");
01901   printf("    First line:  <# of triangles>\n");
01902   printf("    Following lines:  <triangle #> <maximum area>\n\n");
01903   printf(
01904 "    An .area file associates with each triangle a maximum area that is used\n"
01905 );
01906   printf(
01907 "    for mesh refinement.  As with other file formats, every triangle must\n");
01908   printf(
01909 "    be represented, and they must be numbered consecutively.  A triangle\n");
01910   printf(
01911 "    may be left unconstrained by assigning it a negative maximum area.\n");
01912   printf("\n");
01913   printf("  .edge files:\n");
01914   printf("    First line:  <# of edges> <# of boundary markers (0 or 1)>\n");
01915   printf(
01916 "    Following lines:  <edge #> <endpoint> <endpoint> [boundary marker]\n");
01917   printf("\n");
01918   printf(
01919 "    Endpoints are indices into the corresponding .node file.  Triangle can\n"
01920 );
01921   printf(
01922 "    produce .edge files (use the -e switch), but cannot read them.  The\n");
01923   printf(
01924 "    optional column of boundary markers is suppressed by the -B switch.\n");
01925   printf("\n");
01926   printf(
01927 "    In Voronoi diagrams, one also finds a special kind of edge that is an\n");
01928   printf(
01929 "    infinite ray with only one endpoint.  For these edges, a different\n");
01930   printf("    format is used:\n\n");
01931   printf("        <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
01932   printf(
01933 "    The `direction' is a floating-point vector that indicates the direction\n"
01934 );
01935   printf("    of the infinite ray.\n\n");
01936   printf("  .neigh files:\n");
01937   printf(
01938 "    First line:  <# of triangles> <# of neighbors per triangle (always 3)>\n"
01939 );
01940   printf(
01941 "    Following lines:  <triangle #> <neighbor> <neighbor> <neighbor>\n");
01942   printf("\n");
01943   printf(
01944 "    Neighbors are indices into the corresponding .ele file.  An index of -1\n"
01945 );
01946   printf(
01947 "    indicates a mesh boundary, and therefore no neighbor.  Triangle can\n");
01948   printf(
01949 "    produce .neigh files (use the -n switch), but cannot read them.\n");
01950   printf("\n");
01951   printf(
01952 "    The first neighbor of triangle i is opposite the first corner of\n");
01953   printf("    triangle i, and so on.\n\n");
01954   printf("Boundary Markers:\n\n");
01955   printf(
01956 "  Boundary markers are tags used mainly to identify which output points and\n"
01957 );
01958   printf(
01959 "  edges are associated with which PSLG segment, and to identify which\n");
01960   printf(
01961 "  points and edges occur on a boundary of the triangulation.  A common use\n"
01962 );
01963   printf(
01964 "  is to determine where boundary conditions should be applied to a finite\n");
01965   printf(
01966 "  element mesh.  You can prevent boundary markers from being written into\n");
01967   printf("  files produced by Triangle by using the -B switch.\n\n");
01968   printf(
01969 "  The boundary marker associated with each segment in an output .poly file\n"
01970 );
01971   printf("  or edge in an output .edge file is chosen as follows:\n");
01972   printf(
01973 "    - If an output edge is part or all of a PSLG segment with a nonzero\n");
01974   printf(
01975 "      boundary marker, then the edge is assigned the same marker.\n");
01976   printf(
01977 "    - Otherwise, if the edge occurs on a boundary of the triangulation\n");
01978   printf(
01979 "      (including boundaries of holes), then the edge is assigned the marker\n"
01980 );
01981   printf("      one (1).\n");
01982   printf("    - Otherwise, the edge is assigned the marker zero (0).\n");
01983   printf(
01984 "  The boundary marker associated with each point in an output .node file is\n"
01985 );
01986   printf("  chosen as follows:\n");
01987   printf(
01988 "    - If a point is assigned a nonzero boundary marker in the input file,\n");
01989   printf(
01990 "      then it is assigned the same marker in the output .node file.\n");
01991   printf(
01992 "    - Otherwise, if the point lies on a PSLG segment (including the\n");
01993   printf(
01994 "      segment's endpoints) with a nonzero boundary marker, then the point\n");
01995   printf(
01996 "      is assigned the same marker.  If the point lies on several such\n");
01997   printf("      segments, one of the markers is chosen arbitrarily.\n");
01998   printf(
01999 "    - Otherwise, if the point occurs on a boundary of the triangulation,\n");
02000   printf("      then the point is assigned the marker one (1).\n");
02001   printf("    - Otherwise, the point is assigned the marker zero (0).\n");
02002   printf("\n");
02003   printf(
02004 "  If you want Triangle to determine for you which points and edges are on\n");
02005   printf(
02006 "  the boundary, assign them the boundary marker zero (or use no markers at\n"
02007 );
02008   printf(
02009 "  all) in your input files.  Alternatively, you can mark some of them and\n");
02010   printf("  leave others marked zero, allowing Triangle to label them.\n\n");
02011   printf("Triangulation Iteration Numbers:\n\n");
02012   printf(
02013 "  Because Triangle can read and refine its own triangulations, input\n");
02014   printf(
02015 "  and output files have iteration numbers.  For instance, Triangle might\n");
02016   printf(
02017 "  read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
02018   printf(
02019 "  triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
02020   printf("  mesh.4.poly.  Files with no iteration number are treated as if\n");
02021   printf(
02022 "  their iteration number is zero; hence, Triangle might read the file\n");
02023   printf(
02024 "  points.node, triangulate it, and produce the files points.1.node and\n");
02025   printf("  points.1.ele.\n\n");
02026   printf(
02027 "  Iteration numbers allow you to create a sequence of successively finer\n");
02028   printf(
02029 "  meshes suitable for multigrid methods.  They also allow you to produce a\n"
02030 );
02031   printf(
02032 "  sequence of meshes using error estimate-driven mesh refinement.\n");
02033   printf("\n");
02034   printf(
02035 "  If you're not using refinement or quality meshing, and you don't like\n");
02036   printf(
02037 "  iteration numbers, use the -I switch to disable them.  This switch will\n");
02038   printf(
02039 "  also disable output of .node and .poly files to prevent your input files\n"
02040 );
02041   printf(
02042 "  from being overwritten.  (If the input is a .poly file that contains its\n"
02043 );
02044   printf("  own points, a .node file will be written.)\n\n");
02045   printf("Examples of How to Use Triangle:\n\n");
02046   printf(
02047 "  `triangle dots' will read points from dots.node, and write their Delaunay\n"
02048 );
02049   printf(
02050 "  triangulation to dots.1.node and dots.1.ele.  (dots.1.node will be\n");
02051   printf(
02052 "  identical to dots.node.)  `triangle -I dots' writes the triangulation to\n"
02053 );
02054   printf(
02055 "  dots.ele instead.  (No additional .node file is needed, so none is\n");
02056   printf("  written.)\n\n");
02057   printf(
02058 "  `triangle -pe object.1' will read a PSLG from object.1.poly (and possibly\n"
02059 );
02060   printf(
02061 "  object.1.node, if the points are omitted from object.1.poly) and write\n");
02062   printf("  their constrained Delaunay triangulation to object.2.node and\n");
02063   printf(
02064 "  object.2.ele.  The segments will be copied to object.2.poly, and all\n");
02065   printf("  edges will be written to object.2.edge.\n\n");
02066   printf(
02067 "  `triangle -pq31.5a.1 object' will read a PSLG from object.poly (and\n");
02068   printf(
02069 "  possibly object.node), generate a mesh whose angles are all greater than\n"
02070 );
02071   printf(
02072 "  31.5 degrees and whose triangles all have area smaller than 0.1, and\n");
02073   printf(
02074 "  write the mesh to object.1.node and object.1.ele.  Each segment may have\n"
02075 );
02076   printf(
02077 "  been broken up into multiple edges; the resulting constrained edges are\n");
02078   printf("  written to object.1.poly.\n\n");
02079   printf(
02080 "  Here is a sample file `box.poly' describing a square with a square hole:\n"
02081 );
02082   printf("\n");
02083   printf(
02084 "    # A box with eight points in 2D, no attributes, one boundary marker.\n");
02085   printf("    8 2 0 1\n");
02086   printf("    # Outer box has these vertices:\n");
02087   printf("     1   0 0   0\n");
02088   printf("     2   0 3   0\n");
02089   printf("     3   3 0   0\n");
02090   printf("     4   3 3   33     # A special marker for this point.\n");
02091   printf("    # Inner square has these vertices:\n");
02092   printf("     5   1 1   0\n");
02093   printf("     6   1 2   0\n");
02094   printf("     7   2 1   0\n");
02095   printf("     8   2 2   0\n");
02096   printf("    # Five segments with boundary markers.\n");
02097   printf("    5 1\n");
02098   printf("     1   1 2   5      # Left side of outer box.\n");
02099   printf("     2   5 7   0      # Segments 2 through 5 enclose the hole.\n");
02100   printf("     3   7 8   0\n");
02101   printf("     4   8 6   10\n");
02102   printf("     5   6 5   0\n");
02103   printf("    # One hole in the middle of the inner square.\n");
02104   printf("    1\n");
02105   printf("     1   1.5 1.5\n\n");
02106   printf(
02107 "  Note that some segments are missing from the outer square, so one must\n");
02108   printf(
02109 "  use the `-c' switch.  After `triangle -pqc box.poly', here is the output\n"
02110 );
02111   printf(
02112 "  file `box.1.node', with twelve points.  The last four points were added\n");
02113   printf(
02114 "  to meet the angle constraint.  Points 1, 2, and 9 have markers from\n");
02115   printf(
02116 "  segment 1.  Points 6 and 8 have markers from segment 4.  All the other\n");
02117   printf(
02118 "  points but 4 have been marked to indicate that they lie on a boundary.\n");
02119   printf("\n");
02120   printf("    12  2  0  1\n");
02121   printf("       1    0   0      5\n");
02122   printf("       2    0   3      5\n");
02123   printf("       3    3   0      1\n");
02124   printf("       4    3   3     33\n");
02125   printf("       5    1   1      1\n");
02126   printf("       6    1   2     10\n");
02127   printf("       7    2   1      1\n");
02128   printf("       8    2   2     10\n");
02129   printf("       9    0   1.5    5\n");
02130   printf("      10    1.5   0    1\n");
02131   printf("      11    3   1.5    1\n");
02132   printf("      12    1.5   3    1\n");
02133   printf("    # Generated by triangle -pqc box.poly\n\n");
02134   printf("  Here is the output file `box.1.ele', with twelve triangles.\n\n");
02135   printf("    12  3  0\n");
02136   printf("       1     5   6   9\n");
02137   printf("       2    10   3   7\n");
02138   printf("       3     6   8  12\n");
02139   printf("       4     9   1   5\n");
02140   printf("       5     6   2   9\n");
02141   printf("       6     7   3  11\n");
02142   printf("       7    11   4   8\n");
02143   printf("       8     7   5  10\n");
02144   printf("       9    12   2   6\n");
02145   printf("      10     8   7  11\n");
02146   printf("      11     5   1  10\n");
02147   printf("      12     8   4  12\n");
02148   printf("    # Generated by triangle -pqc box.poly\n\n");
02149   printf(
02150 "  Here is the output file `box.1.poly'.  Note that segments have been added\n"
02151 );
02152   printf(
02153 "  to represent the convex hull, and some segments have been split by newly\n"
02154 );
02155   printf(
02156 "  added points.  Note also that <# of points> is set to zero to indicate\n");
02157   printf("  that the points should be read from the .node file.\n\n");
02158   printf("    0  2  0  1\n");
02159   printf("    12  1\n");
02160   printf("       1     1   9     5\n");
02161   printf("       2     5   7     1\n");
02162   printf("       3     8   7     1\n");
02163   printf("       4     6   8    10\n");
02164   printf("       5     5   6     1\n");
02165   printf("       6     3  10     1\n");
02166   printf("       7     4  11     1\n");
02167   printf("       8     2  12     1\n");
02168   printf("       9     9   2     5\n");
02169   printf("      10    10   1     1\n");
02170   printf("      11    11   3     1\n");
02171   printf("      12    12   4     1\n");
02172   printf("    1\n");
02173   printf("       1   1.5 1.5\n");
02174   printf("    # Generated by triangle -pqc box.poly\n\n");
02175   printf("Refinement and Area Constraints:\n\n");
02176   printf(
02177 "  The -r switch causes a mesh (.node and .ele files) to be read and\n");
02178   printf(
02179 "  refined.  If the -p switch is also used, a .poly file is read and used to\n"
02180 );
02181   printf(
02182 "  specify edges that are constrained and cannot be eliminated (although\n");
02183   printf(
02184 "  they can be divided into smaller edges) by the refinement process.\n");
02185   printf("\n");
02186   printf(
02187 "  When you refine a mesh, you generally want to impose tighter quality\n");
02188   printf(
02189 "  constraints.  One way to accomplish this is to use -q with a larger\n");
02190   printf(
02191 "  angle, or -a followed by a smaller area than you used to generate the\n");
02192   printf(
02193 "  mesh you are refining.  Another way to do this is to create an .area\n");
02194   printf(
02195 "  file, which specifies a maximum area for each triangle, and use the -a\n");
02196   printf(
02197 "  switch (without a number following).  Each triangle's area constraint is\n"
02198 );
02199   printf(
02200 "  applied to that triangle.  Area constraints tend to diffuse as the mesh\n");
02201   printf(
02202 "  is refined, so if there are large variations in area constraint between\n");
02203   printf("  adjacent triangles, you may not get the results you want.\n\n");
02204   printf(
02205 "  If you are refining a mesh composed of linear (three-node) elements, the\n"
02206 );
02207   printf(
02208 "  output mesh will contain all the nodes present in the input mesh, in the\n"
02209 );
02210   printf(
02211 "  same order, with new nodes added at the end of the .node file.  However,\n"
02212 );
02213   printf(
02214 "  there is no guarantee that each output element is contained in a single\n");
02215   printf(
02216 "  input element.  Often, output elements will overlap two input elements,\n");
02217   printf(
02218 "  and input edges are not present in the output mesh.  Hence, a sequence of\n"
02219 );
02220   printf(
02221 "  refined meshes will form a hierarchy of nodes, but not a hierarchy of\n");
02222   printf(
02223 "  elements.  If you a refining a mesh of higher-order elements, the\n");
02224   printf(
02225 "  hierarchical property applies only to the nodes at the corners of an\n");
02226   printf("  element; other nodes may not be present in the refined mesh.\n\n");
02227   printf(
02228 "  It is important to understand that maximum area constraints in .poly\n");
02229   printf(
02230 "  files are handled differently from those in .area files.  A maximum area\n"
02231 );
02232   printf(
02233 "  in a .poly file applies to the whole (segment-bounded) region in which a\n"
02234 );
02235   printf(
02236 "  point falls, whereas a maximum area in an .area file applies to only one\n"
02237 );
02238   printf(
02239 "  triangle.  Area constraints in .poly files are used only when a mesh is\n");
02240   printf(
02241 "  first generated, whereas area constraints in .area files are used only to\n"
02242 );
02243   printf(
02244 "  refine an existing mesh, and are typically based on a posteriori error\n");
02245   printf(
02246 "  estimates resulting from a finite element simulation on that mesh.\n");
02247   printf("\n");
02248   printf(
02249 "  `triangle -rq25 object.1' will read object.1.node and object.1.ele, then\n"
02250 );
02251   printf(
02252 "  refine the triangulation to enforce a 25 degree minimum angle, and then\n");
02253   printf(
02254 "  write the refined triangulation to object.2.node and object.2.ele.\n");
02255   printf("\n");
02256   printf(
02257 "  `triangle -rpaa6.2 z.3' will read z.3.node, z.3.ele, z.3.poly, and\n");
02258   printf(
02259 "  z.3.area.  After reconstructing the mesh and its segments, Triangle will\n"
02260 );
02261   printf(
02262 "  refine the mesh so that no triangle has area greater than 6.2, and\n");
02263   printf(
02264 "  furthermore the triangles satisfy the maximum area constraints in\n");
02265   printf(
02266 "  z.3.area.  The output is written to z.4.node, z.4.ele, and z.4.poly.\n");
02267   printf("\n");
02268   printf(
02269 "  The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
02270   printf(
02271 "  x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
02272   printf("  suitable for multigrid.\n\n");
02273   printf("Convex Hulls and Mesh Boundaries:\n\n");
02274   printf(
02275 "  If the input is a point set (rather than a PSLG), Triangle produces its\n");
02276   printf(
02277 "  convex hull as a by-product in the output .poly file if you use the -c\n");
02278   printf(
02279 "  switch.  There are faster algorithms for finding a two-dimensional convex\n"
02280 );
02281   printf(
02282 "  hull than triangulation, of course, but this one comes for free.  If the\n"
02283 );
02284   printf(
02285 "  input is an unconstrained mesh (you are using the -r switch but not the\n");
02286   printf(
02287 "  -p switch), Triangle produces a list of its boundary edges (including\n");
02288   printf("  hole boundaries) as a by-product if you use the -c switch.\n\n");
02289   printf("Voronoi Diagrams:\n\n");
02290   printf(
02291 "  The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
02292   printf(
02293 "  .v.edge.  For example, `triangle -v points' will read points.node,\n");
02294   printf(
02295 "  produce its Delaunay triangulation in points.1.node and points.1.ele,\n");
02296   printf(
02297 "  and produce its Voronoi diagram in points.1.v.node and points.1.v.edge.\n");
02298   printf(
02299 "  The .v.node file contains a list of all Voronoi vertices, and the .v.edge\n"
02300 );
02301   printf(
02302 "  file contains a list of all Voronoi edges, some of which may be infinite\n"
02303 );
02304   printf(
02305 "  rays.  (The choice of filenames makes it easy to run the set of Voronoi\n");
02306   printf("  vertices through Triangle, if so desired.)\n\n");
02307   printf(
02308 "  This implementation does not use exact arithmetic to compute the Voronoi\n"
02309 );
02310   printf(
02311 "  vertices, and does not check whether neighboring vertices are identical.\n"
02312 );
02313   printf(
02314 "  Be forewarned that if the Delaunay triangulation is degenerate or\n");
02315   printf(
02316 "  near-degenerate, the Voronoi diagram may have duplicate points, crossing\n"
02317 );
02318   printf(
02319 "  edges, or infinite rays whose direction vector is zero.  Also, if you\n");
02320   printf(
02321 "  generate a constrained (as opposed to conforming) Delaunay triangulation,\n"
02322 );
02323   printf(
02324 "  or if the triangulation has holes, the corresponding Voronoi diagram is\n");
02325   printf("  likely to have crossing edges and unlikely to make sense.\n\n");
02326   printf("Mesh Topology:\n\n");
02327   printf(
02328 "  You may wish to know which triangles are adjacent to a certain Delaunay\n");
02329   printf(
02330 "  edge in an .edge file, which Voronoi regions are adjacent to a certain\n");
02331   printf(
02332 "  Voronoi edge in a .v.edge file, or which Voronoi regions are adjacent to\n"
02333 );
02334   printf(
02335 "  each other.  All of this information can be found by cross-referencing\n");
02336   printf(
02337 "  output files with the recollection that the Delaunay triangulation and\n");
02338   printf("  the Voronoi diagrams are planar duals.\n\n");
02339   printf(
02340 "  Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
02341   printf(
02342 "  the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
02343   printf(
02344 "  wise from the Voronoi edge.  Triangle j of an .ele file is the dual of\n");
02345   printf(
02346 "  vertex j of the corresponding .v.node file; and Voronoi region k is the\n");
02347   printf("  dual of point k of the corresponding .node file.\n\n");
02348   printf(
02349 "  Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
02350   printf(
02351 "  vertices of the corresponding Voronoi edge; their dual triangles are on\n");
02352   printf(
02353 "  the left and right of the Delaunay edge, respectively.  To find the\n");
02354   printf(
02355 "  Voronoi regions adjacent to a Voronoi edge, look at the endpoints of the\n"
02356 );
02357   printf(
02358 "  corresponding Delaunay edge; their dual regions are on the right and left\n"
02359 );
02360   printf(
02361 "  of the Voronoi edge, respectively.  To find which Voronoi regions are\n");
02362   printf("  adjacent to each other, just read the list of Delaunay edges.\n");
02363   printf("\n");
02364   printf("Statistics:\n");
02365   printf("\n");
02366   printf(
02367 "  After generating a mesh, Triangle prints a count of the number of points,\n"
02368 );
02369   printf(
02370 "  triangles, edges, boundary edges, and segments in the output mesh.  If\n");
02371   printf(
02372 "  you've forgotten the statistics for an existing mesh, the -rNEP switches\n"
02373 );
02374   printf(
02375 "  (or -rpNEP if you've got a .poly file for the existing mesh) will\n");
02376   printf("  regenerate these statistics without writing any output.\n\n");
02377   printf(
02378 "  The -V switch produces extended statistics, including a rough estimate\n");
02379   printf(
02380 "  of memory use and a histogram of triangle aspect ratios and angles in the\n"
02381 );
02382   printf("  mesh.\n\n");
02383   printf("Exact Arithmetic:\n\n");
02384   printf(
02385 "  Triangle uses adaptive exact arithmetic to perform what computational\n");
02386   printf(
02387 "  geometers call the `orientation' and `incircle' tests.  If the floating-\n"
02388 );
02389   printf(
02390 "  point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
02391   printf(
02392 "  most workstations do), and does not use extended precision internal\n");
02393   printf(
02394 "  registers, then your output is guaranteed to be an absolutely true\n");
02395   printf("  Delaunay or conforming Delaunay triangulation, roundoff error\n");
02396   printf(
02397 "  notwithstanding.  The word `adaptive' implies that these arithmetic\n");
02398   printf(
02399 "  routines compute the result only to the precision necessary to guarantee\n"
02400 );
02401   printf(
02402 "  correctness, so they are usually nearly as fast as their approximate\n");
02403   printf(
02404 "  counterparts.  The exact tests can be disabled with the -X switch.  On\n");
02405   printf(
02406 "  most inputs, this switch will reduce the computation time by about eight\n"
02407 );
02408   printf(
02409 "  percent - it's not worth the risk.  There are rare difficult inputs\n");
02410   printf(
02411 "  (having many collinear and cocircular points), however, for which the\n");
02412   printf(
02413 "  difference could be a factor of two.  These are precisely the inputs most\n"
02414 );
02415   printf("  likely to cause errors if you use the -X switch.\n\n");
02416   printf(
02417 "  Unfortunately, these routines don't solve every numerical problem.  Exact\n"
02418 );
02419   printf(
02420 "  arithmetic is not used to compute the positions of points, because the\n");
02421   printf(
02422 "  bit complexity of point coordinates would grow without bound.  Hence,\n");
02423   printf(
02424 "  segment intersections aren't computed exactly; in very unusual cases,\n");
02425   printf(
02426 "  roundoff error in computing an intersection point might actually lead to\n"
02427 );
02428   printf(
02429 "  an inverted triangle and an invalid triangulation.  (This is one reason\n");
02430   printf(
02431 "  to compute your own intersection points in your .poly files.)  Similarly,\n"
02432 );
02433   printf(
02434 "  exact arithmetic is not used to compute the vertices of the Voronoi\n");
02435   printf("  diagram.\n\n");
02436   printf(
02437 "  Underflow and overflow can also cause difficulties; the exact arithmetic\n"
02438 );
02439   printf(
02440 "  routines do not ameliorate out-of-bounds exponents, which can arise\n");
02441   printf(
02442 "  during the orientation and incircle tests.  As a rule of thumb, you\n");
02443   printf(
02444 "  should ensure that your input values are within a range such that their\n");
02445   printf(
02446 "  third powers can be taken without underflow or overflow.  Underflow can\n");
02447   printf(
02448 "  silently prevent the tests from being performed exactly, while overflow\n");
02449   printf("  will typically cause a floating exception.\n\n");
02450   printf("Calling Triangle from Another Program:\n\n");
02451   printf("  Read the file triangle.h for details.\n\n");
02452   printf("Troubleshooting:\n\n");
02453   printf("  Please read this section before mailing me bugs.\n\n");
02454   printf("  `My output mesh has no triangles!'\n\n");
02455   printf(
02456 "    If you're using a PSLG, you've probably failed to specify a proper set\n"
02457 );
02458   printf(
02459 "    of bounding segments, or forgotten to use the -c switch.  Or you may\n");
02460   printf(
02461 "    have placed a hole badly.  To test these possibilities, try again with\n"
02462 );
02463   printf(
02464 "    the -c and -O switches.  Alternatively, all your input points may be\n");
02465   printf(
02466 "    collinear, in which case you can hardly expect to triangulate them.\n");
02467   printf("\n");
02468   printf("  `Triangle doesn't terminate, or just crashes.'\n");
02469   printf("\n");
02470   printf(
02471 "    Bad things can happen when triangles get so small that the distance\n");
02472   printf(
02473 "    between their vertices isn't much larger than the precision of your\n");
02474   printf(
02475 "    machine's arithmetic.  If you've compiled Triangle for single-precision\n"
02476 );
02477   printf(
02478 "    arithmetic, you might do better by recompiling it for double-precision.\n"
02479 );
02480   printf(
02481 "    Then again, you might just have to settle for more lenient constraints\n"
02482 );
02483   printf(
02484 "    on the minimum angle and the maximum area than you had planned.\n");
02485   printf("\n");
02486   printf(
02487 "    You can minimize precision problems by ensuring that the origin lies\n");
02488   printf(
02489 "    inside your point set, or even inside the densest part of your\n");
02490   printf(
02491 "    mesh.  On the other hand, if you're triangulating an object whose x\n");
02492   printf(
02493 "    coordinates all fall between 6247133 and 6247134, you're not leaving\n");
02494   printf("    much floating-point precision for Triangle to work with.\n\n");
02495   printf(
02496 "    Precision problems can occur covertly if the input PSLG contains two\n");
02497   printf(
02498 "    segments that meet (or intersect) at a very small angle, or if such an\n"
02499 );
02500   printf(
02501 "    angle is introduced by the -c switch, which may occur if a point lies\n");
02502   printf(
02503 "    ever-so-slightly inside the convex hull, and is connected by a PSLG\n");
02504   printf(
02505 "    segment to a point on the convex hull.  If you don't realize that a\n");
02506   printf(
02507 "    small angle is being formed, you might never discover why Triangle is\n");
02508   printf(
02509 "    crashing.  To check for this possibility, use the -S switch (with an\n");
02510   printf(
02511 "    appropriate limit on the number of Steiner points, found by trial-and-\n"
02512 );
02513   printf(
02514 "    error) to stop Triangle early, and view the output .poly file with\n");
02515   printf(
02516 "    Show Me (described below).  Look carefully for small angles between\n");
02517   printf(
02518 "    segments; zoom in closely, as such segments might look like a single\n");
02519   printf("    segment from a distance.\n\n");
02520   printf(
02521 "    If some of the input values are too large, Triangle may suffer a\n");
02522   printf(
02523 "    floating exception due to overflow when attempting to perform an\n");
02524   printf(
02525 "    orientation or incircle test.  (Read the section on exact arithmetic\n");
02526   printf(
02527 "    above.)  Again, I recommend compiling Triangle for double (rather\n");
02528   printf("    than single) precision arithmetic.\n\n");
02529   printf(
02530 "  `The numbering of the output points doesn't match the input points.'\n");
02531   printf("\n");
02532   printf(
02533 "    You may have eaten some of your input points with a hole, or by placing\n"
02534 );
02535   printf("    them outside the area enclosed by segments.\n\n");
02536   printf(
02537 "  `Triangle executes without incident, but when I look at the resulting\n");
02538   printf(
02539 "  mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
02540   printf("\n");
02541   printf(
02542 "    If you select the -X switch, Triangle's divide-and-conquer Delaunay\n");
02543   printf(
02544 "    triangulation algorithm occasionally makes mistakes due to floating-\n");
02545   printf(
02546 "    point roundoff error.  Although these errors are rare, don't use the -X\n"
02547 );
02548   printf("    switch.  If you still have problems, please report the bug.\n");
02549   printf("\n");
02550   printf(
02551 "  Strange things can happen if you've taken liberties with your PSLG.  Do\n");
02552   printf(
02553 "  you have a point lying in the middle of a segment?  Triangle sometimes\n");
02554   printf(
02555 "  copes poorly with that sort of thing.  Do you want to lay out a collinear\n"
02556 );
02557   printf(
02558 "  row of evenly spaced, segment-connected points?  Have you simply defined\n"
02559 );
02560   printf(
02561 "  one long segment connecting the leftmost point to the rightmost point,\n");
02562   printf(
02563 "  and a bunch of points lying along it?  This method occasionally works,\n");
02564   printf(
02565 "  especially with horizontal and vertical lines, but often it doesn't, and\n"
02566 );
02567   printf(
02568 "  you'll have to connect each adjacent pair of points with a separate\n");
02569   printf("  segment.  If you don't like it, tough.\n\n");
02570   printf(
02571 "  Furthermore, if you have segments that intersect other than at their\n");
02572   printf(
02573 "  endpoints, try not to let the intersections fall extremely close to PSLG\n"
02574 );
02575   printf("  points or each other.\n\n");
02576   printf(
02577 "  If you have problems refining a triangulation not produced by Triangle:\n");
02578   printf(
02579 "  Are you sure the triangulation is geometrically valid?  Is it formatted\n");
02580   printf(
02581 "  correctly for Triangle?  Are the triangles all listed so the first three\n"
02582 );
02583   printf("  points are their corners in counterclockwise order?\n\n");
02584   printf("Show Me:\n\n");
02585   printf(
02586 "  Triangle comes with a separate program named `Show Me', whose primary\n");
02587   printf(
02588 "  purpose is to draw meshes on your screen or in PostScript.  Its secondary\n"
02589 );
02590   printf(
02591 "  purpose is to check the validity of your input files, and do so more\n");
02592   printf(
02593 "  thoroughly than Triangle does.  Show Me requires that you have the X\n");
02594   printf(
02595 "  Windows system.  If you didn't receive Show Me with Triangle, complain to\n"
02596 );
02597   printf("  whomever you obtained Triangle from, then send me mail.\n\n");
02598   printf("Triangle on the Web:\n\n");
02599   printf(
02600 "  To see an illustrated, updated version of these instructions, check out\n");
02601   printf("\n");
02602   printf("    http://www.cs.cmu.edu/~quake/triangle.html\n");
02603   printf("\n");
02604   printf("A Brief Plea:\n");
02605   printf("\n");
02606   printf(
02607 "  If you use Triangle, and especially if you use it to accomplish real\n");
02608   printf(
02609 "  work, I would like very much to hear from you.  A short letter or email\n");
02610   printf(
02611 "  (to jrs@cs.cmu.edu) describing how you use Triangle will mean a lot to\n");
02612   printf(
02613 "  me.  The more people I know are using this program, the more easily I can\n"
02614 );
02615   printf(
02616 "  justify spending time on improvements and on the three-dimensional\n");
02617   printf(
02618 "  successor to Triangle, which in turn will benefit you.  Also, I can put\n");
02619   printf(
02620 "  you on a list to receive email whenever a new version of Triangle is\n");
02621   printf("  available.\n\n");
02622   printf(
02623 "  If you use a mesh generated by Triangle in a publication, please include\n"
02624 );
02625   printf("  an acknowledgment as well.\n\n");
02626   printf("Research credit:\n\n");
02627   printf(
02628 "  Of course, I can take credit for only a fraction of the ideas that made\n");
02629   printf(
02630 "  this mesh generator possible.  Triangle owes its existence to the efforts\n"
02631 );
02632   printf(
02633 "  of many fine computational geometers and other researchers, including\n");
02634   printf(
02635 "  Marshall Bern, L. Paul Chew, Boris Delaunay, Rex A. Dwyer, David\n");
02636   printf(
02637 "  Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E. Knuth, C. L.\n");
02638   printf(
02639 "  Lawson, Der-Tsai Lee, Ernst P. Mucke, Douglas M. Priest, Jim Ruppert,\n");
02640   printf(
02641 "  Isaac Saias, Bruce J. Schachter, Micha Sharir, Jorge Stolfi, Christopher\n"
02642 );
02643   printf(
02644 "  J. Van Wyk, David F. Watson, and Binhai Zhu.  See the comments at the\n");
02645   printf("  beginning of the source code for references.\n\n");
02646   exit(0);
02647 }
02648 
02649 #endif /* not TRILIBRARY */
02650 
02651 /*****************************************************************************/
02652 /*                                                                           */
02653 /*  internalerror()   Ask the user to send me the defective product.  Exit.  */
02654 /*                                                                           */
02655 /*****************************************************************************/
02656 
02657 void internalerror()
02658 {
02659   printf("  Please report this bug to jrs@cs.cmu.edu\n");
02660   printf("  Include the message above, your input data set, and the exact\n");
02661   printf("    command line you used to run Triangle.\n");
02662   exit(1);
02663 }
02664 
02665 /*****************************************************************************/
02666 /*                                                                           */
02667 /*  parsecommandline()   Read the command line, identify switches, and set   */
02668 /*                       up options and file names.                          */
02669 /*                                                                           */
02670 /*  The effects of this routine are felt entirely through global variables.  */
02671 /*                                                                           */
02672 /*****************************************************************************/
02673 
02674 void parsecommandline(argc, argv)
02675 int argc;
02676 char **argv;
02677 {
02678 #ifdef TRILIBRARY
02679 #define STARTINDEX 0
02680 #else /* not TRILIBRARY */
02681 #define STARTINDEX 1
02682   int increment;
02683   int meshnumber;
02684 #endif /* not TRILIBRARY */
02685   int i, j, k;
02686   char workstring[FILENAMESIZE];
02687 
02688   poly = refine = quality = vararea = fixedarea = regionattrib = convex = 0;
02689   firstnumber = 1;
02690   edgesout = voronoi = neighbors = geomview = 0;
02691   nobound = nopolywritten = nonodewritten = noelewritten = noiterationnum = 0;
02692   noholes = noexact = 0;
02693   incremental = sweepline = 0;
02694   dwyer = 1;
02695   splitseg = 0;
02696   docheck = 0;
02697   nobisect = 0;
02698   steiner = -1;
02699   order = 1;
02700   minangle = 0.0;
02701   maxarea = -1.0;
02702   quiet = verbose = 0;
02703 #ifndef TRILIBRARY
02704   innodefilename[0] = '\0';
02705 #endif /* not TRILIBRARY */
02706 
02707   for (i = STARTINDEX; i < argc; i++) {
02708 #ifndef TRILIBRARY
02709     if (argv[i][0] == '-') {
02710 #endif /* not TRILIBRARY */
02711       for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
02712         if (argv[i][j] == 'p') {
02713           poly = 1;
02714         }
02715 #ifndef CDT_ONLY
02716         if (argv[i][j] == 'r') {
02717           refine = 1;
02718         }
02719         if (argv[i][j] == 'q') {
02720           quality = 1;
02721           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
02722               (argv[i][j + 1] == '.')) {
02723             k = 0;
02724             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
02725                    (argv[i][j + 1] == '.')) {
02726               j++;
02727               workstring[k] = argv[i][j];
02728               k++;
02729             }
02730             workstring[k] = '\0';
02731             minangle = (REAL) strtod(workstring, (char **) NULL);
02732           } else {
02733             minangle = 20.0;
02734           }
02735         }
02736         if (argv[i][j] == 'a') {
02737           quality = 1;
02738           if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
02739               (argv[i][j + 1] == '.')) {
02740             fixedarea = 1;
02741             k = 0;
02742             while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
02743                    (argv[i][j + 1] == '.')) {
02744               j++;
02745               workstring[k] = argv[i][j];
02746               k++;
02747             }
02748             workstring[k] = '\0';
02749             maxarea = (REAL) strtod(workstring, (char **) NULL);
02750             if (maxarea <= 0.0) {
02751               printf("Error:  Maximum area must be greater than zero.\n");
02752               exit(1);
02753             }
02754           } else {
02755             vararea = 1;
02756           }
02757         }
02758 #endif /* not CDT_ONLY */
02759         if (argv[i][j] == 'A') {
02760           regionattrib = 1;
02761         }
02762         if (argv[i][j] == 'c') {
02763           convex = 1;
02764         }
02765         if (argv[i][j] == 'z') {
02766           firstnumber = 0;
02767         }
02768         if (argv[i][j] == 'e') {
02769           edgesout = 1;
02770         }
02771         if (argv[i][j] == 'v') {
02772           voronoi = 1;
02773         }
02774         if (argv[i][j] == 'n') {
02775           neighbors = 1;
02776         }
02777         if (argv[i][j] == 'g') {
02778           geomview = 1;
02779         }
02780         if (argv[i][j] == 'B') {
02781           nobound = 1;
02782         }
02783         if (argv[i][j] == 'P') {
02784           nopolywritten = 1;
02785         }
02786         if (argv[i][j] == 'N') {
02787           nonodewritten = 1;
02788         }
02789         if (argv[i][j] == 'E') {
02790           noelewritten = 1;
02791         }
02792 #ifndef TRILIBRARY
02793         if (argv[i][j] == 'I') {
02794           noiterationnum = 1;
02795         }
02796 #endif /* not TRILIBRARY */
02797         if (argv[i][j] == 'O') {
02798           noholes = 1;
02799         }
02800         if (argv[i][j] == 'X') {
02801           noexact = 1;
02802         }
02803         if (argv[i][j] == 'o') {
02804           if (argv[i][j + 1] == '2') {
02805             j++;
02806             order = 2;
02807           }
02808         }
02809 #ifndef CDT_ONLY
02810         if (argv[i][j] == 'Y') {
02811           nobisect++;
02812         }
02813         if (argv[i][j] == 'S') {
02814           steiner = 0;
02815           while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
02816             j++;
02817             steiner = steiner * 10 + (int) (argv[i][j] - '0');
02818           }
02819         }
02820 #endif /* not CDT_ONLY */
02821 #ifndef REDUCED
02822         if (argv[i][j] == 'i') {
02823           incremental = 1;
02824         }
02825         if (argv[i][j] == 'F') {
02826           sweepline = 1;
02827         }
02828 #endif /* not REDUCED */
02829         if (argv[i][j] == 'l') {
02830           dwyer = 0;
02831         }
02832 #ifndef REDUCED
02833 #ifndef CDT_ONLY
02834         if (argv[i][j] == 's') {
02835           splitseg = 1;
02836         }
02837 #endif /* not CDT_ONLY */
02838         if (argv[i][j] == 'C') {
02839           docheck = 1;
02840         }
02841 #endif /* not REDUCED */
02842         if (argv[i][j] == 'Q') {
02843           quiet = 1;
02844         }
02845         if (argv[i][j] == 'V') {
02846           verbose++;
02847         }
02848 #ifndef TRILIBRARY
02849         if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
02850             (argv[i][j] == '?')) {
02851           info();
02852         }
02853 #endif /* not TRILIBRARY */
02854       }
02855 #ifndef TRILIBRARY
02856     } else {
02857       strncpy(innodefilename, argv[i], FILENAMESIZE - 1);
02858       innodefilename[FILENAMESIZE - 1] = '\0';
02859     }
02860 #endif /* not TRILIBRARY */
02861   }
02862 #ifndef TRILIBRARY
02863   if (innodefilename[0] == '\0') {
02864     syntax();
02865   }
02866   if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".node")) {
02867     innodefilename[strlen(innodefilename) - 5] = '\0';
02868   }
02869   if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".poly")) {
02870     innodefilename[strlen(innodefilename) - 5] = '\0';
02871     poly = 1;
02872   }
02873 #ifndef CDT_ONLY
02874   if (!strcmp(&innodefilename[strlen(innodefilename) - 4], ".ele")) {
02875     innodefilename[strlen(innodefilename) - 4] = '\0';
02876     refine = 1;
02877   }
02878   if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".area")) {
02879     innodefilename[strlen(innodefilename) - 5] = '\0';
02880     refine = 1;
02881     quality = 1;
02882     vararea = 1;
02883   }
02884 #endif /* not CDT_ONLY */
02885 #endif /* not TRILIBRARY */
02886   steinerleft = steiner;
02887   useshelles = poly || refine || quality || convex;
02888   goodangle = cos(minangle * PI / 180.0);
02889   goodangle *= goodangle;
02890   if (refine && noiterationnum) {
02891     printf(
02892       "Error:  You cannot use the -I switch when refining a triangulation.\n");
02893     exit(1);
02894   }
02895   /* Be careful not to allocate space for element area constraints that */
02896   /*   will never be assigned any value (other than the default -1.0).  */
02897   if (!refine && !poly) {
02898     vararea = 0;
02899   }
02900   /* Be careful not to add an extra attribute to each element unless the */
02901   /*   input supports it (PSLG in, but not refining a preexisting mesh). */
02902   if (refine || !poly) {
02903     regionattrib = 0;
02904   }
02905 
02906 #ifndef TRILIBRARY
02907   strcpy(inpolyfilename, innodefilename);
02908   strcpy(inelefilename, innodefilename);
02909   strcpy(areafilename, innodefilename);
02910   increment = 0;
02911   strcpy(workstring, innodefilename);
02912   j = 1;
02913   while (workstring[j] != '\0') {
02914     if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
02915       increment = j + 1;
02916     }
02917     j++;
02918   }
02919   meshnumber = 0;
02920   if (increment > 0) {
02921     j = increment;
02922     do {
02923       if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
02924         meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
02925       } else {
02926         increment = 0;
02927       }
02928       j++;
02929     } while (workstring[j] != '\0');
02930   }
02931   if (noiterationnum) {
02932     strcpy(outnodefilename, innodefilename);
02933     strcpy(outelefilename, innodefilename);
02934     strcpy(edgefilename, innodefilename);
02935     strcpy(vnodefilename, innodefilename);
02936     strcpy(vedgefilename, innodefilename);
02937     strcpy(neighborfilename, innodefilename);
02938     strcpy(offfilename, innodefilename);
02939     strcat(outnodefilename, ".node");
02940     strcat(outelefilename, ".ele");
02941     strcat(edgefilename, ".edge");
02942     strcat(vnodefilename, ".v.node");
02943     strcat(vedgefilename, ".v.edge");
02944     strcat(neighborfilename, ".neigh");
02945     strcat(offfilename, ".off");
02946   } else if (increment == 0) {
02947     strcpy(outnodefilename, innodefilename);
02948     strcpy(outpolyfilename, innodefilename);
02949     strcpy(outelefilename, innodefilename);
02950     strcpy(edgefilename, innodefilename);
02951     strcpy(vnodefilename, innodefilename);
02952     strcpy(vedgefilename, innodefilename);
02953     strcpy(neighborfilename, innodefilename);
02954     strcpy(offfilename, innodefilename);
02955     strcat(outnodefilename, ".1.node");
02956     strcat(outpolyfilename, ".1.poly");
02957     strcat(outelefilename, ".1.ele");
02958     strcat(edgefilename, ".1.edge");
02959     strcat(vnodefilename, ".1.v.node");
02960     strcat(vedgefilename, ".1.v.edge");
02961     strcat(neighborfilename, ".1.neigh");
02962     strcat(offfilename, ".1.off");
02963   } else {
02964     workstring[increment] = '%';
02965     workstring[increment + 1] = 'd';
02966     workstring[increment + 2] = '\0';
02967     sprintf(outnodefilename, workstring, meshnumber + 1);
02968     strcpy(outpolyfilename, outnodefilename);
02969     strcpy(outelefilename, outnodefilename);
02970     strcpy(edgefilename, outnodefilename);
02971     strcpy(vnodefilename, outnodefilename);
02972     strcpy(vedgefilename, outnodefilename);
02973     strcpy(neighborfilename, outnodefilename);
02974     strcpy(offfilename, outnodefilename);
02975     strcat(outnodefilename, ".node");
02976     strcat(outpolyfilename, ".poly");
02977     strcat(outelefilename, ".ele");
02978     strcat(edgefilename, ".edge");
02979     strcat(vnodefilename, ".v.node");
02980     strcat(vedgefilename, ".v.edge");
02981     strcat(neighborfilename, ".neigh");
02982     strcat(offfilename, ".off");
02983   }
02984   strcat(innodefilename, ".node");
02985   strcat(inpolyfilename, ".poly");
02986   strcat(inelefilename, ".ele");
02987   strcat(areafilename, ".area");
02988 #endif /* not TRILIBRARY */
02989 }
02990 
02991 /**                                                                         **/
02992 /**                                                                         **/
02993 /********* User interaction routines begin here                      *********/
02994 
02995 /********* Debugging routines begin here                             *********/
02996 /**                                                                         **/
02997 /**                                                                         **/
02998 
02999 /*****************************************************************************/
03000 /*                                                                           */
03001 /*  printtriangle()   Print out the details of a triangle/edge handle.       */
03002 /*                                                                           */
03003 /*  I originally wrote this procedure to simplify debugging; it can be       */
03004 /*  called directly from the debugger, and presents information about a      */
03005 /*  triangle/edge handle in digestible form.  It's also used when the        */
03006 /*  highest level of verbosity (`-VVV') is specified.                        */
03007 /*                                                                           */
03008 /*****************************************************************************/
03009 
03010 void printtriangle(t)
03011 struct triedge *t;
03012 {
03013   struct triedge printtri;
03014   struct edge printsh;
03015   point printpoint;
03016 
03017   printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
03018          t->orient);
03019   decode(t->tri[0], printtri);
03020   if (printtri.tri == dummytri) {
03021     printf("    [0] = Outer space\n");
03022   } else {
03023     printf("    [0] = x%lx  %d\n", (unsigned long) printtri.tri,
03024            printtri.orient);
03025   }
03026   decode(t->tri[1], printtri);
03027   if (printtri.tri == dummytri) {
03028     printf("    [1] = Outer space\n");
03029   } else {
03030     printf("    [1] = x%lx  %d\n", (unsigned long) printtri.tri,
03031            printtri.orient);
03032   }
03033   decode(t->tri[2], printtri);
03034   if (printtri.tri == dummytri) {
03035     printf("    [2] = Outer space\n");
03036   } else {
03037     printf("    [2] = x%lx  %d\n", (unsigned long) printtri.tri,
03038            printtri.orient);
03039   }
03040   org(*t, printpoint);
03041   if (printpoint == (point) NULL)
03042     printf("    Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
03043   else
03044     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
03045            (t->orient + 1) % 3 + 3, (unsigned long) printpoint,
03046            printpoint[0], printpoint[1]);
03047   dest(*t, printpoint);
03048   if (printpoint == (point) NULL)
03049     printf("    Dest  [%d] = NULL\n", (t->orient + 2) % 3 + 3);
03050   else
03051     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
03052            (t->orient + 2) % 3 + 3, (unsigned long) printpoint,
03053            printpoint[0], printpoint[1]);
03054   apex(*t, printpoint);
03055   if (printpoint == (point) NULL)
03056     printf("    Apex  [%d] = NULL\n", t->orient + 3);
03057   else
03058     printf("    Apex  [%d] = x%lx  (%.12g, %.12g)\n",
03059            t->orient + 3, (unsigned long) printpoint,
03060            printpoint[0], printpoint[1]);
03061   if (useshelles) {
03062     sdecode(t->tri[6], printsh);
03063     if (printsh.sh != dummysh) {
03064       printf("    [6] = x%lx  %d\n", (unsigned long) printsh.sh,
03065              printsh.shorient);
03066     }
03067     sdecode(t->tri[7], printsh);
03068     if (printsh.sh != dummysh) {
03069       printf("    [7] = x%lx  %d\n", (unsigned long) printsh.sh,
03070              printsh.shorient);
03071     }
03072     sdecode(t->tri[8], printsh);
03073     if (printsh.sh != dummysh) {
03074       printf("    [8] = x%lx  %d\n", (unsigned long) printsh.sh,
03075              printsh.shorient);
03076     }
03077   }
03078   if (vararea) {
03079     printf("    Area constraint:  %.4g\n", areabound(*t));
03080   }
03081 }
03082 
03083 /*****************************************************************************/
03084 /*                                                                           */
03085 /*  printshelle()   Print out the details of a shell edge handle.            */
03086 /*                                                                           */
03087 /*  I originally wrote this procedure to simplify debugging; it can be       */
03088 /*  called directly from the debugger, and presents information about a      */
03089 /*  shell edge handle in digestible form.  It's also used when the highest   */
03090 /*  level of verbosity (`-VVV') is specified.                                */
03091 /*                                                                           */
03092 /*****************************************************************************/
03093 
03094 void printshelle(s)
03095 struct edge *s;
03096 {
03097   struct edge printsh;
03098   struct triedge printtri;
03099   point printpoint;
03100 
03101   printf("shell edge x%lx with orientation %d and mark %d:\n",
03102          (unsigned long) s->sh, s->shorient, mark(*s));
03103   sdecode(s->sh[0], printsh);
03104   if (printsh.sh == dummysh) {
03105     printf("    [0] = No shell\n");
03106   } else {
03107     printf("    [0] = x%lx  %d\n", (unsigned long) printsh.sh,
03108            printsh.shorient);
03109   }
03110   sdecode(s->sh[1], printsh);
03111   if (printsh.sh == dummysh) {
03112     printf("    [1] = No shell\n");
03113   } else {
03114     printf("    [1] = x%lx  %d\n", (unsigned long) printsh.sh,
03115            printsh.shorient);
03116   }
03117   sorg(*s, printpoint);
03118   if (printpoint == (point) NULL)
03119     printf("    Origin[%d] = NULL\n", 2 + s->shorient);
03120   else
03121     printf("    Origin[%d] = x%lx  (%.12g, %.12g)\n",
03122            2 + s->shorient, (unsigned long) printpoint,
03123            printpoint[0], printpoint[1]);
03124   sdest(*s, printpoint);
03125   if (printpoint == (point) NULL)
03126     printf("    Dest  [%d] = NULL\n", 3 - s->shorient);
03127   else
03128     printf("    Dest  [%d] = x%lx  (%.12g, %.12g)\n",
03129            3 - s->shorient, (unsigned long) printpoint,
03130            printpoint[0], printpoint[1]);
03131   decode(s->sh[4], printtri);
03132   if (printtri.tri == dummytri) {
03133     printf("    [4] = Outer space\n");
03134   } else {
03135     printf("    [4] = x%lx  %d\n", (unsigned long) printtri.tri,
03136            printtri.orient);
03137   }
03138   decode(s->sh[5], printtri);
03139   if (printtri.tri == dummytri) {
03140     printf("    [5] = Outer space\n");
03141   } else {
03142     printf("    [5] = x%lx  %d\n", (unsigned long) printtri.tri,
03143            printtri.orient);
03144   }
03145 }
03146 
03147 /**                                                                         **/
03148 /**                                                                         **/
03149 /********* Debugging routines end here                               *********/
03150 
03151 /********* Memory management routines begin here                     *********/
03152 /**                                                                         **/
03153 /**                                                                         **/
03154 
03155 /*****************************************************************************/
03156 /*                                                                           */
03157 /*  poolinit()   Initialize a pool of memory for allocation of items.        */
03158 /*                                                                           */
03159 /*  This routine initializes the machinery for allocating items.  A `pool'   */
03160 /*  is created whose records have size at least `bytecount'.  Items will be  */
03161 /*  allocated in `itemcount'-item blocks.  Each item is assumed to be a      */
03162 /*  collection of words, and either pointers or floating-point values are    */
03163 /*  assumed to be the "primary" word type.  (The "primary" word type is used */
03164 /*  to determine alignment of items.)  If `alignment' isn't zero, all items  */
03165 /*  will be `alignment'-byte aligned in memory.  `alignment' must be either  */
03166 /*  a multiple or a factor of the primary word size; powers of two are safe. */
03167 /*  `alignment' is normally used to create a few unused bits at the bottom   */
03168 /*  of each item's pointer, in which information may be stored.              */
03169 /*                                                                           */
03170 /*  Don't change this routine unless you understand it.                      */
03171 /*                                                                           */
03172 /*****************************************************************************/
03173 
03174 void poolinit(pool, bytecount, itemcount, wtype, alignment)
03175 struct memorypool *pool;
03176 int bytecount;
03177 int itemcount;
03178 enum wordtype wtype;
03179 int alignment;
03180 {
03181   int wordsize;
03182 
03183   /* Initialize values in the pool. */
03184   pool->itemwordtype = wtype;
03185   wordsize = (pool->itemwordtype == POINTER) ? sizeof(VOID *) : sizeof(REAL);
03186   /* Find the proper alignment, which must be at least as large as:   */
03187   /*   - The parameter `alignment'.                                   */
03188   /*   - The primary word type, to avoid unaligned accesses.          */
03189   /*   - sizeof(VOID *), so the stack of dead items can be maintained */
03190   /*       without unaligned accesses.                                */
03191   if (alignment > wordsize) {
03192     pool->alignbytes = alignment;
03193   } else {
03194     pool->alignbytes = wordsize;
03195   }
03196   if (sizeof(VOID *) > pool->alignbytes) {
03197     pool->alignbytes = sizeof(VOID *);
03198   }
03199   pool->itemwords = ((bytecount + pool->alignbytes - 1) / pool->alignbytes)
03200                   * (pool->alignbytes / wordsize);
03201   pool->itembytes = pool->itemwords * wordsize;
03202   pool->itemsperblock = itemcount;
03203 
03204   /* Allocate a block of items.  Space for `itemsperblock' items and one    */
03205   /*   pointer (to point to the next block) are allocated, as well as space */
03206   /*   to ensure alignment of the items.                                    */
03207   pool->firstblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes
03208                                       + sizeof(VOID *) + pool->alignbytes);
03209   if (pool->firstblock == (VOID **) NULL) {
03210     printf("Error:  Out of memory.\n");
03211     exit(1);
03212   }
03213   /* Set the next block pointer to NULL. */
03214   *(pool->firstblock) = (VOID *) NULL;
03215   poolrestart(pool);
03216 }
03217 
03218 /*****************************************************************************/
03219 /*                                                                           */
03220 /*  poolrestart()   Deallocate all items in a pool.                          */
03221 /*                                                                           */
03222 /*  The pool is returned to its starting state, except that no memory is     */
03223 /*  freed to the operating system.  Rather, the previously allocated blocks  */
03224 /*  are ready to be reused.                                                  */
03225 /*                                                                           */
03226 /*****************************************************************************/
03227 
03228 void poolrestart(pool)
03229 struct memorypool *pool;
03230 {
03231   unsigned long alignptr;
03232 
03233   pool->items = 0;
03234   pool->maxitems = 0;
03235 
03236   /* Set the currently active block. */
03237   pool->nowblock = pool->firstblock;
03238   /* Find the first item in the pool.  Increment by the size of (VOID *). */
03239   alignptr = (unsigned long) (pool->nowblock + 1);
03240   /* Align the item on an `alignbytes'-byte boundary. */
03241   pool->nextitem = (VOID *)
03242     (alignptr + (unsigned long) pool->alignbytes
03243      - (alignptr % (unsigned long) pool->alignbytes));
03244   /* There are lots of unallocated items left in this block. */
03245   pool->unallocateditems = pool->itemsperblock;
03246   /* The stack of deallocated items is empty. */
03247   pool->deaditemstack = (VOID *) NULL;
03248 }
03249 
03250 /*****************************************************************************/
03251 /*                                                                           */
03252 /*  pooldeinit()   Free to the operating system all memory taken by a pool.  */
03253 /*                                                                           */
03254 /*****************************************************************************/
03255 
03256 void pooldeinit(pool)
03257 struct memorypool *pool;
03258 {
03259   while (pool->firstblock != (VOID **) NULL) {
03260     pool->nowblock = (VOID **) *(pool->firstblock);
03261     free(pool->firstblock);
03262     pool->firstblock = pool->nowblock;
03263   }
03264 }
03265 
03266 /*****************************************************************************/
03267 /*                                                                           */
03268 /*  poolalloc()   Allocate space for an item.                                */
03269 /*                                                                           */
03270 /*****************************************************************************/
03271 
03272 VOID *poolalloc(pool)
03273 struct memorypool *pool;
03274 {
03275   VOID *newitem;
03276   VOID **newblock;
03277   unsigned long alignptr;
03278 
03279   /* First check the linked list of dead items.  If the list is not   */
03280   /*   empty, allocate an item from the list rather than a fresh one. */
03281   if (pool->deaditemstack != (VOID *) NULL) {
03282     newitem = pool->deaditemstack;               /* Take first item in list. */
03283     pool->deaditemstack = * (VOID **) pool->deaditemstack;
03284   } else {
03285     /* Check if there are any free items left in the current block. */
03286     if (pool->unallocateditems == 0) {
03287       /* Check if another block must be allocated. */
03288       if (*(pool->nowblock) == (VOID *) NULL) {
03289         /* Allocate a new block of items, pointed to by the previous block. */
03290         newblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes
03291                                     + sizeof(VOID *) + pool->alignbytes);
03292         if (newblock == (VOID **) NULL) {
03293           printf("Error:  Out of memory.\n");
03294           exit(1);
03295         }
03296         *(pool->nowblock) = (VOID *) newblock;
03297         /* The next block pointer is NULL. */
03298         *newblock = (VOID *) NULL;
03299       }
03300       /* Move to the new block. */
03301       pool->nowblock = (VOID **) *(pool->nowblock);
03302       /* Find the first item in the block.    */
03303       /*   Increment by the size of (VOID *). */
03304       alignptr = (unsigned long) (pool->nowblock + 1);
03305       /* Align the item on an `alignbytes'-byte boundary. */
03306       pool->nextitem = (VOID *)
03307         (alignptr + (unsigned long) pool->alignbytes
03308          - (alignptr % (unsigned long) pool->alignbytes));
03309       /* There are lots of unallocated items left in this block. */
03310       pool->unallocateditems = pool->itemsperblock;
03311     }
03312     /* Allocate a new item. */
03313     newitem = pool->nextitem;
03314     /* Advance `nextitem' pointer to next free item in block. */
03315     if (pool->itemwordtype == POINTER) {
03316       pool->nextitem = (VOID *) ((VOID **) pool->nextitem + pool->itemwords);
03317     } else {
03318       pool->nextitem = (VOID *) ((REAL *) pool->nextitem + pool->itemwords);
03319     }
03320     pool->unallocateditems--;
03321     pool->maxitems++;
03322   }
03323   pool->items++;
03324   return newitem;
03325 }
03326 
03327 /*****************************************************************************/
03328 /*                                                                           */
03329 /*  pooldealloc()   Deallocate space for an item.                            */
03330 /*                                                                           */
03331 /*  The deallocated space is stored in a queue for later reuse.              */
03332 /*                                                                           */
03333 /*****************************************************************************/
03334 
03335 void pooldealloc(pool, dyingitem)
03336 struct memorypool *pool;
03337 VOID *dyingitem;
03338 {
03339   /* Push freshly killed item onto stack. */
03340   *((VOID **) dyingitem) = pool->deaditemstack;
03341   pool->deaditemstack = dyingitem;
03342   pool->items--;
03343 }
03344 
03345 /*****************************************************************************/
03346 /*                                                                           */
03347 /*  traversalinit()   Prepare to traverse the entire list of items.          */
03348 /*                                                                           */
03349 /*  This routine is used in conjunction with traverse().                     */
03350 /*                                                                           */
03351 /*****************************************************************************/
03352 
03353 void traversalinit(pool)
03354 struct memorypool *pool;
03355 {
03356   unsigned long alignptr;
03357 
03358   /* Begin the traversal in the first block. */
03359   pool->pathblock = pool->firstblock;
03360   /* Find the first item in the block.  Increment by the size of (VOID *). */
03361   alignptr = (unsigned long) (pool->pathblock + 1);
03362   /* Align with item on an `alignbytes'-byte boundary. */
03363   pool->pathitem = (VOID *)
03364     (alignptr + (unsigned long) pool->alignbytes
03365      - (alignptr % (unsigned long) pool->alignbytes));
03366   /* Set the number of items left in the current block. */
03367   pool->pathitemsleft = pool->itemsperblock;
03368 }
03369 
03370 /*****************************************************************************/
03371 /*                                                                           */
03372 /*  traverse()   Find the next item in the list.                             */
03373 /*                                                                           */
03374 /*  This routine is used in conjunction with traversalinit().  Be forewarned */
03375 /*  that this routine successively returns all items in the list, including  */
03376 /*  deallocated ones on the deaditemqueue.  It's up to you to figure out     */
03377 /*  which ones are actually dead.  Why?  I don't want to allocate extra      */
03378 /*  space just to demarcate dead items.  It can usually be done more         */
03379 /*  space-efficiently by a routine that knows something about the structure  */
03380 /*  of the item.                                                             */
03381 /*                                                                           */
03382 /*****************************************************************************/
03383 
03384 VOID *traverse(pool)
03385 struct memorypool *pool;
03386 {
03387   VOID *newitem;
03388   unsigned long alignptr;
03389 
03390   /* Stop upon exhausting the list of items. */
03391   if (pool->pathitem == pool->nextitem) {
03392     return (VOID *) NULL;
03393   }
03394   /* Check whether any untraversed items remain in the current block. */
03395   if (pool->pathitemsleft == 0) {
03396     /* Find the next block. */
03397     pool->pathblock = (VOID **) *(pool->pathblock);
03398     /* Find the first item in the block.  Increment by the size of (VOID *). */
03399     alignptr = (unsigned long) (pool->pathblock + 1);
03400     /* Align with item on an `alignbytes'-byte boundary. */
03401     pool->pathitem = (VOID *)
03402       (alignptr + (unsigned long) pool->alignbytes
03403        - (alignptr % (unsigned long) pool->alignbytes));
03404     /* Set the number of items left in the current block. */
03405     pool->pathitemsleft = pool->itemsperblock;
03406   }
03407   newitem = pool->pathitem;
03408   /* Find the next item in the block. */
03409   if (pool->itemwordtype == POINTER) {
03410     pool->pathitem = (VOID *) ((VOID **) pool->pathitem + pool->itemwords);
03411   } else {
03412     pool->pathitem = (VOID *) ((REAL *) pool->pathitem + pool->itemwords);
03413   }
03414   pool->pathitemsleft--;
03415   return newitem;
03416 }
03417 
03418 /*****************************************************************************/
03419 /*                                                                           */
03420 /*  dummyinit()   Initialize the triangle that fills "outer space" and the   */
03421 /*                omnipresent shell edge.                                    */
03422 /*                                                                           */
03423 /*  The triangle that fills "outer space", called `dummytri', is pointed to  */
03424 /*  by every triangle and shell edge on a boundary (be it outer or inner) of */
03425 /*  the triangulation.  Also, `dummytri' points to one of the triangles on   */
03426 /*  the convex hull (until the holes and concavities are carved), making it  */
03427 /*  possible to find a starting triangle for point location.                 */
03428 /*                                                                           */
03429 /*  The omnipresent shell edge, `dummysh', is pointed to by every triangle   */
03430 /*  or shell edge that doesn't have a full complement of real shell edges    */
03431 /*  to point to.                                                             */
03432 /*                                                                           */
03433 /*****************************************************************************/
03434 
03435 void dummyinit(trianglewords, shellewords)
03436 int trianglewords;
03437 int shellewords;
03438 {
03439   unsigned long alignptr;
03440 
03441   /* `triwords' and `shwords' are used by the mesh manipulation primitives */
03442   /*   to extract orientations of triangles and shell edges from pointers. */
03443   triwords = trianglewords;       /* Initialize `triwords' once and for all. */
03444   shwords = shellewords;           /* Initialize `shwords' once and for all. */
03445 
03446   /* Set up `dummytri', the `triangle' that occupies "outer space". */
03447   dummytribase = (triangle *) malloc(triwords * sizeof(triangle)
03448                                      + triangles.alignbytes);
03449   if (dummytribase == (triangle *) NULL) {
03450     printf("Error:  Out of memory.\n");
03451     exit(1);
03452   }
03453   /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
03454   alignptr = (unsigned long) dummytribase;
03455   dummytri = (triangle *)
03456     (alignptr + (unsigned long) triangles.alignbytes
03457      - (alignptr % (unsigned long) triangles.alignbytes));
03458   /* Initialize the three adjoining triangles to be "outer space".  These  */
03459   /*   will eventually be changed by various bonding operations, but their */
03460   /*   values don't really matter, as long as they can legally be          */
03461   /*   dereferenced.                                                       */
03462   dummytri[0] = (triangle) dummytri;
03463   dummytri[1] = (triangle) dummytri;
03464   dummytri[2] = (triangle) dummytri;
03465   /* Three NULL vertex points. */
03466   dummytri[3] = (triangle) NULL;
03467   dummytri[4] = (triangle) NULL;
03468   dummytri[5] = (triangle) NULL;
03469 
03470   if (useshelles) {
03471     /* Set up `dummysh', the omnipresent "shell edge" pointed to by any      */
03472     /*   triangle side or shell edge end that isn't attached to a real shell */
03473     /*   edge.                                                               */
03474     dummyshbase = (shelle *) malloc(shwords * sizeof(shelle)
03475                                     + shelles.alignbytes);
03476     if (dummyshbase == (shelle *) NULL) {
03477       printf("Error:  Out of memory.\n");
03478       exit(1);
03479     }
03480     /* Align `dummysh' on a `shelles.alignbytes'-byte boundary. */
03481     alignptr = (unsigned long) dummyshbase;
03482     dummysh = (shelle *)
03483       (alignptr + (unsigned long) shelles.alignbytes
03484        - (alignptr % (unsigned long) shelles.alignbytes));
03485     /* Initialize the two adjoining shell edges to be the omnipresent shell */
03486     /*   edge.  These will eventually be changed by various bonding         */
03487     /*   operations, but their values don't really matter, as long as they  */
03488     /*   can legally be dereferenced.                                       */
03489     dummysh[0] = (shelle) dummysh;
03490     dummysh[1] = (shelle) dummysh;
03491     /* Two NULL vertex points. */
03492     dummysh[2] = (shelle) NULL;
03493     dummysh[3] = (shelle) NULL;
03494     /* Initialize the two adjoining triangles to be "outer space". */
03495     dummysh[4] = (shelle) dummytri;
03496     dummysh[5] = (shelle) dummytri;
03497     /* Set the boundary marker to zero. */
03498     * (int *) (dummysh + 6) = 0;
03499 
03500     /* Initialize the three adjoining shell edges of `dummytri' to be */
03501     /*   the omnipresent shell edge.                                  */
03502     dummytri[6] = (triangle) dummysh;
03503     dummytri[7] = (triangle) dummysh;
03504     dummytri[8] = (triangle) dummysh;
03505   }
03506 }
03507 
03508 /*****************************************************************************/
03509 /*                                                                           */
03510 /*  initializepointpool()   Calculate the size of the point data structure   */
03511 /*                          and initialize its memory pool.                  */
03512 /*                                                                           */
03513 /*  This routine also computes the `pointmarkindex' and `point2triindex'     */
03514 /*  indices used to find values within each point.                           */
03515 /*                                                                           */
03516 /*****************************************************************************/
03517 
03518 void initializepointpool()
03519 {
03520   int pointsize;
03521 
03522   /* The index within each point at which the boundary marker is found.  */
03523   /*   Ensure the point marker is aligned to a sizeof(int)-byte address. */
03524   pointmarkindex = ((mesh_dim + nextras) * sizeof(REAL) + sizeof(int) - 1)
03525                  / sizeof(int);
03526   pointsize = (pointmarkindex + 1) * sizeof(int);
03527   if (poly) {
03528     /* The index within each point at which a triangle pointer is found.   */
03529     /*   Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
03530     point2triindex = (pointsize + sizeof(triangle) - 1) / sizeof(triangle);
03531     pointsize = (point2triindex + 1) * sizeof(triangle);
03532   }
03533   /* Initialize the pool of points. */
03534   poolinit(&points, pointsize, POINTPERBLOCK,
03535            (sizeof(REAL) >= sizeof(triangle)) ? FLOATINGPOINT : POINTER, 0);
03536 }
03537 
03538 /*****************************************************************************/
03539 /*                                                                           */
03540 /*  initializetrisegpools()   Calculate the sizes of the triangle and shell  */
03541 /*                            edge data structures and initialize their      */
03542 /*                            memory pools.                                  */
03543 /*                                                                           */
03544 /*  This routine also computes the `highorderindex', `elemattribindex', and  */
03545 /*  `areaboundindex' indices used to find values within each triangle.       */
03546 /*                                                                           */
03547 /*****************************************************************************/
03548 
03549 void initializetrisegpools()
03550 {
03551   int trisize;
03552 
03553   /* The index within each triangle at which the extra nodes (above three)  */
03554   /*   associated with high order elements are found.  There are three      */
03555   /*   pointers to other triangles, three pointers to corners, and possibly */
03556   /*   three pointers to shell edges before the extra nodes.                */
03557   highorderindex = 6 + (useshelles * 3);
03558   /* The number of bytes occupied by a triangle. */
03559   trisize = ((order + 1) * (order + 2) / 2 + (highorderindex - 3)) *
03560             sizeof(triangle);
03561   /* The index within each triangle at which its attributes are found, */
03562   /*   where the index is measured in REALs.                           */
03563   elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
03564   /* The index within each triangle at which the maximum area constraint  */
03565   /*   is found, where the index is measured in REALs.  Note that if the  */
03566   /*   `regionattrib' flag is set, an additional attribute will be added. */
03567   areaboundindex = elemattribindex + eextras + regionattrib;
03568   /* If triangle attributes or an area bound are needed, increase the number */
03569   /*   of bytes occupied by a triangle.                                      */
03570   if (vararea) {
03571     trisize = (areaboundindex + 1) * sizeof(REAL);
03572   } else if (eextras + regionattrib > 0) {
03573     trisize = areaboundindex * sizeof(REAL);
03574   }
03575   /* If a Voronoi diagram or triangle neighbor graph is requested, make    */
03576   /*   sure there's room to store an integer index in each triangle.  This */
03577   /*   integer index can occupy the same space as the shell edges or       */
03578   /*   attributes or area constraint or extra nodes.                       */
03579   if ((voronoi || neighbors) &&
03580       (trisize < 6 * sizeof(triangle) + sizeof(int))) {
03581     trisize = 6 * sizeof(triangle) + sizeof(int);
03582   }
03583   /* Having determined the memory size of a triangle, initialize the pool. */
03584   poolinit(&triangles, trisize, TRIPERBLOCK, POINTER, 4);
03585 
03586   if (useshelles) {
03587     /* Initialize the pool of shell edges. */
03588     poolinit(&shelles, 6 * sizeof(triangle) + sizeof(int), SHELLEPERBLOCK,
03589              POINTER, 4);
03590 
03591     /* Initialize the "outer space" triangle and omnipresent shell edge. */
03592     dummyinit(triangles.itemwords, shelles.itemwords);
03593   } else {
03594     /* Initialize the "outer space" triangle. */
03595     dummyinit(triangles.itemwords, 0);
03596   }
03597 }
03598 
03599 /*****************************************************************************/
03600 /*                                                                           */
03601 /*  triangledealloc()   Deallocate space for a triangle, marking it dead.    */
03602 /*                                                                           */
03603 /*****************************************************************************/
03604 
03605 void triangledealloc(dyingtriangle)
03606 triangle *dyingtriangle;
03607 {
03608   /* Set triangle's vertices to NULL.  This makes it possible to        */
03609   /*   detect dead triangles when traversing the list of all triangles. */
03610   dyingtriangle[3] = (triangle) NULL;
03611   dyingtriangle[4] = (triangle) NULL;
03612   dyingtriangle[5] = (triangle) NULL;
03613   pooldealloc(&triangles, (VOID *) dyingtriangle);
03614 }
03615 
03616 /*****************************************************************************/
03617 /*                                                                           */
03618 /*  triangletraverse()   Traverse the triangles, skipping dead ones.         */
03619 /*                                                                           */
03620 /*****************************************************************************/
03621 
03622 triangle *triangletraverse()
03623 {
03624   triangle *newtriangle;
03625 
03626   do {
03627     newtriangle = (triangle *) traverse(&triangles);
03628     if (newtriangle == (triangle *) NULL) {
03629       return (triangle *) NULL;
03630     }
03631   } while (newtriangle[3] == (triangle) NULL);            /* Skip dead ones. */
03632   return newtriangle;
03633 }
03634 
03635 /*****************************************************************************/
03636 /*                                                                           */
03637 /*  shelledealloc()   Deallocate space for a shell edge, marking it dead.    */
03638 /*                                                                           */
03639 /*****************************************************************************/
03640 
03641 void shelledealloc(dyingshelle)
03642 shelle *dyingshelle;
03643 {
03644   /* Set shell edge's vertices to NULL.  This makes it possible to */
03645   /*   detect dead shells when traversing the list of all shells.  */
03646   dyingshelle[2] = (shelle) NULL;
03647   dyingshelle[3] = (shelle) NULL;
03648   pooldealloc(&shelles, (VOID *) dyingshelle);
03649 }
03650 
03651 /*****************************************************************************/
03652 /*                                                                           */
03653 /*  shelletraverse()   Traverse the shell edges, skipping dead ones.         */
03654 /*                                                                           */
03655 /*****************************************************************************/
03656 
03657 shelle *shelletraverse()
03658 {
03659   shelle *newshelle;
03660 
03661   do {
03662     newshelle = (shelle *) traverse(&shelles);
03663     if (newshelle == (shelle *) NULL) {
03664       return (shelle *) NULL;
03665     }
03666   } while (newshelle[2] == (shelle) NULL);                /* Skip dead ones. */
03667   return newshelle;
03668 }
03669 
03670 /*****************************************************************************/
03671 /*                                                                           */
03672 /*  pointdealloc()   Deallocate space for a point, marking it dead.          */
03673 /*                                                                           */
03674 /*****************************************************************************/
03675 
03676 void pointdealloc(dyingpoint)
03677 point dyingpoint;
03678 {
03679   /* Mark the point as dead.  This makes it possible to detect dead points */
03680   /*   when traversing the list of all points.                             */
03681   setpointmark(dyingpoint, DEADPOINT);
03682   pooldealloc(&points, (VOID *) dyingpoint);
03683 }
03684 
03685 /*****************************************************************************/
03686 /*                                                                           */
03687 /*  pointtraverse()   Traverse the points, skipping dead ones.               */
03688 /*                                                                           */
03689 /*****************************************************************************/
03690 
03691 point pointtraverse()
03692 {
03693   point newpoint;
03694 
03695   do {
03696     newpoint = (point) traverse(&points);
03697     if (newpoint == (point) NULL) {
03698       return (point) NULL;
03699     }
03700   } while (pointmark(newpoint) == DEADPOINT);             /* Skip dead ones. */
03701   return newpoint;
03702 }
03703 
03704 /*****************************************************************************/
03705 /*                                                                           */
03706 /*  badsegmentdealloc()   Deallocate space for a bad segment, marking it     */
03707 /*                        dead.                                              */
03708 /*                                                                           */
03709 /*****************************************************************************/
03710 
03711 #ifndef CDT_ONLY
03712 
03713 void badsegmentdealloc(dyingseg)
03714 struct edge *dyingseg;
03715 {
03716   /* Set segment's orientation to -1.  This makes it possible to      */
03717   /*   detect dead segments when traversing the list of all segments. */
03718   dyingseg->shorient = -1;
03719   pooldealloc(&badsegments, (VOID *) dyingseg);
03720 }
03721 
03722 #endif /* not CDT_ONLY */
03723 
03724 /*****************************************************************************/
03725 /*                                                                           */
03726 /*  badsegmenttraverse()   Traverse the bad segments, skipping dead ones.    */
03727 /*                                                                           */
03728 /*****************************************************************************/
03729 
03730 #ifndef CDT_ONLY
03731 
03732 struct edge *badsegmenttraverse()
03733 {
03734   struct edge *newseg;
03735 
03736   do {
03737     newseg = (struct edge *) traverse(&badsegments);
03738     if (newseg == (struct edge *) NULL) {
03739       return (struct edge *) NULL;
03740     }
03741   } while (newseg->shorient == -1);                       /* Skip dead ones. */
03742   return newseg;
03743 }
03744 
03745 #endif /* not CDT_ONLY */
03746 
03747 /*****************************************************************************/
03748 /*                                                                           */
03749 /*  getpoint()   Get a specific point, by number, from the list.             */
03750 /*                                                                           */
03751 /*  The first point is number 'firstnumber'.                                 */
03752 /*                                                                           */
03753 /*  Note that this takes O(n) time (with a small constant, if POINTPERBLOCK  */
03754 /*  is large).  I don't care to take the trouble to make it work in constant */
03755 /*  time.                                                                    */
03756 /*                                                                           */
03757 /*****************************************************************************/
03758 
03759 point getpoint(number)
03760 int number;
03761 {
03762   VOID **getblock;
03763   point foundpoint;
03764   unsigned long alignptr;
03765   int current;
03766 
03767   getblock = points.firstblock;
03768   current = firstnumber;
03769   /* Find the right block. */
03770   while (current + points.itemsperblock <= number) {
03771     getblock = (VOID **) *getblock;
03772     current += points.itemsperblock;
03773   }
03774   /* Now find the right point. */
03775   alignptr = (unsigned long) (getblock + 1);
03776   foundpoint = (point) (alignptr + (unsigned long) points.alignbytes
03777                         - (alignptr % (unsigned long) points.alignbytes));
03778   while (current < number) {
03779     foundpoint += points.itemwords;
03780     current++;
03781   }
03782   return foundpoint;
03783 }
03784 
03785 /*****************************************************************************/
03786 /*                                                                           */
03787 /*  triangledeinit()   Free all remaining allocated memory.                  */
03788 /*                                                                           */
03789 /*****************************************************************************/
03790 
03791 void triangledeinit()
03792 {
03793   pooldeinit(&triangles);
03794   free(dummytribase);
03795   if (useshelles) {
03796     pooldeinit(&shelles);
03797     free(dummyshbase);
03798   }
03799   pooldeinit(&points);
03800 #ifndef CDT_ONLY
03801   if (quality) {
03802     pooldeinit(&badsegments);
03803     if ((minangle > 0.0) || vararea || fixedarea) {
03804       pooldeinit(&badtriangles);
03805     }
03806   }
03807 #endif /* not CDT_ONLY */
03808 }
03809 
03810 /**                                                                         **/
03811 /**                                                                         **/
03812 /********* Memory management routines end here                       *********/
03813 
03814 /********* Constructors begin here                                   *********/
03815 /**                                                                         **/
03816 /**                                                                         **/
03817 
03818 /*****************************************************************************/
03819 /*                                                                           */
03820 /*  maketriangle()   Create a new triangle with orientation zero.            */
03821 /*                                                                           */
03822 /*****************************************************************************/
03823 
03824 void maketriangle(newtriedge)
03825 struct triedge *newtriedge;
03826 {
03827   int i;
03828 
03829   newtriedge->tri = (triangle *) poolalloc(&triangles);
03830   /* Initialize the three adjoining triangles to be "outer space". */
03831   newtriedge->tri[0] = (triangle) dummytri;
03832   newtriedge->tri[1] = (triangle) dummytri;
03833   newtriedge->tri[2] = (triangle) dummytri;
03834   /* Three NULL vertex points. */
03835   newtriedge->tri[3] = (triangle) NULL;
03836   newtriedge->tri[4] = (triangle) NULL;
03837   newtriedge->tri[5] = (triangle) NULL;
03838   /* Initialize the three adjoining shell edges to be the omnipresent */
03839   /*   shell edge.                                                    */
03840   if (useshelles) {
03841     newtriedge->tri[6] = (triangle) dummysh;
03842     newtriedge->tri[7] = (triangle) dummysh;
03843     newtriedge->tri[8] = (triangle) dummysh;
03844   }
03845   for (i = 0; i < eextras; i++) {
03846     setelemattribute(*newtriedge, i, 0.0);
03847   }
03848   if (vararea) {
03849     setareabound(*newtriedge, -1.0);
03850   }
03851 
03852   newtriedge->orient = 0;
03853 }
03854 
03855 /*****************************************************************************/
03856 /*                                                                           */
03857 /*  makeshelle()   Create a new shell edge with orientation zero.            */
03858 /*                                                                           */
03859 /*****************************************************************************/
03860 
03861 void makeshelle(newedge)
03862 struct edge *newedge;
03863 {
03864   newedge->sh = (shelle *) poolalloc(&shelles);
03865   /* Initialize the two adjoining shell edges to be the omnipresent */
03866   /*   shell edge.                                                  */
03867   newedge->sh[0] = (shelle) dummysh;
03868   newedge->sh[1] = (shelle) dummysh;
03869   /* Two NULL vertex points. */
03870   newedge->sh[2] = (shelle) NULL;
03871   newedge->sh[3] = (shelle) NULL;
03872   /* Initialize the two adjoining triangles to be "outer space". */
03873   newedge->sh[4] = (shelle) dummytri;
03874   newedge->sh[5] = (shelle) dummytri;
03875   /* Set the boundary marker to zero. */
03876   setmark(*newedge, 0);
03877 
03878   newedge->shorient = 0;
03879 }
03880 
03881 /**                                                                         **/
03882 /**                                                                         **/
03883 /********* Constructors end here                                     *********/
03884 
03885 /********* Determinant evaluation routines begin here                *********/
03886 /**                                                                         **/
03887 /**                                                                         **/
03888 
03889 /* The adaptive exact arithmetic geometric predicates implemented herein are */
03890 /*   described in detail in my Technical Report CMU-CS-96-140.  The complete */
03891 /*   reference is given in the header.                                       */
03892 
03893 /* Which of the following two methods of finding the absolute values is      */
03894 /*   fastest is compiler-dependent.  A few compilers can inline and optimize */
03895 /*   the fabs() call; but most will incur the overhead of a function call,   */
03896 /*   which is disastrously slow.  A faster way on IEEE machines might be to  */
03897 /*   mask the appropriate bit, but that's difficult to do in C.              */
03898 
03899 #define Absolute(a)  ((a) >= 0.0 ? (a) : -(a))
03900 /* #define Absolute(a)  fabs(a) */
03901 
03902 /* Many of the operations are broken up into two pieces, a main part that    */
03903 /*   performs an approximate operation, and a "tail" that computes the       */
03904 /*   roundoff error of that operation.                                       */
03905 /*                                                                           */
03906 /* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(),    */
03907 /*   Split(), and Two_Product() are all implemented as described in the      */
03908 /*   reference.  Each of these macros requires certain variables to be       */
03909 /*   defined in the calling routine.  The variables `bvirt', `c', `abig',    */
03910 /*   `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because   */
03911 /*   they store the result of an operation that may incur roundoff error.    */
03912 /*   The input parameter `x' (or the highest numbered `x_' parameter) must   */
03913 /*   also be declared `INEXACT'.                                             */
03914 
03915 #define Fast_Two_Sum_Tail(a, b, x, y) \
03916   bvirt = x - a; \
03917   y = b - bvirt
03918 
03919 #define Fast_Two_Sum(a, b, x, y) \
03920   x = (REAL) (a + b); \
03921   Fast_Two_Sum_Tail(a, b, x, y)
03922 
03923 #define Two_Sum_Tail(a, b, x, y) \
03924   bvirt = (REAL) (x - a); \
03925   avirt = x - bvirt; \
03926   bround = b - bvirt; \
03927   around = a - avirt; \
03928   y = around + bround
03929 
03930 #define Two_Sum(a, b, x, y) \
03931   x = (REAL) (a + b); \
03932   Two_Sum_Tail(a, b, x, y)
03933 
03934 #define Two_Diff_Tail(a, b, x, y) \
03935   bvirt = (REAL) (a - x); \
03936   avirt = x + bvirt; \
03937   bround = bvirt - b; \
03938   around = a - avirt; \
03939   y = around + bround
03940 
03941 #define Two_Diff(a, b, x, y) \
03942   x = (REAL) (a - b); \
03943   Two_Diff_Tail(a, b, x, y)
03944 
03945 #define Split(a, ahi, alo) \
03946   c = (REAL) (splitter * a); \
03947   abig = (REAL) (c - a); \
03948   ahi = c - abig; \
03949   alo = a - ahi
03950 
03951 #define Two_Product_Tail(a, b, x, y) \
03952   Split(a, ahi, alo); \
03953   Split(b, bhi, blo); \
03954   err1 = x - (ahi * bhi); \
03955   err2 = err1 - (alo * bhi); \
03956   err3 = err2 - (ahi * blo); \
03957   y = (alo * blo) - err3
03958 
03959 #define Two_Product(a, b, x, y) \
03960   x = (REAL) (a * b); \
03961   Two_Product_Tail(a, b, x, y)
03962 
03963 /* Two_Product_Presplit() is Two_Product() where one of the inputs has       */
03964 /*   already been split.  Avoids redundant splitting.                        */
03965 
03966 #define Two_Product_Presplit(a, b, bhi, blo, x, y) \
03967   x = (REAL) (a * b); \
03968   Split(a, ahi, alo); \
03969   err1 = x - (ahi * bhi); \
03970   err2 = err1 - (alo * bhi); \
03971   err3 = err2 - (ahi * blo); \
03972   y = (alo * blo) - err3
03973 
03974 /* Square() can be done more quickly than Two_Product().                     */
03975 
03976 #define Square_Tail(a, x, y) \
03977   Split(a, ahi, alo); \
03978   err1 = x - (ahi * ahi); \
03979   err3 = err1 - ((ahi + ahi) * alo); \
03980   y = (alo * alo) - err3
03981 
03982 #define Square(a, x, y) \
03983   x = (REAL) (a * a); \
03984   Square_Tail(a, x, y)
03985 
03986 /* Macros for summing expansions of various fixed lengths.  These are all    */
03987 /*   unrolled versions of Expansion_Sum().                                   */
03988 
03989 #define Two_One_Sum(a1, a0, b, x2, x1, x0) \
03990   Two_Sum(a0, b , _i, x0); \
03991   Two_Sum(a1, _i, x2, x1)
03992 
03993 #define Two_One_Diff(a1, a0, b, x2, x1, x0) \
03994   Two_Diff(a0, b , _i, x0); \
03995   Two_Sum( a1, _i, x2, x1)
03996 
03997 #define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
03998   Two_One_Sum(a1, a0, b0, _j, _0, x0); \
03999   Two_One_Sum(_j, _0, b1, x3, x2, x1)
04000 
04001 #define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
04002   Two_One_Diff(a1, a0, b0, _j, _0, x0); \
04003   Two_One_Diff(_j, _0, b1, x3, x2, x1)
04004 
04005 /*****************************************************************************/
04006 /*                                                                           */
04007 /*  exactinit()   Initialize the variables used for exact arithmetic.        */
04008 /*                                                                           */
04009 /*  `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in   */
04010 /*  floating-point arithmetic.  `epsilon' bounds the relative roundoff       */
04011 /*  error.  It is used for floating-point error analysis.                    */
04012 /*                                                                           */
04013 /*  `splitter' is used to split floating-point numbers into two half-        */
04014 /*  length significands for exact multiplication.                            */
04015 /*                                                                           */
04016 /*  I imagine that a highly optimizing compiler might be too smart for its   */
04017 /*  own good, and somehow cause this routine to fail, if it pretends that    */
04018 /*  floating-point arithmetic is too much like real arithmetic.              */
04019 /*                                                                           */
04020 /*  Don't change this routine unless you fully understand it.                */
04021 /*                                                                           */
04022 /*****************************************************************************/
04023 
04024 void exactinit()
04025 {
04026   REAL half;
04027   REAL check, lastcheck;
04028   int every_other;
04029 
04030   every_other = 1;
04031   half = 0.5;
04032   epsilon = 1.0;
04033   splitter = 1.0;
04034   check = 1.0;
04035   /* Repeatedly divide `epsilon' by two until it is too small to add to      */
04036   /*   one without causing roundoff.  (Also check if the sum is equal to     */
04037   /*   the previous sum, for machines that round up instead of using exact   */
04038   /*   rounding.  Not that these routines will work on such machines anyway. */
04039   do {
04040     lastcheck = check;
04041     epsilon *= half;
04042     if (every_other) {
04043       splitter *= 2.0;
04044     }
04045     every_other = !every_other;
04046     check = 1.0 + epsilon;
04047   } while ((check != 1.0) && (check != lastcheck));
04048   splitter += 1.0;
04049   if (verbose > 1) {
04050     printf("Floating point roundoff is of magnitude %.17g\n", epsilon);
04051     printf("Floating point splitter is %.17g\n", splitter);
04052   }
04053   /* Error bounds for orientation and incircle tests. */
04054   resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
04055   ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
04056   ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
04057   ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
04058   iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
04059   iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
04060   iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
04061 }
04062 
04063 /*****************************************************************************/
04064 /*                                                                           */
04065 /*  fast_expansion_sum_zeroelim()   Sum two expansions, eliminating zero     */
04066 /*                                  components from the output expansion.    */
04067 /*                                                                           */
04068 /*  Sets h = e + f.  See my Robust Predicates paper for details.             */
04069 /*                                                                           */
04070 /*  If round-to-even is used (as with IEEE 754), maintains the strongly      */
04071 /*  nonoverlapping property.  (That is, if e is strongly nonoverlapping, h   */
04072 /*  will be also.)  Does NOT maintain the nonoverlapping or nonadjacent      */
04073 /*  properties.                                                              */
04074 /*                                                                           */
04075 /*****************************************************************************/
04076 
04077 int fast_expansion_sum_zeroelim(elen, e, flen, f, h)  /* h cannot be e or f. */
04078 int elen;
04079 REAL *e;
04080 int flen;
04081 REAL *f;
04082 REAL *h;
04083 {
04084   REAL Q;
04085   INEXACT REAL Qnew;
04086   INEXACT REAL hh;
04087   INEXACT REAL bvirt;
04088   REAL avirt, bround, around;
04089   int eindex, findex, hindex;
04090   REAL enow, fnow;
04091 
04092   enow = e[0];
04093   fnow = f[0];
04094   eindex = findex = 0;
04095   if ((fnow > enow) == (fnow > -enow)) {
04096     Q = enow;
04097     enow = e[++eindex];
04098   } else {
04099     Q = fnow;
04100     fnow = f[++findex];
04101   }
04102   hindex = 0;
04103   if ((eindex < elen) && (findex < flen)) {
04104     if ((fnow > enow) == (fnow > -enow)) {
04105       Fast_Two_Sum(enow, Q, Qnew, hh);
04106       enow = e[++eindex];
04107     } else {
04108       Fast_Two_Sum(fnow, Q, Qnew, hh);
04109       fnow = f[++findex];
04110     }
04111     Q = Qnew;
04112     if (hh != 0.0) {
04113       h[hindex++] = hh;
04114     }
04115     while ((eindex < elen) && (findex < flen)) {
04116       if ((fnow > enow) == (fnow > -enow)) {
04117         Two_Sum(Q, enow, Qnew, hh);
04118         enow = e[++eindex];
04119       } else {
04120         Two_Sum(Q, fnow, Qnew, hh);
04121         fnow = f[++findex];
04122       }
04123       Q = Qnew;
04124       if (hh != 0.0) {
04125         h[hindex++] = hh;
04126       }
04127     }
04128   }
04129   while (eindex < elen) {
04130     Two_Sum(Q, enow, Qnew, hh);
04131     enow = e[++eindex];
04132     Q = Qnew;
04133     if (hh != 0.0) {
04134       h[hindex++] = hh;
04135     }
04136   }
04137   while (findex < flen) {
04138     Two_Sum(Q, fnow, Qnew, hh);
04139     fnow = f[++findex];
04140     Q = Qnew;
04141     if (hh != 0.0) {
04142       h[hindex++] = hh;
04143     }
04144   }
04145   if ((Q != 0.0) || (hindex == 0)) {
04146     h[hindex++] = Q;
04147   }
04148   return hindex;
04149 }
04150 
04151 /*****************************************************************************/
04152 /*                                                                           */
04153 /*  scale_expansion_zeroelim()   Multiply an expansion by a scalar,          */
04154 /*                               eliminating zero components from the        */
04155 /*                               output expansion.                           */
04156 /*                                                                           */
04157 /*  Sets h = be.  See my Robust Predicates paper for details.                */
04158 /*                                                                           */
04159 /*  Maintains the nonoverlapping property.  If round-to-even is used (as     */
04160 /*  with IEEE 754), maintains the strongly nonoverlapping and nonadjacent    */
04161 /*  properties as well.  (That is, if e has one of these properties, so      */
04162 /*  will h.)                                                                 */
04163 /*                                                                           */
04164 /*****************************************************************************/
04165 
04166 int scale_expansion_zeroelim(elen, e, b, h)   /* e and h cannot be the same. */
04167 int elen;
04168 REAL *e;
04169 REAL b;
04170 REAL *h;
04171 {
04172   INEXACT REAL Q, sum;
04173   REAL hh;
04174   INEXACT REAL product1;
04175   REAL product0;
04176   int eindex, hindex;
04177   REAL enow;
04178   INEXACT REAL bvirt;
04179   REAL avirt, bround, around;
04180   INEXACT REAL c;
04181   INEXACT REAL abig;
04182   REAL ahi, alo, bhi, blo;
04183   REAL err1, err2, err3;
04184 
04185   Split(b, bhi, blo);
04186   Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
04187   hindex = 0;
04188   if (hh != 0) {
04189     h[hindex++] = hh;
04190   }
04191   for (eindex = 1; eindex < elen; eindex++) {
04192     enow = e[eindex];
04193     Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
04194     Two_Sum(Q, product0, sum, hh);
04195     if (hh != 0) {
04196       h[hindex++] = hh;
04197     }
04198     Fast_Two_Sum(product1, sum, Q, hh);
04199     if (hh != 0) {
04200       h[hindex++] = hh;
04201     }
04202   }
04203   if ((Q != 0.0) || (hindex == 0)) {
04204     h[hindex++] = Q;
04205   }
04206   return hindex;
04207 }
04208 
04209 /*****************************************************************************/
04210 /*                                                                           */
04211 /*  estimate()   Produce a one-word estimate of an expansion's value.        */
04212 /*                                                                           */
04213 /*  See my Robust Predicates paper for details.                              */
04214 /*                                                                           */
04215 /*****************************************************************************/
04216 
04217 REAL estimate(elen, e)
04218 int elen;
04219 REAL *e;
04220 {
04221   REAL Q;
04222   int eindex;
04223 
04224   Q = e[0];
04225   for (eindex = 1; eindex < elen; eindex++) {
04226     Q += e[eindex];
04227   }
04228   return Q;
04229 }
04230 
04231 /*****************************************************************************/
04232 /*                                                                           */
04233 /*  counterclockwise()   Return a positive value if the points pa, pb, and   */
04234 /*                       pc occur in counterclockwise order; a negative      */
04235 /*                       value if they occur in clockwise order; and zero    */
04236 /*                       if they are collinear.  The result is also a rough  */
04237 /*                       approximation of twice the signed area of the       */
04238 /*                       triangle defined by the three points.               */
04239 /*                                                                           */
04240 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
04241 /*  result returned is the determinant of a matrix.  This determinant is     */
04242 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
04243 /*  the degree it is needed to ensure that the returned value has the        */
04244 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
04245 /*  more slowly when the input points are collinear or nearly so.            */
04246 /*                                                                           */
04247 /*  See my Robust Predicates paper for details.                              */
04248 /*                                                                           */
04249 /*****************************************************************************/
04250 
04251 REAL counterclockwiseadapt(pa, pb, pc, detsum)
04252 point pa;
04253 point pb;
04254 point pc;
04255 REAL detsum;
04256 {
04257   INEXACT REAL acx, acy, bcx, bcy;
04258   REAL acxtail, acytail, bcxtail, bcytail;
04259   INEXACT REAL detleft, detright;
04260   REAL detlefttail, detrighttail;
04261   REAL det, errbound;
04262   REAL B[4], C1[8], C2[12], D[16];
04263   INEXACT REAL B3;
04264   int C1length, C2length, Dlength;
04265   REAL u[4];
04266   INEXACT REAL u3;
04267   INEXACT REAL s1, t1;
04268   REAL s0, t0;
04269 
04270   INEXACT REAL bvirt;
04271   REAL avirt, bround, around;
04272   INEXACT REAL c;
04273   INEXACT REAL abig;
04274   REAL ahi, alo, bhi, blo;
04275   REAL err1, err2, err3;
04276   INEXACT REAL _i, _j;
04277   REAL _0;
04278 
04279   acx = (REAL) (pa[0] - pc[0]);
04280   bcx = (REAL) (pb[0] - pc[0]);
04281   acy = (REAL) (pa[1] - pc[1]);
04282   bcy = (REAL) (pb[1] - pc[1]);
04283 
04284   Two_Product(acx, bcy, detleft, detlefttail);
04285   Two_Product(acy, bcx, detright, detrighttail);
04286 
04287   Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
04288                B3, B[2], B[1], B[0]);
04289   B[3] = B3;
04290 
04291   det = estimate(4, B);
04292   errbound = ccwerrboundB * detsum;
04293   if ((det >= errbound) || (-det >= errbound)) {
04294     return det;
04295   }
04296 
04297   Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
04298   Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
04299   Two_Diff_Tail(pa[1], pc[1], acy, acytail);
04300   Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
04301 
04302   if ((acxtail == 0.0) && (acytail == 0.0)
04303       && (bcxtail == 0.0) && (bcytail == 0.0)) {
04304     return det;
04305   }
04306 
04307   errbound = ccwerrboundC * detsum + resulterrbound * Absolute(det);
04308   det += (acx * bcytail + bcy * acxtail)
04309        - (acy * bcxtail + bcx * acytail);
04310   if ((det >= errbound) || (-det >= errbound)) {
04311     return det;
04312   }
04313 
04314   Two_Product(acxtail, bcy, s1, s0);
04315   Two_Product(acytail, bcx, t1, t0);
04316   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
04317   u[3] = u3;
04318   C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
04319 
04320   Two_Product(acx, bcytail, s1, s0);
04321   Two_Product(acy, bcxtail, t1, t0);
04322   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
04323   u[3] = u3;
04324   C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
04325 
04326   Two_Product(acxtail, bcytail, s1, s0);
04327   Two_Product(acytail, bcxtail, t1, t0);
04328   Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
04329   u[3] = u3;
04330   Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
04331 
04332   return(D[Dlength - 1]);
04333 }
04334 
04335 REAL counterclockwise(pa, pb, pc)
04336 point pa;
04337 point pb;
04338 point pc;
04339 {
04340   REAL detleft, detright, det;
04341   REAL detsum, errbound;
04342 
04343   counterclockcount++;
04344 
04345   detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
04346   detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
04347   det = detleft - detright;
04348 
04349   if (noexact) {
04350     return det;
04351   }
04352 
04353   if (detleft > 0.0) {
04354     if (detright <= 0.0) {
04355       return det;
04356     } else {
04357       detsum = detleft + detright;
04358     }
04359   } else if (detleft < 0.0) {
04360     if (detright >= 0.0) {
04361       return det;
04362     } else {
04363       detsum = -detleft - detright;
04364     }
04365   } else {
04366     return det;
04367   }
04368 
04369   errbound = ccwerrboundA * detsum;
04370   if ((det >= errbound) || (-det >= errbound)) {
04371     return det;
04372   }
04373 
04374   return counterclockwiseadapt(pa, pb, pc, detsum);
04375 }
04376 
04377 /*****************************************************************************/
04378 /*                                                                           */
04379 /*  incircle()   Return a positive value if the point pd lies inside the     */
04380 /*               circle passing through pa, pb, and pc; a negative value if  */
04381 /*               it lies outside; and zero if the four points are cocircular.*/
04382 /*               The points pa, pb, and pc must be in counterclockwise       */
04383 /*               order, or the sign of the result will be reversed.          */
04384 /*                                                                           */
04385 /*  Uses exact arithmetic if necessary to ensure a correct answer.  The      */
04386 /*  result returned is the determinant of a matrix.  This determinant is     */
04387 /*  computed adaptively, in the sense that exact arithmetic is used only to  */
04388 /*  the degree it is needed to ensure that the returned value has the        */
04389 /*  correct sign.  Hence, this function is usually quite fast, but will run  */
04390 /*  more slowly when the input points are cocircular or nearly so.           */
04391 /*                                                                           */
04392 /*  See my Robust Predicates paper for details.                              */
04393 /*                                                                           */
04394 /*****************************************************************************/
04395 
04396 REAL incircleadapt(pa, pb, pc, pd, permanent)
04397 point pa;
04398 point pb;
04399 point pc;
04400 point pd;
04401 REAL permanent;
04402 {
04403   INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
04404   REAL det, errbound;
04405 
04406   INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
04407   REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
04408   REAL bc[4], ca[4], ab[4];
04409   INEXACT REAL bc3, ca3, ab3;
04410   REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
04411   int axbclen, axxbclen, aybclen, ayybclen, alen;
04412   REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
04413   int bxcalen, bxxcalen, bycalen, byycalen, blen;
04414   REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
04415   int cxablen, cxxablen, cyablen, cyyablen, clen;
04416   REAL abdet[64];
04417   int ablen;
04418   REAL fin1[1152], fin2[1152];
04419   REAL *finnow, *finother, *finswap;
04420   int finlength;
04421 
04422   REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
04423   INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
04424   REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
04425   REAL aa[4], bb[4], cc[4];
04426   INEXACT REAL aa3, bb3, cc3;
04427   INEXACT REAL ti1, tj1;
04428   REAL ti0, tj0;
04429   REAL u[4], v[4];
04430   INEXACT REAL u3, v3;
04431   REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
04432   REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
04433   int temp8len, temp16alen, temp16blen, temp16clen;
04434   int temp32alen, temp32blen, temp48len, temp64len;
04435   REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
04436   int axtbblen, axtcclen, aytbblen, aytcclen;
04437   REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
04438   int bxtaalen, bxtcclen, bytaalen, bytcclen;
04439   REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
04440   int cxtaalen, cxtbblen, cytaalen, cytbblen;
04441   REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
04442   int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen;
04443   REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
04444   int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
04445   REAL axtbctt[8], aytbctt[8], bxtcatt[8];
04446   REAL bytcatt[8], cxtabtt[8], cytabtt[8];
04447   int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
04448   REAL abt[8], bct[8], cat[8];
04449   int abtlen, bctlen, catlen;
04450   REAL abtt[4], bctt[4], catt[4];
04451   int abttlen, bcttlen, cattlen;
04452   INEXACT REAL abtt3, bctt3, catt3;
04453   REAL negate;
04454 
04455   INEXACT REAL bvirt;
04456   REAL avirt, bround, around;
04457   INEXACT REAL c;
04458   INEXACT REAL abig;
04459   REAL ahi, alo, bhi, blo;
04460   REAL err1, err2, err3;
04461   INEXACT REAL _i, _j;
04462   REAL _0;
04463 
04464   adx = (REAL) (pa[0] - pd[0]);
04465   bdx = (REAL) (pb[0] - pd[0]);
04466   cdx = (REAL) (pc[0] - pd[0]);
04467   ady = (REAL) (pa[1] - pd[1]);
04468   bdy = (REAL) (pb[1] - pd[1]);
04469   cdy = (REAL) (pc[1] - pd[1]);
04470 
04471   Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
04472   Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
04473   Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
04474   bc[3] = bc3;
04475   axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
04476   axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
04477   aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
04478   ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
04479   alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
04480 
04481   Two_Product(cdx, ady, cdxady1, cdxady0);
04482   Two_Product(adx, cdy, adxcdy1, adxcdy0);
04483   Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
04484   ca[3] = ca3;
04485   bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
04486   bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
04487   bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
04488   byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
04489   blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
04490 
04491   Two_Product(adx, bdy, adxbdy1, adxbdy0);
04492   Two_Product(bdx, ady, bdxady1, bdxady0);
04493   Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
04494   ab[3] = ab3;
04495   cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
04496   cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
04497   cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
04498   cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
04499   clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
04500 
04501   ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
04502   finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
04503 
04504   det = estimate(finlength, fin1);
04505   errbound = iccerrboundB * permanent;
04506   if ((det >= errbound) || (-det >= errbound)) {
04507     return det;
04508   }
04509 
04510   Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
04511   Two_Diff_Tail(pa[1], pd[1], ady, adytail);
04512   Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
04513   Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
04514   Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
04515   Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
04516   if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
04517       && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
04518     return det;
04519   }
04520 
04521   errbound = iccerrboundC * permanent + resulterrbound * Absolute(det);
04522   det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
04523                                      - (bdy * cdxtail + cdx * bdytail))
04524           + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
04525        + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
04526                                      - (cdy * adxtail + adx * cdytail))
04527           + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
04528        + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
04529                                      - (ady * bdxtail + bdx * adytail))
04530           + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
04531   if ((det >= errbound) || (-det >= errbound)) {
04532     return det;
04533   }
04534 
04535   finnow = fin1;
04536   finother = fin2;
04537 
04538   if ((bdxtail != 0.0) || (bdytail != 0.0)
04539       || (cdxtail != 0.0) || (cdytail != 0.0)) {
04540     Square(adx, adxadx1, adxadx0);
04541     Square(ady, adyady1, adyady0);
04542     Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
04543     aa[3] = aa3;
04544   }
04545   if ((cdxtail != 0.0) || (cdytail != 0.0)
04546       || (adxtail != 0.0) || (adytail != 0.0)) {
04547     Square(bdx, bdxbdx1, bdxbdx0);
04548     Square(bdy, bdybdy1, bdybdy0);
04549     Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
04550     bb[3] = bb3;
04551   }
04552   if ((adxtail != 0.0) || (adytail != 0.0)
04553       || (bdxtail != 0.0) || (bdytail != 0.0)) {
04554     Square(cdx, cdxcdx1, cdxcdx0);
04555     Square(cdy, cdycdy1, cdycdy0);
04556     Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
04557     cc[3] = cc3;
04558   }
04559 
04560   if (adxtail != 0.0) {
04561     axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
04562     temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
04563                                           temp16a);
04564 
04565     axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
04566     temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
04567 
04568     axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
04569     temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
04570 
04571     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04572                                             temp16blen, temp16b, temp32a);
04573     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
04574                                             temp32alen, temp32a, temp48);
04575     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04576                                             temp48, finother);
04577     finswap = finnow; finnow = finother; finother = finswap;
04578   }
04579   if (adytail != 0.0) {
04580     aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
04581     temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
04582                                           temp16a);
04583 
04584     aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
04585     temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
04586 
04587     aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
04588     temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
04589 
04590     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04591                                             temp16blen, temp16b, temp32a);
04592     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
04593                                             temp32alen, temp32a, temp48);
04594     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04595                                             temp48, finother);
04596     finswap = finnow; finnow = finother; finother = finswap;
04597   }
04598   if (bdxtail != 0.0) {
04599     bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
04600     temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
04601                                           temp16a);
04602 
04603     bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
04604     temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
04605 
04606     bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
04607     temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
04608 
04609     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04610                                             temp16blen, temp16b, temp32a);
04611     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
04612                                             temp32alen, temp32a, temp48);
04613     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04614                                             temp48, finother);
04615     finswap = finnow; finnow = finother; finother = finswap;
04616   }
04617   if (bdytail != 0.0) {
04618     bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
04619     temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
04620                                           temp16a);
04621 
04622     bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
04623     temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
04624 
04625     bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
04626     temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
04627 
04628     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04629                                             temp16blen, temp16b, temp32a);
04630     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
04631                                             temp32alen, temp32a, temp48);
04632     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04633                                             temp48, finother);
04634     finswap = finnow; finnow = finother; finother = finswap;
04635   }
04636   if (cdxtail != 0.0) {
04637     cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
04638     temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
04639                                           temp16a);
04640 
04641     cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
04642     temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
04643 
04644     cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
04645     temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
04646 
04647     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04648                                             temp16blen, temp16b, temp32a);
04649     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
04650                                             temp32alen, temp32a, temp48);
04651     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04652                                             temp48, finother);
04653     finswap = finnow; finnow = finother; finother = finswap;
04654   }
04655   if (cdytail != 0.0) {
04656     cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
04657     temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
04658                                           temp16a);
04659 
04660     cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
04661     temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
04662 
04663     cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
04664     temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
04665 
04666     temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04667                                             temp16blen, temp16b, temp32a);
04668     temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
04669                                             temp32alen, temp32a, temp48);
04670     finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04671                                             temp48, finother);
04672     finswap = finnow; finnow = finother; finother = finswap;
04673   }
04674 
04675   if ((adxtail != 0.0) || (adytail != 0.0)) {
04676     if ((bdxtail != 0.0) || (bdytail != 0.0)
04677         || (cdxtail != 0.0) || (cdytail != 0.0)) {
04678       Two_Product(bdxtail, cdy, ti1, ti0);
04679       Two_Product(bdx, cdytail, tj1, tj0);
04680       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
04681       u[3] = u3;
04682       negate = -bdy;
04683       Two_Product(cdxtail, negate, ti1, ti0);
04684       negate = -bdytail;
04685       Two_Product(cdx, negate, tj1, tj0);
04686       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
04687       v[3] = v3;
04688       bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
04689 
04690       Two_Product(bdxtail, cdytail, ti1, ti0);
04691       Two_Product(cdxtail, bdytail, tj1, tj0);
04692       Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
04693       bctt[3] = bctt3;
04694       bcttlen = 4;
04695     } else {
04696       bct[0] = 0.0;
04697       bctlen = 1;
04698       bctt[0] = 0.0;
04699       bcttlen = 1;
04700     }
04701 
04702     if (adxtail != 0.0) {
04703       temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
04704       axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
04705       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
04706                                             temp32a);
04707       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04708                                               temp32alen, temp32a, temp48);
04709       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04710                                               temp48, finother);
04711       finswap = finnow; finnow = finother; finother = finswap;
04712       if (bdytail != 0.0) {
04713         temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
04714         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
04715                                               temp16a);
04716         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
04717                                                 temp16a, finother);
04718         finswap = finnow; finnow = finother; finother = finswap;
04719       }
04720       if (cdytail != 0.0) {
04721         temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
04722         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
04723                                               temp16a);
04724         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
04725                                                 temp16a, finother);
04726         finswap = finnow; finnow = finother; finother = finswap;
04727       }
04728 
04729       temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
04730                                             temp32a);
04731       axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
04732       temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
04733                                             temp16a);
04734       temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
04735                                             temp16b);
04736       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04737                                               temp16blen, temp16b, temp32b);
04738       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
04739                                               temp32blen, temp32b, temp64);
04740       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
04741                                               temp64, finother);
04742       finswap = finnow; finnow = finother; finother = finswap;
04743     }
04744     if (adytail != 0.0) {
04745       temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
04746       aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
04747       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
04748                                             temp32a);
04749       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04750                                               temp32alen, temp32a, temp48);
04751       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04752                                               temp48, finother);
04753       finswap = finnow; finnow = finother; finother = finswap;
04754 
04755 
04756       temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
04757                                             temp32a);
04758       aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
04759       temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
04760                                             temp16a);
04761       temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
04762                                             temp16b);
04763       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04764                                               temp16blen, temp16b, temp32b);
04765       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
04766                                               temp32blen, temp32b, temp64);
04767       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
04768                                               temp64, finother);
04769       finswap = finnow; finnow = finother; finother = finswap;
04770     }
04771   }
04772   if ((bdxtail != 0.0) || (bdytail != 0.0)) {
04773     if ((cdxtail != 0.0) || (cdytail != 0.0)
04774         || (adxtail != 0.0) || (adytail != 0.0)) {
04775       Two_Product(cdxtail, ady, ti1, ti0);
04776       Two_Product(cdx, adytail, tj1, tj0);
04777       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
04778       u[3] = u3;
04779       negate = -cdy;
04780       Two_Product(adxtail, negate, ti1, ti0);
04781       negate = -cdytail;
04782       Two_Product(adx, negate, tj1, tj0);
04783       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
04784       v[3] = v3;
04785       catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
04786 
04787       Two_Product(cdxtail, adytail, ti1, ti0);
04788       Two_Product(adxtail, cdytail, tj1, tj0);
04789       Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
04790       catt[3] = catt3;
04791       cattlen = 4;
04792     } else {
04793       cat[0] = 0.0;
04794       catlen = 1;
04795       catt[0] = 0.0;
04796       cattlen = 1;
04797     }
04798 
04799     if (bdxtail != 0.0) {
04800       temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
04801       bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
04802       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
04803                                             temp32a);
04804       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04805                                               temp32alen, temp32a, temp48);
04806       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04807                                               temp48, finother);
04808       finswap = finnow; finnow = finother; finother = finswap;
04809       if (cdytail != 0.0) {
04810         temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
04811         temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
04812                                               temp16a);
04813         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
04814                                                 temp16a, finother);
04815         finswap = finnow; finnow = finother; finother = finswap;
04816       }
04817       if (adytail != 0.0) {
04818         temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
04819         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
04820                                               temp16a);
04821         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
04822                                                 temp16a, finother);
04823         finswap = finnow; finnow = finother; finother = finswap;
04824       }
04825 
04826       temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
04827                                             temp32a);
04828       bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
04829       temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
04830                                             temp16a);
04831       temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
04832                                             temp16b);
04833       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04834                                               temp16blen, temp16b, temp32b);
04835       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
04836                                               temp32blen, temp32b, temp64);
04837       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
04838                                               temp64, finother);
04839       finswap = finnow; finnow = finother; finother = finswap;
04840     }
04841     if (bdytail != 0.0) {
04842       temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
04843       bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
04844       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
04845                                             temp32a);
04846       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04847                                               temp32alen, temp32a, temp48);
04848       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04849                                               temp48, finother);
04850       finswap = finnow; finnow = finother; finother = finswap;
04851 
04852 
04853       temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
04854                                             temp32a);
04855       bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
04856       temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
04857                                             temp16a);
04858       temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
04859                                             temp16b);
04860       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04861                                               temp16blen, temp16b, temp32b);
04862       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
04863                                               temp32blen, temp32b, temp64);
04864       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
04865                                               temp64, finother);
04866       finswap = finnow; finnow = finother; finother = finswap;
04867     }
04868   }
04869   if ((cdxtail != 0.0) || (cdytail != 0.0)) {
04870     if ((adxtail != 0.0) || (adytail != 0.0)
04871         || (bdxtail != 0.0) || (bdytail != 0.0)) {
04872       Two_Product(adxtail, bdy, ti1, ti0);
04873       Two_Product(adx, bdytail, tj1, tj0);
04874       Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
04875       u[3] = u3;
04876       negate = -ady;
04877       Two_Product(bdxtail, negate, ti1, ti0);
04878       negate = -adytail;
04879       Two_Product(bdx, negate, tj1, tj0);
04880       Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
04881       v[3] = v3;
04882       abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
04883 
04884       Two_Product(adxtail, bdytail, ti1, ti0);
04885       Two_Product(bdxtail, adytail, tj1, tj0);
04886       Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
04887       abtt[3] = abtt3;
04888       abttlen = 4;
04889     } else {
04890       abt[0] = 0.0;
04891       abtlen = 1;
04892       abtt[0] = 0.0;
04893       abttlen = 1;
04894     }
04895 
04896     if (cdxtail != 0.0) {
04897       temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
04898       cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
04899       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
04900                                             temp32a);
04901       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04902                                               temp32alen, temp32a, temp48);
04903       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04904                                               temp48, finother);
04905       finswap = finnow; finnow = finother; finother = finswap;
04906       if (adytail != 0.0) {
04907         temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
04908         temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
04909                                               temp16a);
04910         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
04911                                                 temp16a, finother);
04912         finswap = finnow; finnow = finother; finother = finswap;
04913       }
04914       if (bdytail != 0.0) {
04915         temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
04916         temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
04917                                               temp16a);
04918         finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
04919                                                 temp16a, finother);
04920         finswap = finnow; finnow = finother; finother = finswap;
04921       }
04922 
04923       temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
04924                                             temp32a);
04925       cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
04926       temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
04927                                             temp16a);
04928       temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
04929                                             temp16b);
04930       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04931                                               temp16blen, temp16b, temp32b);
04932       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
04933                                               temp32blen, temp32b, temp64);
04934       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
04935                                               temp64, finother);
04936       finswap = finnow; finnow = finother; finother = finswap;
04937     }
04938     if (cdytail != 0.0) {
04939       temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
04940       cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
04941       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
04942                                             temp32a);
04943       temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04944                                               temp32alen, temp32a, temp48);
04945       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
04946                                               temp48, finother);
04947       finswap = finnow; finnow = finother; finother = finswap;
04948 
04949 
04950       temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
04951                                             temp32a);
04952       cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
04953       temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
04954                                             temp16a);
04955       temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
04956                                             temp16b);
04957       temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
04958                                               temp16blen, temp16b, temp32b);
04959       temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
04960                                               temp32blen, temp32b, temp64);
04961       finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
04962                                               temp64, finother);
04963       finswap = finnow; finnow = finother; finother = finswap;
04964     }
04965   }
04966 
04967   return finnow[finlength - 1];
04968 }
04969 
04970 REAL incircle(pa, pb, pc, pd)
04971 point pa;
04972 point pb;
04973 point pc;
04974 point pd;
04975 {
04976   REAL adx, bdx, cdx, ady, bdy, cdy;
04977   REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
04978   REAL alift, blift, clift;
04979   REAL det;
04980   REAL permanent, errbound;
04981 
04982   incirclecount++;
04983 
04984   adx = pa[0] - pd[0];
04985   bdx = pb[0] - pd[0];
04986   cdx = pc[0] - pd[0];
04987   ady = pa[1] - pd[1];
04988   bdy = pb[1] - pd[1];
04989   cdy = pc[1] - pd[1];
04990 
04991   bdxcdy = bdx * cdy;
04992   cdxbdy = cdx * bdy;
04993   alift = adx * adx + ady * ady;
04994 
04995   cdxady = cdx * ady;
04996   adxcdy = adx * cdy;
04997   blift = bdx * bdx + bdy * bdy;
04998 
04999   adxbdy = adx * bdy;
05000   bdxady = bdx * ady;
05001   clift = cdx * cdx + cdy * cdy;
05002 
05003   det = alift * (bdxcdy - cdxbdy)
05004       + blift * (cdxady - adxcdy)
05005       + clift * (adxbdy - bdxady);
05006 
05007   if (noexact) {
05008     return det;
05009   }
05010 
05011   permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
05012             + (Absolute(cdxady) + Absolute(adxcdy)) * blift
05013             + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
05014   errbound = iccerrboundA * permanent;
05015   if ((det > errbound) || (-det > errbound)) {
05016     return det;
05017   }
05018 
05019   return incircleadapt(pa, pb, pc, pd, permanent);
05020 }
05021 
05022 /**                                                                         **/
05023 /**                                                                         **/
05024 /********* Determinant evaluation routines end here                  *********/
05025 
05026 /*****************************************************************************/
05027 /*                                                                           */
05028 /*  triangleinit()   Initialize some variables.                              */
05029 /*                                                                           */
05030 /*****************************************************************************/
05031 
05032 void triangleinit()
05033 {
05034   points.maxitems = triangles.maxitems = shelles.maxitems = viri.maxitems =
05035     badsegments.maxitems = badtriangles.maxitems = splaynodes.maxitems = 0l;
05036   points.itembytes = triangles.itembytes = shelles.itembytes = viri.itembytes =
05037     badsegments.itembytes = badtriangles.itembytes = splaynodes.itembytes = 0;
05038   recenttri.tri = (triangle *) NULL;    /* No triangle has been visited yet. */
05039   samples = 1;            /* Point location should take at least one sample. */
05040   checksegments = 0;      /* There are no segments in the triangulation yet. */
05041   incirclecount = counterclockcount = hyperbolacount = 0;
05042   circumcentercount = circletopcount = 0;
05043   randomseed = 1;
05044 
05045   exactinit();                     /* Initialize exact arithmetic constants. */
05046 }
05047 
05048 /*****************************************************************************/
05049 /*                                                                           */
05050 /*  randomnation()   Generate a random number between 0 and `choices' - 1.   */
05051 /*                                                                           */
05052 /*  This is a simple linear congruential random number generator.  Hence, it */
05053 /*  is a bad random number generator, but good enough for most randomized    */
05054 /*  geometric algorithms.                                                    */
05055 /*                                                                           */
05056 /*****************************************************************************/
05057 
05058 unsigned long randomnation(choices)
05059 unsigned int choices;
05060 {
05061   randomseed = (randomseed * 1366l + 150889l) % 714025l;
05062   return randomseed / (714025l / choices + 1);
05063 }
05064 
05065 /********* Mesh quality testing routines begin here                  *********/
05066 /**                                                                         **/
05067 /**                                                                         **/
05068 
05069 /*****************************************************************************/
05070 /*                                                                           */
05071 /*  checkmesh()   Test the mesh for topological consistency.                 */
05072 /*                                                                           */
05073 /*****************************************************************************/
05074 
05075 #ifndef REDUCED
05076 
05077 void checkmesh()
05078 {
05079   struct triedge triangleloop;
05080   struct triedge oppotri, oppooppotri;
05081   point triorg, tridest, triapex;
05082   point oppoorg, oppodest;
05083   int horrors;
05084   int saveexact;
05085   triangle ptr;                         /* Temporary variable used by sym(). */
05086 
05087   /* Temporarily turn on exact arithmetic if it's off. */
05088   saveexact = noexact;
05089   noexact = 0;
05090   if (!quiet) {
05091     printf("  Checking consistency of mesh...\n");
05092   }
05093   horrors = 0;
05094   /* Run through the list of triangles, checking each one. */
05095   traversalinit(&triangles);
05096   triangleloop.tri = triangletraverse();
05097   while (triangleloop.tri != (triangle *) NULL) {
05098     /* Check all three edges of the triangle. */
05099     for (triangleloop.orient = 0; triangleloop.orient < 3;
05100          triangleloop.orient++) {
05101       org(triangleloop, triorg);
05102       dest(triangleloop, tridest);
05103       if (triangleloop.orient == 0) {       /* Only test for inversion once. */
05104         /* Test if the triangle is flat or inverted. */
05105         apex(triangleloop, triapex);
05106         if (counterclockwise(triorg, tridest, triapex) <= 0.0) {
05107           printf("  !! !! Inverted ");
05108           printtriangle(&triangleloop);
05109           horrors++;
05110         }
05111       }
05112       /* Find the neighboring triangle on this edge. */
05113       sym(triangleloop, oppotri);
05114       if (oppotri.tri != dummytri) {
05115         /* Check that the triangle's neighbor knows it's a neighbor. */
05116         sym(oppotri, oppooppotri);
05117         if ((triangleloop.tri != oppooppotri.tri)
05118             || (triangleloop.orient != oppooppotri.orient)) {
05119           printf("  !! !! Asymmetric triangle-triangle bond:\n");
05120           if (triangleloop.tri == oppooppotri.tri) {
05121             printf("   (Right triangle, wrong orientation)\n");
05122           }
05123           printf("    First ");
05124           printtriangle(&triangleloop);
05125           printf("    Second (nonreciprocating) ");
05126           printtriangle(&oppotri);
05127           horrors++;
05128         }
05129         /* Check that both triangles agree on the identities */
05130         /*   of their shared vertices.                       */
05131         org(oppotri, oppoorg);
05132         dest(oppotri, oppodest);
05133         if ((triorg != oppodest) || (tridest != oppoorg)) {
05134           printf("  !! !! Mismatched edge coordinates between two triangles:\n"
05135                  );
05136           printf("    First mismatched ");
05137           printtriangle(&triangleloop);
05138           printf("    Second mismatched ");
05139           printtriangle(&oppotri);
05140           horrors++;
05141         }
05142       }
05143     }
05144     triangleloop.tri = triangletraverse();
05145   }
05146   if (horrors == 0) {
05147     if (!quiet) {
05148       printf("  In my studied opinion, the mesh appears to be consistent.\n");
05149     }
05150   } else if (horrors == 1) {
05151     printf("  !! !! !! !! Precisely one festering wound discovered.\n");
05152   } else {
05153     printf("  !! !! !! !! %d abominations witnessed.\n", horrors);
05154   }
05155   /* Restore the status of exact arithmetic. */
05156   noexact = saveexact;
05157 }
05158 
05159 #endif /* not REDUCED */
05160 
05161 /*****************************************************************************/
05162 /*                                                                           */
05163 /*  checkdelaunay()   Ensure that the mesh is (constrained) Delaunay.        */
05164 /*                                                                           */
05165 /*****************************************************************************/
05166 
05167 #ifndef REDUCED
05168 
05169 void checkdelaunay()
05170 {
05171   struct triedge triangleloop;
05172   struct triedge oppotri;
05173   struct edge opposhelle;
05174   point triorg, tridest, triapex;
05175   point oppoapex;
05176   int shouldbedelaunay;
05177   int horrors;
05178   int saveexact;
05179   triangle ptr;                         /* Temporary variable used by sym(). */
05180   shelle sptr;                      /* Temporary variable used by tspivot(). */
05181 
05182   /* Temporarily turn on exact arithmetic if it's off. */
05183   saveexact = noexact;
05184   noexact = 0;
05185   if (!quiet) {
05186     printf("  Checking Delaunay property of mesh...\n");
05187   }
05188   horrors = 0;
05189   /* Run through the list of triangles, checking each one. */
05190   traversalinit(&triangles);
05191   triangleloop.tri = triangletraverse();
05192   while (triangleloop.tri != (triangle *) NULL) {
05193     /* Check all three edges of the triangle. */
05194     for (triangleloop.orient = 0; triangleloop.orient < 3;
05195          triangleloop.orient++) {
05196       org(triangleloop, triorg);
05197       dest(triangleloop, tridest);
05198       apex(triangleloop, triapex);
05199       sym(triangleloop, oppotri);
05200       apex(oppotri, oppoapex);
05201       /* Only test that the edge is locally Delaunay if there is an   */
05202       /*   adjoining triangle whose pointer is larger (to ensure that */
05203       /*   each pair isn't tested twice).                             */
05204       shouldbedelaunay = (oppotri.tri != dummytri)
05205             && (triapex != (point) NULL) && (oppoapex != (point) NULL)
05206             && (triangleloop.tri < oppotri.tri);
05207       if (checksegments && shouldbedelaunay) {
05208         /* If a shell edge separates the triangles, then the edge is */
05209         /*   constrained, so no local Delaunay test should be done.  */
05210         tspivot(triangleloop, opposhelle);
05211         if (opposhelle.sh != dummysh){
05212           shouldbedelaunay = 0;
05213         }
05214       }
05215       if (shouldbedelaunay) {
05216         if (incircle(triorg, tridest, triapex, oppoapex) > 0.0) {
05217           printf("  !! !! Non-Delaunay pair of triangles:\n");
05218           printf("    First non-Delaunay ");
05219           printtriangle(&triangleloop);
05220           printf("    Second non-Delaunay ");
05221           printtriangle(&oppotri);
05222           horrors++;
05223         }
05224       }
05225     }
05226     triangleloop.tri = triangletraverse();
05227   }
05228   if (horrors == 0) {
05229     if (!quiet) {
05230       printf(
05231   "  By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
05232     }
05233   } else if (horrors == 1) {
05234     printf(
05235          "  !! !! !! !! Precisely one terrifying transgression identified.\n");
05236   } else {
05237     printf("  !! !! !! !! %d obscenities viewed with horror.\n", horrors);
05238   }
05239   /* Restore the status of exact arithmetic. */
05240   noexact = saveexact;
05241 }
05242 
05243 #endif /* not REDUCED */
05244 
05245 /*****************************************************************************/
05246 /*                                                                           */
05247 /*  enqueuebadtri()   Add a bad triangle to the end of a queue.              */
05248 /*                                                                           */
05249 /*  The queue is actually a set of 64 queues.  I use multiple queues to give */
05250 /*  priority to smaller angles.  I originally implemented a heap, but the    */
05251 /*  queues are (to my surprise) much faster.                                 */
05252 /*                                                                           */
05253 /*****************************************************************************/
05254 
05255 #ifndef CDT_ONLY
05256 
05257 void enqueuebadtri(instri, angle, insapex, insorg, insdest)
05258 struct triedge *instri;
05259 REAL angle;
05260 point insapex;
05261 point insorg;
05262 point insdest;
05263 {
05264   struct badface *newface;
05265   int queuenumber;
05266 
05267   if (verbose > 2) {
05268     printf("  Queueing bad triangle:\n");
05269     printf("    (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", insorg[0],
05270            insorg[1], insdest[0], insdest[1], insapex[0], insapex[1]);
05271   }
05272   /* Allocate space for the bad triangle. */
05273   newface = (struct badface *) poolalloc(&badtriangles);
05274   triedgecopy(*instri, newface->badfacetri);
05275   newface->key = angle;
05276   newface->faceapex = insapex;
05277   newface->faceorg = insorg;
05278   newface->facedest = insdest;
05279   newface->nextface = (struct badface *) NULL;
05280   /* Determine the appropriate queue to put the bad triangle into. */
05281   if (angle > 0.6) {
05282     queuenumber = (int) (160.0 * (angle - 0.6));
05283     if (queuenumber > 63) {
05284       queuenumber = 63;
05285     }
05286   } else {
05287     /* It's not a bad angle; put the triangle in the lowest-priority queue. */
05288     queuenumber = 0;
05289   }
05290   /* Add the triangle to the end of a queue. */
05291   *queuetail[queuenumber] = newface;
05292   /* Maintain a pointer to the NULL pointer at the end of the queue. */
05293   queuetail[queuenumber] = &newface->nextface;
05294 }
05295 
05296 #endif /* not CDT_ONLY */
05297 
05298 /*****************************************************************************/
05299 /*                                                                           */
05300 /*  dequeuebadtri()   Remove a triangle from the front of the queue.         */
05301 /*                                                                           */
05302 /*****************************************************************************/
05303 
05304 #ifndef CDT_ONLY
05305 
05306 struct badface *dequeuebadtri()
05307 {
05308   struct badface *result;
05309   int queuenumber;
05310 
05311   /* Look for a nonempty queue. */
05312   for (queuenumber = 63; queuenumber >= 0; queuenumber--) {
05313     result = queuefront[queuenumber];
05314     if (result != (struct badface *) NULL) {
05315       /* Remove the triangle from the queue. */
05316       queuefront[queuenumber] = result->nextface;
05317       /* Maintain a pointer to the NULL pointer at the end of the queue. */
05318       if (queuefront[queuenumber] == (struct badface *) NULL) {
05319         queuetail[queuenumber] = &queuefront[queuenumber];
05320       }
05321       return result;
05322     }
05323   }
05324   return (struct badface *) NULL;
05325 }
05326 
05327 #endif /* not CDT_ONLY */
05328 
05329 /*****************************************************************************/
05330 /*                                                                           */
05331 /*  checkedge4encroach()   Check a segment to see if it is encroached; add   */
05332 /*                         it to the list if it is.                          */
05333 /*                                                                           */
05334 /*  An encroached segment is an unflippable edge that has a point in its     */
05335 /*  diametral circle (that is, it faces an angle greater than 90 degrees).   */
05336 /*  This definition is due to Ruppert.                                       */
05337 /*                                                                           */
05338 /*  Returns a nonzero value if the edge is encroached.                       */
05339 /*                                                                           */
05340 /*****************************************************************************/
05341 
05342 #ifndef CDT_ONLY
05343 
05344 int checkedge4encroach(testedge)
05345 struct edge *testedge;
05346 {
05347   struct triedge neighbortri;
05348   struct edge testsym;
05349   struct edge *badedge;
05350   int addtolist;
05351   int sides;
05352   point eorg, edest, eapex;
05353   triangle ptr;                     /* Temporary variable used by stpivot(). */
05354 
05355   addtolist = 0;
05356   sides = 0;
05357 
05358   sorg(*testedge, eorg);
05359   sdest(*testedge, edest);
05360   /* Check one neighbor of the shell edge. */
05361   stpivot(*testedge, neighbortri);
05362   /* Does the neighbor exist, or is this a boundary edge? */
05363   if (neighbortri.tri != dummytri) {
05364     sides++;
05365     /* Find a vertex opposite this edge. */
05366     apex(neighbortri, eapex);
05367     /* Check whether the vertex is inside the diametral circle of the  */
05368     /*   shell edge.  Pythagoras' Theorem is used to check whether the */
05369     /*   angle at the vertex is greater than 90 degrees.               */
05370     if (eapex[0] * (eorg[0] + edest[0]) + eapex[1] * (eorg[1] + edest[1]) >
05371         eapex[0] * eapex[0] + eorg[0] * edest[0] +
05372         eapex[1] * eapex[1] + eorg[1] * edest[1]) {
05373       addtolist = 1;
05374     }
05375   }
05376   /* Check the other neighbor of the shell edge. */
05377   ssym(*testedge, testsym);
05378   stpivot(testsym, neighbortri);
05379   /* Does the neighbor exist, or is this a boundary edge? */
05380   if (neighbortri.tri != dummytri) {
05381     sides++;
05382     /* Find the other vertex opposite this edge. */
05383     apex(neighbortri, eapex);
05384     /* Check whether the vertex is inside the diametral circle of the  */
05385     /*   shell edge.  Pythagoras' Theorem is used to check whether the */
05386     /*   angle at the vertex is greater than 90 degrees.               */
05387     if (eapex[0] * (eorg[0] + edest[0]) +
05388         eapex[1] * (eorg[1] + edest[1]) >
05389         eapex[0] * eapex[0] + eorg[0] * edest[0] +
05390         eapex[1] * eapex[1] + eorg[1] * edest[1]) {
05391       addtolist += 2;
05392     }
05393   }
05394 
05395   if (addtolist && (!nobisect || ((nobisect == 1) && (sides == 2)))) {
05396     if (verbose > 2) {
05397       printf("  Queueing encroached segment (%.12g, %.12g) (%.12g, %.12g).\n",
05398              eorg[0], eorg[1], edest[0], edest[1]);
05399     }
05400     /* Add the shell edge to the list of encroached segments. */
05401     /*   Be sure to get the orientation right.                */
05402     badedge = (struct edge *) poolalloc(&badsegments);
05403     if (addtolist == 1) {
05404       shellecopy(*testedge, *badedge);
05405     } else {
05406       shellecopy(testsym, *badedge);
05407     }
05408   }
05409   return addtolist;
05410 }
05411 
05412 #endif /* not CDT_ONLY */
05413 
05414 /*****************************************************************************/
05415 /*                                                                           */
05416 /*  testtriangle()   Test a face for quality measures.                       */
05417 /*                                                                           */
05418 /*  Tests a triangle to see if it satisfies the minimum angle condition and  */
05419 /*  the maximum area condition.  Triangles that aren't up to spec are added  */
05420 /*  to the bad triangle queue.                                               */
05421 /*                                                                           */
05422 /*****************************************************************************/
05423 
05424 #ifndef CDT_ONLY
05425 
05426 void testtriangle(testtri)
05427 struct triedge *testtri;
05428 {
05429   struct triedge sametesttri;
05430   struct edge edge1, edge2;
05431   point torg, tdest, tapex;
05432   point anglevertex;
05433   REAL dxod, dyod, dxda, dyda, dxao, dyao;
05434   REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
05435   REAL apexlen, orglen, destlen;
05436   REAL angle;
05437   REAL area;
05438   shelle sptr;                      /* Temporary variable used by tspivot(). */
05439 
05440   org(*testtri, torg);
05441   dest(*testtri, tdest);
05442   apex(*testtri, tapex);
05443   dxod = torg[0] - tdest[0];
05444   dyod = torg[1] - tdest[1];
05445   dxda = tdest[0] - tapex[0];
05446   dyda = tdest[1] - tapex[1];
05447   dxao = tapex[0] - torg[0];
05448   dyao = tapex[1] - torg[1];
05449   dxod2 = dxod * dxod;
05450   dyod2 = dyod * dyod;
05451   dxda2 = dxda * dxda;
05452   dyda2 = dyda * dyda;
05453   dxao2 = dxao * dxao;
05454   dyao2 = dyao * dyao;
05455   /* Find the lengths of the triangle's three edges. */
05456   apexlen = dxod2 + dyod2;
05457   orglen = dxda2 + dyda2;
05458   destlen = dxao2 + dyao2;
05459   if ((apexlen < orglen) && (apexlen < destlen)) {
05460     /* The edge opposite the apex is shortest. */
05461     /* Find the square of the cosine of the angle at the apex. */
05462     angle = dxda * dxao + dyda * dyao;
05463     angle = angle * angle / (orglen * destlen);
05464     anglevertex = tapex;
05465     lnext(*testtri, sametesttri);
05466     tspivot(sametesttri, edge1);
05467     lnextself(sametesttri);
05468     tspivot(sametesttri, edge2);
05469   } else if (orglen < destlen) {
05470     /* The edge opposite the origin is shortest. */
05471     /* Find the square of the cosine of the angle at the origin. */
05472     angle = dxod * dxao + dyod * dyao;
05473     angle = angle * angle / (apexlen * destlen);
05474     anglevertex = torg;
05475     tspivot(*testtri, edge1);
05476     lprev(*testtri, sametesttri);
05477     tspivot(sametesttri, edge2);
05478   } else {
05479     /* The edge opposite the destination is shortest. */
05480     /* Find the square of the cosine of the angle at the destination. */
05481     angle = dxod * dxda + dyod * dyda;
05482     angle = angle * angle / (apexlen * orglen);
05483     anglevertex = tdest;
05484     tspivot(*testtri, edge1);
05485     lnext(*testtri, sametesttri);
05486     tspivot(sametesttri, edge2);
05487   }
05488   /* Check if both edges that form the angle are segments. */
05489   if ((edge1.sh != dummysh) && (edge2.sh != dummysh)) {
05490     /* The angle is a segment intersection. */
05491     if ((angle > 0.9924) && !quiet) {                  /* Roughly 5 degrees. */
05492       if (angle > 1.0) {
05493         /* Beware of a floating exception in acos(). */
05494         angle = 1.0;
05495       }
05496       /* Find the actual angle in degrees, for printing. */
05497       angle = acos(sqrt(angle)) * (180.0 / PI);
05498       printf(
05499       "Warning:  Small angle (%.4g degrees) between segments at point\n",
05500              angle);
05501       printf("  (%.12g, %.12g)\n", anglevertex[0], anglevertex[1]);
05502     }
05503     /* Don't add this bad triangle to the list; there's nothing that */
05504     /*   can be done about a small angle between two segments.       */
05505     angle = 0.0;
05506   }
05507   /* Check whether the angle is smaller than permitted. */
05508   if (angle > goodangle) {
05509     /* Add this triangle to the list of bad triangles. */
05510     enqueuebadtri(testtri, angle, tapex, torg, tdest);
05511     return;
05512   }
05513   if (vararea || fixedarea) {
05514     /* Check whether the area is larger than permitted. */
05515     area = 0.5 * (dxod * dyda - dyod * dxda);
05516     if (fixedarea && (area > maxarea)) {
05517       /* Add this triangle to the list of bad triangles. */
05518       enqueuebadtri(testtri, angle, tapex, torg, tdest);
05519     } else if (vararea) {
05520       /* Nonpositive area constraints are treated as unconstrained. */
05521       if ((area > areabound(*testtri)) && (areabound(*testtri) > 0.0)) {
05522         /* Add this triangle to the list of bad triangles. */
05523         enqueuebadtri(testtri, angle, tapex, torg, tdest);
05524       }
05525     }
05526   }
05527 }
05528 
05529 #endif /* not CDT_ONLY */
05530 
05531 /**                                                                         **/
05532 /**                                                                         **/
05533 /********* Mesh quality testing routines end here                    *********/
05534 
05535 /********* Point location routines begin here                        *********/
05536 /**                                                                         **/
05537 /**                                                                         **/
05538 
05539 /*****************************************************************************/
05540 /*                                                                           */
05541 /*  makepointmap()   Construct a mapping from points to triangles to improve  */
05542 /*                  the speed of point location for segment insertion.       */
05543 /*                                                                           */
05544 /*  Traverses all the triangles, and provides each corner of each triangle   */
05545 /*  with a pointer to that triangle.  Of course, pointers will be            */
05546 /*  overwritten by other pointers because (almost) each point is a corner    */
05547 /*  of several triangles, but in the end every point will point to some      */
05548 /*  triangle that contains it.                                               */
05549 /*                                                                           */
05550 /*****************************************************************************/
05551 
05552 void makepointmap()
05553 {
05554   struct triedge triangleloop;
05555   point triorg;
05556 
05557   if (verbose) {
05558     printf("    Constructing mapping from points to triangles.\n");
05559   }
05560   traversalinit(&triangles);
05561   triangleloop.tri = triangletraverse();
05562   while (triangleloop.tri != (triangle *) NULL) {
05563     /* Check all three points of the triangle. */
05564     for (triangleloop.orient = 0; triangleloop.orient < 3;
05565          triangleloop.orient++) {
05566       org(triangleloop, triorg);
05567       setpoint2tri(triorg, encode(triangleloop));
05568     }
05569     triangleloop.tri = triangletraverse();
05570   }
05571 }
05572 
05573 /*****************************************************************************/
05574 /*                                                                           */
05575 /*  preciselocate()   Find a triangle or edge containing a given point.      */
05576 /*                                                                           */
05577 /*  Begins its search from `searchtri'.  It is important that `searchtri'    */
05578 /*  be a handle with the property that `searchpoint' is strictly to the left */
05579 /*  of the edge denoted by `searchtri', or is collinear with that edge and   */
05580 /*  does not intersect that edge.  (In particular, `searchpoint' should not  */
05581 /*  be the origin or destination of that edge.)                              */
05582 /*                                                                           */
05583 /*  These conditions are imposed because preciselocate() is normally used in */
05584 /*  one of two situations:                                                   */
05585 /*                                                                           */
05586 /*  (1)  To try to find the location to insert a new point.  Normally, we    */
05587 /*       know an edge that the point is strictly to the left of.  In the     */
05588 /*       incremental Delaunay algorithm, that edge is a bounding box edge.   */
05589 /*       In Ruppert's Delaunay refinement algorithm for quality meshing,     */
05590 /*       that edge is the shortest edge of the triangle whose circumcenter   */
05591 /*       is being inserted.                                                  */
05592 /*                                                                           */
05593 /*  (2)  To try to find an existing point.  In this case, any edge on the    */
05594 /*       convex hull is a good starting edge.  The possibility that the      */
05595 /*       vertex one seeks is an endpoint of the starting edge must be        */
05596 /*       screened out before preciselocate() is called.                      */
05597 /*                                                                           */
05598 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
05599 /*                                                                           */
05600 /*  This implementation differs from that given by Guibas and Stolfi.  It    */
05601 /*  walks from triangle to triangle, crossing an edge only if `searchpoint'  */
05602 /*  is on the other side of the line containing that edge.  After entering   */
05603 /*  a triangle, there are two edges by which one can leave that triangle.    */
05604 /*  If both edges are valid (`searchpoint' is on the other side of both      */
05605 /*  edges), one of the two is chosen by drawing a line perpendicular to      */
05606 /*  the entry edge (whose endpoints are `forg' and `fdest') passing through  */
05607 /*  `fapex'.  Depending on which side of this perpendicular `searchpoint'    */
05608 /*  falls on, an exit edge is chosen.                                        */
05609 /*                                                                           */
05610 /*  This implementation is empirically faster than the Guibas and Stolfi     */
05611 /*  point location routine (which I originally used), which tends to spiral  */
05612 /*  in toward its target.                                                    */
05613 /*                                                                           */
05614 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
05615 /*  is a handle whose origin is the existing vertex.                         */
05616 /*                                                                           */
05617 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
05618 /*  handle whose primary edge is the edge on which the point lies.           */
05619 /*                                                                           */
05620 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
05621 /*  `searchtri' is a handle on the triangle that contains the point.         */
05622 /*                                                                           */
05623 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
05624 /*  handle whose primary edge the point is to the right of.  This might      */
05625 /*  occur when the circumcenter of a triangle falls just slightly outside    */
05626 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
05627 /*  seeking a hole or region point that a foolish user has placed outside    */
05628 /*  the mesh.                                                                */
05629 /*                                                                           */
05630 /*  WARNING:  This routine is designed for convex triangulations, and will   */
05631 /*  not generally work after the holes and concavities have been carved.     */
05632 /*  However, it can still be used to find the circumcenter of a triangle, as */
05633 /*  long as the search is begun from the triangle in question.               */
05634 /*                                                                           */
05635 /*****************************************************************************/
05636 
05637 enum locateresult preciselocate(searchpoint, searchtri)
05638 point searchpoint;
05639 struct triedge *searchtri;
05640 {
05641   struct triedge backtracktri;
05642   point forg, fdest, fapex;
05643   point swappoint;
05644   REAL orgorient, destorient;
05645   int moveleft;
05646   triangle ptr;                         /* Temporary variable used by sym(). */
05647 
05648   if (verbose > 2) {
05649     printf("  Searching for point (%.12g, %.12g).\n",
05650            searchpoint[0], searchpoint[1]);
05651   }
05652   /* Where are we? */
05653   org(*searchtri, forg);
05654   dest(*searchtri, fdest);
05655   apex(*searchtri, fapex);
05656   while (1) {
05657     if (verbose > 2) {
05658       printf("    At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
05659              forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
05660     }
05661     /* Check whether the apex is the point we seek. */
05662     if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
05663       lprevself(*searchtri);
05664       return ONVERTEX;
05665     }
05666     /* Does the point lie on the other side of the line defined by the */
05667     /*   triangle edge opposite the triangle's destination?            */
05668     destorient = counterclockwise(forg, fapex, searchpoint);
05669     /* Does the point lie on the other side of the line defined by the */
05670     /*   triangle edge opposite the triangle's origin?                 */
05671     orgorient = counterclockwise(fapex, fdest, searchpoint);
05672     if (destorient > 0.0) {
05673       if (orgorient > 0.0) {
05674         /* Move left if the inner product of (fapex - searchpoint) and  */
05675         /*   (fdest - forg) is positive.  This is equivalent to drawing */
05676         /*   a line perpendicular to the line (forg, fdest) passing     */
05677         /*   through `fapex', and determining which side of this line   */
05678         /*   `searchpoint' falls on.                                    */
05679         moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
05680                    (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
05681       } else {
05682         moveleft = 1;
05683       }
05684     } else {
05685       if (orgorient > 0.0) {
05686         moveleft = 0;
05687       } else {
05688         /* The point we seek must be on the boundary of or inside this */
05689         /*   triangle.                                                 */
05690         if (destorient == 0.0) {
05691           lprevself(*searchtri);
05692           return ONEDGE;
05693         }
05694         if (orgorient == 0.0) {
05695           lnextself(*searchtri);
05696           return ONEDGE;
05697         }
05698         return INTRIANGLE;
05699       }
05700     }
05701 
05702     /* Move to another triangle.  Leave a trace `backtracktri' in case */
05703     /*   floating-point roundoff or some such bogey causes us to walk  */
05704     /*   off a boundary of the triangulation.  We can just bounce off  */
05705     /*   the boundary as if it were an elastic band.                   */
05706     if (moveleft) {
05707       lprev(*searchtri, backtracktri);
05708       fdest = fapex;
05709     } else {
05710       lnext(*searchtri, backtracktri);
05711       forg = fapex;
05712     }
05713     sym(backtracktri, *searchtri);
05714 
05715     /* Check for walking off the edge. */
05716     if (searchtri->tri == dummytri) {
05717       /* Turn around. */
05718       triedgecopy(backtracktri, *searchtri);
05719       swappoint = forg;
05720       forg = fdest;
05721       fdest = swappoint;
05722       apex(*searchtri, fapex);
05723       /* Check if the point really is beyond the triangulation boundary. */
05724       destorient = counterclockwise(forg, fapex, searchpoint);
05725       orgorient = counterclockwise(fapex, fdest, searchpoint);
05726       if ((orgorient < 0.0) && (destorient < 0.0)) {
05727         return OUTSIDE;
05728       }
05729     } else {
05730       apex(*searchtri, fapex);
05731     }
05732   }
05733 }
05734 
05735 /*****************************************************************************/
05736 /*                                                                           */
05737 /*  locate()   Find a triangle or edge containing a given point.             */
05738 /*                                                                           */
05739 /*  Searching begins from one of:  the input `searchtri', a recently         */
05740 /*  encountered triangle `recenttri', or from a triangle chosen from a       */
05741 /*  random sample.  The choice is made by determining which triangle's       */
05742 /*  origin is closest to the point we are searcing for.  Normally,           */
05743 /*  `searchtri' should be a handle on the convex hull of the triangulation.  */
05744 /*                                                                           */
05745 /*  Details on the random sampling method can be found in the Mucke, Saias,  */
05746 /*  and Zhu paper cited in the header of this code.                          */
05747 /*                                                                           */
05748 /*  On completion, `searchtri' is a triangle that contains `searchpoint'.    */
05749 /*                                                                           */
05750 /*  Returns ONVERTEX if the point lies on an existing vertex.  `searchtri'   */
05751 /*  is a handle whose origin is the existing vertex.                         */
05752 /*                                                                           */
05753 /*  Returns ONEDGE if the point lies on a mesh edge.  `searchtri' is a       */
05754 /*  handle whose primary edge is the edge on which the point lies.           */
05755 /*                                                                           */
05756 /*  Returns INTRIANGLE if the point lies strictly within a triangle.         */
05757 /*  `searchtri' is a handle on the triangle that contains the point.         */
05758 /*                                                                           */
05759 /*  Returns OUTSIDE if the point lies outside the mesh.  `searchtri' is a    */
05760 /*  handle whose primary edge the point is to the right of.  This might      */
05761 /*  occur when the circumcenter of a triangle falls just slightly outside    */
05762 /*  the mesh due to floating-point roundoff error.  It also occurs when      */
05763 /*  seeking a hole or region point that a foolish user has placed outside    */
05764 /*  the mesh.                                                                */
05765 /*                                                                           */
05766 /*  WARNING:  This routine is designed for convex triangulations, and will   */
05767 /*  not generally work after the holes and concavities have been carved.     */
05768 /*                                                                           */
05769 /*****************************************************************************/
05770 
05771 enum locateresult locate(searchpoint, searchtri)
05772 point searchpoint;
05773 struct triedge *searchtri;
05774 {
05775   VOID **sampleblock;
05776   triangle *firsttri;
05777   struct triedge sampletri;
05778   point torg, tdest;
05779   unsigned long alignptr;
05780   REAL searchdist, dist;
05781   REAL ahead;
05782   long sampleblocks, samplesperblock, samplenum;
05783   long triblocks;
05784   long i, j;
05785   triangle ptr;                         /* Temporary variable used by sym(). */
05786 
05787   if (verbose > 2) {
05788     printf("  Randomly sampling for a triangle near point (%.12g, %.12g).\n",
05789            searchpoint[0], searchpoint[1]);
05790   }
05791   /* Record the distance from the suggested starting triangle to the */
05792   /*   point we seek.                                                */
05793   org(*searchtri, torg);
05794   searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
05795              + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
05796   if (verbose > 2) {
05797     printf("    Boundary triangle has origin (%.12g, %.12g).\n",
05798            torg[0], torg[1]);
05799   }
05800 
05801   /* If a recently encountered triangle has been recorded and has not been */
05802   /*   deallocated, test it as a good starting point.                      */
05803   if (recenttri.tri != (triangle *) NULL) {
05804     if (recenttri.tri[3] != (triangle) NULL) {
05805       org(recenttri, torg);
05806       if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
05807         triedgecopy(recenttri, *searchtri);
05808         return ONVERTEX;
05809       }
05810       dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
05811            + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
05812       if (dist < searchdist) {
05813         triedgecopy(recenttri, *searchtri);
05814         searchdist = dist;
05815         if (verbose > 2) {
05816           printf("    Choosing recent triangle with origin (%.12g, %.12g).\n",
05817                  torg[0], torg[1]);
05818         }
05819       }
05820     }
05821   }
05822 
05823   /* The number of random samples taken is proportional to the cube root of */
05824   /*   the number of triangles in the mesh.  The next bit of code assumes   */
05825   /*   that the number of triangles increases monotonically.                */
05826   while (SAMPLEFACTOR * samples * samples * samples < triangles.items) {
05827     samples++;
05828   }
05829   triblocks = (triangles.maxitems + TRIPERBLOCK - 1) / TRIPERBLOCK;
05830   samplesperblock = 1 + (samples / triblocks);
05831   sampleblocks = samples / samplesperblock;
05832   sampleblock = triangles.firstblock;
05833   sampletri.orient = 0;
05834   for (i = 0; i < sampleblocks; i++) {
05835     alignptr = (unsigned long) (sampleblock + 1);
05836     firsttri = (triangle *) (alignptr + (unsigned long) triangles.alignbytes
05837                           - (alignptr % (unsigned long) triangles.alignbytes));
05838     for (j = 0; j < samplesperblock; j++) {
05839       if (i == triblocks - 1) {
05840         samplenum = randomnation((int)
05841                                  (triangles.maxitems - (i * TRIPERBLOCK)));
05842       } else {
05843         samplenum = randomnation(TRIPERBLOCK);
05844       }
05845       sampletri.tri = (triangle *)
05846                       (firsttri + (samplenum * triangles.itemwords));
05847       if (sampletri.tri[3] != (triangle) NULL) {
05848         org(sampletri, torg);
05849         dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0])
05850              + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
05851         if (dist < searchdist) {
05852           triedgecopy(sampletri, *searchtri);
05853           searchdist = dist;
05854           if (verbose > 2) {
05855             printf("    Choosing triangle with origin (%.12g, %.12g).\n",
05856                    torg[0], torg[1]);
05857           }
05858         }
05859       }
05860     }
05861     sampleblock = (VOID **) *sampleblock;
05862   }
05863   /* Where are we? */
05864   org(*searchtri, torg);
05865   dest(*searchtri, tdest);
05866   /* Check the starting triangle's vertices. */
05867   if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
05868     return ONVERTEX;
05869   }
05870   if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
05871     lnextself(*searchtri);
05872     return ONVERTEX;
05873   }
05874   /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
05875   ahead = counterclockwise(torg, tdest, searchpoint);
05876   if (ahead < 0.0) {
05877     /* Turn around so that `searchpoint' is to the left of the */
05878     /*   edge specified by `searchtri'.                        */
05879     symself(*searchtri);
05880   } else if (ahead == 0.0) {
05881     /* Check if `searchpoint' is between `torg' and `tdest'. */
05882     if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0]))
05883         && ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
05884       return ONEDGE;
05885     }
05886   }
05887   return preciselocate(searchpoint, searchtri);
05888 }
05889 
05890 /**                                                                         **/
05891 /**                                                                         **/
05892 /********* Point location routines end here                          *********/
05893 
05894 /********* Mesh transformation routines begin here                   *********/
05895 /**                                                                         **/
05896 /**                                                                         **/
05897 
05898 /*****************************************************************************/
05899 /*                                                                           */
05900 /*  insertshelle()   Create a new shell edge and insert it between two       */
05901 /*                   triangles.                                              */
05902 /*                                                                           */
05903 /*  The new shell edge is inserted at the edge described by the handle       */
05904 /*  `tri'.  Its vertices are properly initialized.  The marker `shellemark'  */
05905 /*  is applied to the shell edge and, if appropriate, its vertices.          */
05906 /*                                                                           */
05907 /*****************************************************************************/
05908 
05909 void insertshelle(tri, shellemark)
05910 struct triedge *tri;          /* Edge at which to insert the new shell edge. */
05911 int shellemark;                            /* Marker for the new shell edge. */
05912 {
05913   struct triedge oppotri;
05914   struct edge newshelle;
05915   point triorg, tridest;
05916   triangle ptr;                         /* Temporary variable used by sym(). */
05917   shelle sptr;                      /* Temporary variable used by tspivot(). */
05918 
05919   /* Mark points if possible. */
05920   org(*tri, triorg);
05921   dest(*tri, tridest);
05922   if (pointmark(triorg) == 0) {
05923     setpointmark(triorg, shellemark);
05924   }
05925   if (pointmark(tridest) == 0) {
05926     setpointmark(tridest, shellemark);
05927   }
05928   /* Check if there's already a shell edge here. */
05929   tspivot(*tri, newshelle);
05930   if (newshelle.sh == dummysh) {
05931     /* Make new shell edge and initialize its vertices. */
05932     makeshelle(&newshelle);
05933     setsorg(newshelle, tridest);
05934     setsdest(newshelle, triorg);
05935     /* Bond new shell edge to the two triangles it is sandwiched between. */
05936     /*   Note that the facing triangle `oppotri' might be equal to        */
05937     /*   `dummytri' (outer space), but the new shell edge is bonded to it */
05938     /*   all the same.                                                    */
05939     tsbond(*tri, newshelle);
05940     sym(*tri, oppotri);
05941     ssymself(newshelle);
05942     tsbond(oppotri, newshelle);
05943     setmark(newshelle, shellemark);
05944     if (verbose > 2) {
05945       printf("  Inserting new ");
05946       printshelle(&newshelle);
05947     }
05948   } else {
05949     if (mark(newshelle) == 0) {
05950       setmark(newshelle, shellemark);
05951     }
05952   }
05953 }
05954 
05955 /*****************************************************************************/
05956 /*                                                                           */
05957 /*  Terminology                                                              */
05958 /*                                                                           */
05959 /*  A "local transformation" replaces a small set of triangles with another  */
05960 /*  set of triangles.  This may or may not involve inserting or deleting a   */
05961 /*  point.                                                                   */
05962 /*                                                                           */
05963 /*  The term "casing" is used to describe the set of triangles that are      */
05964 /*  attached to the triangles being transformed, but are not transformed     */
05965 /*  themselves.  Think of the casing as a fixed hollow structure inside      */
05966 /*  which all the action happens.  A "casing" is only defined relative to    */
05967 /*  a single transformation; each occurrence of a transformation will        */
05968 /*  involve a different casing.                                              */
05969 /*                                                                           */
05970 /*  A "shell" is similar to a "casing".  The term "shell" describes the set  */
05971 /*  of shell edges (if any) that are attached to the triangles being         */
05972 /*  transformed.  However, I sometimes use "shell" to refer to a single      */
05973 /*  shell edge, so don't get confused.                                       */
05974 /*                                                                           */
05975 /*****************************************************************************/
05976 
05977 /*****************************************************************************/
05978 /*                                                                           */
05979 /*  flip()   Transform two triangles to two different triangles by flipping  */
05980 /*           an edge within a quadrilateral.                                 */
05981 /*                                                                           */
05982 /*  Imagine the original triangles, abc and bad, oriented so that the        */
05983 /*  shared edge ab lies in a horizontal plane, with the point b on the left  */
05984 /*  and the point a on the right.  The point c lies below the edge, and the  */
05985 /*  point d lies above the edge.  The `flipedge' handle holds the edge ab    */
05986 /*  of triangle abc, and is directed left, from vertex a to vertex b.        */
05987 /*                                                                           */
05988 /*  The triangles abc and bad are deleted and replaced by the triangles cdb  */
05989 /*  and dca.  The triangles that represent abc and bad are NOT deallocated;  */
05990 /*  they are reused for dca and cdb, respectively.  Hence, any handles that  */
05991 /*  may have held the original triangles are still valid, although not       */
05992 /*  directed as they were before.                                            */
05993 /*                                                                           */
05994 /*  Upon completion of this routine, the `flipedge' handle holds the edge    */
05995 /*  dc of triangle dca, and is directed down, from vertex d to vertex c.     */
05996 /*  (Hence, the two triangles have rotated counterclockwise.)                */
05997 /*                                                                           */
05998 /*  WARNING:  This transformation is geometrically valid only if the         */
05999 /*  quadrilateral adbc is convex.  Furthermore, this transformation is       */
06000 /*  valid only if there is not a shell edge between the triangles abc and    */
06001 /*  bad.  This routine does not check either of these preconditions, and     */
06002 /*  it is the responsibility of the calling routine to ensure that they are  */
06003 /*  met.  If they are not, the streets shall be filled with wailing and      */
06004 /*  gnashing of teeth.                                                       */
06005 /*                                                                           */
06006 /*****************************************************************************/
06007 
06008 void flip(flipedge)
06009 struct triedge *flipedge;                    /* Handle for the triangle abc. */
06010 {
06011   struct triedge botleft, botright;
06012   struct triedge topleft, topright;
06013   struct triedge top;
06014   struct triedge botlcasing, botrcasing;
06015   struct triedge toplcasing, toprcasing;
06016   struct edge botlshelle, botrshelle;
06017   struct edge toplshelle, toprshelle;
06018   point leftpoint, rightpoint, botpoint;
06019   point farpoint;
06020   triangle ptr;                         /* Temporary variable used by sym(). */
06021   shelle sptr;                      /* Temporary variable used by tspivot(). */
06022 
06023   /* Identify the vertices of the quadrilateral. */
06024   org(*flipedge, rightpoint);
06025   dest(*flipedge, leftpoint);
06026   apex(*flipedge, botpoint);
06027   sym(*flipedge, top);
06028 #ifdef SELF_CHECK
06029   if (top.tri == dummytri) {
06030     printf("Internal error in flip():  Attempt to flip on boundary.\n");
06031     lnextself(*flipedge);
06032     return;
06033   }
06034   if (checksegments) {
06035     tspivot(*flipedge, toplshelle);
06036     if (toplshelle.sh != dummysh) {
06037       printf("Internal error in flip():  Attempt to flip a segment.\n");
06038       lnextself(*flipedge);
06039       return;
06040     }
06041   }
06042 #endif /* SELF_CHECK */
06043   apex(top, farpoint);
06044 
06045   /* Identify the casing of the quadrilateral. */
06046   lprev(top, topleft);
06047   sym(topleft, toplcasing);
06048   lnext(top, topright);
06049   sym(topright, toprcasing);
06050   lnext(*flipedge, botleft);
06051   sym(botleft, botlcasing);
06052   lprev(*flipedge, botright);
06053   sym(botright, botrcasing);
06054   /* Rotate the quadrilateral one-quarter turn counterclockwise. */
06055   bond(topleft, botlcasing);
06056   bond(botleft, botrcasing);
06057   bond(botright, toprcasing);
06058   bond(topright, toplcasing);
06059 
06060   if (checksegments) {
06061     /* Check for shell edges and rebond them to the quadrilateral. */
06062     tspivot(topleft, toplshelle);
06063     tspivot(botleft, botlshelle);
06064     tspivot(botright, botrshelle);
06065     tspivot(topright, toprshelle);
06066     if (toplshelle.sh == dummysh) {
06067       tsdissolve(topright);
06068     } else {
06069       tsbond(topright, toplshelle);
06070     }
06071     if (botlshelle.sh == dummysh) {
06072       tsdissolve(topleft);
06073     } else {
06074       tsbond(topleft, botlshelle);
06075     }
06076     if (botrshelle.sh == dummysh) {
06077       tsdissolve(botleft);
06078     } else {
06079       tsbond(botleft, botrshelle);
06080     }
06081     if (toprshelle.sh == dummysh) {
06082       tsdissolve(botright);
06083     } else {
06084       tsbond(botright, toprshelle);
06085     }
06086   }
06087 
06088   /* New point assignments for the rotated quadrilateral. */
06089   setorg(*flipedge, farpoint);
06090   setdest(*flipedge, botpoint);
06091   setapex(*flipedge, rightpoint);
06092   setorg(top, botpoint);
06093   setdest(top, farpoint);
06094   setapex(top, leftpoint);
06095   if (verbose > 2) {
06096     printf("  Edge flip results in left ");
06097     lnextself(topleft);
06098     printtriangle(&topleft);
06099     printf("  and right ");
06100     printtriangle(flipedge);
06101   }
06102 }
06103 
06104 /*****************************************************************************/
06105 /*                                                                           */
06106 /*  insertsite()   Insert a vertex into a Delaunay triangulation,            */
06107 /*                 performing flips as necessary to maintain the Delaunay    */
06108 /*                 property.                                                 */
06109 /*                                                                           */
06110 /*  The point `insertpoint' is located.  If `searchtri.tri' is not NULL,     */
06111 /*  the search for the containing triangle begins from `searchtri'.  If      */
06112 /*  `searchtri.tri' is NULL, a full point location procedure is called.      */
06113 /*  If `insertpoint' is found inside a triangle, the triangle is split into  */
06114 /*  three; if `insertpoint' lies on an edge, the edge is split in two,       */
06115 /*  thereby splitting the two adjacent triangles into four.  Edge flips are  */
06116 /*  used to restore the Delaunay property.  If `insertpoint' lies on an      */
06117 /*  existing vertex, no action is taken, and the value DUPLICATEPOINT is     */
06118 /*  returned.  On return, `searchtri' is set to a handle whose origin is the */
06119 /*  existing vertex.                                                         */
06120 /*                                                                           */
06121 /*  Normally, the parameter `splitedge' is set to NULL, implying that no     */
06122 /*  segment should be split.  In this case, if `insertpoint' is found to     */
06123 /*  lie on a segment, no action is taken, and the value VIOLATINGPOINT is    */
06124 /*  returned.  On return, `searchtri' is set to a handle whose primary edge  */
06125 /*  is the violated segment.                                                 */
06126 /*                                                                           */
06127 /*  If the calling routine wishes to split a segment by inserting a point in */
06128 /*  it, the parameter `splitedge' should be that segment.  In this case,     */
06129 /*  `searchtri' MUST be the triangle handle reached by pivoting from that    */
06130 /*  segment; no point location is done.                                      */
06131 /*                                                                           */
06132 /*  `segmentflaws' and `triflaws' are flags that indicate whether or not     */
06133 /*  there should be checks for the creation of encroached segments or bad    */
06134 /*  quality faces.  If a newly inserted point encroaches upon segments,      */
06135 /*  these segments are added to the list of segments to be split if          */
06136 /*  `segmentflaws' is set.  If bad triangles are created, these are added    */
06137 /*  to the queue if `triflaws' is set.                                       */
06138 /*                                                                           */
06139 /*  If a duplicate point or violated segment does not prevent the point      */
06140 /*  from being inserted, the return value will be ENCROACHINGPOINT if the    */
06141 /*  point encroaches upon a segment (and checking is enabled), or            */
06142 /*  SUCCESSFULPOINT otherwise.  In either case, `searchtri' is set to a      */
06143 /*  handle whose origin is the newly inserted vertex.                        */
06144 /*                                                                           */
06145 /*  insertsite() does not use flip() for reasons of speed; some              */
06146 /*  information can be reused from edge flip to edge flip, like the          */
06147 /*  locations of shell edges.                                                */
06148 /*                                                                           */
06149 /*****************************************************************************/
06150 
06151 enum insertsiteresult insertsite(insertpoint, searchtri, splitedge,
06152                                  segmentflaws, triflaws)
06153 point insertpoint;
06154 struct triedge *searchtri;
06155 struct edge *splitedge;
06156 int segmentflaws;
06157 int triflaws;
06158 {
06159   struct triedge horiz;
06160   struct triedge top;
06161   struct triedge botleft, botright;
06162   struct triedge topleft, topright;
06163   struct triedge newbotleft, newbotright;
06164   struct triedge newtopright;
06165   struct triedge botlcasing, botrcasing;
06166   struct triedge toplcasing, toprcasing;
06167   struct triedge testtri;
06168   struct edge botlshelle, botrshelle;
06169   struct edge toplshelle, toprshelle;
06170   struct edge brokenshelle;
06171   struct edge checkshelle;
06172   struct edge rightedge;
06173   struct edge newedge;
06174   struct edge *encroached;
06175   point first;
06176   point leftpoint, rightpoint, botpoint, toppoint, farpoint;
06177   REAL attrib;
06178   REAL area;
06179   enum insertsiteresult success;
06180   enum locateresult intersect;
06181   int doflip;
06182   int mirrorflag;
06183   int i;
06184   triangle ptr;                         /* Temporary variable used by sym(). */
06185   shelle sptr;         /* Temporary variable used by spivot() and tspivot(). */
06186 
06187   if (verbose > 1) {
06188     printf("  Inserting (%.12g, %.12g).\n", insertpoint[0], insertpoint[1]);
06189   }
06190   if (splitedge == (struct edge *) NULL) {
06191     /* Find the location of the point to be inserted.  Check if a good */
06192     /*   starting triangle has already been provided by the caller.    */
06193     if (searchtri->tri == (triangle *) NULL) {
06194       /* Find a boundary triangle. */
06195       horiz.tri = dummytri;
06196       horiz.orient = 0;
06197       symself(horiz);
06198       /* Search for a triangle containing `insertpoint'. */
06199       intersect = locate(insertpoint, &horiz);
06200     } else {
06201       /* Start searching from the triangle provided by the caller. */
06202       triedgecopy(*searchtri, horiz);
06203       intersect = preciselocate(insertpoint, &horiz);
06204     }
06205   } else {
06206     /* The calling routine provides the edge in which the point is inserted. */
06207     triedgecopy(*searchtri, horiz);
06208     intersect = ONEDGE;
06209   }
06210   if (intersect == ONVERTEX) {
06211     /* There's already a vertex there.  Return in `searchtri' a triangle */
06212     /*   whose origin is the existing vertex.                            */
06213     triedgecopy(horiz, *searchtri);
06214     triedgecopy(horiz, recenttri);
06215     return DUPLICATEPOINT;
06216   }
06217   if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
06218     /* The vertex falls on an edge or boundary. */
06219     if (checksegments && (splitedge == (struct edge *) NULL)) {
06220       /* Check whether the vertex falls on a shell edge. */
06221       tspivot(horiz, brokenshelle);
06222       if (brokenshelle.sh != dummysh) {
06223         /* The vertex falls on a shell edge. */
06224         if (segmentflaws) {
06225           if (nobisect == 0) {
06226             /* Add the shell edge to the list of encroached segments. */
06227             encroached = (struct edge *) poolalloc(&badsegments);
06228             shellecopy(brokenshelle, *encroached);
06229           } else if ((nobisect == 1) && (intersect == ONEDGE)) {
06230             /* This segment may be split only if it is an internal boundary. */
06231             sym(horiz, testtri);
06232             if (testtri.tri != dummytri) {
06233               /* Add the shell edge to the list of encroached segments. */
06234               encroached = (struct edge *) poolalloc(&badsegments);
06235               shellecopy(brokenshelle, *encroached);
06236             }
06237           }
06238         }
06239         /* Return a handle whose primary edge contains the point, */
06240         /*   which has not been inserted.                         */
06241         triedgecopy(horiz, *searchtri);
06242         triedgecopy(horiz, recenttri);
06243         return VIOLATINGPOINT;
06244       }
06245     }
06246     /* Insert the point on an edge, dividing one triangle into two (if */
06247     /*   the edge lies on a boundary) or two triangles into four.      */
06248     lprev(horiz, botright);
06249     sym(botright, botrcasing);
06250     sym(horiz, topright);
06251     /* Is there a second triangle?  (Or does this edge lie on a boundary?) */
06252     mirrorflag = topright.tri != dummytri;
06253     if (mirrorflag) {
06254       lnextself(topright);
06255       sym(topright, toprcasing);
06256       maketriangle(&newtopright);
06257     } else {
06258       /* Splitting the boundary edge increases the number of boundary edges. */
06259       hullsize++;
06260     }
06261     maketriangle(&newbotright);
06262 
06263     /* Set the vertices of changed and new triangles. */
06264     org(horiz, rightpoint);
06265     dest(horiz, leftpoint);
06266     apex(horiz, botpoint);
06267     setorg(newbotright, botpoint);
06268     setdest(newbotright, rightpoint);
06269     setapex(newbotright, insertpoint);
06270     setorg(horiz, insertpoint);
06271     for (i = 0; i < eextras; i++) {
06272       /* Set the element attributes of a new triangle. */
06273       setelemattribute(newbotright, i, elemattribute(botright, i));
06274     }
06275     if (vararea) {
06276       /* Set the area constraint of a new triangle. */
06277       setareabound(newbotright, areabound(botright));
06278     }
06279     if (mirrorflag) {
06280       dest(topright, toppoint);
06281       setorg(newtopright, rightpoint);
06282       setdest(newtopright, toppoint);
06283       setapex(newtopright, insertpoint);
06284       setorg(topright, insertpoint);
06285       for (i = 0; i < eextras; i++) {
06286         /* Set the element attributes of another new triangle. */
06287         setelemattribute(newtopright, i, elemattribute(topright, i));
06288       }
06289       if (vararea) {
06290         /* Set the area constraint of another new triangle. */
06291         setareabound(newtopright, areabound(topright));
06292       }
06293     }
06294 
06295     /* There may be shell edges that need to be bonded */
06296     /*   to the new triangle(s).                       */
06297     if (checksegments) {
06298       tspivot(botright, botrshelle);
06299       if (botrshelle.sh != dummysh) {
06300         tsdissolve(botright);
06301         tsbond(newbotright, botrshelle);
06302       }
06303       if (mirrorflag) {
06304         tspivot(topright, toprshelle);
06305         if (toprshelle.sh != dummysh) {
06306           tsdissolve(topright);
06307           tsbond(newtopright, toprshelle);
06308         }
06309       }
06310     }
06311 
06312     /* Bond the new triangle(s) to the surrounding triangles. */
06313     bond(newbotright, botrcasing);
06314     lprevself(newbotright);
06315     bond(newbotright, botright);
06316     lprevself(newbotright);
06317     if (mirrorflag) {
06318       bond(newtopright, toprcasing);
06319       lnextself(newtopright);
06320       bond(newtopright, topright);
06321       lnextself(newtopright);
06322       bond(newtopright, newbotright);
06323     }
06324 
06325     if (splitedge != (struct edge *) NULL) {
06326       /* Split the shell edge into two. */
06327       setsdest(*splitedge, insertpoint);
06328       ssymself(*splitedge);
06329       spivot(*splitedge, rightedge);
06330       insertshelle(&newbotright, mark(*splitedge));
06331       tspivot(newbotright, newedge);
06332       sbond(*splitedge, newedge);
06333       ssymself(newedge);
06334       sbond(newedge, rightedge);
06335       ssymself(*splitedge);
06336     }
06337 
06338 #ifdef SELF_CHECK
06339     if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) {
06340       printf("Internal error in insertsite():\n");
06341       printf("  Clockwise triangle prior to edge point insertion (bottom).\n");
06342     }
06343     if (mirrorflag) {
06344       if (counterclockwise(leftpoint, rightpoint, toppoint) < 0.0) {
06345         printf("Internal error in insertsite():\n");
06346         printf("  Clockwise triangle prior to edge point insertion (top).\n");
06347       }
06348       if (counterclockwise(rightpoint, toppoint, insertpoint) < 0.0) {
06349         printf("Internal error in insertsite():\n");
06350         printf("  Clockwise triangle after edge point insertion (top right).\n"
06351                );
06352       }
06353       if (counterclockwise(toppoint, leftpoint, insertpoint) < 0.0) {
06354         printf("Internal error in insertsite():\n");
06355         printf("  Clockwise triangle after edge point insertion (top left).\n"
06356                );
06357       }
06358     }
06359     if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) {
06360       printf("Internal error in insertsite():\n");
06361       printf("  Clockwise triangle after edge point insertion (bottom left).\n"
06362              );
06363     }
06364     if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
06365       printf("Internal error in insertsite():\n");
06366       printf(
06367         "  Clockwise triangle after edge point insertion (bottom right).\n");
06368     }
06369 #endif /* SELF_CHECK */
06370     if (verbose > 2) {
06371       printf("  Updating bottom left ");
06372       printtriangle(&botright);
06373       if (mirrorflag) {
06374         printf("  Updating top left ");
06375         printtriangle(&topright);
06376         printf("  Creating top right ");
06377         printtriangle(&newtopright);
06378       }
06379       printf("  Creating bottom right ");
06380       printtriangle(&newbotright);
06381     }
06382 
06383     /* Position `horiz' on the first edge to check for */
06384     /*   the Delaunay property.                        */
06385     lnextself(horiz);
06386   } else {
06387     /* Insert the point in a triangle, splitting it into three. */
06388     lnext(horiz, botleft);
06389     lprev(horiz, botright);
06390     sym(botleft, botlcasing);
06391     sym(botright, botrcasing);
06392     maketriangle(&newbotleft);
06393     maketriangle(&newbotright);
06394 
06395     /* Set the vertices of changed and new triangles. */
06396     org(horiz, rightpoint);
06397     dest(horiz, leftpoint);
06398     apex(horiz, botpoint);
06399     setorg(newbotleft, leftpoint);
06400     setdest(newbotleft, botpoint);
06401     setapex(newbotleft, insertpoint);
06402     setorg(newbotright, botpoint);
06403     setdest(newbotright, rightpoint);
06404     setapex(newbotright, insertpoint);
06405     setapex(horiz, insertpoint);
06406     for (i = 0; i < eextras; i++) {
06407       /* Set the element attributes of the new triangles. */
06408       attrib = elemattribute(horiz, i);
06409       setelemattribute(newbotleft, i, attrib);
06410       setelemattribute(newbotright, i, attrib);
06411     }
06412     if (vararea) {
06413       /* Set the area constraint of the new triangles. */
06414       area = areabound(horiz);
06415       setareabound(newbotleft, area);
06416       setareabound(newbotright, area);
06417     }
06418 
06419     /* There may be shell edges that need to be bonded */
06420     /*   to the new triangles.                         */
06421     if (checksegments) {
06422       tspivot(botleft, botlshelle);
06423       if (botlshelle.sh != dummysh) {
06424         tsdissolve(botleft);
06425         tsbond(newbotleft, botlshelle);
06426       }
06427       tspivot(botright, botrshelle);
06428       if (botrshelle.sh != dummysh) {
06429         tsdissolve(botright);
06430         tsbond(newbotright, botrshelle);
06431       }
06432     }
06433 
06434     /* Bond the new triangles to the surrounding triangles. */
06435     bond(newbotleft, botlcasing);
06436     bond(newbotright, botrcasing);
06437     lnextself(newbotleft);
06438     lprevself(newbotright);
06439     bond(newbotleft, newbotright);
06440     lnextself(newbotleft);
06441     bond(botleft, newbotleft);
06442     lprevself(newbotright);
06443     bond(botright, newbotright);
06444 
06445 #ifdef SELF_CHECK
06446     if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) {
06447       printf("Internal error in insertsite():\n");
06448       printf("  Clockwise triangle prior to point insertion.\n");
06449     }
06450     if (counterclockwise(rightpoint, leftpoint, insertpoint) < 0.0) {
06451       printf("Internal error in insertsite():\n");
06452       printf("  Clockwise triangle after point insertion (top).\n");
06453     }
06454     if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) {
06455       printf("Internal error in insertsite():\n");
06456       printf("  Clockwise triangle after point insertion (left).\n");
06457     }
06458     if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) {
06459       printf("Internal error in insertsite():\n");
06460       printf("  Clockwise triangle after point insertion (right).\n");
06461     }
06462 #endif /* SELF_CHECK */
06463     if (verbose > 2) {
06464       printf("  Updating top ");
06465       printtriangle(&horiz);
06466       printf("  Creating left ");
06467       printtriangle(&newbotleft);
06468       printf("  Creating right ");
06469       printtriangle(&newbotright);
06470     }
06471   }
06472 
06473   /* The insertion is successful by default, unless an encroached */
06474   /*   edge is found.                                             */
06475   success = SUCCESSFULPOINT;
06476   /* Circle around the newly inserted vertex, checking each edge opposite */
06477   /*   it for the Delaunay property.  Non-Delaunay edges are flipped.     */
06478   /*   `horiz' is always the edge being checked.  `first' marks where to  */
06479   /*   stop circling.                                                     */
06480   org(horiz, first);
06481   rightpoint = first;
06482   dest(horiz, leftpoint);
06483   /* Circle until finished. */
06484   while (1) {
06485     /* By default, the edge will be flipped. */
06486     doflip = 1;
06487     if (checksegments) {
06488       /* Check for a segment, which cannot be flipped. */
06489       tspivot(horiz, checkshelle);
06490       if (checkshelle.sh != dummysh) {
06491         /* The edge is a segment and cannot be flipped. */
06492         doflip = 0;
06493 #ifndef CDT_ONLY
06494         if (segmentflaws) {
06495           /* Does the new point encroach upon this segment? */
06496           if (checkedge4encroach(&checkshelle)) {
06497             success = ENCROACHINGPOINT;
06498           }
06499         }
06500 #endif /* not CDT_ONLY */
06501       }
06502     }
06503     if (doflip) {
06504       /* Check if the edge is a boundary edge. */
06505       sym(horiz, top);
06506       if (top.tri == dummytri) {
06507         /* The edge is a boundary edge and cannot be flipped. */
06508         doflip = 0;
06509       } else {
06510         /* Find the point on the other side of the edge. */
06511         apex(top, farpoint);
06512         /* In the incremental Delaunay triangulation algorithm, any of    */
06513         /*   `leftpoint', `rightpoint', and `farpoint' could be vertices  */
06514         /*   of the triangular bounding box.  These vertices must be      */
06515         /*   treated as if they are infinitely distant, even though their */
06516         /*   "coordinates" are not.                                       */
06517         if ((leftpoint == infpoint1) || (leftpoint == infpoint2)
06518                    || (leftpoint == infpoint3)) {
06519           /* `leftpoint' is infinitely distant.  Check the convexity of */
06520           /*   the boundary of the triangulation.  'farpoint' might be  */
06521           /*   infinite as well, but trust me, this same condition      */
06522           /*   should be applied.                                       */
06523           doflip = counterclockwise(insertpoint, rightpoint, farpoint) > 0.0;
06524         } else if ((rightpoint == infpoint1) || (rightpoint == infpoint2)
06525                    || (rightpoint == infpoint3)) {
06526           /* `rightpoint' is infinitely distant.  Check the convexity of */
06527           /*   the boundary of the triangulation.  'farpoint' might be  */
06528           /*   infinite as well, but trust me, this same condition      */
06529           /*   should be applied.                                       */
06530           doflip = counterclockwise(farpoint, leftpoint, insertpoint) > 0.0;
06531         } else if ((farpoint == infpoint1) || (farpoint == infpoint2)
06532             || (farpoint == infpoint3)) {
06533           /* `farpoint' is infinitely distant and cannot be inside */
06534           /*   the circumcircle of the triangle `horiz'.           */
06535           doflip = 0;
06536         } else {
06537           /* Test whether the edge is locally Delaunay. */
06538           doflip = incircle(leftpoint, insertpoint, rightpoint, farpoint)
06539                    > 0.0;
06540         }
06541         if (doflip) {
06542           /* We made it!  Flip the edge `horiz' by rotating its containing */
06543           /*   quadrilateral (the two triangles adjacent to `horiz').      */
06544           /* Identify the casing of the quadrilateral. */
06545           lprev(top, topleft);
06546           sym(topleft, toplcasing);
06547           lnext(top, topright);
06548           sym(topright, toprcasing);
06549           lnext(horiz, botleft);
06550           sym(botleft, botlcasing);
06551           lprev(horiz, botright);
06552           sym(botright, botrcasing);
06553           /* Rotate the quadrilateral one-quarter turn counterclockwise. */
06554           bond(topleft, botlcasing);
06555           bond(botleft, botrcasing);
06556           bond(botright, toprcasing);
06557           bond(topright, toplcasing);
06558           if (checksegments) {
06559             /* Check for shell edges and rebond them to the quadrilateral. */
06560             tspivot(topleft, toplshelle);
06561             tspivot(botleft, botlshelle);
06562             tspivot(botright, botrshelle);
06563             tspivot(topright, toprshelle);
06564             if (toplshelle.sh == dummysh) {
06565               tsdissolve(topright);
06566             } else {
06567               tsbond(topright, toplshelle);
06568             }
06569             if (botlshelle.sh == dummysh) {
06570               tsdissolve(topleft);
06571             } else {
06572               tsbond(topleft, botlshelle);
06573             }
06574             if (botrshelle.sh == dummysh) {
06575               tsdissolve(botleft);
06576             } else {
06577               tsbond(botleft, botrshelle);
06578             }
06579             if (toprshelle.sh == dummysh) {
06580               tsdissolve(botright);
06581             } else {
06582               tsbond(botright, toprshelle);
06583             }
06584           }
06585           /* New point assignments for the rotated quadrilateral. */
06586           setorg(horiz, farpoint);
06587           setdest(horiz, insertpoint);
06588           setapex(horiz, rightpoint);
06589           setorg(top, insertpoint);
06590           setdest(top, farpoint);
06591           setapex(top, leftpoint);
06592           for (i = 0; i < eextras; i++) {
06593             /* Take the average of the two triangles' attributes. */
06594             attrib = 0.5 * (elemattribute(top, i) + elemattribute(horiz, i));
06595             setelemattribute(top, i, attrib);
06596             setelemattribute(horiz, i, attrib);
06597           }
06598           if (vararea) {
06599             if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
06600               area = -1.0;
06601             } else {
06602               /* Take the average of the two triangles' area constraints.    */
06603               /*   This prevents small area constraints from migrating a     */
06604               /*   long, long way from their original location due to flips. */
06605               area = 0.5 * (areabound(top) + areabound(horiz));
06606             }
06607             setareabound(top, area);
06608             setareabound(horiz, area);
06609           }
06610 #ifdef SELF_CHECK
06611           if (insertpoint != (point) NULL) {
06612             if (counterclockwise(leftpoint, insertpoint, rightpoint) < 0.0) {
06613               printf("Internal error in insertsite():\n");
06614               printf("  Clockwise triangle prior to edge flip (bottom).\n");
06615             }
06616             /* The following test has been removed because constrainededge() */
06617             /*   sometimes generates inverted triangles that insertsite()    */
06618             /*   removes.                                                    */
06619 /*
06620             if (counterclockwise(rightpoint, farpoint, leftpoint) < 0.0) {
06621               printf("Internal error in insertsite():\n");
06622               printf("  Clockwise triangle prior to edge flip (top).\n");
06623             }
06624 */
06625             if (counterclockwise(farpoint, leftpoint, insertpoint) < 0.0) {
06626               printf("Internal error in insertsite():\n");
06627               printf("  Clockwise triangle after edge flip (left).\n");
06628             }
06629             if (counterclockwise(insertpoint, rightpoint, farpoint) < 0.0) {
06630               printf("Internal error in insertsite():\n");
06631               printf("  Clockwise triangle after edge flip (right).\n");
06632             }
06633           }
06634 #endif /* SELF_CHECK */
06635           if (verbose > 2) {
06636             printf("  Edge flip results in left ");
06637             lnextself(topleft);
06638             printtriangle(&topleft);
06639             printf("  and right ");
06640             printtriangle(&horiz);
06641           }
06642           /* On the next iterations, consider the two edges that were  */
06643           /*   exposed (this is, are now visible to the newly inserted */
06644           /*   point) by the edge flip.                                */
06645           lprevself(horiz);
06646           leftpoint = farpoint;
06647         }
06648       }
06649     }
06650     if (!doflip) {
06651       /* The handle `horiz' is accepted as locally Delaunay. */
06652 #ifndef CDT_ONLY
06653       if (triflaws) {
06654         /* Check the triangle `horiz' for quality. */
06655         testtriangle(&horiz);
06656       }
06657 #endif /* not CDT_ONLY */
06658       /* Look for the next edge around the newly inserted point. */
06659       lnextself(horiz);
06660       sym(horiz, testtri);
06661       /* Check for finishing a complete revolution about the new point, or */
06662       /*   falling off the edge of the triangulation.  The latter will     */
06663       /*   happen when a point is inserted at a boundary.                  */
06664       if ((leftpoint == first) || (testtri.tri == dummytri)) {
06665         /* We're done.  Return a triangle whose origin is the new point. */
06666         lnext(horiz, *searchtri);
06667         lnext(horiz, recenttri);
06668         return success;
06669       }
06670       /* Finish finding the next edge around the newly inserted point. */
06671       lnext(testtri, horiz);
06672       rightpoint = leftpoint;
06673       dest(horiz, leftpoint);
06674     }
06675   }
06676 }
06677 
06678 /*****************************************************************************/
06679 /*                                                                           */
06680 /*  triangulatepolygon()   Find the Delaunay triangulation of a polygon that */
06681 /*                         has a certain "nice" shape.  This includes the    */
06682 /*                         polygons that result from deletion of a point or  */
06683 /*                         insertion of a segment.                           */
06684 /*                                                                           */
06685 /*  This is a conceptually difficult routine.  The starting assumption is    */
06686 /*  that we have a polygon with n sides.  n - 1 of these sides are currently */
06687 /*  represented as edges in the mesh.  One side, called the "base", need not */
06688 /*  be.                                                                      */
06689 /*                                                                           */
06690 /*  Inside the polygon is a structure I call a "fan", consisting of n - 1    */
06691 /*  triangles that share a common origin.  For each of these triangles, the  */
06692 /*  edge opposite the origin is one of the sides of the polygon.  The        */
06693 /*  primary edge of each triangle is the edge directed from the origin to    */
06694 /*  the destination; note that this is not the same edge that is a side of   */
06695 /*  the polygon.  `firstedge' is the primary edge of the first triangle.     */
06696 /*  From there, the triangles follow in counterclockwise order about the     */
06697 /*  polygon, until `lastedge', the primary edge of the last triangle.        */
06698 /*  `firstedge' and `lastedge' are probably connected to other triangles     */
06699 /*  beyond the extremes of the fan, but their identity is not important, as  */
06700 /*  long as the fan remains connected to them.                               */
06701 /*                                                                           */
06702 /*  Imagine the polygon oriented so that its base is at the bottom.  This    */
06703 /*  puts `firstedge' on the far right, and `lastedge' on the far left.       */
06704 /*  The right vertex of the base is the destination of `firstedge', and the  */
06705 /*  left vertex of the base is the apex of `lastedge'.                       */
06706 /*                                                                           */
06707 /*  The challenge now is to find the right sequence of edge flips to         */
06708 /*  transform the fan into a Delaunay triangulation of the polygon.  Each    */
06709 /*  edge flip effectively removes one triangle from the fan, committing it   */
06710 /*  to the polygon.  The resulting polygon has one fewer edge.  If `doflip'  */
06711 /*  is set, the final flip will be performed, resulting in a fan of one      */
06712 /*  (useless?) triangle.  If `doflip' is not set, the final flip is not      */
06713 /*  performed, resulting in a fan of two triangles, and an unfinished        */
06714 /*  triangular polygon that is not yet filled out with a single triangle.    */
06715 /*  On completion of the routine, `lastedge' is the last remaining triangle, */
06716 /*  or the leftmost of the last two.                                         */
06717 /*                                                                           */
06718 /*  Although the flips are performed in the order described above, the       */
06719 /*  decisions about what flips to perform are made in precisely the reverse  */
06720 /*  order.  The recursive triangulatepolygon() procedure makes a decision,   */
06721 /*  uses up to two recursive calls to triangulate the "subproblems"          */
06722 /*  (polygons with fewer edges), and then performs an edge flip.             */
06723 /*                                                                           */
06724 /*  The "decision" it makes is which vertex of the polygon should be         */
06725 /*  connected to the base.  This decision is made by testing every possible  */
06726 /*  vertex.  Once the best vertex is found, the two edges that connect this  */
06727 /*  vertex to the base become the bases for two smaller polygons.  These     */
06728 /*  are triangulated recursively.  Unfortunately, this approach can take     */
06729 /*  O(n^2) time not only in the worst case, but in many common cases.  It's  */
06730 /*  rarely a big deal for point deletion, where n is rarely larger than ten, */
06731 /*  but it could be a big deal for segment insertion, especially if there's  */
06732 /*  a lot of long segments that each cut many triangles.  I ought to code    */
06733 /*  a faster algorithm some time.                                            */
06734 /*                                                                           */
06735 /*  The `edgecount' parameter is the number of sides of the polygon,         */
06736 /*  including its base.  `triflaws' is a flag that determines whether the    */
06737 /*  new triangles should be tested for quality, and enqueued if they are     */
06738 /*  bad.                                                                     */
06739 /*                                                                           */
06740 /*****************************************************************************/
06741 
06742 void triangulatepolygon(firstedge, lastedge, edgecount, doflip, triflaws)
06743 struct triedge *firstedge;
06744 struct triedge *lastedge;
06745 int edgecount;
06746 int doflip;
06747 int triflaws;
06748 {
06749   struct triedge testtri;
06750   struct triedge besttri;
06751   struct triedge tempedge;
06752   point leftbasepoint, rightbasepoint;
06753   point testpoint;
06754   point bestpoint;
06755   int bestnumber;
06756   int i;
06757   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
06758 
06759   /* Identify the base vertices. */
06760   apex(*lastedge, leftbasepoint);
06761   dest(*firstedge, rightbasepoint);
06762   if (verbose > 2) {
06763     printf("  Triangulating interior polygon at edge\n");
06764     printf("    (%.12g, %.12g) (%.12g, %.12g)\n", leftbasepoint[0],
06765            leftbasepoint[1], rightbasepoint[0], rightbasepoint[1]);
06766   }
06767   /* Find the best vertex to connect the base to. */
06768   onext(*firstedge, besttri);
06769   dest(besttri, bestpoint);
06770   triedgecopy(besttri, testtri);
06771   bestnumber = 1;
06772   for (i = 2; i <= edgecount - 2; i++) {
06773     onextself(testtri);
06774     dest(testtri, testpoint);
06775     /* Is this a better vertex? */
06776     if (incircle(leftbasepoint, rightbasepoint, bestpoint, testpoint) > 0.0) {
06777       triedgecopy(testtri, besttri);
06778       bestpoint = testpoint;
06779       bestnumber = i;
06780     }
06781   }
06782   if (verbose > 2) {
06783     printf("    Connecting edge to (%.12g, %.12g)\n", bestpoint[0],
06784            bestpoint[1]);
06785   }
06786   if (bestnumber > 1) {
06787     /* Recursively triangulate the smaller polygon on the right. */
06788     oprev(besttri, tempedge);
06789     triangulatepolygon(firstedge, &tempedge, bestnumber + 1, 1, triflaws);
06790   }
06791   if (bestnumber < edgecount - 2) {
06792     /* Recursively triangulate the smaller polygon on the left. */
06793     sym(besttri, tempedge);
06794     triangulatepolygon(&besttri, lastedge, edgecount - bestnumber, 1,
06795                        triflaws);
06796     /* Find `besttri' again; it may have been lost to edge flips. */
06797     sym(tempedge, besttri);
06798   }
06799   if (doflip) {
06800     /* Do one final edge flip. */
06801     flip(&besttri);
06802 #ifndef CDT_ONLY
06803     if (triflaws) {
06804       /* Check the quality of the newly committed triangle. */
06805       sym(besttri, testtri);
06806       testtriangle(&testtri);
06807     }
06808 #endif /* not CDT_ONLY */
06809   }
06810   /* Return the base triangle. */
06811   triedgecopy(besttri, *lastedge);
06812 }
06813 
06814 /*****************************************************************************/
06815 /*                                                                           */
06816 /*  deletesite()   Delete a vertex from a Delaunay triangulation, ensuring   */
06817 /*                 that the triangulation remains Delaunay.                  */
06818 /*                                                                           */
06819 /*  The origin of `deltri' is deleted.  The union of the triangles adjacent  */
06820 /*  to this point is a polygon, for which the Delaunay triangulation is      */
06821 /*  found.  Two triangles are removed from the mesh.                         */
06822 /*                                                                           */
06823 /*  Only interior points that do not lie on segments (shell edges) or        */
06824 /*  boundaries may be deleted.                                               */
06825 /*                                                                           */
06826 /*****************************************************************************/
06827 
06828 #ifndef CDT_ONLY
06829 
06830 void deletesite(deltri)
06831 struct triedge *deltri;
06832 {
06833   struct triedge countingtri;
06834   struct triedge firstedge, lastedge;
06835   struct triedge deltriright;
06836   struct triedge lefttri, righttri;
06837   struct triedge leftcasing, rightcasing;
06838   struct edge leftshelle, rightshelle;
06839   point delpoint;
06840   point neworg;
06841   int edgecount;
06842   triangle ptr;   /* Temporary variable used by sym(), onext(), and oprev(). */
06843   shelle sptr;                      /* Temporary variable used by tspivot(). */
06844 
06845   org(*deltri, delpoint);
06846   if (verbose > 1) {
06847     printf("  Deleting (%.12g, %.12g).\n", delpoint[0], delpoint[1]);
06848   }
06849   pointdealloc(delpoint);
06850 
06851   /* Count the degree of the point being deleted. */
06852   onext(*deltri, countingtri);
06853   edgecount = 1;
06854   while (!triedgeequal(*deltri, countingtri)) {
06855 #ifdef SELF_CHECK
06856     if (countingtri.tri == dummytri) {
06857       printf("Internal error in deletesite():\n");
06858       printf("  Attempt to delete boundary point.\n");
06859       internalerror();
06860     }
06861 #endif /* SELF_CHECK */
06862     edgecount++;
06863     onextself(countingtri);
06864   }
06865 
06866 #ifdef SELF_CHECK
06867   if (edgecount < 3) {
06868     printf("Internal error in deletesite():\n  Point has degree %d.\n",
06869            edgecount);
06870     internalerror();
06871   }
06872 #endif /* SELF_CHECK */
06873   if (edgecount > 3) {
06874     /* Triangulate the polygon defined by the union of all triangles */
06875     /*   adjacent to the point being deleted.  Check the quality of  */
06876     /*   the resulting triangles.                                    */
06877     onext(*deltri, firstedge);
06878     oprev(*deltri, lastedge);
06879     triangulatepolygon(&firstedge, &lastedge, edgecount, 0, !nobisect);
06880   }
06881   /* Splice out two triangles. */
06882   lprev(*deltri, deltriright);
06883   dnext(*deltri, lefttri);
06884   sym(lefttri, leftcasing);
06885   oprev(deltriright, righttri);
06886   sym(righttri, rightcasing);
06887   bond(*deltri, leftcasing);
06888   bond(deltriright, rightcasing);
06889   tspivot(lefttri, leftshelle);
06890   if (leftshelle.sh != dummysh) {
06891     tsbond(*deltri, leftshelle);
06892   }
06893   tspivot(righttri, rightshelle);
06894   if (rightshelle.sh != dummysh) {
06895     tsbond(deltriright, rightshelle);
06896   }
06897 
06898   /* Set the new origin of `deltri' and check its quality. */
06899   org(lefttri, neworg);
06900   setorg(*deltri, neworg);
06901   if (!nobisect) {
06902     testtriangle(deltri);
06903   }
06904 
06905   /* Delete the two spliced-out triangles. */
06906   triangledealloc(lefttri.tri);
06907   triangledealloc(righttri.tri);
06908 }
06909 
06910 #endif /* not CDT_ONLY */
06911 
06912 /**                                                                         **/
06913 /**                                                                         **/
06914 /********* Mesh transformation routines end here                     *********/
06915 
06916 /********* Divide-and-conquer Delaunay triangulation begins here     *********/
06917 /**                                                                         **/
06918 /**                                                                         **/
06919 
06920 /*****************************************************************************/
06921 /*                                                                           */
06922 /*  The divide-and-conquer bounding box                                      */
06923 /*                                                                           */
06924 /*  I originally implemented the divide-and-conquer and incremental Delaunay */
06925 /*  triangulations using the edge-based data structure presented by Guibas   */
06926 /*  and Stolfi.  Switching to a triangle-based data structure doubled the    */
06927 /*  speed.  However, I had to think of a few extra tricks to maintain the    */
06928 /*  elegance of the original algorithms.                                     */
06929 /*                                                                           */
06930 /*  The "bounding box" used by my variant of the divide-and-conquer          */
06931 /*  algorithm uses one triangle for each edge of the convex hull of the      */
06932 /*  triangulation.  These bounding triangles all share a common apical       */
06933 /*  vertex, which is represented by NULL and which represents nothing.       */
06934 /*  The bounding triangles are linked in a circular fan about this NULL      */
06935 /*  vertex, and the edges on the convex hull of the triangulation appear     */
06936 /*  opposite the NULL vertex.  You might find it easiest to imagine that     */
06937 /*  the NULL vertex is a point in 3D space behind the center of the          */
06938 /*  triangulation, and that the bounding triangles form a sort of cone.      */
06939 /*                                                                           */
06940 /*  This bounding box makes it easy to represent degenerate cases.  For      */
06941 /*  instance, the triangulation of two vertices is a single edge.  This edge */
06942 /*  is represented by two bounding box triangles, one on each "side" of the  */
06943 /*  edge.  These triangles are also linked together in a fan about the NULL  */
06944 /*  vertex.                                                                  */
06945 /*                                                                           */
06946 /*  The bounding box also makes it easy to traverse the convex hull, as the  */
06947 /*  divide-and-conquer algorithm needs to do.                                */
06948 /*                                                                           */
06949 /*****************************************************************************/
06950 
06951 /*****************************************************************************/
06952 /*                                                                           */
06953 /*  pointsort()   Sort an array of points by x-coordinate, using the         */
06954 /*                y-coordinate as a secondary key.                           */
06955 /*                                                                           */
06956 /*  Uses quicksort.  Randomized O(n log n) time.  No, I did not make any of  */
06957 /*  the usual quicksort mistakes.                                            */
06958 /*                                                                           */
06959 /*****************************************************************************/
06960 
06961 void pointsort(sortarray, arraysize)
06962 point *sortarray;
06963 int arraysize;
06964 {
06965   int left, right;
06966   int pivot;
06967   REAL pivotx, pivoty;
06968   point temp;
06969 
06970   if (arraysize == 2) {
06971     /* Recursive base case. */
06972     if ((sortarray[0][0] > sortarray[1][0]) ||
06973         ((sortarray[0][0] == sortarray[1][0]) &&
06974          (sortarray[0][1] > sortarray[1][1]))) {
06975       temp = sortarray[1];
06976       sortarray[1] = sortarray[0];
06977       sortarray[0] = temp;
06978     }
06979     return;
06980   }
06981   /* Choose a random pivot to split the array. */
06982   pivot = (int) randomnation(arraysize);
06983   pivotx = sortarray[pivot][0];
06984   pivoty = sortarray[pivot][1];
06985   /* Split the array. */
06986   left = -1;
06987   right = arraysize;
06988   while (left < right) {
06989     /* Search for a point whose x-coordinate is too large for the left. */
06990     do {
06991       left++;
06992     } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
06993                                  ((sortarray[left][0] == pivotx) &&
06994                                   (sortarray[left][1] < pivoty))));
06995     /* Search for a point whose x-coordinate is too small for the right. */
06996     do {
06997       right--;
06998     } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
06999                                  ((sortarray[right][0] == pivotx) &&
07000                                   (sortarray[right][1] > pivoty))));
07001     if (left < right) {
07002       /* Swap the left and right points. */
07003       temp = sortarray[left];
07004       sortarray[left] = sortarray[right];
07005       sortarray[right] = temp;
07006     }
07007   }
07008   if (left > 1) {
07009     /* Recursively sort the left subset. */
07010     pointsort(sortarray, left);
07011   }
07012   if (right < arraysize - 2) {
07013     /* Recursively sort the right subset. */
07014     pointsort(&sortarray[right + 1], arraysize - right - 1);
07015   }
07016 }
07017 
07018 /*****************************************************************************/
07019 /*                                                                           */
07020 /*  pointmedian()   An order statistic algorithm, almost.  Shuffles an array */
07021 /*                  of points so that the first `median' points occur        */
07022 /*                  lexicographically before the remaining points.           */
07023 /*                                                                           */
07024 /*  Uses the x-coordinate as the primary key if axis == 0; the y-coordinate  */
07025 /*  if axis == 1.  Very similar to the pointsort() procedure, but runs in    */
07026 /*  randomized linear time.                                                  */
07027 /*                                                                           */
07028 /*****************************************************************************/
07029 
07030 void pointmedian(sortarray, arraysize, median, axis)
07031 point *sortarray;
07032 int arraysize;
07033 int median;
07034 int axis;
07035 {
07036   int left, right;
07037   int pivot;
07038   REAL pivot1, pivot2;
07039   point temp;
07040 
07041   if (arraysize == 2) {
07042     /* Recursive base case. */
07043     if ((sortarray[0][axis] > sortarray[1][axis]) ||
07044         ((sortarray[0][axis] == sortarray[1][axis]) &&
07045          (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
07046       temp = sortarray[1];
07047       sortarray[1] = sortarray[0];
07048       sortarray[0] = temp;
07049     }
07050     return;
07051   }
07052   /* Choose a random pivot to split the array. */
07053   pivot = (int) randomnation(arraysize);
07054   pivot1 = sortarray[pivot][axis];
07055   pivot2 = sortarray[pivot][1 - axis];
07056   /* Split the array. */
07057   left = -1;
07058   right = arraysize;
07059   while (left < right) {
07060     /* Search for a point whose x-coordinate is too large for the left. */
07061     do {
07062       left++;
07063     } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
07064                                  ((sortarray[left][axis] == pivot1) &&
07065                                   (sortarray[left][1 - axis] < pivot2))));
07066     /* Search for a point whose x-coordinate is too small for the right. */
07067     do {
07068       right--;
07069     } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
07070                                  ((sortarray[right][axis] == pivot1) &&
07071                                   (sortarray[right][1 - axis] > pivot2))));
07072     if (left < right) {
07073       /* Swap the left and right points. */
07074       temp = sortarray[left];
07075       sortarray[left] = sortarray[right];
07076       sortarray[right] = temp;
07077     }
07078   }
07079   /* Unlike in pointsort(), at most one of the following */
07080   /*   conditionals is true.                             */
07081   if (left > median) {
07082     /* Recursively shuffle the left subset. */
07083     pointmedian(sortarray, left, median, axis);
07084   }
07085   if (right < median - 1) {
07086     /* Recursively shuffle the right subset. */
07087     pointmedian(&sortarray[right + 1], arraysize - right - 1,
07088                 median - right - 1, axis);
07089   }
07090 }
07091 
07092 /*****************************************************************************/
07093 /*                                                                           */
07094 /*  alternateaxes()   Sorts the points as appropriate for the divide-and-    */
07095 /*                    conquer algorithm with alternating cuts.               */
07096 /*                                                                           */
07097 /*  Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1.   */
07098 /*  For the base case, subsets containing only two or three points are       */
07099 /*  always sorted by x-coordinate.                                           */
07100 /*                                                                           */
07101 /*****************************************************************************/
07102 
07103 void alternateaxes(sortarray, arraysize, axis)
07104 point *sortarray;
07105 int arraysize;
07106 int axis;
07107 {
07108   int divider;
07109 
07110   divider = arraysize >> 1;
07111   if (arraysize <= 3) {
07112     /* Recursive base case:  subsets of two or three points will be      */
07113     /*   handled specially, and should always be sorted by x-coordinate. */
07114     axis = 0;
07115   }
07116   /* Partition with a horizontal or vertical cut. */
07117   pointmedian(sortarray, arraysize, divider, axis);
07118   /* Recursively partition the subsets with a cross cut. */
07119   if (arraysize - divider >= 2) {
07120     if (divider >= 2) {
07121       alternateaxes(sortarray, divider, 1 - axis);
07122     }
07123     alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
07124   }
07125 }
07126 
07127 /*****************************************************************************/
07128 /*                                                                           */
07129 /*  mergehulls()   Merge two adjacent Delaunay triangulations into a         */
07130 /*                 single Delaunay triangulation.                            */
07131 /*                                                                           */
07132 /*  This is similar to the algorithm given by Guibas and Stolfi, but uses    */
07133 /*  a triangle-based, rather than edge-based, data structure.                */
07134 /*                                                                           */
07135 /*  The algorithm walks up the gap between the two triangulations, knitting  */
07136 /*  them together.  As they are merged, some of their bounding triangles     */
07137 /*  are converted into real triangles of the triangulation.  The procedure   */
07138 /*  pulls each hull's bounding triangles apart, then knits them together     */
07139 /*  like the teeth of two gears.  The Delaunay property determines, at each  */
07140 /*  step, whether the next "tooth" is a bounding triangle of the left hull   */
07141 /*  or the right.  When a bounding triangle becomes real, its apex is        */
07142 /*  changed from NULL to a real point.                                       */
07143 /*                                                                           */
07144 /*  Only two new triangles need to be allocated.  These become new bounding  */
07145 /*  triangles at the top and bottom of the seam.  They are used to connect   */
07146 /*  the remaining bounding triangles (those that have not been converted     */
07147 /*  into real triangles) into a single fan.                                  */
07148 /*                                                                           */
07149 /*  On entry, `farleft' and `innerleft' are bounding triangles of the left   */
07150 /*  triangulation.  The origin of `farleft' is the leftmost vertex, and      */
07151 /*  the destination of `innerleft' is the rightmost vertex of the            */
07152 /*  triangulation.  Similarly, `innerright' and `farright' are bounding      */
07153 /*  triangles of the right triangulation.  The origin of `innerright' and    */
07154 /*  destination of `farright' are the leftmost and rightmost vertices.       */
07155 /*                                                                           */
07156 /*  On completion, the origin of `farleft' is the leftmost vertex of the     */
07157 /*  merged triangulation, and the destination of `farright' is the rightmost */
07158 /*  vertex.                                                                  */
07159 /*                                                                           */
07160 /*****************************************************************************/
07161 
07162 void mergehulls(farleft, innerleft, innerright, farright, axis)
07163 struct triedge *farleft;
07164 struct triedge *innerleft;
07165 struct triedge *innerright;
07166 struct triedge *farright;
07167 int axis;
07168 {
07169   struct triedge leftcand, rightcand;
07170   struct triedge baseedge;
07171   struct triedge nextedge;
07172   struct triedge sidecasing, topcasing, outercasing;
07173   struct triedge checkedge;
07174   point innerleftdest;
07175   point innerrightorg;
07176   point innerleftapex, innerrightapex;
07177   point farleftpt, farrightpt;
07178   point farleftapex, farrightapex;
07179   point lowerleft, lowerright;
07180   point upperleft, upperright;
07181   point nextapex;
07182   point checkvertex;
07183   int changemade;
07184   int badedge;
07185   int leftfinished, rightfinished;
07186   triangle ptr;                         /* Temporary variable used by sym(). */
07187 
07188   dest(*innerleft, innerleftdest);
07189   apex(*innerleft, innerleftapex);
07190   org(*innerright, innerrightorg);
07191   apex(*innerright, innerrightapex);
07192   /* Special treatment for horizontal cuts. */
07193   if (dwyer && (axis == 1)) {
07194     org(*farleft, farleftpt);
07195     apex(*farleft, farleftapex);
07196     dest(*farright, farrightpt);
07197     apex(*farright, farrightapex);
07198     /* The pointers to the extremal points are shifted to point to the */
07199     /*   topmost and bottommost point of each hull, rather than the    */
07200     /*   leftmost and rightmost points.                                */
07201     while (farleftapex[1] < farleftpt[1]) {
07202       lnextself(*farleft);
07203       symself(*farleft);
07204       farleftpt = farleftapex;
07205       apex(*farleft, farleftapex);
07206     }
07207     sym(*innerleft, checkedge);
07208     apex(checkedge, checkvertex);
07209     while (checkvertex[1] > innerleftdest[1]) {
07210       lnext(checkedge, *innerleft);
07211       innerleftapex = innerleftdest;
07212       innerleftdest = checkvertex;
07213       sym(*innerleft, checkedge);
07214       apex(checkedge, checkvertex);
07215     }
07216     while (innerrightapex[1] < innerrightorg[1]) {
07217       lnextself(*innerright);
07218       symself(*innerright);
07219       innerrightorg = innerrightapex;
07220       apex(*innerright, innerrightapex);
07221     }
07222     sym(*farright, checkedge);
07223     apex(checkedge, checkvertex);
07224     while (checkvertex[1] > farrightpt[1]) {
07225       lnext(checkedge, *farright);
07226       farrightapex = farrightpt;
07227       farrightpt = checkvertex;
07228       sym(*farright, checkedge);
07229       apex(checkedge, checkvertex);
07230     }
07231   }
07232   /* Find a line tangent to and below both hulls. */
07233   do {
07234     changemade = 0;
07235     /* Make innerleftdest the "bottommost" point of the left hull. */
07236     if (counterclockwise(innerleftdest, innerleftapex, innerrightorg) > 0.0) {
07237       lprevself(*innerleft);
07238       symself(*innerleft);
07239       innerleftdest = innerleftapex;
07240       apex(*innerleft, innerleftapex);
07241       changemade = 1;
07242     }
07243     /* Make innerrightorg the "bottommost" point of the right hull. */
07244     if (counterclockwise(innerrightapex, innerrightorg, innerleftdest) > 0.0) {
07245       lnextself(*innerright);
07246       symself(*innerright);
07247       innerrightorg = innerrightapex;
07248       apex(*innerright, innerrightapex);
07249       changemade = 1;
07250     }
07251   } while (changemade);
07252   /* Find the two candidates to be the next "gear tooth". */
07253   sym(*innerleft, leftcand);
07254   sym(*innerright, rightcand);
07255   /* Create the bottom new bounding triangle. */
07256   maketriangle(&baseedge);
07257   /* Connect it to the bounding boxes of the left and right triangulations. */
07258   bond(baseedge, *innerleft);
07259   lnextself(baseedge);
07260   bond(baseedge, *innerright);
07261   lnextself(baseedge);
07262   setorg(baseedge, innerrightorg);
07263   setdest(baseedge, innerleftdest);
07264   /* Apex is intentionally left NULL. */
07265   if (verbose > 2) {
07266     printf("  Creating base bounding ");
07267     printtriangle(&baseedge);
07268   }
07269   /* Fix the extreme triangles if necessary. */
07270   org(*farleft, farleftpt);
07271   if (innerleftdest == farleftpt) {
07272     lnext(baseedge, *farleft);
07273   }
07274   dest(*farright, farrightpt);
07275   if (innerrightorg == farrightpt) {
07276     lprev(baseedge, *farright);
07277   }
07278   /* The vertices of the current knitting edge. */
07279   lowerleft = innerleftdest;
07280   lowerright = innerrightorg;
07281   /* The candidate vertices for knitting. */
07282   apex(leftcand, upperleft);
07283   apex(rightcand, upperright);
07284   /* Walk up the gap between the two triangulations, knitting them together. */
07285   while (1) {
07286     /* Have we reached the top?  (This isn't quite the right question,       */
07287     /*   because even though the left triangulation might seem finished now, */
07288     /*   moving up on the right triangulation might reveal a new point of    */
07289     /*   the left triangulation.  And vice-versa.)                           */
07290     leftfinished = counterclockwise(upperleft, lowerleft, lowerright) <= 0.0;
07291     rightfinished = counterclockwise(upperright, lowerleft, lowerright) <= 0.0;
07292     if (leftfinished && rightfinished) {
07293       /* Create the top new bounding triangle. */
07294       maketriangle(&nextedge);
07295       setorg(nextedge, lowerleft);
07296       setdest(nextedge, lowerright);
07297       /* Apex is intentionally left NULL. */
07298       /* Connect it to the bounding boxes of the two triangulations. */
07299       bond(nextedge, baseedge);
07300       lnextself(nextedge);
07301       bond(nextedge, rightcand);
07302       lnextself(nextedge);
07303       bond(nextedge, leftcand);
07304       if (verbose > 2) {
07305         printf("  Creating top bounding ");
07306         printtriangle(&baseedge);
07307       }
07308       /* Special treatment for horizontal cuts. */
07309       if (dwyer && (axis == 1)) {
07310         org(*farleft, farleftpt);
07311         apex(*farleft, farleftapex);
07312         dest(*farright, farrightpt);
07313         apex(*farright, farrightapex);
07314         sym(*farleft, checkedge);
07315         apex(checkedge, checkvertex);
07316         /* The pointers to the extremal points are restored to the leftmost */
07317         /*   and rightmost points (rather than topmost and bottommost).     */
07318         while (checkvertex[0] < farleftpt[0]) {
07319           lprev(checkedge, *farleft);
07320           farleftapex = farleftpt;
07321           farleftpt = checkvertex;
07322           sym(*farleft, checkedge);
07323           apex(checkedge, checkvertex);
07324         }
07325         while (farrightapex[0] > farrightpt[0]) {
07326           lprevself(*farright);
07327           symself(*farright);
07328           farrightpt = farrightapex;
07329           apex(*farright, farrightapex);
07330         }
07331       }
07332       return;
07333     }
07334     /* Consider eliminating edges from the left triangulation. */
07335     if (!leftfinished) {
07336       /* What vertex would be exposed if an edge were deleted? */
07337       lprev(leftcand, nextedge);
07338       symself(nextedge);
07339       apex(nextedge, nextapex);
07340       /* If nextapex is NULL, then no vertex would be exposed; the */
07341       /*   triangulation would have been eaten right through.      */
07342       if (nextapex != (point) NULL) {
07343         /* Check whether the edge is Delaunay. */
07344         badedge = incircle(lowerleft, lowerright, upperleft, nextapex) > 0.0;
07345         while (badedge) {
07346           /* Eliminate the edge with an edge flip.  As a result, the    */
07347           /*   left triangulation will have one more boundary triangle. */
07348           lnextself(nextedge);
07349           sym(nextedge, topcasing);
07350           lnextself(nextedge);
07351           sym(nextedge, sidecasing);
07352           bond(nextedge, topcasing);
07353           bond(leftcand, sidecasing);
07354           lnextself(leftcand);
07355           sym(leftcand, outercasing);
07356           lprevself(nextedge);
07357           bond(nextedge, outercasing);
07358           /* Correct the vertices to reflect the edge flip. */
07359           setorg(leftcand, lowerleft);
07360           setdest(leftcand, NULL);
07361           setapex(leftcand, nextapex);
07362           setorg(nextedge, NULL);
07363           setdest(nextedge, upperleft);
07364           setapex(nextedge, nextapex);
07365           /* Consider the newly exposed vertex. */
07366           upperleft = nextapex;
07367           /* What vertex would be exposed if another edge were deleted? */
07368           triedgecopy(sidecasing, nextedge);
07369           apex(nextedge, nextapex);
07370           if (nextapex != (point) NULL) {
07371             /* Check whether the edge is Delaunay. */
07372             badedge = incircle(lowerleft, lowerright, upperleft, nextapex)
07373                       > 0.0;
07374           } else {
07375             /* Avoid eating right through the triangulation. */
07376             badedge = 0;
07377           }
07378         }
07379       }
07380     }
07381     /* Consider eliminating edges from the right triangulation. */
07382     if (!rightfinished) {
07383       /* What vertex would be exposed if an edge were deleted? */
07384       lnext(rightcand, nextedge);
07385       symself(nextedge);
07386       apex(nextedge, nextapex);
07387       /* If nextapex is NULL, then no vertex would be exposed; the */
07388       /*   triangulation would have been eaten right through.      */
07389       if (nextapex != (point) NULL) {
07390         /* Check whether the edge is Delaunay. */
07391         badedge = incircle(lowerleft, lowerright, upperright, nextapex) > 0.0;
07392         while (badedge) {
07393           /* Eliminate the edge with an edge flip.  As a result, the     */
07394           /*   right triangulation will have one more boundary triangle. */
07395           lprevself(nextedge);
07396           sym(nextedge, topcasing);
07397           lprevself(nextedge);
07398           sym(nextedge, sidecasing);
07399           bond(nextedge, topcasing);
07400           bond(rightcand, sidecasing);
07401           lprevself(rightcand);
07402           sym(rightcand, outercasing);
07403           lnextself(nextedge);
07404           bond(nextedge, outercasing);
07405           /* Correct the vertices to reflect the edge flip. */
07406           setorg(rightcand, NULL);
07407           setdest(rightcand, lowerright);
07408           setapex(rightcand, nextapex);
07409           setorg(nextedge, upperright);
07410           setdest(nextedge, NULL);
07411           setapex(nextedge, nextapex);
07412           /* Consider the newly exposed vertex. */
07413           upperright = nextapex;
07414           /* What vertex would be exposed if another edge were deleted? */
07415           triedgecopy(sidecasing, nextedge);
07416           apex(nextedge, nextapex);
07417           if (nextapex != (point) NULL) {
07418             /* Check whether the edge is Delaunay. */
07419             badedge = incircle(lowerleft, lowerright, upperright, nextapex)
07420                       > 0.0;
07421           } else {
07422             /* Avoid eating right through the triangulation. */
07423             badedge = 0;
07424           }
07425         }
07426       }
07427     }
07428     if (leftfinished || (!rightfinished &&
07429            (incircle(upperleft, lowerleft, lowerright, upperright) > 0.0))) {
07430       /* Knit the triangulations, adding an edge from `lowerleft' */
07431       /*   to `upperright'.                                       */
07432       bond(baseedge, rightcand);
07433       lprev(rightcand, baseedge);
07434       setdest(baseedge, lowerleft);
07435       lowerright = upperright;
07436       sym(baseedge, rightcand);
07437       apex(rightcand, upperright);
07438     } else {
07439       /* Knit the triangulations, adding an edge from `upperleft' */
07440       /*   to `lowerright'.                                       */
07441       bond(baseedge, leftcand);
07442       lnext(leftcand, baseedge);
07443       setorg(baseedge, lowerright);
07444       lowerleft = upperleft;
07445       sym(baseedge, leftcand);
07446       apex(leftcand, upperleft);
07447     }
07448     if (verbose > 2) {
07449       printf("  Connecting ");
07450       printtriangle(&baseedge);
07451     }
07452   }
07453 }
07454 
07455 /*****************************************************************************/
07456 /*                                                                           */
07457 /*  divconqrecurse()   Recursively form a Delaunay triangulation by the      */
07458 /*                     divide-and-conquer method.                            */
07459 /*                                                                           */
07460 /*  Recursively breaks down the problem into smaller pieces, which are       */
07461 /*  knitted together by mergehulls().  The base cases (problems of two or    */
07462 /*  three points) are handled specially here.                                */
07463 /*                                                                           */
07464 /*  On completion, `farleft' and `farright' are bounding triangles such that */
07465 /*  the origin of `farleft' is the leftmost vertex (breaking ties by         */
07466 /*  choosing the highest leftmost vertex), and the destination of            */
07467 /*  `farright' is the rightmost vertex (breaking ties by choosing the        */
07468 /*  lowest rightmost vertex).                                                */
07469 /*                                                                           */
07470 /*****************************************************************************/
07471 
07472 void divconqrecurse(sortarray, vertices, axis, farleft, farright)
07473 point *sortarray;
07474 int vertices;
07475 int axis;
07476 struct triedge *farleft;
07477 struct triedge *farright;
07478 {
07479   struct triedge midtri, tri1, tri2, tri3;
07480   struct triedge innerleft, innerright;
07481   REAL area;
07482   int divider;
07483 
07484   if (verbose > 2) {
07485     printf("  Triangulating %d points.\n", vertices);
07486   }
07487   if (vertices == 2) {
07488     /* The triangulation of two vertices is an edge.  An edge is */
07489     /*   represented by two bounding triangles.                  */
07490     maketriangle(farleft);
07491     setorg(*farleft, sortarray[0]);
07492     setdest(*farleft, sortarray[1]);
07493     /* The apex is intentionally left NULL. */
07494     maketriangle(farright);
07495     setorg(*farright, sortarray[1]);
07496     setdest(*farright, sortarray[0]);
07497     /* The apex is intentionally left NULL. */
07498     bond(*farleft, *farright);
07499     lprevself(*farleft);
07500     lnextself(*farright);
07501     bond(*farleft, *farright);
07502     lprevself(*farleft);
07503     lnextself(*farright);
07504     bond(*farleft, *farright);
07505     if (verbose > 2) {
07506       printf("  Creating ");
07507       printtriangle(farleft);
07508       printf("  Creating ");
07509       printtriangle(farright);
07510     }
07511     /* Ensure that the origin of `farleft' is sortarray[0]. */
07512     lprev(*farright, *farleft);
07513     return;
07514   } else if (vertices == 3) {
07515     /* The triangulation of three vertices is either a triangle (with */
07516     /*   three bounding triangles) or two edges (with four bounding   */
07517     /*   triangles).  In either case, four triangles are created.     */
07518     maketriangle(&midtri);
07519     maketriangle(&tri1);
07520     maketriangle(&tri2);
07521     maketriangle(&tri3);
07522     area = counterclockwise(sortarray[0], sortarray[1], sortarray[2]);
07523     if (area == 0.0) {
07524       /* Three collinear points; the triangulation is two edges. */
07525       setorg(midtri, sortarray[0]);
07526       setdest(midtri, sortarray[1]);
07527       setorg(tri1, sortarray[1]);
07528       setdest(tri1, sortarray[0]);
07529       setorg(tri2, sortarray[2]);
07530       setdest(tri2, sortarray[1]);
07531       setorg(tri3, sortarray[1]);
07532       setdest(tri3, sortarray[2]);
07533       /* All apices are intentionally left NULL. */
07534       bond(midtri, tri1);
07535       bond(tri2, tri3);
07536       lnextself(midtri);
07537       lprevself(tri1);
07538       lnextself(tri2);
07539       lprevself(tri3);
07540       bond(midtri, tri3);
07541       bond(tri1, tri2);
07542       lnextself(midtri);
07543       lprevself(tri1);
07544       lnextself(tri2);
07545       lprevself(tri3);
07546       bond(midtri, tri1);
07547       bond(tri2, tri3);
07548       /* Ensure that the origin of `farleft' is sortarray[0]. */
07549       triedgecopy(tri1, *farleft);
07550       /* Ensure that the destination of `farright' is sortarray[2]. */
07551       triedgecopy(tri2, *farright);
07552     } else {
07553       /* The three points are not collinear; the triangulation is one */
07554       /*   triangle, namely `midtri'.                                 */
07555       setorg(midtri, sortarray[0]);
07556       setdest(tri1, sortarray[0]);
07557       setorg(tri3, sortarray[0]);
07558       /* Apices of tri1, tri2, and tri3 are left NULL. */
07559       if (area > 0.0) {
07560         /* The vertices are in counterclockwise order. */
07561         setdest(midtri, sortarray[1]);
07562         setorg(tri1, sortarray[1]);
07563         setdest(tri2, sortarray[1]);
07564         setapex(midtri, sortarray[2]);
07565         setorg(tri2, sortarray[2]);
07566         setdest(tri3, sortarray[2]);
07567       } else {
07568         /* The vertices are in clockwise order. */
07569         setdest(midtri, sortarray[2]);
07570         setorg(tri1, sortarray[2]);
07571         setdest(tri2, sortarray[2]);
07572         setapex(midtri, sortarray[1]);
07573         setorg(tri2, sortarray[1]);
07574         setdest(tri3, sortarray[1]);
07575       }
07576       /* The topology does not depend on how the vertices are ordered. */
07577       bond(midtri, tri1);
07578       lnextself(midtri);
07579       bond(midtri, tri2);
07580       lnextself(midtri);
07581       bond(midtri, tri3);
07582       lprevself(tri1);
07583       lnextself(tri2);
07584       bond(tri1, tri2);
07585       lprevself(tri1);
07586       lprevself(tri3);
07587       bond(tri1, tri3);
07588       lnextself(tri2);
07589       lprevself(tri3);
07590       bond(tri2, tri3);
07591       /* Ensure that the origin of `farleft' is sortarray[0]. */
07592       triedgecopy(tri1, *farleft);
07593       /* Ensure that the destination of `farright' is sortarray[2]. */
07594       if (area > 0.0) {
07595         triedgecopy(tri2, *farright);
07596       } else {
07597         lnext(*farleft, *farright);
07598       }
07599     }
07600     if (verbose > 2) {
07601       printf("  Creating ");
07602       printtriangle(&midtri);
07603       printf("  Creating ");
07604       printtriangle(&tri1);
07605       printf("  Creating ");
07606       printtriangle(&tri2);
07607       printf("  Creating ");
07608       printtriangle(&tri3);
07609     }
07610     return;
07611   } else {
07612     /* Split the vertices in half. */
07613     divider = vertices >> 1;
07614     /* Recursively triangulate each half. */
07615     divconqrecurse(sortarray, divider, 1 - axis, farleft, &innerleft);
07616     divconqrecurse(&sortarray[divider], vertices - divider, 1 - axis,
07617                    &innerright, farright);
07618     if (verbose > 1) {
07619       printf("  Joining triangulations with %d and %d vertices.\n", divider,
07620              vertices - divider);
07621     }
07622     /* Merge the two triangulations into one. */
07623     mergehulls(farleft, &innerleft, &innerright, farright, axis);
07624   }
07625 }
07626 
07627 long removeghosts(startghost)
07628 struct triedge *startghost;
07629 {
07630   struct triedge searchedge;
07631   struct triedge dissolveedge;
07632   struct triedge deadtri;
07633   point markorg;
07634   long hullsize;
07635   triangle ptr;                         /* Temporary variable used by sym(). */
07636 
07637   if (verbose) {
07638     printf("  Removing ghost triangles.\n");
07639   }
07640   /* Find an edge on the convex hull to start point location from. */
07641   lprev(*startghost, searchedge);
07642   symself(searchedge);
07643   dummytri[0] = encode(searchedge);
07644   /* Remove the bounding box and count the convex hull edges. */
07645   triedgecopy(*startghost, dissolveedge);
07646   hullsize = 0;
07647   do {
07648     hullsize++;
07649     lnext(dissolveedge, deadtri);
07650     lprevself(dissolveedge);
07651     symself(dissolveedge);
07652     /* If no PSLG is involved, set the boundary markers of all the points */
07653     /*   on the convex hull.  If a PSLG is used, this step is done later. */
07654     if (!poly) {
07655       /* Watch out for the case where all the input points are collinear. */
07656       if (dissolveedge.tri != dummytri) {
07657         org(dissolveedge, markorg);
07658         if (pointmark(markorg) == 0) {
07659           setpointmark(markorg, 1);
07660         }
07661       }
07662     }
07663     /* Remove a bounding triangle from a convex hull triangle. */
07664     dissolve(dissolveedge);
07665     /* Find the next bounding triangle. */
07666     sym(deadtri, dissolveedge);
07667     /* Delete the bounding triangle. */
07668     triangledealloc(deadtri.tri);
07669   } while (!triedgeequal(dissolveedge, *startghost));
07670   return hullsize;
07671 }
07672 
07673 /*****************************************************************************/
07674 /*                                                                           */
07675 /*  divconqdelaunay()   Form a Delaunay triangulation by the divide-and-     */
07676 /*                      conquer method.                                      */
07677 /*                                                                           */
07678 /*  Sorts the points, calls a recursive procedure to triangulate them, and   */
07679 /*  removes the bounding box, setting boundary markers as appropriate.       */
07680 /*                                                                           */
07681 /*****************************************************************************/
07682 
07683 long divconqdelaunay()
07684 {
07685   point *sortarray;
07686   struct triedge hullleft, hullright;
07687   int divider;
07688   int i, j;
07689 
07690   /* Allocate an array of pointers to points for sorting. */
07691   sortarray = (point *) malloc(inpoints * sizeof(point));
07692   if (sortarray == (point *) NULL) {
07693     printf("Error:  Out of memory.\n");
07694     exit(1);
07695   }
07696   traversalinit(&points);
07697   for (i = 0; i < inpoints; i++) {
07698     sortarray[i] = pointtraverse();
07699   }
07700   if (verbose) {
07701     printf("  Sorting points.\n");
07702   }
07703   /* Sort the points. */
07704   pointsort(sortarray, inpoints);
07705   /* Discard duplicate points, which can really mess up the algorithm. */
07706   i = 0;
07707   for (j = 1; j < inpoints; j++) {
07708     if ((sortarray[i][0] == sortarray[j][0])
07709         && (sortarray[i][1] == sortarray[j][1])) {
07710       if (!quiet) {
07711         printf(
07712 "Warning:  A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
07713                sortarray[j][0], sortarray[j][1]);
07714       }
07715 /*  Commented out - would eliminate point from output .node file, but causes
07716     a failure if some segment has this point as an endpoint.
07717       setpointmark(sortarray[j], DEADPOINT);
07718 */
07719     } else {
07720       i++;
07721       sortarray[i] = sortarray[j];
07722     }
07723   }
07724   i++;
07725   if (dwyer) {
07726     /* Re-sort the array of points to accommodate alternating cuts. */
07727     divider = i >> 1;
07728     if (i - divider >= 2) {
07729       if (divider >= 2) {
07730         alternateaxes(sortarray, divider, 1);
07731       }
07732       alternateaxes(&sortarray[divider], i - divider, 1);
07733     }
07734   }
07735   if (verbose) {
07736     printf("  Forming triangulation.\n");
07737   }
07738   /* Form the Delaunay triangulation. */
07739   divconqrecurse(sortarray, i, 0, &hullleft, &hullright);
07740   free(sortarray);
07741 
07742   return removeghosts(&hullleft);
07743 }
07744 
07745 /**                                                                         **/
07746 /**                                                                         **/
07747 /********* Divide-and-conquer Delaunay triangulation ends here       *********/
07748 
07749 /********* Incremental Delaunay triangulation begins here            *********/
07750 /**                                                                         **/
07751 /**                                                                         **/
07752 
07753 /*****************************************************************************/
07754 /*                                                                           */
07755 /*  boundingbox()   Form an "infinite" bounding triangle to insert points    */
07756 /*                  into.                                                    */
07757 /*                                                                           */
07758 /*  The points at "infinity" are assigned finite coordinates, which are used */
07759 /*  by the point location routines, but (mostly) ignored by the Delaunay     */
07760 /*  edge flip routines.                                                      */
07761 /*                                                                           */
07762 /*****************************************************************************/
07763 
07764 #ifndef REDUCED
07765 
07766 void boundingbox()
07767 {
07768   struct triedge inftri;          /* Handle for the triangular bounding box. */
07769   REAL width;
07770 
07771   if (verbose) {
07772     printf("  Creating triangular bounding box.\n");
07773   }
07774   /* Find the width (or height, whichever is larger) of the triangulation. */
07775   width = xmax - xmin;
07776   if (ymax - ymin > width) {
07777     width = ymax - ymin;
07778   }
07779   if (width == 0.0) {
07780     width = 1.0;
07781   }
07782   /* Create the vertices of the bounding box. */
07783   infpoint1 = (point) malloc(points.itembytes);
07784   infpoint2 = (point) malloc(points.itembytes);
07785   infpoint3 = (point) malloc(points.itembytes);
07786   if ((infpoint1 == (point) NULL) || (infpoint2 == (point) NULL)
07787       || (infpoint3 == (point) NULL)) {
07788     printf("Error:  Out of memory.\n");
07789     exit(1);
07790   }
07791   infpoint1[0] = xmin - 50.0 * width;
07792   infpoint1[1] = ymin - 40.0 * width;
07793   infpoint2[0] = xmax + 50.0 * width;
07794   infpoint2[1] = ymin - 40.0 * width;
07795   infpoint3[0] = 0.5 * (xmin + xmax);
07796   infpoint3[1] = ymax + 60.0 * width;
07797 
07798   /* Create the bounding box. */
07799   maketriangle(&inftri);
07800   setorg(inftri, infpoint1);
07801   setdest(inftri, infpoint2);
07802   setapex(inftri, infpoint3);
07803   /* Link dummytri to the bounding box so we can always find an */
07804   /*   edge to begin searching (point location) from.           */
07805   dummytri[0] = (triangle) inftri.tri;
07806   if (verbose > 2) {
07807     printf("  Creating ");
07808     printtriangle(&inftri);
07809   }
07810 }
07811 
07812 #endif /* not REDUCED */
07813 
07814 /*****************************************************************************/
07815 /*                                                                           */
07816 /*  removebox()   Remove the "infinite" bounding triangle, setting boundary  */
07817 /*                markers as appropriate.                                    */
07818 /*                                                                           */
07819 /*  The triangular bounding box has three boundary triangles (one for each   */
07820 /*  side of the bounding box), and a bunch of triangles fanning out from     */
07821 /*  the three bounding box vertices (one triangle for each edge of the       */
07822 /*  convex hull of the inner mesh).  This routine removes these triangles.   */
07823 /*                                                                           */
07824 /*****************************************************************************/
07825 
07826 #ifndef REDUCED
07827 
07828 long removebox()
07829 {
07830   struct triedge deadtri;
07831   struct triedge searchedge;
07832   struct triedge checkedge;
07833   struct triedge nextedge, finaledge, dissolveedge;
07834   point markorg;
07835   long hullsize;
07836   triangle ptr;                         /* Temporary variable used by sym(). */
07837 
07838   if (verbose) {
07839     printf("  Removing triangular bounding box.\n");
07840   }
07841   /* Find a boundary triangle. */
07842   nextedge.tri = dummytri;
07843   nextedge.orient = 0;
07844   symself(nextedge);
07845   /* Mark a place to stop. */
07846   lprev(nextedge, finaledge);
07847   lnextself(nextedge);
07848   symself(nextedge);
07849   /* Find a triangle (on the boundary of the point set) that isn't */
07850   /*   a bounding box triangle.                                    */
07851   lprev(nextedge, searchedge);
07852   symself(searchedge);
07853   /* Check whether nextedge is another boundary triangle */
07854   /*   adjacent to the first one.                        */
07855   lnext(nextedge, checkedge);
07856   symself(checkedge);
07857   if (checkedge.tri == dummytri) {
07858     /* Go on to the next triangle.  There are only three boundary   */
07859     /*   triangles, and this next triangle cannot be the third one, */
07860     /*   so it's safe to stop here.                                 */
07861     lprevself(searchedge);
07862     symself(searchedge);
07863   }
07864   /* Find a new boundary edge to search from, as the current search */
07865   /*   edge lies on a bounding box triangle and will be deleted.    */
07866   dummytri[0] = encode(searchedge);
07867   hullsize = -2l;
07868   while (!triedgeequal(nextedge, finaledge)) {
07869     hullsize++;
07870     lprev(nextedge, dissolveedge);
07871     symself(dissolveedge);
07872     /* If not using a PSLG, the vertices should be marked now. */
07873     /*   (If using a PSLG, markhull() will do the job.)        */
07874     if (!poly) {
07875       /* Be careful!  One must check for the case where all the input   */
07876       /*   points are collinear, and thus all the triangles are part of */
07877       /*   the bounding box.  Otherwise, the setpointmark() call below  */
07878       /*   will cause a bad pointer reference.                          */
07879       if (dissolveedge.tri != dummytri) {
07880         org(dissolveedge, markorg);
07881         if (pointmark(markorg) == 0) {
07882           setpointmark(markorg, 1);
07883         }
07884       }
07885     }
07886     /* Disconnect the bounding box triangle from the mesh triangle. */
07887     dissolve(dissolveedge);
07888     lnext(nextedge, deadtri);
07889     sym(deadtri, nextedge);
07890     /* Get rid of the bounding box triangle. */
07891     triangledealloc(deadtri.tri);
07892     /* Do we need to turn the corner? */
07893     if (nextedge.tri == dummytri) {
07894       /* Turn the corner. */
07895       triedgecopy(dissolveedge, nextedge);
07896     }
07897   }
07898   triangledealloc(finaledge.tri);
07899 
07900   free(infpoint1);                  /* Deallocate the bounding box vertices. */
07901   free(infpoint2);
07902   free(infpoint3);
07903 
07904   return hullsize;
07905 }
07906 
07907 #endif /* not REDUCED */
07908 
07909 /*****************************************************************************/
07910 /*                                                                           */
07911 /*  incrementaldelaunay()   Form a Delaunay triangulation by incrementally   */
07912 /*                          adding vertices.                                 */
07913 /*                                                                           */
07914 /*****************************************************************************/
07915 
07916 #ifndef REDUCED
07917 
07918 long incrementaldelaunay()
07919 {
07920   struct triedge starttri;
07921   point pointloop;
07922   int i;
07923 
07924   /* Create a triangular bounding box. */
07925   boundingbox();
07926   if (verbose) {
07927     printf("  Incrementally inserting points.\n");
07928   }
07929   traversalinit(&points);
07930   pointloop = pointtraverse();
07931   i = 1;
07932   while (pointloop != (point) NULL) {
07933     /* Find a boundary triangle to search from. */
07934     starttri.tri = (triangle *) NULL;
07935     if (insertsite(pointloop, &starttri, (struct edge *) NULL, 0, 0) ==
07936         DUPLICATEPOINT) {
07937       if (!quiet) {
07938         printf(
07939 "Warning:  A duplicate point at (%.12g, %.12g) appeared and was ignored.\n",
07940                pointloop[0], pointloop[1]);
07941       }
07942 /*  Commented out - would eliminate point from output .node file.
07943       setpointmark(pointloop, DEADPOINT);
07944 */
07945     }
07946     pointloop = pointtraverse();
07947     i++;
07948   }
07949   /* Remove the bounding box. */
07950   return removebox();
07951 }
07952 
07953 #endif /* not REDUCED */
07954 
07955 /**                                                                         **/
07956 /**                                                                         **/
07957 /********* Incremental Delaunay triangulation ends here              *********/
07958 
07959 /********* Sweepline Delaunay triangulation begins here              *********/
07960 /**                                                                         **/
07961 /**                                                                         **/
07962 
07963 #ifndef REDUCED
07964 
07965 void eventheapinsert(heap, heapsize, newevent)
07966 struct event **heap;
07967 int heapsize;
07968 struct event *newevent;
07969 {
07970   REAL eventx, eventy;
07971   int eventnum;
07972   int parent;
07973   int notdone;
07974 
07975   eventx = newevent->xkey;
07976   eventy = newevent->ykey;
07977   eventnum = heapsize;
07978   notdone = eventnum > 0;
07979   while (notdone) {
07980     parent = (eventnum - 1) >> 1;
07981     if ((heap[parent]->ykey < eventy) ||
07982         ((heap[parent]->ykey == eventy)
07983          && (heap[parent]->xkey <= eventx))) {
07984       notdone = 0;
07985     } else {
07986       heap[eventnum] = heap[parent];
07987       heap[eventnum]->heapposition = eventnum;
07988 
07989       eventnum = parent;
07990       notdone = eventnum > 0;
07991     }
07992   }
07993   heap[eventnum] = newevent;
07994   newevent->heapposition = eventnum;
07995 }
07996 
07997 #endif /* not REDUCED */
07998 
07999 #ifndef REDUCED
08000 
08001 void eventheapify(heap, heapsize, eventnum)
08002 struct event **heap;
08003 int heapsize;
08004 int eventnum;
08005 {
08006   struct event *thisevent;
08007   REAL eventx, eventy;
08008   int leftchild, rightchild;
08009   int smallest;
08010   int notdone;
08011 
08012   thisevent = heap[eventnum];
08013   eventx = thisevent->xkey;
08014   eventy = thisevent->ykey;
08015   leftchild = 2 * eventnum + 1;
08016   notdone = leftchild < heapsize;
08017   while (notdone) {
08018     if ((heap[leftchild]->ykey < eventy) ||
08019         ((heap[leftchild]->ykey == eventy)
08020          && (heap[leftchild]->xkey < eventx))) {
08021       smallest = leftchild;
08022     } else {
08023       smallest = eventnum;
08024     }
08025     rightchild = leftchild + 1;
08026     if (rightchild < heapsize) {
08027       if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
08028           ((heap[rightchild]->ykey == heap[smallest]->ykey)
08029            && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
08030         smallest = rightchild;
08031       }
08032     }
08033     if (smallest == eventnum) {
08034       notdone = 0;
08035     } else {
08036       heap[eventnum] = heap[smallest];
08037       heap[eventnum]->heapposition = eventnum;
08038       heap[smallest] = thisevent;
08039       thisevent->heapposition = smallest;
08040 
08041       eventnum = smallest;
08042       leftchild = 2 * eventnum + 1;
08043       notdone = leftchild < heapsize;
08044     }
08045   }
08046 }
08047 
08048 #endif /* not REDUCED */
08049 
08050 #ifndef REDUCED
08051 
08052 void eventheapdelete(heap, heapsize, eventnum)
08053 struct event **heap;
08054 int heapsize;
08055 int eventnum;
08056 {
08057   struct event *moveevent;
08058   REAL eventx, eventy;
08059   int parent;
08060   int notdone;
08061 
08062   moveevent = heap[heapsize - 1];
08063   if (eventnum > 0) {
08064     eventx = moveevent->xkey;
08065     eventy = moveevent->ykey;
08066     do {
08067       parent = (eventnum - 1) >> 1;
08068       if ((heap[parent]->ykey < eventy) ||
08069           ((heap[parent]->ykey == eventy)
08070            && (heap[parent]->xkey <= eventx))) {
08071         notdone = 0;
08072       } else {
08073         heap[eventnum] = heap[parent];
08074         heap[eventnum]->heapposition = eventnum;
08075 
08076         eventnum = parent;
08077         notdone = eventnum > 0;
08078       }
08079     } while (notdone);
08080   }
08081   heap[eventnum] = moveevent;
08082   moveevent->heapposition = eventnum;
08083   eventheapify(heap, heapsize - 1, eventnum);
08084 }
08085 
08086 #endif /* not REDUCED */
08087 
08088 #ifndef REDUCED
08089 
08090 void createeventheap(eventheap, events, freeevents)
08091 struct event ***eventheap;
08092 struct event **events;
08093 struct event **freeevents;
08094 {
08095   point thispoint;
08096   int maxevents;
08097   int i;
08098 
08099   maxevents = (3 * inpoints) / 2;
08100   *eventheap = (struct event **) malloc(maxevents * sizeof(struct event *));
08101   if (*eventheap == (struct event **) NULL) {
08102     printf("Error:  Out of memory.\n");
08103     exit(1);
08104   }
08105   *events = (struct event *) malloc(maxevents * sizeof(struct event));
08106   if (*events == (struct event *) NULL) {
08107     printf("Error:  Out of memory.\n");
08108     exit(1);
08109   }
08110   traversalinit(&points);
08111   for (i = 0; i < inpoints; i++) {
08112     thispoint = pointtraverse();
08113     (*events)[i].eventptr = (VOID *) thispoint;
08114     (*events)[i].xkey = thispoint[0];
08115     (*events)[i].ykey = thispoint[1];
08116     eventheapinsert(*eventheap, i, *events + i);
08117   }
08118   *freeevents = (struct event *) NULL;
08119   for (i = maxevents - 1; i >= inpoints; i--) {
08120     (*events)[i].eventptr = (VOID *) *freeevents;
08121     *freeevents = *events + i;
08122   }
08123 }
08124 
08125 #endif /* not REDUCED */
08126 
08127 #ifndef REDUCED
08128 
08129 int rightofhyperbola(fronttri, newsite)
08130 struct triedge *fronttri;
08131 point newsite;
08132 {
08133   point leftpoint, rightpoint;
08134   REAL dxa, dya, dxb, dyb;
08135 
08136   hyperbolacount++;
08137 
08138   dest(*fronttri, leftpoint);
08139   apex(*fronttri, rightpoint);
08140   if ((leftpoint[1] < rightpoint[1])
08141       || ((leftpoint[1] == rightpoint[1]) && (leftpoint[0] < rightpoint[0]))) {
08142     if (newsite[0] >= rightpoint[0]) {
08143       return 1;
08144     }
08145   } else {
08146     if (newsite[0] <= leftpoint[0]) {
08147       return 0;
08148     }
08149   }
08150   dxa = leftpoint[0] - newsite[0];
08151   dya = leftpoint[1] - newsite[1];
08152   dxb = rightpoint[0] - newsite[0];
08153   dyb = rightpoint[1] - newsite[1];
08154   return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
08155 }
08156 
08157 #endif /* not REDUCED */
08158 
08159 #ifndef REDUCED
08160 
08161 REAL circletop(pa, pb, pc, ccwabc)
08162 point pa;
08163 point pb;
08164 point pc;
08165 REAL ccwabc;
08166 {
08167   REAL xac, yac, xbc, ybc, xab, yab;
08168   REAL aclen2, bclen2, ablen2;
08169 
08170   circletopcount++;
08171 
08172   xac = pa[0] - pc[0];
08173   yac = pa[1] - pc[1];
08174   xbc = pb[0] - pc[0];
08175   ybc = pb[1] - pc[1];
08176   xab = pa[0] - pb[0];
08177   yab = pa[1] - pb[1];
08178   aclen2 = xac * xac + yac * yac;
08179   bclen2 = xbc * xbc + ybc * ybc;
08180   ablen2 = xab * xab + yab * yab;
08181   return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
08182                / (2.0 * ccwabc);
08183 }
08184 
08185 #endif /* not REDUCED */
08186 
08187 #ifndef REDUCED
08188 
08189 void check4deadevent(checktri, freeevents, eventheap, heapsize)
08190 struct triedge *checktri;
08191 struct event **freeevents;
08192 struct event **eventheap;
08193 int *heapsize;
08194 {
08195   struct event *deadevent;
08196   point eventpoint;
08197   int eventnum;
08198 
08199   org(*checktri, eventpoint);
08200   if (eventpoint != (point) NULL) {
08201     deadevent = (struct event *) eventpoint;
08202     eventnum = deadevent->heapposition;
08203     deadevent->eventptr = (VOID *) *freeevents;
08204     *freeevents = deadevent;
08205     eventheapdelete(eventheap, *heapsize, eventnum);
08206     (*heapsize)--;
08207     setorg(*checktri, NULL);
08208   }
08209 }
08210 
08211 #endif /* not REDUCED */
08212 
08213 #ifndef REDUCED
08214 
08215 struct splaynode *splay(splaytree, searchpoint, searchtri)
08216 struct splaynode *splaytree;
08217 point searchpoint;
08218 struct triedge *searchtri;
08219 {
08220   struct splaynode *child, *grandchild;
08221   struct splaynode *lefttree, *righttree;
08222   struct splaynode *leftright;
08223   point checkpoint;
08224   int rightofroot, rightofchild;
08225 
08226   if (splaytree == (struct splaynode *) NULL) {
08227     return (struct splaynode *) NULL;
08228   }
08229   dest(splaytree->keyedge, checkpoint);
08230   if (checkpoint == splaytree->keydest) {
08231     rightofroot = rightofhyperbola(&splaytree->keyedge, searchpoint);
08232     if (rightofroot) {
08233       triedgecopy(splaytree->keyedge, *searchtri);
08234       child = splaytree->rchild;
08235     } else {
08236       child = splaytree->lchild;
08237     }
08238     if (child == (struct splaynode *) NULL) {
08239       return splaytree;
08240     }
08241     dest(child->keyedge, checkpoint);
08242     if (checkpoint != child->keydest) {
08243       child = splay(child, searchpoint, searchtri);
08244       if (child == (struct splaynode *) NULL) {
08245         if (rightofroot) {
08246           splaytree->rchild = (struct splaynode *) NULL;
08247         } else {
08248           splaytree->lchild = (struct splaynode *) NULL;
08249         }
08250         return splaytree;
08251       }
08252     }
08253     rightofchild = rightofhyperbola(&child->keyedge, searchpoint);
08254     if (rightofchild) {
08255       triedgecopy(child->keyedge, *searchtri);
08256       grandchild = splay(child->rchild, searchpoint, searchtri);
08257       child->rchild = grandchild;
08258     } else {
08259       grandchild = splay(child->lchild, searchpoint, searchtri);
08260       child->lchild = grandchild;
08261     }
08262     if (grandchild == (struct splaynode *) NULL) {
08263       if (rightofroot) {
08264         splaytree->rchild = child->lchild;
08265         child->lchild = splaytree;
08266       } else {
08267         splaytree->lchild = child->rchild;
08268         child->rchild = splaytree;
08269       }
08270       return child;
08271     }
08272     if (rightofchild) {
08273       if (rightofroot) {
08274         splaytree->rchild = child->lchild;
08275         child->lchild = splaytree;
08276       } else {
08277         splaytree->lchild = grandchild->rchild;
08278         grandchild->rchild = splaytree;
08279       }
08280       child->rchild = grandchild->lchild;
08281       grandchild->lchild = child;
08282     } else {
08283       if (rightofroot) {
08284         splaytree->rchild = grandchild->lchild;
08285         grandchild->lchild = splaytree;
08286       } else {
08287         splaytree->lchild = child->rchild;
08288         child->rchild = splaytree;
08289       }
08290       child->lchild = grandchild->rchild;
08291       grandchild->rchild = child;
08292     }
08293     return grandchild;
08294   } else {
08295     lefttree = splay(splaytree->lchild, searchpoint, searchtri);
08296     righttree = splay(splaytree->rchild, searchpoint, searchtri);
08297 
08298     pooldealloc(&splaynodes, (VOID *) splaytree);
08299     if (lefttree == (struct splaynode *) NULL) {
08300       return righttree;
08301     } else if (righttree == (struct splaynode *) NULL) {
08302       return lefttree;
08303     } else if (lefttree->rchild == (struct splaynode *) NULL) {
08304       lefttree->rchild = righttree->lchild;
08305       righttree->lchild = lefttree;
08306       return righttree;
08307     } else if (righttree->lchild == (struct splaynode *) NULL) {
08308       righttree->lchild = lefttree->rchild;
08309       lefttree->rchild = righttree;
08310       return lefttree;
08311     } else {
08312 /*      printf("Holy Toledo!!!\n"); */
08313       leftright = lefttree->rchild;
08314       while (leftright->rchild != (struct splaynode *) NULL) {
08315         leftright = leftright->rchild;
08316       }
08317       leftright->rchild = righttree;
08318       return lefttree;
08319     }
08320   }
08321 }
08322 
08323 #endif /* not REDUCED */
08324 
08325 #ifndef REDUCED
08326 
08327 struct splaynode *splayinsert(splayroot, newkey, searchpoint)
08328 struct splaynode *splayroot;
08329 struct triedge *newkey;
08330 point searchpoint;
08331 {
08332   struct splaynode *newsplaynode;
08333 
08334   newsplaynode = (struct splaynode *) poolalloc(&splaynodes);
08335   triedgecopy(*newkey, newsplaynode->keyedge);
08336   dest(*newkey, newsplaynode->keydest);
08337   if (splayroot == (struct splaynode *) NULL) {
08338     newsplaynode->lchild = (struct splaynode *) NULL;
08339     newsplaynode->rchild = (struct splaynode *) NULL;
08340   } else if (rightofhyperbola(&splayroot->keyedge, searchpoint)) {
08341     newsplaynode->lchild = splayroot;
08342     newsplaynode->rchild = splayroot->rchild;
08343     splayroot->rchild = (struct splaynode *) NULL;
08344   } else {
08345     newsplaynode->lchild = splayroot->lchild;
08346     newsplaynode->rchild = splayroot;
08347     splayroot->lchild = (struct splaynode *) NULL;
08348   }
08349   return newsplaynode;
08350 }
08351 
08352 #endif /* not REDUCED */
08353 
08354 #ifndef REDUCED
08355 
08356 struct splaynode *circletopinsert(splayroot, newkey, pa, pb, pc, topy)
08357 struct splaynode *splayroot;
08358 struct triedge *newkey;
08359 point pa;
08360 point pb;
08361 point pc;
08362 REAL topy;
08363 {
08364   REAL ccwabc;
08365   REAL xac, yac, xbc, ybc;
08366   REAL aclen2, bclen2;
08367   REAL searchpoint[2];
08368   struct triedge dummytri;
08369 
08370   ccwabc = counterclockwise(pa, pb, pc);
08371   xac = pa[0] - pc[0];
08372   yac = pa[1] - pc[1];
08373   xbc = pb[0] - pc[0];
08374   ybc = pb[1] - pc[1];
08375   aclen2 = xac * xac + yac * yac;
08376   bclen2 = xbc * xbc + ybc * ybc;
08377   searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
08378   searchpoint[1] = topy;
08379   return splayinsert(splay(splayroot, (point) searchpoint, &dummytri), newkey,
08380                      (point) searchpoint);
08381 }
08382 
08383 #endif /* not REDUCED */
08384 
08385 #ifndef REDUCED
08386 
08387 struct splaynode *frontlocate(splayroot, bottommost, searchpoint, searchtri,
08388                               farright)
08389 struct splaynode *splayroot;
08390 struct triedge *bottommost;
08391 point searchpoint;
08392 struct triedge *searchtri;
08393 int *farright;
08394 {
08395   int farrightflag;
08396   triangle ptr;                       /* Temporary variable used by onext(). */
08397 
08398   triedgecopy(*bottommost, *searchtri);
08399   splayroot = splay(splayroot, searchpoint, searchtri);
08400 
08401   farrightflag = 0;
08402   while (!farrightflag && rightofhyperbola(searchtri, searchpoint)) {
08403     onextself(*searchtri);
08404     farrightflag = triedgeequal(*searchtri, *bottommost);
08405   }
08406   *farright = farrightflag;
08407   return splayroot;
08408 }
08409 
08410 #endif /* not REDUCED */
08411 
08412 #ifndef REDUCED
08413 
08414 long sweeplinedelaunay()
08415 {
08416   struct