PageRenderTime 71ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 2ms

/contrib/gtkgensurf/triangle.c

https://gitlab.com/illwieckz/netradiant
C | 12631 lines | 8857 code | 874 blank | 2900 comment | 1792 complexity | 8758741fd6acfa480a2e2328d8de068f MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, LGPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. #define ANSI_DECLARATORS
  2. /*****************************************************************************/
  3. /* */
  4. /* 888888888 ,o, / 888 */
  5. /* 888 88o88o " o8888o 88o8888o o88888o 888 o88888o */
  6. /* 888 888 888 88b 888 888 888 888 888 d888 88b */
  7. /* 888 888 888 o88^o888 888 888 "88888" 888 8888oo888 */
  8. /* 888 888 888 C888 888 888 888 / 888 q888 */
  9. /* 888 888 888 "88o^888 888 888 Cb 888 "88oooo" */
  10. /* "8oo8D */
  11. /* */
  12. /* A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator. */
  13. /* (triangle.c) */
  14. /* */
  15. /* Version 1.3 */
  16. /* July 19, 1996 */
  17. /* */
  18. /* Copyright 1996 */
  19. /* Jonathan Richard Shewchuk */
  20. /* School of Computer Science */
  21. /* Carnegie Mellon University */
  22. /* 5000 Forbes Avenue */
  23. /* Pittsburgh, Pennsylvania 15213-3891 */
  24. /* jrs@cs.cmu.edu */
  25. /* */
  26. /* This program may be freely redistributed under the condition that the */
  27. /* copyright notices (including this entire header and the copyright */
  28. /* notice printed when the `-h' switch is selected) are not removed, and */
  29. /* no compensation is received. Private, research, and institutional */
  30. /* use is free. You may distribute modified versions of this code UNDER */
  31. /* THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE */
  32. /* SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE */
  33. /* AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR */
  34. /* NOTICE IS GIVEN OF THE MODIFICATIONS. Distribution of this code as */
  35. /* part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT */
  36. /* WITH THE AUTHOR. (If you are not directly supplying this code to a */
  37. /* customer, and you are instead telling them how they can obtain it for */
  38. /* free, then you are not required to make any arrangement with me.) */
  39. /* */
  40. /* Hypertext instructions for Triangle are available on the Web at */
  41. /* */
  42. /* http://www.cs.cmu.edu/~quake/triangle.html */
  43. /* */
  44. /* Some of the references listed below are marked [*]. These are available */
  45. /* for downloading from the Web page */
  46. /* */
  47. /* http://www.cs.cmu.edu/~quake/triangle.research.html */
  48. /* */
  49. /* A paper discussing some aspects of Triangle is available. See Jonathan */
  50. /* Richard Shewchuk, "Triangle: Engineering a 2D Quality Mesh Generator */
  51. /* and Delaunay Triangulator," First Workshop on Applied Computational */
  52. /* Geometry, ACM, May 1996. [*] */
  53. /* */
  54. /* Triangle was created as part of the Archimedes project in the School of */
  55. /* Computer Science at Carnegie Mellon University. Archimedes is a */
  56. /* system for compiling parallel finite element solvers. For further */
  57. /* information, see Anja Feldmann, Omar Ghattas, John R. Gilbert, Gary L. */
  58. /* Miller, David R. O'Hallaron, Eric J. Schwabe, Jonathan R. Shewchuk, */
  59. /* and Shang-Hua Teng, "Automated Parallel Solution of Unstructured PDE */
  60. /* Problems." To appear in Communications of the ACM, we hope. */
  61. /* */
  62. /* The quality mesh generation algorithm is due to Jim Ruppert, "A */
  63. /* Delaunay Refinement Algorithm for Quality 2-Dimensional Mesh */
  64. /* Generation," Journal of Algorithms 18(3):548-585, May 1995. [*] */
  65. /* */
  66. /* My implementation of the divide-and-conquer and incremental Delaunay */
  67. /* triangulation algorithms follows closely the presentation of Guibas */
  68. /* and Stolfi, even though I use a triangle-based data structure instead */
  69. /* of their quad-edge data structure. (In fact, I originally implemented */
  70. /* Triangle using the quad-edge data structure, but switching to a */
  71. /* triangle-based data structure sped Triangle by a factor of two.) The */
  72. /* mesh manipulation primitives and the two aforementioned Delaunay */
  73. /* triangulation algorithms are described by Leonidas J. Guibas and Jorge */
  74. /* Stolfi, "Primitives for the Manipulation of General Subdivisions and */
  75. /* the Computation of Voronoi Diagrams," ACM Transactions on Graphics */
  76. /* 4(2):74-123, April 1985. */
  77. /* */
  78. /* Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai */
  79. /* Lee and Bruce J. Schachter, "Two Algorithms for Constructing the */
  80. /* Delaunay Triangulation," International Journal of Computer and */
  81. /* Information Science 9(3):219-242, 1980. The idea to improve the */
  82. /* divide-and-conquer algorithm by alternating between vertical and */
  83. /* horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and- */
  84. /* Conquer Algorithm for Constructing Delaunay Triangulations," */
  85. /* Algorithmica 2(2):137-151, 1987. */
  86. /* */
  87. /* The incremental insertion algorithm was first proposed by C. L. Lawson, */
  88. /* "Software for C1 Surface Interpolation," in Mathematical Software III, */
  89. /* John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977. */
  90. /* For point location, I use the algorithm of Ernst P. Mucke, Isaac */
  91. /* Saias, and Binhai Zhu, "Fast Randomized Point Location Without */
  92. /* Preprocessing in Two- and Three-dimensional Delaunay Triangulations," */
  93. /* Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
  94. /* ACM, May 1996. [*] If I were to randomize the order of point */
  95. /* insertion (I currently don't bother), their result combined with the */
  96. /* result of Leonidas J. Guibas, Donald E. Knuth, and Micha Sharir, */
  97. /* "Randomized Incremental Construction of Delaunay and Voronoi */
  98. /* Diagrams," Algorithmica 7(4):381-413, 1992, would yield an expected */
  99. /* O(n^{4/3}) bound on running time. */
  100. /* */
  101. /* The O(n log n) sweepline Delaunay triangulation algorithm is taken from */
  102. /* Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams", */
  103. /* Algorithmica 2(2):153-174, 1987. A random sample of edges on the */
  104. /* boundary of the triangulation are maintained in a splay tree for the */
  105. /* purpose of point location. Splay trees are described by Daniel */
  106. /* Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
  107. /* Trees," Journal of the ACM 32(3):652-686, July 1985. */
  108. /* */
  109. /* The algorithms for exact computation of the signs of determinants are */
  110. /* described in Jonathan Richard Shewchuk, "Adaptive Precision Floating- */
  111. /* Point Arithmetic and Fast Robust Geometric Predicates," Technical */
  112. /* Report CMU-CS-96-140, School of Computer Science, Carnegie Mellon */
  113. /* University, Pittsburgh, Pennsylvania, May 1996. [*] (Submitted to */
  114. /* Discrete & Computational Geometry.) An abbreviated version appears as */
  115. /* Jonathan Richard Shewchuk, "Robust Adaptive Floating-Point Geometric */
  116. /* Predicates," Proceedings of the Twelfth Annual Symposium on Computa- */
  117. /* tional Geometry, ACM, May 1996. [*] Many of the ideas for my exact */
  118. /* arithmetic routines originate with Douglas M. Priest, "Algorithms for */
  119. /* Arbitrary Precision Floating Point Arithmetic," Tenth Symposium on */
  120. /* Computer Arithmetic, 132-143, IEEE Computer Society Press, 1991. [*] */
  121. /* Many of the ideas for the correct evaluation of the signs of */
  122. /* determinants are taken from Steven Fortune and Christopher J. Van Wyk, */
  123. /* "Efficient Exact Arithmetic for Computational Geometry," Proceedings */
  124. /* of the Ninth Annual Symposium on Computational Geometry, ACM, */
  125. /* pp. 163-172, May 1993, and from Steven Fortune, "Numerical Stability */
  126. /* of Algorithms for 2D Delaunay Triangulations," International Journal */
  127. /* of Computational Geometry & Applications 5(1-2):193-213, March-June */
  128. /* 1995. */
  129. /* */
  130. /* For definitions of and results involving Delaunay triangulations, */
  131. /* constrained and conforming versions thereof, and other aspects of */
  132. /* triangular mesh generation, see the excellent survey by Marshall Bern */
  133. /* and David Eppstein, "Mesh Generation and Optimal Triangulation," in */
  134. /* Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang, */
  135. /* editors, World Scientific, Singapore, pp. 23-90, 1992. */
  136. /* */
  137. /* The time for incrementally adding PSLG (planar straight line graph) */
  138. /* segments to create a constrained Delaunay triangulation is probably */
  139. /* O(n^2) per segment in the worst case and O(n) per edge in the common */
  140. /* case, where n is the number of triangles that intersect the segment */
  141. /* before it is inserted. This doesn't count point location, which can */
  142. /* be much more expensive. (This note does not apply to conforming */
  143. /* Delaunay triangulations, for which a different method is used to */
  144. /* insert segments.) */
  145. /* */
  146. /* The time for adding segments to a conforming Delaunay triangulation is */
  147. /* not clear, but does not depend upon n alone. In some cases, very */
  148. /* small features (like a point lying next to a segment) can cause a */
  149. /* single segment to be split an arbitrary number of times. Of course, */
  150. /* floating-point precision is a practical barrier to how much this can */
  151. /* happen. */
  152. /* */
  153. /* The time for deleting a point from a Delaunay triangulation is O(n^2) in */
  154. /* the worst case and O(n) in the common case, where n is the degree of */
  155. /* the point being deleted. I could improve this to expected O(n) time */
  156. /* by "inserting" the neighboring vertices in random order, but n is */
  157. /* usually quite small, so it's not worth the bother. (The O(n) time */
  158. /* for random insertion follows from L. Paul Chew, "Building Voronoi */
  159. /* Diagrams for Convex Polygons in Linear Expected Time," Technical */
  160. /* Report PCS-TR90-147, Department of Mathematics and Computer Science, */
  161. /* Dartmouth College, 1990. */
  162. /* */
  163. /* Ruppert's Delaunay refinement algorithm typically generates triangles */
  164. /* at a linear rate (constant time per triangle) after the initial */
  165. /* triangulation is formed. There may be pathological cases where more */
  166. /* time is required, but these never arise in practice. */
  167. /* */
  168. /* The segment intersection formulae are straightforward. If you want to */
  169. /* see them derived, see Franklin Antonio. "Faster Line Segment */
  170. /* Intersection." In Graphics Gems III (David Kirk, editor), pp. 199- */
  171. /* 202. Academic Press, Boston, 1992. */
  172. /* */
  173. /* If you make any improvements to this code, please please please let me */
  174. /* know, so that I may obtain the improvements. Even if you don't change */
  175. /* the code, I'd still love to hear what it's being used for. */
  176. /* */
  177. /* Disclaimer: Neither I nor Carnegie Mellon warrant this code in any way */
  178. /* whatsoever. This code is provided "as-is". Use at your own risk. */
  179. /* */
  180. /*****************************************************************************/
  181. /* For single precision (which will save some memory and reduce paging), */
  182. /* define the symbol SINGLE by using the -DSINGLE compiler switch or by */
  183. /* writing "#define SINGLE" below. */
  184. /* */
  185. /* For double precision (which will allow you to refine meshes to a smaller */
  186. /* edge length), leave SINGLE undefined. */
  187. /* */
  188. /* Double precision uses more memory, but improves the resolution of the */
  189. /* meshes you can generate with Triangle. It also reduces the likelihood */
  190. /* of a floating exception due to overflow. Finally, it is much faster */
  191. /* than single precision on 64-bit architectures like the DEC Alpha. I */
  192. /* recommend double precision unless you want to generate a mesh for which */
  193. /* you do not have enough memory. */
  194. #define SINGLE
  195. #ifdef SINGLE
  196. #define REAL float
  197. #else /* not SINGLE */
  198. #define REAL double
  199. #endif /* not SINGLE */
  200. /* If yours is not a Unix system, define the NO_TIMER compiler switch to */
  201. /* remove the Unix-specific timing code. */
  202. #define NO_TIMER
  203. /* To insert lots of self-checks for internal errors, define the SELF_CHECK */
  204. /* symbol. This will slow down the program significantly. It is best to */
  205. /* define the symbol using the -DSELF_CHECK compiler switch, but you could */
  206. /* write "#define SELF_CHECK" below. If you are modifying this code, I */
  207. /* recommend you turn self-checks on. */
  208. /* #define SELF_CHECK */
  209. /* To compile Triangle as a callable object library (triangle.o), define the */
  210. /* TRILIBRARY symbol. Read the file triangle.h for details on how to call */
  211. /* the procedure triangulate() that results. */
  212. #define TRILIBRARY
  213. /* It is possible to generate a smaller version of Triangle using one or */
  214. /* both of the following symbols. Define the REDUCED symbol to eliminate */
  215. /* all features that are primarily of research interest; specifically, the */
  216. /* -i, -F, -s, and -C switches. Define the CDT_ONLY symbol to eliminate */
  217. /* all meshing algorithms above and beyond constrained Delaunay */
  218. /* triangulation; specifically, the -r, -q, -a, -S, and -s switches. */
  219. /* These reductions are most likely to be useful when generating an object */
  220. /* library (triangle.o) by defining the TRILIBRARY symbol. */
  221. #define REDUCED
  222. #define CDT_ONLY
  223. /* On some machines, the exact arithmetic routines might be defeated by the */
  224. /* use of internal extended precision floating-point registers. Sometimes */
  225. /* this problem can be fixed by defining certain values to be volatile, */
  226. /* thus forcing them to be stored to memory and rounded off. This isn't */
  227. /* a great solution, though, as it slows Triangle down. */
  228. /* */
  229. /* To try this out, write "#define INEXACT volatile" below. Normally, */
  230. /* however, INEXACT should be defined to be nothing. ("#define INEXACT".) */
  231. #define INEXACT /* Nothing */
  232. /* #define INEXACT volatile */
  233. /* Maximum number of characters in a file name (including the null). */
  234. #define FILENAMESIZE 512
  235. /* Maximum number of characters in a line read from a file (including the */
  236. /* null). */
  237. #define INPUTLINESIZE 512
  238. /* For efficiency, a variety of data structures are allocated in bulk. The */
  239. /* following constants determine how many of each structure is allocated */
  240. /* at once. */
  241. #define TRIPERBLOCK 4092 /* Number of triangles allocated at once. */
  242. #define SHELLEPERBLOCK 508 /* Number of shell edges allocated at once. */
  243. #define POINTPERBLOCK 4092 /* Number of points allocated at once. */
  244. #define VIRUSPERBLOCK 1020 /* Number of virus triangles allocated at once. */
  245. /* Number of encroached segments allocated at once. */
  246. #define BADSEGMENTPERBLOCK 252
  247. /* Number of skinny triangles allocated at once. */
  248. #define BADTRIPERBLOCK 4092
  249. /* Number of splay tree nodes allocated at once. */
  250. #define SPLAYNODEPERBLOCK 508
  251. /* The point marker DEADPOINT is an arbitrary number chosen large enough to */
  252. /* (hopefully) not conflict with user boundary markers. Make sure that it */
  253. /* is small enough to fit into your machine's integer size. */
  254. #define DEADPOINT -1073741824
  255. /* The next line is used to outsmart some very stupid compilers. If your */
  256. /* compiler is smarter, feel free to replace the "int" with "void". */
  257. /* Not that it matters. */
  258. #define VOID int
  259. /* Two constants for algorithms based on random sampling. Both constants */
  260. /* have been chosen empirically to optimize their respective algorithms. */
  261. /* Used for the point location scheme of Mucke, Saias, and Zhu, to decide */
  262. /* how large a random sample of triangles to inspect. */
  263. #define SAMPLEFACTOR 11
  264. /* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
  265. /* of boundary edges should be maintained in the splay tree for point */
  266. /* location on the front. */
  267. #define SAMPLERATE 10
  268. /* A number that speaks for itself, every kissable digit. */
  269. #define PI 3.141592653589793238462643383279502884197169399375105820974944592308
  270. /* Another fave. */
  271. #define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
  272. /* And here's one for those of you who are intimidated by math. */
  273. #define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
  274. #include <stdio.h>
  275. #include <string.h>
  276. #include <math.h>
  277. #ifndef NO_TIMER
  278. #include <sys/time.h>
  279. #endif /* NO_TIMER */
  280. #ifdef TRILIBRARY
  281. #include "triangle.h"
  282. #endif /* TRILIBRARY */
  283. /* The following obscenity seems to be necessary to ensure that this program */
  284. /* will port to Dec Alphas running OSF/1, because their stdio.h file commits */
  285. /* the unpardonable sin of including stdlib.h. Hence, malloc(), free(), and */
  286. /* exit() may or may not already be defined at this point. I declare these */
  287. /* functions explicitly because some non-ANSI C compilers lack stdlib.h. */
  288. #ifndef _STDLIB_H_
  289. extern void *malloc();
  290. extern void free();
  291. extern void exit();
  292. extern double strtod();
  293. extern long strtol();
  294. #endif /* _STDLIB_H_ */
  295. /* A few forward declarations. */
  296. void poolrestart();
  297. #ifndef TRILIBRARY
  298. char *readline();
  299. char *findfield();
  300. #endif /* not TRILIBRARY */
  301. /* Labels that signify whether a record consists primarily of pointers or of */
  302. /* floating-point words. Used to make decisions about data alignment. */
  303. enum wordtype {POINTER, FLOATINGPOINT};
  304. /* Labels that signify the result of point location. The result of a */
  305. /* search indicates that the point falls in the interior of a triangle, on */
  306. /* an edge, on a vertex, or outside the mesh. */
  307. enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
  308. /* Labels that signify the result of site insertion. The result indicates */
  309. /* that the point was inserted with complete success, was inserted but */
  310. /* encroaches on a segment, was not inserted because it lies on a segment, */
  311. /* or was not inserted because another point occupies the same location. */
  312. enum insertsiteresult {SUCCESSFULPOINT, ENCROACHINGPOINT, VIOLATINGPOINT,
  313. DUPLICATEPOINT};
  314. /* Labels that signify the result of direction finding. The result */
  315. /* indicates that a segment connecting the two query points falls within */
  316. /* the direction triangle, along the left edge of the direction triangle, */
  317. /* or along the right edge of the direction triangle. */
  318. enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
  319. /* Labels that signify the result of the circumcenter computation routine. */
  320. /* The return value indicates which edge of the triangle is shortest. */
  321. enum circumcenterresult {OPPOSITEORG, OPPOSITEDEST, OPPOSITEAPEX};
  322. /*****************************************************************************/
  323. /* */
  324. /* The basic mesh data structures */
  325. /* */
  326. /* There are three: points, triangles, and shell edges (abbreviated */
  327. /* `shelle'). These three data structures, linked by pointers, comprise */
  328. /* the mesh. A point simply represents a point in space and its properties.*/
  329. /* A triangle is a triangle. A shell edge is a special data structure used */
  330. /* to represent impenetrable segments in the mesh (including the outer */
  331. /* boundary, boundaries of holes, and internal boundaries separating two */
  332. /* triangulated regions). Shell edges represent boundaries defined by the */
  333. /* user that triangles may not lie across. */
  334. /* */
  335. /* A triangle consists of a list of three vertices, a list of three */
  336. /* adjoining triangles, a list of three adjoining shell edges (when shell */
  337. /* edges are used), an arbitrary number of optional user-defined floating- */
  338. /* point attributes, and an optional area constraint. The latter is an */
  339. /* upper bound on the permissible area of each triangle in a region, used */
  340. /* for mesh refinement. */
  341. /* */
  342. /* For a triangle on a boundary of the mesh, some or all of the neighboring */
  343. /* triangles may not be present. For a triangle in the interior of the */
  344. /* mesh, often no neighboring shell edges are present. Such absent */
  345. /* triangles and shell edges are never represented by NULL pointers; they */
  346. /* are represented by two special records: `dummytri', the triangle that */
  347. /* fills "outer space", and `dummysh', the omnipresent shell edge. */
  348. /* `dummytri' and `dummysh' are used for several reasons; for instance, */
  349. /* they can be dereferenced and their contents examined without causing the */
  350. /* memory protection exception that would occur if NULL were dereferenced. */
  351. /* */
  352. /* However, it is important to understand that a triangle includes other */
  353. /* information as well. The pointers to adjoining vertices, triangles, and */
  354. /* shell edges are ordered in a way that indicates their geometric relation */
  355. /* to each other. Furthermore, each of these pointers contains orientation */
  356. /* information. Each pointer to an adjoining triangle indicates which face */
  357. /* of that triangle is contacted. Similarly, each pointer to an adjoining */
  358. /* shell edge indicates which side of that shell edge is contacted, and how */
  359. /* the shell edge is oriented relative to the triangle. */
  360. /* */
  361. /* Shell edges are found abutting edges of triangles; either sandwiched */
  362. /* between two triangles, or resting against one triangle on an exterior */
  363. /* boundary or hole boundary. */
  364. /* */
  365. /* A shell edge consists of a list of two vertices, a list of two */
  366. /* adjoining shell edges, and a list of two adjoining triangles. One of */
  367. /* the two adjoining triangles may not be present (though there should */
  368. /* always be one), and neighboring shell edges might not be present. */
  369. /* Shell edges also store a user-defined integer "boundary marker". */
  370. /* Typically, this integer is used to indicate what sort of boundary */
  371. /* conditions are to be applied at that location in a finite element */
  372. /* simulation. */
  373. /* */
  374. /* Like triangles, shell edges maintain information about the relative */
  375. /* orientation of neighboring objects. */
  376. /* */
  377. /* Points are relatively simple. A point is a list of floating point */
  378. /* numbers, starting with the x, and y coordinates, followed by an */
  379. /* arbitrary number of optional user-defined floating-point attributes, */
  380. /* followed by an integer boundary marker. During the segment insertion */
  381. /* phase, there is also a pointer from each point to a triangle that may */
  382. /* contain it. Each pointer is not always correct, but when one is, it */
  383. /* speeds up segment insertion. These pointers are assigned values once */
  384. /* at the beginning of the segment insertion phase, and are not used or */
  385. /* updated at any other time. Edge swapping during segment insertion will */
  386. /* render some of them incorrect. Hence, don't rely upon them for */
  387. /* anything. For the most part, points do not have any information about */
  388. /* what triangles or shell edges they are linked to. */
  389. /* */
  390. /*****************************************************************************/
  391. /*****************************************************************************/
  392. /* */
  393. /* Handles */
  394. /* */
  395. /* The oriented triangle (`triedge') and oriented shell edge (`edge') data */
  396. /* structures defined below do not themselves store any part of the mesh. */
  397. /* The mesh itself is made of `triangle's, `shelle's, and `point's. */
  398. /* */
  399. /* Oriented triangles and oriented shell edges will usually be referred to */
  400. /* as "handles". A handle is essentially a pointer into the mesh; it */
  401. /* allows you to "hold" one particular part of the mesh. Handles are used */
  402. /* to specify the regions in which one is traversing and modifying the mesh.*/
  403. /* A single `triangle' may be held by many handles, or none at all. (The */
  404. /* latter case is not a memory leak, because the triangle is still */
  405. /* connected to other triangles in the mesh.) */
  406. /* */
  407. /* A `triedge' is a handle that holds a triangle. It holds a specific side */
  408. /* of the triangle. An `edge' is a handle that holds a shell edge. It */
  409. /* holds either the left or right side of the edge. */
  410. /* */
  411. /* Navigation about the mesh is accomplished through a set of mesh */
  412. /* manipulation primitives, further below. Many of these primitives take */
  413. /* a handle and produce a new handle that holds the mesh near the first */
  414. /* handle. Other primitives take two handles and glue the corresponding */
  415. /* parts of the mesh together. The exact position of the handles is */
  416. /* important. For instance, when two triangles are glued together by the */
  417. /* bond() primitive, they are glued by the sides on which the handles lie. */
  418. /* */
  419. /* Because points have no information about which triangles they are */
  420. /* attached to, I commonly represent a point by use of a handle whose */
  421. /* origin is the point. A single handle can simultaneously represent a */
  422. /* triangle, an edge, and a point. */
  423. /* */
  424. /*****************************************************************************/
  425. /* The triangle data structure. Each triangle contains three pointers to */
  426. /* adjoining triangles, plus three pointers to vertex points, plus three */
  427. /* pointers to shell edges (defined below; these pointers are usually */
  428. /* `dummysh'). It may or may not also contain user-defined attributes */
  429. /* and/or a floating-point "area constraint". It may also contain extra */
  430. /* pointers for nodes, when the user asks for high-order elements. */
  431. /* Because the size and structure of a `triangle' is not decided until */
  432. /* runtime, I haven't simply defined the type `triangle' to be a struct. */
  433. typedef REAL **triangle; /* Really: typedef triangle *triangle */
  434. /* An oriented triangle: includes a pointer to a triangle and orientation. */
  435. /* The orientation denotes an edge of the triangle. Hence, there are */
  436. /* three possible orientations. By convention, each edge is always */
  437. /* directed to point counterclockwise about the corresponding triangle. */
  438. struct triedge {
  439. triangle *tri;
  440. int orient; /* Ranges from 0 to 2. */
  441. };
  442. /* The shell data structure. Each shell edge contains two pointers to */
  443. /* adjoining shell edges, plus two pointers to vertex points, plus two */
  444. /* pointers to adjoining triangles, plus one shell marker. */
  445. typedef REAL **shelle; /* Really: typedef shelle *shelle */
  446. /* An oriented shell edge: includes a pointer to a shell edge and an */
  447. /* orientation. The orientation denotes a side of the edge. Hence, there */
  448. /* are two possible orientations. By convention, the edge is always */
  449. /* directed so that the "side" denoted is the right side of the edge. */
  450. struct edge {
  451. shelle *sh;
  452. int shorient; /* Ranges from 0 to 1. */
  453. };
  454. /* The point data structure. Each point is actually an array of REALs. */
  455. /* The number of REALs is unknown until runtime. An integer boundary */
  456. /* marker, and sometimes a pointer to a triangle, is appended after the */
  457. /* REALs. */
  458. typedef REAL *point;
  459. /* A queue used to store encroached segments. Each segment's vertices are */
  460. /* stored so that one can check whether a segment is still the same. */
  461. struct badsegment {
  462. struct edge encsegment; /* An encroached segment. */
  463. point segorg, segdest; /* The two vertices. */
  464. struct badsegment *nextsegment; /* Pointer to next encroached segment. */
  465. };
  466. /* A queue used to store bad triangles. The key is the square of the cosine */
  467. /* of the smallest angle of the triangle. Each triangle's vertices are */
  468. /* stored so that one can check whether a triangle is still the same. */
  469. struct badface {
  470. struct triedge badfacetri; /* A bad triangle. */
  471. REAL key; /* cos^2 of smallest (apical) angle. */
  472. point faceorg, facedest, faceapex; /* The three vertices. */
  473. struct badface *nextface; /* Pointer to next bad triangle. */
  474. };
  475. /* A node in a heap used to store events for the sweepline Delaunay */
  476. /* algorithm. Nodes do not point directly to their parents or children in */
  477. /* the heap. Instead, each node knows its position in the heap, and can */
  478. /* look up its parent and children in a separate array. The `eventptr' */
  479. /* points either to a `point' or to a triangle (in encoded format, so that */
  480. /* an orientation is included). In the latter case, the origin of the */
  481. /* oriented triangle is the apex of a "circle event" of the sweepline */
  482. /* algorithm. To distinguish site events from circle events, all circle */
  483. /* events are given an invalid (smaller than `xmin') x-coordinate `xkey'. */
  484. struct event {
  485. REAL xkey, ykey; /* Coordinates of the event. */
  486. VOID *eventptr; /* Can be a point or the location of a circle event. */
  487. int heapposition; /* Marks this event's position in the heap. */
  488. };
  489. /* A node in the splay tree. Each node holds an oriented ghost triangle */
  490. /* that represents a boundary edge of the growing triangulation. When a */
  491. /* circle event covers two boundary edges with a triangle, so that they */
  492. /* are no longer boundary edges, those edges are not immediately deleted */
  493. /* from the tree; rather, they are lazily deleted when they are next */
  494. /* encountered. (Since only a random sample of boundary edges are kept */
  495. /* in the tree, lazy deletion is faster.) `keydest' is used to verify */
  496. /* that a triangle is still the same as when it entered the splay tree; if */
  497. /* it has been rotated (due to a circle event), it no longer represents a */
  498. /* boundary edge and should be deleted. */
  499. struct splaynode {
  500. struct triedge keyedge; /* Lprev of an edge on the front. */
  501. point keydest; /* Used to verify that splay node is still live. */
  502. struct splaynode *lchild, *rchild; /* Children in splay tree. */
  503. };
  504. /* A type used to allocate memory. firstblock is the first block of items. */
  505. /* nowblock is the block from which items are currently being allocated. */
  506. /* nextitem points to the next slab of free memory for an item. */
  507. /* deaditemstack is the head of a linked list (stack) of deallocated items */
  508. /* that can be recycled. unallocateditems is the number of items that */
  509. /* remain to be allocated from nowblock. */
  510. /* */
  511. /* Traversal is the process of walking through the entire list of items, and */
  512. /* is separate from allocation. Note that a traversal will visit items on */
  513. /* the "deaditemstack" stack as well as live items. pathblock points to */
  514. /* the block currently being traversed. pathitem points to the next item */
  515. /* to be traversed. pathitemsleft is the number of items that remain to */
  516. /* be traversed in pathblock. */
  517. /* */
  518. /* itemwordtype is set to POINTER or FLOATINGPOINT, and is used to suggest */
  519. /* what sort of word the record is primarily made up of. alignbytes */
  520. /* determines how new records should be aligned in memory. itembytes and */
  521. /* itemwords are the length of a record in bytes (after rounding up) and */
  522. /* words. itemsperblock is the number of items allocated at once in a */
  523. /* single block. items is the number of currently allocated items. */
  524. /* maxitems is the maximum number of items that have been allocated at */
  525. /* once; it is the current number of items plus the number of records kept */
  526. /* on deaditemstack. */
  527. struct memorypool {
  528. VOID **firstblock, **nowblock;
  529. VOID *nextitem;
  530. VOID *deaditemstack;
  531. VOID **pathblock;
  532. VOID *pathitem;
  533. enum wordtype itemwordtype;
  534. int alignbytes;
  535. int itembytes, itemwords;
  536. int itemsperblock;
  537. long items, maxitems;
  538. int unallocateditems;
  539. int pathitemsleft;
  540. };
  541. /* Variables used to allocate memory for triangles, shell edges, points, */
  542. /* viri (triangles being eaten), bad (encroached) segments, bad (skinny */
  543. /* or too large) triangles, and splay tree nodes. */
  544. static struct memorypool triangles;
  545. static struct memorypool shelles;
  546. static struct memorypool points;
  547. static struct memorypool viri;
  548. static struct memorypool badsegments;
  549. static struct memorypool badtriangles;
  550. static struct memorypool splaynodes;
  551. /* Variables that maintain the bad triangle queues. The tails are pointers */
  552. /* to the pointers that have to be filled in to enqueue an item. */
  553. static struct badface *queuefront[64];
  554. static struct badface **queuetail[64];
  555. static REAL xmin, xmax, ymin, ymax; /* x and y bounds. */
  556. static REAL xminextreme; /* Nonexistent x value used as a flag in sweepline. */
  557. static int inpoints; /* Number of input points. */
  558. static int inelements; /* Number of input triangles. */
  559. static int insegments; /* Number of input segments. */
  560. static int holes; /* Number of input holes. */
  561. static int regions; /* Number of input regions. */
  562. static long edges; /* Number of output edges. */
  563. static int mesh_dim; /* Dimension (ought to be 2). */
  564. static int nextras; /* Number of attributes per point. */
  565. static int eextras; /* Number of attributes per triangle. */
  566. static long hullsize; /* Number of edges of convex hull. */
  567. static int triwords; /* Total words per triangle. */
  568. static int shwords; /* Total words per shell edge. */
  569. static int pointmarkindex; /* Index to find boundary marker of a point. */
  570. static int point2triindex; /* Index to find a triangle adjacent to a point. */
  571. static int highorderindex; /* Index to find extra nodes for high-order elements. */
  572. static int elemattribindex; /* Index to find attributes of a triangle. */
  573. static int areaboundindex; /* Index to find area bound of a triangle. */
  574. static int checksegments; /* Are there segments in the triangulation yet? */
  575. static int readnodefile; /* Has a .node file been read? */
  576. static long samples; /* Number of random samples for point location. */
  577. static unsigned long randomseed; /* Current random number seed. */
  578. static REAL splitter; /* Used to split REAL factors for exact multiplication. */
  579. static REAL epsilon; /* Floating-point machine epsilon. */
  580. static REAL resulterrbound;
  581. static REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
  582. static REAL iccerrboundA, iccerrboundB, iccerrboundC;
  583. static long incirclecount; /* Number of incircle tests performed. */
  584. static long counterclockcount; /* Number of counterclockwise tests performed. */
  585. static long hyperbolacount; /* Number of right-of-hyperbola tests performed. */
  586. static long circumcentercount; /* Number of circumcenter calculations performed. */
  587. static long circletopcount; /* Number of circle top calculations performed. */
  588. /* Switches for the triangulator. */
  589. /* poly: -p switch. refine: -r switch. */
  590. /* quality: -q switch. */
  591. /* minangle: minimum angle bound, specified after -q switch. */
  592. /* goodangle: cosine squared of minangle. */
  593. /* vararea: -a switch without number. */
  594. /* fixedarea: -a switch with number. */
  595. /* maxarea: maximum area bound, specified after -a switch. */
  596. /* regionattrib: -A switch. convex: -c switch. */
  597. /* firstnumber: inverse of -z switch. All items are numbered starting */
  598. /* from firstnumber. */
  599. /* edgesout: -e switch. voronoi: -v switch. */
  600. /* neighbors: -n switch. geomview: -g switch. */
  601. /* nobound: -B switch. nopolywritten: -P switch. */
  602. /* nonodewritten: -N switch. noelewritten: -E switch. */
  603. /* noiterationnum: -I switch. noholes: -O switch. */
  604. /* noexact: -X switch. */
  605. /* order: element order, specified after -o switch. */
  606. /* nobisect: count of how often -Y switch is selected. */
  607. /* steiner: maximum number of Steiner points, specified after -S switch. */
  608. /* steinerleft: number of Steiner points not yet used. */
  609. /* incremental: -i switch. sweepline: -F switch. */
  610. /* dwyer: inverse of -l switch. */
  611. /* splitseg: -s switch. */
  612. /* docheck: -C switch. */
  613. /* quiet: -Q switch. verbose: count of how often -V switch is selected. */
  614. /* useshelles: -p, -r, -q, or -c switch; determines whether shell edges */
  615. /* are used at all. */
  616. /* */
  617. /* Read the instructions to find out the meaning of these switches. */
  618. static int poly, refine, quality, vararea, fixedarea, regionattrib, convex;
  619. static int firstnumber;
  620. static int edgesout, voronoi, neighbors, geomview;
  621. static int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
  622. static int noholes, noexact;
  623. static int incremental, sweepline, dwyer;
  624. static int splitseg;
  625. static int docheck;
  626. static int quiet, verbose;
  627. static int useshelles;
  628. static int order;
  629. static int nobisect;
  630. static int steiner, steinerleft;
  631. static REAL minangle, goodangle;
  632. static REAL maxarea;
  633. /* Variables for file names. */
  634. #ifndef TRILIBRARY
  635. char innodefilename[FILENAMESIZE];
  636. char inelefilename[FILENAMESIZE];
  637. char inpolyfilename[FILENAMESIZE];
  638. char areafilename[FILENAMESIZE];
  639. char outnodefilename[FILENAMESIZE];
  640. char outelefilename[FILENAMESIZE];
  641. char outpolyfilename[FILENAMESIZE];
  642. char edgefilename[FILENAMESIZE];
  643. char vnodefilename[FILENAMESIZE];
  644. char vedgefilename[FILENAMESIZE];
  645. char neighborfilename[FILENAMESIZE];
  646. char offfilename[FILENAMESIZE];
  647. #endif /* not TRILIBRARY */
  648. /* Triangular bounding box points. */
  649. static point infpoint1, infpoint2, infpoint3;
  650. /* Pointer to the `triangle' that occupies all of "outer space". */
  651. static triangle *dummytri;
  652. static triangle *dummytribase; /* Keep base address so we can free() it later. */
  653. /* Pointer to the omnipresent shell edge. Referenced by any triangle or */
  654. /* shell edge that isn't really connected to a shell edge at that */
  655. /* location. */
  656. static shelle *dummysh;
  657. static shelle *dummyshbase; /* Keep base address so we can free() it later. */
  658. /* Pointer to a recently visited triangle. Improves point location if */
  659. /* proximate points are inserted sequentially. */
  660. static struct triedge recenttri;
  661. /*****************************************************************************/
  662. /* */
  663. /* Mesh manipulation primitives. Each triangle contains three pointers to */
  664. /* other triangles, with orientations. Each pointer points not to the */
  665. /* first byte of a triangle, but to one of the first three bytes of a */
  666. /* triangle. It is necessary to extract both the triangle itself and the */
  667. /* orientation. To save memory, I keep both pieces of information in one */
  668. /* pointer. To make this possible, I assume that all triangles are aligned */
  669. /* to four-byte boundaries. The `decode' routine below decodes a pointer, */
  670. /* extracting an orientation (in the range 0 to 2) and a pointer to the */
  671. /* beginning of a triangle. The `encode' routine compresses a pointer to a */
  672. /* triangle and an orientation into a single pointer. My assumptions that */
  673. /* triangles are four-byte-aligned and that the `unsigned long' type is */
  674. /* long enough to hold a pointer are two of the few kludges in this program.*/
  675. /* */
  676. /* Shell edges are manipulated similarly. A pointer to a shell edge */
  677. /* carries both an address and an orientation in the range 0 to 1. */
  678. /* */
  679. /* The other primitives take an oriented triangle or oriented shell edge, */
  680. /* and return an oriented triangle or oriented shell edge or point; or they */
  681. /* change the connections in the data structure. */
  682. /* */
  683. /*****************************************************************************/
  684. /********* Mesh manipulation primitives begin here *********/
  685. /** **/
  686. /** **/
  687. /* Fast lookup arrays to speed some of the mesh manipulation primitives. */
  688. int plus1mod3[3] = {1, 2, 0};
  689. int minus1mod3[3] = {2, 0, 1};
  690. /********* Primitives for triangles *********/
  691. /* */
  692. /* */
  693. /* decode() converts a pointer to an oriented triangle. The orientation is */
  694. /* extracted from the two least significant bits of the pointer. */
  695. #define decode( ptr, triedge ) \
  696. ( triedge ).orient = (int) ( (unsigned long) ( ptr ) & (unsigned long) 3l ); \
  697. ( triedge ).tri = (triangle *) \
  698. ( (unsigned long) ( ptr ) ^ (unsigned long) ( triedge ).orient )
  699. /* encode() compresses an oriented triangle into a single pointer. It */
  700. /* relies on the assumption that all triangles are aligned to four-byte */
  701. /* boundaries, so the two least significant bits of (triedge).tri are zero.*/
  702. #define encode( triedge ) \
  703. (triangle) ( (unsigned long) ( triedge ).tri | (unsigned long) ( triedge ).orient )
  704. /* The following edge manipulation primitives are all described by Guibas */
  705. /* and Stolfi. However, they use an edge-based data structure, whereas I */
  706. /* am using a triangle-based data structure. */
  707. /* sym() finds the abutting triangle, on the same edge. Note that the */
  708. /* edge direction is necessarily reversed…

Large files files are truncated, but you can click here to view the full file