Debian Codegraph @

debian/external_deps/fetk/gamer/src/tetgen/tetgen.cpp

raw
1 ///////////////////////////////////////////////////////////////////////////////
2 // //
3 // TetGen //
4 // //
5 // A Quality Tetrahedral Mesh Generator and 3D Delaunay Triangulator //
6 // //
7 // Version 1.4 //
8 // January 14, 2006 //
9 // //
10 // Copyright 2002, 2004, 2005, 2006 //
11 // Hang Si //
12 // Rathausstr. 9, 10178 Berlin, Germany //
13 // [email protected] //
14 // //
15 // You can obtain TetGen via internet: http://tetgen.berlios.de. It may be //
16 // freely copied, modified, and redistributed under the copyright notices //
17 // given in the file LICENSE. //
18 // //
19 ///////////////////////////////////////////////////////////////////////////////
20
21 ///////////////////////////////////////////////////////////////////////////////
22 // //
23 // tetgen.cxx //
24 // //
25 // The C++ implementation file of the TetGen library. //
26 // //
27 ///////////////////////////////////////////////////////////////////////////////
28
29 #include "tetgen_p.h"
30
31 ///////////////////////////////////////////////////////////////////////////////
32 // //
33 // terminatetetgen() Terminate TetGen with a given exit code. //
34 // //
35 ///////////////////////////////////////////////////////////////////////////////
36
37 void terminatetetgen(int x)
38 {
39 #ifdef TETLIBRARY
40 throw x;
41 #else
42 exit(x);
43 #endif // #ifdef TETLIBRARY
44 }
45
46 //
47 // Begin of class 'tetgenio' implementation
48 //
49
50 ///////////////////////////////////////////////////////////////////////////////
51 // //
52 // initialize() Initialize all variables of 'tetgenio'. //
53 // //
54 // It is called by the only class constructor 'tetgenio()' implicitly. Thus, //
55 // all variables are guaranteed to be initialized. Each array is initialized //
56 // to be a 'NULL' pointer, and its length is equal zero. Some variables have //
57 // their default value, 'firstnumber' equals zero, 'mesh_dim' equals 3, and //
58 // 'numberofcorners' equals 4. Another possible use of this routine is to //
59 // call it before to re-use an object. //
60 // //
61 ///////////////////////////////////////////////////////////////////////////////
62
63 void tetgenio::initialize()
64 {
65 firstnumber = 0; // Default item index is numbered from Zero.
66 mesh_dim = 3; // Default mesh dimension is 3.
67
68 pointlist = (REAL *) NULL;
69 pointattributelist = (REAL *) NULL;
70 addpointlist = (REAL *) NULL;
71 addpointattributelist = (REAL *) NULL;
72 pointmarkerlist = (int *) NULL;
73 numberofpoints = 0;
74 numberofpointattributes = 0;
75 numberofaddpoints = 0;
76
77 tetrahedronlist = (int *) NULL;
78 tetrahedronattributelist = (REAL *) NULL;
79 tetrahedronvolumelist = (REAL *) NULL;
80 neighborlist = (int *) NULL;
81 numberoftetrahedra = 0;
82 numberofcorners = 4; // Default is 4 nodes per element.
83 numberoftetrahedronattributes = 0;
84
85 trifacelist = (int *) NULL;
86 adjtetlist = (int *) NULL;
87 trifacemarkerlist = (int *) NULL;
88 numberoftrifaces = 0;
89
90 facetlist = (facet *) NULL;
91 facetmarkerlist = (int *) NULL;
92 numberoffacets = 0;
93
94 edgelist = (int *) NULL;
95 edgemarkerlist = (int *) NULL;
96 numberofedges = 0;
97
98 holelist = (REAL *) NULL;
99 numberofholes = 0;
100
101 regionlist = (REAL *) NULL;
102 numberofregions = 0;
103
104 facetconstraintlist = (REAL *) NULL;
105 numberoffacetconstraints = 0;
106 segmentconstraintlist = (REAL *) NULL;
107 numberofsegmentconstraints = 0;
108 nodeconstraintlist = (REAL *) NULL;
109 numberofnodeconstraints = 0;
110
111 pbcgrouplist = (pbcgroup *) NULL;
112 numberofpbcgroups = 0;
113 }
114
115 ///////////////////////////////////////////////////////////////////////////////
116 // //
117 // deinitialize() Free the memory allocated in 'tetgenio'. //
118 // //
119 // It is called by the class destructor '~tetgenio()' implicitly. Hence, the //
120 // occupied memory by arrays of an object will be automatically released on //
121 // the deletion of the object. However, this routine assumes that the memory //
122 // is allocated by C++ memory allocation operator 'new', thus it is freed by //
123 // the C++ array deletor 'delete []'. If one uses the C/C++ library function //
124 // 'malloc()' to allocate memory for arrays, one has to free them with the //
125 // 'free()' function, and call routine 'initialize()' once to disable this //
126 // routine on deletion of the object. //
127 // //
128 ///////////////////////////////////////////////////////////////////////////////
129
130 void tetgenio::deinitialize()
131 {
132 facet *f;
133 polygon *p;
134 pbcgroup *pg;
135 int i, j;
136
137 if (pointlist != (REAL *) NULL) {
138 delete [] pointlist;
139 }
140 if (pointattributelist != (REAL *) NULL) {
141 delete [] pointattributelist;
142 }
143 if (addpointlist != (REAL *) NULL) {
144 delete [] addpointlist;
145 }
146 if (addpointattributelist != (REAL *) NULL) {
147 delete [] addpointattributelist;
148 }
149 if (pointmarkerlist != (int *) NULL) {
150 delete [] pointmarkerlist;
151 }
152
153 if (tetrahedronlist != (int *) NULL) {
154 delete [] tetrahedronlist;
155 }
156 if (tetrahedronattributelist != (REAL *) NULL) {
157 delete [] tetrahedronattributelist;
158 }
159 if (tetrahedronvolumelist != (REAL *) NULL) {
160 delete [] tetrahedronvolumelist;
161 }
162 if (neighborlist != (int *) NULL) {
163 delete [] neighborlist;
164 }
165
166 if (trifacelist != (int *) NULL) {
167 delete [] trifacelist;
168 }
169 if (adjtetlist != (int *) NULL) {
170 delete [] adjtetlist;
171 }
172 if (trifacemarkerlist != (int *) NULL) {
173 delete [] trifacemarkerlist;
174 }
175
176 if (edgelist != (int *) NULL) {
177 delete [] edgelist;
178 }
179 if (edgemarkerlist != (int *) NULL) {
180 delete [] edgemarkerlist;
181 }
182
183 if (facetlist != (facet *) NULL) {
184 for (i = 0; i < numberoffacets; i++) {
185 f = &facetlist[i];
186 for (j = 0; j < f->numberofpolygons; j++) {
187 p = &f->polygonlist[j];
188 delete [] p->vertexlist;
189 }
190 delete [] f->polygonlist;
191 if (f->holelist != (REAL *) NULL) {
192 delete [] f->holelist;
193 }
194 }
195 delete [] facetlist;
196 }
197 if (facetmarkerlist != (int *) NULL) {
198 delete [] facetmarkerlist;
199 }
200
201 if (holelist != (REAL *) NULL) {
202 delete [] holelist;
203 }
204 if (regionlist != (REAL *) NULL) {
205 delete [] regionlist;
206 }
207 if (facetconstraintlist != (REAL *) NULL) {
208 delete [] facetconstraintlist;
209 }
210 if (segmentconstraintlist != (REAL *) NULL) {
211 delete [] segmentconstraintlist;
212 }
213 if (nodeconstraintlist != (REAL *) NULL) {
214 delete [] nodeconstraintlist;
215 }
216 if (pbcgrouplist != (pbcgroup *) NULL) {
217 for (i = 0; i < numberofpbcgroups; i++) {
218 pg = &(pbcgrouplist[i]);
219 if (pg->pointpairlist != (int *) NULL) {
220 delete [] pg->pointpairlist;
221 }
222 }
223 delete [] pbcgrouplist;
224 }
225 }
226
227 ///////////////////////////////////////////////////////////////////////////////
228 // //
229 // load_node_call() Load a list of nodes. //
230 // //
231 // It is a support routine for routines: 'load_nodes()', 'load_poly()', and //
232 // 'load_tetmesh()'. 'infile' is the file handle contains the node list. It //
233 // may point to a .node, or .poly or .smesh file. 'markers' indicates each //
234 // node contains an additional marker (integer) or not. 'infilename' is the //
235 // name of the file being read, it is only appeared in error message. //
236 // //
237 // The 'firstnumber' (0 or 1) is automatically determined by the number of //
238 // the first index of the first point. //
239 // //
240 ///////////////////////////////////////////////////////////////////////////////
241
242 bool tetgenio::load_node_call(FILE* infile, int markers, char* infilename)
243 {
244 char inputline[INPUTLINESIZE];
245 char *stringptr;
246 REAL x, y, z, attrib;
247 int firstnode, currentmarker;
248 int index, attribindex;
249 int i, j;
250
251 // Initialize 'pointlist', 'pointattributelist', and 'pointmarkerlist'.
252 pointlist = new REAL[numberofpoints * 3];
253 if (pointlist == (REAL *) NULL) {
254 printf("Error: Out of memory.\n");
255 terminatetetgen(1);
256 }
257 if (numberofpointattributes > 0) {
258 pointattributelist = new REAL[numberofpoints * numberofpointattributes];
259 if (pointattributelist == (REAL *) NULL) {
260 printf("Error: Out of memory.\n");
261 terminatetetgen(1);
262 }
263 }
264 if (markers) {
265 pointmarkerlist = new int[numberofpoints];
266 if (pointmarkerlist == (int *) NULL) {
267 printf("Error: Out of memory.\n");
268 terminatetetgen(1);
269 }
270 }
271
272 // Read the point section.
273 index = 0;
274 attribindex = 0;
275 for (i = 0; i < numberofpoints; i++) {
276 stringptr = readnumberline(inputline, infile, infilename);
277 if (i == 0) {
278 firstnode = (int) strtol (stringptr, &stringptr, 0);
279 if ((firstnode == 0) || (firstnode == 1)) {
280 firstnumber = firstnode;
281 }
282 }
283 stringptr = findnextnumber(stringptr);
284 if (*stringptr == '\0') {
285 printf("Error: Point %d has no x coordinate.\n", firstnumber + i);
286 break;
287 }
288 x = (REAL) strtod(stringptr, &stringptr);
289 stringptr = findnextnumber(stringptr);
290 if (*stringptr == '\0') {
291 printf("Error: Point %d has no y coordinate.\n", firstnumber + i);
292 break;
293 }
294 y = (REAL) strtod(stringptr, &stringptr);
295 if (mesh_dim == 3) {
296 stringptr = findnextnumber(stringptr);
297 if (*stringptr == '\0') {
298 printf("Error: Point %d has no z coordinate.\n", firstnumber + i);
299 break;
300 }
301 z = (REAL) strtod(stringptr, &stringptr);
302 } else {
303 z = 0.0; // mesh_dim == 2;
304 }
305 pointlist[index++] = x;
306 pointlist[index++] = y;
307 pointlist[index++] = z;
308 // Read the point attributes.
309 for (j = 0; j < numberofpointattributes; j++) {
310 stringptr = findnextnumber(stringptr);
311 if (*stringptr == '\0') {
312 attrib = 0.0;
313 } else {
314 attrib = (REAL) strtod(stringptr, &stringptr);
315 }
316 pointattributelist[attribindex++] = attrib;
317 }
318 if (markers) {
319 // Read a point marker.
320 stringptr = findnextnumber(stringptr);
321 if (*stringptr == '\0') {
322 currentmarker = 0;
323 } else {
324 currentmarker = (int) strtol (stringptr, &stringptr, 0);
325 }
326 pointmarkerlist[i] = currentmarker;
327 }
328 }
329 if (i < numberofpoints) {
330 // Failed to read points due to some error.
331 delete [] pointlist;
332 pointlist = (REAL *) NULL;
333 if (markers) {
334 delete [] pointmarkerlist;
335 pointmarkerlist = (int *) NULL;
336 }
337 if (numberofpointattributes > 0) {
338 delete [] pointattributelist;
339 pointattributelist = (REAL *) NULL;
340 }
341 numberofpoints = 0;
342 return false;
343 }
344 return true;
345 }
346
347 ///////////////////////////////////////////////////////////////////////////////
348 // //
349 // load_node() Load a list of nodes from a .node file. //
350 // //
351 // 'filename' is the inputfile without suffix. The node list is in 'filename.//
352 // node'. On completion, the node list is returned in 'pointlist'. //
353 // //
354 ///////////////////////////////////////////////////////////////////////////////
355
356 bool tetgenio::load_node(char* filename)
357 {
358 FILE *infile;
359 char innodefilename[FILENAMESIZE];
360 char inputline[INPUTLINESIZE];
361 char *stringptr;
362 int markers;
363
364 // Assembling the actual file names we want to open.
365 strcpy(innodefilename, filename);
366 strcat(innodefilename, ".node");
367
368 // Try to open a .node file.
369 infile = fopen(innodefilename, "r");
370 if (infile == (FILE *) NULL) {
371 printf("File I/O Error: Cannot access file %s.\n", innodefilename);
372 return false;
373 }
374 printf("Opening %s.\n", innodefilename);
375 // Read number of points, number of dimensions, number of point
376 // attributes, and number of boundary markers.
377 stringptr = readnumberline(inputline, infile, innodefilename);
378 numberofpoints = (int) strtol (stringptr, &stringptr, 0);
379 stringptr = findnextnumber(stringptr);
380 if (*stringptr == '\0') {
381 mesh_dim = 3;
382 } else {
383 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
384 }
385 stringptr = findnextnumber(stringptr);
386 if (*stringptr == '\0') {
387 numberofpointattributes = 0;
388 } else {
389 numberofpointattributes = (int) strtol (stringptr, &stringptr, 0);
390 }
391 stringptr = findnextnumber(stringptr);
392 if (*stringptr == '\0') {
393 markers = 0;
394 } else {
395 markers = (int) strtol (stringptr, &stringptr, 0);
396 }
397
398 if ((mesh_dim != 3) && (mesh_dim != 2)) {
399 printf("Input error: TetGen only works for 2D & 3D point sets.\n");
400 fclose(infile);
401 return false;
402 }
403 if (numberofpoints < (mesh_dim + 1)) {
404 printf("Input error: TetGen needs at least %d points.\n", mesh_dim + 1);
405 fclose(infile);
406 return false;
407 }
408
409 // Load the list of nodes.
410 if (!load_node_call(infile, markers, innodefilename)) {
411 fclose(infile);
412 return false;
413 }
414 fclose(infile);
415 return true;
416 }
417
418 ///////////////////////////////////////////////////////////////////////////////
419 // //
420 // load_addnodes() Load a list of additional nodes into 'addpointlists'. //
421 // //
422 // 'filename' is the filename of the original inputfile without suffix. The //
423 // additional nodes are found in file 'filename-a.node'. //
424 // //
425 ///////////////////////////////////////////////////////////////////////////////
426
427 bool tetgenio::load_addnodes(char* filename)
428 {
429 FILE *infile;
430 char addnodefilename[FILENAMESIZE];
431 char inputline[INPUTLINESIZE];
432 char *stringptr;
433 REAL x, y, z;
434 int index;
435 int i;
436
437 // Additional nodes are saved in file "filename-a.node".
438 strcpy(addnodefilename, filename);
439 strcat(addnodefilename, "-a.node");
440 infile = fopen(addnodefilename, "r");
441 if (infile != (FILE *) NULL) {
442 printf("Opening %s.\n", addnodefilename);
443 } else {
444 // Strange! However, it is not a fatal error.
445 printf("Warning: Can't opening %s. Skipped.\n", addnodefilename);
446 numberofaddpoints = 0;
447 return false;
448 }
449
450 // Read the number of additional points.
451 stringptr = readnumberline(inputline, infile, addnodefilename);
452 numberofaddpoints = (int) strtol (stringptr, &stringptr, 0);
453 if (numberofaddpoints == 0) {
454 // It looks this file contains no point.
455 fclose(infile);
456 return false;
457 }
458 // Initialize 'addpointlist';
459 addpointlist = new REAL[numberofaddpoints * mesh_dim];
460 if (addpointlist == (REAL *) NULL) {
461 printf("Error: Out of memory.\n");
462 terminatetetgen(1);
463 }
464
465 // Read the list of additional points.
466 index = 0;
467 for (i = 0; i < numberofaddpoints; i++) {
468 stringptr = readnumberline(inputline, infile, addnodefilename);
469 stringptr = findnextnumber(stringptr);
470 if (*stringptr == '\0') {
471 printf("Error: Point %d has no x coordinate.\n", firstnumber + i);
472 break;
473 }
474 x = (REAL) strtod(stringptr, &stringptr);
475 stringptr = findnextnumber(stringptr);
476 if (*stringptr == '\0') {
477 printf("Error: Point %d has no y coordinate.\n", firstnumber + i);
478 break;
479 }
480 y = (REAL) strtod(stringptr, &stringptr);
481 stringptr = findnextnumber(stringptr);
482 if (*stringptr == '\0') {
483 printf("Error: Point %d has no z coordinate.\n", firstnumber + i);
484 break;
485 }
486 z = (REAL) strtod(stringptr, &stringptr);
487 addpointlist[index++] = x;
488 addpointlist[index++] = y;
489 addpointlist[index++] = z;
490 }
491 fclose(infile);
492
493 if (i < numberofaddpoints) {
494 // Failed to read to additional points due to some error.
495 delete [] addpointlist;
496 addpointlist = (REAL *) NULL;
497 numberofaddpoints = 0;
498 return false;
499 }
500 return true;
501 }
502
503 ///////////////////////////////////////////////////////////////////////////////
504 // //
505 // load_pbc() Load a list of pbc groups into 'pbcgrouplist'. //
506 // //
507 // 'filename' is the filename of the original inputfile without suffix. The //
508 // pbc groups are found in file 'filename.pbc'. //
509 // //
510 // This routine will be called both in load_poly() and load_tetmesh(). //
511 // //
512 ///////////////////////////////////////////////////////////////////////////////
513
514 bool tetgenio::load_pbc(char* filename)
515 {
516 FILE *infile;
517 char pbcfilename[FILENAMESIZE];
518 char inputline[INPUTLINESIZE];
519 char *stringptr;
520 pbcgroup *pg;
521 int index, p1, p2;
522 int i, j, k;
523
524 // Pbc groups are saved in file "filename.pbc".
525 strcpy(pbcfilename, filename);
526 strcat(pbcfilename, ".pbc");
527 infile = fopen(pbcfilename, "r");
528 if (infile != (FILE *) NULL) {
529 printf("Opening %s.\n", pbcfilename);
530 } else {
531 // No such file. Return.
532 return false;
533 }
534
535 // Read the number of pbc groups.
536 stringptr = readnumberline(inputline, infile, pbcfilename);
537 numberofpbcgroups = (int) strtol (stringptr, &stringptr, 0);
538 if (numberofpbcgroups == 0) {
539 // It looks this file contains no point.
540 fclose(infile);
541 return false;
542 }
543 // Initialize 'pbcgrouplist';
544 pbcgrouplist = new pbcgroup[numberofpbcgroups];
545
546 // Read the list of pbc groups.
547 for (i = 0; i < numberofpbcgroups; i++) {
548 pg = &(pbcgrouplist[i]);
549 // Initialize pbcgroup i;
550 pg->numberofpointpairs = 0;
551 pg->pointpairlist = (int *) NULL;
552 // Read 'fmark1', 'fmark2'.
553 stringptr = readnumberline(inputline, infile, pbcfilename);
554 if (*stringptr == '\0') break;
555 pg->fmark1 = (int) strtol(stringptr, &stringptr, 0);
556 stringptr = findnextnumber(stringptr);
557 if (*stringptr == '\0') break;
558 pg->fmark2 = (int) strtol(stringptr, &stringptr, 0);
559 // Read 'transmat'.
560 do {
561 stringptr = readline(inputline, infile, NULL);
562 } while ((*stringptr != '[') && (*stringptr != '\0'));
563 if (*stringptr == '\0') break;
564 for (j = 0; j < 4; j++) {
565 for (k = 0; k < 4; k++) {
566 // Read the entry of [j, k].
567 stringptr = findnextnumber(stringptr);
568 if (*stringptr == '\0') {
569 // Try to read another line.
570 stringptr = readnumberline(inputline, infile, pbcfilename);
571 if (*stringptr == '\0') break;
572 }
573 pg->transmat[j][k] = (REAL) strtod(stringptr, &stringptr);
574 }
575 if (k < 4) break; // Not complete!
576 }
577 if (j < 4) break; // Not complete!
578 // Read 'numberofpointpairs'.
579 stringptr = readnumberline(inputline, infile, pbcfilename);
580 if (*stringptr == '\0') break;
581 pg->numberofpointpairs = (int) strtol(stringptr, &stringptr, 0);
582 if (pg->numberofpointpairs > 0) {
583 pg->pointpairlist = new int[pg->numberofpointpairs * 2];
584 // Read the point pairs.
585 index = 0;
586 for (j = 0; j < pg->numberofpointpairs; j++) {
587 stringptr = readnumberline(inputline, infile, pbcfilename);
588 p1 = (int) strtol(stringptr, &stringptr, 0);
589 stringptr = findnextnumber(stringptr);
590 p2 = (int) strtol(stringptr, &stringptr, 0);
591 pg->pointpairlist[index++] = p1;
592 pg->pointpairlist[index++] = p2;
593 }
594 }
595 }
596 fclose(infile);
597
598 if (i < numberofpbcgroups) {
599 // Failed to read to additional points due to some error.
600 delete [] pbcgrouplist;
601 pbcgrouplist = (pbcgroup *) NULL;
602 numberofpbcgroups = 0;
603 return false;
604 }
605 return true;
606 }
607
608 ///////////////////////////////////////////////////////////////////////////////
609 // //
610 // load_var() Load variant constraints applied on facets, segments, nodes.//
611 // //
612 // 'filename' is the filename of the original inputfile without suffix. The //
613 // constraints are found in file 'filename.var'. //
614 // //
615 ///////////////////////////////////////////////////////////////////////////////
616
617 bool tetgenio::load_var(char* filename)
618 {
619 FILE *infile;
620 char varfilename[FILENAMESIZE];
621 char inputline[INPUTLINESIZE];
622 char *stringptr;
623 int index;
624 int i;
625
626 // Variant constraints are saved in file "filename.var".
627 strcpy(varfilename, filename);
628 strcat(varfilename, ".var");
629 infile = fopen(varfilename, "r");
630 if (infile != (FILE *) NULL) {
631 printf("Opening %s.\n", varfilename);
632 } else {
633 // No such file. Return.
634 return false;
635 }
636
637 // Read the facet constraint section.
638 stringptr = readnumberline(inputline, infile, varfilename);
639 if (*stringptr != '\0') {
640 numberoffacetconstraints = (int) strtol (stringptr, &stringptr, 0);
641 } else {
642 numberoffacetconstraints = 0;
643 }
644 if (numberoffacetconstraints > 0) {
645 // Initialize 'facetconstraintlist'.
646 facetconstraintlist = new REAL[numberoffacetconstraints * 2];
647 index = 0;
648 for (i = 0; i < numberoffacetconstraints; i++) {
649 stringptr = readnumberline(inputline, infile, varfilename);
650 stringptr = findnextnumber(stringptr);
651 if (*stringptr == '\0') {
652 printf("Error: facet constraint %d has no facet marker.\n",
653 firstnumber + i);
654 break;
655 } else {
656 facetconstraintlist[index++] = (REAL) strtod(stringptr, &stringptr);
657 }
658 stringptr = findnextnumber(stringptr);
659 if (*stringptr == '\0') {
660 printf("Error: facet constraint %d has no maximum area bound.\n",
661 firstnumber + i);
662 break;
663 } else {
664 facetconstraintlist[index++] = (REAL) strtod(stringptr, &stringptr);
665 }
666 }
667 if (i < numberoffacetconstraints) {
668 // This must be caused by an error.
669 fclose(infile);
670 return false;
671 }
672 }
673
674 // Read the segment constraint section.
675 stringptr = readnumberline(inputline, infile, varfilename);
676 if (*stringptr != '\0') {
677 numberofsegmentconstraints = (int) strtol (stringptr, &stringptr, 0);
678 } else {
679 numberofsegmentconstraints = 0;
680 }
681 if (numberofsegmentconstraints > 0) {
682 // Initialize 'segmentconstraintlist'.
683 segmentconstraintlist = new REAL[numberofsegmentconstraints * 3];
684 index = 0;
685 for (i = 0; i < numberofsegmentconstraints; i++) {
686 stringptr = readnumberline(inputline, infile, varfilename);
687 stringptr = findnextnumber(stringptr);
688 if (*stringptr == '\0') {
689 printf("Error: segment constraint %d has no frist endpoint.\n",
690 firstnumber + i);
691 break;
692 } else {
693 segmentconstraintlist[index++] = (REAL) strtod(stringptr, &stringptr);
694 }
695 stringptr = findnextnumber(stringptr);
696 if (*stringptr == '\0') {
697 printf("Error: segment constraint %d has no second endpoint.\n",
698 firstnumber + i);
699 break;
700 } else {
701 segmentconstraintlist[index++] = (REAL) strtod(stringptr, &stringptr);
702 }
703 stringptr = findnextnumber(stringptr);
704 if (*stringptr == '\0') {
705 printf("Error: segment constraint %d has no maximum length bound.\n",
706 firstnumber + i);
707 break;
708 } else {
709 segmentconstraintlist[index++] = (REAL) strtod(stringptr, &stringptr);
710 }
711 }
712 if (i < numberofsegmentconstraints) {
713 // This must be caused by an error.
714 fclose(infile);
715 return false;
716 }
717 }
718
719 // Read the node constraint section. It is optional.
720 stringptr = readnumberline(inputline, infile, NULL);
721 if (stringptr != (char *) NULL && *stringptr != '\0') {
722 numberofnodeconstraints = (int) strtol (stringptr, &stringptr, 0);
723 } else {
724 numberofnodeconstraints = 0;
725 }
726 if (numberofnodeconstraints > 0) {
727 // Initialize 'nodeconstraintlist'.
728 nodeconstraintlist = new REAL[numberofnodeconstraints * 2];
729 index = 0;
730 for (i = 0; i < numberofnodeconstraints; i++) {
731 stringptr = readnumberline(inputline, infile, varfilename);
732 stringptr = findnextnumber(stringptr);
733 if (*stringptr == '\0') {
734 printf("Error: node constraint %d has no node index.\n",
735 firstnumber + i);
736 break;
737 } else {
738 nodeconstraintlist[index++] = (REAL) strtod(stringptr, &stringptr);
739 }
740 stringptr = findnextnumber(stringptr);
741 if (*stringptr == '\0') {
742 printf("Error: node constraint %d has no edge length bound.\n",
743 firstnumber + i);
744 break;
745 } else {
746 nodeconstraintlist[index++] = (REAL) strtod(stringptr, &stringptr);
747 }
748 }
749 if (i < numberofnodeconstraints) {
750 // This must be caused by an error.
751 fclose(infile);
752 return false;
753 }
754 }
755
756 fclose(infile);
757 return true;
758 }
759
760 ///////////////////////////////////////////////////////////////////////////////
761 // //
762 // load_mtr() Load a size specification map from file. //
763 // //
764 // 'filename' is the filename of the original inputfile without suffix. The //
765 // size map is found in file 'filename.mtr'. //
766 // //
767 ///////////////////////////////////////////////////////////////////////////////
768
769 bool tetgenio::load_mtr(char* filename)
770 {
771 FILE *infile;
772 char mtrfilename[FILENAMESIZE];
773 char inputline[INPUTLINESIZE];
774 char *stringptr;
775 REAL attrib;
776 int attribindex;
777 int i, j;
778
779 strcpy(mtrfilename, filename);
780 strcat(mtrfilename, ".mtr");
781 infile = fopen(mtrfilename, "r");
782 if (infile != (FILE *) NULL) {
783 printf("Opening %s.\n", mtrfilename);
784 } else {
785 // No such file. Return.
786 return false;
787 }
788
789 // Read number of points, number of columns (1, 3, or 6).
790 stringptr = readnumberline(inputline, infile, mtrfilename);
791 stringptr = findnextnumber(stringptr); // Skip number of points.
792 i = (int) strtol (stringptr, &stringptr, 0);
793 if ((i != 1) && (i != 3) && (i != 6)) {
794 // Column number doesn't match. Do nothing with this file.
795 fclose(infile);
796 return false;
797 }
798
799 // Metric tensors are saved in pointattributelist.
800 if (pointattributelist != (REAL *) NULL) {
801 delete [] pointattributelist;
802 pointattributelist = (REAL *) NULL;
803 }
804 numberofpointattributes = i;
805 // Allocate space for pointattributelist.
806 pointattributelist = new REAL[numberofpoints * numberofpointattributes];
807 if (pointattributelist == (REAL *) NULL) {
808 printf("Error: Out of memory.\n");
809 terminatetetgen(1);
810 }
811 attribindex = 0;
812 for (i = 0; i < numberofpoints; i++) {
813 // Read metrics.
814 stringptr = readnumberline(inputline, infile, mtrfilename);
815 for (j = 0; j < numberofpointattributes; j++) {
816 // stringptr = findnextnumber(stringptr);
817 if (*stringptr == '\0') {
818 printf("Error: Metric %d is missing value #%d in %s.\n",
819 i + firstnumber, j + 1, mtrfilename);
820 terminatetetgen(1);
821 }
822 attrib = (REAL) strtod(stringptr, &stringptr);
823 pointattributelist[attribindex++] = attrib;
824 }
825 }
826
827 fclose(infile);
828 return true;
829 }
830
831 ///////////////////////////////////////////////////////////////////////////////
832 // //
833 // load_poly() Load a piecewise linear complex from a .poly or .smesh. //
834 // //
835 // 'filename' is the inputfile without suffix. The PLC is in 'filename.poly' //
836 // or 'filename.smesh', and possibly plus 'filename.node' (when the first //
837 // line of the file starts with a zero). //
838 // //
839 ///////////////////////////////////////////////////////////////////////////////
840
841 bool tetgenio::load_poly(char* filename)
842 {
843 FILE *infile, *polyfile;
844 char innodefilename[FILENAMESIZE];
845 char inpolyfilename[FILENAMESIZE];
846 char insmeshfilename[FILENAMESIZE];
847 char inputline[INPUTLINESIZE];
848 char *stringptr, *infilename;
849 int smesh, markers, currentmarker;
850 int readnodefile, index;
851 int i, j, k;
852
853 // Assembling the actual file names we want to open.
854 strcpy(innodefilename, filename);
855 strcpy(inpolyfilename, filename);
856 strcpy(insmeshfilename, filename);
857 strcat(innodefilename, ".node");
858 strcat(inpolyfilename, ".poly");
859 strcat(insmeshfilename, ".smesh");
860
861 // First assume it is a .poly file.
862 smesh = 0;
863 // Try to open a .poly file.
864 polyfile = fopen(inpolyfilename, "r");
865 if (polyfile == (FILE *) NULL) {
866 // .poly doesn't exist! Try to open a .smesh file.
867 polyfile = fopen(insmeshfilename, "r");
868 if (polyfile == (FILE *) NULL) {
869 printf("File I/O Error: Cannot access file %s and %s.\n",
870 inpolyfilename, insmeshfilename);
871 return false;
872 } else {
873 printf("Opening %s.\n", insmeshfilename);
874 }
875 smesh = 1;
876 } else {
877 printf("Opening %s.\n", inpolyfilename);
878 }
879 // Initialize the default values.
880 mesh_dim = 3; // Three-dimemsional accoordinates.
881 numberofpointattributes = 0; // no point attribute.
882 markers = 0; // no boundary marker.
883 // Read number of points, number of dimensions, number of point
884 // attributes, and number of boundary markers.
885 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
886 numberofpoints = (int) strtol (stringptr, &stringptr, 0);
887 stringptr = findnextnumber(stringptr);
888 if (*stringptr != '\0') {
889 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
890 }
891 stringptr = findnextnumber(stringptr);
892 if (*stringptr != '\0') {
893 numberofpointattributes = (int) strtol (stringptr, &stringptr, 0);
894 }
895 stringptr = findnextnumber(stringptr);
896 if (*stringptr != '\0') {
897 markers = (int) strtol (stringptr, &stringptr, 0);
898 }
899 if (numberofpoints > 0) {
900 readnodefile = 0;
901 if (smesh) {
902 infilename = insmeshfilename;
903 } else {
904 infilename = inpolyfilename;
905 }
906 infile = polyfile;
907 } else {
908 // If the .poly or .smesh file claims there are zero points, that
909 // means the points should be read from a separate .node file.
910 readnodefile = 1;
911 infilename = innodefilename;
912 }
913
914 if (readnodefile) {
915 // Read the points from the .node file.
916 printf("Opening %s.\n", innodefilename);
917 infile = fopen(innodefilename, "r");
918 if (infile == (FILE *) NULL) {
919 printf("File I/O Error: Cannot access file %s.\n", innodefilename);
920 return false;
921 }
922 // Initialize the default values.
923 mesh_dim = 3; // Three-dimemsional accoordinates.
924 numberofpointattributes = 0; // no point attribute.
925 markers = 0; // no boundary marker.
926 // Read number of points, number of dimensions, number of point
927 // attributes, and number of boundary markers.
928 stringptr = readnumberline(inputline, infile, innodefilename);
929 numberofpoints = (int) strtol (stringptr, &stringptr, 0);
930 stringptr = findnextnumber(stringptr);
931 if (*stringptr != '\0') {
932 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
933 }
934 stringptr = findnextnumber(stringptr);
935 if (*stringptr != '\0') {
936 numberofpointattributes = (int) strtol (stringptr, &stringptr, 0);
937 }
938 stringptr = findnextnumber(stringptr);
939 if (*stringptr != '\0') {
940 markers = (int) strtol (stringptr, &stringptr, 0);
941 }
942 }
943
944 if ((mesh_dim != 3) && (mesh_dim != 2)) {
945 printf("Input error: TetGen only works for 2D & 3D point sets.\n");
946 fclose(infile);
947 return false;
948 }
949 if (numberofpoints < (mesh_dim + 1)) {
950 printf("Input error: TetGen needs at least %d points.\n", mesh_dim + 1);
951 fclose(infile);
952 return false;
953 }
954
955 // Load the list of nodes.
956 if (!load_node_call(infile, markers, infilename)) {
957 fclose(infile);
958 return false;
959 }
960
961 if (readnodefile) {
962 fclose(infile);
963 }
964
965 facet *f;
966 polygon *p;
967
968 if (mesh_dim == 3) {
969
970 // Read number of facets and number of boundary markers.
971 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
972 numberoffacets = (int) strtol (stringptr, &stringptr, 0);
973 if (numberoffacets <= 0) {
974 // No facet list, return.
975 fclose(polyfile);
976 return true;
977 }
978 stringptr = findnextnumber(stringptr);
979 if (*stringptr == '\0') {
980 markers = 0; // no boundary marker.
981 } else {
982 markers = (int) strtol (stringptr, &stringptr, 0);
983 }
984
985 // Initialize the 'facetlist', 'facetmarkerlist'.
986 facetlist = new facet[numberoffacets];
987 if (markers == 1) {
988 facetmarkerlist = new int[numberoffacets];
989 }
990
991 // Read data into 'facetlist', 'facetmarkerlist'.
992 if (smesh == 0) {
993 // Facets are in .poly file format.
994 for (i = 1; i <= numberoffacets; i++) {
995 f = &(facetlist[i - 1]);
996 init(f);
997 f->numberofholes = 0;
998 currentmarker = 0;
999 // Read number of polygons, number of holes, and a boundary marker.
1000 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1001 f->numberofpolygons = (int) strtol (stringptr, &stringptr, 0);
1002 stringptr = findnextnumber(stringptr);
1003 if (*stringptr != '\0') {
1004 f->numberofholes = (int) strtol (stringptr, &stringptr, 0);
1005 if (markers == 1) {
1006 stringptr = findnextnumber(stringptr);
1007 if (*stringptr != '\0') {
1008 currentmarker = (int) strtol(stringptr, &stringptr, 0);
1009 }
1010 }
1011 }
1012 // Initialize facetmarker if it needs.
1013 if (markers == 1) {
1014 facetmarkerlist[i - 1] = currentmarker;
1015 }
1016 // Each facet should has at least one polygon.
1017 if (f->numberofpolygons <= 0) {
1018 printf("Error: Wrong number of polygon in %d facet.\n", i);
1019 break;
1020 }
1021 // Initialize the 'f->polygonlist'.
1022 f->polygonlist = new polygon[f->numberofpolygons];
1023 // Go through all polygons, read in their vertices.
1024 for (j = 1; j <= f->numberofpolygons; j++) {
1025 p = &(f->polygonlist[j - 1]);
1026 init(p);
1027 // Read number of vertices of this polygon.
1028 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1029 p->numberofvertices = (int) strtol(stringptr, &stringptr, 0);
1030 if (p->numberofvertices < 1) {
1031 printf("Error: Wrong polygon %d in facet %d\n", j, i);
1032 break;
1033 }
1034 // Initialize 'p->vertexlist'.
1035 p->vertexlist = new int[p->numberofvertices];
1036 // Read all vertices of this polygon.
1037 for (k = 1; k <= p->numberofvertices; k++) {
1038 stringptr = findnextnumber(stringptr);
1039 if (*stringptr == '\0') {
1040 // Try to load another non-empty line and continue to read the
1041 // rest of vertices.
1042 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1043 if (*stringptr == '\0') {
1044 printf("Error: Missing %d endpoints of polygon %d in facet %d",
1045 p->numberofvertices - k, j, i);
1046 break;
1047 }
1048 }
1049 p->vertexlist[k - 1] = (int) strtol (stringptr, &stringptr, 0);
1050 }
1051 }
1052 if (j <= f->numberofpolygons) {
1053 // This must be caused by an error. However, there're j - 1
1054 // polygons have been read. Reset the 'f->numberofpolygon'.
1055 if (j == 1) {
1056 // This is the first polygon.
1057 delete [] f->polygonlist;
1058 }
1059 f->numberofpolygons = j - 1;
1060 // No hole will be read even it exists.
1061 f->numberofholes = 0;
1062 break;
1063 }
1064 // If this facet has hole pints defined, read them.
1065 if (f->numberofholes > 0) {
1066 // Initialize 'f->holelist'.
1067 f->holelist = new REAL[f->numberofholes * 3];
1068 // Read the holes' coordinates.
1069 index = 0;
1070 for (j = 1; j <= f->numberofholes; j++) {
1071 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1072 for (k = 1; k <= 3; k++) {
1073 stringptr = findnextnumber(stringptr);
1074 if (*stringptr == '\0') {
1075 printf("Error: Hole %d in facet %d has no coordinates", j, i);
1076 break;
1077 }
1078 f->holelist[index++] = (REAL) strtod (stringptr, &stringptr);
1079 }
1080 if (k <= 3) {
1081 // This must be caused by an error.
1082 break;
1083 }
1084 }
1085 if (j <= f->numberofholes) {
1086 // This must be caused by an error.
1087 break;
1088 }
1089 }
1090 }
1091 if (i <= numberoffacets) {
1092 // This must be caused by an error.
1093 numberoffacets = i - 1;
1094 fclose(polyfile);
1095 return false;
1096 }
1097 } else { // poly == 0
1098 // Read the facets from a .smesh file.
1099 for (i = 1; i <= numberoffacets; i++) {
1100 f = &(facetlist[i - 1]);
1101 init(f);
1102 // Initialize 'f->facetlist'. In a .smesh file, each facetlist only
1103 // contains exactly one polygon, no hole.
1104 f->numberofpolygons = 1;
1105 f->polygonlist = new polygon[f->numberofpolygons];
1106 p = &(f->polygonlist[0]);
1107 init(p);
1108 // Read number of vertices of this polygon.
1109 stringptr = readnumberline(inputline, polyfile, insmeshfilename);
1110 p->numberofvertices = (int) strtol (stringptr, &stringptr, 0);
1111 if (p->numberofvertices < 1) {
1112 printf("Error: Wrong number of vertex in facet %d\n", i);
1113 break;
1114 }
1115 // Initialize 'p->vertexlist'.
1116 p->vertexlist = new int[p->numberofvertices];
1117 for (k = 1; k <= p->numberofvertices; k++) {
1118 stringptr = findnextnumber(stringptr);
1119 if (*stringptr == '\0') {
1120 // Try to load another non-empty line and continue to read the
1121 // rest of vertices.
1122 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1123 if (*stringptr == '\0') {
1124 printf("Error: Missing %d endpoints in facet %d",
1125 p->numberofvertices - k, i);
1126 break;
1127 }
1128 }
1129 p->vertexlist[k - 1] = (int) strtol (stringptr, &stringptr, 0);
1130 }
1131 if (k <= p->numberofvertices) {
1132 // This must be caused by an error.
1133 break;
1134 }
1135 // Read facet's boundary marker at last.
1136 if (markers == 1) {
1137 stringptr = findnextnumber(stringptr);
1138 if (*stringptr == '\0') {
1139 currentmarker = 0;
1140 } else {
1141 currentmarker = (int) strtol(stringptr, &stringptr, 0);
1142 }
1143 facetmarkerlist[i - 1] = currentmarker;
1144 }
1145 }
1146 if (i <= numberoffacets) {
1147 // This must be caused by an error.
1148 numberoffacets = i - 1;
1149 fclose(polyfile);
1150 return false;
1151 }
1152 }
1153
1154 // Read the hole section.
1155 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1156 if (*stringptr != '\0') {
1157 numberofholes = (int) strtol (stringptr, &stringptr, 0);
1158 } else {
1159 numberofholes = 0;
1160 }
1161 if (numberofholes > 0) {
1162 // Initialize 'holelist'.
1163 holelist = new REAL[numberofholes * 3];
1164 for (i = 0; i < 3 * numberofholes; i += 3) {
1165 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1166 stringptr = findnextnumber(stringptr);
1167 if (*stringptr == '\0') {
1168 printf("Error: Hole %d has no x coord.\n", firstnumber + (i / 3));
1169 break;
1170 } else {
1171 holelist[i] = (REAL) strtod(stringptr, &stringptr);
1172 }
1173 stringptr = findnextnumber(stringptr);
1174 if (*stringptr == '\0') {
1175 printf("Error: Hole %d has no y coord.\n", firstnumber + (i / 3));
1176 break;
1177 } else {
1178 holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
1179 }
1180 stringptr = findnextnumber(stringptr);
1181 if (*stringptr == '\0') {
1182 printf("Error: Hole %d has no z coord.\n", firstnumber + (i / 3));
1183 break;
1184 } else {
1185 holelist[i + 2] = (REAL) strtod(stringptr, &stringptr);
1186 }
1187 }
1188 if (i < 3 * numberofholes) {
1189 // This must be caused by an error.
1190 fclose(polyfile);
1191 return false;
1192 }
1193 }
1194
1195 // Read the region section. The 'region' section is optional, if we
1196 // don't reach the end-of-file, try read it in.
1197 stringptr = readnumberline(inputline, polyfile, NULL);
1198 if (stringptr != (char *) NULL && *stringptr != '\0') {
1199 numberofregions = (int) strtol (stringptr, &stringptr, 0);
1200 } else {
1201 numberofregions = 0;
1202 }
1203 if (numberofregions > 0) {
1204 // Initialize 'regionlist'.
1205 regionlist = new REAL[numberofregions * 5];
1206 index = 0;
1207 for (i = 0; i < numberofregions; i++) {
1208 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1209 stringptr = findnextnumber(stringptr);
1210 if (*stringptr == '\0') {
1211 printf("Error: Region %d has no x coordinate.\n", firstnumber + i);
1212 break;
1213 } else {
1214 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
1215 }
1216 stringptr = findnextnumber(stringptr);
1217 if (*stringptr == '\0') {
1218 printf("Error: Region %d has no y coordinate.\n", firstnumber + i);
1219 break;
1220 } else {
1221 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
1222 }
1223 stringptr = findnextnumber(stringptr);
1224 if (*stringptr == '\0') {
1225 printf("Error: Region %d has no z coordinate.\n", firstnumber + i);
1226 break;
1227 } else {
1228 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
1229 }
1230 stringptr = findnextnumber(stringptr);
1231 if (*stringptr == '\0') {
1232 printf("Error: Region %d has no region attrib.\n", firstnumber + i);
1233 break;
1234 } else {
1235 regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
1236 }
1237 stringptr = findnextnumber(stringptr);
1238 if (*stringptr == '\0') {
1239 regionlist[index] = regionlist[index - 1];
1240 } else {
1241 regionlist[index] = (REAL) strtod(stringptr, &stringptr);
1242 }
1243 index++;
1244 }
1245 if (i < numberofregions) {
1246 // This must be caused by an error.
1247 fclose(polyfile);
1248 return false;
1249 }
1250 }
1251
1252 } else {
1253
1254 // Read a PSLG from Triangle's poly file.
1255 assert(mesh_dim == 2);
1256 // A PSLG is a facet of a PLC.
1257 numberoffacets = 1;
1258 // Initialize the 'facetlist'.
1259 facetlist = new facet[numberoffacets];
1260 facetmarkerlist = (int *) NULL; // No facet markers.
1261 f = &(facetlist[0]);
1262 init(f);
1263 // Read number of segments.
1264 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1265 // Segments are degenerate polygons.
1266 f->numberofpolygons = (int) strtol (stringptr, &stringptr, 0);
1267 if (f->numberofpolygons > 0) {
1268 f->polygonlist = new polygon[f->numberofpolygons];
1269 }
1270 // Go through all segments, read in their vertices.
1271 for (j = 0; j < f->numberofpolygons; j++) {
1272 p = &(f->polygonlist[j]);
1273 init(p);
1274 // Read in a segment.
1275 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1276 stringptr = findnextnumber(stringptr); // Skip its index.
1277 p->numberofvertices = 2; // A segment always has two vertices.
1278 p->vertexlist = new int[p->numberofvertices];
1279 p->vertexlist[0] = (int) strtol (stringptr, &stringptr, 0);
1280 stringptr = findnextnumber(stringptr);
1281 p->vertexlist[1] = (int) strtol (stringptr, &stringptr, 0);
1282 }
1283 // Read number of holes.
1284 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1285 f->numberofholes = (int) strtol (stringptr, &stringptr, 0);
1286 if (f->numberofholes > 0) {
1287 // Initialize 'f->holelist'.
1288 f->holelist = new REAL[f->numberofholes * 3];
1289 // Read the holes' coordinates.
1290 for (j = 0; j < f->numberofholes; j++) {
1291 // Read a 2D hole point.
1292 stringptr = readnumberline(inputline, polyfile, inpolyfilename);
1293 stringptr = findnextnumber(stringptr); // Skip its index.
1294 f->holelist[j * 3] = (REAL) strtod (stringptr, &stringptr);
1295 stringptr = findnextnumber(stringptr);
1296 f->holelist[j * 3 + 1] = (REAL) strtod (stringptr, &stringptr);
1297 f->holelist[j * 3 + 2] = 0.0; // The z-coord.
1298 }
1299 }
1300 // The regions are skipped.
1301
1302 }
1303
1304 // End of reading poly/smesh file.
1305 fclose(polyfile);
1306
1307 // Try to load a .var file if it exists.
1308 load_var(filename);
1309 // Try to load a .mtr file if it exists.
1310 load_mtr(filename);
1311 // Try to read a .pbc file if it exists.
1312 load_pbc(filename);
1313
1314 return true;
1315 }
1316
1317 ///////////////////////////////////////////////////////////////////////////////
1318 // //
1319 // load_off() Load a polyhedron described in a .off file. //
1320 // //
1321 // The .off format is one of file formats of the Geomview, an interactive //
1322 // program for viewing and manipulating geometric objects. More information //
1323 // is available form: http://www.geomview.org. //
1324 // //
1325 // 'filename' is a input filename with extension .off or without extension ( //
1326 // the .off will be added in this case). On completion, the polyhedron is //
1327 // returned in 'pointlist' and 'facetlist'. //
1328 // //
1329 ///////////////////////////////////////////////////////////////////////////////
1330
1331 bool tetgenio::load_off(char* filename)
1332 {
1333 FILE *fp;
1334 tetgenio::facet *f;
1335 tetgenio::polygon *p;
1336 char infilename[FILENAMESIZE];
1337 char buffer[INPUTLINESIZE];
1338 char *bufferp;
1339 double *coord;
1340 int nverts = 0, iverts = 0;
1341 int nfaces = 0, ifaces = 0;
1342 int nedges = 0;
1343 int line_count = 0, i;
1344
1345 strncpy(infilename, filename, 1024 - 1);
1346 infilename[FILENAMESIZE - 1] = '\0';
1347 if (infilename[0] == '\0') {
1348 printf("Error: No filename.\n");
1349 return false;
1350 }
1351 if (strcmp(&infilename[strlen(infilename) - 4], ".off") != 0) {
1352 strcat(infilename, ".off");
1353 }
1354
1355 if (!(fp = fopen(infilename, "r"))) {
1356 printf("File I/O Error: Unable to open file %s\n", infilename);
1357 return false;
1358 }
1359 printf("Opening %s.\n", infilename);
1360
1361 // OFF requires the index starts from '0'.
1362 firstnumber = 0;
1363
1364 while ((bufferp = readline(buffer, fp, &line_count)) != NULL) {
1365 // Check section
1366 if (nverts == 0) {
1367 // Read header
1368 bufferp = strstr(bufferp, "OFF");
1369 if (bufferp != NULL) {
1370 // Read mesh counts
1371 bufferp = findnextnumber(bufferp); // Skip field "OFF".
1372 if (*bufferp == '\0') {
1373 // Read a non-empty line.
1374 bufferp = readline(buffer, fp, &line_count);
1375 }
1376 if ((sscanf(bufferp, "%d%d%d", &nverts, &nfaces, &nedges) != 3)
1377 || (nverts == 0)) {
1378 printf("Syntax error reading header on line %d in file %s\n",
1379 line_count, infilename);
1380 fclose(fp);
1381 return false;
1382 }
1383 // Allocate memory for 'tetgenio'
1384 if (nverts > 0) {
1385 numberofpoints = nverts;
1386 pointlist = new REAL[nverts * 3];
1387 }
1388 if (nfaces > 0) {
1389 numberoffacets = nfaces;
1390 facetlist = new tetgenio::facet[nfaces];
1391 }
1392 }
1393 } else if (iverts < nverts) {
1394 // Read vertex coordinates
1395 coord = &pointlist[iverts * 3];
1396 for (i = 0; i < 3; i++) {
1397 if (*bufferp == '\0') {
1398 printf("Syntax error reading vertex coords on line %d in file %s\n",
1399 line_count, infilename);
1400 fclose(fp);
1401 return false;
1402 }
1403 coord[i] = (REAL) strtod(bufferp, &bufferp);
1404 bufferp = findnextnumber(bufferp);
1405 }
1406 iverts++;
1407 } else if (ifaces < nfaces) {
1408 // Get next face
1409 f = &facetlist[ifaces];
1410 init(f);
1411 // In .off format, each facet has one polygon, no hole.
1412 f->numberofpolygons = 1;
1413 f->polygonlist = new tetgenio::polygon[1];
1414 p = &f->polygonlist[0];
1415 init(p);
1416 // Read the number of vertices, it should be greater than 0.
1417 p->numberofvertices = (int) strtol(bufferp, &bufferp, 0);
1418 if (p->numberofvertices == 0) {
1419 printf("Syntax error reading polygon on line %d in file %s\n",
1420 line_count, infilename);
1421 fclose(fp);
1422 return false;
1423 }
1424 // Allocate memory for face vertices
1425 p->vertexlist = new int[p->numberofvertices];
1426 for (i = 0; i < p->numberofvertices; i++) {
1427 bufferp = findnextnumber(bufferp);
1428 if (*bufferp == '\0') {
1429 printf("Syntax error reading polygon on line %d in file %s\n",
1430 line_count, infilename);
1431 fclose(fp);
1432 return false;
1433 }
1434 p->vertexlist[i] = (int) strtol(bufferp, &bufferp, 0);
1435 }
1436 ifaces++;
1437 } else {
1438 // Should never get here
1439 printf("Found extra text starting at line %d in file %s\n", line_count,
1440 infilename);
1441 break;
1442 }
1443 }
1444
1445 // Close file
1446 fclose(fp);
1447
1448 // Check whether read all points
1449 if (iverts != nverts) {
1450 printf("Expected %d vertices, but read only %d vertices in file %s\n",
1451 nverts, iverts, infilename);
1452 return false;
1453 }
1454
1455 // Check whether read all faces
1456 if (ifaces != nfaces) {
1457 printf("Expected %d faces, but read only %d faces in file %s\n",
1458 nfaces, ifaces, infilename);
1459 return false;
1460 }
1461
1462 return true;
1463 }
1464
1465 ///////////////////////////////////////////////////////////////////////////////
1466 // //
1467 // load_ply() Load a polyhedron described in a .ply file. //
1468 // //
1469 // 'filename' is the file name with extension .ply or without extension (the //
1470 // .ply will be added in this case). //
1471 // //
1472 // This is a simplified version of reading .ply files, which only reads the //
1473 // set of vertices and the set of faces. Other informations (such as color, //
1474 // material, texture, etc) in .ply file are ignored. Complete routines for //
1475 // reading and writing ,ply files are available from: http://www.cc.gatech. //
1476 // edu/projects/large_models/ply.html. Except the header section, ply file //
1477 // format has exactly the same format for listing vertices and polygons as //
1478 // off file format. //
1479 // //
1480 // On completion, 'pointlist' and 'facetlist' together return the polyhedron.//
1481 // //
1482 ///////////////////////////////////////////////////////////////////////////////
1483
1484 bool tetgenio::load_ply(char* filename)
1485 {
1486 FILE *fp;
1487 tetgenio::facet *f;
1488 tetgenio::polygon *p;
1489 char infilename[FILENAMESIZE];
1490 char buffer[INPUTLINESIZE];
1491 char *bufferp, *str;
1492 double *coord;
1493 int endheader = 0, format = 0;
1494 int nverts = 0, iverts = 0;
1495 int nfaces = 0, ifaces = 0;
1496 int line_count = 0, i;
1497
1498 strncpy(infilename, filename, FILENAMESIZE - 1);
1499 infilename[FILENAMESIZE - 1] = '\0';
1500 if (infilename[0] == '\0') {
1501 printf("Error: No filename.\n");
1502 return false;
1503 }
1504 if (strcmp(&infilename[strlen(infilename) - 4], ".ply") != 0) {
1505 strcat(infilename, ".ply");
1506 }
1507
1508 if (!(fp = fopen(infilename, "r"))) {
1509 printf("Error: Unable to open file %s\n", infilename);
1510 return false;
1511 }
1512 printf("Opening %s.\n", infilename);
1513
1514 // PLY requires the index starts from '0'.
1515 firstnumber = 0;
1516
1517 while ((bufferp = readline(buffer, fp, &line_count)) != NULL) {
1518 if (!endheader) {
1519 // Find if it is the keyword "end_header".
1520 str = strstr(bufferp, "end_header");
1521 // strstr() is case sensitive.
1522 if (!str) str = strstr(bufferp, "End_header");
1523 if (!str) str = strstr(bufferp, "End_Header");
1524 if (str) {
1525 // This is the end of the header section.
1526 endheader = 1;
1527 continue;
1528 }
1529 // Parse the number of vertices and the number of faces.
1530 if (nverts == 0 || nfaces == 0) {
1531 // Find if it si the keyword "element".
1532 str = strstr(bufferp, "element");
1533 if (!str) str = strstr(bufferp, "Element");
1534 if (str) {
1535 bufferp = findnextfield(str);
1536 if (*bufferp == '\0') {
1537 printf("Syntax error reading element type on line%d in file %s\n",
1538 line_count, infilename);
1539 fclose(fp);
1540 return false;
1541 }
1542 if (nverts == 0) {
1543 // Find if it is the keyword "vertex".
1544 str = strstr(bufferp, "vertex");
1545 if (!str) str = strstr(bufferp, "Vertex");
1546 if (str) {
1547 bufferp = findnextnumber(str);
1548 if (*bufferp == '\0') {
1549 printf("Syntax error reading vertex number on line");
1550 printf(" %d in file %s\n", line_count, infilename);
1551 fclose(fp);
1552 return false;
1553 }
1554 nverts = (int) strtol(bufferp, &bufferp, 0);
1555 // Allocate memory for 'tetgenio'
1556 if (nverts > 0) {
1557 numberofpoints = nverts;
1558 pointlist = new REAL[nverts * 3];
1559 }
1560 }
1561 }
1562 if (nfaces == 0) {
1563 // Find if it is the keyword "face".
1564 str = strstr(bufferp, "face");
1565 if (!str) str = strstr(bufferp, "Face");
1566 if (str) {
1567 bufferp = findnextnumber(str);
1568 if (*bufferp == '\0') {
1569 printf("Syntax error reading face number on line");
1570 printf(" %d in file %s\n", line_count, infilename);
1571 fclose(fp);
1572 return false;
1573 }
1574 nfaces = (int) strtol(bufferp, &bufferp, 0);
1575 // Allocate memory for 'tetgenio'
1576 if (nfaces > 0) {
1577 numberoffacets = nfaces;
1578 facetlist = new tetgenio::facet[nfaces];
1579 }
1580 }
1581 }
1582 } // It is not the string "element".
1583 }
1584 if (format == 0) {
1585 // Find the keyword "format".
1586 str = strstr(bufferp, "format");
1587 if (!str) str = strstr(bufferp, "Format");
1588 if (str) {
1589 format = 1;
1590 bufferp = findnextfield(str);
1591 // Find if it is the string "ascii".
1592 str = strstr(bufferp, "ascii");
1593 if (!str) str = strstr(bufferp, "ASCII");
1594 if (!str) {
1595 printf("This routine only reads ascii format of ply files.\n");
1596 printf("Hint: You can convert the binary to ascii format by\n");
1597 printf(" using the provided ply tools:\n");
1598 printf(" ply2ascii < %s > ascii_%s\n", infilename, infilename);
1599 fclose(fp);
1600 return false;
1601 }
1602 }
1603 }
1604 } else if (iverts < nverts) {
1605 // Read vertex coordinates
1606 coord = &pointlist[iverts * 3];
1607 for (i = 0; i < 3; i++) {
1608 if (*bufferp == '\0') {
1609 printf("Syntax error reading vertex coords on line %d in file %s\n",
1610 line_count, infilename);
1611 fclose(fp);
1612 return false;
1613 }
1614 coord[i] = (REAL) strtod(bufferp, &bufferp);
1615 bufferp = findnextnumber(bufferp);
1616 }
1617 iverts++;
1618 } else if (ifaces < nfaces) {
1619 // Get next face
1620 f = &facetlist[ifaces];
1621 init(f);
1622 // In .off format, each facet has one polygon, no hole.
1623 f->numberofpolygons = 1;
1624 f->polygonlist = new tetgenio::polygon[1];
1625 p = &f->polygonlist[0];
1626 init(p);
1627 // Read the number of vertices, it should be greater than 0.
1628 p->numberofvertices = (int) strtol(bufferp, &bufferp, 0);
1629 if (p->numberofvertices == 0) {
1630 printf("Syntax error reading polygon on line %d in file %s\n",
1631 line_count, infilename);
1632 fclose(fp);
1633 return false;
1634 }
1635 // Allocate memory for face vertices
1636 p->vertexlist = new int[p->numberofvertices];
1637 for (i = 0; i < p->numberofvertices; i++) {
1638 bufferp = findnextnumber(bufferp);
1639 if (*bufferp == '\0') {
1640 printf("Syntax error reading polygon on line %d in file %s\n",
1641 line_count, infilename);
1642 fclose(fp);
1643 return false;
1644 }
1645 p->vertexlist[i] = (int) strtol(bufferp, &bufferp, 0);
1646 }
1647 ifaces++;
1648 } else {
1649 // Should never get here
1650 printf("Found extra text starting at line %d in file %s\n", line_count,
1651 infilename);
1652 break;
1653 }
1654 }
1655
1656 // Close file
1657 fclose(fp);
1658
1659 // Check whether read all points
1660 if (iverts != nverts) {
1661 printf("Expected %d vertices, but read only %d vertices in file %s\n",
1662 nverts, iverts, infilename);
1663 return false;
1664 }
1665
1666 // Check whether read all faces
1667 if (ifaces != nfaces) {
1668 printf("Expected %d faces, but read only %d faces in file %s\n",
1669 nfaces, ifaces, infilename);
1670 return false;
1671 }
1672
1673 return true;
1674 }
1675
1676 ///////////////////////////////////////////////////////////////////////////////
1677 // //
1678 // load_stl() Load a surface mesh described in a .stl file. //
1679 // //
1680 // 'filename' is the file name with extension .stl or without extension (the //
1681 // .stl will be added in this case). //
1682 // //
1683 // The .stl or stereolithography format is an ASCII or binary file used in //
1684 // manufacturing. It is a list of the triangular surfaces that describe a //
1685 // computer generated solid model. This is the standard input for most rapid //
1686 // prototyping machines. //
1687 // //
1688 // On completion, 'pointlist' and 'facetlist' together return the polyhedron.//
1689 // Note: After load_stl(), there exist many duplicated points in 'pointlist'.//
1690 // They will be unified during the Delaunay tetrahedralization process. //
1691 // //
1692 ///////////////////////////////////////////////////////////////////////////////
1693
1694 bool tetgenio::load_stl(char* filename)
1695 {
1696 FILE *fp;
1697 tetgenmesh::list *plist;
1698 tetgenio::facet *f;
1699 tetgenio::polygon *p;
1700 char infilename[FILENAMESIZE];
1701 char buffer[INPUTLINESIZE];
1702 char *bufferp, *str;
1703 double *coord;
1704 int solid = 0;
1705 int nverts = 0, iverts = 0;
1706 int nfaces = 0;
1707 int line_count = 0, i;
1708
1709 strncpy(infilename, filename, FILENAMESIZE - 1);
1710 infilename[FILENAMESIZE - 1] = '\0';
1711 if (infilename[0] == '\0') {
1712 printf("Error: No filename.\n");
1713 return false;
1714 }
1715 if (strcmp(&infilename[strlen(infilename) - 4], ".stl") != 0) {
1716 strcat(infilename, ".stl");
1717 }
1718
1719 if (!(fp = fopen(infilename, "r"))) {
1720 printf("Error: Unable to open file %s\n", infilename);
1721 return false;
1722 }
1723 printf("Opening %s.\n", infilename);
1724
1725 // STL file has no number of points available. Use a list to read points.
1726 plist = new tetgenmesh::list(sizeof(double) * 3, NULL, 1024);
1727
1728 while ((bufferp = readline(buffer, fp, &line_count)) != NULL) {
1729 // The ASCII .stl file must start with the lower case keyword solid and
1730 // end with endsolid.
1731 if (solid == 0) {
1732 // Read header
1733 bufferp = strstr(bufferp, "solid");
1734 if (bufferp != NULL) {
1735 solid = 1;
1736 }
1737 } else {
1738 // We're inside the block of the solid.
1739 str = bufferp;
1740 // Is this the end of the solid.
1741 bufferp = strstr(bufferp, "endsolid");
1742 if (bufferp != NULL) {
1743 solid = 0;
1744 } else {
1745 // Read the XYZ coordinates if it is a vertex.
1746 bufferp = str;
1747 bufferp = strstr(bufferp, "vertex");
1748 if (bufferp != NULL) {
1749 coord = (double *) plist->append(NULL);
1750 for (i = 0; i < 3; i++) {
1751 bufferp = findnextnumber(bufferp);
1752 if (*bufferp == '\0') {
1753 printf("Syntax error reading vertex coords on line %d\n",
1754 line_count);
1755 delete plist;
1756 fclose(fp);
1757 return false;
1758 }
1759 coord[i] = (REAL) strtod(bufferp, &bufferp);
1760 }
1761 }
1762 }
1763 }
1764 }
1765 fclose(fp);
1766
1767 nverts = plist->len();
1768 // nverts should be an integer times 3 (every 3 vertices denote a face).
1769 if (nverts == 0 || (nverts % 3 != 0)) {
1770 printf("Error: Wrong number of vertices in file %s.\n", infilename);
1771 delete plist;
1772 return false;
1773 }
1774 numberofpoints = nverts;
1775 pointlist = new REAL[nverts * 3];
1776 for (i = 0; i < nverts; i++) {
1777 coord = (double *) (* plist)[i];
1778 iverts = i * 3;
1779 pointlist[iverts] = (REAL) coord[0];
1780 pointlist[iverts + 1] = (REAL) coord[1];
1781 pointlist[iverts + 2] = (REAL) coord[2];
1782 }
1783
1784 nfaces = (int) (nverts / 3);
1785 numberoffacets = nfaces;
1786 facetlist = new tetgenio::facet[nfaces];
1787
1788 // Default use '1' as the array starting index.
1789 firstnumber = 1;
1790 iverts = firstnumber;
1791 for (i = 0; i < nfaces; i++) {
1792 f = &facetlist[i];
1793 init(f);
1794 // In .stl format, each facet has one polygon, no hole.
1795 f->numberofpolygons = 1;
1796 f->polygonlist = new tetgenio::polygon[1];
1797 p = &f->polygonlist[0];
1798 init(p);
1799 // Each polygon has three vertices.
1800 p->numberofvertices = 3;
1801 p->vertexlist = new int[p->numberofvertices];
1802 p->vertexlist[0] = iverts;
1803 p->vertexlist[1] = iverts + 1;
1804 p->vertexlist[2] = iverts + 2;
1805 iverts += 3;
1806 }
1807
1808 delete plist;
1809 return true;
1810 }
1811
1812 ///////////////////////////////////////////////////////////////////////////////
1813 // //
1814 // load_medit() Load a surface mesh described in .mesh file. //
1815 // //
1816 // 'filename' is the file name with extension .mesh or without entension ( //
1817 // the .mesh will be added in this case). .mesh is the file format of Medit, //
1818 // a user-friendly interactive mesh viewing program. //
1819 // //
1820 // This routine ONLY reads the sections containing vertices and triangles, //
1821 // other sections (such as tetrahedra, edges, ...) are ignored. //
1822 // //
1823 ///////////////////////////////////////////////////////////////////////////////
1824
1825 bool tetgenio::load_medit(char* filename)
1826 {
1827 FILE *fp;
1828 tetgenio::facet *f;
1829 tetgenio::polygon *p;
1830 char infilename[FILENAMESIZE];
1831 char buffer[INPUTLINESIZE];
1832 char *bufferp, *str;
1833 double *coord;
1834 int dimension = 0;
1835 int nverts = 0;
1836 int nfaces = 0;
1837 int line_count = 0;
1838 int corners = 0; // 3 (triangle) or 4 (quad).
1839 int i, j;
1840
1841 strncpy(infilename, filename, FILENAMESIZE - 1);
1842 infilename[FILENAMESIZE - 1] = '\0';
1843 if (infilename[0] == '\0') {
1844 printf("Error: No filename.\n");
1845 return false;
1846 }
1847 if (strcmp(&infilename[strlen(infilename) - 5], ".mesh") != 0) {
1848 strcat(infilename, ".mesh");
1849 }
1850
1851 if (!(fp = fopen(infilename, "r"))) {
1852 printf("Error: Unable to open file %s\n", infilename);
1853 return false;
1854 }
1855 printf("Opening %s.\n", infilename);
1856
1857 // Default uses the index starts from '1'.
1858 firstnumber = 1;
1859
1860 while ((bufferp = readline(buffer, fp, &line_count)) != NULL) {
1861 if (*bufferp == '#') continue; // A comment line is skipped.
1862 if (dimension == 0) {
1863 // Find if it is the keyword "Dimension".
1864 str = strstr(bufferp, "Dimension");
1865 if (!str) str = strstr(bufferp, "dimension");
1866 if (!str) str = strstr(bufferp, "DIMENSION");
1867 if (str) {
1868 // Read the dimensions
1869 bufferp = findnextnumber(str); // Skip field "Dimension".
1870 if (*bufferp == '\0') {
1871 // Read a non-empty line.
1872 bufferp = readline(buffer, fp, &line_count);
1873 }
1874 dimension = (int) strtol(bufferp, &bufferp, 0);
1875 if (dimension != 2 && dimension != 3) {
1876 printf("Unknown dimension in file on line %d in file %s\n",
1877 line_count, infilename);
1878 fclose(fp);
1879 return false;
1880 }
1881 mesh_dim = dimension;
1882 }
1883 }
1884 if (nverts == 0) {
1885 // Find if it is the keyword "Vertices".
1886 str = strstr(bufferp, "Vertices");
1887 if (!str) str = strstr(bufferp, "vertices");
1888 if (!str) str = strstr(bufferp, "VERTICES");
1889 if (str) {
1890 // Read the number of vertices.
1891 bufferp = findnextnumber(str); // Skip field "Vertices".
1892 if (*bufferp == '\0') {
1893 // Read a non-empty line.
1894 bufferp = readline(buffer, fp, &line_count);
1895 }
1896 nverts = (int) strtol(bufferp, &bufferp, 0);
1897 // Allocate memory for 'tetgenio'
1898 if (nverts > 0) {
1899 numberofpoints = nverts;
1900 pointlist = new REAL[nverts * 3];
1901 }
1902 // Read the follwoing node list.
1903 for (i = 0; i < nverts; i++) {
1904 bufferp = readline(buffer, fp, &line_count);
1905 if (bufferp == NULL) {
1906 printf("Unexpected end of file on line %d in file %s\n",
1907 line_count, infilename);
1908 fclose(fp);
1909 return false;
1910 }
1911 // Read vertex coordinates
1912 coord = &pointlist[i * 3];
1913 for (j = 0; j < 3; j++) {
1914 if (*bufferp == '\0') {
1915 printf("Syntax error reading vertex coords on line");
1916 printf(" %d in file %s\n", line_count, infilename);
1917 fclose(fp);
1918 return false;
1919 }
1920 if ((j < 2) || (dimension == 3)) {
1921 coord[j] = (REAL) strtod(bufferp, &bufferp);
1922 } else {
1923 assert((j == 2) && (dimension == 2));
1924 coord[j] = 0.0;
1925 }
1926 bufferp = findnextnumber(bufferp);
1927 }
1928 }
1929 continue;
1930 }
1931 }
1932 if (nfaces == 0) {
1933 // Find if it is the keyword "Triangles" or "Quadrilaterals".
1934 str = strstr(bufferp, "Triangles");
1935 if (!str) str = strstr(bufferp, "triangles");
1936 if (!str) str = strstr(bufferp, "TRIANGLES");
1937 if (str) {
1938 corners = 3;
1939 } else {
1940 str = strstr(bufferp, "Quadrilaterals");
1941 if (!str) str = strstr(bufferp, "quadrilaterals");
1942 if (!str) str = strstr(bufferp, "QUADRILATERALS");
1943 if (str) {
1944 corners = 4;
1945 }
1946 }
1947 if (corners == 3 || corners == 4) {
1948 // Read the number of triangles (or quadrilaterals).
1949 bufferp = findnextnumber(str); // Skip field "Triangles".
1950 if (*bufferp == '\0') {
1951 // Read a non-empty line.
1952 bufferp = readline(buffer, fp, &line_count);
1953 }
1954 nfaces = strtol(bufferp, &bufferp, 0);
1955 // Allocate memory for 'tetgenio'
1956 if (nfaces > 0) {
1957 numberoffacets = nfaces;
1958 facetlist = new tetgenio::facet[nfaces];
1959 facetmarkerlist = new int[nfaces];
1960 }
1961 // Read the following list of faces.
1962 for (i = 0; i < nfaces; i++) {
1963 bufferp = readline(buffer, fp, &line_count);
1964 if (bufferp == NULL) {
1965 printf("Unexpected end of file on line %d in file %s\n",
1966 line_count, infilename);
1967 fclose(fp);
1968 return false;
1969 }
1970 f = &facetlist[i];
1971 tetgenio::init(f);
1972 // In .mesh format, each facet has one polygon, no hole.
1973 f->numberofpolygons = 1;
1974 f->polygonlist = new tetgenio::polygon[1];
1975 p = &f->polygonlist[0];
1976 tetgenio::init(p);
1977 p->numberofvertices = corners;
1978 // Allocate memory for face vertices
1979 p->vertexlist = new int[p->numberofvertices];
1980 // Read the vertices of the face.
1981 for (j = 0; j < corners; j++) {
1982 if (*bufferp == '\0') {
1983 printf("Syntax error reading face on line %d in file %s\n",
1984 line_count, infilename);
1985 fclose(fp);
1986 return false;
1987 }
1988 p->vertexlist[j] = (int) strtol(bufferp, &bufferp, 0);
1989 if (firstnumber == 1) {
1990 // Check if a '0' index appears.
1991 if (p->vertexlist[j] == 0) {
1992 // The first index is set to be 0.
1993 firstnumber = 0;
1994 }
1995 }
1996 bufferp = findnextnumber(bufferp);
1997 }
1998 // Read the marker of the face if it exists.
1999 facetmarkerlist[i] = 0;
2000 if (*bufferp != '\0') {
2001 facetmarkerlist[i] = (int) strtol(bufferp, &bufferp, 0);
2002 }
2003 }
2004 continue;
2005 }
2006 }
2007 if (nverts > 0 && nfaces > 0) break; // Ignore other data.
2008 }
2009
2010 // Close file
2011 fclose(fp);
2012
2013 return true;
2014 }
2015
2016 ///////////////////////////////////////////////////////////////////////////////
2017 // //
2018 // load_plc() Load a piecewise linear complex from file. //
2019 // //
2020 // This is main entrance for loading plcs from different file formats into //
2021 // tetgenio. 'filename' is the input file name without extention. 'object' //
2022 // indicates which file format is used to describ the plc. //
2023 // //
2024 ///////////////////////////////////////////////////////////////////////////////
2025
2026 bool tetgenio::load_plc(char* filename, int object)
2027 {
2028 enum tetgenbehavior::objecttype type;
2029
2030 type = (enum tetgenbehavior::objecttype) object;
2031 switch (type) {
2032 case tetgenbehavior::NODES:
2033 return load_node(filename);
2034 case tetgenbehavior::POLY:
2035 return load_poly(filename);
2036 case tetgenbehavior::OFF:
2037 return load_off(filename);
2038 case tetgenbehavior::PLY:
2039 return load_ply(filename);
2040 case tetgenbehavior::STL:
2041 return load_stl(filename);
2042 case tetgenbehavior::MEDIT:
2043 return load_medit(filename);
2044 default:
2045 return load_poly(filename);
2046 }
2047 }
2048
2049 ///////////////////////////////////////////////////////////////////////////////
2050 // //
2051 // load_tetmesh() Load a tetrahedral mesh from files. //
2052 // //
2053 // 'filename' is the inputfile without suffix. The nodes of the tetrahedral //
2054 // mesh is in "filename.node", the elements is in "filename.ele", if the //
2055 // "filename.face" and "filename.vol" exists, they will also be read. //
2056 // //
2057 ///////////////////////////////////////////////////////////////////////////////
2058
2059 bool tetgenio::load_tetmesh(char* filename)
2060 {
2061 FILE *infile;
2062 char innodefilename[FILENAMESIZE];
2063 char inelefilename[FILENAMESIZE];
2064 char infacefilename[FILENAMESIZE];
2065 char inedgefilename[FILENAMESIZE];
2066 char involfilename[FILENAMESIZE];
2067 char inputline[INPUTLINESIZE];
2068 char *stringptr, *infilename;
2069 REAL attrib, volume;
2070 int volelements;
2071 int markers, corner;
2072 int index, attribindex;
2073 int i, j;
2074
2075 // Assembling the actual file names we want to open.
2076 strcpy(innodefilename, filename);
2077 strcpy(inelefilename, filename);
2078 strcpy(infacefilename, filename);
2079 strcpy(inedgefilename, filename);
2080 strcpy(involfilename, filename);
2081 strcat(innodefilename, ".node");
2082 strcat(inelefilename, ".ele");
2083 strcat(infacefilename, ".face");
2084 strcat(inedgefilename, ".edge");
2085 strcat(involfilename, ".vol");
2086
2087 // Read the points from a .node file.
2088 infilename = innodefilename;
2089 printf("Opening %s.\n", infilename);
2090 infile = fopen(infilename, "r");
2091 if (infile == (FILE *) NULL) {
2092 printf("File I/O Error: Cannot access file %s.\n", infilename);
2093 return false;
2094 }
2095 // Read number of points, number of dimensions, number of point
2096 // attributes, and number of boundary markers.
2097 stringptr = readnumberline(inputline, infile, infilename);
2098 numberofpoints = (int) strtol (stringptr, &stringptr, 0);
2099 stringptr = findnextnumber(stringptr);
2100 if (*stringptr == '\0') {
2101 mesh_dim = 3;
2102 } else {
2103 mesh_dim = (int) strtol (stringptr, &stringptr, 0);
2104 }
2105 stringptr = findnextnumber(stringptr);
2106 if (*stringptr == '\0') {
2107 numberofpointattributes = 0;
2108 } else {
2109 numberofpointattributes = (int) strtol (stringptr, &stringptr, 0);
2110 }
2111 stringptr = findnextnumber(stringptr);
2112 if (*stringptr == '\0') {
2113 markers = 0; // Default value.
2114 } else {
2115 markers = (int) strtol (stringptr, &stringptr, 0);
2116 }
2117
2118 if (mesh_dim != 3) {
2119 printf("Error: load_tetmesh() only works for 3D points.\n");
2120 fclose(infile);
2121 return false;
2122 }
2123 if (numberofpoints < 4) {
2124 printf("File I/O error: Input should has at least 4 points.\n");
2125 fclose(infile);
2126 return false;
2127 }
2128
2129 // Load the list of nodes.
2130 if (!load_node_call(infile, markers, infilename)) {
2131 fclose(infile);
2132 return false;
2133 }
2134 fclose(infile);
2135
2136 // Read the elements from an .ele file.
2137 infilename = inelefilename;
2138 infile = fopen(infilename, "r");
2139 if (infile != (FILE *) NULL) {
2140 printf("Opening %s.\n", infilename);
2141 // Read number of elements, number of corners (4 or 10), number of
2142 // element attributes.
2143 stringptr = readnumberline(inputline, infile, infilename);
2144 numberoftetrahedra = (int) strtol (stringptr, &stringptr, 0);
2145 stringptr = findnextnumber(stringptr);
2146 if (*stringptr == '\0') {
2147 numberofcorners = 4; // Default read 4 nodes per element.
2148 } else {
2149 numberofcorners = (int) strtol (stringptr, &stringptr, 0);
2150 }
2151 stringptr = findnextnumber(stringptr);
2152 if (*stringptr == '\0') {
2153 numberoftetrahedronattributes = 0; // Default no attribute.
2154 } else {
2155 numberoftetrahedronattributes = (int) strtol (stringptr, &stringptr, 0);
2156 }
2157 if (numberofcorners != 4 && numberofcorners != 10) {
2158 printf("Error: Wrong number of corners %d (should be 4 or 10).\n",
2159 numberofcorners);
2160 fclose(infile);
2161 return false;
2162 }
2163 // Allocate memory for tetrahedra.
2164 if (numberoftetrahedra > 0) {
2165 tetrahedronlist = new int[numberoftetrahedra * numberofcorners];
2166 if (tetrahedronlist == (int *) NULL) {
2167 printf("Error: Out of memory.\n");
2168 terminatetetgen(1);
2169 }
2170 // Allocate memory for output tetrahedron attributes if necessary.
2171 if (numberoftetrahedronattributes > 0) {
2172 tetrahedronattributelist = new REAL[numberoftetrahedra *
2173 numberoftetrahedronattributes];
2174 if (tetrahedronattributelist == (REAL *) NULL) {
2175 printf("Error: Out of memory.\n");
2176 terminatetetgen(1);
2177 }
2178 }
2179 }
2180 // Read the list of tetrahedra.
2181 index = 0;
2182 attribindex = 0;
2183 for (i = 0; i < numberoftetrahedra; i++) {
2184 // Read tetrahedron index and the tetrahedron's corners.
2185 stringptr = readnumberline(inputline, infile, infilename);
2186 for (j = 0; j < numberofcorners; j++) {
2187 stringptr = findnextnumber(stringptr);
2188 if (*stringptr == '\0') {
2189 printf("Error: Tetrahedron %d is missing vertex %d in %s.\n",
2190 i + firstnumber, j + 1, infilename);
2191 terminatetetgen(1);
2192 }
2193 corner = (int) strtol(stringptr, &stringptr, 0);
2194 if (corner < firstnumber || corner >= numberofpoints + firstnumber) {
2195 printf("Error: Tetrahedron %d has an invalid vertex index.\n",
2196 i + firstnumber);
2197 terminatetetgen(1);
2198 }
2199 tetrahedronlist[index++] = corner;
2200 }
2201 // Read the tetrahedron's attributes.
2202 for (j = 0; j < numberoftetrahedronattributes; j++) {
2203 stringptr = findnextnumber(stringptr);
2204 if (*stringptr == '\0') {
2205 attrib = 0.0;
2206 } else {
2207 attrib = (REAL) strtod(stringptr, &stringptr);
2208 }
2209 tetrahedronattributelist[attribindex++] = attrib;
2210 }
2211 }
2212 fclose(infile);
2213 }
2214
2215 // Read the hullfaces or subfaces from a .face file if it exists.
2216 infilename = infacefilename;
2217 infile = fopen(infilename, "r");
2218 if (infile != (FILE *) NULL) {
2219 printf("Opening %s.\n", infilename);
2220 // Read number of faces, boundary markers.
2221 stringptr = readnumberline(inputline, infile, infilename);
2222 numberoftrifaces = (int) strtol (stringptr, &stringptr, 0);
2223 stringptr = findnextnumber(stringptr);
2224 if (*stringptr == '\0') {
2225 markers = 0; // Default there is no marker per face.
2226 } else {
2227 markers = (int) strtol (stringptr, &stringptr, 0);
2228 }
2229 if (numberoftrifaces > 0) {
2230 trifacelist = new int[numberoftrifaces * 3];
2231 if (trifacelist == (int *) NULL) {
2232 printf("Error: Out of memory.\n");
2233 terminatetetgen(1);
2234 }
2235 if (markers) {
2236 trifacemarkerlist = new int[numberoftrifaces * 3];
2237 if (trifacemarkerlist == (int *) NULL) {
2238 printf("Error: Out of memory.\n");
2239 terminatetetgen(1);
2240 }
2241 }
2242 }
2243 // Read the list of faces.
2244 index = 0;
2245 for (i = 0; i < numberoftrifaces; i++) {
2246 // Read face index and the face's three corners.
2247 stringptr = readnumberline(inputline, infile, infilename);
2248 for (j = 0; j < 3; j++) {
2249 stringptr = findnextnumber(stringptr);
2250 if (*stringptr == '\0') {
2251 printf("Error: Face %d is missing vertex %d in %s.\n",
2252 i + firstnumber, j + 1, infilename);
2253 terminatetetgen(1);
2254 }
2255 corner = (int) strtol(stringptr, &stringptr, 0);
2256 if (corner < firstnumber || corner >= numberofpoints + firstnumber) {
2257 printf("Error: Face %d has an invalid vertex index.\n",
2258 i + firstnumber);
2259 terminatetetgen(1);
2260 }
2261 trifacelist[index++] = corner;
2262 }
2263 // Read the boundary marker if it exists.
2264 if (markers) {
2265 stringptr = findnextnumber(stringptr);
2266 if (*stringptr == '\0') {
2267 attrib = 0.0;
2268 } else {
2269 attrib = (REAL) strtod(stringptr, &stringptr);
2270 }
2271 trifacemarkerlist[i] = (int) attrib;
2272 }
2273 }
2274 fclose(infile);
2275 }
2276
2277 // Read the boundary edges from a .edge file if it exists.
2278 infilename = inedgefilename;
2279 infile = fopen(infilename, "r");
2280 if (infile != (FILE *) NULL) {
2281 printf("Opening %s.\n", infilename);
2282 // Read number of boundary edges.
2283 stringptr = readnumberline(inputline, infile, infilename);
2284 numberofedges = (int) strtol (stringptr, &stringptr, 0);
2285 if (numberofedges > 0) {
2286 edgelist = new int[numberofedges * 2];
2287 if (edgelist == (int *) NULL) {
2288 printf("Error: Out of memory.\n");
2289 terminatetetgen(1);
2290 }
2291 }
2292 // Read the list of faces.
2293 index = 0;
2294 for (i = 0; i < numberofedges; i++) {
2295 // Read face index and the edge's two endpoints.
2296 stringptr = readnumberline(inputline, infile, infilename);
2297 for (j = 0; j < 2; j++) {
2298 stringptr = findnextnumber(stringptr);
2299 if (*stringptr == '\0') {
2300 printf("Error: Edge %d is missing vertex %d in %s.\n",
2301 i + firstnumber, j + 1, infilename);
2302 terminatetetgen(1);
2303 }
2304 corner = (int) strtol(stringptr, &stringptr, 0);
2305 if (corner < firstnumber || corner >= numberofpoints + firstnumber) {
2306 printf("Error: Edge %d has an invalid vertex index.\n",
2307 i + firstnumber);
2308 terminatetetgen(1);
2309 }
2310 edgelist[index++] = corner;
2311 }
2312 }
2313 fclose(infile);
2314 }
2315
2316 // Read the volume constraints from a .vol file if it exists.
2317 infilename = involfilename;
2318 infile = fopen(infilename, "r");
2319 if (infile != (FILE *) NULL) {
2320 printf("Opening %s.\n", infilename);
2321 // Read number of tetrahedra.
2322 stringptr = readnumberline(inputline, infile, infilename);
2323 volelements = (int) strtol (stringptr, &stringptr, 0);
2324 if (volelements != numberoftetrahedra) {
2325 printf("Warning: %s and %s disagree on number of tetrahedra.\n",
2326 inelefilename, involfilename);
2327 volelements = 0;
2328 }
2329 if (volelements > 0) {
2330 tetrahedronvolumelist = new REAL[volelements];
2331 if (tetrahedronvolumelist == (REAL *) NULL) {
2332 printf("Error: Out of memory.\n");
2333 terminatetetgen(1);
2334 }
2335 }
2336 // Read the list of volume constraints.
2337 for (i = 0; i < volelements; i++) {
2338 stringptr = readnumberline(inputline, infile, infilename);
2339 stringptr = findnextnumber(stringptr);
2340 if (*stringptr == '\0') {
2341 volume = -1.0; // No constraint on this tetrahedron.
2342 } else {
2343 volume = (REAL) strtod(stringptr, &stringptr);
2344 }
2345 tetrahedronvolumelist[i] = volume;
2346 }
2347 fclose(infile);
2348 }
2349
2350 // Try to load a .mtr file if it exists.
2351 load_mtr(filename);
2352 // Try to read a .pbc file if it exists.
2353 load_pbc(filename);
2354
2355 return true;
2356 }
2357
2358 ///////////////////////////////////////////////////////////////////////////////
2359 // //
2360 // save_nodes() Save points to a .node file. //
2361 // //
2362 // 'filename' is a string containing the file name without suffix. //
2363 // //
2364 ///////////////////////////////////////////////////////////////////////////////
2365
2366 void tetgenio::save_nodes(char* filename)
2367 {
2368 FILE *fout;
2369 char outnodefilename[FILENAMESIZE];
2370 int i, j;
2371
2372 sprintf(outnodefilename, "%s.node", filename);
2373 printf("Saving nodes to %s\n", outnodefilename);
2374 fout = fopen(outnodefilename, "w");
2375 fprintf(fout, "%d %d %d %d\n", numberofpoints, mesh_dim,
2376 numberofpointattributes, pointmarkerlist != NULL ? 1 : 0);
2377 for (i = 0; i < numberofpoints; i++) {
2378 if (mesh_dim == 2) {
2379 fprintf(fout, "%d %.16g %.16g", i + firstnumber, pointlist[i * 2],
2380 pointlist[i * 2 + 1]);
2381 } else {
2382 fprintf(fout, "%d %.16g %.16g %.16g", i + firstnumber,
2383 pointlist[i * 3], pointlist[i * 3 + 1], pointlist[i * 3 + 2]);
2384 }
2385 for (j = 0; j < numberofpointattributes; j++) {
2386 fprintf(fout, " %.16g",
2387 pointattributelist[i * numberofpointattributes + j]);
2388 }
2389 if (pointmarkerlist != NULL) {
2390 fprintf(fout, " %d", pointmarkerlist[i]);
2391 }
2392 fprintf(fout, "\n");
2393 }
2394
2395 fclose(fout);
2396 }
2397
2398 ///////////////////////////////////////////////////////////////////////////////
2399 // //
2400 // save_elements() Save elements to a .ele file. //
2401 // //
2402 // 'filename' is a string containing the file name without suffix. //
2403 // //
2404 ///////////////////////////////////////////////////////////////////////////////
2405
2406 void tetgenio::save_elements(char* filename)
2407 {
2408 FILE *fout;
2409 char outelefilename[FILENAMESIZE];
2410 int i, j;
2411
2412 sprintf(outelefilename, "%s.ele", filename);
2413 printf("Saving elements to %s\n", outelefilename);
2414 fout = fopen(outelefilename, "w");
2415 fprintf(fout, "%d %d %d\n", numberoftetrahedra, numberofcorners,
2416 numberoftetrahedronattributes);
2417 for (i = 0; i < numberoftetrahedra; i++) {
2418 fprintf(fout, "%d", i + firstnumber);
2419 for (j = 0; j < numberofcorners; j++) {
2420 fprintf(fout, " %5d", tetrahedronlist[i * numberofcorners + j]);
2421 }
2422 for (j = 0; j < numberoftetrahedronattributes; j++) {
2423 fprintf(fout, " %g",
2424 tetrahedronattributelist[i * numberoftetrahedronattributes + j]);
2425 }
2426 fprintf(fout, "\n");
2427 }
2428
2429 fclose(fout);
2430 }
2431
2432 ///////////////////////////////////////////////////////////////////////////////
2433 // //
2434 // save_faces() Save faces to a .face file. //
2435 // //
2436 // 'filename' is a string containing the file name without suffix. //
2437 // //
2438 ///////////////////////////////////////////////////////////////////////////////
2439
2440 void tetgenio::save_faces(char* filename)
2441 {
2442 FILE *fout;
2443 char outfacefilename[FILENAMESIZE];
2444 int i;
2445
2446 sprintf(outfacefilename, "%s.face", filename);
2447 printf("Saving faces to %s\n", outfacefilename);
2448 fout = fopen(outfacefilename, "w");
2449 fprintf(fout, "%d %d\n", numberoftrifaces,
2450 trifacemarkerlist != NULL ? 1 : 0);
2451 for (i = 0; i < numberoftrifaces; i++) {
2452 fprintf(fout, "%d %5d %5d %5d", i + firstnumber, trifacelist[i * 3],
2453 trifacelist[i * 3 + 1], trifacelist[i * 3 + 2]);
2454 if (trifacemarkerlist != NULL) {
2455 fprintf(fout, " %d", trifacemarkerlist[i]);
2456 }
2457 fprintf(fout, "\n");
2458 }
2459
2460 fclose(fout);
2461 }
2462
2463 ///////////////////////////////////////////////////////////////////////////////
2464 // //
2465 // save_edges() Save egdes to a .edge file. //
2466 // //
2467 // 'filename' is a string containing the file name without suffix. //
2468 // //
2469 ///////////////////////////////////////////////////////////////////////////////
2470
2471 void tetgenio::save_edges(char* filename)
2472 {
2473 FILE *fout;
2474 char outedgefilename[FILENAMESIZE];
2475 int i;
2476
2477 sprintf(outedgefilename, "%s.edge", filename);
2478 printf("Saving edges to %s\n", outedgefilename);
2479 fout = fopen(outedgefilename, "w");
2480 fprintf(fout, "%d %d\n", numberofedges, edgemarkerlist != NULL ? 1 : 0);
2481 for (i = 0; i < numberofedges; i++) {
2482 fprintf(fout, "%d %4d %4d", i + firstnumber, edgelist[i * 2],
2483 edgelist[i * 2 + 1]);
2484 if (edgemarkerlist != NULL) {
2485 fprintf(fout, " %d", edgemarkerlist[i]);
2486 }
2487 fprintf(fout, "\n");
2488 }
2489
2490 fclose(fout);
2491 }
2492
2493 ///////////////////////////////////////////////////////////////////////////////
2494 // //
2495 // save_neighbors() Save egdes to a .neigh file. //
2496 // //
2497 // 'filename' is a string containing the file name without suffix. //
2498 // //
2499 ///////////////////////////////////////////////////////////////////////////////
2500
2501 void tetgenio::save_neighbors(char* filename)
2502 {
2503 FILE *fout;
2504 char outneighborfilename[FILENAMESIZE];
2505 int i;
2506
2507 sprintf(outneighborfilename, "%s.neigh", filename);
2508 printf("Saving neighbors to %s\n", outneighborfilename);
2509 fout = fopen(outneighborfilename, "w");
2510 fprintf(fout, "%d %d\n", numberoftetrahedra, mesh_dim + 1);
2511 for (i = 0; i < numberoftetrahedra; i++) {
2512 if (mesh_dim == 2) {
2513 fprintf(fout, "%d %5d %5d %5d", i + firstnumber, neighborlist[i * 3],
2514 neighborlist[i * 3 + 1], neighborlist[i * 3 + 2]);
2515 } else {
2516 fprintf(fout, "%d %5d %5d %5d %5d", i + firstnumber,
2517 neighborlist[i * 4], neighborlist[i * 4 + 1],
2518 neighborlist[i * 4 + 2], neighborlist[i * 4 + 3]);
2519 }
2520 fprintf(fout, "\n");
2521 }
2522
2523 fclose(fout);
2524 }
2525
2526 ///////////////////////////////////////////////////////////////////////////////
2527 // //
2528 // save_poly() Save segments or facets to a .poly file. //
2529 // //
2530 // 'filename' is a string containing the file name without suffix. It only //
2531 // save the facets, holes and regions. The nodes are saved in a .node file //
2532 // by routine save_nodes(). //
2533 // //
2534 ///////////////////////////////////////////////////////////////////////////////
2535
2536 void tetgenio::save_poly(char* filename)
2537 {
2538 FILE *fout;
2539 facet *f;
2540 polygon *p;
2541 char outpolyfilename[FILENAMESIZE];
2542 int i, j, k;
2543
2544 sprintf(outpolyfilename, "%s.poly", filename);
2545 printf("Saving poly to %s\n", outpolyfilename);
2546 fout = fopen(outpolyfilename, "w");
2547
2548 // The zero indicates that the vertices are in a separate .node file.
2549 // Followed by number of dimensions, number of vertex attributes,
2550 // and number of boundary markers (zero or one).
2551 fprintf(fout, "%d %d %d %d\n", 0, mesh_dim, numberofpointattributes,
2552 pointmarkerlist != NULL ? 1 : 0);
2553
2554 // Save segments or facets.
2555 if (mesh_dim == 2) {
2556 // Number of segments, number of boundary markers (zero or one).
2557 fprintf(fout, "%d %d\n", numberofedges, edgemarkerlist != NULL ? 1 : 0);
2558 for (i = 0; i < numberofedges; i++) {
2559 fprintf(fout, "%d %4d %4d", i + firstnumber, edgelist[i * 2],
2560 edgelist[i * 2 + 1]);
2561 if (edgemarkerlist != NULL) {
2562 fprintf(fout, " %d", edgemarkerlist[i]);
2563 }
2564 fprintf(fout, "\n");
2565 }
2566 } else {
2567 // Number of facets, number of boundary markers (zero or one).
2568 fprintf(fout, "%d %d\n", numberoffacets, facetmarkerlist != NULL ? 1 : 0);
2569 for (i = 0; i < numberoffacets; i++) {
2570 f = &(facetlist[i]);
2571 fprintf(fout, "%d %d %d # %d\n", f->numberofpolygons,f->numberofholes,
2572 facetmarkerlist != NULL ? facetmarkerlist[i] : 0, i + firstnumber);
2573 // Output polygons of this facet.
2574 for (j = 0; j < f->numberofpolygons; j++) {
2575 p = &(f->polygonlist[j]);
2576 fprintf(fout, "%d ", p->numberofvertices);
2577 for (k = 0; k < p->numberofvertices; k++) {
2578 if (((k + 1) % 10) == 0) {
2579 fprintf(fout, "\n ");
2580 }
2581 fprintf(fout, " %d", p->vertexlist[k]);
2582 }
2583 fprintf(fout, "\n");
2584 }
2585 // Output holes of this facet.
2586 for (j = 0; j < f->numberofholes; j++) {
2587 fprintf(fout, "%d %.12g %.12g %.12g\n", j + firstnumber,
2588 f->holelist[j * 3], f->holelist[j * 3 + 1], f->holelist[j * 3 + 2]);
2589 }
2590 }
2591 }
2592
2593 // Save holes.
2594 fprintf(fout, "%d\n", numberofholes);
2595 for (i = 0; i < numberofholes; i++) {
2596 // Output x, y coordinates.
2597 fprintf(fout, "%d %.12g %.12g", i + firstnumber, holelist[i * mesh_dim],
2598 holelist[i * mesh_dim + 1]);
2599 if (mesh_dim == 3) {
2600 // Output z coordinate.
2601 fprintf(fout, " %.12g", holelist[i * mesh_dim + 2]);
2602 }
2603 fprintf(fout, "\n");
2604 }
2605
2606 // Save regions.
2607 fprintf(fout, "%d\n", numberofregions);
2608 for (i = 0; i < numberofregions; i++) {
2609 if (mesh_dim == 2) {
2610 // Output the index, x, y coordinates, attribute (region number)
2611 // and maximum area constraint (maybe -1).
2612 fprintf(fout, "%d %.12g %.12g %.12g %.12g\n", i + firstnumber,
2613 regionlist[i * 4], regionlist[i * 4 + 1],
2614 regionlist[i * 4 + 2], regionlist[i * 4 + 3]);
2615 } else {
2616 // Output the index, x, y, z coordinates, attribute (region number)
2617 // and maximum volume constraint (maybe -1).
2618 fprintf(fout, "%d %.12g %.12g %.12g %.12g %.12g\n", i + firstnumber,
2619 regionlist[i * 5], regionlist[i * 5 + 1],
2620 regionlist[i * 5 + 2], regionlist[i * 5 + 3],
2621 regionlist[i * 5 + 4]);
2622 }
2623 }
2624
2625 fclose(fout);
2626 }
2627
2628 ///////////////////////////////////////////////////////////////////////////////
2629 // //
2630 // readline() Read a nonempty line from a file. //
2631 // //
2632 // A line is considered "nonempty" if it contains something more than white //
2633 // spaces. If a line is considered empty, it will be dropped and the next //
2634 // line will be read, this process ends until reaching the end-of-file or a //
2635 // non-empty line. Return NULL if it is the end-of-file, otherwise, return //
2636 // a pointer to the first non-whitespace character of the line. //
2637 // //
2638 ///////////////////////////////////////////////////////////////////////////////
2639
2640 char* tetgenio::readline(char *string, FILE *infile, int *linenumber)
2641 {
2642 char *result;
2643
2644 // Search for a non-empty line.
2645 do {
2646 result = fgets(string, INPUTLINESIZE - 1, infile);
2647 if (linenumber) (*linenumber)++;
2648 if (result == (char *) NULL) {
2649 return (char *) NULL;
2650 }
2651 // Skip white spaces.
2652 while ((*result == ' ') || (*result == '\t')) result++;
2653 // If it's end of line, read another line and try again.
2654 } while (*result == '\0');
2655 return result;
2656 }
2657
2658 ///////////////////////////////////////////////////////////////////////////////
2659 // //
2660 // findnextfield() Find the next field of a string. //
2661 // //
2662 // Jumps past the current field by searching for whitespace or a comma, then //
2663 // jumps past the whitespace or the comma to find the next field. //
2664 // //
2665 ///////////////////////////////////////////////////////////////////////////////
2666
2667 char* tetgenio::findnextfield(char *string)
2668 {
2669 char *result;
2670
2671 result = string;
2672 // Skip the current field. Stop upon reaching whitespace or a comma.
2673 while ((*result != '\0') && (*result != ' ') && (*result != '\t') &&
2674 (*result != ',') && (*result != ';')) {
2675 result++;
2676 }
2677 // Now skip the whitespace or the comma, stop at anything else that looks
2678 // like a character, or the end of a line.
2679 while ((*result == ' ') || (*result == '\t') || (*result == ',') ||
2680 (*result == ';')) {
2681 result++;
2682 }
2683 return result;
2684 }
2685
2686 ///////////////////////////////////////////////////////////////////////////////
2687 // //
2688 // readnumberline() Read a nonempty number line from a file. //
2689 // //
2690 // A line is considered "nonempty" if it contains something that looks like //
2691 // a number. Comments (prefaced by `#') are ignored. //
2692 // //
2693 ///////////////////////////////////////////////////////////////////////////////
2694
2695 char* tetgenio::readnumberline(char *string, FILE *infile, char *infilename)
2696 {
2697 char *result;
2698
2699 // Search for something that looks like a number.
2700 do {
2701 result = fgets(string, INPUTLINESIZE, infile);
2702 if (result == (char *) NULL) {
2703 if (infilename != (char *) NULL) {
2704 printf(" Error: Unexpected end of file in %s.\n", infilename);
2705 terminatetetgen(1);
2706 }
2707 return result;
2708 }
2709 // Skip anything that doesn't look like a number, a comment,
2710 // or the end of a line.
2711 while ((*result != '\0') && (*result != '#')
2712 && (*result != '.') && (*result != '+') && (*result != '-')
2713 && ((*result < '0') || (*result > '9'))) {
2714 result++;
2715 }
2716 // If it's a comment or end of line, read another line and try again.
2717 } while ((*result == '#') || (*result == '\0'));
2718 return result;
2719 }
2720
2721 ///////////////////////////////////////////////////////////////////////////////
2722 // //
2723 // findnextnumber() Find the next field of a number string. //
2724 // //
2725 // Jumps past the current field by searching for whitespace or a comma, then //
2726 // jumps past the whitespace or the comma to find the next field that looks //
2727 // like a number. //
2728 // //
2729 ///////////////////////////////////////////////////////////////////////////////
2730
2731 char* tetgenio::findnextnumber(char *string)
2732 {
2733 char *result;
2734
2735 result = string;
2736 // Skip the current field. Stop upon reaching whitespace or a comma.
2737 while ((*result != '\0') && (*result != '#') && (*result != ' ') &&
2738 (*result != '\t') && (*result != ',')) {
2739 result++;
2740 }
2741 // Now skip the whitespace and anything else that doesn't look like a
2742 // number, a comment, or the end of a line.
2743 while ((*result != '\0') && (*result != '#')
2744 && (*result != '.') && (*result != '+') && (*result != '-')
2745 && ((*result < '0') || (*result > '9'))) {
2746 result++;
2747 }
2748 // Check for a comment (prefixed with `#').
2749 if (*result == '#') {
2750 *result = '\0';
2751 }
2752 return result;
2753 }
2754
2755 //
2756 // End of class 'tetgenio' implementation
2757 //
2758
2759 static REAL PI = 3.14159265358979323846264338327950288419716939937510582;
2760
2761 //
2762 // Begin of class 'tetgenbehavior' implementation
2763 //
2764
2765 ///////////////////////////////////////////////////////////////////////////////
2766 // //
2767 // tetgenbehavior() Initialize veriables of 'tetgenbehavior'. //
2768 // //
2769 ///////////////////////////////////////////////////////////////////////////////
2770
2771 tetgenbehavior::tetgenbehavior()
2772 {
2773 // Initialize command line switches.
2774 plc = 0;
2775 refine = 0;
2776 quality = 0;
2777 smooth = 1;
2778 metric = 0;
2779 bgmesh = 0;
2780 minratio = 2.0;
2781 goodratio = 0.0;
2782 minangle = 20.0;
2783 goodangle = 0.0;
2784 maxdihedral = 170.0;
2785 varvolume = 0;
2786 fixedvolume = 0;
2787 maxvolume = -1.0;
2788 regionattrib = 0;
2789 insertaddpoints = 0;
2790 diagnose = 0;
2791 offcenter = 0;
2792 conformdel = 0;
2793 alpha1 = sqrt(2.0);
2794 alpha2 = 0.5;
2795 alpha3 = 0.6;
2796 zeroindex = 0;
2797 facesout = 0;
2798 edgesout = 0;
2799 neighout = 0;
2800 meditview = 0;
2801 gidview = 0;
2802 geomview = 0;
2803 order = 1;
2804 nojettison = 0;
2805 nobound = 0;
2806 nonodewritten = 0;
2807 noelewritten = 0;
2808 nofacewritten = 0;
2809 noiterationnum = 0;
2810 nobisect = 0;
2811 noflip = 0;
2812 steiner = -1;
2813 fliprepair = 1;
2814 nomerge = 0;
2815 docheck = 0;
2816 quiet = 1; // Zeyun Yu
2817 verbose = 0;
2818 tol = 0;
2819 useshelles = 0;
2820 epsilon = 1.0e-8;
2821 epsilon2 = 1.0e-5;
2822 object = NONE;
2823 // Initialize strings
2824 commandline[0] = '\0';
2825 infilename[0] = '\0';
2826 outfilename[0] = '\0';
2827 bgmeshfilename[0] = '\0';
2828 }
2829
2830 ///////////////////////////////////////////////////////////////////////////////
2831 // //
2832 // versioninfo() Print the version information of TetGen. //
2833 // //
2834 ///////////////////////////////////////////////////////////////////////////////
2835
2836 void tetgenbehavior::versioninfo()
2837 {
2838 printf("Version 1.4.1 (July 06, 2006).\n");
2839 }
2840
2841 ///////////////////////////////////////////////////////////////////////////////
2842 // //
2843 // syntax() Print list of command line switches and exit the program. //
2844 // //
2845 ///////////////////////////////////////////////////////////////////////////////
2846
2847 void tetgenbehavior::syntax()
2848 {
2849 printf(" tetgen [-pq__a__AriMYS__T__dzjo_fengGOJBNEFICQVvh] input_file\n");
2850 printf(" -p Tetrahedralizes a piecewise linear complex.\n");
2851 printf(" -q Quality mesh generation. A minimum radius-edge ratio may\n");
2852 printf(" be specified (default 2.0).\n");
2853 printf(" -a Applies a maximum tetrahedron volume constraint.\n");
2854 printf(" -A Assigns attributes to identify tetrahedra in different ");
2855 printf("regions.\n");
2856 printf(" -r Reconstructs and Refines a previously generated mesh.\n");
2857 printf(" -i Inserts a list of additional points into mesh.\n");
2858 printf(" -M Does not merge coplanar facets.\n");
2859 printf(" -Y Suppresses boundary facets/segments splitting.\n");
2860 printf(" -S Specifies maximum number of added Steiner points.\n");
2861 printf(" -T Set a tolerance for coplanar test (default 1e-8).\n");
2862 printf(" -d Diagnoses the validation of the input PLC.\n");
2863 printf(" -z Numbers all output items starting from zero.\n");
2864 printf(" -o2 Generates second-order subparametric elements.\n");
2865 printf(" -P Outputs triangulated PLC facets to .smesh file.\n");
2866 printf(" -f Outputs all faces (instead of boundary faces) to .face ");
2867 printf("file.\n");
2868 printf(" -e Outputs subsegments to .edge file.\n");
2869 printf(" -n Outputs tetrahedra neighbors to .neigh file.\n");
2870 printf(" -g Outputs mesh to .mesh file for viewing by Medit.\n");
2871 printf(" -G Outputs mesh to .msh file for viewing by Gid.\n");
2872 printf(" -O Outputs mesh to .off file for viewing by Geomview.\n");
2873 printf(" -J No jettison of unused vertices from output .node file.\n");
2874 printf(" -B Suppresses output of boundary information.\n");
2875 printf(" -N Suppresses output of .node file.\n");
2876 printf(" -E Suppresses output of .ele file.\n");
2877 printf(" -F Suppresses output of .face file.\n");
2878 printf(" -I Suppresses mesh iteration numbers.\n");
2879 printf(" -C Checks the consistency of the final mesh.\n");
2880 printf(" -Q Quiet: No terminal output except errors.\n");
2881 printf(" -V Verbose: Detailed information, more terminal output.\n");
2882 printf(" -v Prints the version information.\n");
2883 printf(" -h Help: A brief instruction for using TetGen.\n");
2884 }
2885
2886 ///////////////////////////////////////////////////////////////////////////////
2887 // //
2888 // usage() Print a brief instruction for using TetGen. //
2889 // //
2890 ///////////////////////////////////////////////////////////////////////////////
2891
2892 void tetgenbehavior::usage()
2893 {
2894 printf("TetGen\n");
2895 printf("A Quality Tetrahedral Mesh Generator and 3D Delaunay ");
2896 printf("Triangulator\n");
2897 versioninfo();
2898 printf("\n");
2899 printf("Copyright 2002, 2004, 2005, 2006\n");
2900 printf("Hang Si\n");
2901 printf("Rathausstr. 9, 10178 Berlin, Germany\n");
2902 printf("[email protected]\n");
2903 printf("\n");
2904 printf("What Can TetGen Do?\n");
2905 printf("\n");
2906 printf(" TetGen generates exact Delaunay tetrahedralizations, exact\n");
2907 printf(" constrained Delaunay tetrahedralizations, and quality ");
2908 printf("tetrahedral\n meshes. The latter are nicely graded and whose ");
2909 printf("tetrahedra have\n radius-edge ratio bounded, thus are suitable ");
2910 printf("for finite element and\n finite volume analysis.\n");
2911 printf("\n");
2912 printf("Command Line Syntax:\n");
2913 printf("\n");
2914 printf(" Below is the command line syntax of TetGen with a list of ");
2915 printf("short\n");
2916 printf(" descriptions. Underscores indicate that numbers may optionally\n");
2917 printf(" follow certain switches. Do not leave any space between a ");
2918 printf("switch\n");
2919 printf(" and its numeric parameter. \'input_file\' contains input data\n");
2920 printf(" depending on the switches you supplied which may be a ");
2921 printf(" piecewise\n");
2922 printf(" linear complex or a list of nodes. File formats and detailed\n");
2923 printf(" description of command line switches are found in user's ");
2924 printf("manual.\n");
2925 printf("\n");
2926 syntax();
2927 printf("\n");
2928 printf("Examples of How to Use TetGen:\n");
2929 printf("\n");
2930 printf(" \'tetgen object\' reads vertices from object.node, and writes ");
2931 printf("their\n Delaunay tetrahedralization to object.1.node and ");
2932 printf("object.1.ele.\n");
2933 printf("\n");
2934 printf(" \'tetgen -p object\' reads a PLC from object.poly or object.");
2935 printf("smesh (and\n possibly object.node) and writes its constrained ");
2936 printf("Delaunay\n tetrahedralization to object.1.node, object.1.ele and ");
2937 printf("object.1.face.\n");
2938 printf("\n");
2939 printf(" \'tetgen -pq1.414a.1 object\' reads a PLC from object.poly or\n");
2940 printf(" object.smesh (and possibly object.node), generates a mesh ");
2941 printf("whose\n tetrahedra have radius-edge ratio smaller than 1.414 and ");
2942 printf("have volume\n of 0.1 or less, and writes the mesh to ");
2943 printf("object.1.node, object.1.ele\n and object.1.face.\n");
2944 printf("\n");
2945 printf("Please send bugs/comments to Hang Si <[email protected]>\n");
2946 }
2947
2948 ///////////////////////////////////////////////////////////////////////////////
2949 // //
2950 // parse_commandline() Read the command line, identify switches, and set //
2951 // up options and file names. //
2952 // //
2953 // 'argc' and 'argv' are the same parameters passed to the function main() //
2954 // of a C/C++ program. They together represent the command line user invoked //
2955 // from an environment in which TetGen is running. //
2956 // //
2957 // When TetGen is invoked from an environment. 'argc' is nonzero, switches //
2958 // and input filename should be supplied as zero-terminated strings in //
2959 // argv[0] through argv[argc - 1] and argv[0] shall be the name used to //
2960 // invoke TetGen, i.e. "tetgen". Switches are previously started with a //
2961 // dash '-' to identify them from the input filename. //
2962 // //
2963 // When TetGen is called from within another program. 'argc' is set to zero. //
2964 // switches are given in one zero-terminated string (no previous dash is //
2965 // required.), and 'argv' is a pointer points to this string. No input //
2966 // filename is required (usually the input data has been directly created by //
2967 // user in the 'tetgenio' structure). A default filename 'tetgen-tmpfile' //
2968 // will be created for debugging output purpose. //
2969 // //
2970 ///////////////////////////////////////////////////////////////////////////////
2971
2972 bool tetgenbehavior::parse_commandline(int argc, char **argv)
2973 {
2974 int startindex;
2975 int increment;
2976 int meshnumber;
2977 int Rcount;
2978 int i, j, k;
2979 char workstring[1024];
2980
2981 // First determine the input style of the switches.
2982 if (argc == 0) {
2983 startindex = 0; // Switches are given without a dash.
2984 argc = 1; // For running the following for-loop once.
2985 commandline[0] = '\0';
2986 } else {
2987 startindex = 1;
2988 strcpy(commandline, argv[0]);
2989 strcat(commandline, " ");
2990 }
2991
2992 // Rcount used to count the number of '-R' be used.
2993 Rcount = 0;
2994
2995 for (i = startindex; i < argc; i++) {
2996 // Remember the command line switches.
2997 strcat(commandline, argv[i]);
2998 strcat(commandline, " ");
2999 if (startindex == 1) {
3000 // Is this string a filename?
3001 if (argv[i][0] != '-') {
3002 strncpy(infilename, argv[i], 1024 - 1);
3003 infilename[1024 - 1] = '\0';
3004 // Go to the next string directly.
3005 continue;
3006 }
3007 }
3008 // Parse the individual switch from the string.
3009 for (j = startindex; argv[i][j] != '\0'; j++) {
3010 if (argv[i][j] == 'p') {
3011 plc = 1;
3012 } else if (argv[i][j] == 'r') {
3013 refine = 1;
3014 } else if (argv[i][j] == 'm') {
3015 metric = 1;
3016 } else if (argv[i][j] == 'b') {
3017 bgmesh = 1;
3018 } else if (argv[i][j] == 'q') {
3019 quality = 1;
3020 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3021 (argv[i][j + 1] == '.')) {
3022 k = 0;
3023 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3024 (argv[i][j + 1] == '.')) {
3025 j++;
3026 workstring[k] = argv[i][j];
3027 k++;
3028 }
3029 workstring[k] = '\0';
3030 minratio = (REAL) strtod(workstring, (char **) NULL);
3031 }
3032 } else if (argv[i][j] == 'a') {
3033 quality = 1;
3034 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3035 (argv[i][j + 1] == '.')) {
3036 fixedvolume = 1;
3037 k = 0;
3038 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3039 (argv[i][j + 1] == '.') || (argv[i][j + 1] == 'e') ||
3040 (argv[i][j + 1] == '-') || (argv[i][j + 1] == '+')) {
3041 j++;
3042 workstring[k] = argv[i][j];
3043 k++;
3044 }
3045 workstring[k] = '\0';
3046 maxvolume = (REAL) strtod(workstring, (char **) NULL);
3047 } else {
3048 varvolume = 1;
3049 }
3050 } else if (argv[i][j] == 'A') {
3051 regionattrib++;
3052 } else if (argv[i][j] == 'i') {
3053 insertaddpoints = 1;
3054 } else if (argv[i][j] == 'd') {
3055 diagnose = 1;
3056 } else if (argv[i][j] == 'z') {
3057 zeroindex = 1;
3058 } else if (argv[i][j] == 'f') {
3059 facesout = 1;
3060 } else if (argv[i][j] == 'e') {
3061 edgesout = 1;
3062 } else if (argv[i][j] == 'n') {
3063 neighout++;
3064 } else if (argv[i][j] == 'g') {
3065 meditview = 1;
3066 } else if (argv[i][j] == 'G') {
3067 gidview = 1;
3068 } else if (argv[i][j] == 'O') {
3069 geomview = 1;
3070 } else if (argv[i][j] == 'M') {
3071 nomerge = 1;
3072 } else if (argv[i][j] == 'Y') {
3073 nobisect++;
3074 } else if (argv[i][j] == 'J') {
3075 nojettison = 1;
3076 } else if (argv[i][j] == 'B') {
3077 nobound = 1;
3078 } else if (argv[i][j] == 'N') {
3079 nonodewritten = 1;
3080 } else if (argv[i][j] == 'E') {
3081 noelewritten = 1;
3082 } else if (argv[i][j] == 'F') {
3083 nofacewritten = 1;
3084 } else if (argv[i][j] == 'I') {
3085 noiterationnum = 1;
3086 } else if (argv[i][j] == 'o') {
3087 if (argv[i][j + 1] == '2') {
3088 j++;
3089 order = 2;
3090 }
3091 } else if (argv[i][j] == 'S') {
3092 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3093 (argv[i][j + 1] == '.')) {
3094 k = 0;
3095 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3096 (argv[i][j + 1] == '.') || (argv[i][j + 1] == 'e') ||
3097 (argv[i][j + 1] == '-') || (argv[i][j + 1] == '+')) {
3098 j++;
3099 workstring[k] = argv[i][j];
3100 k++;
3101 }
3102 workstring[k] = '\0';
3103 steiner = (int) strtol(workstring, (char **) NULL, 0);
3104 }
3105 } else if (argv[i][j] == 's') {
3106 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3107 (argv[i][j + 1] == '.')) {
3108 k = 0;
3109 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3110 (argv[i][j + 1] == '.') || (argv[i][j + 1] == 'e') ||
3111 (argv[i][j + 1] == '-') || (argv[i][j + 1] == '+')) {
3112 j++;
3113 workstring[k] = argv[i][j];
3114 k++;
3115 }
3116 workstring[k] = '\0';
3117 maxdihedral = (REAL) strtod(workstring, (char **) NULL);
3118 if (maxdihedral >= 180.0) smooth = 0;
3119 }
3120 } else if (argv[i][j] == 'R') {
3121 Rcount++;
3122 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3123 (argv[i][j + 1] == '.')) {
3124 k = 0;
3125 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3126 (argv[i][j + 1] == '.') || (argv[i][j + 1] == 'e') ||
3127 (argv[i][j + 1] == '-') || (argv[i][j + 1] == '+')) {
3128 j++;
3129 workstring[k] = argv[i][j];
3130 k++;
3131 }
3132 workstring[k] = '\0';
3133 if (Rcount == 1) {
3134 alpha1 = (REAL) strtod(workstring, (char **) NULL);
3135 } else if (Rcount == 2) {
3136 alpha2 = (REAL) strtod(workstring, (char **) NULL);
3137 } else if (Rcount == 3) {
3138 alpha3 = (REAL) strtod(workstring, (char **) NULL);
3139 }
3140 }
3141 } else if (argv[i][j] == 'D') {
3142 conformdel++;
3143 } else if (argv[i][j] == 'T') {
3144 tol++;
3145 if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3146 (argv[i][j + 1] == '.')) {
3147 k = 0;
3148 while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
3149 (argv[i][j + 1] == '.') || (argv[i][j + 1] == 'e') ||
3150 (argv[i][j + 1] == '-') || (argv[i][j + 1] == '+')) {
3151 j++;
3152 workstring[k] = argv[i][j];
3153 k++;
3154 }
3155 workstring[k] = '\0';
3156 if (tol == 1) {
3157 epsilon = (REAL) strtod(workstring, (char **) NULL);
3158 } else if (tol == 2) {
3159 epsilon2 = (REAL) strtod(workstring, (char **) NULL);
3160 }
3161 }
3162 } else if (argv[i][j] == 'C') {
3163 docheck++;
3164 } else if (argv[i][j] == 'X') {
3165 fliprepair = 0;
3166 } else if (argv[i][j] == 'Q') {
3167 quiet = 1;
3168 } else if (argv[i][j] == 'V') {
3169 verbose++;
3170 } else if (argv[i][j] == 'v') {
3171 versioninfo();
3172 terminatetetgen(0);
3173 } else if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
3174 (argv[i][j] == '?')) {
3175 usage();
3176 terminatetetgen(0);
3177 } else {
3178 printf("Warning: Unknown switch -%c.\n", argv[i][j]);
3179 }
3180 }
3181 }
3182
3183 if (startindex == 0) {
3184 // Set a temporary filename for debugging output.
3185 strcpy(infilename, "tetgen-tmpfile");
3186 } else {
3187 if (infilename[0] == '\0') {
3188 // No input file name. Print the syntax and exit.
3189 syntax();
3190 terminatetetgen(0);
3191 }
3192 // Recognize the object from file extension if it is available.
3193 if (!strcmp(&infilename[strlen(infilename) - 5], ".node")) {
3194 infilename[strlen(infilename) - 5] = '\0';
3195 object = NODES;
3196 } else if (!strcmp(&infilename[strlen(infilename) - 5], ".poly")) {
3197 infilename[strlen(infilename) - 5] = '\0';
3198 object = POLY;
3199 plc = 1;
3200 } else if (!strcmp(&infilename[strlen(infilename) - 6], ".smesh")) {
3201 infilename[strlen(infilename) - 6] = '\0';
3202 object = POLY;
3203 plc = 1;
3204 } else if (!strcmp(&infilename[strlen(infilename) - 4], ".off")) {
3205 infilename[strlen(infilename) - 4] = '\0';
3206 object = OFF;
3207 plc = 1;
3208 } else if (!strcmp(&infilename[strlen(infilename) - 4], ".ply")) {
3209 infilename[strlen(infilename) - 4] = '\0';
3210 object = PLY;
3211 plc = 1;
3212 } else if (!strcmp(&infilename[strlen(infilename) - 4], ".stl")) {
3213 infilename[strlen(infilename) - 4] = '\0';
3214 object = STL;
3215 plc = 1;
3216 } else if (!strcmp(&infilename[strlen(infilename) - 5], ".mesh")) {
3217 infilename[strlen(infilename) - 5] = '\0';
3218 object = MEDIT;
3219 plc = 1;
3220 } else if (!strcmp(&infilename[strlen(infilename) - 4], ".ele")) {
3221 infilename[strlen(infilename) - 4] = '\0';
3222 object = MESH;
3223 refine = 1;
3224 }
3225 }
3226 plc = plc || diagnose;
3227 useshelles = plc || refine || quality;
3228 goodratio = minratio;
3229 goodratio *= goodratio;
3230
3231 // Detect improper combinations of switches.
3232 if (plc && refine) {
3233 printf("Error: Switch -r cannot use together with -p.\n");
3234 return false;
3235 }
3236 if (refine && (plc || noiterationnum)) {
3237 printf("Error: Switches %s cannot use together with -r.\n",
3238 "-p, -d, -c, and -I");
3239 return false;
3240 }
3241 if (diagnose && (quality || insertaddpoints || (order == 2) || neighout
3242 || docheck)) {
3243 printf("Error: Switches %s cannot use together with -d.\n",
3244 "-q, -i, -o2, -n, and -C");
3245 return false;
3246 }
3247
3248 // Be careful not to allocate space for element area constraints that
3249 // will never be assigned any value (other than the default -1.0).
3250 if (!refine && !plc) {
3251 varvolume = 0;
3252 }
3253 // Be careful not to add an extra attribute to each element unless the
3254 // input supports it (PLC in, but not refining a preexisting mesh).
3255 if (refine || !plc) {
3256 regionattrib = 0;
3257 }
3258 // Calculate the goodangle for testing bad subfaces.
3259 goodangle = cos(minangle * PI / 180.0);
3260 goodangle *= goodangle;
3261
3262 increment = 0;
3263 strcpy(workstring, infilename);
3264 j = 1;
3265 while (workstring[j] != '\0') {
3266 if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
3267 increment = j + 1;
3268 }
3269 j++;
3270 }
3271 meshnumber = 0;
3272 if (increment > 0) {
3273 j = increment;
3274 do {
3275 if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
3276 meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
3277 } else {
3278 increment = 0;
3279 }
3280 j++;
3281 } while (workstring[j] != '\0');
3282 }
3283 if (noiterationnum) {
3284 strcpy(outfilename, infilename);
3285 } else if (increment == 0) {
3286 strcpy(outfilename, infilename);
3287 strcat(outfilename, ".1");
3288 } else {
3289 workstring[increment] = '%';
3290 workstring[increment + 1] = 'd';
3291 workstring[increment + 2] = '\0';
3292 sprintf(outfilename, workstring, meshnumber + 1);
3293 }
3294 // Background filename has the form "*.b.ele", "*.b.node", ...
3295 strcpy(bgmeshfilename, infilename);
3296 strcat(bgmeshfilename, ".b");
3297
3298 return true;
3299 }
3300
3301 //
3302 // End of class 'tetgenbehavior' implementation
3303 //
3304
3305 //
3306 // Begin of class 'tetgenmesh' implementation
3307 //
3308
3309 //
3310 // Begin of class 'list', 'memorypool' and 'link' implementation
3311 //
3312
3313 // Following are predefined compare functions for primitive data types.
3314 // These functions take two pointers of the corresponding date type,
3315 // perform the comparation. Return -1, 0 or 1 indicating the default
3316 // linear order of two operators.
3317
3318 // Compare two 'integers'.
3319 int tetgenmesh::compare_2_ints(const void* x, const void* y) {
3320 if (* (int *) x < * (int *) y) {
3321 return -1;
3322 } else if (* (int *) x > * (int *) y) {
3323 return 1;
3324 } else {
3325 return 0;
3326 }
3327 }
3328
3329 // Compare two 'longs'. Note: in 64-bit machine the 'long' type is 64-bit
3330 // (8-byte) where the 'int' only 32-bit (4-byte).
3331 int tetgenmesh::compare_2_longs(const void* x, const void* y) {
3332 if (* (long *) x < * (long *) y) {
3333 return -1;
3334 } else if (* (long *) x > * (long *) y) {
3335 return 1;
3336 } else {
3337 return 0;
3338 }
3339 }
3340
3341 // Compare two 'unsigned longs'.
3342 int tetgenmesh::compare_2_unsignedlongs(const void* x, const void* y) {
3343 if (* (unsigned long *) x < * (unsigned long *) y) {
3344 return -1;
3345 } else if (* (unsigned long *) x > * (unsigned long *) y) {
3346 return 1;
3347 } else {
3348 return 0;
3349 }
3350 }
3351
3352 ///////////////////////////////////////////////////////////////////////////////
3353 // //
3354 // set_compfunc() Determine the size of primitive data types and set the //
3355 // corresponding predefined linear order functions. //
3356 // //
3357 // 'str' is a zero-end string indicating a primitive data type, like 'int', //
3358 // 'long' or 'unsigned long'. Every string ending with a '*' is though as a //
3359 // type of pointer and the type 'unsign long' is used for it. //
3360 // //
3361 // When the type of 'str' is determined, the size of this type (in byte) is //
3362 // returned in 'itbytes', and the pointer of corresponding predefined linear //
3363 // order functions is returned in 'pcomp'. //
3364 // //
3365 ///////////////////////////////////////////////////////////////////////////////
3366
3367 void tetgenmesh::set_compfunc(char* str, int* itbytes, compfunc* pcomp)
3368 {
3369 // First figure out whether it is a pointer or not.
3370 if (str[strlen(str) - 1] == '*') {
3371 *itbytes = sizeof(unsigned long);
3372 *pcomp = &compare_2_unsignedlongs;
3373 return;
3374 }
3375 // Then determine other types.
3376 if (strcmp(str, "int") == 0) {
3377 *itbytes = sizeof(int);
3378 *pcomp = &compare_2_ints;
3379 } else if (strcmp(str, "long") == 0) {
3380 *itbytes = sizeof(long);
3381 *pcomp = &compare_2_longs;
3382 } else if (strcmp(str, "unsigned long") == 0) {
3383 *itbytes = sizeof(unsigned long);
3384 *pcomp = &compare_2_unsignedlongs;
3385 } else {
3386 // It is an unknown type.
3387 printf("Error in set_compfunc(): unknown type %s.\n", str);
3388 terminatetetgen(1);
3389 }
3390 }
3391
3392 ///////////////////////////////////////////////////////////////////////////////
3393 // //
3394 // listinit() Initialize a list for storing a data type. //
3395 // //
3396 // Determine the size of each item, set the maximum size allocated at onece, //
3397 // set the expand size in case the list is full, and set the linear order //
3398 // function if it is provided (default is NULL). //
3399 // //
3400 ///////////////////////////////////////////////////////////////////////////////
3401
3402 void tetgenmesh::list::
3403 listinit(int itbytes, compfunc pcomp, int mitems,int exsize)
3404 {
3405 #ifdef SELF_CHECK
3406 assert(itbytes > 0 && mitems > 0 && exsize > 0);
3407 #endif
3408 itembytes = itbytes;
3409 comp = pcomp;
3410 maxitems = mitems;
3411 expandsize = exsize;
3412 base = (char *) malloc(maxitems * itembytes);
3413 if (base == (char *) NULL) {
3414 printf("Error: Out of memory.\n");
3415 terminatetetgen(1);
3416 }
3417 items = 0;
3418 }
3419
3420 ///////////////////////////////////////////////////////////////////////////////
3421 // //
3422 // append() Add a new item at the end of the list. //
3423 // //
3424 // A new space at the end of this list will be allocated for storing the new //
3425 // item. If the memory is not sufficient, reallocation will be performed. If //
3426 // 'appitem' is not NULL, the contents of this pointer will be copied to the //
3427 // new allocated space. Returns the pointer to the new allocated space. //
3428 // //
3429 ///////////////////////////////////////////////////////////////////////////////
3430
3431 void* tetgenmesh::list::append(void *appitem)
3432 {
3433 // Do we have enough space?
3434 if (items == maxitems) {
3435 char* newbase = (char *) realloc(base, (maxitems + expandsize) *
3436 itembytes);
3437 if (newbase == (char *) NULL) {
3438 printf("Error: Out of memory.\n");
3439 terminatetetgen(1);
3440 }
3441 base = newbase;
3442 maxitems += expandsize;
3443 }
3444 if (appitem != (void *) NULL) {
3445 memcpy(base + items * itembytes, appitem, itembytes);
3446 }
3447 items++;
3448 return (void *) (base + (items - 1) * itembytes);
3449 }
3450
3451 ///////////////////////////////////////////////////////////////////////////////
3452 // //
3453 // insert() Insert an item before 'pos' (range from 0 to items - 1). //
3454 // //
3455 // A new space will be inserted at the position 'pos', that is, items lie //
3456 // after pos (including the item at pos) will be moved one space downwords. //
3457 // If 'insitem' is not NULL, its contents will be copied into the new //
3458 // inserted space. Return a pointer to the new inserted space. //
3459 // //
3460 ///////////////////////////////////////////////////////////////////////////////
3461
3462 void* tetgenmesh::list::insert(int pos, void* insitem)
3463 {
3464 if (pos >= items) {
3465 return append(insitem);
3466 }
3467 // Do we have enough space.
3468 if (items == maxitems) {
3469 char* newbase = (char *) realloc(base, (maxitems + expandsize) *
3470 itembytes);
3471 if (newbase == (char *) NULL) {
3472 printf("Error: Out of memory.\n");
3473 terminatetetgen(1);
3474 }
3475 base = newbase;
3476 maxitems += expandsize;
3477 }
3478 // Do block move.
3479 memmove(base + (pos + 1) * itembytes, // dest
3480 base + pos * itembytes, // src
3481 (items - pos) * itembytes); // size in bytes
3482 // Insert the item.
3483 if (insitem != (void *) NULL) {
3484 memcpy(base + pos * itembytes, insitem, itembytes);
3485 }
3486 items++;
3487 return (void *) (base + pos * itembytes);
3488 }
3489
3490 ///////////////////////////////////////////////////////////////////////////////
3491 // //
3492 // del() Delete an item at 'pos' (range from 0 to items - 1). //
3493 // //
3494 // The space at 'pos' will be overlapped by other item. If 'order' is 1, the //
3495 // remaining items of the list have the same order as usual, i.e., items lie //
3496 // after pos will be moved one space upwords. If 'order' is 0, the last item //
3497 // of the list will be moved up to pos. //
3498 // //
3499 ///////////////////////////////////////////////////////////////////////////////
3500
3501 void tetgenmesh::list::del(int pos, int order)
3502 {
3503 // If 'pos' is the last item of the list, nothing need to do.
3504 if (pos >= 0 && pos < items - 1) {
3505 if (order == 1) {
3506 // Do block move.
3507 memmove(base + pos * itembytes, // dest
3508 base + (pos + 1) * itembytes, // src
3509 (items - pos - 1) * itembytes);
3510 } else {
3511 // Use the last item to overlap the del item.
3512 memcpy(base + pos * itembytes, // item at pos
3513 base + (items - 1) * itembytes, // item at last
3514 itembytes);
3515 }
3516 }
3517 if (items > 0) {
3518 items--;
3519 }
3520 }
3521
3522 ///////////////////////////////////////////////////////////////////////////////
3523 // //
3524 // hasitem() Search in this list to find if 'checkitem' exists. //
3525 // //
3526 // This routine assumes that a linear order function has been set. It loops //
3527 // through the entire list, compares each item to 'checkitem'. If it exists, //
3528 // return its position (between 0 to items - 1), otherwise, return -1. //
3529 // //
3530 ///////////////////////////////////////////////////////////////////////////////
3531
3532 int tetgenmesh::list::hasitem(void* checkitem)
3533 {
3534 int i;
3535
3536 for (i = 0; i < items; i++) {
3537 if (comp != (compfunc) NULL) {
3538 if ((* comp)((void *)(base + i * itembytes), checkitem) == 0) {
3539 return i;
3540 }
3541 }
3542 }
3543 return -1;
3544 }
3545
3546 ///////////////////////////////////////////////////////////////////////////////
3547 // //
3548 // sort() Sort the items with respect to a linear order function. //
3549 // //
3550 // Uses QuickSort routines (qsort) of the standard C/C++ library (stdlib.h). //
3551 // //
3552 ///////////////////////////////////////////////////////////////////////////////
3553
3554 void tetgenmesh::list::sort()
3555 {
3556 qsort((void *) base, (size_t) items, (size_t) itembytes, comp);
3557 }
3558
3559 ///////////////////////////////////////////////////////////////////////////////
3560 // //
3561 // memorypool() The constructors of memorypool. //
3562 // //
3563 ///////////////////////////////////////////////////////////////////////////////
3564
3565 tetgenmesh::memorypool::memorypool()
3566 {
3567 firstblock = nowblock = (void **) NULL;
3568 nextitem = (void *) NULL;
3569 deaditemstack = (void *) NULL;
3570 pathblock = (void **) NULL;
3571 pathitem = (void *) NULL;
3572 itemwordtype = POINTER;
3573 alignbytes = 0;
3574 itembytes = itemwords = 0;
3575 itemsperblock = 0;
3576 items = maxitems = 0l;
3577 unallocateditems = 0;
3578 pathitemsleft = 0;
3579 }
3580
3581 tetgenmesh::memorypool::
3582 memorypool(int bytecount, int itemcount, enum wordtype wtype, int alignment)
3583 {
3584 poolinit(bytecount, itemcount, wtype, alignment);
3585 }
3586
3587 ///////////////////////////////////////////////////////////////////////////////
3588 // //
3589 // ~memorypool() Free to the operating system all memory taken by a pool. //
3590 // //
3591 ///////////////////////////////////////////////////////////////////////////////
3592
3593 tetgenmesh::memorypool::~memorypool()
3594 {
3595 while (firstblock != (void **) NULL) {
3596 nowblock = (void **) *(firstblock);
3597 free(firstblock);
3598 firstblock = nowblock;
3599 }
3600 }
3601
3602 ///////////////////////////////////////////////////////////////////////////////
3603 // //
3604 // poolinit() Initialize a pool of memory for allocation of items. //
3605 // //
3606 // A `pool' is created whose records have size at least `bytecount'. Items //
3607 // will be allocated in `itemcount'-item blocks. Each item is assumed to be //
3608 // a collection of words, and either pointers or floating-point values are //
3609 // assumed to be the "primary" word type. (The "primary" word type is used //
3610 // to determine alignment of items.) If `alignment' isn't zero, all items //
3611 // will be `alignment'-byte aligned in memory. `alignment' must be either a //
3612 // multiple or a factor of the primary word size; powers of two are safe. //
3613 // `alignment' is normally used to create a few unused bits at the bottom of //
3614 // each item's pointer, in which information may be stored. //
3615 // //
3616 ///////////////////////////////////////////////////////////////////////////////
3617
3618 void tetgenmesh::memorypool::
3619 poolinit(int bytecount, int itemcount, enum wordtype wtype, int alignment)
3620 {
3621 int wordsize;
3622
3623 // Initialize values in the pool.
3624 itemwordtype = wtype;
3625 wordsize = (itemwordtype == POINTER) ? sizeof(void *) : sizeof(REAL);
3626 // Find the proper alignment, which must be at least as large as:
3627 // - The parameter `alignment'.
3628 // - The primary word type, to avoid unaligned accesses.
3629 // - sizeof(void *), so the stack of dead items can be maintained
3630 // without unaligned accesses.
3631 if (alignment > wordsize) {
3632 alignbytes = alignment;
3633 } else {
3634 alignbytes = wordsize;
3635 }
3636 if ((int) sizeof(void *) > alignbytes) {
3637 alignbytes = (int) sizeof(void *);
3638 }
3639 itemwords = ((bytecount + alignbytes - 1) / alignbytes)
3640 * (alignbytes / wordsize);
3641 itembytes = itemwords * wordsize;
3642 itemsperblock = itemcount;
3643
3644 // Allocate a block of items. Space for `itemsperblock' items and one
3645 // pointer (to point to the next block) are allocated, as well as space
3646 // to ensure alignment of the items.
3647 firstblock = (void **) malloc(itemsperblock * itembytes + sizeof(void *)
3648 + alignbytes);
3649 if (firstblock == (void **) NULL) {
3650 printf("Error: Out of memory.\n");
3651 terminatetetgen(1);
3652 }
3653 // Set the next block pointer to NULL.
3654 *(firstblock) = (void *) NULL;
3655 restart();
3656 }
3657
3658 ///////////////////////////////////////////////////////////////////////////////
3659 // //
3660 // restart() Deallocate all items in this pool. //
3661 // //
3662 // The pool is returned to its starting state, except that no memory is //
3663 // freed to the operating system. Rather, the previously allocated blocks //
3664 // are ready to be reused. //
3665 // //
3666 ///////////////////////////////////////////////////////////////////////////////
3667
3668 void tetgenmesh::memorypool::restart()
3669 {
3670 unsigned long alignptr;
3671
3672 items = 0;
3673 maxitems = 0;
3674
3675 // Set the currently active block.
3676 nowblock = firstblock;
3677 // Find the first item in the pool. Increment by the size of (void *).
3678 alignptr = (unsigned long) (nowblock + 1);
3679 // Align the item on an `alignbytes'-byte boundary.
3680 nextitem = (void *)
3681 (alignptr + (unsigned long) alignbytes -
3682 (alignptr % (unsigned long) alignbytes));
3683 // There are lots of unallocated items left in this block.
3684 unallocateditems = itemsperblock;
3685 // The stack of deallocated items is empty.
3686 deaditemstack = (void *) NULL;
3687 }
3688
3689 ///////////////////////////////////////////////////////////////////////////////
3690 // //
3691 // alloc() Allocate space for an item. //
3692 // //
3693 ///////////////////////////////////////////////////////////////////////////////
3694
3695 void* tetgenmesh::memorypool::alloc()
3696 {
3697 void *newitem;
3698 void **newblock;
3699 unsigned long alignptr;
3700
3701 // First check the linked list of dead items. If the list is not
3702 // empty, allocate an item from the list rather than a fresh one.
3703 if (deaditemstack != (void *) NULL) {
3704 newitem = deaditemstack; // Take first item in list.
3705 deaditemstack = * (void **) deaditemstack;
3706 } else {
3707 // Check if there are any free items left in the current block.
3708 if (unallocateditems == 0) {
3709 // Check if another block must be allocated.
3710 if (*nowblock == (void *) NULL) {
3711 // Allocate a new block of items, pointed to by the previous block.
3712 newblock = (void **) malloc(itemsperblock * itembytes + sizeof(void *)
3713 + alignbytes);
3714 if (newblock == (void **) NULL) {
3715 printf("Error: Out of memory.\n");
3716 terminatetetgen(1);
3717 }
3718 *nowblock = (void *) newblock;
3719 // The next block pointer is NULL.
3720 *newblock = (void *) NULL;
3721 }
3722 // Move to the new block.
3723 nowblock = (void **) *nowblock;
3724 // Find the first item in the block.
3725 // Increment by the size of (void *).
3726 alignptr = (unsigned long) (nowblock + 1);
3727 // Align the item on an `alignbytes'-byte boundary.
3728 nextitem = (void *)
3729 (alignptr + (unsigned long) alignbytes -
3730 (alignptr % (unsigned long) alignbytes));
3731 // There are lots of unallocated items left in this block.
3732 unallocateditems = itemsperblock;
3733 }
3734 // Allocate a new item.
3735 newitem = nextitem;
3736 // Advance `nextitem' pointer to next free item in block.
3737 if (itemwordtype == POINTER) {
3738 nextitem = (void *) ((void **) nextitem + itemwords);
3739 } else {
3740 nextitem = (void *) ((REAL *) nextitem + itemwords);
3741 }
3742 unallocateditems--;
3743 maxitems++;
3744 }
3745 items++;
3746 return newitem;
3747 }
3748
3749 ///////////////////////////////////////////////////////////////////////////////
3750 // //
3751 // dealloc() Deallocate space for an item. //
3752 // //
3753 // The deallocated space is stored in a queue for later reuse. //
3754 // //
3755 ///////////////////////////////////////////////////////////////////////////////
3756
3757 void tetgenmesh::memorypool::dealloc(void *dyingitem)
3758 {
3759 // Push freshly killed item onto stack.
3760 *((void **) dyingitem) = deaditemstack;
3761 deaditemstack = dyingitem;
3762 items--;
3763 }
3764
3765 ///////////////////////////////////////////////////////////////////////////////
3766 // //
3767 // traversalinit() Prepare to traverse the entire list of items. //
3768 // //
3769 // This routine is used in conjunction with traverse(). //
3770 // //
3771 ///////////////////////////////////////////////////////////////////////////////
3772
3773 void tetgenmesh::memorypool::traversalinit()
3774 {
3775 unsigned long alignptr;
3776
3777 // Begin the traversal in the first block.
3778 pathblock = firstblock;
3779 // Find the first item in the block. Increment by the size of (void *).
3780 alignptr = (unsigned long) (pathblock + 1);
3781 // Align with item on an `alignbytes'-byte boundary.
3782 pathitem = (void *)
3783 (alignptr + (unsigned long) alignbytes -
3784 (alignptr % (unsigned long) alignbytes));
3785 // Set the number of items left in the current block.
3786 pathitemsleft = itemsperblock;
3787 }
3788
3789 ///////////////////////////////////////////////////////////////////////////////
3790 // //
3791 // traverse() Find the next item in the list. //
3792 // //
3793 // This routine is used in conjunction with traversalinit(). Be forewarned //
3794 // that this routine successively returns all items in the list, including //
3795 // deallocated ones on the deaditemqueue. It's up to you to figure out which //
3796 // ones are actually dead. It can usually be done more space-efficiently by //
3797 // a routine that knows something about the structure of the item. //
3798 // //
3799 ///////////////////////////////////////////////////////////////////////////////
3800
3801 void* tetgenmesh::memorypool::traverse()
3802 {
3803 void *newitem;
3804 unsigned long alignptr;
3805
3806 // Stop upon exhausting the list of items.
3807 if (pathitem == nextitem) {
3808 return (void *) NULL;
3809 }
3810 // Check whether any untraversed items remain in the current block.
3811 if (pathitemsleft == 0) {
3812 // Find the next block.
3813 pathblock = (void **) *pathblock;
3814 // Find the first item in the block. Increment by the size of (void *).
3815 alignptr = (unsigned long) (pathblock + 1);
3816 // Align with item on an `alignbytes'-byte boundary.
3817 pathitem = (void *)
3818 (alignptr + (unsigned long) alignbytes -
3819 (alignptr % (unsigned long) alignbytes));
3820 // Set the number of items left in the current block.
3821 pathitemsleft = itemsperblock;
3822 }
3823 newitem = pathitem;
3824 // Find the next item in the block.
3825 if (itemwordtype == POINTER) {
3826 pathitem = (void *) ((void **) pathitem + itemwords);
3827 } else {
3828 pathitem = (void *) ((REAL *) pathitem + itemwords);
3829 }
3830 pathitemsleft--;
3831 return newitem;
3832 }
3833
3834 ///////////////////////////////////////////////////////////////////////////////
3835 // //
3836 // linkinit() Initialize a link for storing items. //
3837 // //
3838 // The input parameters are the size of each item, a pointer of a linear //
3839 // order function and the number of items allocating in one memory bulk. //
3840 // //
3841 ///////////////////////////////////////////////////////////////////////////////
3842
3843 void tetgenmesh::link::linkinit(int bytecount, compfunc pcomp, int itemcount)
3844 {
3845 #ifdef SELF_CHECK
3846 assert(bytecount > 0 && itemcount > 0);
3847 #endif
3848 // Remember the real size of each item.
3849 linkitembytes = bytecount;
3850 // Set the linear order function for this link.
3851 comp = pcomp;
3852
3853 // Call the constructor of 'memorypool' to initialize its variables.
3854 // like: itembytes, itemwords, items, ... Each node has size
3855 // bytecount + 2 * sizeof(void **), and total 'itemcount + 2' (because
3856 // link has additional two nodes 'head' and 'tail').
3857 poolinit(bytecount + 2 * sizeof(void **), itemcount + 2, POINTER, 0);
3858
3859 // Initial state of this link.
3860 head = (void **) alloc();
3861 tail = (void **) alloc();
3862 *head = (void *) tail;
3863 *(head + 1) = NULL;
3864 *tail = NULL;
3865 *(tail + 1) = (void *) head;
3866 nextlinkitem = *head;
3867 curpos = 1;
3868 linkitems = 0;
3869 }
3870
3871 ///////////////////////////////////////////////////////////////////////////////
3872 // //
3873 // clear() Deallocate all nodes in this link. //
3874 // //
3875 // The link is returned to its starting state, except that no memory is //
3876 // freed to the operating system. Rather, the previously allocated blocks //
3877 // are ready to be reused. //
3878 // //
3879 ///////////////////////////////////////////////////////////////////////////////
3880
3881 void tetgenmesh::link::clear()
3882 {
3883 // Reset the pool.
3884 restart();
3885
3886 // Initial state of this link.
3887 head = (void **) alloc();
3888 tail = (void **) alloc();
3889 *head = (void *) tail;
3890 *(head + 1) = NULL;
3891 *tail = NULL;
3892 *(tail + 1) = (void *) head;
3893 nextlinkitem = *head;
3894 curpos = 1;
3895 linkitems = 0;
3896 }
3897
3898 ///////////////////////////////////////////////////////////////////////////////
3899 // //
3900 // move() Causes 'nextlinkitem' to traverse the specified number of nodes,//
3901 // updates 'curpos' to be the node to which 'nextlinkitem' points. //
3902 // //
3903 // 'numberofnodes' is a number indicating how many nodes need be traversed //
3904 // (not counter the current node) need be traversed. It may be positive(move //
3905 // forward) or negative (move backward). Return TRUE if it is successful. //
3906 // //
3907 ///////////////////////////////////////////////////////////////////////////////
3908
3909 bool tetgenmesh::link::move(int numberofnodes)
3910 {
3911 void **nownode;
3912 int i;
3913
3914 nownode = (void **) nextlinkitem;
3915 if (numberofnodes > 0) {
3916 // Move forward.
3917 i = 0;
3918 while ((i < numberofnodes) && *nownode) {
3919 nownode = (void **) *nownode;
3920 i++;
3921 }
3922 if (*nownode == NULL) return false;
3923 nextlinkitem = (void *) nownode;
3924 curpos += numberofnodes;
3925 } else if (numberofnodes < 0) {
3926 // Move backward.
3927 i = 0;
3928 numberofnodes = -numberofnodes;
3929 while ((i < numberofnodes) && *(nownode + 1)) {
3930 nownode = (void **) *(nownode + 1);
3931 i++;
3932 }
3933 if (*(nownode + 1) == NULL) return false;
3934 nextlinkitem = (void *) nownode;
3935 curpos -= numberofnodes;
3936 }
3937 return true;
3938 }
3939
3940 ///////////////////////////////////////////////////////////////////////////////
3941 // //
3942 // locate() Locates the node at the specified position. //
3943 // //
3944 // The number 'pos' (between 1 and 'linkitems') indicates the location. This //
3945 // routine first decides the shortest path traversing from 'curpos' to 'pos',//
3946 // i.e., from head, tail or 'curpos'. Routine 'move()' is called to really //
3947 // traverse the link. If success, 'nextlinkitem' points to the node, 'curpos'//
3948 // and 'pos' are equal. Otherwise, return FALSE. //
3949 // //
3950 ///////////////////////////////////////////////////////////////////////////////
3951
3952 bool tetgenmesh::link::locate(int pos)
3953 {
3954 int headdist, taildist, curdist;
3955 int abscurdist, mindist;
3956
3957 if (pos < 1 || pos > linkitems) return false;
3958
3959 headdist = pos - 1;
3960 taildist = linkitems - pos;
3961 curdist = pos - curpos;
3962 abscurdist = curdist >= 0 ? curdist : -curdist;
3963
3964 if (headdist > taildist) {
3965 if (taildist > abscurdist) {
3966 mindist = curdist;
3967 } else {
3968 // taildist <= abs(curdist)
3969 mindist = -taildist;
3970 goend();
3971 }
3972 } else {
3973 // headdist <= taildist
3974 if (headdist > abscurdist) {
3975 mindist = curdist;
3976 } else {
3977 // headdist <= abs(curdist)
3978 mindist = headdist;
3979 rewind();
3980 }
3981 }
3982
3983 return move(mindist);
3984 }
3985
3986 ///////////////////////////////////////////////////////////////////////////////
3987 // //
3988 // add() Add a node at the end of this link. //
3989 // //
3990 // A new node is appended to the end of the link. If 'newitem' is not NULL, //
3991 // its conents will be copied to the data slot of the new node. Returns the //
3992 // pointer to the newest added node. //
3993 // //
3994 ///////////////////////////////////////////////////////////////////////////////
3995
3996 void* tetgenmesh::link::add(void* newitem)
3997 {
3998 void **newnode = tail;
3999 if (newitem != (void *) NULL) {
4000 memcpy((void *)(newnode + 2), newitem, linkitembytes);
4001 }
4002 tail = (void **) alloc();
4003 *tail = NULL;
4004 *newnode = (void*) tail;
4005 *(tail + 1) = (void*) newnode;
4006 linkitems++;
4007 return (void *)(newnode + 2);
4008 }
4009
4010 ///////////////////////////////////////////////////////////////////////////////
4011 // //
4012 // insert() Inserts a node before the specified position. //
4013 // //
4014 // 'pos' (between 1 and 'linkitems') indicates the inserting position. This //
4015 // routine inserts a new node before the node of 'pos'. If 'newitem' is not //
4016 // NULL, its conents will be copied into the data slot of the new node. If //
4017 // 'pos' is larger than 'linkitems', it is equal as 'add()'. A pointer to //
4018 // the newest inserted item is returned. //
4019 // //
4020 ///////////////////////////////////////////////////////////////////////////////
4021
4022 void* tetgenmesh::link::insert(int pos, void* insitem)
4023 {
4024 if (!locate(pos)) {
4025 return add(insitem);
4026 }
4027
4028 void **nownode = (void **) nextlinkitem;
4029
4030 // Insert a node before 'nownode'.
4031 void **newnode = (void **) alloc();
4032 if (insitem != (void *) NULL) {
4033 memcpy((void *)(newnode + 2), insitem, linkitembytes);
4034 }
4035
4036 *(void **)(*(nownode + 1)) = (void *) newnode;
4037 *newnode = (void *) nownode;
4038 *(newnode + 1) = *(nownode + 1);
4039 *(nownode + 1) = (void *) newnode;
4040
4041 linkitems++;
4042
4043 nextlinkitem = (void *) newnode;
4044 return (void *)(newnode + 2);
4045 }
4046
4047 ///////////////////////////////////////////////////////////////////////////////
4048 // //
4049 // del() Delete a node containing the given pointer. //
4050 // //
4051 // Returns a pointer of the deleted data. If you try to delete a non-existed //
4052 // node (e.g. link is empty or a wrong index is given) return NULL. //
4053 // //
4054 ///////////////////////////////////////////////////////////////////////////////
4055
4056 void* tetgenmesh::link::del(void* delitem)
4057 {
4058 void **deadnode = (void **) ((void **) delitem - 2);
4059
4060 // now delete the nownode
4061 void **nextnode = (void **) *deadnode;
4062 void **prevnode = (void **) *(deadnode + 1);
4063 *prevnode = (void *) nextnode;
4064 *(nextnode + 1) = (void *) prevnode;
4065
4066 dealloc((void *) deadnode);
4067 linkitems--;
4068
4069 nextlinkitem = (void *) nextnode;
4070 return (void *)(deadnode + 2);
4071 }
4072
4073 ///////////////////////////////////////////////////////////////////////////////
4074 // //
4075 // del() Delete a node at the specified position. //
4076 // //
4077 // 'pos' between 1 and 'linkitems'. Returns a pointer of the deleted data. //
4078 // If you try to delete a non-existed node (e.g. link is empty or a wrong //
4079 // index is given) return NULL. //
4080 // //
4081 ///////////////////////////////////////////////////////////////////////////////
4082
4083 void* tetgenmesh::link::del(int pos)
4084 {
4085 if (!locate(pos) || (linkitems == 0)) {
4086 return (void *) NULL;
4087 }
4088 return del((void *) ((void **) nextlinkitem + 2));
4089 }
4090
4091 ///////////////////////////////////////////////////////////////////////////////
4092 // //
4093 // getitem() The link traversal routine. //
4094 // //
4095 // Returns the node to which 'nextlinkitem' points. Returns a 'NULL' if the //
4096 // end of the link is reaching. Both 'nextlinkitem' and 'curpos' will be //
4097 // updated after this operation. //
4098 // //
4099 ///////////////////////////////////////////////////////////////////////////////
4100
4101 void* tetgenmesh::link::getitem()
4102 {
4103 if (nextlinkitem == (void *) tail) return NULL;
4104 void **nownode = (void **) nextlinkitem;
4105 nextlinkitem = *nownode;
4106 curpos += 1;
4107 return (void *)(nownode + 2);
4108 }
4109
4110 ///////////////////////////////////////////////////////////////////////////////
4111 // //
4112 // getnitem() Returns the node at a specified position. //
4113 // //
4114 // 'pos' between 1 and 'linkitems'. After this operation, 'nextlinkitem' and //
4115 // 'curpos' will be updated to indicate this node. //
4116 // //
4117 ///////////////////////////////////////////////////////////////////////////////
4118
4119 void* tetgenmesh::link::getnitem(int pos)
4120 {
4121 if (!locate(pos)) return NULL;
4122 return (void *)((void **) nextlinkitem + 2);
4123 }
4124
4125 ///////////////////////////////////////////////////////////////////////////////
4126 // //
4127 // hasitem() Search in this link to find if 'checkitem' exists. //
4128 // //
4129 // If 'checkitem' exists, return its position (between 1 to 'linkitems'), //
4130 // otherwise, return -1. This routine requires the linear order function has //
4131 // been set. //
4132 // //
4133 ///////////////////////////////////////////////////////////////////////////////
4134
4135 int tetgenmesh::link::hasitem(void* checkitem)
4136 {
4137 void *pathitem;
4138 int count;
4139
4140 rewind();
4141 pathitem = getitem();
4142 count = 0;
4143 while (pathitem) {
4144 count ++;
4145 if (comp) {
4146 if ((* comp)(pathitem, checkitem) == 0) {
4147 return count;
4148 }
4149 }
4150 pathitem = getitem();
4151 }
4152 return -1;
4153 }
4154
4155 //
4156 // End of class 'list', 'memorypool' and 'link' implementation
4157 //
4158
4159 //
4160 // Begin of mesh manipulation primitives
4161 //
4162
4163 //
4164 // Begin of tables initialization.
4165 //
4166
4167 // For enumerating three edges of a triangle.
4168
4169 int tetgenmesh::plus1mod3[3] = {1, 2, 0};
4170 int tetgenmesh::minus1mod3[3] = {2, 0, 1};
4171
4172 // Table 've' takes an edge version as input, returns the next edge version
4173 // in the same edge ring.
4174
4175 int tetgenmesh::ve[6] = { 2, 5, 4, 1, 0, 3 };
4176
4177 // Tables 'vo', 'vd' and 'va' take an edge version, return the positions of
4178 // the origin, destination and apex in the triangle.
4179
4180 int tetgenmesh::vo[6] = { 0, 1, 1, 2, 2, 0 };
4181 int tetgenmesh::vd[6] = { 1, 0, 2, 1, 0, 2 };
4182 int tetgenmesh::va[6] = { 2, 2, 0, 0, 1, 1 };
4183
4184 // The following tables are for tetrahedron primitives (operate on trifaces).
4185
4186 // For 'org()', 'dest()' and 'apex()'. Use 'loc' as the first index and
4187 // 'ver' as the second index.
4188
4189 int tetgenmesh::locver2org[4][6] = {
4190 {0, 1, 1, 2, 2, 0},
4191 {0, 3, 3, 1, 1, 0},
4192 {1, 3, 3, 2, 2, 1},
4193 {2, 3, 3, 0, 0, 2}
4194 };
4195 int tetgenmesh::locver2dest[4][6] = {
4196 {1, 0, 2, 1, 0, 2},
4197 {3, 0, 1, 3, 0, 1},
4198 {3, 1, 2, 3, 1, 2},
4199 {3, 2, 0, 3, 2, 0}
4200 };
4201 int tetgenmesh::locver2apex[4][6] = {
4202 {2, 2, 0, 0, 1, 1},
4203 {1, 1, 0, 0, 3, 3},
4204 {2, 2, 1, 1, 3, 3},
4205 {0, 0, 2, 2, 3, 3}
4206 };
4207
4208 // For oppo() primitives, use 'loc' as the index.
4209
4210 int tetgenmesh::loc2oppo[4] = { 3, 2, 0, 1 };
4211
4212 // For fnext() primitive. Use 'loc' as the first index and 'ver' as the
4213 // second index. Returns a new 'loc' and new 'ver' in an array. (It is
4214 // only valid for edge version equals one of {0, 2, 4}.)
4215
4216 int tetgenmesh::locver2nextf[4][6][2] = {
4217 { {1, 5}, {-1, -1}, {2, 5}, {-1, -1}, {3, 5}, {-1, -1} },
4218 { {3, 3}, {-1, -1}, {2, 1}, {-1, -1}, {0, 1}, {-1, -1} },
4219 { {1, 3}, {-1, -1}, {3, 1}, {-1, -1}, {0, 3}, {-1, -1} },
4220 { {2, 3}, {-1, -1}, {1, 1}, {-1, -1}, {0, 5}, {-1, -1} }
4221 };
4222
4223 //
4224 // End of tables initialization.
4225 //
4226
4227 // Some macros for convenience
4228
4229 #define Div2 >> 1
4230 #define Mod2 & 01
4231
4232 // NOTE: These bit operators should only be used in macros below.
4233
4234 // Get orient(Range from 0 to 2) from face version(Range from 0 to 5).
4235
4236 #define Orient(V) ((V) Div2)
4237
4238 // Determine edge ring(0 or 1) from face version(Range from 0 to 5).
4239
4240 #define EdgeRing(V) ((V) Mod2)
4241
4242 //
4243 // Begin of primitives for tetrahedra
4244 //
4245
4246 // Each tetrahedron contains four pointers to its neighboring tetrahedra,
4247 // with face indices. To save memory, both information are kept in a
4248 // single pointer. To make this possible, all tetrahedra are aligned to
4249 // eight-byte boundaries, so that the last three bits of each pointer are
4250 // zeros. A face index (in the range 0 to 3) is compressed into the last
4251 // two bits of each pointer by the function 'encode()'. The function
4252 // 'decode()' decodes a pointer, extracting a face index and a pointer to
4253 // the beginning of a tetrahedron.
4254
4255 inline void tetgenmesh::decode(tetrahedron ptr, triface& t) {
4256 t.loc = (int) ((unsigned long) (ptr) & (unsigned long) 3l);
4257 t.tet = (tetrahedron *) ((unsigned long) (ptr) & ~(unsigned long) 7l);
4258 }
4259
4260 inline tetgenmesh::tetrahedron tetgenmesh::encode(triface& t) {
4261 return (tetrahedron) ((unsigned long) t.tet | (unsigned long) t.loc);
4262 }
4263
4264 // sym() finds the abutting tetrahedron on the same face.
4265
4266 inline void tetgenmesh::sym(triface& t1, triface& t2) {
4267 tetrahedron ptr = t1.tet[t1.loc];
4268 decode(ptr, t2);
4269 }
4270
4271 inline void tetgenmesh::symself(triface& t) {
4272 tetrahedron ptr = t.tet[t.loc];
4273 decode(ptr, t);
4274 }
4275
4276 // Bond two tetrahedra together at their faces.
4277
4278 inline void tetgenmesh::bond(triface& t1, triface& t2) {
4279 t1.tet[t1.loc] = encode(t2);
4280 t2.tet[t2.loc] = encode(t1);
4281 }
4282
4283 // Dissolve a bond (from one side). Note that the other tetrahedron will
4284 // still think it is connected to this tetrahedron. Usually, however,
4285 // the other tetrahedron is being deleted entirely, or bonded to another
4286 // tetrahedron, so it doesn't matter.
4287
4288 inline void tetgenmesh::dissolve(triface& t) {
4289 t.tet[t.loc] = (tetrahedron) dummytet;
4290 }
4291
4292 // These primitives determine or set the origin, destination, apex or
4293 // opposition of a tetrahedron with respect to 'loc' and 'ver'.
4294
4295 inline tetgenmesh::point tetgenmesh::org(triface& t) {
4296 return (point) t.tet[locver2org[t.loc][t.ver] + 4];
4297 }
4298
4299 inline tetgenmesh::point tetgenmesh::dest(triface& t) {
4300 return (point) t.tet[locver2dest[t.loc][t.ver] + 4];
4301 }
4302
4303 inline tetgenmesh::point tetgenmesh::apex(triface& t) {
4304 return (point) t.tet[locver2apex[t.loc][t.ver] + 4];
4305 }
4306
4307 inline tetgenmesh::point tetgenmesh::oppo(triface& t) {
4308 return (point) t.tet[loc2oppo[t.loc] + 4];
4309 }
4310
4311 inline void tetgenmesh::setorg(triface& t, point pointptr) {
4312 t.tet[locver2org[t.loc][t.ver] + 4] = (tetrahedron) pointptr;
4313 }
4314
4315 inline void tetgenmesh::setdest(triface& t, point pointptr) {
4316 t.tet[locver2dest[t.loc][t.ver] + 4] = (tetrahedron) pointptr;
4317 }
4318
4319 inline void tetgenmesh::setapex(triface& t, point pointptr) {
4320 t.tet[locver2apex[t.loc][t.ver] + 4] = (tetrahedron) pointptr;
4321 }
4322
4323 inline void tetgenmesh::setoppo(triface& t, point pointptr) {
4324 t.tet[loc2oppo[t.loc] + 4] = (tetrahedron) pointptr;
4325 }
4326
4327 // These primitives were drived from Mucke's triangle-edge data structure
4328 // to change face-edge relation in a tetrahedron (esym, enext and enext2)
4329 // or between two tetrahedra (fnext).
4330
4331 // If e0 = e(i, j), e1 = e(j, i), that is e0 and e1 are the two directions
4332 // of the same undirected edge of a face. e0.sym() = e1 and vice versa.
4333
4334 inline void tetgenmesh::esym(triface& t1, triface& t2) {
4335 t2.tet = t1.tet;
4336 t2.loc = t1.loc;
4337 t2.ver = t1.ver + (EdgeRing(t1.ver) ? -1 : 1);
4338 }
4339
4340 inline void tetgenmesh::esymself(triface& t) {
4341 t.ver += (EdgeRing(t.ver) ? -1 : 1);
4342 }
4343
4344 // If e0 and e1 are both in the same edge ring of a face, e1 = e0.enext().
4345
4346 inline void tetgenmesh::enext(triface& t1, triface& t2) {
4347 t2.tet = t1.tet;
4348 t2.loc = t1.loc;
4349 t2.ver = ve[t1.ver];
4350 }
4351
4352 inline void tetgenmesh::enextself(triface& t) {
4353 t.ver = ve[t.ver];
4354 }
4355
4356 // enext2() is equal to e2 = e0.enext().enext()
4357
4358 inline void tetgenmesh::enext2(triface& t1, triface& t2) {
4359 t2.tet = t1.tet;
4360 t2.loc = t1.loc;
4361 t2.ver = ve[ve[t1.ver]];
4362 }
4363
4364 inline void tetgenmesh::enext2self(triface& t) {
4365 t.ver = ve[ve[t.ver]];
4366 }
4367
4368 // If f0 and f1 are both in the same face ring of a face, f1 = f0.fnext().
4369 // If f1 exists, return true. Otherwise, return false, i.e., f0 is a
4370 // boundary or hull face.
4371
4372 inline bool tetgenmesh::fnext(triface& t1, triface& t2) {
4373 return getnextface(&t1, &t2);
4374 }
4375
4376 inline bool tetgenmesh::fnextself(triface& t) {
4377 return getnextface(&t, NULL);
4378 }
4379
4380 // enextfnext() and enext2fnext() are combination primitives of enext(),
4381 // enext2() and fnext().
4382
4383 inline void tetgenmesh::enextfnext(triface& t1, triface& t2) {
4384 enext(t1, t2);
4385 fnextself(t2);
4386 }
4387
4388 inline void tetgenmesh::enextfnextself(triface& t) {
4389 enextself(t);
4390 fnextself(t);
4391 }
4392
4393 inline void tetgenmesh::enext2fnext(triface& t1, triface& t2) {
4394 enext2(t1, t2);
4395 fnextself(t2);
4396 }
4397
4398 inline void tetgenmesh::enext2fnextself(triface& t) {
4399 enext2self(t);
4400 fnextself(t);
4401 }
4402
4403 // Primitives to infect or cure a tetrahedron with the virus. The last
4404 // third bit of the pointer is marked for infection. These rely on the
4405 // assumption that all tetrahedron are aligned to eight-byte boundaries.
4406
4407 inline void tetgenmesh::infect(triface& t) {
4408 t.tet[0] = (tetrahedron) ((unsigned long) t.tet[0] | (unsigned long) 4l);
4409 }
4410
4411 inline void tetgenmesh::uninfect(triface& t) {
4412 t.tet[0] = (tetrahedron) ((unsigned long) t.tet[0] & ~ (unsigned long) 4l);
4413 }
4414
4415 // Test a tetrahedron for viral infection.
4416
4417 inline bool tetgenmesh::infected(triface& t) {
4418 return (((unsigned long) t.tet[0] & (unsigned long) 4l) != 0);
4419 }
4420
4421 // Check or set a tetrahedron's attributes.
4422
4423 inline REAL tetgenmesh::elemattribute(tetrahedron* ptr, int attnum) {
4424 return ((REAL *) (ptr))[elemattribindex + attnum];
4425 }
4426
4427 inline void tetgenmesh::
4428 setelemattribute(tetrahedron* ptr, int attnum, REAL value){
4429 ((REAL *) (ptr))[elemattribindex + attnum] = value;
4430 }
4431
4432 // Check or set a tetrahedron's maximum volume bound.
4433
4434 inline REAL tetgenmesh::volumebound(tetrahedron* ptr) {
4435 return ((REAL *) (ptr))[volumeboundindex];
4436 }
4437
4438 inline void tetgenmesh::setvolumebound(tetrahedron* ptr, REAL value) {
4439 ((REAL *) (ptr))[volumeboundindex] = value;
4440 }
4441
4442 //
4443 // End of primitives for tetrahedra
4444 //
4445
4446 //
4447 // Begin of primitives for subfaces/subsegments
4448 //
4449
4450 // Each subface contains three pointers to its neighboring subfaces, with
4451 // edge versions. To save memory, both information are kept in a single
4452 // pointer. To make this possible, all subfaces are aligned to eight-byte
4453 // boundaries, so that the last three bits of each pointer are zeros. An
4454 // edge version (in the range 0 to 5) is compressed into the last three
4455 // bits of each pointer by 'sencode()'. 'sdecode()' decodes a pointer,
4456 // extracting an edge version and a pointer to the beginning of a subface.
4457
4458 inline void tetgenmesh::sdecode(shellface sptr, face& s) {
4459 s.shver = (int) ((unsigned long) (sptr) & (unsigned long) 7l);
4460 s.sh = (shellface *) ((unsigned long) (sptr) & ~ (unsigned long) 7l);
4461 }
4462
4463 inline tetgenmesh::shellface tetgenmesh::sencode(face& s) {
4464 return (shellface) ((unsigned long) s.sh | (unsigned long) s.shver);
4465 }
4466
4467 // spivot() finds the other subface (from this subface) that shares the
4468 // same edge.
4469
4470 inline void tetgenmesh::spivot(face& s1, face& s2) {
4471 shellface sptr = s1.sh[Orient(s1.shver)];
4472 sdecode(sptr, s2);
4473 }
4474
4475 inline void tetgenmesh::spivotself(face& s) {
4476 shellface sptr = s.sh[Orient(s.shver)];
4477 sdecode(sptr, s);
4478 }
4479
4480 // sbond() bonds two subfaces together, i.e., after bonding, both faces
4481 // are pointing to each other.
4482
4483 inline void tetgenmesh::sbond(face& s1, face& s2) {
4484 s1.sh[Orient(s1.shver)] = sencode(s2);
4485 s2.sh[Orient(s2.shver)] = sencode(s1);
4486 }
4487
4488 // sbond1() only bonds s2 to s1, i.e., after bonding, s1 is pointing to s2,
4489 // but s2 is not pointing to s1.
4490
4491 inline void tetgenmesh::sbond1(face& s1, face& s2) {
4492 s1.sh[Orient(s1.shver)] = sencode(s2);
4493 }
4494
4495 // Dissolve a subface bond (from one side). Note that the other subface
4496 // will still think it's connected to this subface.
4497
4498 inline void tetgenmesh::sdissolve(face& s) {
4499 s.sh[Orient(s.shver)] = (shellface) dummysh;
4500 }
4501
4502 // These primitives determine or set the origin, destination, or apex
4503 // of a subface with respect to the edge version.
4504
4505 inline tetgenmesh::point tetgenmesh::sorg(face& s) {
4506 return (point) s.sh[3 + vo[s.shver]];
4507 }
4508
4509 inline tetgenmesh::point tetgenmesh::sdest(face& s) {
4510 return (point) s.sh[3 + vd[s.shver]];
4511 }
4512
4513 inline tetgenmesh::point tetgenmesh::sapex(face& s) {
4514 return (point) s.sh[3 + va[s.shver]];
4515 }
4516
4517 inline void tetgenmesh::setsorg(face& s, point pointptr) {
4518 s.sh[3 + vo[s.shver]] = (shellface) pointptr;
4519 }
4520
4521 inline void tetgenmesh::setsdest(face& s, point pointptr) {
4522 s.sh[3 + vd[s.shver]] = (shellface) pointptr;
4523 }
4524
4525 inline void tetgenmesh::setsapex(face& s, point pointptr) {
4526 s.sh[3 + va[s.shver]] = (shellface) pointptr;
4527 }
4528
4529 // These primitives were drived from Mucke[2]'s triangle-edge data structure
4530 // to change face-edge relation in a subface (sesym, senext and senext2).
4531
4532 inline void tetgenmesh::sesym(face& s1, face& s2) {
4533 s2.sh = s1.sh;
4534 s2.shver = s1.shver + (EdgeRing(s1.shver) ? -1 : 1);
4535 }
4536
4537 inline void tetgenmesh::sesymself(face& s) {
4538 s.shver += (EdgeRing(s.shver) ? -1 : 1);
4539 }
4540
4541 inline void tetgenmesh::senext(face& s1, face& s2) {
4542 s2.sh = s1.sh;
4543 s2.shver = ve[s1.shver];
4544 }
4545
4546 inline void tetgenmesh::senextself(face& s) {
4547 s.shver = ve[s.shver];
4548 }
4549
4550 inline void tetgenmesh::senext2(face& s1, face& s2) {
4551 s2.sh = s1.sh;
4552 s2.shver = ve[ve[s1.shver]];
4553 }
4554
4555 inline void tetgenmesh::senext2self(face& s) {
4556 s.shver = ve[ve[s.shver]];
4557 }
4558
4559 // If f0 and f1 are both in the same face ring, then f1 = f0.fnext(),
4560
4561 inline void tetgenmesh::sfnext(face& s1, face& s2) {
4562 getnextsface(&s1, &s2);
4563 }
4564
4565 inline void tetgenmesh::sfnextself(face& s) {
4566 getnextsface(&s, NULL);
4567 }
4568
4569 // These primitives read or set a pointer of the badface structure. The
4570 // pointer is stored sh[11].
4571
4572 inline tetgenmesh::badface* tetgenmesh::shell2badface(face& s) {
4573 return (badface*) s.sh[11];
4574 }
4575
4576 inline void tetgenmesh::setshell2badface(face& s, badface* value) {
4577 s.sh[11] = (shellface) value;
4578 }
4579
4580 // Check or set a subface's maximum area bound.
4581
4582 inline REAL tetgenmesh::areabound(face& s) {
4583 return ((REAL *) (s.sh))[areaboundindex];
4584 }
4585
4586 inline void tetgenmesh::setareabound(face& s, REAL value) {
4587 ((REAL *) (s.sh))[areaboundindex] = value;
4588 }
4589
4590 // These two primitives read or set a shell marker. Shell markers are used
4591 // to hold user boundary information.
4592
4593 inline int tetgenmesh::shellmark(face& s) {
4594 return ((int *) (s.sh))[shmarkindex];
4595 }
4596
4597 inline void tetgenmesh::setshellmark(face& s, int value) {
4598 ((int *) (s.sh))[shmarkindex] = value;
4599 }
4600
4601 // These two primitives set or read the type of the subface or subsegment.
4602
4603 inline enum tetgenmesh::shestype tetgenmesh::shelltype(face& s) {
4604 return (enum shestype) ((int *) (s.sh))[shmarkindex + 1];
4605 }
4606
4607 inline void tetgenmesh::setshelltype(face& s, enum shestype value) {
4608 ((int *) (s.sh))[shmarkindex + 1] = (int) value;
4609 }
4610
4611 // These two primitives set or read the pbc group of the subface.
4612
4613 inline int tetgenmesh::shellpbcgroup(face& s) {
4614 return ((int *) (s.sh))[shmarkindex + 2];
4615 }
4616
4617 inline void tetgenmesh::setshellpbcgroup(face& s, int value) {
4618 ((int *) (s.sh))[shmarkindex + 2] = value;
4619 }
4620
4621 // Primitives to infect or cure a subface with the virus. These rely on the
4622 // assumption that all tetrahedra are aligned to eight-byte boundaries.
4623
4624 inline void tetgenmesh::sinfect(face& s) {
4625 s.sh[6] = (shellface) ((unsigned long) s.sh[6] | (unsigned long) 4l);
4626 }
4627
4628 inline void tetgenmesh::suninfect(face& s) {
4629 s.sh[6] = (shellface)((unsigned long) s.sh[6] & ~(unsigned long) 4l);
4630 }
4631
4632 // Test a subface for viral infection.
4633
4634 inline bool tetgenmesh::sinfected(face& s) {
4635 return (((unsigned long) s.sh[6] & (unsigned long) 4l) != 0);
4636 }
4637
4638 //
4639 // End of primitives for subfaces/subsegments
4640 //
4641
4642 //
4643 // Begin of primitives for interacting between tetrahedra and subfaces
4644 //
4645
4646 // tspivot() finds a subface abutting on this tetrahdera.
4647
4648 inline void tetgenmesh::tspivot(triface& t, face& s) {
4649 shellface sptr = (shellface) t.tet[8 + t.loc];
4650 sdecode(sptr, s);
4651 }
4652
4653 // stpivot() finds a tetrahedron abutting a subface.
4654
4655 inline void tetgenmesh::stpivot(face& s, triface& t) {
4656 tetrahedron ptr = (tetrahedron) s.sh[6 + EdgeRing(s.shver)];
4657 decode(ptr, t);
4658 }
4659
4660 // tsbond() bond a tetrahedron to a subface.
4661
4662 inline void tetgenmesh::tsbond(triface& t, face& s) {
4663 t.tet[8 + t.loc] = (tetrahedron) sencode(s);
4664 s.sh[6 + EdgeRing(s.shver)] = (shellface) encode(t);
4665 }
4666
4667 // tsdissolve() dissolve a bond (from the tetrahedron side).
4668
4669 inline void tetgenmesh::tsdissolve(triface& t) {
4670 t.tet[8 + t.loc] = (tetrahedron) dummysh;
4671 }
4672
4673 // stdissolve() dissolve a bond (from the subface side).
4674
4675 inline void tetgenmesh::stdissolve(face& s) {
4676 s.sh[6 + EdgeRing(s.shver)] = (shellface) dummytet;
4677 }
4678
4679 //
4680 // End of primitives for interacting between tetrahedra and subfaces
4681 //
4682
4683 //
4684 // Begin of primitives for interacting between subfaces and subsegs
4685 //
4686
4687 // sspivot() finds a subsegment abutting a subface.
4688
4689 inline void tetgenmesh::sspivot(face& s, face& edge) {
4690 shellface sptr = (shellface) s.sh[8 + Orient(s.shver)];
4691 sdecode(sptr, edge);
4692 }
4693
4694 // ssbond() bond a subface to a subsegment.
4695
4696 inline void tetgenmesh::ssbond(face& s, face& edge) {
4697 s.sh[8 + Orient(s.shver)] = sencode(edge);
4698 edge.sh[0] = sencode(s);
4699 }
4700
4701 // ssdisolve() dissolve a bond (from the subface side)
4702
4703 inline void tetgenmesh::ssdissolve(face& s) {
4704 s.sh[8 + Orient(s.shver)] = (shellface) dummysh;
4705 }
4706
4707 //
4708 // End of primitives for interacting between subfaces and subsegs
4709 //
4710
4711 //
4712 // Begin of primitives for points
4713 //
4714
4715 inline int tetgenmesh::pointmark(point pt) {
4716 return ((int *) (pt))[pointmarkindex];
4717 }
4718
4719 inline void tetgenmesh::setpointmark(point pt, int value) {
4720 ((int *) (pt))[pointmarkindex] = value;
4721 }
4722
4723 // These two primitives set and read the type of the point.
4724
4725 inline enum tetgenmesh::verttype tetgenmesh::pointtype(point pt) {
4726 return (enum verttype) ((int *) (pt))[pointmarkindex + 1];
4727 }
4728
4729 inline void tetgenmesh::setpointtype(point pt, enum verttype value) {
4730 ((int *) (pt))[pointmarkindex + 1] = (int) value;
4731 }
4732
4733 // These following primitives set and read a pointer to a tetrahedron
4734 // a subface/subsegment, a point, or a tet of background mesh.
4735
4736 inline tetgenmesh::tetrahedron tetgenmesh::point2tet(point pt) {
4737 return ((tetrahedron *) (pt))[point2simindex];
4738 }
4739
4740 inline void tetgenmesh::setpoint2tet(point pt, tetrahedron value) {
4741 ((tetrahedron *) (pt))[point2simindex] = value;
4742 }
4743
4744 inline tetgenmesh::shellface tetgenmesh::point2sh(point pt) {
4745 return (shellface) ((tetrahedron *) (pt))[point2simindex + 1];
4746 }
4747
4748 inline void tetgenmesh::setpoint2sh(point pt, shellface value) {
4749 ((tetrahedron *) (pt))[point2simindex + 1] = (tetrahedron) value;
4750 }
4751
4752 inline tetgenmesh::point tetgenmesh::point2ppt(point pt) {
4753 return (point) ((tetrahedron *) (pt))[point2simindex + 2];
4754 }
4755
4756 inline void tetgenmesh::setpoint2ppt(point pt, point value) {
4757 ((tetrahedron *) (pt))[point2simindex + 2] = (tetrahedron) value;
4758 }
4759
4760 inline tetgenmesh::tetrahedron tetgenmesh::point2bgmtet(point pt) {
4761 return ((tetrahedron *) (pt))[point2simindex + 3];
4762 }
4763
4764 inline void tetgenmesh::setpoint2bgmtet(point pt, tetrahedron value) {
4765 ((tetrahedron *) (pt))[point2simindex + 3] = value;
4766 }
4767
4768 // These primitives set and read a pointer to its pbc point.
4769
4770 inline tetgenmesh::point tetgenmesh::point2pbcpt(point pt) {
4771 return (point) ((tetrahedron *) (pt))[point2pbcptindex];
4772 }
4773
4774 inline void tetgenmesh::setpoint2pbcpt(point pt, point value) {
4775 ((tetrahedron *) (pt))[point2pbcptindex] = (tetrahedron) value;
4776 }
4777
4778 //
4779 // End of primitives for points
4780 //
4781
4782 //
4783 // Begin of advanced primitives
4784 //
4785
4786 // adjustedgering() adjusts the edge version so that it belongs to the
4787 // indicated edge ring. The 'direction' only can be 0(CCW) or 1(CW).
4788 // If the edge is not in the wanted edge ring, reverse it.
4789
4790 inline void tetgenmesh::adjustedgering(triface& t, int direction) {
4791 if (EdgeRing(t.ver) != direction) {
4792 esymself(t);
4793 }
4794 }
4795
4796 inline void tetgenmesh::adjustedgering(face& s, int direction) {
4797 if (EdgeRing(s.shver) != direction) {
4798 sesymself(s);
4799 }
4800 }
4801
4802 // isdead() returns TRUE if the tetrahedron or subface has been dealloced.
4803
4804 inline bool tetgenmesh::isdead(triface* t) {
4805 if (t->tet == (tetrahedron *) NULL) return true;
4806 else return t->tet[4] == (tetrahedron) NULL;
4807 }
4808
4809 inline bool tetgenmesh::isdead(face* s) {
4810 if (s->sh == (shellface *) NULL) return true;
4811 else return s->sh[3] == (shellface) NULL;
4812 }
4813
4814 // isfacehaspoint() returns TRUE if the 'testpoint' is one of the vertices
4815 // of the tetface 't' subface 's'.
4816
4817 inline bool tetgenmesh::isfacehaspoint(triface* t, point testpoint) {
4818 return ((org(*t) == testpoint) || (dest(*t) == testpoint) ||
4819 (apex(*t) == testpoint));
4820 }
4821
4822 inline bool tetgenmesh::isfacehaspoint(face* s, point testpoint) {
4823 return (s->sh[3] == (shellface) testpoint) ||
4824 (s->sh[4] == (shellface) testpoint) ||
4825 (s->sh[5] == (shellface) testpoint);
4826 }
4827
4828 // isfacehasedge() returns TRUE if the edge (given by its two endpoints) is
4829 // one of the three edges of the subface 's'.
4830
4831 inline bool tetgenmesh::isfacehasedge(face* s, point tend1, point tend2) {
4832 return (isfacehaspoint(s, tend1) && isfacehaspoint(s, tend2));
4833 }
4834
4835 // issymexist() returns TRUE if the adjoining tetrahedron is not 'duumytet'.
4836
4837 inline bool tetgenmesh::issymexist(triface* t) {
4838 tetrahedron *ptr = (tetrahedron *)
4839 ((unsigned long)(t->tet[t->loc]) & ~(unsigned long)7l);
4840 return ptr != dummytet;
4841 }
4842
4843 ///////////////////////////////////////////////////////////////////////////////
4844 // //
4845 // getnextface() Get the successor of 'tface1' in the face ring. //
4846 // //
4847 // If 'tface1' is not a boundary (or hull) face, then its successor in the //
4848 // face ring exists. The successor is returned in 'tface2' if it is not a //
4849 // NULL, or the 'tface1' itself is used to return this face. On finish, the //
4850 // function returns TRUE. //
4851 // //
4852 // If 'tface1' is a boundary (or hull) face, its successor does not exist. //
4853 // This case, return FALSE and 'tface1' remains unchanged. //
4854 // //
4855 ///////////////////////////////////////////////////////////////////////////////
4856
4857 bool tetgenmesh::getnextface(triface* tface1, triface* tface2)
4858 {
4859 point torg, tdest;
4860 int tloc, tver;
4861
4862 // Where the next face locates, in 'tface1' or in its neigbhour? It can be
4863 // quickly determined by checking the edge ring of 'tface1'.
4864 // if (EdgeRing(tface1->ver) == CW) {
4865 if ((tface1->ver & 01) == CW) {
4866 // The next face is in the neigbhour of 'tface1'.
4867 if (!issymexist(tface1)) {
4868 // Hit outer space - The next face does not exist.
4869 return false;
4870 }
4871 torg = org(*tface1);
4872 tdest = dest(*tface1);
4873 if (tface2) {
4874 sym(*tface1, *tface2);
4875 findedge(tface2, torg, tdest);
4876 } else {
4877 symself(*tface1);
4878 findedge(tface1, torg, tdest);
4879 }
4880 } else {
4881 // The next face is in 'tface1'.
4882 if (tface2) {
4883 *tface2 = *tface1;
4884 }
4885 }
4886
4887 if (tface2) {
4888 tloc = tface2->loc;
4889 tver = tface2->ver;
4890 tface2->loc = locver2nextf[tloc][tver][0];
4891 tface2->ver = locver2nextf[tloc][tver][1];
4892 } else {
4893 tloc = tface1->loc;
4894 tver = tface1->ver;
4895 tface1->loc = locver2nextf[tloc][tver][0];
4896 tface1->ver = locver2nextf[tloc][tver][1];
4897 }
4898 return true;
4899 }
4900
4901 ///////////////////////////////////////////////////////////////////////////////
4902 // //
4903 // getnextsface() Finds the next subface in the face ring. //
4904 // //
4905 // For saving space in the data structure of subface, there only exists one //
4906 // face ring around a segment (see programming manual). This routine imple- //
4907 // ments the double face ring as desired in Muecke's data structure. //
4908 // //
4909 ///////////////////////////////////////////////////////////////////////////////
4910
4911 void tetgenmesh::getnextsface(face* s1, face* s2)
4912 {
4913 face neighsh, spinsh;
4914 face testseg;
4915
4916 sspivot(*s1, testseg);
4917 if (testseg.sh != dummysh) {
4918 testseg.shver = 0;
4919 if (sorg(testseg) == sorg(*s1)) {
4920 spivot(*s1, neighsh);
4921 } else {
4922 spinsh = *s1;
4923 do {
4924 neighsh = spinsh;
4925 spivotself(spinsh);
4926 } while (spinsh.sh != s1->sh);
4927 }
4928 } else {
4929 spivot(*s1, neighsh);
4930 }
4931 if (sorg(neighsh) != sorg(*s1)) {
4932 sesymself(neighsh);
4933 }
4934 if (s2 != (face *) NULL) {
4935 *s2 = neighsh;
4936 } else {
4937 *s1 = neighsh;
4938 }
4939 }
4940
4941 ///////////////////////////////////////////////////////////////////////////////
4942 // //
4943 // tsspivot() Finds a subsegment abutting on a tetrahderon's edge. //
4944 // //
4945 // The edge is represented in the primary edge of 'checkedge'. If there is a //
4946 // subsegment bonded at this edge, it is returned in handle 'checkseg', the //
4947 // edge direction of 'checkseg' is conformed to 'checkedge'. If there isn't, //
4948 // set 'checkseg.sh = dummysh' to indicate it is not a subsegment. //
4949 // //
4950 // To find whether an edge of a tetrahedron is a subsegment or not. First we //
4951 // need find a subface around this edge to see if it contains a subsegment. //
4952 // The reason is there is no direct connection between a tetrahedron and its //
4953 // adjoining subsegments. //
4954 // //
4955 ///////////////////////////////////////////////////////////////////////////////
4956
4957 void tetgenmesh::tsspivot(triface* checkedge, face* checkseg)
4958 {
4959 triface spintet;
4960 face parentsh;
4961 point tapex;
4962 int hitbdry;
4963
4964 spintet = *checkedge;
4965 tapex = apex(*checkedge);
4966 hitbdry = 0;
4967 do {
4968 tspivot(spintet, parentsh);
4969 // Does spintet have a (non-fake) subface attached?
4970 if (parentsh.sh != dummysh && !isdead(&parentsh)) {
4971 // Find a subface!
4972 findedge(&parentsh, org(*checkedge), dest(*checkedge));
4973 sspivot(parentsh, *checkseg);
4974 if (checkseg->sh != dummysh) {
4975 // Find a subsegment! Correct its edge direction before return.
4976 if (sorg(*checkseg) != sorg(parentsh)) {
4977 sesymself(*checkseg);
4978 }
4979 }
4980 return;
4981 }
4982 if (!fnextself(spintet)) {
4983 hitbdry++;
4984 if (hitbdry < 2) {
4985 esym(*checkedge, spintet);
4986 if (!fnextself(spintet)) {
4987 hitbdry++;
4988 }
4989 }
4990 }
4991 } while ((apex(spintet) != tapex) && (hitbdry < 2));
4992 // Not find.
4993 checkseg->sh = dummysh;
4994 }
4995
4996 ///////////////////////////////////////////////////////////////////////////////
4997 // //
4998 // sstpivot() Finds a tetrahedron abutting a subsegment. //
4999 // //
5000 // This is the inverse operation of 'tsspivot()'. One subsegment shared by //
5001 // arbitrary number of tetrahedron, the returned tetrahedron is not unique. //
5002 // The edge direction of the returned tetrahedron is conformed to the given //
5003 // subsegment. //
5004 // //
5005 ///////////////////////////////////////////////////////////////////////////////
5006
5007 void tetgenmesh::sstpivot(face* checkseg, triface* retedge)
5008 {
5009 face parentsh;
5010
5011 // Get the subface which holds the subsegment.
5012 sdecode(checkseg->sh[0], parentsh);
5013 #ifdef SELF_CHECK
5014 assert(parentsh.sh != dummysh);
5015 #endif
5016 // Get a tetraheron to which the subface attches.
5017 stpivot(parentsh, *retedge);
5018 if (retedge->tet == dummytet) {
5019 sesymself(parentsh);
5020 stpivot(parentsh, *retedge);
5021 #ifdef SELF_CHECK
5022 assert(retedge->tet != dummytet);
5023 #endif
5024 }
5025 // Correct the edge direction before return.
5026 findedge(retedge, sorg(*checkseg), sdest(*checkseg));
5027 }
5028
5029 ///////////////////////////////////////////////////////////////////////////////
5030 // //
5031 // findorg() Finds a point in the given handle (tetrahedron or subface). //
5032 // //
5033 // If 'dorg' is a one of vertices of the given handle, set the origin of //
5034 // this handle be that point and return TRUE. Otherwise, return FALSE and //
5035 // 'tface' remains unchanged. //
5036 // //
5037 ///////////////////////////////////////////////////////////////////////////////
5038
5039 bool tetgenmesh::findorg(triface* tface, point dorg)
5040 {
5041 if (org(*tface) == dorg) {
5042 return true;
5043 } else {
5044 if (dest(*tface) == dorg) {
5045 enextself(*tface);
5046 return true;
5047 } else {
5048 if (apex(*tface) == dorg) {
5049 enext2self(*tface);
5050 return true;
5051 } else {
5052 if (oppo(*tface) == dorg) {
5053 // Keep 'tface' referring to the same tet after fnext().
5054 adjustedgering(*tface, CCW);
5055 fnextself(*tface);
5056 enext2self(*tface);
5057 return true;
5058 }
5059 }
5060 }
5061 }
5062 return false;
5063 }
5064
5065 bool tetgenmesh::findorg(face* sface, point dorg)
5066 {
5067 if (sorg(*sface) == dorg) {
5068 return true;
5069 } else {
5070 if (sdest(*sface) == dorg) {
5071 senextself(*sface);
5072 return true;
5073 } else {
5074 if (sapex(*sface) == dorg) {
5075 senext2self(*sface);
5076 return true;
5077 }
5078 }
5079 }
5080 return false;
5081 }
5082
5083 ///////////////////////////////////////////////////////////////////////////////
5084 // //
5085 // findedge() Find an edge in the given handle (tetrahedron or subface). //
5086 // //
5087 // The edge is given in two points 'eorg' and 'edest'. It is assumed that //
5088 // the edge must exist in the given handle (tetrahedron or subface). This //
5089 // routine sets the right edge version for the input handle. //
5090 // //
5091 ///////////////////////////////////////////////////////////////////////////////
5092
5093 void tetgenmesh::findedge(triface* tface, point eorg, point edest)
5094 {
5095 int i;
5096
5097 for (i = 0; i < 3; i++) {
5098 if (org(*tface) == eorg) {
5099 if (dest(*tface) == edest) {
5100 // Edge is found, return.
5101 return;
5102 }
5103 } else {
5104 if (org(*tface) == edest) {
5105 if (dest(*tface) == eorg) {
5106 // Edge is found, inverse the direction and return.
5107 esymself(*tface);
5108 return;
5109 }
5110 }
5111 }
5112 enextself(*tface);
5113 }
5114 // It should never be here.
5115 printf("Internalerror in findedge(): Unable to find an edge in tet.\n");
5116 internalerror();
5117 }
5118
5119 void tetgenmesh::findedge(face* sface, point eorg, point edest)
5120 {
5121 int i;
5122
5123 for (i = 0; i < 3; i++) {
5124 if (sorg(*sface) == eorg) {
5125 if (sdest(*sface) == edest) {
5126 // Edge is found, return.
5127 return;
5128 }
5129 } else {
5130 if (sorg(*sface) == edest) {
5131 if (sdest(*sface) == eorg) {
5132 // Edge is found, inverse the direction and return.
5133 sesymself(*sface);
5134 return;
5135 }
5136 }
5137 }
5138 senextself(*sface);
5139 }
5140 printf("Internalerror in findedge(): Unable to find an edge in subface.\n");
5141 internalerror();
5142 }
5143
5144 ///////////////////////////////////////////////////////////////////////////////
5145 // //
5146 // findface() Find the face has the given origin, destination and apex. //
5147 // //
5148 // On input, 'fface' is a handle which may contain the three corners or may //
5149 // not or may be dead. On return, it represents exactly the face with the //
5150 // given origin, destination and apex. //
5151 // //
5152 ///////////////////////////////////////////////////////////////////////////////
5153
5154 void tetgenmesh::findface(triface *fface, point forg, point fdest, point fapex)
5155 {
5156 triface spintet;
5157 enum finddirectionresult collinear;
5158 int hitbdry;
5159
5160 if (!isdead(fface)) {
5161 // First check the easiest case, that 'fface' is just the right one.
5162 if (org(*fface) == forg && dest(*fface) == fdest &&
5163 apex(*fface) == fapex) return;
5164 } else {
5165 // The input handle is dead, use the 'recenttet' if it is alive.
5166 if (!isdead(&recenttet)) *fface = recenttet;
5167 }
5168
5169 if (!isdead(fface)) {
5170 if (!findorg(fface, forg)) {
5171 // 'forg' is not a corner of 'fface', locate it.
5172 preciselocate(forg, fface, tetrahedrons->items);
5173 }
5174 // It is possible that forg is not found in a non-convex mesh.
5175 if (org(*fface) == forg) {
5176 collinear = finddirection(fface, fdest, tetrahedrons->items);
5177 if (collinear == RIGHTCOLLINEAR) {
5178 // fdest is just the destination.
5179 } else if (collinear == LEFTCOLLINEAR) {
5180 enext2self(*fface);
5181 esymself(*fface);
5182 } else if (collinear == TOPCOLLINEAR) {
5183 fnextself(*fface);
5184 enext2self(*fface);
5185 esymself(*fface);
5186 }
5187 }
5188 // It is possible taht fdest is not found in a non-convex mesh.
5189 if ((org(*fface) == forg) && (dest(*fface) == fdest)) {
5190 // Find the apex of 'fapex'.
5191 spintet = *fface;
5192 hitbdry = 0;
5193 do {
5194 if (apex(spintet) == fapex) {
5195 // We have done. Be careful the edge direction of 'spintet',
5196 // it may reversed because of hitting boundary once.
5197 if (org(spintet) != org(*fface)) {
5198 esymself(spintet);
5199 }
5200 *fface = spintet;
5201 return;
5202 }
5203 if (!fnextself(spintet)) {
5204 hitbdry ++;
5205 if (hitbdry < 2) {
5206 esym(*fface, spintet);
5207 if (!fnextself(spintet)) {
5208 hitbdry ++;
5209 }
5210 }
5211 }
5212 } while (hitbdry < 2 && apex(spintet) != apex(*fface));
5213 // It is possible that fapex is not found in a non-convex mesh.
5214 }
5215 }
5216
5217 if (isdead(fface) || (org(*fface) != forg) || (dest(*fface) != fdest) ||
5218 (apex(*fface) != fapex)) {
5219 // Too bad, the input handle is useless. We have to find a handle
5220 // for 'fface' contains the 'forg' and 'fdest'. Here a brute force
5221 // search is performed.
5222 if (b->verbose > 1) {
5223 printf("Warning in findface(): Perform a brute-force searching.\n");
5224 }
5225 enum verttype forgty, fdestty, fapexty;
5226 int share, i;
5227 forgty = pointtype(forg);
5228 fdestty = pointtype(fdest);
5229 fapexty = pointtype(fapex);
5230 setpointtype(forg, DEADVERTEX);
5231 setpointtype(fdest, DEADVERTEX);
5232 setpointtype(fapex, DEADVERTEX);
5233 tetrahedrons->traversalinit();
5234 fface->tet = tetrahedrontraverse();
5235 while (fface->tet != (tetrahedron *) NULL) {
5236 share = 0;
5237 for (i = 0; i < 4; i++) {
5238 if (pointtype((point) fface->tet[4 + i]) == DEADVERTEX) share ++;
5239 }
5240 if (share == 3) {
5241 // Found! Set the correct face and desired corners.
5242 if (pointtype((point) fface->tet[4]) != DEADVERTEX) {
5243 fface->loc = 2;
5244 } else if (pointtype((point) fface->tet[5]) != DEADVERTEX) {
5245 fface->loc = 3;
5246 } else if (pointtype((point) fface->tet[6]) != DEADVERTEX) {
5247 fface->loc = 1;
5248 } else { // pointtype((point) fface->tet[7]) != DEADVERTEX
5249 fface->loc = 0;
5250 }
5251 findedge(fface, forg, fdest);
5252 break;
5253 }
5254 fface->tet = tetrahedrontraverse();
5255 }
5256 setpointtype(forg, forgty);
5257 setpointtype(fdest, fdestty);
5258 setpointtype(fapex, fapexty);
5259 if (fface->tet == (tetrahedron *) NULL) {
5260 // It is impossible to reach here.
5261 printf("Internal error: Fail to find the indicated face.\n");
5262 internalerror();
5263 }
5264 }
5265 }
5266
5267 ///////////////////////////////////////////////////////////////////////////////
5268 // //
5269 // getonextseg() Get the next SEGMENT counterclockwise with the same org. //
5270 // //
5271 // 's' is a subface. This routine reteuns the segment which is counterclock- //
5272 // wise with the origin of s. //
5273 // //
5274 ///////////////////////////////////////////////////////////////////////////////
5275
5276 void tetgenmesh::getonextseg(face* s, face* lseg)
5277 {
5278 face checksh, checkseg;
5279 point forg;
5280
5281 forg = sorg(*s);
5282 checksh = *s;
5283 do {
5284 // Go to the edge at forg's left side.
5285 senext2self(checksh);
5286 // Check if there is a segment attaching this edge.
5287 sspivot(checksh, checkseg);
5288 if (checkseg.sh != dummysh) break;
5289 // No segment! Go to the neighbor of this subface.
5290 spivotself(checksh);
5291 #ifdef SELF_CHECK
5292 // It should always meet a segment before come back.
5293 assert(checksh.sh != s->sh);
5294 #endif
5295 if (sorg(checksh) != forg) {
5296 sesymself(checksh);
5297 #ifdef SELF_CHECK
5298 assert(sorg(checksh) == forg);
5299 #endif
5300 }
5301 } while (true);
5302 if (sorg(checkseg) != forg) sesymself(checkseg);
5303 *lseg = checkseg;
5304 }
5305
5306 ///////////////////////////////////////////////////////////////////////////////
5307 // //
5308 // getseghasorg() Get the segment containing the given point. //
5309 // //
5310 // 'dorg' is an endpoint of a segment S. 'sseg' is a subsegment of S. This //
5311 // routine search a subsegment (along sseg) of S containing dorg. On return, //
5312 // 'sseg' contains 'dorg' as its origin. //
5313 // //
5314 ///////////////////////////////////////////////////////////////////////////////
5315
5316 void tetgenmesh::getseghasorg(face* sseg, point dorg)
5317 {
5318 face nextseg;
5319 point checkpt;
5320
5321 nextseg = *sseg;
5322 checkpt = sorg(nextseg);
5323 while ((checkpt != dorg) && (pointtype(checkpt) == FREESEGVERTEX)) {
5324 // Search dorg along the original direction of sseg.
5325 senext2self(nextseg);
5326 spivotself(nextseg);
5327 nextseg.shver = 0;
5328 if (sdest(nextseg) != checkpt) sesymself(nextseg);
5329 checkpt = sorg(nextseg);
5330 }
5331 if (checkpt == dorg) {
5332 *sseg = nextseg;
5333 return;
5334 }
5335 nextseg = *sseg;
5336 checkpt = sdest(nextseg);
5337 while ((checkpt != dorg) && (pointtype(checkpt) == FREESEGVERTEX)) {
5338 // Search dorg along the destinational direction of sseg.
5339 senextself(nextseg);
5340 spivotself(nextseg);
5341 nextseg.shver = 0;
5342 if (sorg(nextseg) != checkpt) sesymself(nextseg);
5343 checkpt = sdest(nextseg);
5344 }
5345 if (checkpt == dorg) {
5346 sesym(nextseg, *sseg);
5347 return;
5348 }
5349 // Should never be here.
5350 printf("Internalerror in getseghasorg(): Unable to find the subseg.\n");
5351 internalerror();
5352 }
5353
5354 ///////////////////////////////////////////////////////////////////////////////
5355 // //
5356 // getsubsegfarorg() Get the origin of the parent segment of a subseg. //
5357 // //
5358 ///////////////////////////////////////////////////////////////////////////////
5359
5360 tetgenmesh::point tetgenmesh::getsubsegfarorg(face* sseg)
5361 {
5362 face prevseg;
5363 point checkpt;
5364
5365 checkpt = sorg(*sseg);
5366 senext2(*sseg, prevseg);
5367 spivotself(prevseg);
5368 // Search dorg along the original direction of sseg.
5369 while (prevseg.sh != dummysh) {
5370 prevseg.shver = 0;
5371 if (sdest(prevseg) != checkpt) sesymself(prevseg);
5372 checkpt = sorg(prevseg);
5373 senext2self(prevseg);
5374 spivotself(prevseg);
5375 }
5376 return checkpt;
5377 }
5378
5379 ///////////////////////////////////////////////////////////////////////////////
5380 // //
5381 // getsubsegfardest() Get the dest. of the parent segment of a subseg. //
5382 // //
5383 ///////////////////////////////////////////////////////////////////////////////
5384
5385 tetgenmesh::point tetgenmesh::getsubsegfardest(face* sseg)
5386 {
5387 face nextseg;
5388 point checkpt;
5389
5390 checkpt = sdest(*sseg);
5391 senext(*sseg, nextseg);
5392 spivotself(nextseg);
5393 // Search dorg along the destinational direction of sseg.
5394 while (nextseg.sh != dummysh) {
5395 nextseg.shver = 0;
5396 if (sorg(nextseg) != checkpt) sesymself(nextseg);
5397 checkpt = sdest(nextseg);
5398 senextself(nextseg);
5399 spivotself(nextseg);
5400 }
5401 return checkpt;
5402 }
5403
5404 ///////////////////////////////////////////////////////////////////////////////
5405 // //
5406 // printtet() Print out the details of a tetrahedron on screen. //
5407 // //
5408 // It's also used when the highest level of verbosity (`-VVV') is specified. //
5409 // //
5410 ///////////////////////////////////////////////////////////////////////////////
5411
5412 void tetgenmesh::printtet(triface* tface)
5413 {
5414 triface tmpface, prtface;
5415 point tmppt;
5416 face tmpsh;
5417 int facecount;
5418
5419 printf("Tetra x%lx with loc(%i) and ver(%i):",
5420 (unsigned long)(tface->tet), tface->loc, tface->ver);
5421 if (infected(*tface)) {
5422 printf(" (infected)");
5423 }
5424 printf("\n");
5425
5426 tmpface = *tface;
5427 facecount = 0;
5428 while(facecount < 4) {
5429 tmpface.loc = facecount;
5430 sym(tmpface, prtface);
5431 if(prtface.tet == dummytet) {
5432 printf(" [%i] Outer space.\n", facecount);
5433 } else {
5434 printf(" [%i] x%lx loc(%i).", facecount,
5435 (unsigned long)(prtface.tet), prtface.loc);
5436 if (infected(prtface)) {
5437 printf(" (infected)");
5438 }
5439 printf("\n");
5440 }
5441 facecount ++;
5442 }
5443
5444 tmppt = org(*tface);
5445 if(tmppt == (point) NULL) {
5446 printf(" Org [%i] NULL\n", locver2org[tface->loc][tface->ver]);
5447 } else {
5448 printf(" Org [%i] x%lx (%.12g,%.12g,%.12g) %d\n",
5449 locver2org[tface->loc][tface->ver], (unsigned long)(tmppt),
5450 tmppt[0], tmppt[1], tmppt[2], pointmark(tmppt));
5451 }
5452 tmppt = dest(*tface);
5453 if(tmppt == (point) NULL) {
5454 printf(" Dest[%i] NULL\n", locver2dest[tface->loc][tface->ver]);
5455 } else {
5456 printf(" Dest[%i] x%lx (%.12g,%.12g,%.12g) %d\n",
5457 locver2dest[tface->loc][tface->ver], (unsigned long)(tmppt),
5458 tmppt[0], tmppt[1], tmppt[2], pointmark(tmppt));
5459 }
5460 tmppt = apex(*tface);
5461 if(tmppt == (point) NULL) {
5462 printf(" Apex[%i] NULL\n", locver2apex[tface->loc][tface->ver]);
5463 } else {
5464 printf(" Apex[%i] x%lx (%.12g,%.12g,%.12g) %d\n",
5465 locver2apex[tface->loc][tface->ver], (unsigned long)(tmppt),
5466 tmppt[0], tmppt[1], tmppt[2], pointmark(tmppt));
5467 }
5468 tmppt = oppo(*tface);
5469 if(tmppt == (point) NULL) {
5470 printf(" Oppo[%i] NULL\n", loc2oppo[tface->loc]);
5471 } else {
5472 printf(" Oppo[%i] x%lx (%.12g,%.12g,%.12g) %d\n",
5473 loc2oppo[tface->loc], (unsigned long)(tmppt),
5474 tmppt[0], tmppt[1], tmppt[2], pointmark(tmppt));
5475 }
5476
5477 if (b->useshelles) {
5478 tmpface = *tface;
5479 facecount = 0;
5480 while(facecount < 4) {
5481 tmpface.loc = facecount;
5482 tspivot(tmpface, tmpsh);
5483 if(tmpsh.sh != dummysh) {
5484 printf(" [%i] x%lx ID(%i) ", facecount,
5485 (unsigned long)(tmpsh.sh), shellmark(tmpsh));
5486 if (sorg(tmpsh) == (point) NULL) {
5487 printf("(fake)");
5488 }
5489 printf("\n");
5490 }
5491 facecount ++;
5492 }
5493 }
5494 }
5495
5496 ///////////////////////////////////////////////////////////////////////////////
5497 // //
5498 // printsh() Print out the details of a subface or subsegment on screen. //
5499 // //
5500 // It's also used when the highest level of verbosity (`-VVV') is specified. //
5501 // //
5502 ///////////////////////////////////////////////////////////////////////////////
5503
5504 void tetgenmesh::printsh(face* sface)
5505 {
5506 face prtsh;
5507 triface prttet;
5508 point printpoint;
5509
5510 if (sapex(*sface) != NULL) {
5511 printf("subface x%lx, ver %d, mark %d:",
5512 (unsigned long)(sface->sh), sface->shver, shellmark(*sface));
5513 } else {
5514 printf("Subsegment x%lx, ver %d, mark %d:",
5515 (unsigned long)(sface->sh), sface->shver, shellmark(*sface));
5516 }
5517 if (sinfected(*sface)) {
5518 printf(" (infected)");
5519 }
5520 if (shell2badface(*sface)) {
5521 printf(" (queued)");
5522 }
5523 if (sapex(*sface) != NULL) {
5524 if (shelltype(*sface) == SHARP) {
5525 printf(" (sharp)");
5526 } else if (shelltype(*sface) == SKINNY) {
5527 printf(" (skinny)");
5528 }
5529 } else {
5530 if (shelltype(*sface) == SHARP) {
5531 printf(" (sharp)");
5532 }
5533 }
5534 if (checkpbcs) {
5535 if (shellpbcgroup(*sface) >= 0) {
5536 printf(" (pbc %d)", shellpbcgroup(*sface));
5537 }
5538 }
5539 printf("\n");
5540
5541 sdecode(sface->sh[0], prtsh);
5542 if (prtsh.sh == dummysh) {
5543 printf(" [0] = No shell\n");
5544 } else {
5545 printf(" [0] = x%lx %d\n", (unsigned long)(prtsh.sh), prtsh.shver);
5546 }
5547 sdecode(sface->sh[1], prtsh);
5548 if (prtsh.sh == dummysh) {
5549 printf(" [1] = No shell\n");
5550 } else {
5551 printf(" [1] = x%lx %d\n", (unsigned long)(prtsh.sh), prtsh.shver);
5552 }
5553 sdecode(sface->sh[2], prtsh);
5554 if (prtsh.sh == dummysh) {
5555 printf(" [2] = No shell\n");
5556 } else {
5557 printf(" [2] = x%lx %d\n", (unsigned long)(prtsh.sh), prtsh.shver);
5558 }
5559
5560 printpoint = sorg(*sface);
5561 if (printpoint == (point) NULL)
5562 printf(" Org [%d] = NULL\n", vo[sface->shver]);
5563 else
5564 printf(" Org [%d] = x%lx (%.12g,%.12g,%.12g) %d\n",
5565 vo[sface->shver], (unsigned long)(printpoint), printpoint[0],
5566 printpoint[1], printpoint[2], pointmark(printpoint));
5567 printpoint = sdest(*sface);
5568 if (printpoint == (point) NULL)
5569 printf(" Dest[%d] = NULL\n", vd[sface->shver]);
5570 else
5571 printf(" Dest[%d] = x%lx (%.12g,%.12g,%.12g) %d\n",
5572 vd[sface->shver], (unsigned long)(printpoint), printpoint[0],
5573 printpoint[1], printpoint[2], pointmark(printpoint));
5574
5575 if (sapex(*sface) != NULL) {
5576 printpoint = sapex(*sface);
5577 if (printpoint == (point) NULL)
5578 printf(" Apex[%d] = NULL\n", va[sface->shver]);
5579 else
5580 printf(" Apex[%d] = x%lx (%.12g,%.12g,%.12g) %d\n",
5581 va[sface->shver], (unsigned long)(printpoint), printpoint[0],
5582 printpoint[1], printpoint[2], pointmark(printpoint));
5583
5584 decode(sface->sh[6], prttet);
5585 if (prttet.tet == dummytet) {
5586 printf(" [6] = Outer space\n");
5587 } else {
5588 printf(" [6] = x%lx %d\n",
5589 (unsigned long)(prttet.tet), prttet.loc);
5590 }
5591 decode(sface->sh[7], prttet);
5592 if (prttet.tet == dummytet) {
5593 printf(" [7] = Outer space\n");
5594 } else {
5595 printf(" [7] = x%lx %d\n",
5596 (unsigned long)(prttet.tet), prttet.loc);
5597 }
5598
5599 sdecode(sface->sh[8], prtsh);
5600 if (prtsh.sh == dummysh) {
5601 printf(" [8] = No subsegment\n");
5602 } else {
5603 printf(" [8] = x%lx %d\n",
5604 (unsigned long)(prtsh.sh), prtsh.shver);
5605 }
5606 sdecode(sface->sh[9], prtsh);
5607 if (prtsh.sh == dummysh) {
5608 printf(" [9] = No subsegment\n");
5609 } else {
5610 printf(" [9] = x%lx %d\n",
5611 (unsigned long)(prtsh.sh), prtsh.shver);
5612 }
5613 sdecode(sface->sh[10], prtsh);
5614 if (prtsh.sh == dummysh) {
5615 printf(" [10]= No subsegment\n");
5616 } else {
5617 printf(" [10]= x%lx %d\n",
5618 (unsigned long)(prtsh.sh), prtsh.shver);
5619 }
5620 }
5621 }
5622
5623 //
5624 // End of advanced primitives
5625 //
5626
5627 //
5628 // End of mesh manipulation primitives
5629 //
5630
5631 //
5632 // Begin of mesh items searching routines
5633 //
5634
5635 ///////////////////////////////////////////////////////////////////////////////
5636 // //
5637 // makepoint2tetmap() Construct a mapping from points to tetrahedra. //
5638 // //
5639 // Traverses all the tetrahedra, provides each corner of each tetrahedron //
5640 // with a pointer to that tetrahedera. Some pointers will be overwritten by //
5641 // other pointers because each point may be a corner of several tetrahedra, //
5642 // but in the end every point will point to a tetrahedron that contains it. //
5643 // //
5644 ///////////////////////////////////////////////////////////////////////////////
5645
5646 void tetgenmesh::makepoint2tetmap()
5647 {
5648 triface tetloop;
5649 point pointptr;
5650
5651 if (b->verbose > 0) {
5652 printf(" Constructing mapping from points to tetrahedra.\n");
5653 }
5654
5655 // Initialize the point2tet field of each point.
5656 points->traversalinit();
5657 pointptr = pointtraverse();
5658 while (pointptr != (point) NULL) {
5659 setpoint2tet(pointptr, (tetrahedron) NULL);
5660 pointptr = pointtraverse();
5661 }
5662
5663 tetrahedrons->traversalinit();
5664 tetloop.tet = tetrahedrontraverse();
5665 while (tetloop.tet != (tetrahedron *) NULL) {
5666 // Check all four points of the tetrahedron.
5667 tetloop.loc = 0;
5668 pointptr = org(tetloop);
5669 setpoint2tet(pointptr, encode(tetloop));
5670 pointptr = dest(tetloop);
5671 setpoint2tet(pointptr, encode(tetloop));
5672 pointptr = apex(tetloop);
5673 setpoint2tet(pointptr, encode(tetloop));
5674 pointptr = oppo(tetloop);
5675 setpoint2tet(pointptr, encode(tetloop));
5676 // Get the next tetrahedron in the list.
5677 tetloop.tet = tetrahedrontraverse();
5678 }
5679 }
5680
5681 ///////////////////////////////////////////////////////////////////////////////
5682 // //
5683 // makeindex2pointmap() Create a map from index to vertices. //
5684 // //
5685 // 'idx2verlist' returns the created map. Traverse all vertices, a pointer //
5686 // to each vertex is set into the array. The pointer to the first vertex is //
5687 // saved in 'idx2verlist[0]'. Don't forget to minus 'in->firstnumber' when //
5688 // to get the vertex form its index. //
5689 // //
5690 ///////////////////////////////////////////////////////////////////////////////
5691
5692 void tetgenmesh::makeindex2pointmap(point*& idx2verlist)
5693 {
5694 point pointloop;
5695 int idx;
5696
5697 if (b->verbose > 0) {
5698 printf(" Constructing mapping from indices to points.\n");
5699 }
5700
5701 idx2verlist = new point[points->items];
5702
5703 points->traversalinit();
5704 pointloop = pointtraverse();
5705 idx = 0;
5706 while (pointloop != (point) NULL) {
5707 idx2verlist[idx] = pointloop;
5708 idx++;
5709 pointloop = pointtraverse();
5710 }
5711 }
5712
5713 ///////////////////////////////////////////////////////////////////////////////
5714 // //
5715 // makesegmentmap() Create a map from vertices (their indices) to //
5716 // segments incident at the same vertices. //
5717 // //
5718 // Two arrays 'idx2seglist' and 'segsperverlist' together return the map. //
5719 // They form a sparse matrix structure with size (n + 1) x (n + 1), n is the //
5720 // number of segments. idx2seglist contains row information and //
5721 // segsperverlist contains all (non-zero) elements. The i-th entry of //
5722 // idx2seglist is the starting position of i-th row's (non-zero) elements in //
5723 // segsperverlist. The number of elements of i-th row is calculated by the //
5724 // (i+1)-th entry minus i-th entry of idx2seglist. //
5725 // //
5726 // NOTE: These two arrays will be created inside this routine, don't forget //
5727 // to free them after using. //
5728 // //
5729 ///////////////////////////////////////////////////////////////////////////////
5730
5731 void tetgenmesh::makesegmentmap(int*& idx2seglist, shellface**& segsperverlist)
5732 {
5733 shellface *shloop;
5734 int i, j, k;
5735
5736 if (b->verbose > 0) {
5737 printf(" Constructing mapping from points to segments.\n");
5738 }
5739
5740 // Create and initialize 'idx2seglist'.
5741 idx2seglist = new int[points->items + 1];
5742 for (i = 0; i < points->items + 1; i++) idx2seglist[i] = 0;
5743
5744 // Loop the set of segments once, counter the number of segments sharing
5745 // each vertex.
5746 subsegs->traversalinit();
5747 shloop = shellfacetraverse(subsegs);
5748 while (shloop != (shellface *) NULL) {
5749 // Increment the number of sharing segments for each endpoint.
5750 for (i = 0; i < 2; i++) {
5751 j = pointmark((point) shloop[3 + i]) - in->firstnumber;
5752 idx2seglist[j]++;
5753 }
5754 shloop = shellfacetraverse(subsegs);
5755 }
5756
5757 // Calculate the total length of array 'facesperverlist'.
5758 j = idx2seglist[0];
5759 idx2seglist[0] = 0; // Array starts from 0 element.
5760 for (i = 0; i < points->items; i++) {
5761 k = idx2seglist[i + 1];
5762 idx2seglist[i + 1] = idx2seglist[i] + j;
5763 j = k;
5764 }
5765 // The total length is in the last unit of idx2seglist.
5766 segsperverlist = new shellface*[idx2seglist[i]];
5767 // Loop the set of segments again, set the info. of segments per vertex.
5768 subsegs->traversalinit();
5769 shloop = shellfacetraverse(subsegs);
5770 while (shloop != (shellface *) NULL) {
5771 for (i = 0; i < 2; i++) {
5772 j = pointmark((point) shloop[3 + i]) - in->firstnumber;
5773 segsperverlist[idx2seglist[j]] = shloop;
5774 idx2seglist[j]++;
5775 }
5776 shloop = shellfacetraverse(subsegs);
5777 }
5778 // Contents in 'idx2seglist' are shifted, now shift them back.
5779 for (i = points->items - 1; i >= 0; i--) {
5780 idx2seglist[i + 1] = idx2seglist[i];
5781 }
5782 idx2seglist[0] = 0;
5783 }
5784
5785 ///////////////////////////////////////////////////////////////////////////////
5786 // //
5787 // makesubfacemap() Create a map from vertices (their indices) to //
5788 // subfaces incident at the same vertices. //
5789 // //
5790 // Two arrays 'idx2facelist' and 'facesperverlist' together return the map. //
5791 // They form a sparse matrix structure with size (n + 1) x (n + 1), n is the //
5792 // number of subfaces. idx2facelist contains row information and //
5793 // facesperverlist contains all (non-zero) elements. The i-th entry of //
5794 // idx2facelist is the starting position of i-th row's(non-zero) elements in //
5795 // facesperverlist. The number of elements of i-th row is calculated by the //
5796 // (i+1)-th entry minus i-th entry of idx2facelist. //
5797 // //
5798 // NOTE: These two arrays will be created inside this routine, don't forget //
5799 // to free them after using. //
5800 // //
5801 ///////////////////////////////////////////////////////////////////////////////
5802
5803 void tetgenmesh::
5804 makesubfacemap(int*& idx2facelist, shellface**& facesperverlist)
5805 {
5806 shellface *shloop;
5807 int i, j, k;
5808
5809 if (b->verbose > 0) {
5810 printf(" Constructing mapping from points to subfaces.\n");
5811 }
5812
5813 // Create and initialize 'idx2facelist'.
5814 idx2facelist = new int[points->items + 1];
5815 for (i = 0; i < points->items + 1; i++) idx2facelist[i] = 0;
5816
5817 // Loop the set of subfaces once, counter the number of subfaces sharing
5818 // each vertex.
5819 subfaces->traversalinit();
5820 shloop = shellfacetraverse(subfaces);
5821 while (shloop != (shellface *) NULL) {
5822 // Increment the number of sharing segments for each endpoint.
5823 for (i = 0; i < 3; i++) {
5824 j = pointmark((point) shloop[3 + i]) - in->firstnumber;
5825 idx2facelist[j]++;
5826 }
5827 shloop = shellfacetraverse(subfaces);
5828 }
5829
5830 // Calculate the total length of array 'facesperverlist'.
5831 j = idx2facelist[0];
5832 idx2facelist[0] = 0; // Array starts from 0 element.
5833 for (i = 0; i < points->items; i++) {
5834 k = idx2facelist[i + 1];
5835 idx2facelist[i + 1] = idx2facelist[i] + j;
5836 j = k;
5837 }
5838 // The total length is in the last unit of idx2facelist.
5839 facesperverlist = new shellface*[idx2facelist[i]];
5840 // Loop the set of segments again, set the info. of segments per vertex.
5841 subfaces->traversalinit();
5842 shloop = shellfacetraverse(subfaces);
5843 while (shloop != (shellface *) NULL) {
5844 for (i = 0; i < 3; i++) {
5845 j = pointmark((point) shloop[3 + i]) - in->firstnumber;
5846 facesperverlist[idx2facelist[j]] = shloop;
5847 idx2facelist[j]++;
5848 }
5849 shloop = shellfacetraverse(subfaces);
5850 }
5851 // Contents in 'idx2facelist' are shifted, now shift them back.
5852 for (i = points->items - 1; i >= 0; i--) {
5853 idx2facelist[i + 1] = idx2facelist[i];
5854 }
5855 idx2facelist[0] = 0;
5856 }
5857
5858 ///////////////////////////////////////////////////////////////////////////////
5859 // //
5860 // maketetrahedronmap() Create a map from vertices (their indices) to //
5861 // tetrahedra incident at the same vertices. //
5862 // //
5863 // Two arrays 'idx2tetlist' and 'tetsperverlist' together return the map. //
5864 // They form a sparse matrix structure with size (n + 1) x (n + 1), n is the //
5865 // number of tetrahedra. idx2tetlist contains row information and //
5866 // tetsperverlist contains all (non-zero) elements. The i-th entry of //
5867 // idx2tetlist is the starting position of i-th row's (non-zero) elements in //
5868 // tetsperverlist. The number of elements of i-th row is calculated by the //
5869 // (i+1)-th entry minus i-th entry of idx2tetlist. //
5870 // //
5871 // NOTE: These two arrays will be created inside this routine, don't forget //
5872 // to free them after using. //
5873 // //
5874 ///////////////////////////////////////////////////////////////////////////////
5875
5876 void tetgenmesh::
5877 maketetrahedronmap(int*& idx2tetlist, tetrahedron**& tetsperverlist)
5878 {
5879 tetrahedron *tetloop;
5880 int i, j, k;
5881
5882 if (b->verbose > 0) {
5883 printf(" Constructing mapping from points to tetrahedra.\n");
5884 }
5885
5886 // Create and initialize 'idx2tetlist'.
5887 idx2tetlist = new int[points->items + 1];
5888 for (i = 0; i < points->items + 1; i++) idx2tetlist[i] = 0;
5889
5890 // Loop the set of tetrahedra once, counter the number of tetrahedra
5891 // sharing each vertex.
5892 tetrahedrons->traversalinit();
5893 tetloop = tetrahedrontraverse();
5894 while (tetloop != (tetrahedron *) NULL) {
5895 // Increment the number of sharing tetrahedra for each endpoint.
5896 for (i = 0; i < 4; i++) {
5897 j = pointmark((point) tetloop[4 + i]) - in->firstnumber;
5898 idx2tetlist[j]++;
5899 }
5900 tetloop = tetrahedrontraverse();
5901 }
5902
5903 // Calculate the total length of array 'tetsperverlist'.
5904 j = idx2tetlist[0];
5905 idx2tetlist[0] = 0; // Array starts from 0 element.
5906 for (i = 0; i < points->items; i++) {
5907 k = idx2tetlist[i + 1];
5908 idx2tetlist[i + 1] = idx2tetlist[i] + j;
5909 j = k;
5910 }
5911 // The total length is in the last unit of idx2tetlist.
5912 tetsperverlist = new tetrahedron*[idx2tetlist[i]];
5913 // Loop the set of tetrahedra again, set the info. of tet. per vertex.
5914 tetrahedrons->traversalinit();
5915 tetloop = tetrahedrontraverse();
5916 while (tetloop != (tetrahedron *) NULL) {
5917 for (i = 0; i < 4; i++) {
5918 j = pointmark((point) tetloop[4 + i]) - in->firstnumber;
5919 tetsperverlist[idx2tetlist[j]] = tetloop;
5920 idx2tetlist[j]++;
5921 }
5922 tetloop = tetrahedrontraverse();
5923 }
5924 // Contents in 'idx2tetlist' are shifted, now shift them back.
5925 for (i = points->items - 1; i >= 0; i--) {
5926 idx2tetlist[i + 1] = idx2tetlist[i];
5927 }
5928 idx2tetlist[0] = 0;
5929 }
5930
5931 //
5932 // End of mesh items searching routines
5933 //
5934
5935 //
5936 // Begin of linear algebra functions
5937 //
5938
5939 // dot() returns the dot product: v1 dot v2.
5940
5941 inline REAL tetgenmesh::dot(REAL* v1, REAL* v2)
5942 {
5943 return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
5944 }
5945
5946 // cross() computes the cross product: n = v1 cross v2.
5947
5948 inline void tetgenmesh::cross(REAL* v1, REAL* v2, REAL* n)
5949 {
5950 n[0] = v1[1] * v2[2] - v2[1] * v1[2];
5951 n[1] = -(v1[0] * v2[2] - v2[0] * v1[2]);
5952 n[2] = v1[0] * v2[1] - v2[0] * v1[1];
5953 }
5954
5955 // initm44() initializes a 4x4 matrix.
5956 static void initm44(REAL a00, REAL a01, REAL a02, REAL a03,
5957 REAL a10, REAL a11, REAL a12, REAL a13,
5958 REAL a20, REAL a21, REAL a22, REAL a23,
5959 REAL a30, REAL a31, REAL a32, REAL a33,
5960 REAL M[4][4])
5961 {
5962 M[0][0] = a00; M[0][1] = a01; M[0][2] = a02; M[0][3] = a03;
5963 M[1][0] = a10; M[1][1] = a11; M[1][2] = a12; M[1][3] = a13;
5964 M[2][0] = a20; M[2][1] = a21; M[2][2] = a22; M[2][3] = a23;
5965 M[3][0] = a30; M[3][1] = a31; M[3][2] = a32; M[3][3] = a33;
5966 }
5967
5968 // m4xm4() multiplies 2 4x4 matrics: m1 = m1 * m2.
5969 static void m4xm4(REAL m1[4][4], REAL m2[4][4])
5970 {
5971 REAL tmp[4];
5972 int i, j;
5973
5974 for (i = 0; i < 4; i++) { // i-th row
5975 for (j = 0; j < 4; j++) { // j-th col
5976 tmp[j] = m1[i][0] * m2[0][j] + m1[i][1] * m2[1][j]
5977 + m1[i][2] * m2[2][j] + m1[i][3] * m2[3][j];
5978 }
5979 for (j = 0; j < 4; j++)
5980 m1[i][j] = tmp[j];
5981 }
5982 }
5983
5984 // m4xv4() multiplies a 4x4 matrix and 4x1 vector: v2 = m * v1
5985 static void m4xv4(REAL v2[4], REAL m[4][4], REAL v1[4])
5986 {
5987 v2[0] = m[0][0]*v1[0] + m[0][1]*v1[1] + m[0][2]*v1[2] + m[0][3]*v1[3];
5988 v2[1] = m[1][0]*v1[0] + m[1][1]*v1[1] + m[1][2]*v1[2] + m[1][3]*v1[3];
5989 v2[2] = m[2][0]*v1[0] + m[2][1]*v1[1] + m[2][2]*v1[2] + m[2][3]*v1[3];
5990 v2[3] = m[3][0]*v1[0] + m[3][1]*v1[1] + m[3][2]*v1[2] + m[3][3]*v1[3];
5991 }
5992
5993 ///////////////////////////////////////////////////////////////////////////////
5994 // //
5995 // lu_decmp() Compute the LU decomposition of a matrix. //
5996 // //
5997 // Compute the LU decomposition of a (non-singular) square matrix A using //
5998 // partial pivoting and implicit row exchanges. The result is: //
5999 // A = P * L * U, //
6000 // where P is a permutation matrix, L is unit lower triangular, and U is //
6001 // upper triangular. The factored form of A is used in combination with //
6002 // 'lu_solve()' to solve linear equations: Ax = b, or invert a matrix. //
6003 // //
6004 // The inputs are a square matrix 'lu[N..n+N-1][N..n+N-1]', it's size is 'n'.//
6005 // On output, 'lu' is replaced by the LU decomposition of a rowwise permuta- //
6006 // tion of itself, 'ps[N..n+N-1]' is an output vector that records the row //
6007 // permutation effected by the partial pivoting, effectively, 'ps' array //
6008 // tells the user what the permutation matrix P is; 'd' is output as +1/-1 //
6009 // depending on whether the number of row interchanges was even or odd, //
6010 // respectively. //
6011 // //
6012 // Return true if the LU decomposition is successfully computed, otherwise, //
6013 // return false in case that A is a singular matrix. //
6014 // //
6015 ///////////////////////////////////////////////////////////////////////////////
6016
6017 bool tetgenmesh::lu_decmp(REAL lu[4][4], int n, int* ps, REAL* d, int N)
6018 {
6019 REAL scales[4];
6020 REAL pivot, biggest, mult, tempf;
6021 int pivotindex = 0;
6022 int i, j, k;
6023
6024 *d = 1.0; // No row interchanges yet.
6025
6026 for (i = N; i < n + N; i++) { // For each row.
6027 // Find the largest element in each row for row equilibration
6028 biggest = 0.0;
6029 for (j = N; j < n + N; j++)
6030 if (biggest < (tempf = fabs(lu[i][j])))
6031 biggest = tempf;
6032 if (biggest != 0.0)
6033 scales[i] = 1.0 / biggest;
6034 else {
6035 scales[i] = 0.0;
6036 return false; // Zero row: singular matrix.
6037 }
6038 ps[i] = i; // Initialize pivot sequence.
6039 }
6040
6041 for (k = N; k < n + N - 1; k++) { // For each column.
6042 // Find the largest element in each column to pivot around.
6043 biggest = 0.0;
6044 for (i = k; i < n + N; i++) {
6045 if (biggest < (tempf = fabs(lu[ps[i]][k]) * scales[ps[i]])) {
6046 biggest = tempf;
6047 pivotindex = i;
6048 }
6049 }
6050 if (biggest == 0.0) {
6051 return false; // Zero column: singular matrix.
6052 }
6053 if (pivotindex != k) { // Update pivot sequence.
6054 j = ps[k];
6055 ps[k] = ps[pivotindex];
6056 ps[pivotindex] = j;
6057 *d = -(*d); // ...and change the parity of d.
6058 }
6059
6060 // Pivot, eliminating an extra variable each time
6061 pivot = lu[ps[k]][k];
6062 for (i = k + 1; i < n + N; i++) {
6063 lu[ps[i]][k] = mult = lu[ps[i]][k] / pivot;
6064 if (mult != 0.0) {
6065 for (j = k + 1; j < n + N; j++)
6066 lu[ps[i]][j] -= mult * lu[ps[k]][j];
6067 }
6068 }
6069 }
6070
6071 // (lu[ps[n + N - 1]][n + N - 1] == 0.0) ==> A is singular.
6072 return lu[ps[n + N - 1]][n + N - 1] != 0.0;
6073 }
6074
6075 ///////////////////////////////////////////////////////////////////////////////
6076 // //
6077 // lu_solve() Solves the linear equation: Ax = b, after the matrix A //
6078 // has been decomposed into the lower and upper triangular //
6079 // matrices L and U, where A = LU. //
6080 // //
6081 // 'lu[N..n+N-1][N..n+N-1]' is input, not as the matrix 'A' but rather as //
6082 // its LU decomposition, computed by the routine 'lu_decmp'; 'ps[N..n+N-1]' //
6083 // is input as the permutation vector returned by 'lu_decmp'; 'b[N..n+N-1]' //
6084 // is input as the right-hand side vector, and returns with the solution //
6085 // vector. 'lu', 'n', and 'ps' are not modified by this routine and can be //
6086 // left in place for successive calls with different right-hand sides 'b'. //
6087 // //
6088 ///////////////////////////////////////////////////////////////////////////////
6089
6090 void tetgenmesh::lu_solve(REAL lu[4][4], int n, int* ps, REAL* b, int N)
6091 {
6092 int i, j;
6093 REAL X[4], dot;
6094
6095 for (i = N; i < n + N; i++) X[i] = 0.0;
6096
6097 // Vector reduction using U triangular matrix.
6098 for (i = N; i < n + N; i++) {
6099 dot = 0.0;
6100 for (j = N; j < i + N; j++)
6101 dot += lu[ps[i]][j] * X[j];
6102 X[i] = b[ps[i]] - dot;
6103 }
6104
6105 // Back substitution, in L triangular matrix.
6106 for (i = n + N - 1; i >= N; i--) {
6107 dot = 0.0;
6108 for (j = i + 1; j < n + N; j++)
6109 dot += lu[ps[i]][j] * X[j];
6110 X[i] = (X[i] - dot) / lu[ps[i]][i];
6111 }
6112
6113 for (i = N; i < n + N; i++) b[i] = X[i];
6114 }
6115
6116 //
6117 // End of linear algebra functions
6118 //
6119
6120 //
6121 // Begin of geometric tests
6122 //
6123
6124 // All the following routines require the input objects are not degenerate.
6125 // i.e., a triangle must has three non-collinear corners; an edge must
6126 // has two identical endpoints. Degenerate cases should have to detect
6127 // first and then handled as special cases.
6128
6129 ///////////////////////////////////////////////////////////////////////////////
6130 // //
6131 // edge_vert_col_inter() Test whether an edge (ab) and a collinear vertex //
6132 // (p) are intersecting or not. //
6133 // //
6134 // Possible cases are p is coincident to a (p = a), or to b (p = b), or p is //
6135 // inside ab (a < p < b), or outside ab (p < a or p > b). These cases can be //
6136 // quickly determined by comparing the corresponding coords of a, b, and p //
6137 // (which are not all equal). //
6138 // //
6139 // The return value indicates one of the three cases: DISJOINT, SHAREVERTEX //
6140 // (p = a or p = b), and INTERSECT (a < p < b). //
6141 // //
6142 ///////////////////////////////////////////////////////////////////////////////
6143
6144 enum tetgenmesh::interresult tetgenmesh::edge_vert_col_inter(REAL* A, REAL* B,
6145 REAL* P)
6146 {
6147 int i = 0;
6148 do {
6149 if (A[i] < B[i]) {
6150 if (P[i] < A[i]) {
6151 return DISJOINT;
6152 } else if (P[i] > A[i]) {
6153 if (P[i] < B[i]) {
6154 return INTERSECT;
6155 } else if (P[i] > B[i]) {
6156 return DISJOINT;
6157 } else {
6158 // assert(P[i] == B[i]);
6159 return SHAREVERTEX;
6160 }
6161 } else {
6162 // assert(P[i] == A[i]);
6163 return SHAREVERTEX;
6164 }
6165 } else if (A[i] > B[i]) {
6166 if (P[i] < B[i]) {
6167 return DISJOINT;
6168 } else if (P[i] > B[i]) {
6169 if (P[i] < A[i]) {
6170 return INTERSECT;
6171 } else if (P[i] > A[i]) {
6172 return DISJOINT;
6173 } else {
6174 // assert(P[i] == A[i]);
6175 return SHAREVERTEX;
6176 }
6177 } else {
6178 // assert(P[i] == B[i]);
6179 return SHAREVERTEX;
6180 }
6181 }
6182 // i-th coordinates are equal, try i+1-th;
6183 i++;
6184 } while (i < 3);
6185 // Should never be here.
6186 return DISJOINT;
6187 }
6188
6189 ///////////////////////////////////////////////////////////////////////////////
6190 // //
6191 // edge_edge_cop_inter() Test whether two coplanar edges (ab, and pq) are //
6192 // intersecting or not. //
6193 // //
6194 // Possible cases are ab and pq are disjointed, or proper intersecting (int- //
6195 // ersect at a point other than their endpoints), or both collinear and int- //
6196 // ersecting, or sharing at a common endpoint, or are coincident. //
6197 // //
6198 // A reference point R is required, which is exactly not coplanar with these //
6199 // two edges. Since the caller knows these two edges are coplanar, it must //
6200 // be able to provide (or calculate) such a point. //
6201 // //
6202 // The return value indicates one of the four cases: DISJOINT, SHAREVERTEX, //
6203 // SHAREEDGE, and INTERSECT. //
6204 // //
6205 ///////////////////////////////////////////////////////////////////////////////
6206
6207 enum tetgenmesh::interresult tetgenmesh:: edge_edge_cop_inter(REAL* A, REAL* B,
6208 REAL* P, REAL* Q, REAL* R)
6209 {
6210 REAL s1, s2, s3, s4;
6211
6212 #ifdef SELF_CHECK
6213 assert(R != NULL);
6214 #endif
6215 s1 = orient3d(A, B, R, P);
6216 s2 = orient3d(A, B, R, Q);
6217 if (s1 * s2 > 0.0) {
6218 // Both p and q are at the same side of ab.
6219 return DISJOINT;
6220 }
6221 s3 = orient3d(P, Q, R, A);
6222 s4 = orient3d(P, Q, R, B);
6223 if (s3 * s4 > 0.0) {
6224 // Both a and b are at the same side of pq.
6225 return DISJOINT;
6226 }
6227
6228 // Possible degenerate cases are:
6229 // (1) Only one of p and q is collinear with ab;
6230 // (2) Both p and q are collinear with ab;
6231 // (3) Only one of a and b is collinear with pq.
6232 enum interresult abp, abq;
6233 enum interresult pqa, pqb;
6234
6235 if (s1 == 0.0) {
6236 // p is collinear with ab.
6237 abp = edge_vert_col_inter(A, B, P);
6238 if (abp == INTERSECT) {
6239 // p is inside ab.
6240 return INTERSECT;
6241 }
6242 if (s2 == 0.0) {
6243 // q is collinear with ab. Case (2).
6244 abq = edge_vert_col_inter(A, B, Q);
6245 if (abq == INTERSECT) {
6246 // q is inside ab.
6247 return INTERSECT;
6248 }
6249 if (abp == SHAREVERTEX && abq == SHAREVERTEX) {
6250 // ab and pq are identical.
6251 return SHAREEDGE;
6252 }
6253 pqa = edge_vert_col_inter(P, Q, A);
6254 if (pqa == INTERSECT) {
6255 // a is inside pq.
6256 return INTERSECT;
6257 }
6258 pqb = edge_vert_col_inter(P, Q, B);
6259 if (pqb == INTERSECT) {
6260 // b is inside pq.
6261 return INTERSECT;
6262 }
6263 if (abp == SHAREVERTEX || abq == SHAREVERTEX) {
6264 // either p or q is coincident with a or b.
6265 #ifdef SELF_CHECK
6266 // ONLY one case is possible, otherwise, shoule be SHAREEDGE.
6267 assert(abp ^ abq);
6268 #endif
6269 return SHAREVERTEX;
6270 }
6271 // The last case. They are disjointed.
6272 #ifdef SELF_CHECK
6273 assert((abp == DISJOINT) && (abp == abq && abq == pqa && pqa == pqb));
6274 #endif
6275 return DISJOINT;
6276 } else {
6277 // p is collinear with ab. Case (1).
6278 #ifdef SELF_CHECK
6279 assert(abp == SHAREVERTEX || abp == DISJOINT);
6280 #endif
6281 return abp;
6282 }
6283 }
6284 // p is NOT collinear with ab.
6285 if (s2 == 0.0) {
6286 // q is collinear with ab. Case (1).
6287 abq = edge_vert_col_inter(A, B, Q);
6288 #ifdef SELF_CHECK
6289 assert(abq == SHAREVERTEX || abq == DISJOINT || abq == INTERSECT);
6290 #endif
6291 return abq;
6292 }
6293
6294 // We have found p and q are not collinear with ab. However, it is still
6295 // possible that a or b is collinear with pq (ONLY one of a and b).
6296 if (s3 == 0.0) {
6297 // a is collinear with pq. Case (3).
6298 #ifdef SELF_CHECK
6299 assert(s4 != 0.0);
6300 #endif
6301 pqa = edge_vert_col_inter(P, Q, A);
6302 #ifdef SELF_CHECK
6303 // This case should have been detected in above.
6304 assert(pqa != SHAREVERTEX);
6305 assert(pqa == INTERSECT || pqa == DISJOINT);
6306 #endif
6307 return pqa;
6308 }
6309 if (s4 == 0.0) {
6310 // b is collinear with pq. Case (3).
6311 #ifdef SELF_CHECK
6312 assert(s3 != 0.0);
6313 #endif
6314 pqb = edge_vert_col_inter(P, Q, B);
6315 #ifdef SELF_CHECK
6316 // This case should have been detected in above.
6317 assert(pqb != SHAREVERTEX);
6318 assert(pqb == INTERSECT || pqb == DISJOINT);
6319 #endif
6320 return pqb;
6321 }
6322
6323 // ab and pq are intersecting properly.
6324 return INTERSECT;
6325 }
6326
6327 ///////////////////////////////////////////////////////////////////////////////
6328 // //
6329 // Notations //
6330 // //
6331 // Let ABC be the plane passes through a, b, and c; ABC+ be the halfspace //
6332 // including the set of all points x, such that orient3d(a, b, c, x) > 0; //
6333 // ABC- be the other halfspace, such that for each point x in ABC-, //
6334 // orient3d(a, b, c, x) < 0. For the set of x which are on ABC, orient3d(a, //
6335 // b, c, x) = 0. //
6336 // //
6337 ///////////////////////////////////////////////////////////////////////////////
6338
6339 ///////////////////////////////////////////////////////////////////////////////
6340 // //
6341 // tri_vert_copl_inter() Test whether a triangle (abc) and a coplanar //
6342 // point (p) are intersecting or not. //
6343 // //
6344 // Possible cases are p is inside abc, or on an edge of, or coincident with //
6345 // a vertex of, or outside abc. //
6346 // //
6347 // A reference point R is required. R is exactly not coplanar with abc and p.//
6348 // Since the caller knows they are coplanar, it must be able to provide (or //
6349 // calculate) such a point. //
6350 // //
6351 // The return value indicates one of the four cases: DISJOINT, SHAREVERTEX, //
6352 // and INTERSECT. //
6353 // //
6354 ///////////////////////////////////////////////////////////////////////////////
6355
6356 enum tetgenmesh::interresult tetgenmesh::tri_vert_cop_inter(REAL* A, REAL* B,
6357 REAL* C, REAL* P, REAL* R)
6358 {
6359 REAL s1, s2, s3;
6360 int sign;
6361
6362 #ifdef SELF_CHECK
6363 assert(R != (REAL *) NULL);
6364 #endif
6365 // Adjust the orientation of a, b, c and r, so that we can assume that
6366 // r is strictly in ABC- (i.e., r is above ABC wrt. right-hand rule).
6367 s1 = orient3d(A, B, C, R);
6368 #ifdef SELF_CHECK
6369 assert(s1 != 0.0);
6370 #endif
6371 sign = s1 < 0.0 ? 1 : -1;
6372
6373 // Test starts from here.
6374 s1 = orient3d(A, B, R, P) * sign;
6375 if (s1 < 0.0) {
6376 // p is in ABR-.
6377 return DISJOINT;
6378 }
6379 s2 = orient3d(B, C, R, P) * sign;
6380 if (s2 < 0.0) {
6381 // p is in BCR-.
6382 return DISJOINT;
6383 }
6384 s3 = orient3d(C, A, R, P) * sign;
6385 if (s3 < 0.0) {
6386 // p is in CAR-.
6387 return DISJOINT;
6388 }
6389 if (s1 == 0.0) {
6390 // p is on ABR.
6391 if (s2 == 0.0) {
6392 // p is on BCR.
6393 #ifdef SELF_CHECK
6394 assert(s3 > 0.0);
6395 #endif
6396 // p is coincident with b.
6397 return SHAREVERTEX;
6398 }
6399 if (s3 == 0.0) {
6400 // p is on CAR.
6401 // p is coincident with a.
6402 return SHAREVERTEX;
6403 }
6404 // p is on edge ab.
6405 return INTERSECT;
6406 }
6407 // p is in ABR+.
6408 if (s2 == 0.0) {
6409 // p is on BCR.
6410 if (s3 == 0.0) {
6411 // p is on CAR.
6412 // p is coincident with c.
6413 return SHAREVERTEX;
6414 }
6415 // p is on edge bc.
6416 return INTERSECT;
6417 }
6418 if (s3 == 0.0) {
6419 // p is on CAR.
6420 // p is on edge ca.
6421 return INTERSECT;
6422 }
6423
6424 // p is strictly inside abc.
6425 return INTERSECT;
6426 }
6427
6428 ///////////////////////////////////////////////////////////////////////////////
6429 // //
6430 // tri_edge_cop_inter() Test whether a triangle (abc) and a coplanar edge //
6431 // (pq) are intersecting or not. //
6432 // //
6433 // A reference point R is required. R is exactly not coplanar with abc and //
6434 // pq. Since the caller knows they are coplanar, it must be able to provide //
6435 // (or calculate) such a point. //
6436 // //
6437 // The return value indicates one of the four cases: DISJOINT, SHAREVERTEX, //
6438 // SHAREEDGE, and INTERSECT. //
6439 // //
6440 ///////////////////////////////////////////////////////////////////////////////
6441
6442 enum tetgenmesh::interresult tetgenmesh::tri_edge_cop_inter(REAL* A, REAL* B,
6443 REAL* C, REAL* P, REAL* Q, REAL* R)
6444 {
6445 enum interresult abpq, bcpq, capq;
6446 enum interresult abcp, abcq;
6447
6448 // Test if pq is intersecting one of edges of abc.
6449 abpq = edge_edge_cop_inter(A, B, P, Q, R);
6450 if (abpq == INTERSECT || abpq == SHAREEDGE) {
6451 return abpq;
6452 }
6453 bcpq = edge_edge_cop_inter(B, C, P, Q, R);
6454 if (bcpq == INTERSECT || bcpq == SHAREEDGE) {
6455 return bcpq;
6456 }
6457 capq = edge_edge_cop_inter(C, A, P, Q, R);
6458 if (capq == INTERSECT || capq == SHAREEDGE) {
6459 return capq;
6460 }
6461
6462 // Test if p and q is inside abc.
6463 abcp = tri_vert_cop_inter(A, B, C, P, R);
6464 if (abcp == INTERSECT) {
6465 return INTERSECT;
6466 }
6467 abcq = tri_vert_cop_inter(A, B, C, Q, R);
6468 if (abcq == INTERSECT) {
6469 return INTERSECT;
6470 }
6471
6472 // Combine the test results of edge intersectings and triangle insides
6473 // to detect whether abc and pq are sharing vertex or disjointed.
6474 if (abpq == SHAREVERTEX) {
6475 // p or q is coincident with a or b.
6476 #ifdef SELF_CHECK
6477 assert(abcp ^ abcq);
6478 #endif
6479 return SHAREVERTEX;
6480 }
6481 if (bcpq == SHAREVERTEX) {
6482 // p or q is coincident with b or c.
6483 #ifdef SELF_CHECK
6484 assert(abcp ^ abcq);
6485 #endif
6486 return SHAREVERTEX;
6487 }
6488 if (capq == SHAREVERTEX) {
6489 // p or q is coincident with c or a.
6490 #ifdef SELF_CHECK
6491 assert(abcp ^ abcq);
6492 #endif
6493 return SHAREVERTEX;
6494 }
6495
6496 // They are disjointed.
6497 return DISJOINT;
6498 }
6499
6500 ///////////////////////////////////////////////////////////////////////////////
6501 // //
6502 // tri_edge_inter_tail() Test whether a triangle (abc) and an edge (pq) //
6503 // are intersecting or not. //
6504 // //
6505 // s1 and s2 are results of pre-performed orientation tests. s1 = orient3d( //
6506 // a, b, c, p); s2 = orient3d(a, b, c, q). To separate this routine from //
6507 // tri_edge_inter() can save two orientation tests in tri_tri_inter(). //
6508 // //
6509 // The return value indicates one of the four cases: DISJOINT, SHAREVERTEX, //
6510 // SHAREEDGE, and INTERSECT. //
6511 // //
6512 ///////////////////////////////////////////////////////////////////////////////
6513
6514 enum tetgenmesh::interresult tetgenmesh::tri_edge_inter_tail(REAL* A, REAL* B,
6515 REAL* C, REAL* P, REAL* Q, REAL s1, REAL s2)
6516 {
6517 REAL s3, s4, s5;
6518 int sign;
6519
6520 if (s1 * s2 > 0.0) {
6521 // p, q are at the same halfspace of ABC, no intersection.
6522 return DISJOINT;
6523 }
6524
6525 if (s1 * s2 < 0.0) {
6526 // p, q are both not on ABC (and not sharing vertices, edges of abc).
6527 // Adjust the orientation of a, b, c and p, so that we can assume that
6528 // p is strictly in ABC-, and q is strictly in ABC+.
6529 sign = s1 < 0.0 ? 1 : -1;
6530 s3 = orient3d(A, B, P, Q) * sign;
6531 if (s3 < 0.0) {
6532 // q is at ABP-.
6533 return DISJOINT;
6534 }
6535 s4 = orient3d(B, C, P, Q) * sign;
6536 if (s4 < 0.0) {
6537 // q is at BCP-.
6538 return DISJOINT;
6539 }
6540 s5 = orient3d(C, A, P, Q) * sign;
6541 if (s5 < 0.0) {
6542 // q is at CAP-.
6543 return DISJOINT;
6544 }
6545 if (s3 == 0.0) {
6546 // q is on ABP.
6547 if (s4 == 0.0) {
6548 // q is on BCP (and q must in CAP+).
6549 #ifdef SELF_CHECK
6550 assert(s5 > 0.0);
6551 #endif
6552 // pq intersects abc at vertex b.
6553 return SHAREVERTEX;
6554 }
6555 if (s5 == 0.0) {
6556 // q is on CAP (and q must in BCP+).
6557 // pq intersects abc at vertex a.
6558 return SHAREVERTEX;
6559 }
6560 // q in both BCP+ and CAP+.
6561 // pq crosses ab properly.
6562 return INTERSECT;
6563 }
6564 // q is in ABP+;
6565 if (s4 == 0.0) {
6566 // q is on BCP.
6567 if (s5 == 0.0) {
6568 // q is on CAP.
6569 // pq intersects abc at vertex c.
6570 return SHAREVERTEX;
6571 }
6572 // pq crosses bc properly.
6573 return INTERSECT;
6574 }
6575 // q is in BCP+;
6576 if (s5 == 0.0) {
6577 // q is on CAP.
6578 // pq crosses ca properly.
6579 return INTERSECT;
6580 }
6581 // q is in CAP+;
6582 // pq crosses abc properly.
6583 return INTERSECT;
6584 }
6585
6586 if (s1 != 0.0 || s2 != 0.0) {
6587 // Either p or q is coplanar with abc. ONLY one of them is possible.
6588 if (s1 == 0.0) {
6589 // p is coplanar with abc, q can be used as reference point.
6590 #ifdef SELF_CHECK
6591 assert(s2 != 0.0);
6592 #endif
6593 return tri_vert_cop_inter(A, B, C, P, Q);
6594 } else {
6595 // q is coplanar with abc, p can be used as reference point.
6596 #ifdef SELF_CHECK
6597 assert(s2 == 0.0);
6598 #endif
6599 return tri_vert_cop_inter(A, B, C, Q, P);
6600 }
6601 }
6602
6603 // pq is coplanar with abc. Calculate a point which is exactly not
6604 // coplanar with a, b, and c.
6605 REAL R[3], N[3];
6606 REAL ax, ay, az, bx, by, bz;
6607
6608 ax = A[0] - B[0];
6609 ay = A[1] - B[1];
6610 az = A[2] - B[2];
6611 bx = A[0] - C[0];
6612 by = A[1] - C[1];
6613 bz = A[2] - C[2];
6614 N[0] = ay * bz - by * az;
6615 N[1] = az * bx - bz * ax;
6616 N[2] = ax * by - bx * ay;
6617 // The normal should not be a zero vector (otherwise, abc are collinear).
6618 #ifdef SELF_CHECK
6619 assert((fabs(N[0]) + fabs(N[1]) + fabs(N[2])) > 0.0);
6620 #endif
6621 // The reference point R is lifted from A to the normal direction with
6622 // a distance d = average edge length of the triangle abc.
6623 R[0] = N[0] + A[0];
6624 R[1] = N[1] + A[1];
6625 R[2] = N[2] + A[2];
6626 // Becareful the case: if the non-zero component(s) in N is smaller than
6627 // the machine epsilon (i.e., 2^(-16) for double), R will exactly equal
6628 // to A due to the round-off error. Do check if it is.
6629 if (R[0] == A[0] && R[1] == A[1] && R[2] == A[2]) {
6630 int i, j;
6631 for (i = 0; i < 3; i++) {
6632 #ifdef SELF_CHECK
6633 assert (R[i] == A[i]);
6634 #endif
6635 j = 2;
6636 do {
6637 if (N[i] > 0.0) {
6638 N[i] += (j * macheps);
6639 } else {
6640 N[i] -= (j * macheps);
6641 }
6642 R[i] = N[i] + A[i];
6643 j *= 2;
6644 } while (R[i] == A[i]);
6645 }
6646 }
6647
6648 return tri_edge_cop_inter(A, B, C, P, Q, R);
6649 }
6650
6651 ///////////////////////////////////////////////////////////////////////////////
6652 // //
6653 // tri_edge_inter() Test whether a triangle (abc) and an edge (pq) are //
6654 // intersecting or not. //
6655 // //
6656 // The return value indicates one of the four cases: DISJOINT, SHAREVERTEX, //
6657 // SHAREEDGE, and INTERSECT. //
6658 // //
6659 ///////////////////////////////////////////////////////////////////////////////
6660
6661 enum tetgenmesh::interresult tetgenmesh::tri_edge_inter(REAL* A, REAL* B,
6662 REAL* C, REAL* P, REAL* Q)
6663 {
6664 REAL s1, s2;
6665
6666 // Test the locations of p and q with respect to ABC.
6667 s1 = orient3d(A, B, C, P);
6668 s2 = orient3d(A, B, C, Q);
6669
6670 return tri_edge_inter_tail(A, B, C, P, Q, s1, s2);
6671 }
6672
6673 ///////////////////////////////////////////////////////////////////////////////
6674 // //
6675 // tri_tri_inter() Test whether two triangle (abc) and (opq) are //
6676 // intersecting or not. //
6677 // //
6678 // The return value indicates one of the five cases: DISJOINT, SHAREVERTEX, //
6679 // SHAREEDGE, SHAREFACE, and INTERSECT. //
6680 // //
6681 ///////////////////////////////////////////////////////////////////////////////
6682
6683 enum tetgenmesh::interresult tetgenmesh::tri_tri_inter(REAL* A, REAL* B,
6684 REAL* C, REAL* O, REAL* P, REAL* Q)
6685 {
6686 REAL s_o, s_p, s_q;
6687 REAL s_a, s_b, s_c;
6688
6689 s_o = orient3d(A, B, C, O);
6690 s_p = orient3d(A, B, C, P);
6691 s_q = orient3d(A, B, C, Q);
6692 if ((s_o * s_p > 0.0) && (s_o * s_q > 0.0)) {
6693 // o, p, q are all in the same halfspace of ABC.
6694 return DISJOINT;
6695 }
6696
6697 s_a = orient3d(O, P, Q, A);
6698 s_b = orient3d(O, P, Q, B);
6699 s_c = orient3d(O, P, Q, C);
6700 if ((s_a * s_b > 0.0) && (s_a * s_c > 0.0)) {
6701 // a, b, c are all in the same halfspace of OPQ.
6702 return DISJOINT;
6703 }
6704
6705 enum interresult abcop, abcpq, abcqo;
6706 int shareedge = 0;
6707
6708 abcop = tri_edge_inter_tail(A, B, C, O, P, s_o, s_p);
6709 if (abcop == INTERSECT) {
6710 return INTERSECT;
6711 } else if (abcop == SHAREEDGE) {
6712 shareedge++;
6713 }
6714 abcpq = tri_edge_inter_tail(A, B, C, P, Q, s_p, s_q);
6715 if (abcpq == INTERSECT) {
6716 return INTERSECT;
6717 } else if (abcpq == SHAREEDGE) {
6718 shareedge++;
6719 }
6720 abcqo = tri_edge_inter_tail(A, B, C, Q, O, s_q, s_o);
6721 if (abcqo == INTERSECT) {
6722 return INTERSECT;
6723 } else if (abcqo == SHAREEDGE) {
6724 shareedge++;
6725 }
6726 if (shareedge == 3) {
6727 // opq are coincident with abc.
6728 return SHAREFACE;
6729 }
6730 #ifdef SELF_CHECK
6731 // It is only possible either no share edge or one.
6732 assert(shareedge == 0 || shareedge == 1);
6733 #endif
6734
6735 // Continue to detect whether opq and abc are intersecting or not.
6736 enum interresult opqab, opqbc, opqca;
6737
6738 opqab = tri_edge_inter_tail(O, P, Q, A, B, s_a, s_b);
6739 if (opqab == INTERSECT) {
6740 return INTERSECT;
6741 }
6742 opqbc = tri_edge_inter_tail(O, P, Q, B, C, s_b, s_c);
6743 if (opqbc == INTERSECT) {
6744 return INTERSECT;
6745 }
6746 opqca = tri_edge_inter_tail(O, P, Q, C, A, s_c, s_a);
6747 if (opqca == INTERSECT) {
6748 return INTERSECT;
6749 }
6750
6751 // At this point, two triangles are not intersecting and not coincident.
6752 // They may be share an edge, or share a vertex, or disjoint.
6753 if (abcop == SHAREEDGE) {
6754 #ifdef SELF_CHECK
6755 assert(abcpq == SHAREVERTEX && abcqo == SHAREVERTEX);
6756 #endif
6757 // op is coincident with an edge of abc.
6758 return SHAREEDGE;
6759 }
6760 if (abcpq == SHAREEDGE) {
6761 #ifdef SELF_CHECK
6762 assert(abcop == SHAREVERTEX && abcqo == SHAREVERTEX);
6763 #endif
6764 // pq is coincident with an edge of abc.
6765 return SHAREEDGE;
6766 }
6767 if (abcqo == SHAREEDGE) {
6768 #ifdef SELF_CHECK
6769 assert(abcop == SHAREVERTEX && abcpq == SHAREVERTEX);
6770 #endif
6771 // qo is coincident with an edge of abc.
6772 return SHAREEDGE;
6773 }
6774
6775 // They may share a vertex or disjoint.
6776 if (abcop == SHAREVERTEX) {
6777 // o or p is coincident with a vertex of abc.
6778 if (abcpq == SHAREVERTEX) {
6779 // p is the coincident vertex.
6780 #ifdef SELF_CHECK
6781 assert(abcqo != SHAREVERTEX);
6782 #endif
6783 } else {
6784 // o is the coincident vertex.
6785 #ifdef SELF_CHECK
6786 assert(abcqo == SHAREVERTEX);
6787 #endif
6788 }
6789 return SHAREVERTEX;
6790 }
6791 if (abcpq == SHAREVERTEX) {
6792 // q is the coincident vertex.
6793 #ifdef SELF_CHECK
6794 assert(abcqo == SHAREVERTEX);
6795 #endif
6796 return SHAREVERTEX;
6797 }
6798
6799 // They are disjoint.
6800 return DISJOINT;
6801 }
6802
6803 ///////////////////////////////////////////////////////////////////////////////
6804 // //
6805 // insphere_sos() Insphere test with symbolic perturbation. //
6806 // //
6807 // The input points a, b, c, and d should be non-coplanar. They must be ord- //
6808 // ered so that they have a positive orientation (as defined by orient3d()), //
6809 // or the sign of the result will be reversed. //
6810 // //
6811 // Return a positive value if the point e lies inside the circumsphere of a, //
6812 // b, c, and d; a negative value if it lies outside. //
6813 // //
6814 ///////////////////////////////////////////////////////////////////////////////
6815
6816 REAL tetgenmesh::insphere_sos(REAL* pa, REAL* pb, REAL* pc, REAL* pd, REAL* pe,
6817 int ia, int ib, int ic, int id, int ie)
6818 {
6819 REAL det;
6820
6821 det = insphere(pa, pb, pc, pd, pe);
6822 if (det != 0.0) {
6823 return det;
6824 }
6825
6826 // det = 0.0, use symbolic perturbation.
6827 REAL *p[5], *tmpp;
6828 REAL sign, det_c, det_d;
6829 int idx[5], perm, tmp;
6830 int n, i, j;
6831
6832 p[0] = pa; idx[0] = ia;
6833 p[1] = pb; idx[1] = ib;
6834 p[2] = pc; idx[2] = ic;
6835 p[3] = pd; idx[3] = id;
6836 p[4] = pe; idx[4] = ie;
6837
6838 // Bubble sort the points by the increasing order of the indices.
6839 n = 5;
6840 perm = 0; // The number of total swaps.
6841 for (i = 0; i < n - 1; i++) {
6842 for (j = 0; j < n - 1 - i; j++) {
6843 if (idx[j + 1] < idx[j]) { // compare the two neighbors.
6844 tmp = idx[j]; // swap idx[j] and idx[j + 1]
6845 idx[j] = idx[j + 1];
6846 idx[j + 1] = tmp;
6847 tmpp = p[j]; // swap p[j] and p[j + 1]
6848 p[j] = p[j + 1];
6849 p[j + 1] = tmpp;
6850 perm++;
6851 }
6852 }
6853 }
6854
6855 sign = (perm % 2 == 0) ? 1.0 : -1.0;
6856 det_c = orient3d(p[1], p[2], p[3], p[4]); // orient3d(b, c, d, e)
6857 if (det_c != 0.0) {
6858 return sign * det_c;
6859 }
6860 det_d = orient3d(p[0], p[2], p[3], p[4]); // orient3d(a, c, d, e)
6861 return -sign * det_d;
6862 }
6863
6864 ///////////////////////////////////////////////////////////////////////////////
6865 // //
6866 // iscollinear() Check if three points are approximately collinear. //
6867 // //
6868 // 'eps' is a relative error tolerance. The collinearity is determined by //
6869 // the value q = cos(theta), where theta is the angle between two vectors //
6870 // A->B and A->C. They're collinear if 1.0 - q <= epspp. //
6871 // //
6872 ///////////////////////////////////////////////////////////////////////////////
6873
6874 bool tetgenmesh::iscollinear(REAL* A, REAL* B, REAL* C, REAL eps)
6875 {
6876 REAL abx, aby, abz;
6877 REAL acx, acy, acz;
6878 REAL Lv, Lw, dd;
6879 REAL d, q;
6880
6881 // Limit of two closed points.
6882 q = longest * eps;
6883 q *= q;
6884
6885 abx = A[0] - B[0];
6886 aby = A[1] - B[1];
6887 abz = A[2] - B[2];
6888 acx = A[0] - C[0];
6889 acy = A[1] - C[1];
6890 acz = A[2] - C[2];
6891 Lv = abx * abx + aby * aby + abz * abz;
6892 // Is AB (nearly) indentical?
6893 if (Lv < q) return true;
6894 Lw = acx * acx + acy * acy + acz * acz;
6895 // Is AC (nearly) indentical?
6896 if (Lw < q) return true;
6897 dd = abx * acx + aby * acy + abz * acz;
6898
6899 d = (dd * dd) / (Lv * Lw);
6900 if (d > 1.0) d = 1.0; // Rounding.
6901 q = 1.0 - sqrt(d); // Notice 0 < q < 1.0.
6902
6903 return q <= eps;
6904 }
6905
6906 ///////////////////////////////////////////////////////////////////////////////
6907 // //
6908 // iscoplanar() Check if four points are approximately coplanar. //
6909 // //
6910 // 'vol6' is six times of the signed volume of the tetrahedron formed by the //
6911 // four points. 'eps' is the relative error tolerance. The coplanarity is //
6912 // determined by the value: q = fabs(vol6) / L^3, where L is the average //
6913 // edge length of the tet. They're coplanar if q <= eps. //
6914 // //
6915 ///////////////////////////////////////////////////////////////////////////////
6916
6917 bool tetgenmesh::
6918 iscoplanar(REAL* k, REAL* l, REAL* m, REAL* n, REAL vol6, REAL eps)
6919 {
6920 REAL L, q;
6921 REAL x, y, z;
6922
6923 if (vol6 == 0.0) return true;
6924
6925 x = k[0] - l[0];
6926 y = k[1] - l[1];
6927 z = k[2] - l[2];
6928 L = sqrt(x * x + y * y + z * z);
6929 x = l[0] - m[0];
6930 y = l[1] - m[1];
6931 z = l[2] - m[2];
6932 L += sqrt(x * x + y * y + z * z);
6933 x = m[0] - k[0];
6934 y = m[1] - k[1];
6935 z = m[2] - k[2];
6936 L += sqrt(x * x + y * y + z * z);
6937 x = k[0] - n[0];
6938 y = k[1] - n[1];
6939 z = k[2] - n[2];
6940 L += sqrt(x * x + y * y + z * z);
6941 x = l[0] - n[0];
6942 y = l[1] - n[1];
6943 z = l[2] - n[2];
6944 L += sqrt(x * x + y * y + z * z);
6945 x = m[0] - n[0];
6946 y = m[1] - n[1];
6947 z = m[2] - n[2];
6948 L += sqrt(x * x + y * y + z * z);
6949 #ifdef SELF_CHECK
6950 assert(L > 0.0);
6951 #endif
6952 L /= 6.0;
6953 q = fabs(vol6) / (L * L * L);
6954
6955 return q <= eps;
6956 }
6957
6958 ///////////////////////////////////////////////////////////////////////////////
6959 // //
6960 // iscospheric() Check if five points are approximately coplanar. //
6961 // //
6962 // 'vol24' is the 24 times of the signed volume of the 4-dimensional simplex //
6963 // formed by the five points. 'eps' is the relative tolerance. The cosphere //
6964 // case is determined by the value: q = fabs(vol24) / L^4, where L is the //
6965 // average edge length of the simplex. They're cosphere if q <= eps. //
6966 // //
6967 ///////////////////////////////////////////////////////////////////////////////
6968
6969 bool tetgenmesh::
6970 iscospheric(REAL* k, REAL* l, REAL* m, REAL* n, REAL* o, REAL vol24, REAL eps)
6971 {
6972 REAL L, q;
6973
6974 // A 4D simplex has 10 edges.
6975 L = distance(k, l);
6976 L += distance(l, m);
6977 L += distance(m, k);
6978 L += distance(k, n);
6979 L += distance(l, n);
6980 L += distance(m, n);
6981 L += distance(k, o);
6982 L += distance(l, o);
6983 L += distance(m, o);
6984 L += distance(n, o);
6985 #ifdef SELF_CHECK
6986 assert(L > 0.0);
6987 #endif
6988 L /= 10.0;
6989 q = fabs(vol24) / (L * L * L * L);
6990
6991 return q < eps;
6992 }
6993
6994 //
6995 // End of geometric tests
6996 //
6997
6998 //
6999 // Begin of Geometric quantities calculators
7000 //
7001
7002 // distance() computs the Euclidean distance between two points.
7003 inline REAL tetgenmesh::distance(REAL* p1, REAL* p2)
7004 {
7005 return sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) +
7006 (p2[1] - p1[1]) * (p2[1] - p1[1]) +
7007 (p2[2] - p1[2]) * (p2[2] - p1[2]));
7008 }
7009
7010 ///////////////////////////////////////////////////////////////////////////////
7011 // //
7012 // shortdistance() Returns the shortest distance from point p to a line //
7013 // defined by two points e1 and e2. //
7014 // //
7015 // First compute the projection length l_p of the vector v1 = p - e1 along //
7016 // the vector v2 = e2 - e1. Then Pythagoras' Theorem is used to compute the //
7017 // shortest distance. //
7018 // //
7019 // This routine allows that p is collinear with the line. In this case, the //
7020 // return value is zero. The two points e1 and e2 should not be identical. //
7021 // //
7022 ///////////////////////////////////////////////////////////////////////////////
7023
7024 REAL tetgenmesh::shortdistance(REAL* p, REAL* e1, REAL* e2)
7025 {
7026 REAL v1[3], v2[3];
7027 REAL len, l_p;
7028
7029 v1[0] = e2[0] - e1[0];
7030 v1[1] = e2[1] - e1[1];
7031 v1[2] = e2[2] - e1[2];
7032 v2[0] = p[0] - e1[0];
7033 v2[1] = p[1] - e1[1];
7034 v2[2] = p[2] - e1[2];
7035
7036 len = sqrt(dot(v1, v1));
7037 #ifdef SELF_CHECK
7038 assert(len != 0.0);
7039 #endif
7040 v1[0] /= len;
7041 v1[1] /= len;
7042 v1[2] /= len;
7043 l_p = dot(v1, v2);
7044
7045 return sqrt(dot(v2, v2) - l_p * l_p);
7046 }
7047
7048 ///////////////////////////////////////////////////////////////////////////////
7049 // //
7050 // shortdistance() Returns the shortest distance from point p to a face. //
7051 // //
7052 ///////////////////////////////////////////////////////////////////////////////
7053
7054 REAL tetgenmesh::shortdistance(REAL* p, REAL* e1, REAL* e2, REAL* e3)
7055 {
7056 REAL prj[3];
7057
7058 projpt2face(p, e1, e2, e3, prj);
7059 return distance(p, prj);
7060 }
7061
7062 ///////////////////////////////////////////////////////////////////////////////
7063 // //
7064 // interiorangle() Return the interior angle (0 - 2 * PI) between vectors //
7065 // o->p1 and o->p2. //
7066 // //
7067 // 'n' is the normal of the plane containing face (o, p1, p2). The interior //
7068 // angle is the total angle rotating from o->p1 around n to o->p2. Exchange //
7069 // the position of p1 and p2 will get the complement angle of the other one. //
7070 // i.e., interiorangle(o, p1, p2) = 2 * PI - interiorangle(o, p2, p1). Set //
7071 // 'n' be NULL if you only want the interior angle between 0 - PI. //
7072 // //
7073 ///////////////////////////////////////////////////////////////////////////////
7074
7075 REAL tetgenmesh::interiorangle(REAL* o, REAL* p1, REAL* p2, REAL* n)
7076 {
7077 REAL v1[3], v2[3], np[3];
7078 REAL theta, costheta, lenlen;
7079 REAL ori, len1, len2;
7080
7081 // Get the interior angle (0 - PI) between o->p1, and o->p2.
7082 v1[0] = p1[0] - o[0];
7083 v1[1] = p1[1] - o[1];
7084 v1[2] = p1[2] - o[2];
7085 v2[0] = p2[0] - o[0];
7086 v2[1] = p2[1] - o[1];
7087 v2[2] = p2[2] - o[2];
7088 len1 = sqrt(dot(v1, v1));
7089 len2 = sqrt(dot(v2, v2));
7090 lenlen = len1 * len2;
7091 #ifdef SELF_CHECK
7092 assert(lenlen != 0.0);
7093 #endif
7094 costheta = dot(v1, v2) / lenlen;
7095 if (costheta > 1.0) {
7096 costheta = 1.0; // Roundoff.
7097 } else if (costheta < -1.0) {
7098 costheta = -1.0; // Roundoff.
7099 }
7100 theta = acos(costheta);
7101 if (n != NULL) {
7102 // Get a point above the face (o, p1, p2);
7103 np[0] = o[0] + n[0];
7104 np[1] = o[1] + n[1];
7105 np[2] = o[2] + n[2];
7106 // Adjust theta (0 - 2 * PI).
7107 ori = orient3d(p1, o, np, p2);
7108 if (ori > 0.0) {
7109 theta = 2 * PI - theta;
7110 }
7111 }
7112
7113 return theta;
7114 }
7115
7116 ///////////////////////////////////////////////////////////////////////////////
7117 // //
7118 // projpt2edge() Return the projection point from a point to an edge. //
7119 // //
7120 ///////////////////////////////////////////////////////////////////////////////
7121
7122 void tetgenmesh::projpt2edge(REAL* p, REAL* e1, REAL* e2, REAL* prj)
7123 {
7124 REAL v1[3], v2[3];
7125 REAL len, l_p;
7126
7127 v1[0] = e2[0] - e1[0];
7128 v1[1] = e2[1] - e1[1];
7129 v1[2] = e2[2] - e1[2];
7130 v2[0] = p[0] - e1[0];
7131 v2[1] = p[1] - e1[1];
7132 v2[2] = p[2] - e1[2];
7133
7134 len = sqrt(dot(v1, v1));
7135 #ifdef SELF_CHECK
7136 assert(len != 0.0);
7137 #endif
7138 v1[0] /= len;
7139 v1[1] /= len;
7140 v1[2] /= len;
7141 l_p = dot(v1, v2);
7142
7143 prj[0] = e1[0] + l_p * v1[0];
7144 prj[1] = e1[1] + l_p * v1[1];
7145 prj[2] = e1[2] + l_p * v1[2];
7146 }
7147
7148 ///////////////////////////////////////////////////////////////////////////////
7149 // //
7150 // projpt2face() Return the projection point from a point to a face. //
7151 // //
7152 ///////////////////////////////////////////////////////////////////////////////
7153
7154 void tetgenmesh::projpt2face(REAL* p, REAL* f1, REAL* f2, REAL* f3, REAL* prj)
7155 {
7156 REAL fnormal[3], v1[3];
7157 REAL len, dist;
7158
7159 // Get the unit face normal.
7160 facenormal(f1, f2, f3, fnormal, &len);
7161 #ifdef SELF_CHECK
7162 assert(len > 0.0);
7163 #endif
7164 fnormal[0] /= len;
7165 fnormal[1] /= len;
7166 fnormal[2] /= len;
7167 // Get the vector v1 = |p - f1|.
7168 v1[0] = p[0] - f1[0];
7169 v1[1] = p[1] - f1[1];
7170 v1[2] = p[2] - f1[2];
7171 // Get the project distance.
7172 dist = dot(fnormal, v1);
7173
7174 // Get the project point.
7175 prj[0] = p[0] - dist * fnormal[0];
7176 prj[1] = p[1] - dist * fnormal[1];
7177 prj[2] = p[2] - dist * fnormal[2];
7178 }
7179
7180 ///////////////////////////////////////////////////////////////////////////////
7181 // //
7182 // facenormal() Calculate the normal of a face given by three points. //
7183 // //
7184 // In general, the face normal can be calculate by the cross product of any //
7185 // pair of the three edge vectors. However, if the three points are nearly //
7186 // collinear, the rounding error may harm the result. To choose a good pair //
7187 // of vectors is helpful to reduce the error. //
7188 // //
7189 ///////////////////////////////////////////////////////////////////////////////
7190
7191 void tetgenmesh::facenormal(REAL* pa, REAL* pb, REAL* pc, REAL* n, REAL* nlen)
7192 {
7193 REAL v1[3], v2[3];
7194
7195 v1[0] = pb[0] - pa[0];
7196 v1[1] = pb[1] - pa[1];
7197 v1[2] = pb[2] - pa[2];
7198 v2[0] = pc[0] - pa[0];
7199 v2[1] = pc[1] - pa[1];
7200 v2[2] = pc[2] - pa[2];
7201
7202 cross(v1, v2, n);
7203 if (nlen != (REAL *) NULL) {
7204 *nlen = sqrt(dot(n, n));
7205 }
7206 }
7207
7208 ///////////////////////////////////////////////////////////////////////////////
7209 // //
7210 // edgeorthonormal() Return the unit normal of an edge in a given plane. //
7211 // //
7212 // The edge is from e1 to e2, the plane is defined by given an additional //
7213 // point op, which is non-collinear with the edge. In addition, the side of //
7214 // the edge in which op lies defines the positive position of the normal. //
7215 // //
7216 // Let v1 be the unit vector from e1 to e2, v2 be the unit edge vector from //
7217 // e1 to op, fn be the unit face normal calculated by fn = v1 x v2. Then the //
7218 // unit edge normal of e1e2 pointing to op is n = fn x v1. Note, we should //
7219 // not change the position of fn and v1, otherwise, we get the edge normal //
7220 // pointing to the other side of op. //
7221 // //
7222 ///////////////////////////////////////////////////////////////////////////////
7223
7224 void tetgenmesh::edgeorthonormal(REAL* e1, REAL* e2, REAL* op, REAL* n)
7225 {
7226 REAL v1[3], v2[3], fn[3];
7227 REAL len;
7228
7229 // Get the edge vector v1.
7230 v1[0] = e2[0] - e1[0];
7231 v1[1] = e2[1] - e1[1];
7232 v1[2] = e2[2] - e1[2];
7233 // Get the edge vector v2.
7234 v2[0] = op[0] - e1[0];
7235 v2[1] = op[1] - e1[1];
7236 v2[2] = op[2] - e1[2];
7237 // Get the face normal fn = v1 x v2.
7238 cross(v1, v2, fn);
7239 // Get the edge normal n pointing to op. n = fn x v1.
7240 cross(fn, v1, n);
7241 // Normalize the vector.
7242 len = sqrt(dot(n, n));
7243 n[0] /= len;
7244 n[1] /= len;
7245 n[2] /= len;
7246 }
7247
7248 ///////////////////////////////////////////////////////////////////////////////
7249 // //
7250 // facedihedral() Return the dihedral angle (in radian) between two //
7251 // adjoining faces. //
7252 // //
7253 // 'pa', 'pb' are the shared edge of these two faces, 'pc1', and 'pc2' are //
7254 // apexes of these two faces. Return the angle (between 0 to 2*pi) between //
7255 // the normal of face (pa, pb, pc1) and normal of face (pa, pb, pc2). //
7256 // //
7257 ///////////////////////////////////////////////////////////////////////////////
7258
7259 REAL tetgenmesh::facedihedral(REAL* pa, REAL* pb, REAL* pc1, REAL* pc2)
7260 {
7261 REAL n1[3], n2[3];
7262 REAL n1len, n2len;
7263 REAL costheta, ori;
7264 REAL theta;
7265
7266 facenormal(pa, pb, pc1, n1, &n1len);
7267 facenormal(pa, pb, pc2, n2, &n2len);
7268 costheta = dot(n1, n2) / (n1len * n2len);
7269 // Be careful rounding error!
7270 if (costheta > 1.0) {
7271 costheta = 1.0;
7272 } else if (costheta < -1.0) {
7273 costheta = -1.0;
7274 }
7275 theta = acos(costheta);
7276 ori = orient3d(pa, pb, pc1, pc2);
7277 if (ori > 0.0) {
7278 theta = 2 * PI - theta;
7279 }
7280
7281 return theta;
7282 }
7283
7284 ///////////////////////////////////////////////////////////////////////////////
7285 // //
7286 // tetalldihedral() Get all (six) dihedral angles of a tet. //
7287 // //
7288 // The tet is given by its four corners a, b, c, and d. If 'cosdd' is not //
7289 // NULL, it returns the cosines of the 6 dihedral angles, the corresponding //
7290 // edges are: ab, bc, ca, ad, bd, and cd. If 'cosmaxd' (or 'cosmind') is not //
7291 // NULL, it returns the cosine of the maximal (or minimal) dihedral angle. //
7292 // //
7293 ///////////////////////////////////////////////////////////////////////////////
7294
7295 void tetgenmesh::tetalldihedral(point pa, point pb, point pc, point pd,
7296 REAL* cosdd, REAL* cosmaxd, REAL* cosmind)
7297 {
7298 REAL N[4][3], cosd, len;
7299 int f1, f2, i, j;
7300
7301 // Get four normals of faces of the tet.
7302 tetallnormal(pa, pb, pc, pd, N, NULL);
7303 // Normalize the normals.
7304 for (i = 0; i < 4; i++) {
7305 len = sqrt(dot(N[i], N[i]));
7306 if (len != 0.0) {
7307 for (j = 0; j < 3; j++) N[i][j] /= len;
7308 }
7309 }
7310
7311 for (i = 0; i < 6; i++) {
7312 switch (i) {
7313 case 0: f1 = 2; f2 = 3; break; // edge ab.
7314 case 1: f1 = 0; f2 = 3; break; // edge bc.
7315 case 2: f1 = 1; f2 = 3; break; // edge ca.
7316 case 3: f1 = 1; f2 = 2; break; // edge ad.
7317 case 4: f1 = 2; f2 = 0; break; // edge bd.
7318 case 5: f1 = 0; f2 = 1; break; // edge cd.
7319 }
7320 cosd = -dot(N[f1], N[f2]);
7321 if (cosdd) cosdd[i] = cosd;
7322 if (i == 0) {
7323 if (cosmaxd) *cosmaxd = cosd;
7324 if (cosmind) *cosmind = cosd;
7325 } else {
7326 if (cosmaxd) *cosmaxd = cosd < *cosmaxd ? cosd : *cosmaxd;
7327 if (cosmind) *cosmind = cosd > *cosmind ? cosd : *cosmind;
7328 }
7329 }
7330 }
7331
7332 ///////////////////////////////////////////////////////////////////////////////
7333 // //
7334 // tetallnormal() Get the in-noramls of the four faces of a given tet. //
7335 // //
7336 // Let tet be abcd. N[4][3] returns the four normals, which are: N[0] cbd, //
7337 // N[1] acd, N[2] bad, N[3] abc. These normals are unnormalized. //
7338 // //
7339 ///////////////////////////////////////////////////////////////////////////////
7340
7341 void tetgenmesh::tetallnormal(point pa, point pb, point pc, point pd,
7342 REAL N[4][3], REAL* volume)
7343 {
7344 REAL A[4][4], rhs[4], D;
7345 int indx[4];
7346 int i, j;
7347
7348 // get the entries of A[3][3].
7349 for (i = 0; i < 3; i++) A[0][i] = pa[i] - pd[i]; // d->a vec
7350 for (i = 0; i < 3; i++) A[1][i] = pb[i] - pd[i]; // d->b vec
7351 for (i = 0; i < 3; i++) A[2][i] = pc[i] - pd[i]; // d->c vec
7352 // Compute the inverse of matrix A, to get 3 normals of the 4 faces.
7353 lu_decmp(A, 3, indx, &D, 0); // Decompose the matrix just once.
7354 if (volume != NULL) {
7355 // Get the volume of the tet.
7356 *volume = fabs((A[indx[0]][0] * A[indx[1]][1] * A[indx[2]][2])) / 6.0;
7357 }
7358 for (j = 0; j < 3; j++) {
7359 for (i = 0; i < 3; i++) rhs[i] = 0.0;
7360 rhs[j] = 1.0; // Positive means the inside direction
7361 lu_solve(A, 3, indx, rhs, 0);
7362 for (i = 0; i < 3; i++) N[j][i] = rhs[i];
7363 }
7364 // Get the fourth normal by summing up the first three.
7365 for (i = 0; i < 3; i++) N[3][i] = - N[0][i] - N[1][i] - N[2][i];
7366 }
7367
7368 ///////////////////////////////////////////////////////////////////////////////
7369 // //
7370 // circumsphere() Calculate the smallest circumsphere (center and radius) //
7371 // of the given three or four points. //
7372 // //
7373 // The circumsphere of four points (a tetrahedron) is unique if they are not //
7374 // degenerate. If 'pd = NULL', the smallest circumsphere of three points is //
7375 // the diametral sphere of the triangle if they are not degenerate. //
7376 // //
7377 // Return TRUE if the input points are not degenerate and the circumcenter //
7378 // and circumradius are returned in 'cent' and 'radius' respectively if they //
7379 // are not NULLs. Otherwise, return FALSE indicated the points are degenrate.//
7380 // //
7381 ///////////////////////////////////////////////////////////////////////////////
7382
7383 bool tetgenmesh::
7384 circumsphere(REAL* pa, REAL* pb, REAL* pc, REAL* pd, REAL* cent, REAL* radius)
7385 {
7386 REAL A[4][4], rhs[4], D;
7387 int indx[4];
7388
7389 // Compute the coefficient matrix A (3x3).
7390 A[0][0] = pb[0] - pa[0];
7391 A[0][1] = pb[1] - pa[1];
7392 A[0][2] = pb[2] - pa[2];
7393 A[1][0] = pc[0] - pa[0];
7394 A[1][1] = pc[1] - pa[1];
7395 A[1][2] = pc[2] - pa[2];
7396 if (pd != NULL) {
7397 A[2][0] = pd[0] - pa[0];
7398 A[2][1] = pd[1] - pa[1];
7399 A[2][2] = pd[2] - pa[2];
7400 } else {
7401 cross(A[0], A[1], A[2]);
7402 }
7403
7404 // Compute the right hand side vector b (3x1).
7405 rhs[0] = 0.5 * dot(A[0], A[0]);
7406 rhs[1] = 0.5 * dot(A[1], A[1]);
7407 if (pd != NULL) {
7408 rhs[2] = 0.5 * dot(A[2], A[2]);
7409 } else {
7410 rhs[2] = 0.0;
7411 }
7412
7413 // Solve the 3 by 3 equations use LU decomposition with partial pivoting
7414 // and backward and forward substitute..
7415 if (!lu_decmp(A, 3, indx, &D, 0)) {
7416 if (radius != (REAL *) NULL) *radius = 0.0;
7417 return false;
7418 }
7419 lu_solve(A, 3, indx, rhs, 0);
7420 if (cent != (REAL *) NULL) {
7421 cent[0] = pa[0] + rhs[0];
7422 cent[1] = pa[1] + rhs[1];
7423 cent[2] = pa[2] + rhs[2];
7424 }
7425 if (radius != (REAL *) NULL) {
7426 *radius = sqrt(rhs[0] * rhs[0] + rhs[1] * rhs[1] + rhs[2] * rhs[2]);
7427 }
7428 return true;
7429 }
7430
7431 ///////////////////////////////////////////////////////////////////////////////
7432 // //
7433 // inscribedsphere() Compute the radius and center of the biggest //
7434 // inscribed sphere of a given tetrahedron. //
7435 // //
7436 // The tetrahedron is given by its four points, it must not be degenerate. //
7437 // The center and radius are returned in 'cent' and 'radius' respectively if //
7438 // they are not NULLs. //
7439 // //
7440 // Geometrical fact. For any simplex in d dimension, //
7441 // r/h1 + r/h2 + ... r/hn = 1 (n <= d + 1); //
7442 // where r is the radius of inscribed ball, and h is the height of each side //
7443 // of the simplex. The value of 'r/h' is just the barycenter coordinates of //
7444 // each vertex of the simplex. Therefore, we can compute the radius and //
7445 // center of the smallest inscribed ball as following equations: //
7446 // r = 1.0 / (1/h1 + 1/h2 + ... + 1/hn); (1) //
7447 // C = r/h1 * P1 + r/h2 * P2 + ... + r/hn * Pn; (2) //
7448 // where C is the vector of center, P1, P2, .. Pn are vectors of vertices. //
7449 // Here (2) contains n linear equations with n variables. (h, P) must be a //
7450 // pair, h is the height from P to its opposite face. //
7451 // //
7452 ///////////////////////////////////////////////////////////////////////////////
7453
7454 void tetgenmesh::inscribedsphere(REAL* pa, REAL* pb, REAL* pc, REAL* pd,
7455 REAL* cent, REAL* radius)
7456 {
7457 REAL N[4][3], H[4]; // Normals (colume vectors) and heights of each face.
7458 REAL rd;
7459 int i;
7460
7461 // Get the all normals of the tet.
7462 tetallnormal(pa, pb, pc, pd, N, NULL);
7463 for (i = 0; i < 4; i++) {
7464 // H[i] is the inverse of height of its corresponding face.
7465 H[i] = sqrt(dot(N[i], N[i]));
7466 }
7467 // Compute the radius use eq. (1).
7468 rd = 1.0 / (H[0] + H[1] + H[2] + H[3]);
7469 if (radius != (REAL*) NULL) *radius = rd;
7470 if (cent != (REAL*) NULL) {
7471 // Compute the center use eq. (2).
7472 cent[0] = rd * (H[0] * pa[0] + H[1] * pb[0] + H[2] * pc[0] + H[3] * pd[0]);
7473 cent[1] = rd * (H[0] * pa[1] + H[1] * pb[1] + H[2] * pc[1] + H[3] * pd[1]);
7474 cent[2] = rd * (H[0] * pa[2] + H[1] * pb[2] + H[2] * pc[2] + H[3] * pd[2]);
7475 }
7476 }
7477
7478 ///////////////////////////////////////////////////////////////////////////////
7479 // //
7480 // rotatepoint() Create a point by rotating an existing point. //
7481 // //
7482 // Create a 3D point by rotating point 'p' with an angle 'rotangle' (in arc //
7483 // degree) around a rotating axis given by a vector from point 'p1' to 'p2'. //
7484 // The rotation is according with right-hand rule, i.e., use your right-hand //
7485 // to grab the axis with your thumber pointing to its positive direction, //
7486 // your fingers indicate the rotating direction. //
7487 // //
7488 // The rotating steps are the following: //
7489 // 1. Translate vector 'p1->p2' to origin, M1; //
7490 // 2. Rotate vector around the Y-axis until it lies in the YZ plane, M2; //
7491 // 3. Rotate vector around the X-axis until it lies on the Z axis, M3; //
7492 // 4. Perform the rotation of 'p' around the z-axis, M4; //
7493 // 5. Undo Step 3, M5; //
7494 // 6. Undo Step 2, M6; //
7495 // 7. Undo Step 1, M7; //
7496 // Use matrix multiplication to combine the above sequences, we get: //
7497 // p0' = T * p0, where T = M7 * M6 * M5 * M4 * M3 * M2 * M1 //
7498 // //
7499 ///////////////////////////////////////////////////////////////////////////////
7500
7501 void tetgenmesh::rotatepoint(REAL* p, REAL rotangle, REAL* p1, REAL* p2)
7502 {
7503 REAL T[4][4], pp0[4], p0t[4], p2t[4];
7504 REAL roty, rotx, alphaR, projlen;
7505 REAL dx, dy, dz;
7506
7507 initm44(1, 0, 0, -p1[0],
7508 0, 1, 0, -p1[1],
7509 0, 0, 1, -p1[2],
7510 0, 0, 0, 1, T);
7511 pp0[0] = p[0]; pp0[1] = p[1]; pp0[2] = p[2]; pp0[3] = 1.0;
7512 m4xv4(p0t, T, pp0); // Step 1
7513 pp0[0] = p2[0]; pp0[1] = p2[1]; pp0[2] = p2[2]; pp0[3] = 1.0;
7514 m4xv4(p2t, T, pp0); // Step 1
7515
7516 // Get the rotation angle around y-axis;
7517 dx = p2t[0];
7518 dz = p2t[2];
7519 projlen = sqrt(dx * dx + dz * dz);
7520 if (projlen <= (b->epsilon * 1e-2) * longest) {
7521 roty = 0;
7522 } else {
7523 roty = acos(dz / projlen);
7524 if (dx < 0) {
7525 roty = -roty;
7526 }
7527 }
7528
7529 initm44(cos(-roty), 0, sin(-roty), 0,
7530 0, 1, 0, 0,
7531 -sin(-roty), 0, cos(-roty), 0,
7532 0, 0, 0, 1, T);
7533 pp0[0] = p0t[0]; pp0[1] = p0t[1]; pp0[2] = p0t[2]; pp0[3] = 1.0;
7534 m4xv4(p0t, T, pp0); // Step 2
7535 pp0[0] = p2t[0]; pp0[1] = p2t[1]; pp0[2] = p2t[2]; pp0[3] = 1.0;
7536 m4xv4(p2t, T, pp0); // Step 2
7537
7538 // Get the rotation angle around x-axis
7539 dy = p2t[1];
7540 dz = p2t[2];
7541 projlen = sqrt(dy * dy + dz * dz);
7542 if (projlen <= (b->epsilon * 1e-2) * longest) {
7543 rotx = 0;
7544 } else {
7545 rotx = acos(dz / projlen);
7546 if (dy < 0) {
7547 rotx = -rotx;
7548 }
7549 }
7550
7551 initm44(1, 0, 0, 0,
7552 0, cos(rotx), -sin(rotx), 0,
7553 0, sin(rotx), cos(rotx), 0,
7554 0, 0, 0, 1, T);
7555 pp0[0] = p0t[0]; pp0[1] = p0t[1]; pp0[2] = p0t[2]; pp0[3] = 1.0;
7556 m4xv4(p0t, T, pp0); // Step 3
7557 // pp0[0] = p2t[0]; pp0[1] = p2t[1]; pp0[2] = p2t[2]; pp0[3] = 1.0;
7558 // m4xv4(p2t, T, pp0); // Step 3
7559
7560 alphaR = rotangle;
7561 initm44(cos(alphaR), -sin(alphaR), 0, 0,
7562 sin(alphaR), cos(alphaR), 0, 0,
7563 0, 0, 1, 0,
7564 0, 0, 0, 1, T);
7565 pp0[0] = p0t[0]; pp0[1] = p0t[1]; pp0[2] = p0t[2]; pp0[3] = 1.0;
7566 m4xv4(p0t, T, pp0); // Step 4
7567
7568 initm44(1, 0, 0, 0,
7569 0, cos(-rotx), -sin(-rotx), 0,
7570 0, sin(-rotx), cos(-rotx), 0,
7571 0, 0, 0, 1, T);
7572 pp0[0] = p0t[0]; pp0[1] = p0t[1]; pp0[2] = p0t[2]; pp0[3] = 1.0;
7573 m4xv4(p0t, T, pp0); // Step 5
7574
7575 initm44(cos(roty), 0, sin(roty), 0,
7576 0, 1, 0, 0,
7577 -sin(roty), 0, cos(roty), 0,
7578 0, 0, 0, 1, T);
7579 pp0[0] = p0t[0]; pp0[1] = p0t[1]; pp0[2] = p0t[2]; pp0[3] = 1.0;
7580 m4xv4(p0t, T, pp0); // Step 6
7581
7582 initm44(1, 0, 0, p1[0],
7583 0, 1, 0, p1[1],
7584 0, 0, 1, p1[2],
7585 0, 0, 0, 1, T);
7586 pp0[0] = p0t[0]; pp0[1] = p0t[1]; pp0[2] = p0t[2]; pp0[3] = 1.0;
7587 m4xv4(p0t, T, pp0); // Step 7
7588
7589 p[0] = p0t[0];
7590 p[1] = p0t[1];
7591 p[2] = p0t[2];
7592 }
7593
7594 ///////////////////////////////////////////////////////////////////////////////
7595 // //
7596 // spherelineint() 3D line sphere (or circle) intersection. //
7597 // //
7598 // The line is given by two points p1, and p2, the sphere is centered at c //
7599 // with radius r. This function returns a pointer array p which first index //
7600 // indicates the number of intersection point, followed by coordinate pairs. //
7601 // //
7602 // The following code are adapted from: http://astronomy.swin.edu.au/pbourke //
7603 // /geometry/sphereline. Paul Bourke [email protected] //
7604 // //
7605 ///////////////////////////////////////////////////////////////////////////////
7606
7607 void tetgenmesh::spherelineint(REAL* p1, REAL* p2, REAL* C, REAL R, REAL p[7])
7608 {
7609 REAL x1, y1, z1; // P1 coordinates (point of line)
7610 REAL x2, y2, z2; // P2 coordinates (point of line)
7611 REAL x3, y3, z3, r; // P3 coordinates and radius (sphere)
7612 REAL a, b, c, mu, i ;
7613
7614 x1 = p1[0]; y1 = p1[1]; z1 = p1[2];
7615 x2 = p2[0]; y2 = p2[1]; z2 = p2[2];
7616 x3 = C[0]; y3 = C[1]; z3 = C[2];
7617 r = R;
7618
7619 a = (x2 - x1) * (x2 - x1)
7620 + (y2 - y1) * (y2 - y1)
7621 + (z2 - z1) * (z2 - z1);
7622 b = 2 * ( (x2 - x1) * (x1 - x3)
7623 + (y2 - y1) * (y1 - y3)
7624 + (z2 - z1) * (z1 - z3) ) ;
7625 c = (x3 * x3) + (y3 * y3) + (z3 * z3)
7626 + (x1 * x1) + (y1 * y1) + (z1 * z1)
7627 - 2 * (x3 * x1 + y3 * y1 + z3 * z1) - (r * r) ;
7628 i = b * b - 4 * a * c ;
7629
7630 if (i < 0.0) {
7631 // no intersection
7632 p[0] = 0.0;
7633 } else if (i == 0.0) {
7634 // one intersection
7635 p[0] = 1.0;
7636 mu = -b / (2 * a) ;
7637 p[1] = x1 + mu * (x2 - x1);
7638 p[2] = y1 + mu * (y2 - y1);
7639 p[3] = z1 + mu * (z2 - z1);
7640 } else {
7641 // two intersections
7642 p[0] = 2.0;
7643 // first intersection
7644 mu = (-b + sqrt((b * b) - 4 * a * c)) / (2 * a);
7645 p[1] = x1 + mu * (x2 - x1);
7646 p[2] = y1 + mu * (y2 - y1);
7647 p[3] = z1 + mu * (z2 - z1);
7648 // second intersection
7649 mu = (-b - sqrt((b * b) - 4 * a * c)) / (2 * a);
7650 p[4] = x1 + mu * (x2 - x1);
7651 p[5] = y1 + mu * (y2 - y1);
7652 p[6] = z1 + mu * (z2 - z1);
7653 }
7654 }
7655
7656 ///////////////////////////////////////////////////////////////////////////////
7657 // //
7658 // linelineint() Calculate the shortest line between two lines in 3D. //
7659 // //
7660 // Two 3D lines generally don't intersect at a point, they may be parallel ( //
7661 // no intersections), or coincident (infinite intersections) but most often //
7662 // only their projections onto a plane intersect. If they don't exactly int- //
7663 // ersect at a point they can be connected by a line segment, the shortest //
7664 // segment is unique and is often considered to be their intersection in 3D. //
7665 // //
7666 // The following code are adapted from: http://astronomy.swin.edu.au/pbourke //
7667 // /geometry/lineline3d. Paul Bourke [email protected] //
7668 // //
7669 // Calculate the line segment PaPb that is the shortest route between two //
7670 // lines P1P2 and P3P4. This function returns a pointer array p which first //
7671 // index indicates there exists solution or not, 0 means no solution, 1 meas //
7672 // has solution followed by two coordinate pairs. //
7673 // //
7674 ///////////////////////////////////////////////////////////////////////////////
7675
7676 void tetgenmesh::linelineint(REAL *p1,REAL *p2, REAL *p3, REAL *p4, REAL p[7])
7677 {
7678 REAL p13[3], p43[3], p21[3];
7679 REAL d1343, d4321, d1321, d4343, d2121;
7680 REAL numer, denom;
7681 REAL mua, mub;
7682
7683 p13[0] = p1[0] - p3[0];
7684 p13[1] = p1[1] - p3[1];
7685 p13[2] = p1[2] - p3[2];
7686 p43[0] = p4[0] - p3[0];
7687 p43[1] = p4[1] - p3[1];
7688 p43[2] = p4[2] - p3[2];
7689 if (p43[0] == 0.0 && p43[1] == 0.0 && p43[2] == 0.0) {
7690 p[0] = 0.0;
7691 return;
7692 }
7693
7694 p21[0] = p2[0] - p1[0];
7695 p21[1] = p2[1] - p1[1];
7696 p21[2] = p2[2] - p1[2];
7697 if (p21[0] == 0.0 && p21[1] == 0.0 && p21[2] == 0.0) {
7698 p[0] = 0.0;
7699 return;
7700 }
7701
7702 d1343 = p13[0] * p43[0] + p13[1] * p43[1] + p13[2] * p43[2];
7703 d4321 = p43[0] * p21[0] + p43[1] * p21[1] + p43[2] * p21[2];
7704 d1321 = p13[0] * p21[0] + p13[1] * p21[1] + p13[2] * p21[2];
7705 d4343 = p43[0] * p43[0] + p43[1] * p43[1] + p43[2] * p43[2];
7706 d2121 = p21[0] * p21[0] + p21[1] * p21[1] + p21[2] * p21[2];
7707
7708 denom = d2121 * d4343 - d4321 * d4321;
7709 if (denom == 0.0) {
7710 p[0] = 0.0;
7711 return;
7712 }
7713 numer = d1343 * d4321 - d1321 * d4343;
7714 mua = numer / denom;
7715 mub = (d1343 + d4321 * mua) / d4343;
7716
7717 p[0] = 1.0;
7718 p[1] = p1[0] + mua * p21[0];
7719 p[2] = p1[1] + mua * p21[1];
7720 p[3] = p1[2] + mua * p21[2];
7721 p[4] = p3[0] + mub * p43[0];
7722 p[5] = p3[1] + mub * p43[1];
7723 p[6] = p3[2] + mub * p43[2];
7724 }
7725
7726 ///////////////////////////////////////////////////////////////////////////////
7727 // //
7728 // planelineint() Calculate the intersection of a line and a plane. //
7729 // //
7730 // The equation of a plane (points P are on the plane with normal N and P3 //
7731 // on the plane) can be written as: N dot (P - P3) = 0. The equation of the //
7732 // line (points P on the line passing through P1 and P2) can be written as: //
7733 // P = P1 + u (P2 - P1). The intersection of these two occurs when: //
7734 // N dot (P1 + u (P2 - P1)) = N dot P3. //
7735 // Solving for u gives: //
7736 // N dot (P3 - P1) //
7737 // u = ------------------. //
7738 // N dot (P2 - P1) //
7739 // If the denominator is 0 then N (the normal to the plane) is perpendicular //
7740 // to the line. Thus the line is either parallel to the plane and there are //
7741 // no solutions or the line is on the plane in which case there are an infi- //
7742 // nite number of solutions. //
7743 // //
7744 // The plane is given by three points pa, pb, and pc, e1 and e2 defines the //
7745 // line. If u is non-zero, The intersection point (if exists) returns in ip. //
7746 // //
7747 ///////////////////////////////////////////////////////////////////////////////
7748
7749 void tetgenmesh::planelineint(REAL* pa, REAL* pb, REAL* pc, REAL* e1, REAL* e2,
7750 REAL* ip, REAL* u)
7751 {
7752 REAL n[3], det, det1;
7753
7754 // Calculate N.
7755 facenormal(pa, pb, pc, n, NULL);
7756 // Calculate N dot (e2 - e1).
7757 det = n[0] * (e2[0] - e1[0]) + n[1] * (e2[1] - e1[1])
7758 + n[2] * (e2[2] - e1[2]);
7759 if (det != 0.0) {
7760 // Calculate N dot (pa - e1)
7761 det1 = n[0] * (pa[0] - e1[0]) + n[1] * (pa[1] - e1[1])
7762 + n[2] * (pa[2] - e1[2]);
7763 *u = det1 / det;
7764 ip[0] = e1[0] + *u * (e2[0] - e1[0]);
7765 ip[1] = e1[1] + *u * (e2[1] - e1[1]);
7766 ip[2] = e1[2] + *u * (e2[2] - e1[2]);
7767 } else {
7768 *u = 0.0;
7769 }
7770 }
7771
7772 //
7773 // End of Geometric quantities calculators
7774 //
7775
7776 //
7777 // Begin of memory management routines
7778 //
7779
7780 ///////////////////////////////////////////////////////////////////////////////
7781 // //
7782 // dummyinit() Initialize the tetrahedron that fills "outer space" and //
7783 // the omnipresent subface. //
7784 // //
7785 // The tetrahedron that fills "outer space" called 'dummytet', is pointed to //
7786 // by every tetrahedron and subface on a boundary (be it outer or inner) of //
7787 // the tetrahedralization. Also, 'dummytet' points to one of the tetrahedron //
7788 // on the convex hull(until the holes and concavities are carved), making it //
7789 // possible to find a starting tetrahedron for point location. //
7790 // //
7791 // The omnipresent subface,'dummysh', is pointed to by every tetrahedron or //
7792 // subface that doesn't have a full complement of real subface to point to. //
7793 // //
7794 ///////////////////////////////////////////////////////////////////////////////
7795
7796 void tetgenmesh::dummyinit(int tetwords, int shwords)
7797 {
7798 unsigned long alignptr;
7799
7800 // Set up 'dummytet', the 'tetrahedron' that occupies "outer space".
7801 dummytetbase = (tetrahedron *) new char[tetwords * sizeof(tetrahedron)
7802 + tetrahedrons->alignbytes];
7803 // Align 'dummytet' on a 'tetrahedrons->alignbytes'-byte boundary.
7804 alignptr = (unsigned long) dummytetbase;
7805 dummytet = (tetrahedron *)
7806 (alignptr + (unsigned long) tetrahedrons->alignbytes
7807 - (alignptr % (unsigned long) tetrahedrons->alignbytes));
7808 // Initialize the four adjoining tetrahedra to be "outer space". These
7809 // will eventually be changed by various bonding operations, but their
7810 // values don't really matter, as long as they can legally be
7811 // dereferenced.
7812 dummytet[0] = (tetrahedron) dummytet;
7813 dummytet[1] = (tetrahedron) dummytet;
7814 dummytet[2] = (tetrahedron) dummytet;
7815 dummytet[3] = (tetrahedron) dummytet;
7816 // Four null vertex points.
7817 dummytet[4] = (tetrahedron) NULL;
7818 dummytet[5] = (tetrahedron) NULL;
7819 dummytet[6] = (tetrahedron) NULL;
7820 dummytet[7] = (tetrahedron) NULL;
7821
7822 if (b->useshelles) {
7823 // Set up 'dummysh', the omnipresent "subface" pointed to by any
7824 // tetrahedron side or subface end that isn't attached to a real
7825 // subface.
7826 dummyshbase = (shellface *) new char[shwords * sizeof(shellface)
7827 + subfaces->alignbytes];
7828 // Align 'dummysh' on a 'subfaces->alignbytes'-byte boundary.
7829 alignptr = (unsigned long) dummyshbase;
7830 dummysh = (shellface *)
7831 (alignptr + (unsigned long) subfaces->alignbytes
7832 - (alignptr % (unsigned long) subfaces->alignbytes));
7833 // Initialize the three adjoining subfaces to be the omnipresent
7834 // subface. These will eventually be changed by various bonding
7835 // operations, but their values don't really matter, as long as they
7836 // can legally be dereferenced.
7837 dummysh[0] = (shellface) dummysh;
7838 dummysh[1] = (shellface) dummysh;
7839 dummysh[2] = (shellface) dummysh;
7840 // Three null vertex points.
7841 dummysh[3] = (shellface) NULL;
7842 dummysh[4] = (shellface) NULL;
7843 dummysh[5] = (shellface) NULL;
7844 // Initialize the two adjoining tetrahedra to be "outer space".
7845 dummysh[6] = (shellface) dummytet;
7846 dummysh[7] = (shellface) dummytet;
7847 // Initialize the three adjoining subsegments to be "out boundary".
7848 dummysh[8] = (shellface) dummysh;
7849 dummysh[9] = (shellface) dummysh;
7850 dummysh[10] = (shellface) dummysh;
7851 // Initialize the pointer to badface structure.
7852 dummysh[11] = (shellface) NULL;
7853 // Initialize the four adjoining subfaces of 'dummytet' to be the
7854 // omnipresent subface.
7855 dummytet[8 ] = (tetrahedron) dummysh;
7856 dummytet[9 ] = (tetrahedron) dummysh;
7857 dummytet[10] = (tetrahedron) dummysh;
7858 dummytet[11] = (tetrahedron) dummysh;
7859 }
7860 }
7861
7862 ///////////////////////////////////////////////////////////////////////////////
7863 // //
7864 // initializepools() Calculate the sizes of the point, tetrahedron, and //
7865 // subface. Initialize their memory pools. //
7866 // //
7867 // This routine also computes the indices 'pointmarkindex', 'point2simindex',//
7868 // and 'point2pbcptindex' used to find values within each point; computes //
7869 // indices 'highorderindex', 'elemattribindex', and 'volumeboundindex' used //
7870 // to find values within each tetrahedron. //
7871 // //
7872 // There are two types of boundary elements, which are subfaces and subsegs, //
7873 // they are stored in seperate pools. However, the data structures of them //
7874 // are the same. A subsegment can be regarded as a degenerate subface, i.e.,//
7875 // one of its three corners is not used. We set the apex of it be 'NULL' to //
7876 // distinguish it's a subsegment. //
7877 // //
7878 ///////////////////////////////////////////////////////////////////////////////
7879
7880 void tetgenmesh::initializepools()
7881 {
7882 enum wordtype wtype;
7883 int pointsize, elesize, shsize;
7884
7885 // Default checkpbc = 0;
7886 if ((b->plc || b->refine) && (in->pbcgrouplist != NULL)) {
7887 checkpbcs = 1;
7888 }
7889 // Default varconstraint = 0;
7890 if (in->segmentconstraintlist || in->facetconstraintlist) {
7891 varconstraint = 1;
7892 }
7893
7894 // The index within each point at which its local feature size is found.
7895 // It is saved directly after the list of point attributes.
7896 if (b->bgmesh && (bgm != (tetgenmesh *) NULL)) {
7897 // A background mesh is in use. That point attributes should be the
7898 // same as that of the background mesh.
7899 pointlfsindex = 3 + bgm->in->numberofpointattributes;
7900 } else {
7901 pointlfsindex = 3 + in->numberofpointattributes;
7902 }
7903 // The index within each point at which a element pointer is found, where
7904 // the index is measured in pointers. Ensure the index is aligned to a
7905 // sizeof(tetrahedron)-byte address.
7906 point2simindex = ((pointlfsindex + b->quality) * sizeof(REAL)
7907 + sizeof(tetrahedron) - 1) / sizeof(tetrahedron);
7908 if (b->plc || b->refine) {
7909 // Increase the point size by three pointers, which are:
7910 // - a pointer to a tet, read by point2tet();
7911 // - a pointer to a subface/subsegment , read by point2sh();
7912 // - a pointer to a parent point, read by point2ppt()).
7913 pointsize = (point2simindex + 3) * sizeof(tetrahedron);
7914 if (bgm != (tetgenmesh *) NULL) {
7915 // Increase the size by one pointer to a tet of the background mesh.
7916 pointsize = (point2simindex + 4) * sizeof(tetrahedron);
7917 }
7918 // The index within each point at which a pbc point is found.
7919 point2pbcptindex = (pointsize + sizeof(tetrahedron) - 1)
7920 / sizeof(tetrahedron);
7921 if (checkpbcs) {
7922 // Increase the size by one pointer to a corresponding pbc point,
7923 // read by point2pbcpt().
7924 pointsize = (point2pbcptindex + 1) * sizeof(tetrahedron);
7925 }
7926 } else {
7927 pointsize = point2simindex * sizeof(tetrahedron);
7928 }
7929 // The index within each point at which the boundary marker is found,
7930 // Ensure the point marker is aligned to a sizeof(int)-byte address.
7931 pointmarkindex = (pointsize + sizeof(int) - 1) / sizeof(int);
7932 // Now point size is the ints (inidcated by pointmarkindex) plus:
7933 // - an integer for boundary marker;
7934 // - an integer for vertex type;
7935 pointsize = (pointmarkindex + 2) * sizeof(int);
7936 // Decide the wordtype used in vertex pool.
7937 wtype = (sizeof(REAL) >= sizeof(tetrahedron)) ? FLOATINGPOINT : POINTER;
7938 // Initialize the pool of vertices.
7939 points = new memorypool(pointsize, VERPERBLOCK, wtype, 0);
7940
7941 // The number of bytes occupied by a tetrahedron. There are four pointers
7942 // to other tetrahedra, four pointers to corners, and possibly four
7943 // pointers to subfaces.
7944 elesize = (8 + b->useshelles * 4) * sizeof(tetrahedron);
7945 // The index within each element at which its attributes are found, where
7946 // the index is measured in REALs.
7947 elemattribindex = (elesize + sizeof(REAL) - 1) / sizeof(REAL);
7948 // The index within each element at which the maximum voulme bound is
7949 // found, where the index is measured in REALs. Note that if the
7950 // `b->regionattrib' flag is set, an additional attribute will be added.
7951 volumeboundindex = elemattribindex + in->numberoftetrahedronattributes
7952 + (b->regionattrib > 0);
7953 // If element attributes or an constraint are needed, increase the number
7954 // of bytes occupied by an element.
7955 if (b->varvolume) {
7956 elesize = (volumeboundindex + 1) * sizeof(REAL);
7957 } else if (in->numberoftetrahedronattributes + b->regionattrib > 0) {
7958 elesize = volumeboundindex * sizeof(REAL);
7959 }
7960 // If element neighbor graph is requested (-n switch), an additional
7961 // integer is allocated for each element.
7962 if (b->neighout) {
7963 elemmarkerindex = (elesize + sizeof(int) - 1) / sizeof(int);
7964 elesize = (elemmarkerindex + 1) * sizeof(int);
7965 }
7966 // If -o2 switch is used, an additional pointer pointed to the list of
7967 // higher order nodes is allocated for each element.
7968 if (b->order == 2) {
7969 highorderindex = (elesize + sizeof(tetrahedron) - 1) / sizeof(tetrahedron);
7970 elesize = (highorderindex + 1) * sizeof(tetrahedron);
7971 }
7972 // Having determined the memory size of an element, initialize the pool.
7973 tetrahedrons = new memorypool(elesize, ELEPERBLOCK, POINTER, 8);
7974
7975 if (b->useshelles) {
7976 // The number of bytes occupied by a subface. The list of pointers
7977 // stored in a subface are: three to other subfaces, three to corners,
7978 // three to subsegments, two to tetrahedra, and one to a badface.
7979 shsize = 12 * sizeof(shellface);
7980 // The index within each subface at which the maximum area bound is
7981 // found, where the index is measured in REALs.
7982 areaboundindex = (shsize + sizeof(REAL) - 1) / sizeof(REAL);
7983 // If -q switch is in use, increase the number of bytes occupied by
7984 // a subface for saving maximum area bound.
7985 if (b->quality && varconstraint) {
7986 shsize = (areaboundindex + 1) * sizeof(REAL);
7987 } else {
7988 shsize = areaboundindex * sizeof(REAL);
7989 }
7990 // The index within subface at which the facet marker is found. Ensure
7991 // the marker is aligned to a sizeof(int)-byte address.
7992 shmarkindex = (shsize + sizeof(int) - 1) / sizeof(int);
7993 // Increase the number of bytes by two or three integers, one for facet
7994 // marker, one for shellface type, and optionally one for pbc group.
7995 shsize = (shmarkindex + 2 + checkpbcs) * sizeof(int);
7996 // Initialize the pool of subfaces. Each subface record is eight-byte
7997 // aligned so it has room to store an edge version (from 0 to 5) in
7998 // the least three bits.
7999 subfaces = new memorypool(shsize, SUBPERBLOCK, POINTER, 8);
8000 // Initialize the pool of subsegments. The subsegment's record is same
8001 // with subface.
8002 subsegs = new memorypool(shsize, SUBPERBLOCK, POINTER, 8);
8003 // Initialize the "outer space" tetrahedron and omnipresent subface.
8004 dummyinit(tetrahedrons->itemwords, subfaces->itemwords);
8005 } else {
8006 // Initialize the "outer space" tetrahedron.
8007 dummyinit(tetrahedrons->itemwords, 0);
8008 }
8009 }
8010
8011 ///////////////////////////////////////////////////////////////////////////////
8012 // //
8013 // tetrahedrondealloc() Deallocate space for a tet., marking it dead. //
8014 // //
8015 ///////////////////////////////////////////////////////////////////////////////
8016
8017 void tetgenmesh::tetrahedrondealloc(tetrahedron *dyingtetrahedron)
8018 {
8019 // Set tetrahedron's vertices to NULL. This makes it possible to detect
8020 // dead tetrahedra when traversing the list of all tetrahedra.
8021 dyingtetrahedron[4] = (tetrahedron) NULL;
8022 dyingtetrahedron[5] = (tetrahedron) NULL;
8023 dyingtetrahedron[6] = (tetrahedron) NULL;
8024 dyingtetrahedron[7] = (tetrahedron) NULL;
8025 tetrahedrons->dealloc((void *) dyingtetrahedron);
8026 }
8027
8028 ///////////////////////////////////////////////////////////////////////////////
8029 // //
8030 // tetrahedrontraverse() Traverse the tetrahedra, skipping dead ones. //
8031 // //
8032 ///////////////////////////////////////////////////////////////////////////////
8033
8034 tetgenmesh::tetrahedron* tetgenmesh::tetrahedrontraverse()
8035 {
8036 tetrahedron *newtetrahedron;
8037
8038 do {
8039 newtetrahedron = (tetrahedron *) tetrahedrons->traverse();
8040 if (newtetrahedron == (tetrahedron *) NULL) {
8041 return (tetrahedron *) NULL;
8042 }
8043 } while (newtetrahedron[7] == (tetrahedron) NULL); // Skip dead ones.
8044 return newtetrahedron;
8045 }
8046
8047 ///////////////////////////////////////////////////////////////////////////////
8048 // //
8049 // shellfacedealloc() Deallocate space for a shellface, marking it dead. //
8050 // Used both for dealloc a subface and subsegment. //
8051 // //
8052 ///////////////////////////////////////////////////////////////////////////////
8053
8054 void tetgenmesh::shellfacedealloc(memorypool *pool, shellface *dyingsh)
8055 {
8056 // Set shellface's vertices to NULL. This makes it possible to detect dead
8057 // shellfaces when traversing the list of all shellfaces.
8058 dyingsh[3] = (shellface) NULL;
8059 dyingsh[4] = (shellface) NULL;
8060 dyingsh[5] = (shellface) NULL;
8061 pool->dealloc((void *) dyingsh);
8062 }
8063
8064 ///////////////////////////////////////////////////////////////////////////////
8065 // //
8066 // shellfacetraverse() Traverse the subfaces, skipping dead ones. Used //
8067 // for both subfaces and subsegments pool traverse. //
8068 // //
8069 ///////////////////////////////////////////////////////////////////////////////
8070
8071 tetgenmesh::shellface* tetgenmesh::shellfacetraverse(memorypool *pool)
8072 {
8073 shellface *newshellface;
8074
8075 do {
8076 newshellface = (shellface *) pool->traverse();
8077 if (newshellface == (shellface *) NULL) {
8078 return (shellface *) NULL;
8079 }
8080 } while (newshellface[3] == (shellface) NULL); // Skip dead ones.
8081 return newshellface;
8082 }
8083
8084 ///////////////////////////////////////////////////////////////////////////////
8085 // //
8086 // badfacedealloc() Deallocate space for a badface, marking it dead. //
8087 // //
8088 ///////////////////////////////////////////////////////////////////////////////
8089
8090 void tetgenmesh::badfacedealloc(memorypool *pool, badface *dying)
8091 {
8092 // Set badface's forg to NULL. This makes it possible to detect dead
8093 // ones when traversing the list of all items.
8094 dying->forg = (point) NULL;
8095 pool->dealloc((void *) dying);
8096 }
8097
8098 ///////////////////////////////////////////////////////////////////////////////
8099 // //
8100 // badfacetraverse() Traverse the pools, skipping dead ones. //
8101 // //
8102 ///////////////////////////////////////////////////////////////////////////////
8103
8104 tetgenmesh::badface* tetgenmesh::badfacetraverse(memorypool *pool)
8105 {
8106 badface *newsh;
8107
8108 do {
8109 newsh = (badface *) pool->traverse();
8110 if (newsh == (badface *) NULL) {
8111 return (badface *) NULL;
8112 }
8113 } while (newsh->forg == (point) NULL); // Skip dead ones.
8114 return newsh;
8115 }
8116
8117 ///////////////////////////////////////////////////////////////////////////////
8118 // //
8119 // pointdealloc() Deallocate space for a point, marking it dead. //
8120 // //
8121 ///////////////////////////////////////////////////////////////////////////////
8122
8123 void tetgenmesh::pointdealloc(point dyingpoint)
8124 {
8125 // Mark the point as dead. This makes it possible to detect dead points
8126 // when traversing the list of all points.
8127 setpointtype(dyingpoint, DEADVERTEX);
8128 points->dealloc((void *) dyingpoint);
8129 }
8130
8131 ///////////////////////////////////////////////////////////////////////////////
8132 // //
8133 // pointtraverse() Traverse the points, skipping dead ones. //
8134 // //
8135 ///////////////////////////////////////////////////////////////////////////////
8136
8137 tetgenmesh::point tetgenmesh::pointtraverse()
8138 {
8139 point newpoint;
8140
8141 do {
8142 newpoint = (point) points->traverse();
8143 if (newpoint == (point) NULL) {
8144 return (point) NULL;
8145 }
8146 } while (pointtype(newpoint) == DEADVERTEX); // Skip dead ones.
8147 return newpoint;
8148 }
8149
8150 ///////////////////////////////////////////////////////////////////////////////
8151 // //
8152 // maketetrahedron() Create a new tetrahedron. //
8153 // //
8154 ///////////////////////////////////////////////////////////////////////////////
8155
8156 void tetgenmesh::maketetrahedron(triface *newtet)
8157 {
8158 newtet->tet = (tetrahedron *) tetrahedrons->alloc();
8159 // Initialize the four adjoining tetrahedra to be "outer space".
8160 newtet->tet[0] = (tetrahedron) dummytet;
8161 newtet->tet[1] = (tetrahedron) dummytet;
8162 newtet->tet[2] = (tetrahedron) dummytet;
8163 newtet->tet[3] = (tetrahedron) dummytet;
8164 // Four NULL vertices.
8165 newtet->tet[4] = (tetrahedron) NULL;
8166 newtet->tet[5] = (tetrahedron) NULL;
8167 newtet->tet[6] = (tetrahedron) NULL;
8168 newtet->tet[7] = (tetrahedron) NULL;
8169 // Initialize the four adjoining subfaces to be the omnipresent subface.
8170 if (b->useshelles) {
8171 newtet->tet[8 ] = (tetrahedron) dummysh;
8172 newtet->tet[9 ] = (tetrahedron) dummysh;
8173 newtet->tet[10] = (tetrahedron) dummysh;
8174 newtet->tet[11] = (tetrahedron) dummysh;
8175 }
8176 for (int i = 0; i < in->numberoftetrahedronattributes; i++) {
8177 setelemattribute(newtet->tet, i, 0.0);
8178 }
8179 if (b->varvolume) {
8180 setvolumebound(newtet->tet, -1.0);
8181 }
8182 // Initialize the location and version to be Zero.
8183 newtet->loc = 0;
8184 newtet->ver = 0;
8185 }
8186
8187 ///////////////////////////////////////////////////////////////////////////////
8188 // //
8189 // makeshellface() Create a new shellface with version zero. Used for //
8190 // both subfaces and seusegments. //
8191 // //
8192 ///////////////////////////////////////////////////////////////////////////////
8193
8194 void tetgenmesh::makeshellface(memorypool *pool, face *newface)
8195 {
8196 newface->sh = (shellface *) pool->alloc();
8197 //Initialize the three adjoining subfaces to be the omnipresent subface.
8198 newface->sh[0] = (shellface) dummysh;
8199 newface->sh[1] = (shellface) dummysh;
8200 newface->sh[2] = (shellface) dummysh;
8201 // Three NULL vertices.
8202 newface->sh[3] = (shellface) NULL;
8203 newface->sh[4] = (shellface) NULL;
8204 newface->sh[5] = (shellface) NULL;
8205 // Initialize the two adjoining tetrahedra to be "outer space".
8206 newface->sh[6] = (shellface) dummytet;
8207 newface->sh[7] = (shellface) dummytet;
8208 // Initialize the three adjoining subsegments to be the omnipresent
8209 // subsegments.
8210 newface->sh [8] = (shellface) dummysh;
8211 newface->sh [9] = (shellface) dummysh;
8212 newface->sh[10] = (shellface) dummysh;
8213 // Initialize the pointer to badface structure.
8214 newface->sh[11] = (shellface) NULL;
8215 if (b->quality && varconstraint) {
8216 // Initialize the maximum area bound.
8217 setareabound(*newface, 0.0);
8218 }
8219 // Set the boundary marker to zero.
8220 setshellmark(*newface, 0);
8221 // Set the type.
8222 setshelltype(*newface, NSHARPNSKINNY);
8223 if (checkpbcs) {
8224 // Set the pbcgroup be ivalid.
8225 setshellpbcgroup(*newface, -1);
8226 }
8227 // Initialize the version to be Zero.
8228 newface->shver = 0;
8229 }
8230
8231 ///////////////////////////////////////////////////////////////////////////////
8232 // //
8233 // makepoint() Create a new point. //
8234 // //
8235 ///////////////////////////////////////////////////////////////////////////////
8236
8237 void tetgenmesh::makepoint(point* pnewpoint)
8238 {
8239 int ptmark, i;
8240
8241 *pnewpoint = (point) points->alloc();
8242 // Initialize three coordinates.
8243 (*pnewpoint)[0] = 0.0;
8244 (*pnewpoint)[1] = 0.0;
8245 (*pnewpoint)[2] = 0.0;
8246 // Initialize the list of user-defined attributes.
8247 if (bgm != (tetgenmesh *) NULL) {
8248 for (i = 0; i < bgm->in->numberofpointattributes; i++) {
8249 (*pnewpoint)[3 + i] = 0.0;
8250 }
8251 } else {
8252 for (i = 0; i < in->numberofpointattributes; i++) {
8253 (*pnewpoint)[3 + i] = 0.0;
8254 }
8255 }
8256 if (b->plc || b->refine) {
8257 // Initialize the point-to-simplex filed.
8258 setpoint2tet(*pnewpoint, NULL);
8259 setpoint2sh(*pnewpoint, NULL);
8260 setpoint2ppt(*pnewpoint, NULL);
8261 if (bgm != (tetgenmesh *) NULL) {
8262 setpoint2bgmtet(*pnewpoint, NULL);
8263 }
8264 if (checkpbcs) {
8265 // Initialize the other pointer to its pbc point.
8266 setpoint2pbcpt(*pnewpoint, NULL);
8267 }
8268 }
8269 // Initialize the point marker (starting from in->firstnumber).
8270 ptmark = (int) points->items - (in->firstnumber == 1 ? 0 : 1);
8271 setpointmark(*pnewpoint, ptmark);
8272 // Initialize the point type be UNUSEDVERTEX.
8273 setpointtype(*pnewpoint, UNUSEDVERTEX);
8274 }
8275
8276 //
8277 // End of memory management routines
8278 //
8279
8280 //
8281 // Begin of point location routines
8282 //
8283
8284 ///////////////////////////////////////////////////////////////////////////////
8285 // //
8286 // randomnation() Generate a random number between 0 and 'choices' - 1. //
8287 // //
8288 ///////////////////////////////////////////////////////////////////////////////
8289
8290 unsigned long tetgenmesh::randomnation(unsigned int choices)
8291 {
8292 randomseed = (randomseed * 1366l + 150889l) % 714025l;
8293 return randomseed / (714025l / choices + 1);
8294 }
8295
8296 ///////////////////////////////////////////////////////////////////////////////
8297 // //
8298 // distance2() Returns the square "distance" of a tetrahedron to point p. //
8299 // //
8300 ///////////////////////////////////////////////////////////////////////////////
8301
8302 REAL tetgenmesh::distance2(tetrahedron* tetptr, point p)
8303 {
8304 point p1, p2, p3, p4;
8305 REAL dx, dy, dz;
8306
8307 p1 = (point) tetptr[4];
8308 p2 = (point) tetptr[5];
8309 p3 = (point) tetptr[6];
8310 p4 = (point) tetptr[7];
8311
8312 dx = p[0] - 0.25 * (p1[0] + p2[0] + p3[0] + p4[0]);
8313 dy = p[1] - 0.25 * (p1[1] + p2[1] + p3[1] + p4[1]);
8314 dz = p[2] - 0.25 * (p1[2] + p2[2] + p3[2] + p4[2]);
8315
8316 return dx * dx + dy * dy + dz * dz;
8317 }
8318
8319 ///////////////////////////////////////////////////////////////////////////////
8320 // //
8321 // preciselocate() Find a simplex containing a given point. //
8322 // //
8323 // This routine implements the simple Walk-through point location algorithm. //
8324 // Begins its search from 'searchtet', assume there is a line segment L from //
8325 // a vertex of 'searchtet' to the query point 'searchpt', and simply walk //
8326 // towards 'searchpt' by traversing all faces intersected by L. //
8327 // //
8328 // On completion, 'searchtet' is a tetrahedron that contains 'searchpt'. The //
8329 // returned value indicates one of the following cases: //
8330 // - Returns ONVERTEX if the point lies on an existing vertex. 'searchtet' //
8331 // is a handle whose origin is the existing vertex. //
8332 // - Returns ONEDGE if the point lies on a mesh edge. 'searchtet' is a //
8333 // handle whose primary edge is the edge on which the point lies. //
8334 // - Returns ONFACE if the point lies strictly within a face. 'searchtet' //
8335 // is a handle whose primary face is the face on which the point lies. //
8336 // - Returns INTETRAHEDRON if the point lies strictly in a tetrahededron. //
8337 // 'searchtet' is a handle on the tetrahedron that contains the point. //
8338 // - Returns OUTSIDE if the point lies outside the mesh. 'searchtet' is a //
8339 // handle whose location is the face the point is to 'above' of. //
8340 // //
8341 // WARNING: This routine is designed for convex triangulations, and will not //
8342 // generally work after the holes and concavities have been carved. //
8343 // //
8344 // If 'maxtetnumber' > 0, stop the searching process if the number of passed //
8345 // tets is larger than it and return OUTSIDE. //
8346 // //
8347 ///////////////////////////////////////////////////////////////////////////////
8348
8349 enum tetgenmesh::locateresult tetgenmesh::preciselocate(point searchpt,
8350 triface* searchtet, long maxtetnumber)
8351 {
8352 triface backtracetet;
8353 triface walkthroface;
8354 point forg, fdest, fapex, toppo;
8355 REAL ori1, ori2, ori3, ori4;
8356 long tetnumber;
8357 int side;
8358
8359 if (isdead(searchtet)) searchtet->tet = dummytet;
8360 if (searchtet->tet == dummytet) {
8361 searchtet->loc = 0;
8362 symself(*searchtet);
8363 }
8364 // 'searchtet' should be a valid tetrahedron now.
8365 #ifdef SELF_CHECK
8366 assert(!isdead(searchtet) && (searchtet->tet != dummytet));
8367 #endif
8368
8369 searchtet->ver = 0; // Keep in CCW edge ring.
8370 // Find a face of 'searchtet' such that the 'searchpt' lies strictly
8371 // above it. Such face should always exist.
8372 for (searchtet->loc = 0; searchtet->loc < 4; searchtet->loc++) {
8373 forg = org(*searchtet);
8374 fdest = dest(*searchtet);
8375 fapex = apex(*searchtet);
8376 ori1 = orient3d(forg, fdest, fapex, searchpt);
8377 if (ori1 < 0.0) break;
8378 }
8379 #ifdef SELF_CHECK
8380 assert(searchtet->loc < 4);
8381 #endif
8382
8383 // Define 'tetnumber' for exit the loop when it's running endless.
8384 tetnumber = 0l;
8385 while ((maxtetnumber > 0l) && (tetnumber <= maxtetnumber)) {
8386 // Check if we are reaching the boundary of the triangulation.
8387 if (searchtet->tet == dummytet) {
8388 *searchtet = backtracetet;
8389 return OUTSIDE;
8390 }
8391 // Initialize the face for returning the walk-through face.
8392 walkthroface.tet = (tetrahedron *) NULL;
8393 // Adjust the edge ring, so that 'ori1 < 0.0' holds.
8394 searchtet->ver = 0;
8395 // 'toppo' remains unchange for the following orientation tests.
8396 toppo = oppo(*searchtet);
8397 // Check the three sides of 'searchtet' to find the face through which
8398 // we can walk next.
8399 for (side = 0; side < 3; side++) {
8400 forg = org(*searchtet);
8401 fdest = dest(*searchtet);
8402 ori2 = orient3d(forg, fdest, toppo, searchpt);
8403 if (ori2 == 0.0) {
8404 // They are coplanar, check if 'searchpt' lies inside, or on an edge,
8405 // or coindice with a vertex of face (forg, fdest, toppo).
8406 fapex = apex(*searchtet);
8407 ori3 = orient3d(fdest, fapex, toppo, searchpt);
8408 if (ori3 < 0.0) {
8409 // Outside the face (fdest, fapex, toppo), walk through it.
8410 enextself(*searchtet);
8411 fnext(*searchtet, walkthroface);
8412 break;
8413 }
8414 ori4 = orient3d(fapex, forg, toppo, searchpt);
8415 if (ori4 < 0.0) {
8416 // Outside the face (fapex, forg, toppo), walk through it.
8417 enext2self(*searchtet);
8418 fnext(*searchtet, walkthroface);
8419 break;
8420 }
8421 // Remember, ori1 < 0.0, which means 'searchpt' will not on edge
8422 // (forg, fdest) or on vertex forg or fdest.
8423 #ifdef SELF_CHECK
8424 assert(ori1 < 0.0);
8425 #endif
8426 // The rest possible cases are:
8427 // (1) 'searchpt' lies on edge (fdest, toppo);
8428 // (2) 'searchpt' lies on edge (toppo, forg);
8429 // (3) 'searchpt' coincident with toppo;
8430 // (4) 'searchpt' lies inside face (forg, fdest, toppo).
8431 fnextself(*searchtet);
8432 if (ori3 == 0.0) {
8433 if (ori4 == 0.0) {
8434 // Case (4).
8435 enext2self(*searchtet);
8436 return ONVERTEX;
8437 } else {
8438 // Case (1).
8439 enextself(*searchtet);
8440 return ONEDGE;
8441 }
8442 }
8443 if (ori4 == 0.0) {
8444 // Case (2).
8445 enext2self(*searchtet);
8446 return ONEDGE;
8447 }
8448 // Case (4).
8449 return ONFACE;
8450 } else if (ori2 < 0.0) {
8451 // Outside the face (forg, fdest, toppo), walk through it.
8452 fnext(*searchtet, walkthroface);
8453 break;
8454 }
8455 // Go to check next side.
8456 enextself(*searchtet);
8457 }
8458 if (side >= 3) {
8459 // Found! Inside tetrahedron.
8460 return INTETRAHEDRON;
8461 }
8462 // We walk through the face 'walkthroface' and continue the searching.
8463 #ifdef SELF_CHECK
8464 assert(walkthroface.tet != (tetrahedron *) NULL);
8465 #endif
8466 // Store the face handle in 'backtracetet' before we take the real walk.
8467 // So we are able to restore the handle to 'searchtet' if we are
8468 // reaching the outer boundary.
8469 backtracetet = walkthroface;
8470 sym(walkthroface, *searchtet);
8471 tetnumber++;
8472 }
8473
8474 // Should never be here.
8475 // printf("Internal error in preciselocate(): Point location failed.\n");
8476 // internalerror();
8477 return OUTSIDE;
8478 }
8479
8480 ///////////////////////////////////////////////////////////////////////////////
8481 // //
8482 // locate() Find a simplex containing a given point. //
8483 // //
8484 // This routine implements Muecke's Jump-and-walk point location algorithm. //
8485 // It improves the simple walk-through by "jumping" to a good starting point //
8486 // via random sampling. Searching begins from one of handles: the input //
8487 // 'searchtet', a recently encountered tetrahedron 'recenttet', or from one //
8488 // chosen from a random sample. The choice is made by determining which one //
8489 // 's barycenter is closest to the point we are searcing for. Having chosen //
8490 // the starting tetrahedron, the simple Walk-through algorithm is used to do //
8491 // the real walking. //
8492 // //
8493 // The return value indicates the location of the 'searchpt' (INTETRAHEDRON, //
8494 // or ONFACE, ...). 'searchtet' is adjusted to a tetrahedron corresponding //
8495 // to that value. See the introduction part of preciselocate() for detail. //
8496 // //
8497 // WARNING: This routine is designed for convex triangulations, and will not //
8498 // generally work after the holes and concavities have been carved. //
8499 // //
8500 ///////////////////////////////////////////////////////////////////////////////
8501
8502 enum tetgenmesh::locateresult tetgenmesh::
8503 locate(point searchpt, triface *searchtet)
8504 {
8505 tetrahedron *firsttet, *tetptr;
8506 void **sampleblock;
8507 long sampleblocks, samplesperblock, samplenum;
8508 long tetblocks, i, j;
8509 unsigned long alignptr;
8510 REAL searchdist, dist;
8511
8512 // 'searchtet' should be a valid tetrahedron.
8513 if (isdead(searchtet)) {
8514 searchtet->tet = dummytet;
8515 }
8516 if (searchtet->tet == dummytet) {
8517 // This is an 'Outer Space' handle, get a hull tetrahedron.
8518 searchtet->loc = 0;
8519 symself(*searchtet);
8520 }
8521 #ifdef SELF_CHECK
8522 assert(!isdead(searchtet));
8523 #endif
8524
8525 // Get the distance from the suggested starting tet to the point we seek.
8526 searchdist = distance2(searchtet->tet, searchpt);
8527
8528 // If a recently encountered tetrahedron has been recorded and has not
8529 // been deallocated, test it as a good starting point.
8530 if (!isdead(&recenttet) && (recenttet.tet != searchtet->tet)) {
8531 dist = distance2(recenttet.tet, searchpt);
8532 if (dist < searchdist) {
8533 *searchtet = recenttet;
8534 searchdist = dist;
8535 }
8536 }
8537
8538 // Select "good" candidate using k random samples, taking the closest one.
8539 // The number of random samples taken is proportional to the fourth root
8540 // of the number of tetrahedra in the mesh. The next bit of code assumes
8541 // that the number of tetrahedra increases monotonically.
8542 while (SAMPLEFACTOR * samples * samples * samples * samples <
8543 tetrahedrons->items) {
8544 samples++;
8545 }
8546 // Find how much blocks in current tet pool.
8547 tetblocks = (tetrahedrons->maxitems + ELEPERBLOCK - 1) / ELEPERBLOCK;
8548 // Find the average samles per block. Each block at least have 1 sample.
8549 samplesperblock = 1 + (samples / tetblocks);
8550 sampleblocks = samples / samplesperblock;
8551 sampleblock = tetrahedrons->firstblock;
8552 for (i = 0; i < sampleblocks; i++) {
8553 alignptr = (unsigned long) (sampleblock + 1);
8554 firsttet = (tetrahedron *)
8555 (alignptr + (unsigned long) tetrahedrons->alignbytes
8556 - (alignptr % (unsigned long) tetrahedrons->alignbytes));
8557 for (j = 0; j < samplesperblock; j++) {
8558 if (i == tetblocks - 1) {
8559 // This is the last block.
8560 samplenum = randomnation((int)
8561 (tetrahedrons->maxitems - (i * ELEPERBLOCK)));
8562 } else {
8563 samplenum = randomnation(ELEPERBLOCK);
8564 }
8565 tetptr = (tetrahedron *)
8566 (firsttet + (samplenum * tetrahedrons->itemwords));
8567 if (tetptr[4] != (tetrahedron) NULL) {
8568 dist = distance2(tetptr, searchpt);
8569 if (dist < searchdist) {
8570 searchtet->tet = tetptr;
8571 searchdist = dist;
8572 }
8573 }
8574 }
8575 sampleblock = (void **) *sampleblock;
8576 }
8577
8578 // Call simple walk-through to locate the point.
8579 return preciselocate(searchpt, searchtet, tetrahedrons->items);
8580 }
8581
8582 ///////////////////////////////////////////////////////////////////////////////
8583 // //
8584 // adjustlocate() Adjust the precise location of a vertex. //
8585 // //
8586 // 'precise' is the value returned from preciselocate(). It indicates the //
8587 // exact location of the point 'searchpt' with respect to the tetrahedron //
8588 // 'searchtet'. 'epspp' is a given relative tolerance. //
8589 // //
8590 // This routine re-evaluates the orientations of searchpt with respect to //
8591 // the four sides of searchtet. Detects the coplanarities by additinal tests //
8592 // which are based on the given tolerance. If 'precise' is ONFACE or ONEDGE, //
8593 // we can save one or two orientation tests. //
8594 // //
8595 // The return value indicates the location of the 'searchpt' (INTETRAHEDRON, //
8596 // or ONFACE, ...). 'searchtet' is adjusted to a tetrahedron corresponding //
8597 // to that value. See the introduction part of preciselocate() for detail. //
8598 // //
8599 // WARNING: This routine detect degenerate case using relative tolerance. //
8600 // It is better used after locate() or preciselocate(). For general inputs, //
8601 // it may not able to tell the correct location. //
8602 // //
8603 ///////////////////////////////////////////////////////////////////////////////
8604
8605 enum tetgenmesh::locateresult tetgenmesh::
8606 adjustlocate(point searchpt, triface* searchtet, enum locateresult precise,
8607 REAL epspp)
8608 {
8609 point torg, tdest, tapex, toppo;
8610 REAL s1, s2, s3, s4;
8611
8612 // For the given 'searchtet', the orientations tests are:
8613 // s1: (tdest, torg, tapex, searchpt);
8614 // s2: (torg, tdest, toppo, searchpt);
8615 // s3: (tdest, tapex, toppo, searchpt);
8616 // s4: (tapex, torg, toppo, searchpt);
8617 adjustedgering(*searchtet, CCW);
8618 torg = org(*searchtet);
8619 tdest = dest(*searchtet);
8620 tapex = apex(*searchtet);
8621 toppo = oppo(*searchtet);
8622
8623 switch (precise) {
8624 case ONVERTEX:
8625 // This case we don't need do any further test.
8626 return ONVERTEX;
8627 case ONEDGE:
8628 // (torg, tdest);
8629 s1 = 0.0;
8630 s2 = 0.0;
8631 break;
8632 case ONFACE:
8633 // (tdest, torg, tapex);
8634 s1 = 0.0;
8635 s2 = orient3d(torg, tdest, toppo, searchpt);
8636 break;
8637 default: // INTETRAHEDRON or OUTSIDE
8638 s1 = orient3d(tdest, torg, tapex, searchpt);
8639 s2 = orient3d(torg, tdest, toppo, searchpt);
8640 }
8641
8642 if (s1 != 0.0) {
8643 if (iscoplanar(tdest, torg, tapex, searchpt, s1, epspp)) {
8644 s1 = 0.0;
8645 }
8646 }
8647 if (s1 < 0.0) {
8648 return OUTSIDE;
8649 }
8650
8651 if (s2 != 0.0) {
8652 if (iscoplanar(torg, tdest, toppo, searchpt, s2, epspp)) {
8653 s2 = 0.0;
8654 }
8655 }
8656 if (s2 < 0.0) {
8657 fnextself(*searchtet);
8658 return OUTSIDE;
8659 }
8660
8661 s3 = orient3d(tdest, tapex, toppo, searchpt);
8662 if (s3 != 0.0) {
8663 if (iscoplanar(tdest, tapex, toppo, searchpt, s3, epspp)) {
8664 s3 = 0.0;
8665 }
8666 }
8667 if (s3 < 0.0) {
8668 enextfnextself(*searchtet);
8669 return OUTSIDE;
8670 }
8671
8672 s4 = orient3d(tapex, torg, toppo, searchpt);
8673 if (s4 != 0.0) {
8674 if (iscoplanar(tapex, torg, toppo, searchpt, s4, epspp)) {
8675 s4 = 0.0;
8676 }
8677 }
8678 if (s4 < 0.0) {
8679 enext2fnextself(*searchtet);
8680 return OUTSIDE;
8681 }
8682
8683 // Determine degenerate cases.
8684 if (s1 == 0.0) {
8685 if (s2 == 0.0) {
8686 if (s3 == 0.0) {
8687 // On tdest.
8688 enextself(*searchtet);
8689 return ONVERTEX;
8690 }
8691 if (s4 == 0.0) {
8692 // On torg.
8693 return ONVERTEX;
8694 }
8695 // On edge (torg, tdest).
8696 return ONEDGE;
8697 }
8698 if (s3 == 0.0) {
8699 if (s4 == 0.0) {
8700 // On tapex.
8701 enext2self(*searchtet);
8702 return ONVERTEX;
8703 }
8704 // On edge (tdest, tapex).
8705 enextself(*searchtet);
8706 return ONEDGE;
8707 }
8708 if (s4 == 0.0) {
8709 // On edge (tapex, torg).
8710 enext2self(*searchtet);
8711 return ONEDGE;
8712 }
8713 // On face (torg, tdest, tapex).
8714 return ONFACE;
8715 }
8716 if (s2 == 0.0) {
8717 fnextself(*searchtet);
8718 if (s3 == 0.0) {
8719 if (s4 == 0.0) {
8720 // On toppo.
8721 enext2self(*searchtet);
8722 return ONVERTEX;
8723 }
8724 // On edge (tdest, toppo).
8725 enextself(*searchtet);
8726 return ONEDGE;
8727 }
8728 if (s4 == 0.0) {
8729 // On edge (toppo, torg).
8730 enext2self(*searchtet);
8731 return ONEDGE;
8732 }
8733 // On face (torg, tdest, toppo).
8734 return ONFACE;
8735 }
8736 if (s3 == 0.0) {
8737 enextfnextself(*searchtet);
8738 if (s4 == 0.0) {
8739 // On edge (tapex, toppo).
8740 enextself(*searchtet);
8741 return ONEDGE;
8742 }
8743 // On face (tdest, tapex, toppo).
8744 return ONFACE;
8745 }
8746 if (s4 == 0.0) {
8747 enext2fnextself(*searchtet);
8748 // On face (tapex, torg, toppo).
8749 return ONFACE;
8750 }
8751
8752 // Inside tetrahedron.
8753 return INTETRAHEDRON;
8754 }
8755
8756 ///////////////////////////////////////////////////////////////////////////////
8757 // //
8758 // locatesub() Find a point in the surface mesh of a facet. //
8759 // //
8760 // Searching begins from the input 'searchsh', it should be a handle on the //
8761 // convex hull of the facet triangulation. //
8762 // //
8763 // If 'stopatseg' is nonzero, the search will stop if it tries to walk //
8764 // through a subsegment, and will return OUTSIDE. //
8765 // //
8766 // On completion, 'searchsh' is a subface that contains 'searchpt'. //
8767 // - Returns ONVERTEX if the point lies on an existing vertex. 'searchsh' //
8768 // is a handle whose origin is the existing vertex. //
8769 // - Returns ONEDGE if the point lies on a mesh edge. 'searchsh' is a //
8770 // handle whose primary edge is the edge on which the point lies. //
8771 // - Returns ONFACE if the point lies strictly within a subface. //
8772 // 'searchsh' is a handle on which the point lies. //
8773 // - Returns OUTSIDE if the point lies outside the triangulation. //
8774 // //
8775 // WARNING: This routine is designed for convex triangulations, and will not //
8776 // not generally work after the holes and concavities have been carved. //
8777 // //
8778 ///////////////////////////////////////////////////////////////////////////////
8779
8780 enum tetgenmesh::locateresult tetgenmesh::locatesub(point searchpt,
8781 face* searchsh, int stopatseg, REAL epspp)
8782 {
8783 face backtracksh, spinsh, checkedge;
8784 point forg, fdest, fapex;
8785 REAL orgori, destori;
8786 REAL ori, sign;
8787 int moveleft, i;
8788
8789 if (searchsh->sh == dummysh) {
8790 searchsh->shver = 0;
8791 spivotself(*searchsh);
8792 #ifdef SELF_CHECK
8793 assert(searchsh->sh != dummysh);
8794 #endif
8795 }
8796 // Find the sign to simulate that abovepoint is 'above' the facet.
8797 adjustedgering(*searchsh, CCW);
8798 forg = sorg(*searchsh);
8799 fdest = sdest(*searchsh);
8800 fapex = sapex(*searchsh);
8801 ori = orient3d(forg, fdest, fapex, abovepoint);
8802 sign = ori > 0.0 ? -1 : 1;
8803
8804 // Orient 'searchsh' so that 'searchpt' is below it (i.e., searchpt has
8805 // CCW orientation with respect to searchsh in plane). Such edge
8806 // should always exist. Save it as (forg, fdest).
8807 for (i = 0; i < 3; i++) {
8808 forg = sorg(*searchsh);
8809 fdest = sdest(*searchsh);
8810 ori = orient3d(forg, fdest, abovepoint, searchpt) * sign;
8811 if (ori > 0.0) break;
8812 senextself(*searchsh);
8813 }
8814 #ifdef SELF_CHECK
8815 assert(i < 3);
8816 #endif
8817
8818 while (1) {
8819 fapex = sapex(*searchsh);
8820 // Check whether the apex is the point we seek.
8821 if (fapex[0] == searchpt[0] && fapex[1] == searchpt[1] &&
8822 fapex[2] == searchpt[2]) {
8823 senext2self(*searchsh);
8824 return ONVERTEX;
8825 }
8826 // Does the point lie on the other side of the line defined by the
8827 // triangle edge opposite the triangle's destination?
8828 destori = orient3d(forg, fapex, abovepoint, searchpt) * sign;
8829 if (epspp > 0.0) {
8830 if (iscoplanar(forg, fapex, abovepoint, searchpt, destori, epspp)) {
8831 destori = 0.0;
8832 }
8833 }
8834 // Does the point lie on the other side of the line defined by the
8835 // triangle edge opposite the triangle's origin?
8836 orgori = orient3d(fapex, fdest, abovepoint, searchpt) * sign;
8837 if (epspp > 0.0) {
8838 if (iscoplanar(fapex, fdest, abovepoint, searchpt, orgori, epspp)) {
8839 orgori = 0.0;
8840 }
8841 }
8842 if (destori > 0.0) {
8843 moveleft = 1;
8844 } else {
8845 if (orgori > 0.0) {
8846 moveleft = 0;
8847 } else {
8848 // The point must be on the boundary of or inside this triangle.
8849 if (destori == 0.0) {
8850 senext2self(*searchsh);
8851 return ONEDGE;
8852 }
8853 if (orgori == 0.0) {
8854 senextself(*searchsh);
8855 return ONEDGE;
8856 }
8857 return ONFACE;
8858 }
8859 }
8860 // Move to another triangle. Leave a trace `backtracksh' in case
8861 // walking off a boundary of the triangulation.
8862 if (moveleft) {
8863 senext2(*searchsh, backtracksh);
8864 fdest = fapex;
8865 } else {
8866 senext(*searchsh, backtracksh);
8867 forg = fapex;
8868 }
8869 // Check if we meet a segment.
8870 sspivot(backtracksh, checkedge);
8871 if (checkedge.sh != dummysh) {
8872 if (stopatseg) {
8873 // The flag indicates we should not cross a segment. Stop.
8874 *searchsh = backtracksh;
8875 return OUTSIDE;
8876 }
8877 // Try to walk through a segment. We need to find a coplanar subface
8878 // sharing this segment to get into.
8879 spinsh = backtracksh;
8880 do {
8881 spivotself(spinsh);
8882 if (spinsh.sh == backtracksh.sh) {
8883 // Turn back, no coplanar subface is found.
8884 break;
8885 }
8886 // Are they belong to the same facet.
8887 if (shellmark(spinsh) == shellmark(backtracksh)) {
8888 // Find a coplanar subface. Walk into it.
8889 *searchsh = spinsh;
8890 break;
8891 }
8892 // Are they (nearly) coplanar?
8893 ori = orient3d(forg, fdest, sapex(backtracksh), sapex(spinsh));
8894 if (iscoplanar(forg, fdest, sapex(backtracksh), sapex(spinsh), ori,
8895 b->epsilon)) {
8896 // Find a coplanar subface. Walk into it.
8897 *searchsh = spinsh;
8898 break;
8899 }
8900 } while (spinsh.sh != backtracksh.sh);
8901 } else {
8902 spivot(backtracksh, *searchsh);
8903 }
8904 // Check for walking right out of the triangulation.
8905 if ((searchsh->sh == dummysh) || (searchsh->sh == backtracksh.sh)) {
8906 // Go back to the last triangle.
8907 *searchsh = backtracksh;
8908 return OUTSIDE;
8909 }
8910 // To keep the same orientation wrt abovepoint.
8911 if (sorg(*searchsh) != forg) sesymself(*searchsh);
8912 #ifdef SELF_CHECK
8913 assert((sorg(*searchsh) == forg) && (sdest(*searchsh) == fdest));
8914 #endif
8915 }
8916 }
8917
8918 ///////////////////////////////////////////////////////////////////////////////
8919 // //
8920 // adjustlocatesub() Adjust the precise location of a vertex. //
8921 // //
8922 // 'precise' is the precise location (returned from locatesub()) of 'searcht'//
8923 // with respect to 'searchsh'. 'epspp' is the given relative tolerance. //
8924 // //
8925 // This routine re-evaluates the orientations of 'searchpt' with respect to //
8926 // the three edges of 'searchsh'. Detects the collinearities by additinal //
8927 // tests based on the given tolerance. If 'precise' is ONEDGE, one can save //
8928 // one orientation test for the current edge of 'searchsh'. //
8929 // //
8930 // On completion, 'searchsh' is a subface contains 'searchpt'. The returned //
8931 // value indicates one of the following cases: //
8932 // - Returns ONVERTEX if the point lies on an existing vertex. 'searchsh' //
8933 // is a handle whose origin is the existing vertex. //
8934 // - Returns ONEDGE if the point lies on a mesh edge. 'searchsh' is a //
8935 // handle whose primary edge is the edge on which the point lies. //
8936 // - Returns ONFACE if the point lies strictly within a subface. //
8937 // 'searchsh' is a handle on which the point lies. //
8938 // - Returns OUTSIDE if the point lies outside 'searchsh'. //
8939 // //
8940 ///////////////////////////////////////////////////////////////////////////////
8941
8942 enum tetgenmesh::locateresult tetgenmesh::
8943 adjustlocatesub(point searchpt, face* searchsh, enum locateresult precise,
8944 REAL epspp)
8945 {
8946 point pa, pb, pc;
8947 bool s1, s2, s3;
8948
8949 pa = sorg(*searchsh);
8950 pb = sdest(*searchsh);
8951 pc = sapex(*searchsh);
8952
8953 if (precise == ONEDGE) {
8954 s1 = true;
8955 } else {
8956 s1 = iscollinear(pa, pb, searchpt, epspp);
8957 }
8958 s2 = iscollinear(pb, pc, searchpt, epspp);
8959 s3 = iscollinear(pc, pa, searchpt, epspp);
8960 if (s1) {
8961 if (s2) {
8962 // on vertex pb.
8963 #ifdef SELF_CHECK
8964 assert(!s3);
8965 #endif
8966 senextself(*searchsh);
8967 return ONVERTEX;
8968 } else if (s3) {
8969 // on vertex pa.
8970 return ONVERTEX;
8971 } else {
8972 // on edge pa->pb.
8973 return ONEDGE;
8974 }
8975 } else if (s2) {
8976 if (s3) {
8977 // on vertex pc.
8978 senext2self(*searchsh);
8979 return ONVERTEX;
8980 } else {
8981 // on edge pb->pc.
8982 senextself(*searchsh);
8983 return ONEDGE;
8984 }
8985 } else if (s3) {
8986 // on edge pc->pa.
8987 senext2self(*searchsh);
8988 return ONEDGE;
8989 } else {
8990 return precise;
8991 }
8992 }
8993
8994 ///////////////////////////////////////////////////////////////////////////////
8995 // //
8996 // locateseg() Find a point in subsegments. //
8997 // //
8998 // Searching begins from the input 'searchseg', it should be a subsegment of //
8999 // the whole segment. //
9000 // //
9001 // On completion, 'searchseg' is a subsegment that contains 'searchpt'. //
9002 // - Returns ONVERTEX if the point lies on an existing vertex. 'searchseg' //
9003 // is a handle whose origin is the existing vertex. //
9004 // - Returns ONEDGE if the point lies inside 'searchseg'. //
9005 // - Returns OUTSIDE if the point lies outside the segment. //
9006 // //
9007 ///////////////////////////////////////////////////////////////////////////////
9008
9009 enum tetgenmesh::locateresult tetgenmesh::
9010 locateseg(point searchpt, face* searchseg)
9011 {
9012 face backtraceseg;
9013 point pa, pb;
9014 REAL dx, dy, dz;
9015 int moveleft;
9016 int i;
9017
9018 moveleft = 0;
9019 while (1) {
9020 searchseg->shver = 0;
9021 pa = sorg(*searchseg);
9022 pb = sdest(*searchseg);
9023 // Find the biggest difference in x, y, and z coordinates of a and b.
9024 dx = fabs(pb[0] - pa[0]);
9025 dy = fabs(pb[1] - pa[1]);
9026 dz = fabs(pb[2] - pa[2]);
9027 if (dx > dy) {
9028 if (dx > dz) {
9029 i = 0;
9030 } else {
9031 i = 2;
9032 }
9033 } else {
9034 if (dy > dz) {
9035 i = 1;
9036 } else {
9037 i = 2;
9038 }
9039 }
9040 if (pa[i] < pb[i]) {
9041 if (searchpt[i] < pa[i]) {
9042 moveleft = 1;
9043 } else if (searchpt[i] > pa[i]) {
9044 if (searchpt[i] < pb[i]) {
9045 return ONEDGE;
9046 } else if (searchpt[i] > pb[i]) {
9047 moveleft = 0;
9048 } else {
9049 #ifdef SELF_CHECK
9050 assert(searchpt[i] == pb[i]);
9051 #endif
9052 sesymself(*searchseg);
9053 return ONVERTEX;
9054 }
9055 } else {
9056 #ifdef SELF_CHECK
9057 assert(searchpt[i] == pa[i]);
9058 #endif
9059 return ONVERTEX;
9060 }
9061 } else if (pa[i] > pb[i]) {
9062 if (searchpt[i] < pb[i]) {
9063 moveleft = 0;
9064 } else if (searchpt[i] > pb[i]) {
9065 if (searchpt[i] < pa[i]) {
9066 return ONEDGE;
9067 } else if (searchpt[i] > pa[i]) {
9068 moveleft = 1;
9069 } else {
9070 #ifdef SELF_CHECK
9071 assert(searchpt[i] == pa[i]);
9072 #endif
9073 return ONVERTEX;
9074 }
9075 } else {
9076 #ifdef SELF_CHECK
9077 assert(searchpt[i] == pb[i]);
9078 #endif
9079 sesymself(*searchseg);
9080 return ONVERTEX;
9081 }
9082 }
9083 backtraceseg = *searchseg;
9084 if (moveleft) {
9085 senext2self(*searchseg);
9086 } else {
9087 senextself(*searchseg);
9088 }
9089 spivotself(*searchseg);
9090 if (searchseg->sh == dummysh) {
9091 *searchseg = backtraceseg;
9092 break;
9093 }
9094 }
9095
9096 return OUTSIDE;
9097 }
9098
9099 ///////////////////////////////////////////////////////////////////////////////
9100 // //
9101 // adjustlocateseg() Adjust the precise location of a vertex on segment. //
9102 // //
9103 // 'searchpt' is either inside or ouside the segment 'searchseg'. It will be //
9104 // adjusted to on vertex if it is very close to an endpoint of 'searchseg'. //
9105 // 'epspp' is the given relative tolerance. //
9106 // //
9107 ///////////////////////////////////////////////////////////////////////////////
9108
9109 enum tetgenmesh::locateresult tetgenmesh::
9110 adjustlocateseg(point searchpt, face* searchseg, enum locateresult precise,
9111 REAL epspp)
9112 {
9113 point pa, pb;
9114 REAL L, d, r;
9115
9116 pa = sorg(*searchseg);
9117 pb = sdest(*searchseg);
9118 L = distance(pa, pb);
9119
9120 // Is searchpt approximate to pa?
9121 d = distance(pa, searchpt);
9122 r = d / L;
9123 if (r <= epspp) {
9124 return ONVERTEX;
9125 }
9126 // Is searchpt approximate to pb?
9127 d = distance(pb, searchpt);
9128 r = d / L;
9129 if (r <= epspp) {
9130 sesymself(*searchseg);
9131 return ONVERTEX;
9132 }
9133
9134 return precise;
9135 }
9136
9137 //
9138 // End of point location routines
9139 //
9140
9141 //
9142 // Begin of mesh transformation routines
9143 //
9144
9145 ///////////////////////////////////////////////////////////////////////////////
9146 // //
9147 // Flip operations //
9148 // //
9149 // If abc is a hull face, it is unflipable, and is locally Delaunay. In the //
9150 // following, we assume abc is an interior face, and the other tetrahedron //
9151 // adjoining at abc is bace. //
9152 // //
9153 // If the convex hull CH of the set {a, b, c, d, e} only has four vertices, //
9154 // i.e., one vertex lies inside CH, then abc is unflipable, and is locally //
9155 // Delaunay. If CH is the vertex set itself, we have the following cases to //
9156 // determine whether abc is flipable or not. //
9157 // //
9158 // If no four points of {a, b, c, d, e} are coplanar, a 2-to-3 flip can be //
9159 // applied to abc if the edge de crosses the triangle abc; a 3-to-2 flip can //
9160 // be applied to abc if ab crosses cde, and abde exists, otherwise, face abc //
9161 // is unflipable, i.e., the tetrahedron abde is not present. //
9162 // //
9163 // If four points of {a, b, c, d, e} are coplanar (two faces are coplanar). //
9164 // Assume faces abd and abe are coplanar (it is impossible be abc). If a, b, //
9165 // d, e form a non-convex quadrilateral, then abc is unflipable, furthermore,//
9166 // it is locally Delaunay. Assume they are convex quadrilateral, if abd and //
9167 // abe are hull faces, a 2-to-2 flip can be applied to abc; if abd and abe //
9168 // are interior faces, assume two tetrahedra adjoining abd and abe at the //
9169 // opposite sides are abdg and abef, respectively. If g = f, a 4-to-4 flip //
9170 // can be applied to abc, otherwise, abc is unflipable. //
9171 // //
9172 // There are other cases which can cause abc unflipable. If abc is a subface,//
9173 // a 2-to-3 flip is forbidden; if ab is a subsegment, flips 3-to-2, 2-to-2, //
9174 // and 4-to-4 are forbidden. //
9175 // //
9176 ///////////////////////////////////////////////////////////////////////////////
9177
9178 ///////////////////////////////////////////////////////////////////////////////
9179 // //
9180 // categorizeface() Determine the flip type of a given face. //
9181 // //
9182 // On input, 'horiz' represents the face we want to flip (you can imagine it //
9183 // is parallel to the horizon). Let the tetrahedron above it be abcd, where //
9184 // abc is 'horiz'. //
9185 // //
9186 // This routine determines the suitable type of flip operation for 'horiz'. //
9187 // - Returns T23 if a 2-to-3 flip is applicable. 'horiz' is same as input. //
9188 // - Returns T32 if a 3-to-2 flip is applicable. 'horiz' is adjusted so //
9189 // that the primary edge of 'horiz' is the flipable edge. //
9190 // - Returns T22 if a 2-to-2 or 4-to-4 flip is applicable. 'horiz' is //
9191 // adjusted so that the primary edge of 'horiz' is the flipable edge. //
9192 // - Returns FORBIDDENFACE indicates although a 2-to-3 flip is applicable, //
9193 // but it is a subface and should not be flipped away. //
9194 // - Returns FORBIDDENEDGE indicates although a 3-to-2, or 2-to-2, or //
9195 // 4-to-4 flip is applicable, but the flipable edge is a subsegment and //
9196 // should not be flipped away. 'horiz' is adjusted so that the primary //
9197 // edge of 'horiz' is the flipable edge. //
9198 // - Returns UNFLIPABLE indicates it is unflipable due to the absence of //
9199 // a tetrahedron. 'horiz' is adjusted so that the primary edge of 'horiz'//
9200 // is the unflipable edge. Possibly, It is a subsegment. //
9201 // - Returns NONCONVEX indicates it is unflipable and is locally Delaunay. //
9202 // //
9203 // Given a face abc, with two adjoining tetrahedra abcd and bace. If abc is //
9204 // flipable, i.e., T23, T32, T22 or T44, its flip type can be determined by //
9205 // doing five orientation tests: two tests for determining that d, e lie on //
9206 // the different sides of abc, three tests for determining if the edge de //
9207 // intersects the face abc. However, if we use the neighbor information of //
9208 // the mesh data structure, we can reduce the five orientation tests to at //
9209 // most three tests, that is, the two tests for determining whether d and e //
9210 // lie on the different sides of abc can be saved. //
9211 // //
9212 ///////////////////////////////////////////////////////////////////////////////
9213
9214 enum tetgenmesh::fliptype tetgenmesh::categorizeface(triface& horiz)
9215 {
9216 triface symhoriz, casing;
9217 face checksh, checkseg;
9218 face cassh1, cassh2;
9219 point pa, pb, pc, pd, pe, pf, pg;
9220 point abdoppo, bcdoppo, cadoppo;
9221 REAL ori1, ori2, ori3;
9222 int adjtet;
9223
9224 sym(horiz, symhoriz);
9225 if (symhoriz.tet == dummytet) {
9226 // A hull face is unflipable and locally Delaunay.
9227 return NONCONVEX;
9228 }
9229
9230 adjustedgering(horiz, CCW);
9231 findedge(&symhoriz, dest(horiz), org(horiz));
9232 pa = org(horiz);
9233 pb = dest(horiz);
9234 pc = apex(horiz);
9235 pd = oppo(horiz);
9236 pe = oppo(symhoriz);
9237
9238 // Find the number of adjacent tetrahedra of abc, which have d, e, and one
9239 // of corners of abc as their corners. This number can be 0, 1 and 2.
9240 abdoppo = bcdoppo = cadoppo = (point) NULL;
9241 adjtet = 0;
9242 fnext(horiz, casing); // at edge 'ab'.
9243 symself(casing);
9244 if (casing.tet != dummytet) {
9245 abdoppo = oppo(casing);
9246 if (abdoppo == pe) adjtet++;
9247 }
9248 enextfnext(horiz, casing); // at edge 'bc'.
9249 symself(casing);
9250 if (casing.tet != dummytet) {
9251 bcdoppo = oppo(casing);
9252 if (bcdoppo == pe) adjtet++;
9253 }
9254 enext2fnext(horiz, casing); // at edge 'ca'.
9255 symself(casing);
9256 if (casing.tet != dummytet) {
9257 cadoppo = oppo(casing);
9258 if (cadoppo == pe) adjtet++;
9259 }
9260
9261 if (adjtet == 0) {
9262 // No adjacent tetrahedron. Types T23, T22 and T44 are possible.
9263 ori1 = orient3d(pa, pb, pd, pe);
9264 if (checksubfaces && ori1 != 0.0) {
9265 // Check if abd and abe are both boundary faces?
9266 fnext(horiz, casing);
9267 tspivot(casing, cassh1);
9268 fnext(symhoriz, casing);
9269 tspivot(casing, cassh2);
9270 if ((cassh1.sh != dummysh) && (cassh2.sh != dummysh)) {
9271 // abd and abe are both boundary faces. Check if ab is a segment.
9272 findedge(&cassh1, pa, pb);
9273 sspivot(cassh1, checkseg);
9274 if (checkseg.sh == dummysh) {
9275 // ab is not a segment - abd and abe belong to the same facet.
9276 // The four points are forced to be coplanar.
9277 ori1 = 0.0;
9278 } else {
9279 // ab is a segment - abd and abe belong to two different facets.
9280 // In principle, a, b, c and d can form a tetrahedron (since
9281 // ori1 != 0.0). However, we should avoid to create a very
9282 // flat one which may form a sequence of extremely badly-shaped
9283 // or even wrong orientational tets. Test with a larger epsilon.
9284 if (iscoplanar(pa, pb, pd, pe, ori1, b->epsilon * 1e+2)) ori1 = 0.0;
9285 }
9286 } else {
9287 // abd and abe are not both boundary faces. Check if abd and bae
9288 // are approximately coplanar with respect to the epsilon.
9289 if (iscoplanar(pa, pb, pd, pe, ori1, b->epsilon)) ori1 = 0.0;
9290 }
9291 }
9292 if (ori1 < 0.0) {
9293 // e lies above abd, unflipable, tet abde is not present.
9294 #ifdef SELF_CHECK
9295 if (!nonconvex) {
9296 // abd and abe should not be hull faces, check it.
9297 fnext(horiz, casing);
9298 symself(casing);
9299 assert(casing.tet != dummytet);
9300 fnext(symhoriz, casing);
9301 symself(casing);
9302 assert(casing.tet != dummytet);
9303 }
9304 #endif
9305 if (checksubfaces) {
9306 // The nonconvexbility may be casued by existing an subsegment.
9307 tsspivot(&horiz, &checkseg);
9308 if (checkseg.sh != dummysh) {
9309 return FORBIDDENEDGE;
9310 }
9311 }
9312 return UNFLIPABLE;
9313 }
9314 ori2 = orient3d(pb, pc, pd, pe);
9315 if (checksubfaces && ori2 != 0.0) {
9316 // Check if bcd and cbe are both boundary faces.
9317 enextfnext(horiz, casing);
9318 tspivot(casing, cassh1);
9319 enext2fnext(symhoriz, casing);
9320 tspivot(casing, cassh2);
9321 if (cassh1.sh != dummysh && cassh2.sh != dummysh) {
9322 // bcd and cbe are both boundary faces. Check if bc is a segment.
9323 findedge(&cassh1, pb, pc);
9324 sspivot(cassh1, checkseg);
9325 if (checkseg.sh == dummysh) {
9326 // bc is not a segment - bcd and cbe belong to the same facet.
9327 // The four points are forced to be coplanar.
9328 ori2 = 0.0;
9329 } else {
9330 if (iscoplanar(pb, pc, pd, pe, ori2, b->epsilon * 1e+2)) ori2 = 0.0;
9331 }
9332 } else {
9333 // bcd and cbe are not both boundary faces. Check if bcd and cbe
9334 // are approximately coplanar with respect to the epsilon.
9335 if (iscoplanar(pb, pc, pd, pe, ori2, b->epsilon)) ori2 = 0.0;
9336 }
9337 }
9338 if (ori2 < 0.0) {
9339 // e lies above bcd, unflipable, tet bcde is not present.
9340 #ifdef SELF_CHECK
9341 if (!nonconvex) {
9342 // bcd and cbe should not be hull faces, check it.
9343 enextfnext(horiz, casing);
9344 symself(casing);
9345 assert(casing.tet != dummytet);
9346 enext2fnext(symhoriz, casing);
9347 symself(casing);
9348 assert(casing.tet != dummytet);
9349 }
9350 #endif
9351 enextself(horiz);
9352 if (checksubfaces) {
9353 // The nonconvexbility may be casued by existing an subsegment.
9354 tsspivot(&horiz, &checkseg);
9355 if (checkseg.sh != dummysh) {
9356 return FORBIDDENEDGE;
9357 }
9358 }
9359 return UNFLIPABLE;
9360 }
9361 ori3 = orient3d(pc, pa, pd, pe);
9362 if (checksubfaces && ori3 != 0.0) {
9363 // Check if cad and ace are both boundary faces.
9364 enext2fnext(horiz, casing);
9365 tspivot(casing, cassh1);
9366 enextfnext(symhoriz, casing);
9367 tspivot(casing, cassh2);
9368 if (cassh1.sh != dummysh && cassh2.sh != dummysh) {
9369 // cad and ace are both boundary faces. Check if ca is a segment.
9370 findedge(&cassh1, pc, pa);
9371 sspivot(cassh1, checkseg);
9372 if (checkseg.sh == dummysh) {
9373 // ca is not a segment - cad and ace belong to the same facet.
9374 // The four points are forced to be coplanar.
9375 ori3 = 0.0;
9376 } else {
9377 // ca is a segment - cad and ace belong to two different facets.
9378 // In principle, c, a, d and e can form a tetrahedron (since
9379 // ori3 != 0.0). Use a larger eps to test if they're coplanar.
9380 if (iscoplanar(pc, pa, pd, pe, ori3, b->epsilon * 1e+2)) ori3 = 0.0;
9381 }
9382 } else {
9383 // cad and ace are not both boundary faces. Check if cad and ace
9384 // are approximately coplanar with respect to the epsilon.
9385 if (iscoplanar(pc, pa, pd, pe, ori3, b->epsilon)) ori3 = 0.0;
9386 }
9387 }
9388 if (ori3 < 0.0) {
9389 // e lies above cad, unflipable, tet cade is not present.
9390 #ifdef SELF_CHECK
9391 if (!nonconvex) {
9392 // cad and ace should not be hull faces, check it.
9393 enext2fnext(horiz, casing);
9394 symself(casing);
9395 assert(casing.tet != dummytet);
9396 enextfnext(symhoriz, casing);
9397 symself(casing);
9398 assert(casing.tet != dummytet);
9399 }
9400 #endif
9401 enext2self(horiz);
9402 if (checksubfaces) {
9403 // The nonconvexbility may be casued by existing an subsegment.
9404 tsspivot(&horiz, &checkseg);
9405 if (checkseg.sh != dummysh) {
9406 return FORBIDDENEDGE;
9407 }
9408 }
9409 return UNFLIPABLE;
9410 }
9411 if (ori1 == 0.0) {
9412 // e is coplanar with abd.
9413 if (ori2 * ori3 == 0.0) {
9414 // only one zero is possible.
9415 // assert(!(ori2 == 0.0 && ori3 == 0.0));
9416 // Three points (d, e, and a or b) are collinear, abc is unflipable
9417 // and locally Delaunay.
9418 return NONCONVEX;
9419 }
9420 } else if (ori2 == 0.0) {
9421 // e is coplanar with bcd.
9422 if (ori1 * ori3 == 0.0) {
9423 // only one zero is possible.
9424 // assert(!(ori1 == 0.0 && ori3 == 0.0));
9425 // Three points (d, e, and b or c) are collinear, abc is unflipable
9426 // and locally Delaunay.
9427 return NONCONVEX;
9428 }
9429 // Adjust 'horiz' and 'symhoriz' be the edge bc.
9430 enextself(horiz);
9431 enext2self(symhoriz);
9432 } else if (ori3 == 0.0) {
9433 // e is coplanar with cad.
9434 if (ori1 * ori2 == 0.0) {
9435 // only one zero is possible.
9436 // assert(!(ori1 == 0.0 && ori2 == 0.0));
9437 // Three points (d, e, and c or a) are collinear, abc is unflipable
9438 // and locally Delaunay.
9439 return NONCONVEX;
9440 }
9441 // Adjust 'horiz' and 'symhoriz' be the edge ca.
9442 enext2self(horiz);
9443 enextself(symhoriz);
9444 } else {
9445 // e lies below all three faces, flipable.
9446 if (checksubfaces) {
9447 tspivot(horiz, checksh);
9448 if (checksh.sh != dummysh) {
9449 // To flip a subface is forbidden.
9450 return FORBIDDENFACE;
9451 }
9452 }
9453 return T23;
9454 }
9455 // Four points are coplanar, T22 or T44 is possible.
9456 if (checksubfaces) {
9457 tsspivot(&horiz, &checkseg);
9458 if (checkseg.sh != dummysh) {
9459 // To flip a subsegment is forbidden.
9460 return FORBIDDENEDGE;
9461 }
9462 tspivot(horiz, checksh);
9463 if (checksh.sh != dummysh) {
9464 // To flip a subface is forbidden.
9465 return FORBIDDENFACE;
9466 }
9467 }
9468 // Assume the four coplanar points are a, b, d, e, abd and abe are two
9469 // coplanar faces. If both abd and abe are hull faces, flipable(T22).
9470 // If they are interior faces, get the opposite tetrahedra abdf and
9471 // abeg, if f = g, flipable (T44). Otherwise, unflipable.
9472 pf = pg = (point) NULL;
9473 fnext(horiz, casing);
9474 symself(casing);
9475 if (casing.tet != dummytet) {
9476 pf = oppo(casing);
9477 }
9478 fnext(symhoriz, casing);
9479 symself(casing);
9480 if (casing.tet != dummytet) {
9481 pg = oppo(casing);
9482 }
9483 if (pf == pg) {
9484 // Either T22 (pf == pg == NULL) or T44 (pf and pg) is possible.
9485 if (checksubfaces) {
9486 // Retreat the corner points a, b, and c.
9487 pa = org(horiz);
9488 pb = dest(horiz);
9489 pc = apex(horiz);
9490 // Be careful not to create an inverted tetrahedron. Check the case.
9491 ori1 = orient3d(pc, pd, pe, pa);
9492 if (ori1 <= 0) return NONCONVEX;
9493 ori1 = orient3d(pd, pc, pe, pb);
9494 if (ori1 <= 0) return NONCONVEX;
9495 if (pf != (point) NULL) {
9496 ori1 = orient3d(pd, pf, pe, pa);
9497 if (ori1 <= 0) return NONCONVEX;
9498 ori1 = orient3d(pf, pd, pe, pb);
9499 if (ori1 <= 0) return NONCONVEX;
9500 }
9501 }
9502 if (pf == (point) NULL) {
9503 // abd and abe are hull faces, flipable.
9504 return T22;
9505 } else {
9506 // abd and abe are interior faces, flipable.
9507 #ifdef SELF_CHECK
9508 assert(pf != (point) NULL);
9509 #endif
9510 return T44;
9511 }
9512 } else {
9513 // ab has more than four faces around it, unflipable.
9514 return UNFLIPABLE;
9515 }
9516 } else if (adjtet == 1) {
9517 // One of its three edges is locally non-convex. Type T32 is possible.
9518 // Adjust current configuration so that edge ab is non-convex.
9519 if (bcdoppo == pe) {
9520 // Edge bc is non-convex. Adjust 'horiz' and 'symhoriz' be edge bc.
9521 enextself(horiz);
9522 enext2self(symhoriz);
9523 pa = org(horiz);
9524 pb = dest(horiz);
9525 pc = apex(horiz);
9526 } else if (cadoppo == pe) {
9527 // Edge ca is non-convex. Adjust 'horiz' and 'symhoriz' be edge ca.
9528 enext2self(horiz);
9529 enextself(symhoriz);
9530 pa = org(horiz);
9531 pb = dest(horiz);
9532 pc = apex(horiz);
9533 } else {
9534 // Edge ab is non-convex.
9535 #ifdef SELF_CHECK
9536 assert(abdoppo == pe);
9537 #endif
9538 } // Now ab is the non-convex edge.
9539 // In order to be flipable, ab should cross face cde. Check it.
9540 ori1 = orient3d(pc, pd, pe, pa);
9541 if (checksubfaces && ori1 != 0.0) {
9542 // Check if cad and ace are both boundary faces.
9543 enext2fnext(horiz, casing);
9544 tspivot(casing, cassh1);
9545 enextfnext(symhoriz, casing);
9546 tspivot(casing, cassh2);
9547 if (cassh1.sh != dummysh && cassh2.sh != dummysh) {
9548 // cad and ace are both boundary faces. Check if ca is a segment.
9549 findedge(&cassh1, pc, pa);
9550 sspivot(cassh1, checkseg);
9551 if (checkseg.sh == dummysh) {
9552 // ca is not a segment. cad and ace belong to the same facet.
9553 // The four points are forced to be coplanar.
9554 ori1 = 0.0;
9555 } else {
9556 // ca is a segment. cad and ace belong to different facets.
9557 // In principle, c, d, e, and a can form a tetrahedron (since
9558 // ori1 != 0.0). However, we should avoid to create a very
9559 // flat tet. Use a larger epsilon to test if they're coplanar.
9560 if (iscoplanar(pc, pd, pe, pa, ori1, b->epsilon * 1e+2)) ori1 = 0.0;
9561 }
9562 } else {
9563 // Check if c, d, e, and a are approximately coplanar.
9564 if (iscoplanar(pc, pd, pe, pa, ori1, b->epsilon)) ori1 = 0.0;
9565 }
9566 }
9567 if (ori1 <= 0.0) {
9568 // a lies above or is coplanar cde, abc is locally Delaunay.
9569 return NONCONVEX;
9570 }
9571 ori2 = orient3d(pd, pc, pe, pb);
9572 if (checksubfaces && ori2 != 0.0) {
9573 // Check if bcd and cbe are both boundary faces.
9574 enextfnext(horiz, casing);
9575 tspivot(casing, cassh1);
9576 enext2fnext(symhoriz, casing);
9577 tspivot(casing, cassh2);
9578 if (cassh1.sh != dummysh && cassh2.sh != dummysh) {
9579 // bcd and cbe are both boundary faces. Check if bc is a segment.
9580 findedge(&cassh1, pb, pc);
9581 sspivot(cassh1, checkseg);
9582 if (checkseg.sh == dummysh) {
9583 // bc is not a segment. bcd and cbe belong to the same facet.
9584 // The four points are forced to be coplanar.
9585 ori2 = 0.0;
9586 } else {
9587 // bc is a segment. bcd and cbe belong to different facets.
9588 // In principle, d, c, e, and b can form a tetrahedron (since
9589 // ori2 != 0.0). However, we should avoid to create a very
9590 // flat tet. Use a larger epsilon to test if they're coplanar.
9591 if (iscoplanar(pd, pc, pe, pb, ori2, b->epsilon * 1e+2)) ori2 = 0.0;
9592 }
9593 } else {
9594 // Check if d, c, e, and b are approximately coplanar.
9595 if (iscoplanar(pd, pc, pe, pb, ori2, b->epsilon)) ori2 = 0.0;
9596 }
9597 }
9598 if (ori2 <= 0.0) {
9599 // b lies above dce, unflipable, and abc is locally Delaunay.
9600 return NONCONVEX;
9601 }
9602 // Edge ab crosses face cde properly.
9603 if (checksubfaces) {
9604 // If abc is subface, then ab must be a subsegment (because abde is
9605 // a tetrahedron and ab crosses cde properly).
9606 tsspivot(&horiz, &checkseg);
9607 if (checkseg.sh != dummysh) {
9608 // To flip a subsegment is forbidden.
9609 return FORBIDDENEDGE;
9610 }
9611 // Both abd and bae should not be subfaces (because they're not
9612 // coplanar and ab is not a subsegment). However, they may be
9613 // subfaces and belong to a facet (created during facet recovery),
9614 // that is, abde is an invalid tetrahedron. Find this case out.
9615 fnext(horiz, casing);
9616 tspivot(casing, cassh1);
9617 fnext(symhoriz, casing);
9618 tspivot(casing, cassh2);
9619 if (cassh1.sh != dummysh || cassh2.sh != dummysh) {
9620 if (!b->quiet) {
9621 // Unfortunately, they're subfaces. Corrections need be done here.
9622 printf("Warning: A tetrahedron spans two subfaces of a facet.\n");
9623 }
9624 // Temporarily, let it be there.
9625 return UNFLIPABLE;
9626 }
9627 }
9628 return T32;
9629 } else {
9630 // The convex hull of {a, b, c, d, e} has only four vertices, abc is
9631 // unflipable, furthermore, it is locally Delaunay.
9632 return NONCONVEX;
9633 }
9634 }
9635
9636 ///////////////////////////////////////////////////////////////////////////////
9637 // //
9638 // enqueueflipface(), enqueueflipedge() Queue a face (or an edge). //
9639 // //
9640 // The face (or edge) may be non-locally Delaunay. It is queued for process- //
9641 // ing in flip() (or flipsub()). The vertices of the face (edge) are stored //
9642 // seperatly to ensure the face (or edge) is still the same one when we save //
9643 // it since other flips will cause this face (or edge) be changed or dead. //
9644 // //
9645 ///////////////////////////////////////////////////////////////////////////////
9646
9647 void tetgenmesh::enqueueflipface(triface& checkface, queue* flipqueue)
9648 {
9649 badface *queface;
9650
9651 queface = (badface *) flipqueue->push((void *) NULL);
9652 queface->tt = checkface;
9653 queface->forg = org(checkface);
9654 queface->fdest = dest(checkface);
9655 queface->fapex = apex(checkface);
9656 }
9657
9658 void tetgenmesh::enqueueflipedge(face& checkedge, queue* flipqueue)
9659 {
9660 badface *queface;
9661
9662 queface = (badface *) flipqueue->push((void *) NULL);
9663 queface->ss = checkedge;
9664 queface->forg = sorg(checkedge);
9665 queface->fdest = sdest(checkedge);
9666 }
9667
9668 ///////////////////////////////////////////////////////////////////////////////
9669 // //
9670 // flip23() Perform a 2-to-3 flip. //
9671 // //
9672 // On input, 'flipface' represents the face will be flipped. Let it is abc, //
9673 // the two tetrahedra sharing abc are abcd, bace. abc is not a subface. //
9674 // //
9675 // A 2-to-3 flip is to change two tetrahedra abcd, bace to three tetrahedra //
9676 // edab, edbc, and edca. As a result, face abc has been removed and three //
9677 // new faces eda, edb and edc have been created. //
9678 // //
9679 // On completion, 'flipface' returns edab. If 'flipqueue' is not NULL, all //
9680 // possibly non-Delaunay faces are added into it. //
9681 // //
9682 ///////////////////////////////////////////////////////////////////////////////
9683
9684 void tetgenmesh::flip23(triface* flipface, queue* flipqueue)
9685 {
9686 triface abcd, bace; // Old configuration.
9687 triface oldabd, oldbcd, oldcad;
9688 triface abdcasing, bcdcasing, cadcasing;
9689 face abdsh, bcdsh, cadsh;
9690 triface oldbae, oldcbe, oldace;
9691 triface baecasing, cbecasing, acecasing;
9692 face baesh, cbesh, acesh;
9693 triface edab, edbc, edca; // New configuration.
9694 point pa, pb, pc, pd, pe;
9695 REAL attrib, volume;
9696 int i;
9697
9698 abcd = *flipface;
9699 adjustedgering(abcd, CCW); // abcd represents edge ab.
9700 sym(abcd, bace);
9701 findedge(&bace, dest(abcd), org(abcd)); // bace represents edge ba.
9702 pa = org(abcd);
9703 pb = dest(abcd);
9704 pc = apex(abcd);
9705 pd = oppo(abcd);
9706 pe = oppo(bace);
9707
9708 if (b->verbose > 2) {
9709 printf(" Do T23 on face (%d, %d, %d, %d).\n", pointmark(pa),
9710 pointmark(pb), pointmark(pc), pointmark(pd));
9711 }
9712 flip23s++;
9713
9714 #ifdef SELF_CHECK
9715 // Edge de must cross face abc properly.
9716 assert(orient3d(pa, pb, pd, pe) >= 0.0);
9717 assert(orient3d(pb, pc, pd, pe) >= 0.0);
9718 assert(orient3d(pc, pa, pd, pe) >= 0.0);
9719 #endif
9720
9721 // Storing the old configuration outside the convex hull.
9722 fnext(abcd, oldabd);
9723 enextfnext(abcd, oldbcd);
9724 enext2fnext(abcd, oldcad);
9725 fnext(bace, oldbae);
9726 enext2fnext(bace, oldcbe);
9727 enextfnext(bace, oldace);
9728 sym(oldabd, abdcasing);
9729 sym(oldbcd, bcdcasing);
9730 sym(oldcad, cadcasing);
9731 sym(oldbae, baecasing);
9732 sym(oldcbe, cbecasing);
9733 sym(oldace, acecasing);
9734 if (checksubfaces) {
9735 tspivot(oldabd, abdsh);
9736 tspivot(oldbcd, bcdsh);
9737 tspivot(oldcad, cadsh);
9738 tspivot(oldbae, baesh);
9739 tspivot(oldcbe, cbesh);
9740 tspivot(oldace, acesh);
9741 }
9742
9743 // Creating the new configuration inside the convex hull.
9744 edab.tet = abcd.tet; // Update abcd to be edab.
9745 setorg (edab, pe);
9746 setdest(edab, pd);
9747 setapex(edab, pa);
9748 setoppo(edab, pb);
9749 edbc.tet = bace.tet; // Update bace to be edbc.
9750 setorg (edbc, pe);
9751 setdest(edbc, pd);
9752 setapex(edbc, pb);
9753 setoppo(edbc, pc);
9754 maketetrahedron(&edca); // Create edca.
9755 setorg (edca, pe);
9756 setdest(edca, pd);
9757 setapex(edca, pc);
9758 setoppo(edca, pa);
9759 // Set the element attributes of the new tetrahedron 'edca'.
9760 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
9761 attrib = elemattribute(abcd.tet, i);
9762 setelemattribute(edca.tet, i, attrib);
9763 }
9764 // Set the volume constraint of the new tetrahedron 'edca' if the -ra
9765 // switches are not used together. In -ra case, the various volume
9766 // constraints can be spreaded very far.
9767 if (b->varvolume && !b->refine) {
9768 volume = volumebound(abcd.tet);
9769 setvolumebound(edca.tet, volume);
9770 }
9771
9772 // Clear old bonds in edab(was abcd) and edbc(was bace).
9773 for (i = 0; i < 4; i ++) {
9774 edab.loc = i;
9775 dissolve(edab);
9776 edbc.loc = i;
9777 dissolve(edbc);
9778 }
9779 // Bond the faces inside the convex hull.
9780 edab.loc = 0;
9781 edca.loc = 1;
9782 bond(edab, edca);
9783 edab.loc = 1;
9784 edbc.loc = 0;
9785 bond(edab, edbc);
9786 edbc.loc = 1;
9787 edca.loc = 0;
9788 bond(edbc, edca);
9789 // Bond the faces on the convex hull.
9790 edab.loc = 2;
9791 bond(edab, abdcasing);
9792 edab.loc = 3;
9793 bond(edab, baecasing);
9794 edbc.loc = 2;
9795 bond(edbc, bcdcasing);
9796 edbc.loc = 3;
9797 bond(edbc, cbecasing);
9798 edca.loc = 2;
9799 bond(edca, cadcasing);
9800 edca.loc = 3;
9801 bond(edca, acecasing);
9802 // There may exist subfaces that need to be bonded to new configuarton.
9803 if (checksubfaces) {
9804 // Clear old flags in edab(was abcd) and edbc(was bace).
9805 for (i = 0; i < 4; i ++) {
9806 edab.loc = i;
9807 tsdissolve(edab);
9808 edbc.loc = i;
9809 tsdissolve(edbc);
9810 }
9811 if (abdsh.sh != dummysh) {
9812 edab.loc = 2;
9813 tsbond(edab, abdsh);
9814 }
9815 if (baesh.sh != dummysh) {
9816 edab.loc = 3;
9817 tsbond(edab, baesh);
9818 }
9819 if (bcdsh.sh != dummysh) {
9820 edbc.loc = 2;
9821 tsbond(edbc, bcdsh);
9822 }
9823 if (cbesh.sh != dummysh) {
9824 edbc.loc = 3;
9825 tsbond(edbc, cbesh);
9826 }
9827 if (cadsh.sh != dummysh) {
9828 edca.loc = 2;
9829 tsbond(edca, cadsh);
9830 }
9831 if (acesh.sh != dummysh) {
9832 edca.loc = 3;
9833 tsbond(edca, acesh);
9834 }
9835 }
9836
9837 edab.loc = 0;
9838 edbc.loc = 0;
9839 edca.loc = 0;
9840 if (b->verbose > 3) {
9841 printf(" Updating edab ");
9842 printtet(&edab);
9843 printf(" Updating edbc ");
9844 printtet(&edbc);
9845 printf(" Creating edca ");
9846 printtet(&edca);
9847 }
9848
9849 if (flipqueue != (queue *) NULL) {
9850 enextfnext(edab, abdcasing);
9851 enqueueflipface(abdcasing, flipqueue);
9852 enext2fnext(edab, baecasing);
9853 enqueueflipface(baecasing, flipqueue);
9854 enextfnext(edbc, bcdcasing);
9855 enqueueflipface(bcdcasing, flipqueue);
9856 enext2fnext(edbc, cbecasing);
9857 enqueueflipface(cbecasing, flipqueue);
9858 enextfnext(edca, cadcasing);
9859 enqueueflipface(cadcasing, flipqueue);
9860 enext2fnext(edca, acecasing);
9861 enqueueflipface(acecasing, flipqueue);
9862 }
9863
9864 // Save a live handle in 'recenttet'.
9865 recenttet = edbc;
9866 // Set the return handle be edab.
9867 *flipface = edab;
9868 }
9869
9870 ///////////////////////////////////////////////////////////////////////////////
9871 // //
9872 // flip32() Perform a 3-to-2 flip. //
9873 // //
9874 // On input, 'flipface' represents the face will be flipped. Let it is eda, //
9875 // where edge ed is locally non-convex. Three tetrahedra sharing ed are edab,//
9876 // edbc, and edca. ed is not a subsegment. //
9877 // //
9878 // A 3-to-2 flip is to change the three tetrahedra edab, edbc, and edca into //
9879 // another two tetrahedra abcd and bace. As a result, the edge ed has been //
9880 // removed and the face abc has been created. //
9881 // //
9882 // On completion, 'flipface' returns abcd. If 'flipqueue' is not NULL, all //
9883 // possibly non-Delaunay faces are added into it. //
9884 // //
9885 ///////////////////////////////////////////////////////////////////////////////
9886
9887 void tetgenmesh::flip32(triface* flipface, queue* flipqueue)
9888 {
9889 triface edab, edbc, edca; // Old configuration.
9890 triface oldabd, oldbcd, oldcad;
9891 triface abdcasing, bcdcasing, cadcasing;
9892 face abdsh, bcdsh, cadsh;
9893 triface oldbae, oldcbe, oldace;
9894 triface baecasing, cbecasing, acecasing;
9895 face baesh, cbesh, acesh;
9896 triface abcd, bace; // New configuration.
9897 point pa, pb, pc, pd, pe;
9898 int i;
9899
9900 edab = *flipface;
9901 adjustedgering(edab, CCW);
9902 fnext(edab, edbc);
9903 symself(edbc);
9904 findedge(&edbc, org(edab), dest(edab));
9905 fnext(edbc, edca);
9906 symself(edca);
9907 findedge(&edca, org(edab), dest(edab));
9908 pa = apex(edab);
9909 pb = oppo(edab);
9910 pc = oppo(edbc);
9911 pd = dest(edab);
9912 pe = org(edab);
9913
9914 if (b->verbose > 2) {
9915 printf(" Do T32 on face (%d, %d, %d, %d).\n",
9916 pointmark(pe), pointmark(pd), pointmark(pa), pointmark(pb));
9917 }
9918 flip32s++;
9919
9920 #ifdef SELF_CHECK
9921 // Edge de must cross face abc properly.
9922 // assert(orient3d(pa, pb, pc, pd) <= 0.0);
9923 // assert(orient3d(pb, pa, pc, pe) <= 0.0);
9924 #endif
9925
9926 // Storing the old configuration outside the convex hull.
9927 enextfnext(edab, oldabd);
9928 enext2fnext(edab, oldbae);
9929 enextfnext(edbc, oldbcd);
9930 enext2fnext(edbc, oldcbe);
9931 enextfnext(edca, oldcad);
9932 enext2fnext(edca, oldace);
9933 sym(oldabd, abdcasing);
9934 sym(oldbcd, bcdcasing);
9935 sym(oldcad, cadcasing);
9936 sym(oldbae, baecasing);
9937 sym(oldcbe, cbecasing);
9938 sym(oldace, acecasing);
9939 if (checksubfaces) {
9940 tspivot(oldabd, abdsh);
9941 tspivot(oldbcd, bcdsh);
9942 tspivot(oldcad, cadsh);
9943 tspivot(oldbae, baesh);
9944 tspivot(oldcbe, cbesh);
9945 tspivot(oldace, acesh);
9946 }
9947
9948 // Creating the new configuration inside the convex hull.
9949 abcd.tet = edab.tet; // Update edab to be abcd.
9950 setorg (abcd, pa);
9951 setdest(abcd, pb);
9952 setapex(abcd, pc);
9953 setoppo(abcd, pd);
9954 bace.tet = edbc.tet; // Update edbc to be bace.
9955 setorg (bace, pb);
9956 setdest(bace, pa);
9957 setapex(bace, pc);
9958 setoppo(bace, pe);
9959 // Dealloc a redundant tetrahedron (edca).
9960 tetrahedrondealloc(edca.tet);
9961
9962 // Clear the old bonds in abcd (was edab) and bace (was edbc).
9963 for (i = 0; i < 4; i ++) {
9964 abcd.loc = i;
9965 dissolve(abcd);
9966 bace.loc = i;
9967 dissolve(bace);
9968 }
9969 // Bond the inside face of the convex hull.
9970 abcd.loc = 0;
9971 bace.loc = 0;
9972 bond(abcd, bace);
9973 // Bond the outside faces of the convex hull.
9974 abcd.loc = 1;
9975 bond(abcd, abdcasing);
9976 abcd.loc = 2;
9977 bond(abcd, bcdcasing);
9978 abcd.loc = 3;
9979 bond(abcd, cadcasing);
9980 bace.loc = 1;
9981 bond(bace, baecasing);
9982 bace.loc = 3;
9983 bond(bace, cbecasing);
9984 bace.loc = 2;
9985 bond(bace, acecasing);
9986 if (checksubfaces) {
9987 // Clear old bonds in abcd(was edab) and bace(was edbc).
9988 for (i = 0; i < 4; i ++) {
9989 abcd.loc = i;
9990 tsdissolve(abcd);
9991 bace.loc = i;
9992 tsdissolve(bace);
9993 }
9994 if (abdsh.sh != dummysh) {
9995 abcd.loc = 1;
9996 tsbond(abcd, abdsh);
9997 }
9998 if (baesh.sh != dummysh) {
9999 bace.loc = 1;
10000 tsbond(bace, baesh);
10001 }
10002 if (bcdsh.sh != dummysh) {
10003 abcd.loc = 2;
10004 tsbond(abcd, bcdsh);
10005 }
10006 if (cbesh.sh != dummysh) {
10007 bace.loc = 3;
10008 tsbond(bace, cbesh);
10009 }
10010 if (cadsh.sh != dummysh) {
10011 abcd.loc = 3;
10012 tsbond(abcd, cadsh);
10013 }
10014 if (acesh.sh != dummysh) {
10015 bace.loc = 2;
10016 tsbond(bace, acesh);
10017 }
10018 }
10019
10020 abcd.loc = 0;
10021 bace.loc = 0;
10022 if (b->verbose > 3) {
10023 printf(" Updating abcd ");
10024 printtet(&abcd);
10025 printf(" Updating bace ");
10026 printtet(&bace);
10027 printf(" Deleting edca ");
10028 // printtet(&edca);
10029 }
10030
10031 if (flipqueue != (queue *) NULL) {
10032 fnext(abcd, abdcasing);
10033 enqueueflipface(abdcasing, flipqueue);
10034 fnext(bace, baecasing);
10035 enqueueflipface(baecasing, flipqueue);
10036 enextfnext(abcd, bcdcasing);
10037 enqueueflipface(bcdcasing, flipqueue);
10038 enextfnext(bace, cbecasing);
10039 enqueueflipface(cbecasing, flipqueue);
10040 enext2fnext(abcd, cadcasing);
10041 enqueueflipface(cadcasing, flipqueue);
10042 enext2fnext(bace, acecasing);
10043 enqueueflipface(acecasing, flipqueue);
10044 }
10045
10046 // Save a live handle in 'recenttet'.
10047 recenttet = abcd;
10048 // Set the return handle be abcd.
10049 *flipface = abcd;
10050 }
10051
10052 ///////////////////////////////////////////////////////////////////////////////
10053 // //
10054 // flip22() Perform a 2-to-2 (or 4-to-4) flip. //
10055 // //
10056 // On input, 'flipface' represents the face will be flipped. Let it is abe, //
10057 // ab is the flipable edge, the two tetrahedra sharing abe are abce and bade,//
10058 // hence a, b, c and d are coplanar. If abc, bad are interior faces, the two //
10059 // tetrahedra opposite to e are bacf and abdf. ab is not a subsegment. //
10060 // //
10061 // A 2-to-2 flip is to change two tetrahedra abce and bade into another two //
10062 // tetrahedra dcae and cdbe. If bacf and abdf exist, they're changed to cdaf //
10063 // and dcbf, thus a 4-to-4 flip. As a result, two or four tetrahedra have //
10064 // rotated counterclockwise (using right-hand rule with thumb points to e): //
10065 // abce->dcae, bade->cdbe, and bacf->cdaf, abdf->dcbf. //
10066 // //
10067 // If abc and bad are subfaces, a 2-to-2 flip is performed simultaneously by //
10068 // calling routine flip22sub(), hence abc->dca, bad->cdb. The edge rings of //
10069 // the flipped subfaces dca and cdb have the same orientation as abc and bad.//
10070 // Hence, they have the same orientation as other subfaces of the facet with //
10071 // respect to the lift point of this facet. //
10072 // //
10073 // On completion, 'flipface' holds edge dc of tetrahedron dcae. 'flipqueue' //
10074 // contains all possibly non-Delaunay faces if it is not NULL. //
10075 // //
10076 ///////////////////////////////////////////////////////////////////////////////
10077
10078 void tetgenmesh::flip22(triface* flipface, queue* flipqueue)
10079 {
10080 triface abce, bade;
10081 triface oldbce, oldcae, oldade, olddbe;
10082 triface bcecasing, caecasing, adecasing, dbecasing;
10083 face bcesh, caesh, adesh, dbesh;
10084 triface bacf, abdf;
10085 triface oldacf, oldcbf, oldbdf, olddaf;
10086 triface acfcasing, cbfcasing, bdfcasing, dafcasing;
10087 face acfsh, cbfsh, bdfsh, dafsh;
10088 face abc, bad;
10089 point pa, pb, pc, pd, pe, pf;
10090 int mirrorflag;
10091
10092 adjustedgering(*flipface, CCW); // 'flipface' is bae.
10093 fnext(*flipface, abce);
10094 esymself(abce);
10095 adjustedgering(*flipface, CW); // 'flipface' is abe.
10096 fnext(*flipface, bade);
10097 #ifdef SELF_CHECK
10098 assert(bade.tet != dummytet);
10099 #endif
10100 esymself(bade);
10101 pa = org(abce);
10102 pb = dest(abce);
10103 pc = apex(abce);
10104 pd = apex(bade);
10105 pe = oppo(bade);
10106 #ifdef SELF_CHECK
10107 assert(oppo(abce) == pe);
10108 #endif
10109 sym(abce, bacf);
10110 mirrorflag = bacf.tet != dummytet;
10111 if (mirrorflag) {
10112 findedge(&bacf, pb, pa);
10113 sym(bade, abdf);
10114 #ifdef SELF_CHECK
10115 assert(abdf.tet != dummytet);
10116 #endif
10117 findedge(&abdf, pa, pb);
10118 pf = oppo(bacf);
10119 #ifdef SELF_CHECK
10120 assert(oppo(abdf) == pf);
10121 #endif
10122 }
10123
10124 if (b->verbose > 2) {
10125 printf(" Do %s on edge (%d, %d).\n", mirrorflag ? "T44" : "T22",
10126 pointmark(pa), pointmark(pb));
10127 }
10128 mirrorflag ? flip44s++ : flip22s++;
10129
10130 #ifdef SELF_CHECK
10131 // The quadrilateral formed by a, b, c, and d must be convex.
10132 assert(orient3d(pc, pd, pe, pa) <= 0.0);
10133 assert(orient3d(pd, pc, pe, pb) <= 0.0);
10134 #endif
10135
10136 // Save the old configuration at the convex hull.
10137 enextfnext(abce, oldbce);
10138 enext2fnext(abce, oldcae);
10139 enextfnext(bade, oldade);
10140 enext2fnext(bade, olddbe);
10141 sym(oldbce, bcecasing);
10142 sym(oldcae, caecasing);
10143 sym(oldade, adecasing);
10144 sym(olddbe, dbecasing);
10145 if (checksubfaces) {
10146 tspivot(oldbce, bcesh);
10147 tspivot(oldcae, caesh);
10148 tspivot(oldade, adesh);
10149 tspivot(olddbe, dbesh);
10150 tspivot(abce, abc);
10151 tspivot(bade, bad);
10152 }
10153 if (mirrorflag) {
10154 enextfnext(bacf, oldacf);
10155 enext2fnext(bacf, oldcbf);
10156 enextfnext(abdf, oldbdf);
10157 enext2fnext(abdf, olddaf);
10158 sym(oldacf, acfcasing);
10159 sym(oldcbf, cbfcasing);
10160 sym(oldbdf, bdfcasing);
10161 sym(olddaf, dafcasing);
10162 if (checksubfaces) {
10163 tspivot(oldacf, acfsh);
10164 tspivot(oldcbf, cbfsh);
10165 tspivot(oldbdf, bdfsh);
10166 tspivot(olddaf, dafsh);
10167 }
10168 }
10169
10170 // Rotate abce, bade one-quarter turn counterclockwise.
10171 bond(oldbce, caecasing);
10172 bond(oldcae, adecasing);
10173 bond(oldade, dbecasing);
10174 bond(olddbe, bcecasing);
10175 if (checksubfaces) {
10176 // Check for subfaces and rebond them to the rotated tets.
10177 if (caesh.sh == dummysh) {
10178 tsdissolve(oldbce);
10179 } else {
10180 tsbond(oldbce, caesh);
10181 }
10182 if (adesh.sh == dummysh) {
10183 tsdissolve(oldcae);
10184 } else {
10185 tsbond(oldcae, adesh);
10186 }
10187 if (dbesh.sh == dummysh) {
10188 tsdissolve(oldade);
10189 } else {
10190 tsbond(oldade, dbesh);
10191 }
10192 if (bcesh.sh == dummysh) {
10193 tsdissolve(olddbe);
10194 } else {
10195 tsbond(olddbe, bcesh);
10196 }
10197 }
10198 if (mirrorflag) {
10199 // Rotate bacf, abdf one-quarter turn counterclockwise.
10200 bond(oldcbf, acfcasing);
10201 bond(oldacf, dafcasing);
10202 bond(olddaf, bdfcasing);
10203 bond(oldbdf, cbfcasing);
10204 if (checksubfaces) {
10205 // Check for subfaces and rebond them to the rotated tets.
10206 if (acfsh.sh == dummysh) {
10207 tsdissolve(oldcbf);
10208 } else {
10209 tsbond(oldcbf, acfsh);
10210 }
10211 if (dafsh.sh == dummysh) {
10212 tsdissolve(oldacf);
10213 } else {
10214 tsbond(oldacf, dafsh);
10215 }
10216 if (bdfsh.sh == dummysh) {
10217 tsdissolve(olddaf);
10218 } else {
10219 tsbond(olddaf, bdfsh);
10220 }
10221 if (cbfsh.sh == dummysh) {
10222 tsdissolve(oldbdf);
10223 } else {
10224 tsbond(oldbdf, cbfsh);
10225 }
10226 }
10227 }
10228
10229 // New vertex assignments for the rotated tetrahedra.
10230 setorg(abce, pd); // Update abce to dcae
10231 setdest(abce, pc);
10232 setapex(abce, pa);
10233 setorg(bade, pc); // Update bade to cdbe
10234 setdest(bade, pd);
10235 setapex(bade, pb);
10236 if (mirrorflag) {
10237 setorg(bacf, pc); // Update bacf to cdaf
10238 setdest(bacf, pd);
10239 setapex(bacf, pa);
10240 setorg(abdf, pd); // Update abdf to dcbf
10241 setdest(abdf, pc);
10242 setapex(abdf, pb);
10243 }
10244
10245 // Are there subfaces need to be flipped?
10246 if (checksubfaces && abc.sh != dummysh) {
10247 #ifdef SELF_CHECK
10248 assert(bad.sh != dummysh);
10249 #endif
10250 // Adjust the edge be ab, so the rotation of subfaces is according with
10251 // the rotation of tetrahedra.
10252 findedge(&abc, pa, pb);
10253 // Flip an edge of two subfaces, ignore non-Delaunay edges.
10254 flip22sub(&abc, NULL);
10255 }
10256
10257 if (b->verbose > 3) {
10258 printf(" Updating abce ");
10259 printtet(&abce);
10260 printf(" Updating bade ");
10261 printtet(&bade);
10262 if (mirrorflag) {
10263 printf(" Updating bacf ");
10264 printtet(&bacf);
10265 printf(" Updating abdf ");
10266 printtet(&abdf);
10267 }
10268 }
10269
10270 if (flipqueue != (queue *) NULL) {
10271 enextfnext(abce, bcecasing);
10272 enqueueflipface(bcecasing, flipqueue);
10273 enext2fnext(abce, caecasing);
10274 enqueueflipface(caecasing, flipqueue);
10275 enextfnext(bade, adecasing);
10276 enqueueflipface(adecasing, flipqueue);
10277 enext2fnext(bade, dbecasing);
10278 enqueueflipface(dbecasing, flipqueue);
10279 if (mirrorflag) {
10280 enextfnext(bacf, acfcasing);
10281 enqueueflipface(acfcasing, flipqueue);
10282 enext2fnext(bacf, cbfcasing);
10283 enqueueflipface(cbfcasing, flipqueue);
10284 enextfnext(abdf, bdfcasing);
10285 enqueueflipface(bdfcasing, flipqueue);
10286 enext2fnext(abdf, dafcasing);
10287 enqueueflipface(dafcasing, flipqueue);
10288 }
10289 // The two new faces dcae (abce), cdbe (bade) may still not be locally
10290 // Delaunay, and may need be flipped (flip23). On the other hand, in
10291 // conforming Delaunay algorithm, two new subfaces dca (abc), and cdb
10292 // (bad) may be non-conforming Delaunay, they need be queued if they
10293 // are locally Delaunay but non-conforming Delaunay.
10294 enqueueflipface(abce, flipqueue);
10295 enqueueflipface(bade, flipqueue);
10296 }
10297
10298 // Save a live handle in 'recenttet'.
10299 recenttet = abce;
10300 }
10301
10302 ///////////////////////////////////////////////////////////////////////////////
10303 // //
10304 // flip22sub() Perform a 2-to-2 flip on a subface edge. //
10305 // //
10306 // The flip edge is given by subface 'flipedge'. Let it is abc, where ab is //
10307 // the flipping edge. The other subface is bad, where a, b, c, d form a //
10308 // convex quadrilateral. ab is not a subsegment. //
10309 // //
10310 // A 2-to-2 subface flip is to change two subfaces abc and bad to another //
10311 // two subfaces dca and cdb. Hence, edge ab has been removed and dc becomes //
10312 // an edge. If a point e is above abc, this flip is equal to rotate abc and //
10313 // bad counterclockwise using right-hand rule with thumb points to e. It is //
10314 // important to know that the edge rings of the flipped subfaces dca and cdb //
10315 // are keeping the same orientation as their original subfaces. So they have //
10316 // the same orientation with respect to the lift point of this facet. //
10317 // //
10318 // During rotating, the face rings of the four edges bc, ca, ad, and de need //
10319 // be re-connected. If the edge is not a subsegment, then its face ring has //
10320 // only two faces, a sbond() will bond them together. If it is a subsegment, //
10321 // one should use sbond1() twice to bond two different handles to the rotat- //
10322 // ing subface, one is predecssor (-casin), another is successor (-casout). //
10323 // //
10324 // If 'flipqueue' is not NULL, it returns four edges bc, ca, ad, de, which //
10325 // may be non-Delaunay. //
10326 // //
10327 ///////////////////////////////////////////////////////////////////////////////
10328
10329 void tetgenmesh::flip22sub(face* flipedge, queue* flipqueue)
10330 {
10331 face abc, bad;
10332 face oldbc, oldca, oldad, olddb;
10333 face bccasin, bccasout, cacasin, cacasout;
10334 face adcasin, adcasout, dbcasin, dbcasout;
10335 face bc, ca, ad, db;
10336 face spinsh;
10337 point pa, pb, pc, pd;
10338
10339 abc = *flipedge;
10340 spivot(abc, bad);
10341 if (sorg(bad) != sdest(abc)) {
10342 sesymself(bad);
10343 }
10344 pa = sorg(abc);
10345 pb = sdest(abc);
10346 pc = sapex(abc);
10347 pd = sapex(bad);
10348
10349 if (b->verbose > 2) {
10350 printf(" Flip sub edge (%d, %d).\n", pointmark(pa), pointmark(pb));
10351 }
10352
10353 // Save the old configuration outside the quadrilateral.
10354 senext(abc, oldbc);
10355 senext2(abc, oldca);
10356 senext(bad, oldad);
10357 senext2(bad, olddb);
10358 // Get the outside connection. Becareful if there is a subsegment on the
10359 // quadrilateral, two casings (casin and casout) are needed to save for
10360 // keeping the face link.
10361 spivot(oldbc, bccasout);
10362 sspivot(oldbc, bc);
10363 if (bc.sh != dummysh) {
10364 // 'bc' is a subsegment.
10365 if (bccasout.sh != dummysh) {
10366 if (oldbc.sh != bccasout.sh) {
10367 // 'oldbc' is not self-bonded.
10368 spinsh = bccasout;
10369 do {
10370 bccasin = spinsh;
10371 spivotself(spinsh);
10372 } while (spinsh.sh != oldbc.sh);
10373 } else {
10374 bccasout.sh = dummysh;
10375 }
10376 }
10377 ssdissolve(oldbc);
10378 }
10379 spivot(oldca, cacasout);
10380 sspivot(oldca, ca);
10381 if (ca.sh != dummysh) {
10382 // 'ca' is a subsegment.
10383 if (cacasout.sh != dummysh) {
10384 if (oldca.sh != cacasout.sh) {
10385 // 'oldca' is not self-bonded.
10386 spinsh = cacasout;
10387 do {
10388 cacasin = spinsh;
10389 spivotself(spinsh);
10390 } while (spinsh.sh != oldca.sh);
10391 } else {
10392 cacasout.sh = dummysh;
10393 }
10394 }
10395 ssdissolve(oldca);
10396 }
10397 spivot(oldad, adcasout);
10398 sspivot(oldad, ad);
10399 if (ad.sh != dummysh) {
10400 // 'ad' is a subsegment.
10401 if (adcasout.sh != dummysh) {
10402 if (oldad.sh != adcasout.sh) {
10403 // 'adcasout' is not self-bonded.
10404 spinsh = adcasout;
10405 do {
10406 adcasin = spinsh;
10407 spivotself(spinsh);
10408 } while (spinsh.sh != oldad.sh);
10409 } else {
10410 adcasout.sh = dummysh;
10411 }
10412 }
10413 ssdissolve(oldad);
10414 }
10415 spivot(olddb, dbcasout);
10416 sspivot(olddb, db);
10417 if (db.sh != dummysh) {
10418 // 'db' is a subsegment.
10419 if (dbcasout.sh != dummysh) {
10420 if (olddb.sh != dbcasout.sh) {
10421 // 'dbcasout' is not self-bonded.
10422 spinsh = dbcasout;
10423 do {
10424 dbcasin = spinsh;
10425 spivotself(spinsh);
10426 } while (spinsh.sh != olddb.sh);
10427 } else {
10428 dbcasout.sh = dummysh;
10429 }
10430 }
10431 ssdissolve(olddb);
10432 }
10433
10434 // Rotate abc and bad one-quarter turn counterclockwise.
10435 if (ca.sh != dummysh) {
10436 if (cacasout.sh != dummysh) {
10437 sbond1(cacasin, oldbc);
10438 sbond1(oldbc, cacasout);
10439 } else {
10440 // Bond 'oldbc' to itself.
10441 sbond(oldbc, oldbc);
10442 // Make sure that dummysh always correctly bonded.
10443 dummysh[0] = sencode(oldbc);
10444 }
10445 ssbond(oldbc, ca);
10446 } else {
10447 sbond(oldbc, cacasout);
10448 }
10449 if (ad.sh != dummysh) {
10450 if (adcasout.sh != dummysh) {
10451 sbond1(adcasin, oldca);
10452 sbond1(oldca, adcasout);
10453 } else {
10454 // Bond 'oldca' to itself.
10455 sbond(oldca, oldca);
10456 // Make sure that dummysh always correctly bonded.
10457 dummysh[0] = sencode(oldca);
10458 }
10459 ssbond(oldca, ad);
10460 } else {
10461 sbond(oldca, adcasout);
10462 }
10463 if (db.sh != dummysh) {
10464 if (dbcasout.sh != dummysh) {
10465 sbond1(dbcasin, oldad);
10466 sbond1(oldad, dbcasout);
10467 } else {
10468 // Bond 'oldad' to itself.
10469 sbond(oldad, oldad);
10470 // Make sure that dummysh always correctly bonded.
10471 dummysh[0] = sencode(oldad);
10472 }
10473 ssbond(oldad, db);
10474 } else {
10475 sbond(oldad, dbcasout);
10476 }
10477 if (bc.sh != dummysh) {
10478 if (bccasout.sh != dummysh) {
10479 sbond1(bccasin, olddb);
10480 sbond1(olddb, bccasout);
10481 } else {
10482 // Bond 'olddb' to itself.
10483 sbond(olddb, olddb);
10484 // Make sure that dummysh always correctly bonded.
10485 dummysh[0] = sencode(olddb);
10486 }
10487 ssbond(olddb, bc);
10488 } else {
10489 sbond(olddb, bccasout);
10490 }
10491
10492 // New vertex assignments for the rotated subfaces.
10493 setsorg(abc, pd); // Update abc to dca.
10494 setsdest(abc, pc);
10495 setsapex(abc, pa);
10496 setsorg(bad, pc); // Update bad to cdb.
10497 setsdest(bad, pd);
10498 setsapex(bad, pb);
10499
10500 if (flipqueue != (queue *) NULL) {
10501 enqueueflipedge(bccasout, flipqueue);
10502 enqueueflipedge(cacasout, flipqueue);
10503 enqueueflipedge(adcasout, flipqueue);
10504 enqueueflipedge(dbcasout, flipqueue);
10505 }
10506 }
10507
10508 ///////////////////////////////////////////////////////////////////////////////
10509 // //
10510 // flip() Flips non-locally Delaunay faces in flipqueue until it is empty.//
10511 // //
10512 // Assumpation: Current tetrahedralization is non-Delaunay after inserting //
10513 // a point or performing a flip operation, all possibly non-Delaunay faces //
10514 // are in 'flipqueue'. //
10515 // //
10516 // If 'plastflip' is not NULL, it is used to return a stack of recently //
10517 // flipped faces. This stack will be used to reverse the flips done in this //
10518 // routine later for removing a newly inserted point because it encroaches //
10519 // any subfaces or subsegments. //
10520 // //
10521 // The return value is the total number of flips done during this invocation.//
10522 // //
10523 ///////////////////////////////////////////////////////////////////////////////
10524
10525 long tetgenmesh::flip(queue* flipqueue, badface **plastflip)
10526 {
10527 badface *qface, *newflip;
10528 triface flipface, symface;
10529 point pa, pb, pc, pd, pe;
10530 enum fliptype fc;
10531 REAL sign, bakepsilon;
10532 long flipcount, maxfaces;
10533 int epscount, fcount;
10534 int ia, ib, ic, id, ie;
10535
10536 if (b->verbose > 1) {
10537 printf(" Do flipface queue: %ld faces.\n", flipqueue->len());
10538 }
10539
10540 flipcount = flip23s + flip32s + flip22s + flip44s;
10541 if (checksubfaces) {
10542 maxfaces = (4l * tetrahedrons->items + hullsize) / 2l;
10543 fcount = 0;
10544 }
10545
10546 if (plastflip != (badface **) NULL) {
10547 // Initialize the stack of the flip sequence.
10548 flipstackers->restart();
10549 *plastflip = (badface *) NULL;
10550 }
10551
10552 // Loop until the queue is empty.
10553 while (!flipqueue->empty()) {
10554 qface = (badface *) flipqueue->pop();
10555 flipface = qface->tt;
10556 // Check the validity of this face.
10557 if (isdead(&flipface) || flipface.tet == dummytet ||
10558 (org(flipface) != qface->forg) ||
10559 (dest(flipface) != qface->fdest) ||
10560 (apex(flipface) != qface->fapex) ||
10561 (oppo(flipface) == (point) NULL)) continue;
10562 sym(flipface, symface);
10563 // Only do check when the adjacent tet exists and it's not a "fake" tet.
10564 if (symface.tet != dummytet && oppo(symface) != (point) NULL) {
10565 // For positive orientation that insphere() test requires.
10566 adjustedgering(flipface, CW);
10567 pa = org(flipface);
10568 pb = dest(flipface);
10569 pc = apex(flipface);
10570 pd = oppo(flipface);
10571 pe = oppo(symface);
10572 // if (symbolic) {
10573 ia = pointmark(pa);
10574 ib = pointmark(pb);
10575 ic = pointmark(pc);
10576 id = pointmark(pd);
10577 ie = pointmark(pe);
10578 sign = insphere_sos(pa, pb, pc, pd, pe, ia, ib, ic, id, ie);
10579 assert(sign != 0.0);
10580 // } else {
10581 // sign = insphere(pa, pb, pc, pd, pe);
10582 // }
10583 } else {
10584 sign = -1.0; // A hull face is locally Delaunay.
10585 }
10586 if (sign > 0.0) {
10587 // 'flipface' is non-locally Delaunay, try to flip it.
10588 if (checksubfaces) {
10589 fcount++;
10590 bakepsilon = b->epsilon;
10591 epscount = 0;
10592 while (epscount < 32) {
10593 fc = categorizeface(flipface);
10594 if (fc == NONCONVEX) {
10595 b->epsilon *= 1e-1;
10596 epscount++;
10597 continue;
10598 }
10599 break;
10600 }
10601 b->epsilon = bakepsilon;
10602 if (epscount >= 32) {
10603 if (b->verbose > 0) {
10604 printf("Warning: Can't flip a degenerate tetrahedron.\n");
10605 }
10606 fc = NONCONVEX;
10607 }
10608 } else {
10609 fc = categorizeface(flipface);
10610 #ifdef SELF_CHECK
10611 assert(fc != NONCONVEX);
10612 #endif
10613 }
10614 switch (fc) {
10615 // The following face types are flipable.
10616 case T44:
10617 case T22:
10618 flip22(&flipface, flipqueue);
10619 break;
10620 case T23:
10621 flip23(&flipface, flipqueue);
10622 break;
10623 case T32:
10624 flip32(&flipface, flipqueue);
10625 break;
10626 // The following face types are unflipable.
10627 case UNFLIPABLE:
10628 break;
10629 case FORBIDDENFACE:
10630 break;
10631 case FORBIDDENEDGE:
10632 break;
10633 // This case is only possible when the domain is nonconvex.
10634 case NONCONVEX:
10635 // assert(nonconvex);
10636 break;
10637 }
10638 if (plastflip != (badface **) NULL) {
10639 if ((fc == T44) || (fc == T22) || (fc == T23) || (fc == T32)) {
10640 // Push the flipped face into stack.
10641 newflip = (badface *) flipstackers->alloc();
10642 newflip->tt = flipface;
10643 newflip->key = (REAL) fc;
10644 newflip->forg = org(flipface);
10645 newflip->fdest = dest(flipface);
10646 newflip->fapex = apex(flipface);
10647 newflip->previtem = *plastflip;
10648 *plastflip = newflip;
10649 }
10650 }
10651 }
10652 }
10653
10654 flipcount = flip23s + flip32s + flip22s + flip44s - flipcount;
10655 if (b->verbose > 1) {
10656 printf(" %ld flips.\n", flipcount);
10657 }
10658
10659 return flipcount;
10660 }
10661
10662 ///////////////////////////////////////////////////////////////////////////////
10663 // //
10664 // undoflip() Undo the most recent flip sequence induced by flip(). //
10665 // //
10666 // 'lastflip' is the stack of recently flipped faces. Walks through the list //
10667 // of flips, in the reverse of the order in which they were done, and undoes //
10668 // them. //
10669 // //
10670 ///////////////////////////////////////////////////////////////////////////////
10671
10672 void tetgenmesh::undoflip(badface *lastflip)
10673 {
10674 enum fliptype fc;
10675
10676 while (lastflip != (badface *) NULL) {
10677 // Get the right flipped face.
10678 findface(&lastflip->tt, lastflip->forg, lastflip->fdest, lastflip->fapex);
10679 fc = (enum fliptype) (int) lastflip->key;
10680 switch (fc) {
10681 case T23:
10682 // The reverse operation of T23 is T32.
10683 flip32(&lastflip->tt, NULL);
10684 break;
10685 case T32:
10686 // The reverse operation of T32 is T23.
10687 flip23(&lastflip->tt, NULL);
10688 break;
10689 case T22:
10690 case T44:
10691 // The reverse operation of T22 or T44 is again T22 or T44.
10692 flip22(&lastflip->tt, NULL);
10693 break;
10694 default: // To omit compile warnings.
10695 break;
10696 }
10697 // Go on and process the next transformation.
10698 lastflip = lastflip->previtem;
10699 }
10700 }
10701
10702 ///////////////////////////////////////////////////////////////////////////////
10703 // //
10704 // flipsub() Flip non-Delaunay edges in a queue of (coplanar) subfaces. //
10705 // //
10706 // Assumpation: Current triangulation T contains non-Delaunay edges (after //
10707 // inserting a point or performing a flip). Non-Delaunay edges are queued in //
10708 // 'facequeue'. Returns the total number of flips done during this call. //
10709 // //
10710 ///////////////////////////////////////////////////////////////////////////////
10711
10712 long tetgenmesh::flipsub(queue* flipqueue)
10713 {
10714 badface *qedge;
10715 face flipedge, symedge;
10716 face checkseg;
10717 point pa, pb, pc, pd;
10718 REAL vab[3], vac[3], vad[3];
10719 REAL dot1, dot2, lac, lad;
10720 REAL sign, ori;
10721 int edgeflips;
10722 int i;
10723
10724 if (b->verbose > 1) {
10725 printf(" Start do edge queue: %ld edges.\n", flipqueue->len());
10726 }
10727
10728 edgeflips = 0;
10729
10730 while ((qedge = (badface *) flipqueue->pop()) != NULL) {
10731 flipedge = qedge->ss;
10732 if (flipedge.sh == dummysh) continue;
10733 if ((sorg(flipedge) != qedge->forg) ||
10734 (sdest(flipedge) != qedge->fdest)) continue;
10735 sspivot(flipedge, checkseg);
10736 if (checkseg.sh != dummysh) continue; // Can't flip a subsegment.
10737 spivot(flipedge, symedge);
10738 if (symedge.sh == dummysh) continue; // Can't flip a hull edge.
10739 pa = sorg(flipedge);
10740 pb = sdest(flipedge);
10741 pc = sapex(flipedge);
10742 pd = sapex(symedge);
10743 // Choose the triangle abc or abd as the base depending on the angle1
10744 // (Vac, Vab) and angle2 (Vad, Vab).
10745 for (i = 0; i < 3; i++) vab[i] = pb[i] - pa[i];
10746 for (i = 0; i < 3; i++) vac[i] = pc[i] - pa[i];
10747 for (i = 0; i < 3; i++) vad[i] = pd[i] - pa[i];
10748 dot1 = dot(vac, vab);
10749 dot2 = dot(vad, vab);
10750 dot1 *= dot1;
10751 dot2 *= dot2;
10752 lac = dot(vac, vac);
10753 lad = dot(vad, vad);
10754 if (lad * dot1 <= lac * dot2) {
10755 // angle1 is closer to 90 than angle2, choose abc (flipedge).
10756 abovepoint = facetabovepointarray[shellmark(flipedge)];
10757 if (abovepoint == (point) NULL) {
10758 getfacetabovepoint(&flipedge);
10759 }
10760 sign = insphere(pa, pb, pc, abovepoint, pd);
10761 ori = orient3d(pa, pb, pc, abovepoint);
10762 } else {
10763 // angle2 is closer to 90 than angle1, choose abd (symedge).
10764 abovepoint = facetabovepointarray[shellmark(symedge)];
10765 if (abovepoint == (point) NULL) {
10766 getfacetabovepoint(&symedge);
10767 }
10768 sign = insphere(pa, pb, pd, abovepoint, pc);
10769 ori = orient3d(pa, pb, pd, abovepoint);
10770 }
10771 // Correct the sign.
10772 sign = ori > 0.0 ? sign : -sign;
10773 if (sign > 0.0) {
10774 // Flip the non-Delaunay edge.
10775 flip22sub(&flipedge, flipqueue);
10776 edgeflips++;
10777 }
10778 }
10779
10780 if (b->verbose > 1) {
10781 printf(" Total %d flips.\n", edgeflips);
10782 }
10783
10784 return edgeflips;
10785 }
10786
10787 ///////////////////////////////////////////////////////////////////////////////
10788 // //
10789 // splittetrahedron() Insert a point into a tetrahedron, split it into //
10790 // four tetrahedra. //
10791 // //
10792 // The tetrahedron is given by 'splittet'. Let it is abcd. The inserting //
10793 // point 'newpoint' v should lie strictly inside abcd. //
10794 // //
10795 // Splitting a tetrahedron is to shrink abcd to abcv, and create three new //
10796 // tetrahedra badv, cbdv, and acdv. //
10797 // //
10798 // On completion, 'splittet' returns abcv. If 'flipqueue' is not NULL, it //
10799 // contains all possibly non-locally Delaunay faces. //
10800 // //
10801 ///////////////////////////////////////////////////////////////////////////////
10802
10803 void tetgenmesh::
10804 splittetrahedron(point newpoint, triface* splittet, queue* flipqueue)
10805 {
10806 triface oldabd, oldbcd, oldcad; // Old configuration.
10807 triface abdcasing, bcdcasing, cadcasing;
10808 face abdsh, bcdsh, cadsh;
10809 triface abcv, badv, cbdv, acdv; // New configuration.
10810 point pa, pb, pc, pd;
10811 REAL attrib, volume;
10812 int i;
10813
10814 abcv = *splittet;
10815 abcv.ver = 0;
10816 // Set the changed vertices and new tetrahedron.
10817 pa = org(abcv);
10818 pb = dest(abcv);
10819 pc = apex(abcv);
10820 pd = oppo(abcv);
10821
10822 if (b->verbose > 1) {
10823 printf(" Inserting point %d in tetrahedron (%d, %d, %d, %d).\n",
10824 pointmark(newpoint), pointmark(pa), pointmark(pb), pointmark(pc),
10825 pointmark(pd));
10826 }
10827
10828 fnext(abcv, oldabd);
10829 enextfnext(abcv, oldbcd);
10830 enext2fnext(abcv, oldcad);
10831 sym(oldabd, abdcasing);
10832 sym(oldbcd, bcdcasing);
10833 sym(oldcad, cadcasing);
10834 maketetrahedron(&badv);
10835 maketetrahedron(&cbdv);
10836 maketetrahedron(&acdv);
10837
10838 // Set 'badv' vertices.
10839 setorg (badv, pb);
10840 setdest(badv, pa);
10841 setapex(badv, pd);
10842 setoppo(badv, newpoint);
10843 // Set 'cbdv' vertices.
10844 setorg (cbdv, pc);
10845 setdest(cbdv, pb);
10846 setapex(cbdv, pd);
10847 setoppo(cbdv, newpoint);
10848 // Set 'acdv' vertices.
10849 setorg (acdv, pa);
10850 setdest(acdv, pc);
10851 setapex(acdv, pd);
10852 setoppo(acdv, newpoint);
10853 // Set 'abcv' vertices
10854 setoppo(abcv, newpoint);
10855
10856 // Set the element attributes of the new tetrahedra.
10857 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
10858 attrib = elemattribute(abcv.tet, i);
10859 setelemattribute(badv.tet, i, attrib);
10860 setelemattribute(cbdv.tet, i, attrib);
10861 setelemattribute(acdv.tet, i, attrib);
10862 }
10863 // Set the volume constraint of the new tetrahedra.
10864 if (b->varvolume) {
10865 volume = volumebound(abcv.tet);
10866 setvolumebound(badv.tet, volume);
10867 setvolumebound(cbdv.tet, volume);
10868 setvolumebound(acdv.tet, volume);
10869 }
10870
10871 // Bond the new triangles to the surrounding tetrahedron.
10872 bond(badv, abdcasing);
10873 bond(cbdv, bcdcasing);
10874 bond(acdv, cadcasing);
10875 // There may exist subfaces need to be bonded to the new tetrahedra.
10876 if (checksubfaces) {
10877 tspivot(oldabd, abdsh);
10878 if (abdsh.sh != dummysh) {
10879 tsdissolve(oldabd);
10880 tsbond(badv, abdsh);
10881 }
10882 tspivot(oldbcd, bcdsh);
10883 if (bcdsh.sh != dummysh) {
10884 tsdissolve(oldbcd);
10885 tsbond(cbdv, bcdsh);
10886 }
10887 tspivot(oldcad, cadsh);
10888 if (cadsh.sh != dummysh) {
10889 tsdissolve(oldcad);
10890 tsbond(acdv, cadsh);
10891 }
10892 }
10893 badv.loc = 3;
10894 cbdv.loc = 2;
10895 bond(badv, cbdv);
10896 cbdv.loc = 3;
10897 acdv.loc = 2;
10898 bond(cbdv, acdv);
10899 acdv.loc = 3;
10900 badv.loc = 2;
10901 bond(acdv, badv);
10902 badv.loc = 1;
10903 bond(badv, oldabd);
10904 cbdv.loc = 1;
10905 bond(cbdv, oldbcd);
10906 acdv.loc = 1;
10907 bond(acdv, oldcad);
10908
10909 badv.loc = 0;
10910 cbdv.loc = 0;
10911 acdv.loc = 0;
10912 if (b->verbose > 3) {
10913 printf(" Updating abcv ");
10914 printtet(&abcv);
10915 printf(" Creating badv ");
10916 printtet(&badv);
10917 printf(" Creating cbdv ");
10918 printtet(&cbdv);
10919 printf(" Creating acdv ");
10920 printtet(&acdv);
10921 }
10922
10923 if (flipqueue != (queue *) NULL) {
10924 enqueueflipface(abcv, flipqueue);
10925 enqueueflipface(badv, flipqueue);
10926 enqueueflipface(cbdv, flipqueue);
10927 enqueueflipface(acdv, flipqueue);
10928 }
10929
10930 // Save a handle for quick point location.
10931 recenttet = abcv;
10932 // Set the return handle be abcv.
10933 *splittet = abcv;
10934 }
10935
10936 ///////////////////////////////////////////////////////////////////////////////
10937 // //
10938 // unsplittetrahedron() Reverse the operation of inserting a point into a //
10939 // tetrahedron, so as to remove the newly inserted //
10940 // point from the mesh. //
10941 // //
10942 // Assume the origional tetrahedron is abcd, it was split by v into four //
10943 // tetrahedra abcv, badv, cbdv, and acdv. 'splittet' represents face abc of //
10944 // abcv (i.e., its opposite is v). //
10945 // //
10946 // Point v is removed by expanding abcv to abcd, deleting three tetrahedra //
10947 // badv, cbdv and acdv. On return, point v is not deleted in this routine. //
10948 // //
10949 ///////////////////////////////////////////////////////////////////////////////
10950
10951 void tetgenmesh::unsplittetrahedron(triface* splittet)
10952 {
10953 triface abcv, badv, cbdv, acdv;
10954 triface oldabv, oldbcv, oldcav;
10955 triface badcasing, cbdcasing, acdcasing;
10956 face badsh, cbdsh, acdsh;
10957
10958 abcv = *splittet;
10959 adjustedgering(abcv, CCW); // for sure.
10960 fnext(abcv, oldabv);
10961 fnext(oldabv, badv);
10962 esymself(badv);
10963 enextfnext(abcv, oldbcv);
10964 fnext(oldbcv, cbdv);
10965 esymself(cbdv);
10966 enext2fnext(abcv, oldcav);
10967 fnext(oldcav, acdv);
10968 esymself(acdv);
10969
10970 if (b->verbose > 1) {
10971 printf(" Removing point %d in tetrahedron (%d, %d, %d, %d).\n",
10972 pointmark(oppo(abcv)), pointmark(org(abcv)), pointmark(dest(abcv)),
10973 pointmark(apex(abcv)), pointmark(apex(badv)));
10974 }
10975
10976 sym(badv, badcasing);
10977 tspivot(badv, badsh);
10978 sym(cbdv, cbdcasing);
10979 tspivot(cbdv, cbdsh);
10980 sym(acdv, acdcasing);
10981 tspivot(acdv, acdsh);
10982
10983 // Expanding abcv to abcd.
10984 setoppo(abcv, apex(badv));
10985 bond(oldabv, badcasing);
10986 if (badsh.sh != dummysh) {
10987 tsbond(oldabv, badsh);
10988 }
10989 bond(oldbcv, cbdcasing);
10990 if (cbdsh.sh != dummysh) {
10991 tsbond(oldbcv, cbdsh);
10992 }
10993 bond(oldcav, acdcasing);
10994 if (acdsh.sh != dummysh) {
10995 tsbond(oldcav, acdsh);
10996 }
10997
10998 // Delete the three split-out tetrahedra.
10999 tetrahedrondealloc(badv.tet);
11000 tetrahedrondealloc(cbdv.tet);
11001 tetrahedrondealloc(acdv.tet);
11002 }
11003
11004 ///////////////////////////////////////////////////////////////////////////////
11005 // //
11006 // splittetface() Insert a point on a face of a mesh. //
11007 // //
11008 // 'splittet' is the splitting face. Let it is abcd, where abc is the face //
11009 // will be split. If abc is not a hull face, abce is the tetrahedron at the //
11010 // opposite of d. //
11011 // //
11012 // To split face abc by a point v is to shrink the tetrahedra abcd to abvd, //
11013 // create two new tetrahedra bcvd, cavd. If abc is not a hull face, shrink //
11014 // the tetrahedra bace to bave, create two new tetrahedra cbve, acve. //
11015 // //
11016 // If abc is a subface, it is split into three subfaces simultaneously by //
11017 // calling routine splitsubface(), hence, abv, bcv, cav. The edge rings of //
11018 // the split subfaces have the same orientation as abc's. //
11019 // //
11020 // On completion, 'splittet' returns abvd. If 'flipqueue' is not NULL, it //
11021 // contains all possibly non-locally Delaunay faces. //
11022 // //
11023 ///////////////////////////////////////////////////////////////////////////////
11024
11025 void tetgenmesh::
11026 splittetface(point newpoint, triface* splittet, queue* flipqueue)
11027 {
11028 triface abcd, bace; // Old configuration.
11029 triface oldbcd, oldcad, oldace, oldcbe;
11030 triface bcdcasing, cadcasing, acecasing, cbecasing;
11031 face abcsh, bcdsh, cadsh, acesh, cbesh;
11032 triface abvd, bcvd, cavd, bave, cbve, acve; // New configuration.
11033 point pa, pb, pc, pd, pe;
11034 REAL attrib, volume;
11035 bool mirrorflag;
11036 int i;
11037
11038 abcd = *splittet;
11039 // abcd.ver = 0; // Adjust to be CCW edge ring.
11040 adjustedgering(abcd, CCW);
11041 pa = org(abcd);
11042 pb = dest(abcd);
11043 pc = apex(abcd);
11044 pd = oppo(abcd);
11045 pe = (point) NULL; // avoid a compile warning.
11046 // Is there a second tetrahderon?
11047 mirrorflag = issymexist(&abcd);
11048 if (mirrorflag) {
11049 // This is an interior face.
11050 sym(abcd, bace);
11051 findedge(&bace, dest(abcd), org(abcd));
11052 pe = oppo(bace);
11053 }
11054 if (checksubfaces) {
11055 // Is there a subface need to be split together?
11056 tspivot(abcd, abcsh);
11057 if (abcsh.sh != dummysh) {
11058 // Exists! Keep the edge ab of both handles be the same.
11059 findedge(&abcsh, org(abcd), dest(abcd));
11060 }
11061 }
11062
11063 if (b->verbose > 1) {
11064 printf(" Inserting point %d on face (%d, %d, %d).\n", pointmark(newpoint),
11065 pointmark(pa), pointmark(pb), pointmark(pc));
11066 }
11067
11068 #ifdef SELF_CHECK
11069 // Make sure no inversed tetrahedron has been created.
11070 assert(orient3d(pa, pb, pd, newpoint) >= 0.0);
11071 assert(orient3d(pb, pc, pd, newpoint) >= 0.0);
11072 assert(orient3d(pc, pa, pd, newpoint) >= 0.0);
11073 #endif
11074
11075 // Save the old configuration at faces bcd and cad.
11076 enextfnext(abcd, oldbcd);
11077 enext2fnext(abcd, oldcad);
11078 sym(oldbcd, bcdcasing);
11079 sym(oldcad, cadcasing);
11080 // Create two new tetrahedra.
11081 maketetrahedron(&bcvd);
11082 maketetrahedron(&cavd);
11083 if (mirrorflag) {
11084 // Save the old configuration at faces bce and cae.
11085 enextfnext(bace, oldace);
11086 enext2fnext(bace, oldcbe);
11087 sym(oldace, acecasing);
11088 sym(oldcbe, cbecasing);
11089 // Create two new tetrahedra.
11090 maketetrahedron(&acve);
11091 maketetrahedron(&cbve);
11092 } else {
11093 // Splitting a boundary face increases the number of boundary faces.
11094 hullsize += 2;
11095 }
11096
11097 // Set vertices to the changed tetrahedron and new tetrahedra.
11098 abvd = abcd; // Update 'abcd' to 'abvd'.
11099 setapex(abvd, newpoint);
11100 setorg (bcvd, pb); // Set 'bcvd'.
11101 setdest(bcvd, pc);
11102 setapex(bcvd, newpoint);
11103 setoppo(bcvd, pd);
11104 setorg (cavd, pc); // Set 'cavd'.
11105 setdest(cavd, pa);
11106 setapex(cavd, newpoint);
11107 setoppo(cavd, pd);
11108 // Set the element attributes of the new tetrahedra.
11109 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
11110 attrib = elemattribute(abvd.tet, i);
11111 setelemattribute(bcvd.tet, i, attrib);
11112 setelemattribute(cavd.tet, i, attrib);
11113 }
11114 if (b->varvolume) {
11115 // Set the area constraint of the new tetrahedra.
11116 volume = volumebound(abvd.tet);
11117 setvolumebound(bcvd.tet, volume);
11118 setvolumebound(cavd.tet, volume);
11119 }
11120 if (mirrorflag) {
11121 bave = bace; // Update 'bace' to 'bave'.
11122 setapex(bave, newpoint);
11123 setorg (acve, pa); // Set 'acve'.
11124 setdest(acve, pc);
11125 setapex(acve, newpoint);
11126 setoppo(acve, pe);
11127 setorg (cbve, pc); // Set 'cbve'.
11128 setdest(cbve, pb);
11129 setapex(cbve, newpoint);
11130 setoppo(cbve, pe);
11131 // Set the element attributes of the new tetrahedra.
11132 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
11133 attrib = elemattribute(bave.tet, i);
11134 setelemattribute(acve.tet, i, attrib);
11135 setelemattribute(cbve.tet, i, attrib);
11136 }
11137 if (b->varvolume) {
11138 // Set the area constraint of the new tetrahedra.
11139 volume = volumebound(bave.tet);
11140 setvolumebound(acve.tet, volume);
11141 setvolumebound(cbve.tet, volume);
11142 }
11143 }
11144
11145 // Bond the new tetrahedra to the surrounding tetrahedra.
11146 bcvd.loc = 1;
11147 bond(bcvd, bcdcasing);
11148 cavd.loc = 1;
11149 bond(cavd, cadcasing);
11150 bcvd.loc = 3;
11151 bond(bcvd, oldbcd);
11152 cavd.loc = 2;
11153 bond(cavd, oldcad);
11154 bcvd.loc = 2;
11155 cavd.loc = 3;
11156 bond(bcvd, cavd);
11157 if (mirrorflag) {
11158 acve.loc = 1;
11159 bond(acve, acecasing);
11160 cbve.loc = 1;
11161 bond(cbve, cbecasing);
11162 acve.loc = 3;
11163 bond(acve, oldace);
11164 cbve.loc = 2;
11165 bond(cbve, oldcbe);
11166 acve.loc = 2;
11167 cbve.loc = 3;
11168 bond(acve, cbve);
11169 // Bond two new coplanar facets.
11170 bcvd.loc = 0;
11171 cbve.loc = 0;
11172 bond(bcvd, cbve);
11173 cavd.loc = 0;
11174 acve.loc = 0;
11175 bond(cavd, acve);
11176 }
11177
11178 // There may exist subface needed to be bonded to the new tetrahedra.
11179 if (checksubfaces) {
11180 tspivot(oldbcd, bcdsh);
11181 if (bcdsh.sh != dummysh) {
11182 tsdissolve(oldbcd);
11183 bcvd.loc = 1;
11184 tsbond(bcvd, bcdsh);
11185 }
11186 tspivot(oldcad, cadsh);
11187 if (cadsh.sh != dummysh) {
11188 tsdissolve(oldcad);
11189 cavd.loc = 1;
11190 tsbond(cavd, cadsh);
11191 }
11192 if (mirrorflag) {
11193 tspivot(oldace, acesh);
11194 if (acesh.sh != dummysh) {
11195 tsdissolve(oldace);
11196 acve.loc = 1;
11197 tsbond(acve, acesh);
11198 }
11199 tspivot(oldcbe, cbesh);
11200 if (cbesh.sh != dummysh) {
11201 tsdissolve(oldcbe);
11202 cbve.loc = 1;
11203 tsbond(cbve, cbesh);
11204 }
11205 }
11206 // Is there a subface needs to be split together?
11207 if (abcsh.sh != dummysh) {
11208 // Split this subface 'abc' into three i.e, abv, bcv, cav.
11209 splitsubface(newpoint, &abcsh, (queue *) NULL);
11210 }
11211 }
11212
11213 // Save a handle for quick point location.
11214 recenttet = abvd;
11215 // Set the return handle be abvd.
11216 *splittet = abvd;
11217
11218 bcvd.loc = 0;
11219 cavd.loc = 0;
11220 if (mirrorflag) {
11221 cbve.loc = 0;
11222 acve.loc = 0;
11223 }
11224 if (b->verbose > 3) {
11225 printf(" Updating abvd ");
11226 printtet(&abvd);
11227 printf(" Creating bcvd ");
11228 printtet(&bcvd);
11229 printf(" Creating cavd ");
11230 printtet(&cavd);
11231 if (mirrorflag) {
11232 printf(" Updating bave ");
11233 printtet(&bave);
11234 printf(" Creating cbve ");
11235 printtet(&cbve);
11236 printf(" Creating acve ");
11237 printtet(&acve);
11238 }
11239 }
11240
11241 if (flipqueue != (queue *) NULL) {
11242 fnextself(abvd);
11243 enqueueflipface(abvd, flipqueue);
11244 fnextself(bcvd);
11245 enqueueflipface(bcvd, flipqueue);
11246 fnextself(cavd);
11247 enqueueflipface(cavd, flipqueue);
11248 if (mirrorflag) {
11249 fnextself(bave);
11250 enqueueflipface(bave, flipqueue);
11251 fnextself(cbve);
11252 enqueueflipface(cbve, flipqueue);
11253 fnextself(acve);
11254 enqueueflipface(acve, flipqueue);
11255 }
11256 }
11257 }
11258
11259 ///////////////////////////////////////////////////////////////////////////////
11260 // //
11261 // unsplittetface() Reverse the operation of inserting a point on a face, //
11262 // so as to remove the newly inserted point. //
11263 // //
11264 // Assume the original face is abc, the tetrahedron containing abc is abcd. //
11265 // If abc is not a hull face, bace is the tetrahedron at the opposite of d. //
11266 // After face abc was split by a point v, tetrahedron abcd had been split //
11267 // into three tetrahedra, abvd, bcvd, cavd, and bace (if it exists) had been //
11268 // split into bave, cbve, acve. 'splittet' represents abvd (its apex is v). //
11269 // //
11270 // Point v is removed by expanding abvd to abcd, deleting two tetrahedra //
11271 // bcvd, cavd. Expanding bave(if it exists) to bace, deleting two tetrahedra //
11272 // cbve, acve. If abv is a subface, routine unsplitsubface() will be called //
11273 // to reverse the operation of splitting a subface. On completion, point v //
11274 // is not deleted in this routine. //
11275 // //
11276 ///////////////////////////////////////////////////////////////////////////////
11277
11278 void tetgenmesh::unsplittetface(triface* splittet)
11279 {
11280 triface abvd, bcvd, cavd, bave, cbve, acve;
11281 triface oldbvd, oldvad, oldvbe, oldave;
11282 triface bcdcasing, cadcasing, cbecasing, acecasing;
11283 face bcdsh, cadsh, cbesh, acesh;
11284 face abvsh;
11285 bool mirrorflag;
11286
11287 abvd = *splittet;
11288 adjustedgering(abvd, CCW); // for sure.
11289 enextfnext(abvd, oldbvd);
11290 fnext(oldbvd, bcvd);
11291 esymself(bcvd);
11292 enextself(bcvd);
11293 enext2fnext(abvd, oldvad);
11294 fnext(oldvad, cavd);
11295 esymself(cavd);
11296 enext2self(cavd);
11297 // Is there a second tetrahedron?
11298 sym(abvd, bave);
11299 mirrorflag = bave.tet != dummytet;
11300 if (mirrorflag) {
11301 findedge(&bave, dest(abvd), org(abvd));
11302 enextfnext(bave, oldave);
11303 fnext(oldave, acve);
11304 esymself(acve);
11305 enextself(acve);
11306 enext2fnext(bave, oldvbe);
11307 fnext(oldvbe, cbve);
11308 esymself(cbve);
11309 enext2self(cbve);
11310 } else {
11311 // Unsplit a hull face decrease the number of boundary faces.
11312 hullsize -= 2;
11313 }
11314 // Is there a subface at abv.
11315 tspivot(abvd, abvsh);
11316 if (abvsh.sh != dummysh) {
11317 // Exists! Keep the edge ab of both handles be the same.
11318 findedge(&abvsh, org(abvd), dest(abvd));
11319 }
11320
11321 if (b->verbose > 1) {
11322 printf(" Removing point %d on face (%d, %d, %d).\n",
11323 pointmark(apex(abvd)), pointmark(org(abvd)), pointmark(dest(abvd)),
11324 pointmark(dest(bcvd)));
11325 }
11326
11327 fnextself(bcvd); // bcvd has changed to bcdv.
11328 sym(bcvd, bcdcasing);
11329 tspivot(bcvd, bcdsh);
11330 fnextself(cavd); // cavd has changed to cadv.
11331 sym(cavd, cadcasing);
11332 tspivot(cavd, cadsh);
11333 if (mirrorflag) {
11334 fnextself(acve); // acve has changed to acev.
11335 sym(acve, acecasing);
11336 tspivot(acve, acesh);
11337 fnextself(cbve); // cbve has changed to cbev.
11338 sym(cbve, cbecasing);
11339 tspivot(cbve, cbesh);
11340 }
11341
11342 // Expand abvd to abcd.
11343 setapex(abvd, dest(bcvd));
11344 bond(oldbvd, bcdcasing);
11345 if (bcdsh.sh != dummysh) {
11346 tsbond(oldbvd, bcdsh);
11347 }
11348 bond(oldvad, cadcasing);
11349 if (cadsh.sh != dummysh) {
11350 tsbond(oldvad, cadsh);
11351 }
11352 if (mirrorflag) {
11353 // Expanding bave to bace.
11354 setapex(bave, dest(acve));
11355 bond(oldave, acecasing);
11356 if (acesh.sh != dummysh) {
11357 tsbond(oldave, acesh);
11358 }
11359 bond(oldvbe, cbecasing);
11360 if (cbesh.sh != dummysh) {
11361 tsbond(oldvbe, cbesh);
11362 }
11363 }
11364
11365 // Unsplit a subface if there exists.
11366 if (abvsh.sh != dummysh) {
11367 unsplitsubface(&abvsh);
11368 }
11369
11370 // Delete the split-out tetrahedra.
11371 tetrahedrondealloc(bcvd.tet);
11372 tetrahedrondealloc(cavd.tet);
11373 if (mirrorflag) {
11374 tetrahedrondealloc(acve.tet);
11375 tetrahedrondealloc(cbve.tet);
11376 }
11377 }
11378
11379 ///////////////////////////////////////////////////////////////////////////////
11380 // //
11381 // splitsubface() Insert a point on a subface, split it into three. //
11382 // //
11383 // The subface is 'splitface'. Let it is abc. The inserting point 'newpoint'//
11384 // v should lie inside abc. If the neighbor tetrahedra of abc exist, i.e., //
11385 // abcd and bace, they should have been split by routine splittetface() //
11386 // before calling this routine, so the connection between the new tetrahedra //
11387 // and new subfaces can be correctly set. //
11388 // //
11389 // To split subface abc by point v is to shrink abc to abv, create two new //
11390 // subfaces bcv and cav. Set the connection between updated and new created //
11391 // subfaces. If there is a subsegment at edge bc or ca, connection of new //
11392 // subface (bcv or cav) to its casing subfaces is a face link, 'casingin' is //
11393 // the predecessor and 'casingout' is the successor. It is important to keep //
11394 // the orientations of the edge rings of the updated and created subfaces be //
11395 // the same as abc's. So they have the same orientation as other subfaces of //
11396 // this facet with respect to the lift point of this facet. //
11397 // //
11398 // On completion, 'splitface' returns abv. If 'flipqueue' is not NULL, it //
11399 // returns all possibly non-Delaunay edges. //
11400 // //
11401 ///////////////////////////////////////////////////////////////////////////////
11402
11403 void tetgenmesh::
11404 splitsubface(point newpoint, face* splitface, queue* flipqueue)
11405 {
11406 triface abvd, bcvd, cavd, bave, cbve, acve;
11407 face abc, oldbc, oldca, bc, ca, spinsh;
11408 face bccasin, bccasout, cacasin, cacasout;
11409 face abv, bcv, cav;
11410 point pa, pb, pc;
11411
11412 abc = *splitface;
11413 // The newly created subfaces will have the same edge ring as abc.
11414 adjustedgering(abc, CCW);
11415 pa = sorg(abc);
11416 pb = sdest(abc);
11417 pc = sapex(abc);
11418
11419 if (b->verbose > 1) {
11420 printf(" Inserting point %d on subface (%d, %d, %d).\n",
11421 pointmark(newpoint), pointmark(pa), pointmark(pb), pointmark(pc));
11422 }
11423
11424 // Save the old configuration at edge bc and ca. Subsegments may appear
11425 // at both sides, save the face links and dissolve them.
11426 senext(abc, oldbc);
11427 senext2(abc, oldca);
11428 spivot(oldbc, bccasout);
11429 sspivot(oldbc, bc);
11430 if (bc.sh != dummysh) {
11431 if (oldbc.sh != bccasout.sh) {
11432 // 'oldbc' is not self-bonded.
11433 spinsh = bccasout;
11434 do {
11435 bccasin = spinsh;
11436 spivotself(spinsh);
11437 } while (spinsh.sh != oldbc.sh);
11438 } else {
11439 bccasout.sh = dummysh;
11440 }
11441 ssdissolve(oldbc);
11442 }
11443 spivot(oldca, cacasout);
11444 sspivot(oldca, ca);
11445 if (ca.sh != dummysh) {
11446 if (oldca.sh != cacasout.sh) {
11447 // 'oldca' is not self-bonded.
11448 spinsh = cacasout;
11449 do {
11450 cacasin = spinsh;
11451 spivotself(spinsh);
11452 } while (spinsh.sh != oldca.sh);
11453 } else {
11454 cacasout.sh = dummysh;
11455 }
11456 ssdissolve(oldca);
11457 }
11458 // Create two new subfaces.
11459 makeshellface(subfaces, &bcv);
11460 makeshellface(subfaces, &cav);
11461
11462 // Set the vertices of changed and new subfaces.
11463 abv = abc; // Update 'abc' to 'abv'.
11464 setsapex(abv, newpoint);
11465 setsorg(bcv, pb); // Set 'bcv'.
11466 setsdest(bcv, pc);
11467 setsapex(bcv, newpoint);
11468 setsorg(cav, pc); // Set 'cav'.
11469 setsdest(cav, pa);
11470 setsapex(cav, newpoint);
11471 if (b->quality && varconstraint) {
11472 // Copy yhr area bound into the new subfaces.
11473 setareabound(bcv, areabound(abv));
11474 setareabound(cav, areabound(abv));
11475 }
11476 // Copy the boundary mark into the new subfaces.
11477 setshellmark(bcv, shellmark(abv));
11478 setshellmark(cav, shellmark(abv));
11479 // Copy the subface type into the new subfaces.
11480 setshelltype(bcv, shelltype(abv));
11481 setshelltype(cav, shelltype(abv));
11482 if (checkpbcs) {
11483 // Copy the pbcgroup into the new subfaces.
11484 setshellpbcgroup(bcv, shellpbcgroup(abv));
11485 setshellpbcgroup(cav, shellpbcgroup(abv));
11486 }
11487 // Bond the new subfaces to the surrounding subfaces.
11488 if (bc.sh != dummysh) {
11489 if (bccasout.sh != dummysh) {
11490 sbond1(bccasin, bcv);
11491 sbond1(bcv, bccasout);
11492 } else {
11493 // Bond 'bcv' to itsself.
11494 sbond(bcv, bcv);
11495 }
11496 ssbond(bcv, bc);
11497 } else {
11498 sbond(bcv, bccasout);
11499 }
11500 if (ca.sh != dummysh) {
11501 if (cacasout.sh != dummysh) {
11502 sbond1(cacasin, cav);
11503 sbond1(cav, cacasout);
11504 } else {
11505 // Bond 'cav' to itself.
11506 sbond(cav, cav);
11507 }
11508 ssbond(cav, ca);
11509 } else {
11510 sbond(cav, cacasout);
11511 }
11512 senext2self(bcv);
11513 sbond(bcv, oldbc);
11514 senextself(cav);
11515 sbond(cav, oldca);
11516 senext2self(bcv);
11517 senextself(cav);
11518 sbond(bcv, cav);
11519
11520 // Bond the new subfaces to the new tetrahedra if they exist.
11521 stpivot(abv, abvd);
11522 if (abvd.tet != dummytet) {
11523 // Get two new tetrahedra and their syms.
11524 findedge(&abvd, sorg(abv), sdest(abv));
11525 enextfnext(abvd, bcvd);
11526 #ifdef SELF_CHECK
11527 assert(bcvd.tet != dummytet);
11528 #endif
11529 fnextself(bcvd);
11530 enext2fnext(abvd, cavd);
11531 #ifdef SELF_CHECK
11532 assert(cavd.tet != dummytet);
11533 #endif
11534 fnextself(cavd);
11535 // Bond two new subfaces to the two new tetrahedra.
11536 tsbond(bcvd, bcv);
11537 tsbond(cavd, cav);
11538 }
11539 // Set the connection at the other sides if the tetrahedra exist.
11540 sesymself(abv); // bav
11541 stpivot(abv, bave);
11542 if (bave.tet != dummytet) {
11543 sesymself(bcv); // cbv
11544 sesymself(cav); // acv
11545 // Get two new tetrahedra and their syms.
11546 findedge(&bave, sorg(abv), sdest(abv));
11547 enextfnext(bave, acve);
11548 #ifdef SELF_CHECK
11549 assert(acve.tet != dummytet);
11550 #endif
11551 fnextself(acve);
11552 enext2fnext(bave, cbve);
11553 #ifdef SELF_CHECK
11554 assert(cbve.tet != dummytet);
11555 #endif
11556 fnextself(cbve);
11557 // Bond two new subfaces to the two new tetrahedra.
11558 tsbond(acve, cav);
11559 tsbond(cbve, bcv);
11560 }
11561
11562 bcv.shver = 0;
11563 cav.shver = 0;
11564 if (b->verbose > 3) {
11565 printf(" Updating abv ");
11566 printsh(&abv);
11567 printf(" Creating bcv ");
11568 printsh(&bcv);
11569 printf(" Creating cav ");
11570 printsh(&cav);
11571 }
11572
11573 if (flipqueue != (queue *) NULL) {
11574 enqueueflipedge(abv, flipqueue);
11575 enqueueflipedge(bcv, flipqueue);
11576 enqueueflipedge(cav, flipqueue);
11577 }
11578
11579 // Set the return handle be abv.
11580 *splitface = abv;
11581 }
11582
11583 ///////////////////////////////////////////////////////////////////////////////
11584 // //
11585 // unsplitsubface() Reverse the operation of inserting a point on a //
11586 // subface, so as to remove the newly inserted point. //
11587 // //
11588 // Assume the original subface is abc, it was split by a point v into three //
11589 // subfaces abv, bcv and cav. 'splitsh' represents abv. //
11590 // //
11591 // To remove point v is to expand abv to abc, delete bcv and cav. If edge bc //
11592 // or ca is a subsegment, the connection at a subsegment is a subface link, //
11593 // '-casin' and '-casout' are used to save the predecessor and successor of //
11594 // bcv or cav. On completion, point v is not deleted in this routine. //
11595 // //
11596 ///////////////////////////////////////////////////////////////////////////////
11597
11598 void tetgenmesh::unsplitsubface(face* splitsh)
11599 {
11600 face abv, bcv, cav;
11601 face oldbv, oldva, bc, ca, spinsh;
11602 face bccasin, bccasout, cacasin, cacasout;
11603
11604 abv = *splitsh;
11605 senext(abv, oldbv);
11606 spivot(oldbv, bcv);
11607 if (sorg(bcv) != sdest(oldbv)) {
11608 sesymself(bcv);
11609 }
11610 senextself(bcv);
11611 senext2(abv, oldva);
11612 spivot(oldva, cav);
11613 if (sorg(cav) != sdest(oldva)) {
11614 sesymself(cav);
11615 }
11616 senext2self(cav);
11617
11618 if (b->verbose > 1) {
11619 printf(" Removing point %d on subface (%d, %d, %d).\n",
11620 pointmark(sapex(abv)), pointmark(sorg(abv)), pointmark(sdest(abv)),
11621 pointmark(sdest(bcv)));
11622 }
11623
11624 spivot(bcv, bccasout);
11625 sspivot(bcv, bc);
11626 if (bc.sh != dummysh) {
11627 if (bcv.sh != bccasout.sh) {
11628 // 'bcv' is not self-bonded.
11629 spinsh = bccasout;
11630 do {
11631 bccasin = spinsh;
11632 spivotself(spinsh);
11633 } while (spinsh.sh != bcv.sh);
11634 } else {
11635 bccasout.sh = dummysh;
11636 }
11637 }
11638 spivot(cav, cacasout);
11639 sspivot(cav, ca);
11640 if (ca.sh != dummysh) {
11641 if (cav.sh != cacasout.sh) {
11642 // 'cav' is not self-bonded.
11643 spinsh = cacasout;
11644 do {
11645 cacasin = spinsh;
11646 spivotself(spinsh);
11647 } while (spinsh.sh != cav.sh);
11648 } else {
11649 cacasout.sh = dummysh;
11650 }
11651 }
11652
11653 // Expand abv to abc.
11654 setsapex(abv, sdest(bcv));
11655 if (bc.sh != dummysh) {
11656 if (bccasout.sh != dummysh) {
11657 sbond1(bccasin, oldbv);
11658 sbond1(oldbv, bccasout);
11659 } else {
11660 // Bond 'oldbv' to itself.
11661 sbond(oldbv, oldbv);
11662 }
11663 ssbond(oldbv, bc);
11664 } else {
11665 sbond(oldbv, bccasout);
11666 }
11667 if (ca.sh != dummysh) {
11668 if (cacasout.sh != dummysh) {
11669 sbond1(cacasin, oldva);
11670 sbond1(oldva, cacasout);
11671 } else {
11672 // Bond 'oldva' to itself.
11673 sbond(oldva, oldva);
11674 }
11675 ssbond(oldva, ca);
11676 } else {
11677 sbond(oldva, cacasout);
11678 }
11679
11680 // Delete two split-out subfaces.
11681 shellfacedealloc(subfaces, bcv.sh);
11682 shellfacedealloc(subfaces, cav.sh);
11683 }
11684
11685 ///////////////////////////////////////////////////////////////////////////////
11686 // //
11687 // splittetedge() Insert a point on an edge of the mesh. //
11688 // //
11689 // The edge is given by 'splittet'. Assume its four corners are a, b, n1 and //
11690 // n2, where ab is the edge will be split. Around ab may exist any number of //
11691 // tetrahedra. For convenience, they're ordered in a sequence following the //
11692 // right-hand rule with your thumb points from a to b. Let the vertex set of //
11693 // these tetrahedra be {a, b, n1, n2, ..., n(i)}. NOTE the tetrahedra around //
11694 // ab may not connect to each other (can only happen when ab is a subsegment,//
11695 // hence some faces abn(i) are subfaces). If ab is a subsegment, abn1 must //
11696 // be a subface. //
11697 // //
11698 // To split edge ab by a point v is to split all tetrahedra containing ab by //
11699 // v. More specifically, for each such tetrahedron, an1n2b, it is shrunk to //
11700 // an1n2v, and a new tetrahedra bn2n1v is created. If ab is a subsegment, or //
11701 // some faces of the splitting tetrahedra are subfaces, they must be split //
11702 // either by calling routine 'splitsubedge()'. //
11703 // //
11704 // On completion, 'splittet' returns avn1n2. If 'flipqueue' is not NULL, it //
11705 // returns all faces which may become non-Delaunay after this operation. //
11706 // //
11707 ///////////////////////////////////////////////////////////////////////////////
11708
11709 void tetgenmesh::
11710 splittetedge(point newpoint, triface* splittet, queue* flipqueue)
11711 {
11712 triface *bots, *newtops;
11713 triface oldtop, topcasing;
11714 triface spintet, tmpbond0, tmpbond1;
11715 face abseg, splitsh, topsh, spinsh;
11716 point pa, pb, n1, n2;
11717 REAL attrib, volume;
11718 int wrapcount, hitbdry;
11719 int i, j;
11720
11721 if (checksubfaces) {
11722 // Is there a subsegment need to be split together?
11723 tsspivot(splittet, &abseg);
11724 if (abseg.sh != dummysh) {
11725 abseg.shver = 0;
11726 // Orient the edge direction of 'splittet' be abseg.
11727 if (org(*splittet) != sorg(abseg)) {
11728 esymself(*splittet);
11729 }
11730 }
11731 }
11732 spintet = *splittet;
11733 pa = org(spintet);
11734 pb = dest(spintet);
11735
11736 if (b->verbose > 1) {
11737 printf(" Inserting point %d on edge (%d, %d).\n",
11738 pointmark(newpoint), pointmark(pa), pointmark(pb));
11739 }
11740
11741 // Collect the tetrahedra containing the splitting edge (ab).
11742 n1 = apex(spintet);
11743 hitbdry = 0;
11744 wrapcount = 1;
11745 if (checksubfaces && abseg.sh != dummysh) {
11746 // It may happen that some tetrahedra containing ab (a subsegment) are
11747 // completely disconnected with others. If it happens, use the face
11748 // link of ab to cross the boundary.
11749 while (true) {
11750 if (!fnextself(spintet)) {
11751 // Meet a boundary, walk through it.
11752 hitbdry ++;
11753 tspivot(spintet, spinsh);
11754 #ifdef SELF_CHECK
11755 assert(spinsh.sh != dummysh);
11756 #endif
11757 findedge(&spinsh, pa, pb);
11758 sfnextself(spinsh);
11759 stpivot(spinsh, spintet);
11760 #ifdef SELF_CHECK
11761 assert(spintet.tet != dummytet);
11762 #endif
11763 findedge(&spintet, pa, pb);
11764 // Remember this position (hull face) in 'splittet'.
11765 *splittet = spintet;
11766 // Split two hull faces increase the hull size;
11767 hullsize += 2;
11768 }
11769 if (apex(spintet) == n1) break;
11770 wrapcount ++;
11771 }
11772 if (hitbdry > 0) {
11773 wrapcount -= hitbdry;
11774 }
11775 } else {
11776 // All the tetrahedra containing ab are connected together. If there
11777 // are subfaces, 'splitsh' keeps one of them.
11778 splitsh.sh = dummysh;
11779 while (hitbdry < 2) {
11780 if (checksubfaces && splitsh.sh == dummysh) {
11781 tspivot(spintet, splitsh);
11782 }
11783 if (fnextself(spintet)) {
11784 if (apex(spintet) == n1) break;
11785 wrapcount++;
11786 } else {
11787 hitbdry ++;
11788 if (hitbdry < 2) {
11789 esym(*splittet, spintet);
11790 }
11791 }
11792 }
11793 if (hitbdry > 0) {
11794 // ab is on the hull.
11795 wrapcount -= 1;
11796 // 'spintet' now is a hull face, inverse its edge direction.
11797 esym(spintet, *splittet);
11798 // Split two hull faces increases the number of hull faces.
11799 hullsize += 2;
11800 }
11801 }
11802
11803 // Make arrays of updating (bot, oldtop) and new (newtop) tetrahedra.
11804 bots = new triface[wrapcount];
11805 newtops = new triface[wrapcount];
11806 // Spin around ab, gather tetrahedra and set up new tetrahedra.
11807 spintet = *splittet;
11808 for (i = 0; i < wrapcount; i++) {
11809 // Get 'bots[i] = an1n2b'.
11810 enext2fnext(spintet, bots[i]);
11811 esymself(bots[i]);
11812 // Create 'newtops[i]'.
11813 maketetrahedron(&(newtops[i]));
11814 // Go to the next.
11815 fnextself(spintet);
11816 if (checksubfaces && abseg.sh != dummysh) {
11817 if (!issymexist(&spintet)) {
11818 // We meet a hull face, walk through it.
11819 tspivot(spintet, spinsh);
11820 #ifdef SELF_CHECK
11821 assert(spinsh.sh != dummysh);
11822 #endif
11823 findedge(&spinsh, pa, pb);
11824 sfnextself(spinsh);
11825 stpivot(spinsh, spintet);
11826 #ifdef SELF_CHECK
11827 assert(spintet.tet != dummytet);
11828 #endif
11829 findedge(&spintet, pa, pb);
11830 }
11831 }
11832 }
11833
11834 // Set the vertices of updated and new tetrahedra.
11835 for (i = 0; i < wrapcount; i++) {
11836 // Update 'bots[i] = an1n2v'.
11837 setoppo(bots[i], newpoint);
11838 // Set 'newtops[i] = bn2n1v'.
11839 n1 = dest(bots[i]);
11840 n2 = apex(bots[i]);
11841 // Set 'newtops[i]'.
11842 setorg(newtops[i], pb);
11843 setdest(newtops[i], n2);
11844 setapex(newtops[i], n1);
11845 setoppo(newtops[i], newpoint);
11846 // Set the element attributes of a new tetrahedron.
11847 for (j = 0; j < in->numberoftetrahedronattributes; j++) {
11848 attrib = elemattribute(bots[i].tet, j);
11849 setelemattribute(newtops[i].tet, j, attrib);
11850 }
11851 if (b->varvolume) {
11852 // Set the area constraint of a new tetrahedron.
11853 volume = volumebound(bots[i].tet);
11854 setvolumebound(newtops[i].tet, volume);
11855 }
11856 #ifdef SELF_CHECK
11857 // Make sure no inversed tetrahedron has been created.
11858 volume = orient3d(pa, n1, n2, newpoint);
11859 if (volume >= 0.0) {
11860 printf("Internal error in splittetedge(): volume = %.12g.\n", volume);
11861 }
11862 volume = orient3d(pb, n2, n1, newpoint);
11863 if (volume >= 0.0) {
11864 printf("Internal error in splittetedge(): volume = %.12g.\n", volume);
11865 }
11866 #endif
11867 }
11868
11869 // Bond newtops to topcasings and bots.
11870 for (i = 0; i < wrapcount; i++) {
11871 // Get 'oldtop = n1n2va' from 'bots[i]'.
11872 enextfnext(bots[i], oldtop);
11873 sym(oldtop, topcasing);
11874 bond(newtops[i], topcasing);
11875 if (checksubfaces) {
11876 tspivot(oldtop, topsh);
11877 if (topsh.sh != dummysh) {
11878 tsdissolve(oldtop);
11879 tsbond(newtops[i], topsh);
11880 }
11881 }
11882 enextfnext(newtops[i], tmpbond0);
11883 bond(oldtop, tmpbond0);
11884 }
11885 // Bond between newtops.
11886 fnext(newtops[0], tmpbond0);
11887 enext2fnext(bots[0], spintet);
11888 for (i = 1; i < wrapcount; i ++) {
11889 if (issymexist(&spintet)) {
11890 enext2fnext(newtops[i], tmpbond1);
11891 bond(tmpbond0, tmpbond1);
11892 }
11893 fnext(newtops[i], tmpbond0);
11894 enext2fnext(bots[i], spintet);
11895 }
11896 // Bond the last to the first if no boundary.
11897 if (issymexist(&spintet)) {
11898 enext2fnext(newtops[0], tmpbond1);
11899 bond(tmpbond0, tmpbond1);
11900 }
11901
11902 // Is there exist subfaces and subsegment need to be split?
11903 if (checksubfaces) {
11904 if (abseg.sh != dummysh) {
11905 // A subsegment needs be split.
11906 spivot(abseg, splitsh);
11907 #ifdef SELF_CHECK
11908 assert(splitsh.sh != dummysh);
11909 #endif
11910 }
11911 if (splitsh.sh != dummysh) {
11912 // Split subfaces (and subsegment).
11913 findedge(&splitsh, pa, pb);
11914 splitsubedge(newpoint, &splitsh, (queue *) NULL);
11915 }
11916 }
11917
11918 if (b->verbose > 3) {
11919 for (i = 0; i < wrapcount; i++) {
11920 printf(" Updating bots[%i] ", i);
11921 printtet(&(bots[i]));
11922 printf(" Creating newtops[%i] ", i);
11923 printtet(&(newtops[i]));
11924 }
11925 }
11926
11927 if (flipqueue != (queue *) NULL) {
11928 for (i = 0; i < wrapcount; i++) {
11929 enqueueflipface(bots[i], flipqueue);
11930 enqueueflipface(newtops[i], flipqueue);
11931 }
11932 }
11933
11934 // Set the return handle be avn1n2. It is got by transforming from
11935 // 'bots[0]' (which is an1n2v).
11936 fnext(bots[0], spintet); // spintet is an1vn2.
11937 esymself(spintet); // spintet is n1avn2.
11938 enextself(spintet); // spintet is avn1n2.
11939 *splittet = spintet;
11940
11941 delete [] bots;
11942 delete [] newtops;
11943 }
11944
11945 ///////////////////////////////////////////////////////////////////////////////
11946 // //
11947 // unsplittetedge() Reverse the operation of splitting an edge, so as to //
11948 // remove the newly inserted point. //
11949 // //
11950 // Assume the original edge is ab, the tetrahedron containing ab is abn1n2. //
11951 // After ab was split by a point v, every tetrahedron containing ab (e.g., //
11952 // abn1n2) has been split into two (e.g., an1n2v and bn2n1v). 'splittet' //
11953 // represents avn1n2 (i.e., its destination is v). //
11954 // //
11955 // To remove point v is to expand each split tetrahedron containing ab (e.g.,//
11956 // (avn1n2 to abn1n2), then delete the redundant one(e.g., vbn1n2). If there //
11957 // exists any subface around ab, routine unsplitsubedge() will be called to //
11958 // reverse the operation of splitting a edge (or a subsegment) of subfaces. //
11959 // On completion, point v is not deleted in this routine. //
11960 // //
11961 ///////////////////////////////////////////////////////////////////////////////
11962
11963 void tetgenmesh::unsplittetedge(triface* splittet)
11964 {
11965 triface *bots, *newtops;
11966 triface oldtop, topcasing;
11967 triface spintet;
11968 face avseg, splitsh, topsh, spinsh;
11969 point pa, pv, n1;
11970 int wrapcount, hitbdry;
11971 int i;
11972
11973 spintet = *splittet;
11974 pa = org(spintet);
11975 pv = dest(spintet);
11976 if (checksubfaces) {
11977 // Is there a subsegment need to be unsplit together?
11978 tsspivot(splittet, &avseg);
11979 if (avseg.sh != dummysh) {
11980 // The subsegment's direction should conform to 'splittet'.
11981 if (sorg(avseg) != pa) {
11982 sesymself(avseg);
11983 }
11984 }
11985 }
11986
11987 n1 = apex(spintet);
11988 hitbdry = 0;
11989 wrapcount = 1;
11990 if (checksubfaces && avseg.sh != dummysh) {
11991 // It may happen that some tetrahedra containing ab (a subsegment) are
11992 // completely disconnected with others. If it happens, use the face
11993 // link of ab to cross the boundary.
11994 while (true) {
11995 if (!fnextself(spintet)) {
11996 // Meet a boundary, walk through it.
11997 hitbdry ++;
11998 tspivot(spintet, spinsh);
11999 #ifdef SELF_CHECK
12000 assert(spinsh.sh != dummysh);
12001 #endif
12002 findedge(&spinsh, pa, pv);
12003 sfnextself(spinsh);
12004 stpivot(spinsh, spintet);
12005 #ifdef SELF_CHECK
12006 assert(spintet.tet != dummytet);
12007 #endif
12008 findedge(&spintet, pa, pv);
12009 // Remember this position (hull face) in 'splittet'.
12010 *splittet = spintet;
12011 // Split two hull faces increase the hull size;
12012 hullsize += 2;
12013 }
12014 if (apex(spintet) == n1) break;
12015 wrapcount ++;
12016 }
12017 if (hitbdry > 0) {
12018 wrapcount -= hitbdry;
12019 }
12020 } else {
12021 // All the tetrahedra containing ab are connected together. If there
12022 // are subfaces, 'splitsh' keeps one of them.
12023 splitsh.sh = dummysh;
12024 while (hitbdry < 2) {
12025 if (checksubfaces && splitsh.sh == dummysh) {
12026 tspivot(spintet, splitsh);
12027 }
12028 if (fnextself(spintet)) {
12029 if (apex(spintet) == n1) break;
12030 wrapcount++;
12031 } else {
12032 hitbdry ++;
12033 if (hitbdry < 2) {
12034 esym(*splittet, spintet);
12035 }
12036 }
12037 }
12038 if (hitbdry > 0) {
12039 // ab is on the hull.
12040 wrapcount -= 1;
12041 // 'spintet' now is a hull face, inverse its edge direction.
12042 esym(spintet, *splittet);
12043 // Split two hull faces increases the number of hull faces.
12044 hullsize += 2;
12045 }
12046 }
12047
12048 // Make arrays of updating (bot, oldtop) and new (newtop) tetrahedra.
12049 bots = new triface[wrapcount];
12050 newtops = new triface[wrapcount];
12051 // Spin around av, gather tetrahedra and set up new tetrahedra.
12052 spintet = *splittet;
12053 for (i = 0; i < wrapcount; i++) {
12054 // Get 'bots[i] = an1n2v'.
12055 enext2fnext(spintet, bots[i]);
12056 esymself(bots[i]);
12057 // Get 'oldtop = n1n2va'.
12058 enextfnext(bots[i], oldtop);
12059 // Get 'newtops[i] = 'bn1n2v'
12060 fnext(oldtop, newtops[i]); // newtop = n1n2bv
12061 esymself(newtops[i]); // newtop = n2n1bv
12062 enext2self(newtops[i]); // newtop = bn2n1v
12063 // Go to the next.
12064 fnextself(spintet);
12065 if (checksubfaces && avseg.sh != dummysh) {
12066 if (!issymexist(&spintet)) {
12067 // We meet a hull face, walk through it.
12068 tspivot(spintet, spinsh);
12069 #ifdef SELF_CHECK
12070 assert(spinsh.sh != dummysh);
12071 #endif
12072 findedge(&spinsh, pa, pv);
12073 sfnextself(spinsh);
12074 stpivot(spinsh, spintet);
12075 #ifdef SELF_CHECK
12076 assert(spintet.tet != dummytet);
12077 #endif
12078 findedge(&spintet, pa, pv);
12079 }
12080 }
12081 }
12082
12083 if (b->verbose > 1) {
12084 printf(" Removing point %d from edge (%d, %d).\n",
12085 pointmark(oppo(bots[0])), pointmark(org(bots[0])),
12086 pointmark(org(newtops[0])));
12087 }
12088
12089 for (i = 0; i < wrapcount; i++) {
12090 // Expand an1n2v to an1n2b.
12091 setoppo(bots[i], org(newtops[i]));
12092 // Get 'oldtop = n1n2va' from 'bot[i]'.
12093 enextfnext(bots[i], oldtop);
12094 // Get 'topcasing' from 'newtop[i]'
12095 sym(newtops[i], topcasing);
12096 // Bond them.
12097 bond(oldtop, topcasing);
12098 if (checksubfaces) {
12099 tspivot(newtops[i], topsh);
12100 if (topsh.sh != dummysh) {
12101 tsbond(oldtop, topsh);
12102 }
12103 }
12104 // Delete the tetrahedron above an1n2v.
12105 tetrahedrondealloc(newtops[i].tet);
12106 }
12107
12108 // If there exists any subface, unsplit them.
12109 if (checksubfaces) {
12110 if (avseg.sh != dummysh) {
12111 spivot(avseg, splitsh);
12112 #ifdef SELF_CHECK
12113 assert(splitsh.sh != dummysh);
12114 #endif
12115 }
12116 if (splitsh.sh != dummysh) {
12117 findedge(&splitsh, pa, pv);
12118 unsplitsubedge(&splitsh);
12119 }
12120 }
12121
12122 delete [] bots;
12123 delete [] newtops;
12124 }
12125
12126 ///////////////////////////////////////////////////////////////////////////////
12127 // //
12128 // splitsubedge() Insert a point on an edge of the surface mesh. //
12129 // //
12130 // The splitting edge is given by 'splitsh'. Assume its three corners are a, //
12131 // b, c, where ab is the edge will be split. ab may be a subsegment. //
12132 // //
12133 // To split edge ab is to split all subfaces conatining ab. If ab is not a //
12134 // subsegment, there are only two subfaces need be split, otherwise, there //
12135 // may have any number of subfaces need be split. Each splitting subface abc //
12136 // is shrunk to avc, a new subface vbc is created. It is important to keep //
12137 // the orientations of edge rings of avc and vbc be the same as abc's. If ab //
12138 // is a subsegment, it is shrunk to av and a new subsegment vb is created. //
12139 // //
12140 // If there are tetrahedra adjoining to the splitting subfaces, they should //
12141 // be split before calling this routine, so the connection between the new //
12142 // tetrahedra and the new subfaces can be correctly set. //
12143 // //
12144 // On completion, 'splitsh' returns avc. If 'flipqueue' is not NULL, it //
12145 // returns all edges which may be non-Delaunay. //
12146 // //
12147 ///////////////////////////////////////////////////////////////////////////////
12148
12149 void tetgenmesh::splitsubedge(point newpoint, face* splitsh, queue* flipqueue)
12150 {
12151 triface abcd, bace, vbcd, bvce;
12152 face startabc, spinabc, spinsh;
12153 face oldbc, bccasin, bccasout;
12154 face ab, bc;
12155 face avc, vbc, vbc1;
12156 face av, vb;
12157 point pa, pb;
12158
12159 startabc = *splitsh;
12160 // Is there a subsegment?
12161 sspivot(startabc, ab);
12162 if (ab.sh != dummysh) {
12163 ab.shver = 0;
12164 if (sorg(startabc) != sorg(ab)) {
12165 sesymself(startabc);
12166 }
12167 }
12168 pa = sorg(startabc);
12169 pb = sdest(startabc);
12170
12171 if (b->verbose > 1) {
12172 printf(" Inserting point %d on subedge (%d, %d) %s.\n",
12173 pointmark(newpoint), pointmark(pa), pointmark(pb),
12174 (ab.sh != dummysh ? "(seg)" : " "));
12175 }
12176
12177 // Spin arround ab, split every subface containing ab.
12178 spinabc = startabc;
12179 do {
12180 // Adjust spinabc be edge ab.
12181 if (sorg(spinabc) != pa) {
12182 sesymself(spinabc);
12183 }
12184 // Save old configuration at edge bc, if bc has a subsegment, save the
12185 // face link of it and dissolve it from bc.
12186 senext(spinabc, oldbc);
12187 spivot(oldbc, bccasout);
12188 sspivot(oldbc, bc);
12189 if (bc.sh != dummysh) {
12190 if (spinabc.sh != bccasout.sh) {
12191 // 'spinabc' is not self-bonded.
12192 spinsh = bccasout;
12193 do {
12194 bccasin = spinsh;
12195 spivotself(spinsh);
12196 } while (spinsh.sh != oldbc.sh);
12197 } else {
12198 bccasout.sh = dummysh;
12199 }
12200 ssdissolve(oldbc);
12201 }
12202 // Create a new subface.
12203 makeshellface(subfaces, &vbc);
12204 // Split abc.
12205 avc = spinabc; // Update 'abc' to 'avc'.
12206 setsdest(avc, newpoint);
12207 // Make 'vbc' be in the same edge ring as 'avc'.
12208 vbc.shver = avc.shver;
12209 setsorg(vbc, newpoint); // Set 'vbc'.
12210 setsdest(vbc, pb);
12211 setsapex(vbc, sapex(avc));
12212 if (b->quality && varconstraint) {
12213 // Copy the area bound into the new subface.
12214 setareabound(vbc, areabound(avc));
12215 }
12216 // Copy the shell marker and shell type into the new subface.
12217 setshellmark(vbc, shellmark(avc));
12218 setshelltype(vbc, shelltype(avc));
12219 if (checkpbcs) {
12220 // Copy the pbcgroup into the new subface.
12221 setshellpbcgroup(vbc, shellpbcgroup(avc));
12222 }
12223 // Set the connection between updated and new subfaces.
12224 senext2self(vbc);
12225 sbond(vbc, oldbc);
12226 // Set the connection between new subface and casings.
12227 senext2self(vbc);
12228 if (bc.sh != dummysh) {
12229 if (bccasout.sh != dummysh) {
12230 // Insert 'vbc' into face link.
12231 sbond1(bccasin, vbc);
12232 sbond1(vbc, bccasout);
12233 } else {
12234 // Bond 'vbc' to itself.
12235 sbond(vbc, vbc);
12236 }
12237 ssbond(vbc, bc);
12238 } else {
12239 sbond(vbc, bccasout);
12240 }
12241 // Go to next subface at edge ab.
12242 spivotself(spinabc);
12243 if (spinabc.sh == dummysh) {
12244 break; // 'ab' is a hull edge.
12245 }
12246 } while (spinabc.sh != startabc.sh);
12247
12248 // Get the new subface vbc above the updated subface avc (= startabc).
12249 senext(startabc, oldbc);
12250 spivot(oldbc, vbc);
12251 if (sorg(vbc) == newpoint) {
12252 sesymself(vbc);
12253 }
12254 #ifdef SELF_CHECK
12255 assert(sorg(vbc) == sdest(oldbc) && sdest(vbc) == sorg(oldbc));
12256 #endif
12257 senextself(vbc);
12258 // Set the face link for the new created subfaces around edge vb.
12259 spinabc = startabc;
12260 do {
12261 // Go to the next subface at edge av.
12262 spivotself(spinabc);
12263 if (spinabc.sh == dummysh) {
12264 break; // 'ab' is a hull edge.
12265 }
12266 if (sorg(spinabc) != pa) {
12267 sesymself(spinabc);
12268 }
12269 // Get the new subface vbc1 above the updated subface avc (= spinabc).
12270 senext(spinabc, oldbc);
12271 spivot(oldbc, vbc1);
12272 if (sorg(vbc1) == newpoint) {
12273 sesymself(vbc1);
12274 }
12275 #ifdef SELF_CHECK
12276 assert(sorg(vbc1) == sdest(oldbc) && sdest(vbc1) == sorg(oldbc));
12277 #endif
12278 senextself(vbc1);
12279 // Set the connection: vbc->vbc1.
12280 sbond1(vbc, vbc1);
12281 // For the next connection.
12282 vbc = vbc1;
12283 } while (spinabc.sh != startabc.sh);
12284
12285 // Split ab if it is a subsegment.
12286 if (ab.sh != dummysh) {
12287 // Update subsegment ab to av.
12288 av = ab;
12289 setsdest(av, newpoint);
12290 // Create a new subsegment vb.
12291 makeshellface(subsegs, &vb);
12292 setsorg(vb, newpoint);
12293 setsdest(vb, pb);
12294 // vb gets the same mark and segment type as av.
12295 setshellmark(vb, shellmark(av));
12296 setshelltype(vb, shelltype(av));
12297 if (b->quality && varconstraint) {
12298 // Copy the area bound into the new subsegment.
12299 setareabound(vb, areabound(av));
12300 }
12301 // Save the old connection at ab (re-use the handles oldbc, bccasout).
12302 senext(av, oldbc);
12303 spivot(oldbc, bccasout);
12304 // Bond av and vb (bonded at their "fake" edges).
12305 senext2(vb, bccasin);
12306 sbond(bccasin, oldbc);
12307 if (bccasout.sh != dummysh) {
12308 // There is a subsegment connecting with ab at b. It will connect
12309 // to vb at b after splitting.
12310 bccasout.shver = 0;
12311 #ifdef SELF_CHECK
12312 assert(sorg(bccasout) == pb);
12313 #endif
12314 senext2self(bccasout);
12315 senext(vb, bccasin);
12316 sbond(bccasin, bccasout);
12317 }
12318 // Bond all new subfaces (vbc) to vb.
12319 spinabc = startabc;
12320 do {
12321 // Adjust spinabc be edge av.
12322 if (sorg(spinabc) != pa) {
12323 sesymself(spinabc);
12324 }
12325 // Get new subface vbc above the updated subface avc (= spinabc).
12326 senext(spinabc, oldbc);
12327 spivot(oldbc, vbc);
12328 if (sorg(vbc) == newpoint) {
12329 sesymself(vbc);
12330 }
12331 senextself(vbc);
12332 // Bond the new subface and the new subsegment.
12333 ssbond(vbc, vb);
12334 // Go to the next.
12335 spivotself(spinabc);
12336 #ifdef SELF_CHECK
12337 assert(spinabc.sh != dummysh);
12338 #endif
12339 } while (spinabc.sh != startabc.sh);
12340 }
12341
12342 // Bond the new subfaces to new tetrahedra if they exist. New tetrahedra
12343 // should have been created before calling this routine.
12344 spinabc = startabc;
12345 do {
12346 // Adjust spinabc be edge av.
12347 if (sorg(spinabc) != pa) {
12348 sesymself(spinabc);
12349 }
12350 // Get new subface vbc above the updated subface avc (= spinabc).
12351 senext(spinabc, oldbc);
12352 spivot(oldbc, vbc);
12353 if (sorg(vbc) == newpoint) {
12354 sesymself(vbc);
12355 }
12356 senextself(vbc);
12357 // Get the adjacent tetrahedra at 'spinabc'.
12358 stpivot(spinabc, abcd);
12359 if (abcd.tet != dummytet) {
12360 findedge(&abcd, sorg(spinabc), sdest(spinabc));
12361 enextfnext(abcd, vbcd);
12362 fnextself(vbcd);
12363 #ifdef SELF_CHECK
12364 assert(vbcd.tet != dummytet);
12365 #endif
12366 tsbond(vbcd, vbc);
12367 sym(vbcd, bvce);
12368 sesymself(vbc);
12369 tsbond(bvce, vbc);
12370 } else {
12371 // One side is empty, check the other side.
12372 sesymself(spinabc);
12373 stpivot(spinabc, bace);
12374 if (bace.tet != dummytet) {
12375 findedge(&bace, sorg(spinabc), sdest(spinabc));
12376 enext2fnext(bace, bvce);
12377 fnextself(bvce);
12378 #ifdef SELF_CHECK
12379 assert(bvce.tet != dummytet);
12380 #endif
12381 sesymself(vbc);
12382 tsbond(bvce, vbc);
12383 }
12384 }
12385 // Go to the next.
12386 spivotself(spinabc);
12387 if (spinabc.sh == dummysh) {
12388 break; // 'ab' is a hull edge.
12389 }
12390 } while (spinabc.sh != startabc.sh);
12391
12392 if (b->verbose > 3) {
12393 spinabc = startabc;
12394 do {
12395 // Adjust spinabc be edge av.
12396 if (sorg(spinabc) != pa) {
12397 sesymself(spinabc);
12398 }
12399 printf(" Updating abc:\n");
12400 printsh(&spinabc);
12401 // Get new subface vbc above the updated subface avc (= spinabc).
12402 senext(spinabc, oldbc);
12403 spivot(oldbc, vbc);
12404 if (sorg(vbc) == newpoint) {
12405 sesymself(vbc);
12406 }
12407 senextself(vbc);
12408 printf(" Creating vbc:\n");
12409 printsh(&vbc);
12410 // Go to the next.
12411 spivotself(spinabc);
12412 if (spinabc.sh == dummysh) {
12413 break; // 'ab' is a hull edge.
12414 }
12415 } while (spinabc.sh != startabc.sh);
12416 }
12417
12418 if (flipqueue != (queue *) NULL) {
12419 spinabc = startabc;
12420 do {
12421 // Adjust spinabc be edge av.
12422 if (sorg(spinabc) != pa) {
12423 sesymself(spinabc);
12424 }
12425 senext2(spinabc, oldbc); // Re-use oldbc.
12426 enqueueflipedge(oldbc, flipqueue);
12427 // Get new subface vbc above the updated subface avc (= spinabc).
12428 senext(spinabc, oldbc);
12429 spivot(oldbc, vbc);
12430 if (sorg(vbc) == newpoint) {
12431 sesymself(vbc);
12432 }
12433 senextself(vbc);
12434 senext(vbc, oldbc); // Re-use oldbc.
12435 enqueueflipedge(oldbc, flipqueue);
12436 // Go to the next.
12437 spivotself(spinabc);
12438 if (spinabc.sh == dummysh) {
12439 break; // 'ab' is a hull edge.
12440 }
12441 } while (spinabc.sh != startabc.sh);
12442 }
12443 }
12444
12445 ///////////////////////////////////////////////////////////////////////////////
12446 // //
12447 // unsplitsubedge() Reverse the operation of splitting an edge of subface,//
12448 // so as to remove a point from the edge. //
12449 // //
12450 // Assume the original edge is ab, the subface containing it is abc. It was //
12451 // split by a point v into avc, and vbc. 'splitsh' represents avc, further- //
12452 // more, if av is a subsegment, av should be the zero version of the split //
12453 // subsegment (i.e., av.shver = 0), so we are sure that the destination (v) //
12454 // of both avc and av is the deleting point. //
12455 // //
12456 // To remove point v is to expand avc to abc, delete vbc, do the same for //
12457 // other subfaces containing av and vb. If av and vb are subsegments, expand //
12458 // av to ab, delete vb. On completion, point v is not deleted. //
12459 // //
12460 ///////////////////////////////////////////////////////////////////////////////
12461
12462 void tetgenmesh::unsplitsubedge(face* splitsh)
12463 {
12464 face startavc, spinavc, spinbcv;
12465 face oldvc, bccasin, bccasout, spinsh;
12466 face av, vb, bc;
12467 point pa, pv, pb;
12468
12469 startavc = *splitsh;
12470 sspivot(startavc, av);
12471 if (av.sh != dummysh) {
12472 // Orient the direction of subsegment to conform the subface.
12473 if (sorg(av) != sorg(startavc)) {
12474 sesymself(av);
12475 }
12476 #ifdef SELF_CHECK
12477 assert(av.shver == 0);
12478 #endif
12479 }
12480 senext(startavc, oldvc);
12481 spivot(oldvc, vb); // vb is subface vbc
12482 if (sorg(vb) != sdest(oldvc)) {
12483 sesymself(vb);
12484 }
12485 senextself(vb);
12486 pa = sorg(startavc);
12487 pv = sdest(startavc);
12488 pb = sdest(vb);
12489
12490 if (b->verbose > 1) {
12491 printf(" Removing point %d from subedge (%d, %d).\n",
12492 pointmark(pv), pointmark(pa), pointmark(pb));
12493 }
12494
12495 // Spin arround av, unsplit every subface containing av.
12496 spinavc = startavc;
12497 do {
12498 // Adjust spinavc be edge av.
12499 if (sorg(spinavc) != pa) {
12500 sesymself(spinavc);
12501 }
12502 // Save old configuration at edge bc, if bc has a subsegment, save the
12503 // face link of it.
12504 senext(spinavc, oldvc);
12505 spivot(oldvc, spinbcv);
12506 if (sorg(spinbcv) != sdest(oldvc)) {
12507 sesymself(spinbcv);
12508 }
12509 senext2self(spinbcv);
12510 spivot(spinbcv, bccasout);
12511 sspivot(spinbcv, bc);
12512 if (bc.sh != dummysh) {
12513 if (spinbcv.sh != bccasout.sh) {
12514 // 'spinbcv' is not self-bonded.
12515 spinsh = bccasout;
12516 do {
12517 bccasin = spinsh;
12518 spivotself(spinsh);
12519 } while (spinsh.sh != spinbcv.sh);
12520 } else {
12521 bccasout.sh = dummysh;
12522 }
12523 }
12524 // Expand avc to abc.
12525 setsdest(spinavc, pb);
12526 if (bc.sh != dummysh) {
12527 if (bccasout.sh != dummysh) {
12528 sbond1(bccasin, oldvc);
12529 sbond1(oldvc, bccasout);
12530 } else {
12531 // Bond 'oldbc' to itself.
12532 sbond(oldvc, oldvc);
12533 }
12534 ssbond(oldvc, bc);
12535 } else {
12536 sbond(oldvc, bccasout);
12537 }
12538 // Delete bcv.
12539 shellfacedealloc(subfaces, spinbcv.sh);
12540 // Go to next subface at edge av.
12541 spivotself(spinavc);
12542 if (spinavc.sh == dummysh) {
12543 break; // 'av' is a hull edge.
12544 }
12545 } while (spinavc.sh != startavc.sh);
12546
12547 // Is there a subsegment need to be unsplit?
12548 if (av.sh != dummysh) {
12549 senext(av, oldvc); // Re-use oldvc.
12550 spivot(oldvc, vb);
12551 vb.shver = 0;
12552 #ifdef SELF_CHECK
12553 assert(sdest(av) == sorg(vb));
12554 #endif
12555 senext(vb, spinbcv); // Re-use spinbcv.
12556 spivot(spinbcv, bccasout);
12557 // Expand av to ab.
12558 setsdest(av, pb);
12559 sbond(oldvc, bccasout);
12560 // Delete vb.
12561 shellfacedealloc(subsegs, vb.sh);
12562 }
12563 }
12564
12565 ///////////////////////////////////////////////////////////////////////////////
12566 // //
12567 // insertsite() Insert a point into the mesh. //
12568 // //
12569 // The 'newpoint' is located. If 'searchtet->tet' is not NULL, the search //
12570 // for the containing tetrahedron begins from 'searchtet', otherwise, a full //
12571 // point location procedure is called. If 'newpoint' is found inside a //
12572 // tetrahedron, the tetrahedron is split into four (by splittetrahedron()); //
12573 // if 'newpoint' lies on a face, the face is split into three, thereby //
12574 // splitting the two adjacent tetrahedra into six (by splittetface()); if //
12575 // 'newpoint' lies on an edge, the edge is split into two, thereby, every //
12576 // tetrahedron containing this edge is split into two. If 'newpoint' lies on //
12577 // an existing vertex, no action is taken, and the value DUPLICATEPOINT is //
12578 // returned and 'searchtet' is set to a handle whose origin is the vertex. //
12579 // //
12580 // If 'flipqueue' is not NULL, after 'newpoint' is inserted, it returns all //
12581 // faces which may become non-Delaunay due to the newly inserted point. Flip //
12582 // operations can be performed as necessary on them to maintain the Delaunay //
12583 // property. //
12584 // //
12585 ///////////////////////////////////////////////////////////////////////////////
12586
12587 enum tetgenmesh::insertsiteresult tetgenmesh::
12588 insertsite(point newpoint, triface* searchtet, bool approx, queue* flipqueue)
12589 {
12590 enum locateresult intersect, exactloc;
12591 point checkpt;
12592 REAL epspp, checklen;
12593 int count;
12594
12595 if (b->verbose > 1) {
12596 printf(" Insert point to mesh: (%.12g, %.12g, %.12g) %d.\n",
12597 newpoint[0], newpoint[1], newpoint[2], pointmark(newpoint));
12598 }
12599
12600 if (searchtet->tet == (tetrahedron *) NULL) {
12601 // Search for a tetrahedron containing 'newpoint'.
12602 searchtet->tet = dummytet;
12603 exactloc = locate(newpoint, searchtet);
12604 } else {
12605 // Start searching from the tetrahedron provided by the caller.
12606 exactloc = preciselocate(newpoint, searchtet, tetrahedrons->items);
12607 }
12608 intersect = exactloc;
12609 if (approx && (exactloc != ONVERTEX)) {
12610 // Adjust the exact location to an approx. location wrt. epsilon.
12611 epspp = b->epsilon;
12612 count = 0;
12613 while (count < 16) {
12614 intersect = adjustlocate(newpoint, searchtet, exactloc, epspp);
12615 if (intersect == ONVERTEX) {
12616 checkpt = org(*searchtet);
12617 checklen = distance(checkpt, newpoint);
12618 if (checklen / longest > b->epsilon) {
12619 epspp *= 1e-2;
12620 count++;
12621 continue;
12622 }
12623 }
12624 break;
12625 }
12626 }
12627 // Keep current search state for next searching.
12628 recenttet = *searchtet;
12629
12630 // Insert the point using the right routine
12631 switch (intersect) {
12632 case ONVERTEX:
12633 // There's already a vertex there. Return in 'searchtet' a tetrahedron
12634 // whose origin is the existing vertex.
12635 if (b->verbose > 1) {
12636 printf(" Not insert for duplicating point.\n");
12637 }
12638 return DUPLICATEPOINT;
12639
12640 case OUTSIDE:
12641 if (b->verbose > 1) {
12642 printf(" Not insert for locating outside the mesh.\n");
12643 }
12644 return OUTSIDEPOINT;
12645
12646 case ONEDGE:
12647 // 'newpoint' falls on an edge.
12648 splittetedge(newpoint, searchtet, flipqueue);
12649 return SUCCESSONEDGE;
12650
12651 case ONFACE:
12652 // 'newpoint' falls on a face.
12653 splittetface(newpoint, searchtet, flipqueue);
12654 return SUCCESSONFACE;
12655
12656 case INTETRAHEDRON:
12657 // 'newpoint' falls inside a tetrahedron.
12658 splittetrahedron(newpoint, searchtet, flipqueue);
12659 return SUCCESSINTET;
12660
12661 default:
12662 // Impossible case.
12663 return OUTSIDEPOINT;
12664 }
12665 }
12666
12667 ///////////////////////////////////////////////////////////////////////////////
12668 // //
12669 // undosite() Undo the most recently point insertion. //
12670 // //
12671 // 'insresult' indicates in where the newpoint has been inserted, i.e., in a //
12672 // tetrahedron, on a face, or on an edge. A correspoding routine will be //
12673 // called to undo the point insertion. 'splittet' is a handle represent one //
12674 // of the resulting tetrahedra, but it may be changed after transformation, //
12675 // even may be dead. Four points 'torg', ... 'toppo' are the corners which //
12676 // 'splittet' should have. On finish, 'newpoint' is not removed. //
12677 // //
12678 ///////////////////////////////////////////////////////////////////////////////
12679
12680 void tetgenmesh::
12681 undosite(enum insertsiteresult insresult, triface* splittet, point torg,
12682 point tdest, point tapex, point toppo)
12683 {
12684 // Set the four corners of 'splittet' exactly be 'torg', ... 'toppo'.
12685 findface(splittet, torg, tdest, tapex);
12686 if (oppo(*splittet) != toppo) {
12687 symself(*splittet);
12688 #ifdef SELF_CHECK
12689 assert(oppo(*splittet) == toppo);
12690 #endif
12691 // The sym() operation may inverse the edge, correct it if so.
12692 findedge(splittet, torg, tdest);
12693 }
12694
12695 // Unsplit the tetrahedron according to 'insresult'.
12696 switch (insresult) {
12697 case SUCCESSINTET:
12698 // 'splittet' should be the face with 'newpoint' as its opposite.
12699 unsplittetrahedron(splittet);
12700 break;
12701 case SUCCESSONFACE:
12702 // 'splittet' should be the one of three splitted face with 'newpoint'
12703 // as its apex.
12704 unsplittetface(splittet);
12705 break;
12706 case SUCCESSONEDGE:
12707 // 'splittet' should be the tet with destination is 'newpoint'.
12708 unsplittetedge(splittet);
12709 break;
12710 default: // To omit compile warnings.
12711 break;
12712 }
12713 }
12714
12715 ///////////////////////////////////////////////////////////////////////////////
12716 // //
12717 // Terminology: BC(p) and CBC(p), B(p) and C(p). //
12718 // //
12719 // Given an arbitrary point p, the Bowyer-Watson cavity BC(p) is formed by //
12720 // tets whose circumspheres containing p. The outer faces of BC(p) form a //
12721 // polyhedron B(p). //
12722 // //
12723 // If p is on a facet F, the constrained Bowyer-Watson cavity CBC(p) on F is //
12724 // formed by subfaces of F whose circumspheres containing p. The outer edges //
12725 // of CBC(p) form a polygon C(p). B(p) is separated into two parts by C(p), //
12726 // denoted as B_1(p) and B_2(p), one of them may be empty (F is on the hull).//
12727 // //
12728 // If p is on a segment S which is shared by n facets. There exist n C(p)s, //
12729 // each one is a non-closed polygon (without S). B(p) is split into n parts, //
12730 // each of them is denoted as B_i(p), some B_i(p) may be empty. //
12731 // //
12732 ///////////////////////////////////////////////////////////////////////////////
12733
12734 ///////////////////////////////////////////////////////////////////////////////
12735 // //
12736 // formbowatcavitysub() Form CBC(p) and C(p) on a facet F. //
12737 // //
12738 // Parameters: bp = p, bpseg = S, sublist = CBC(p), subceillist = C(p). //
12739 // //
12740 // CBC(p) contains at least one subface on input; S may be NULL which means //
12741 // that p is inside a facet. On output, all subfaces of CBC(p) are infected, //
12742 // and the edge rings are oriented to the same halfspace. //
12743 // //
12744 ///////////////////////////////////////////////////////////////////////////////
12745
12746 void tetgenmesh::formbowatcavitysub(point bp, face* bpseg, list* sublist,
12747 list* subceillist)
12748 {
12749 triface adjtet;
12750 face startsh, neighsh;
12751 face checkseg;
12752 point pa, pb, pc, pd;
12753 REAL sign;
12754 int i, j;
12755
12756 // Form CBC(p) and C(p) by a broadth-first searching.
12757 for (i = 0; i < sublist->len(); i++) {
12758 startsh = * (face *)(* sublist)[i]; // startsh = f.
12759 // Look for three neighbors of f.
12760 for (j = 0; j < 3; j++) {
12761 sspivot(startsh, checkseg);
12762 if (checkseg.sh == dummysh) {
12763 // Get its neighbor n.
12764 spivot(startsh, neighsh);
12765 // Is n already in CBC(p)?
12766 if (!sinfected(neighsh)) {
12767 stpivot(neighsh, adjtet);
12768 if (adjtet.tet == dummytet) {
12769 sesymself(neighsh);
12770 stpivot(neighsh, adjtet);
12771 }
12772 // For positive orientation that insphere() test requires.
12773 adjustedgering(adjtet, CW);
12774 pa = org(adjtet);
12775 pb = dest(adjtet);
12776 pc = apex(adjtet);
12777 pd = oppo(adjtet);
12778 sign = insphere(pa, pb, pc, pd, bp);
12779 if (sign >= 0.0) {
12780 // Orient edge ring of n according to that of f.
12781 if (sorg(neighsh) != sdest(startsh)) sesymself(neighsh);
12782 // Collect it into CBC(p).
12783 sinfect(neighsh);
12784 sublist->append(&neighsh);
12785 } else {
12786 subceillist->append(&startsh); // Found an edge of C(p).
12787 }
12788 }
12789 } else {
12790 // Do not cross a segment.
12791 if (bpseg != (face *) NULL) {
12792 if (checkseg.sh != bpseg->sh) {
12793 subceillist->append(&startsh); // Found an edge of C(p).
12794 }
12795 } else {
12796 subceillist->append(&startsh); // Found an edge of C(p).
12797 }
12798 }
12799 senextself(startsh);
12800 }
12801 }
12802
12803 if (b->verbose > 2) {
12804 printf(" Collect CBC(%d): %d subfaces, %d edges.\n", pointmark(bp),
12805 sublist->len(), subceillist->len());
12806 }
12807 }
12808
12809 ///////////////////////////////////////////////////////////////////////////////
12810 // //
12811 // formbowatcavityquad() Form BC_i(p) and B_i(p) in a quadrant. //
12812 // //
12813 // Parameters: bp = p, tetlist = BC_i(p), ceillist = B_i(p). //
12814 // //
12815 // BC_i(p) contains at least one tet on input. On finish, all tets collected //
12816 // in BC_i(p) are infected. B_i(p) may not closed when p is on segment or in //
12817 // facet. C(p) must be formed before this routine. Check the infect flag of //
12818 // a subface to identify the unclosed side of B_i(p). These sides will be //
12819 // closed by new subfaces of C(p)s. //
12820 // //
12821 ///////////////////////////////////////////////////////////////////////////////
12822
12823 void tetgenmesh::formbowatcavityquad(point bp, list* tetlist, list* ceillist)
12824 {
12825 triface starttet, neightet;
12826 face checksh;
12827 point pa, pb, pc, pd;
12828 REAL sign;
12829 int i;
12830
12831 // Form BC_i(p) and B_i(p) by a broadth-first searching.
12832 for (i = 0; i < tetlist->len(); i++) {
12833 starttet = * (triface *)(* tetlist)[i];
12834 for (starttet.loc = 0; starttet.loc < 4; starttet.loc++) {
12835 // Try to collect the neighbor of the face (f).
12836 tspivot(starttet, checksh);
12837 if (checksh.sh == dummysh) {
12838 // Get its neighbor n.
12839 sym(starttet, neightet);
12840 // Is n already in BC_i(p)?
12841 if (!infected(neightet)) {
12842 // For positive orientation that insphere() test requires.
12843 adjustedgering(neightet, CW);
12844 pa = org(neightet);
12845 pb = dest(neightet);
12846 pc = apex(neightet);
12847 pd = oppo(neightet);
12848 sign = insphere(pa, pb, pc, pd, bp);
12849 if (sign >= 0.0) {
12850 // Collect it into BC_i(p).
12851 infect(neightet);
12852 tetlist->append(&neightet);
12853 } else {
12854 ceillist->append(&starttet); // Found a face of B_i(p).
12855 }
12856 }
12857 } else {
12858 // Do not cross a boundary face.
12859 if (!sinfected(checksh)) {
12860 ceillist->append(&starttet); // Found a face of B_i(p).
12861 }
12862 }
12863 }
12864 }
12865
12866 if (b->verbose > 2) {
12867 printf(" Collect BC_i(%d): %d tets, %d faces.\n", pointmark(bp),
12868 tetlist->len(), ceillist->len());
12869 }
12870 }
12871
12872 ///////////////////////////////////////////////////////////////////////////////
12873 // //
12874 // formbowatcavitysegquad() Form BC_i(p) and B_i(p) in a segment quadrant.//
12875 // //
12876 // Parameters: bp = p, tetlist = BC_i(p), ceillist = B_i(p). //
12877 // //
12878 // BC_i(p) contains at least one tet on input. On finish, all tets collected //
12879 // in BC_i(p) are infected. B_i(p) is not closed. C(p) must be formed before //
12880 // this routine. Check the infect flag of a subface to identify the unclosed //
12881 // sides of B_i(p). These sides will be closed by new subfaces of C(p)s. //
12882 // //
12883 // During the repair of encroaching subsegments, there may exist locally non-//
12884 // Delaunay faces. These faces are collected in BC_i(p) either. B_i(p) has //
12885 // to be formed later than BC_i(p). //
12886 // //
12887 ///////////////////////////////////////////////////////////////////////////////
12888
12889 void tetgenmesh::formbowatcavitysegquad(point bp, list* tetlist,list* ceillist)
12890 {
12891 triface starttet, neightet, cavtet;
12892 face checksh;
12893 point pa, pb, pc, pd, pe;
12894 REAL sign;
12895 int i;
12896
12897 // Form BC_i(p) by a broadth-first searching.
12898 for (i = 0; i < tetlist->len(); i++) {
12899 starttet = * (triface *)(* tetlist)[i];
12900 for (starttet.loc = 0; starttet.loc < 4; starttet.loc++) {
12901 // Try to collect the neighbor of the face f.
12902 tspivot(starttet, checksh);
12903 if (checksh.sh == dummysh) {
12904 // Get its neighbor n.
12905 sym(starttet, neightet);
12906 // Is n already in BC_i(p)?
12907 if (!infected(neightet)) {
12908 // For positive orientation that insphere() test requires.
12909 adjustedgering(neightet, CW);
12910 pa = org(neightet);
12911 pb = dest(neightet);
12912 pc = apex(neightet);
12913 pd = oppo(neightet);
12914 sign = insphere(pa, pb, pc, pd, bp);
12915 if (sign >= 0.0) {
12916 // Collect it into BC_i(p).
12917 infect(neightet);
12918 tetlist->append(&neightet);
12919 } else {
12920 // Check if the face is locally non-Delaunay.
12921 pe = oppo(starttet);
12922 sign = insphere(pa, pb, pc, pd, pe);
12923 if (sign >= 0.0) {
12924 // Collect it into BC_i(p).
12925 infect(neightet);
12926 tetlist->append(&neightet);
12927 }
12928 }
12929 }
12930 }
12931 }
12932 }
12933
12934 // Generate B_i(p).
12935 for (i = 0; i < tetlist->len(); i++) {
12936 cavtet = * (triface *)(* tetlist)[i];
12937 for (cavtet.loc = 0; cavtet.loc < 4; cavtet.loc++) {
12938 tspivot(cavtet, checksh);
12939 if (checksh.sh == dummysh) {
12940 sym(cavtet, neightet);
12941 if (!infected(neightet)) {
12942 ceillist->append(&cavtet); // Found a face of B(p).
12943 }
12944 } else {
12945 // Do not cross a boundary face.
12946 if (!sinfected(checksh)) {
12947 ceillist->append(&cavtet); // Found a face of B(p).
12948 }
12949 }
12950 }
12951 }
12952
12953 if (b->verbose > 2) {
12954 printf(" Collect BC_i(%d): %d tets, %d faces.\n", pointmark(bp),
12955 tetlist->len(), ceillist->len());
12956 }
12957 }
12958
12959 ///////////////////////////////////////////////////////////////////////////////
12960 // //
12961 // formbowatcavity() Form BC(p), B(p), CBC(p)s, and C(p)s. //
12962 // //
12963 // If 'bpseg'(S) != NULL, p is on segment S, else, p is on facet containing //
12964 // 'bpsh' (F). 'n' returns the number of quadrants in BC(p). 'nmax' is the //
12965 // maximum pre-allocated array length for the lists. //
12966 // //
12967 ///////////////////////////////////////////////////////////////////////////////
12968
12969 void tetgenmesh::formbowatcavity(point bp, face* bpseg, face* bpsh, int* n,
12970 int* nmax, list** sublists, list** subceillists, list** tetlists,
12971 list** ceillists)
12972 {
12973 list *sublist;
12974 triface adjtet;
12975 face startsh, spinsh;
12976 point pa, pb;
12977 int i, j;
12978
12979 *n = 0;
12980 if (bpseg != (face *) NULL) {
12981 // p is on segment S.
12982 bpseg->shver = 0;
12983 pa = sorg(*bpseg);
12984 pb = sdest(*bpseg);
12985 // Count the number of facets sharing at S.
12986 spivot(*bpseg, startsh);
12987 spinsh = startsh;
12988 do {
12989 (*n)++; // spinshlist->append(&spinsh);
12990 spivotself(spinsh);
12991 } while (spinsh.sh != startsh.sh);
12992 // *n is the number of quadrants around S.
12993 if (*n > *nmax) {
12994 // Reallocate arrays. Should not happen very often.
12995 delete [] tetlists;
12996 delete [] ceillists;
12997 delete [] sublists;
12998 delete [] subceillists;
12999 tetlists = new list*[*n];
13000 ceillists = new list*[*n];
13001 sublists = new list*[*n];
13002 subceillists = new list*[*n];
13003 *nmax = *n;
13004 }
13005 // Form CBC(p)s and C(p)s.
13006 spinsh = startsh;
13007 for (i = 0; i < *n; i++) {
13008 sublists[i] = new list(sizeof(face), NULL, 256);
13009 subceillists[i] = new list(sizeof(face), NULL, 256);
13010 // Set a subface f to start search.
13011 startsh = spinsh;
13012 // Let f face to the quadrant of interest (used in forming BC(p)).
13013 findedge(&startsh, pa, pb);
13014 sinfect(startsh);
13015 sublists[i]->append(&startsh);
13016 formbowatcavitysub(bp, bpseg, sublists[i], subceillists[i]);
13017 // Go to the next facet.
13018 spivotself(spinsh);
13019 }
13020 } else if (sublists != (list **) NULL) {
13021 // p is on a facet.
13022 *n = 2;
13023 // Form CBC(p) and C(p).
13024 sublists[0] = new list(sizeof(face), NULL, 256);
13025 subceillists[0] = new list(sizeof(face), NULL, 256);
13026 sinfect(*bpsh);
13027 sublists[0]->append(bpsh);
13028 formbowatcavitysub(bp, NULL, sublists[0], subceillists[0]);
13029 } else {
13030 // p is inside a tet.
13031 *n = 1;
13032 }
13033
13034 // Form BC_i(p) and B_i(p).
13035 for (i = 0; i < *n; i++) {
13036 tetlists[i] = new list(sizeof(triface), NULL, 256);
13037 ceillists[i] = new list(sizeof(triface), NULL, 256);
13038 if (sublists != (list **) NULL) {
13039 // There are C(p)s.
13040 sublist = ((bpseg == (face *) NULL) ? sublists[0] : sublists[i]);
13041 // Add all adjacent tets of C_i(p) into BC_i(p).
13042 for (j = 0; j < sublist->len(); j++) {
13043 startsh = * (face *)(* sublist)[j];
13044 // Adjust the side facing to the right quadrant for C(p).
13045 if ((bpseg == (face *) NULL) && (i == 1)) sesymself(startsh);
13046 stpivot(startsh, adjtet);
13047 if (adjtet.tet != dummytet) {
13048 if (!infected(adjtet)) {
13049 infect(adjtet);
13050 tetlists[i]->append(&adjtet);
13051 }
13052 }
13053 }
13054 if (bpseg != (face *) NULL) {
13055 // The quadrant is bounded by another facet.
13056 sublist = ((i < *n - 1) ? sublists[i + 1] : sublists[0]);
13057 for (j = 0; j < sublist->len(); j++) {
13058 startsh = * (face *)(* sublist)[j];
13059 // Adjust the side facing to the right quadrant for C(p).
13060 sesymself(startsh);
13061 stpivot(startsh, adjtet);
13062 if (adjtet.tet != dummytet) {
13063 if (!infected(adjtet)) {
13064 infect(adjtet);
13065 tetlists[i]->append(&adjtet);
13066 }
13067 }
13068 }
13069 }
13070 }
13071 // It is possible that BC_i(p) is empty.
13072 if (tetlists[i]->len() == 0) continue;
13073 // Collect the rest of tets of BC_i(p) and form B_i(p).
13074 // if (b->conformdel) {
13075 // formbowatcavitysegquad(bp, tetlists[i], ceillists[i]);
13076 // } else {
13077 formbowatcavityquad(bp, tetlists[i], ceillists[i]);
13078 // }
13079 }
13080 }
13081
13082 ///////////////////////////////////////////////////////////////////////////////
13083 // //
13084 // releasebowatcavity() Undo and free the memory allocated in routine //
13085 // formbowatcavity(). //
13086 // //
13087 ///////////////////////////////////////////////////////////////////////////////
13088
13089 void tetgenmesh::releasebowatcavity(face* bpseg, int n, list** sublists,
13090 list** subceillist, list** tetlists, list** ceillists)
13091 {
13092 triface oldtet;
13093 face oldsh;
13094 int i, j;
13095
13096 if (sublists != (list **) NULL) {
13097 // Release CBC(p)s.
13098 for (i = 0; i < n; i++) {
13099 // Uninfect subfaces of CBC(p).
13100 for (j = 0; j < sublists[i]->len(); j++) {
13101 oldsh = * (face *)(* (sublists[i]))[j];
13102 #ifdef SELF_CHECK
13103 assert(sinfected(oldsh));
13104 #endif
13105 suninfect(oldsh);
13106 }
13107 delete sublists[i];
13108 delete subceillist[i];
13109 sublists[i] = (list *) NULL;
13110 subceillist[i] = (list *) NULL;
13111 if (bpseg == (face *) NULL) break;
13112 }
13113 }
13114 // Release BC(p).
13115 for (i = 0; i < n; i++) {
13116 // Uninfect tets of BC_i(p).
13117 for (j = 0; j < tetlists[i]->len(); j++) {
13118 oldtet = * (triface *)(* (tetlists[i]))[j];
13119 #ifdef SELF_CHECK
13120 assert(infected(oldtet));
13121 #endif
13122 uninfect(oldtet);
13123 }
13124 delete tetlists[i];
13125 delete ceillists[i];
13126 tetlists[i] = (list *) NULL;
13127 ceillists[i] = (list *) NULL;
13128 }
13129 }
13130
13131 ///////////////////////////////////////////////////////////////////////////////
13132 // //
13133 // validatebowatcavityquad() Valid B_i(p). //
13134 // //
13135 // B_i(p) is valid if all faces of B_i(p) are visible by p, else B_i(p) is //
13136 // invalid. Each tet of BC_i(p) which has such a face is marked (uninfect). //
13137 // They will be removed in updatebowatcavityquad(). //
13138 // //
13139 // Return TRUE if B(p) is valid, else, return FALSE. //
13140 // //
13141 ///////////////////////////////////////////////////////////////////////////////
13142
13143 bool tetgenmesh::validatebowatcavityquad(point bp,list* ceillist,REAL maxcosd)
13144 {
13145 triface ceiltet;
13146 point pa, pb, pc;
13147 REAL ori, cosd;
13148 int remcount, i;
13149
13150 // Check the validate of B(p), cut tets having invisible faces.
13151 remcount = 0;
13152 for (i = 0; i < ceillist->len(); i++) {
13153 ceiltet = * (triface *)(* ceillist)[i];
13154 if (infected(ceiltet)) {
13155 adjustedgering(ceiltet, CCW);
13156 pa = org(ceiltet);
13157 pb = dest(ceiltet);
13158 pc = apex(ceiltet);
13159 ori = orient3d(pa, pb, pc, bp);
13160 if (ori >= 0.0) {
13161 // Found an invisible face.
13162 uninfect(ceiltet);
13163 remcount++;
13164 continue;
13165 }
13166 // If a non-trival 'maxcosd' is given.
13167 if (maxcosd > -1.0) {
13168 // Get the maximal dihedral angle of tet abcp.
13169 tetalldihedral(pa, pb, pc, bp, NULL, &cosd, NULL);
13170 // Do not form the tet if the maximal dihedral angle is not reduced.
13171 if (cosd < maxcosd) {
13172 uninfect(ceiltet);
13173 remcount++;
13174 }
13175 }
13176 }
13177 }
13178 return remcount == 0;
13179 }
13180
13181 ///////////////////////////////////////////////////////////////////////////////
13182 // //
13183 // updatebowatcavityquad() Update BC_i(p) and reform B_i(p). //
13184 // //
13185 // B_i(p) is invalid and some tets in BC_i(p) have been marked to be removed //
13186 // in validatebowatcavityquad(). This routine actually remove the cut tets //
13187 // of BC_i(p) and re-form the B_i(p). //
13188 // //
13189 ///////////////////////////////////////////////////////////////////////////////
13190
13191 void tetgenmesh::updatebowatcavityquad(list* tetlist, list* ceillist)
13192 {
13193 triface cavtet, neightet;
13194 face checksh;
13195 int remcount, i;
13196
13197 remcount = 0;
13198 for (i = 0; i < tetlist->len(); i++) {
13199 cavtet = * (triface *)(* tetlist)[i];
13200 if (!infected(cavtet)) {
13201 tetlist->del(i, 1);
13202 remcount++;
13203 i--;
13204 }
13205 }
13206
13207 // Are there tets have been cut in BC_i(p)?
13208 if (remcount > 0) {
13209 // Re-form B_i(p).
13210 ceillist->clear();
13211 for (i = 0; i < tetlist->len(); i++) {
13212 cavtet = * (triface *)(* tetlist)[i];
13213 for (cavtet.loc = 0; cavtet.loc < 4; cavtet.loc++) {
13214 tspivot(cavtet, checksh);
13215 if (checksh.sh == dummysh) {
13216 sym(cavtet, neightet);
13217 if (!infected(neightet)) {
13218 ceillist->append(&cavtet); // Found a face of B_i(p).
13219 }
13220 } else {
13221 // Do not cross a boundary face.
13222 if (!sinfected(checksh)) {
13223 ceillist->append(&cavtet); // Found a face of B_i(p).
13224 }
13225 }
13226 }
13227 }
13228 if (b->verbose > 2) {
13229 printf(" Update BC_i(p): %d tets, %d faces.\n", tetlist->len(),
13230 ceillist->len());
13231 }
13232 }
13233 }
13234
13235 ///////////////////////////////////////////////////////////////////////////////
13236 // //
13237 // updatebowatcavitysub() Check and update CBC(p) and C(p). //
13238 // //
13239 // A CBC(p) is valid if all its subfaces are inside or on the hull of BC(p). //
13240 // A subface s of CBC(p) is invalid if it is in one of the two cases: //
13241 // (1) s is completely outside BC(p); //
13242 // (2) s has two adjacent tets but only one of them is in BC(p); //
13243 // s is removed from CBC(p) if it is invalid. If there is an adjacent tet of //
13244 // s which is in BC(p), it gets removed from BC(p) too. If CBC(p) is updated,//
13245 // C(p) is re-formed. //
13246 // //
13247 // A C(p) is valid if all its edges are on the hull of BC(p). An edge e of //
13248 // C(p) may be inside BC(p) if e is a segment and belongs to only one facet. //
13249 // To correct C(p), a tet of BC(p) which shields e gets removed. //
13250 // //
13251 // If BC(p) is formed with locally non-Delaunay check (b->conformdel > 0). //
13252 // A boundary-consistent check is needed for non-segment edges of C(p). Let //
13253 // e be such an edge, the subface f contains e and outside C(p) may belong //
13254 // to B(p) due to the non-coplanarity of the facet definition. The tet of //
13255 // BC(p) containing f gets removed to avoid creating a degenerate new tet. //
13256 // //
13257 // 'cutcount' accumulates the total number of cuttets(not only by this call).//
13258 // //
13259 ///////////////////////////////////////////////////////////////////////////////
13260
13261 void tetgenmesh::updatebowatcavitysub(list* sublist, list* subceillist,
13262 int* cutcount)
13263 {
13264 triface adjtet, rotface;
13265 face checksh, neighsh;
13266 face checkseg;
13267 point pa, pb, pc;
13268 REAL ori1, ori2;
13269 int remcount;
13270 int i, j;
13271
13272 remcount = 0;
13273 // Check the validity of CBC(p).
13274 for (i = 0; i < sublist->len(); i++) {
13275 checksh = * (face *)(* sublist)[i];
13276 // Check two adjacent tets of s.
13277 for (j = 0; j < 2; j++) {
13278 stpivot(checksh, adjtet);
13279 if (adjtet.tet != dummytet) {
13280 if (!infected(adjtet)) {
13281 // Could be either case (1) or (2).
13282 suninfect(checksh); // s survives.
13283 // If the sym. adjtet exists, it should remove from BC(p) too.
13284 sesymself(checksh);
13285 stpivot(checksh, adjtet);
13286 if (adjtet.tet != dummytet) {
13287 if (infected(adjtet)) {
13288 // Found an adj. tet in BC(p), remove it.
13289 uninfect(adjtet);
13290 (*cutcount)++;
13291 }
13292 }
13293 // Remove s from C(p).
13294 sublist->del(i, 1);
13295 i--;
13296 remcount++;
13297 break;
13298 }
13299 }
13300 sesymself(checksh);
13301 }
13302 }
13303 if (remcount > 0) {
13304 if (b->verbose > 2) {
13305 printf(" Removed %d subfaces from CBC(p).\n", remcount);
13306 }
13307 // Re-generate C(p).
13308 subceillist->clear();
13309 for (i = 0; i < sublist->len(); i++) {
13310 checksh = * (face *)(* sublist)[i];
13311 for (j = 0; j < 3; j++) {
13312 spivot(checksh, neighsh);
13313 if (!sinfected(neighsh)) {
13314 subceillist->append(&checksh);
13315 }
13316 senextself(checksh);
13317 }
13318 }
13319 if (b->verbose > 2) {
13320 printf(" Update CBC(p): %d subs, %d edges.\n", sublist->len(),
13321 subceillist->len());
13322 }
13323 }
13324
13325 // Check the validity of C(p).
13326 for (i = 0; i < subceillist->len(); i++) {
13327 checksh = * (face *)(* subceillist)[i];
13328 sspivot(checksh, checkseg);
13329 if (checkseg.sh != dummysh) {
13330 // A segment. Check if it is inside BC(p).
13331 stpivot(checksh, adjtet);
13332 if (adjtet.tet == dummytet) {
13333 sesym(checksh, neighsh);
13334 stpivot(neighsh, adjtet);
13335 }
13336 findedge(&adjtet, sorg(checkseg), sdest(checkseg));
13337 adjustedgering(adjtet, CCW);
13338 fnext(adjtet, rotface); // It's the same tet.
13339 // Rotate rotface (f), stop on either of the following cases:
13340 // (a) meet a subface, or
13341 // (b) enter an uninfected tet, or
13342 // (c) rewind back to adjtet.
13343 do {
13344 if (!infected(rotface)) break; // case (b)
13345 tspivot(rotface, neighsh);
13346 if (neighsh.sh != dummysh) break; // case (a)
13347 // Go to the next tet of the facing ring.
13348 fnextself(rotface);
13349 } while (apex(rotface) != apex(adjtet));
13350 // Is it case (c)?
13351 if (apex(rotface) == apex(adjtet)) {
13352 // The segment is enclosed by BC(p), invalid cavity.
13353 pa = org(adjtet);
13354 pb = dest(adjtet);
13355 pc = apex(adjtet);
13356 // Find the shield tet and cut it. Notice that the shield tet may
13357 // not be unique when there are four coplanar points, ie.,
13358 // ori1 * ori2 == 0.0. In such case, choose either of them.
13359 fnext(adjtet, rotface);
13360 do {
13361 fnextself(rotface);
13362 assert(infected(rotface));
13363 ori1 = orient3d(pa, pb, pc, apex(rotface));
13364 ori2 = orient3d(pa, pb, pc, oppo(rotface));
13365 } while (ori1 * ori2 > 0.0);
13366 // Cut this tet from BC(p).
13367 uninfect(rotface);
13368 (*cutcount)++;
13369 }
13370 } else {
13371 /*// An edge. Check if boundary-consistency should be enforced.
13372 if (b->conformdel > 0) {
13373 // Get the adj-sub n at e, it must be outside C(p).
13374 spivot(checksh, neighsh);
13375 assert(!sinfected(neighsh));
13376 // Check if n is on B(p).
13377 for (j = 0; j < 2; j++) {
13378 stpivot(neighsh, adjtet);
13379 if (adjtet.tet != dummytet) {
13380 if (infected(adjtet)) {
13381 uninfect(adjtet);
13382 (*cutcount)++;
13383 }
13384 }
13385 sesymself(neighsh);
13386 }
13387 } */
13388 }
13389 }
13390 }
13391
13392 ///////////////////////////////////////////////////////////////////////////////
13393 // //
13394 // trimbowatcavity() Validate B(p), CBC(p)s and C(p)s, update BC(p). //
13395 // //
13396 // A B(p) is valid if all its faces are visible by p. If a face f of B(p) is //
13397 // found invisible by p, the tet of BC(p) containing f gets removed and B(p) //
13398 // is refromed. The new B(p) may still contain invisible faces by p. Iterat- //
13399 // ively do the above procedure until B(p) is satisfied. //
13400 // //
13401 // A CBC(p) is valid if each subface of CBC(p) is either on the hull of BC(p)//
13402 // or completely inside BC(p). If a subface s of CBC(p) is not valid, it is //
13403 // removed from CBC(p) and C(p) is reformed. If there exists a tet t of BC(p)//
13404 // containg s, t is removed from BC(p). The process for validating BC(p) and //
13405 // B(p) is re-excuted. //
13406 // //
13407 // A C(p) is valid if each edge of C(p) is on the hull of BC(p). If an edge //
13408 // e of C(p) is invalid (e should be a subsegment which only belong to one //
13409 // facet), a tet of BC(p) which contains e and has two other faces shielding //
13410 // e is removed. The process for validating BC(p) and B(p) is re-excuted. //
13411 // //
13412 // If either BC(p) or CBC(p) becomes empty. No valid BC(p) is found, return //
13413 // FALSE. else, return TRUE. //
13414 // //
13415 ///////////////////////////////////////////////////////////////////////////////
13416
13417 bool tetgenmesh::trimbowatcavity(point bp, face* bpseg, int n, list** sublists,
13418 list** subceillists, list** tetlists, list** ceillists, REAL maxcosd)
13419 {
13420 bool valflag;
13421 int oldnum, cutnum, cutcount;
13422 int i;
13423
13424 cutnum = 0; // Count the total number of cut-off tets of BC(p).
13425 valflag = true;
13426
13427 do {
13428 // Validate BC(p), B(p).
13429 for (i = 0; i < n && valflag; i++) {
13430 oldnum = tetlists[i]->len();
13431 // Iteratively validate BC_i(p) and B_i(p).
13432 while (!validatebowatcavityquad(bp, ceillists[i], maxcosd)) {
13433 // Update BC_i(p) and B_i(p).
13434 updatebowatcavityquad(tetlists[i], ceillists[i]);
13435 valflag = tetlists[i]->len() > 0;
13436 }
13437 cutnum += (oldnum - tetlists[i]->len());
13438 }
13439 if (valflag && (sublists != (list **) NULL)) {
13440 // Validate CBC(p), C(p).
13441 cutcount = 0;
13442 for (i = 0; i < n; i++) {
13443 updatebowatcavitysub(sublists[i], subceillists[i], &cutcount);
13444 // Only do once if p is on a facet.
13445 if (bpseg == (face *) NULL) break;
13446 }
13447 // Are there cut tets?
13448 if (cutcount > 0) {
13449 // Squeeze all cut tets in BC(p), keep valflag once it gets FLASE.
13450 for (i = 0; i < n; i++) {
13451 if (tetlists[i]->len() > 0) {
13452 updatebowatcavityquad(tetlists[i], ceillists[i]);
13453 if (valflag) {
13454 valflag = tetlists[i]->len() > 0;
13455 }
13456 }
13457 }
13458 cutnum += cutcount;
13459 // Go back to valid the updated BC(p).
13460 continue;
13461 }
13462 }
13463 break; // Leave the while-loop.
13464 } while (true);
13465
13466 // Check if any CBC(p) becomes non-empty.
13467 if (valflag && (sublists != (list **) NULL)) {
13468 for (i = 0; i < n && valflag; i++) {
13469 valflag = (sublists[i]->len() > 0);
13470 if (bpseg == (face *) NULL) break;
13471 }
13472 }
13473
13474 if (valflag && (cutnum > 0)) {
13475 // Accumulate counters.
13476 if (bpseg != (face *) NULL) {
13477 updsegcount++;
13478 } else if (sublists != (list **) NULL) {
13479 updsubcount++;
13480 } else {
13481 updvolcount++;
13482 }
13483 }
13484
13485 if (!valflag) {
13486 // Accumulate counters.
13487 if (bpseg != (face *) NULL) {
13488 failsegcount++;
13489 } else if (sublists != (list **) NULL) {
13490 failsubcount++;
13491 } else {
13492 failvolcount++;
13493 }
13494 }
13495
13496 return valflag;
13497 }
13498
13499 ///////////////////////////////////////////////////////////////////////////////
13500 // //
13501 // bowatinsertsite() Insert a point using the Bowyer-Watson method. //
13502 // //
13503 // Parameters: 'bp' = p, 'splitseg' = S, 'n' = the number of quadrants, //
13504 // 'sublists', an array of CBC_i(p)s, 'subceillists', an array of C_i(p)s, //
13505 // 'tetlists', an array of BC_i(p)s, 'ceillists', an array of B_i(p)s. //
13506 // //
13507 // If p is inside the mesh domain, then S = NULL, n = 1, CBC(p) and C(p) are //
13508 // NULLs. 'tetlists[0]' = BC(p), 'ceillists[0]' = B(p). //
13509 // If p is on a facet F, then S = NULL, n = 2, and 'subceillists[0]' = C(p), //
13510 // 'subceillists[1]' is not needed (set it to NULL). B_1(p) and B_2(p) are //
13511 // in 'ceillists[0]' and 'ceillists[1]'. //
13512 // If p is on a segment S, then F(S) is a list of subfaces around S, and n = //
13513 // len(F(S)), there are n C_i(p)s and B_i(p)s supplied in 'subceillists[i]'//
13514 // and 'ceillists[i]'. //
13515 // //
13516 // If 'verlist' != NULL, it returns a list of vertices which connect to p. //
13517 // This vertices are used for interpolating size of p. //
13518 // //
13519 // If 'flipque' != NULL, it returns a list of internal faces of new tets in //
13520 // BC(p), faces on C(p)s are excluded. These faces may be locally non- //
13521 // Delaunay and will be flipped if they are flippable. Such non-Delaunay //
13522 // faces may exist when p is inserted to split an encroaching segment. //
13523 // //
13524 // 'chkencseg', 'chkencsub', and 'chkbadtet' are flags that indicate whether //
13525 // or not there should be checks for the creation of encroached subsegments, //
13526 // subfaces, or bad quality tets. If 'chkencseg' = TRUE, the encroached sub- //
13527 // segments are added to the list of subsegments to be split. //
13528 // //
13529 // On return, 'ceillists' returns Star(p). //
13530 // //
13531 ///////////////////////////////////////////////////////////////////////////////
13532
13533 void tetgenmesh::bowatinsertsite(point bp,face* splitseg,int n,list** sublists,
13534 list** subceillists, list** tetlists, list** ceillists, list* verlist,
13535 queue* flipque, bool chkencseg, bool chkencsub, bool chkbadtet)
13536 {
13537 list *ceillist, *subceillist;
13538 triface oldtet, newtet, newface, rotface, neightet;
13539 face oldsh, newsh, newedge, checksh;
13540 face spinsh, casingin, casingout;
13541 face *apsegshs, *pbsegshs;
13542 face apseg, pbseg, checkseg;
13543 point pa, pb, pc;
13544 REAL attrib, volume;
13545 int idx, i, j, k;
13546
13547 if (b->verbose > 1) {
13548 printf(" Insert point %d (%.12g, %.12g, %.12g)", pointmark(bp), bp[0],
13549 bp[1], bp[2]);
13550 }
13551 if (splitseg != (face *) NULL) {
13552 if (b->verbose > 1) {
13553 printf(" on segment.\n");
13554 }
13555 bowatsegcount++;
13556 } else {
13557 if (subceillists != (list **) NULL) {
13558 if (b->verbose > 1) {
13559 printf(" on facet.\n");
13560 }
13561 bowatsubcount++;
13562 } else {
13563 if (b->verbose > 1) {
13564 printf(" in volume.\n");
13565 }
13566 bowatvolcount++;
13567 }
13568 }
13569
13570 // Create new tets to fill B(p).
13571 for (k = 0; k < n; k++) {
13572 // Create new tets from each B_i(p).
13573 ceillist = ceillists[k];
13574 for (i = 0; i < ceillist->len(); i++) {
13575 oldtet = * (triface *)(* ceillist)[i];
13576 adjustedgering(oldtet, CCW);
13577 pa = org(oldtet);
13578 pb = dest(oldtet);
13579 pc = apex(oldtet);
13580 maketetrahedron(&newtet);
13581 setorg(newtet, pa);
13582 setdest(newtet, pb);
13583 setapex(newtet, pc);
13584 setoppo(newtet, bp);
13585 for (j = 0; j < in->numberoftetrahedronattributes; j++) {
13586 attrib = elemattribute(oldtet.tet, j);
13587 setelemattribute(newtet.tet, j, attrib);
13588 }
13589 if (b->varvolume) {
13590 volume = volumebound(oldtet.tet);
13591 if (volume > 0.0) {
13592 if (!b->fixedvolume && b->refine) {
13593 // '-r -a' switches and a .vol file case. Enlarge the maximum
13594 // volume constraint for the new tets. Hence the new points
13595 // only spread near the original constrained tet.
13596 volume *= 1.2;
13597 }
13598 }
13599 setvolumebound(newtet.tet, volume);
13600 }
13601 sym(oldtet, neightet);
13602 tspivot(oldtet, checksh);
13603 if (neightet.tet != dummytet) {
13604 bond(newtet, neightet);
13605 }
13606 if (checksh.sh != dummysh) {
13607 tsbond(newtet, checksh);
13608 }
13609 if (verlist != (list *) NULL) {
13610 // Collect vertices connecting to p.
13611 idx = pointmark(pa);
13612 if (idx >= 0) {
13613 setpointmark(pa, -idx - 1);
13614 verlist->append(&pa);
13615 }
13616 idx = pointmark(pb);
13617 if (idx >= 0) {
13618 setpointmark(pb, -idx - 1);
13619 verlist->append(&pb);
13620 }
13621 idx = pointmark(pc);
13622 if (idx >= 0) {
13623 setpointmark(pc, -idx - 1);
13624 verlist->append(&pc);
13625 }
13626 }
13627 // Replace the tet by the newtet for checking the quality.
13628 * (triface *)(* ceillist)[i] = newtet;
13629 }
13630 }
13631 if (verlist != (list *) NULL) {
13632 // Uninfect collected vertices.
13633 for (i = 0; i < verlist->len(); i++) {
13634 pa = * (point *)(* verlist)[i];
13635 idx = pointmark(pa);
13636 setpointmark(pa, -(idx + 1));
13637 }
13638 }
13639
13640 // Connect new tets of B(p). Not all faces of new tets can be connected,
13641 // e.g., if there are empty B_i(p)s.
13642 for (k = 0; k < n; k++) {
13643 ceillist = ceillists[k];
13644 for (i = 0; i < ceillist->len(); i++) {
13645 newtet = * (triface *)(* ceillist)[i];
13646 newtet.ver = 0;
13647 for (j = 0; j < 3; j++) {
13648 fnext(newtet, newface);
13649 sym(newface, neightet);
13650 if (neightet.tet == dummytet) {
13651 // Find the neighbor face by rotating the faces at edge ab.
13652 esym(newtet, rotface);
13653 pa = org(rotface);
13654 pb = dest(rotface);
13655 while (fnextself(rotface));
13656 // Do we meet a boundary face?
13657 tspivot(rotface, checksh);
13658 if (checksh.sh != dummysh) {
13659 // Walk through the boundary and continue to rotate faces.
13660 do {
13661 findedge(&checksh, pa, pb);
13662 sfnextself(checksh);
13663 assert((sorg(checksh) == pa) && (sdest(checksh) == pb));
13664 stpivot(checksh, rotface);
13665 if (infected(rotface)) {
13666 // Meet an old tet of B_i(p). This side is on the hull and
13667 // will be connected to a new subface created in C(p).
13668 break;
13669 }
13670 findedge(&rotface, pa, pb);
13671 while (fnextself(rotface));
13672 tspivot(rotface, checksh);
13673 } while (checksh.sh != dummysh);
13674 }
13675 // The rotface has edge ab, but it may not have newpt.
13676 if (apex(rotface) == apex(newface)) {
13677 // Bond the two tets together.
13678 bond(newface, rotface);
13679 // Queue (uniquely) this face if 'flipque' is given.
13680 if (flipque != (queue *) NULL) {
13681 enqueueflipface(newface, flipque);
13682 }
13683 }
13684 }
13685 enextself(newtet);
13686 }
13687 }
13688 }
13689
13690 if (subceillists != (list **) NULL) {
13691 // There are C(p)s.
13692 if (splitseg != (face *) NULL) {
13693 // S (ab) is split by p.
13694 splitseg->shver = 0;
13695 pa = sorg(*splitseg);
13696 pb = sdest(*splitseg);
13697 // Allcate two arrays for saving the subface rings of the two new
13698 // segments a->p and p->b.
13699 apsegshs = new face[n];
13700 pbsegshs = new face[n];
13701 }
13702
13703 // For each C_k(p), do the following:
13704 // (1) Create new subfaces to fill C_k(p), insert them into B(p);
13705 // (2) Connect new subfaces to each other;
13706 for (k = 0; k < n; k++) {
13707 subceillist = subceillists[k];
13708
13709 // Check if 'hullsize' should be updated.
13710 oldsh = * (face *)(* subceillist)[0];
13711 stpivot(oldsh, neightet);
13712 if (neightet.tet != dummytet) {
13713 sesymself(oldsh);
13714 stpivot(oldsh, neightet);
13715 }
13716 if (neightet.tet == dummytet) {
13717 // The hull size changes.
13718 hullsize += (subceillist->len() - sublists[k]->len());
13719 }
13720
13721 // (1) Create new subfaces to fill C_k(p), insert them into B(p).
13722 for (i = 0; i < subceillist->len(); i++) {
13723 oldsh = * (face *)(* subceillist)[i];
13724 makeshellface(subfaces, &newsh);
13725 setsorg(newsh, sorg(oldsh));
13726 setsdest(newsh, sdest(oldsh));
13727 setsapex(newsh, bp);
13728 if (b->quality && varconstraint) {
13729 setareabound(newsh, areabound(oldsh));
13730 }
13731 setshellmark(newsh, shellmark(oldsh));
13732 setshelltype(newsh, shelltype(oldsh));
13733 if (checkpbcs) {
13734 setshellpbcgroup(newsh, shellpbcgroup(oldsh));
13735 }
13736 // Replace oldsh by newsh at the edge.
13737 spivot(oldsh, casingout);
13738 sspivot(oldsh, checkseg);
13739 if (checkseg.sh != dummysh) {
13740 // A segment. Insert s into the face ring, ie, s_in -> s -> s_out.
13741 if (oldsh.sh != casingout.sh) {
13742 // s is not bonded to itself.
13743 spinsh = casingout;
13744 do {
13745 casingin = spinsh;
13746 spivotself(spinsh);
13747 } while (sapex(spinsh) != sapex(oldsh));
13748 assert(casingin.sh != oldsh.sh);
13749 // Bond s_in -> s -> s_out (and dissolve s_in -> s_old -> s_out).
13750 sbond1(casingin, newsh);
13751 sbond1(newsh, casingout);
13752 } else {
13753 // Bond newsh -> newsh.
13754 sbond(newsh, newsh);
13755 }
13756 // Bond the segment.
13757 ssbond(newsh, checkseg);
13758 } else {
13759 // Bond s <-> s_out (and dissolve s_out -> s_old).
13760 sbond(newsh, casingout);
13761 }
13762
13763 // Insert newsh into B(p). Use the coonections of oldsh.
13764 stpivot(oldsh, neightet);
13765 if (neightet.tet == dummytet) {
13766 sesymself(oldsh);
13767 sesymself(newsh); // Keep the same orientation as oldsh.
13768 stpivot(oldsh, neightet);
13769 }
13770 assert(infected(neightet));
13771 // Set on the rotating edge.
13772 findedge(&neightet, sorg(oldsh), sdest(oldsh));
13773 // Choose the rotating direction (to the inside of B(p)).
13774 adjustedgering(neightet, CCW);
13775 rotface = neightet;
13776 // Rotate face. Stop at a non-infected tet t (not in B(p)) or a
13777 // hull face f (on B(p)). Get the neighbor n of t or f. n is
13778 // a new tet that has just been created to fill B(p).
13779 do {
13780 fnextself(rotface);
13781 sym(rotface, neightet);
13782 if (neightet.tet == dummytet) {
13783 tspivot(rotface, checksh);
13784 assert(checksh.sh != dummysh);
13785 stpivot(checksh, newtet);
13786 break;
13787 } else if (!infected(neightet)) {
13788 sym(neightet, newtet);
13789 break;
13790 }
13791 } while (true);
13792 assert(newtet.tet != rotface.tet);
13793 // Set the rotating edge of n.
13794 findedge(&newtet, sorg(oldsh), sdest(oldsh));
13795 // Choose the rotating direction (to the inside of B(p)).
13796 adjustedgering(newtet, CCW);
13797 fnext(newtet, newface);
13798 assert(apex(newface) == bp);
13799 // newsh has already been oriented toward n.
13800 tsbond(newface, newsh);
13801 sym(newface, neightet); // 'neightet' maybe outside.
13802 sesymself(newsh);
13803 tsbond(neightet, newsh); // Bond them anyway.
13804
13805 // Replace oldsh by newsh in list.
13806 * (face *)(* subceillist)[i] = newsh;
13807 }
13808
13809 // (2) Connect new subfaces to each other.
13810 for (i = 0; i < subceillist->len(); i++) {
13811 // Get a face cdp.
13812 newsh = * (face *)(* subceillist)[i];
13813 // Get a new tet containing cdp.
13814 stpivot(newsh, newtet);
13815 if (newtet.tet == dummytet) {
13816 sesymself(newsh);
13817 stpivot(newsh, newtet);
13818 }
13819 for (j = 0; j < 2; j++) {
13820 if (j == 0) {
13821 senext(newsh, newedge); // edge dp.
13822 } else {
13823 senext2(newsh, newedge); // edge pc.
13824 sesymself(newedge); // edge cp.
13825 }
13826 if (splitseg != (face *) NULL) {
13827 // Don not operate on newedge if it is ap or pb.
13828 if (sorg(newedge) == pa) {
13829 apsegshs[k] = newedge;
13830 continue;
13831 } else if (sorg(newedge) == pb) {
13832 pbsegshs[k] = newedge;
13833 continue;
13834 }
13835 }
13836 // There should no segment inside the cavity. Check it.
13837 sspivot(newedge, checkseg);
13838 assert(checkseg.sh == dummysh);
13839 spivot(newedge, casingout);
13840 if (casingout.sh == dummysh) {
13841 rotface = newtet;
13842 findedge(&rotface, sorg(newedge), sdest(newedge));
13843 // Rotate newtet until meeting a new subface which contains
13844 // newedge. It must exist since newedge is not a seg.
13845 adjustedgering(rotface, CCW);
13846 do {
13847 fnextself(rotface);
13848 tspivot(rotface, checksh);
13849 if (checksh.sh != dummysh) break;
13850 } while (true);
13851 findedge(&checksh, sorg(newedge), sdest(newedge));
13852 sbond(newedge, checksh);
13853 }
13854 }
13855 }
13856 // Only do once if p is on a facet.
13857 if (splitseg == (face *) NULL) break;
13858 } // for (k = 0; k < n; k++)
13859
13860 if (splitseg != (face *) NULL) {
13861 // Update a->b to be a->p.
13862 apseg = *splitseg;
13863 setsdest(apseg, bp);
13864 // Create a new subsegment p->b.
13865 makeshellface(subsegs, &pbseg);
13866 setsorg(pbseg, bp);
13867 setsdest(pbseg, pb);
13868 // p->b gets the same mark and segment type as a->p.
13869 setshellmark(pbseg, shellmark(apseg));
13870 setshelltype(pbseg, shelltype(apseg));
13871 if (b->quality && varconstraint) {
13872 // Copy the area bound into the new subsegment.
13873 setareabound(pbseg, areabound(apseg));
13874 }
13875 senext(apseg, checkseg);
13876 // Get the old connection at b of a->b.
13877 spivot(checkseg, casingout);
13878 // Bond a->p and p->b together.
13879 senext2(pbseg, casingin);
13880 sbond(casingin, checkseg);
13881 if (casingout.sh != dummysh) {
13882 // There is a subsegment connect at b of p->b.
13883 casingout.shver = 0;
13884 #ifdef SELF_CHECK
13885 assert(sorg(casingout) == pb);
13886 #endif
13887 senext2self(casingout);
13888 senext(pbseg, casingin);
13889 sbond(casingin, casingout);
13890 }
13891
13892 // Bond all new subfaces to a->p and p->b.
13893 for (i = 0; i < n; i++) {
13894 spinsh = apsegshs[i];
13895 findedge(&spinsh, pa, bp);
13896 ssbond(spinsh, apseg);
13897 spinsh = pbsegshs[i];
13898 findedge(&spinsh, bp, pb);
13899 ssbond(spinsh, pbseg);
13900 }
13901 // Bond all subfaces share at a->p together.
13902 for (i = 0; i < n; i++) {
13903 spinsh = apsegshs[i];
13904 if (i < (n - 1)) {
13905 casingout = apsegshs[i + 1];
13906 } else {
13907 casingout = apsegshs[0];
13908 }
13909 sbond1(spinsh, casingout);
13910 }
13911 // Bond all subfaces share at p->b together.
13912 for (i = 0; i < n; i++) {
13913 spinsh = pbsegshs[i];
13914 if (i < (n - 1)) {
13915 casingout = pbsegshs[i + 1];
13916 } else {
13917 casingout = pbsegshs[0];
13918 }
13919 sbond1(spinsh, casingout);
13920 }
13921 delete [] apsegshs;
13922 delete [] pbsegshs;
13923
13924 // Check for newly encroached subsegments if the flag is set.
13925 if (chkencseg) {
13926 // Check if a->p and p->b are encroached by other vertices.
13927 checkseg4encroach(&apseg, NULL, NULL, true);
13928 if (!shell2badface(apseg)) {
13929 if (varconstraint && (areabound(apseg) > 0.0)) {
13930 checkseg4badqual(&apseg, true);
13931 }
13932 }
13933 checkseg4encroach(&pbseg, NULL, NULL, true);
13934 if (!shell2badface(pbseg)) {
13935 if (varconstraint && (areabound(pbseg) > 0.0)) {
13936 checkseg4badqual(&pbseg, true);
13937 }
13938 }
13939 // Check if the adjacent segments are encroached by p.
13940 tallencsegs(bp, n, ceillists);
13941 }
13942 } // if (splitseg != (face *) NULL)
13943
13944 // Delete subfaces of old CBC_i(p)s.
13945 for (k = 0; k < n; k++) {
13946 for (i = 0; i < sublists[k]->len(); i++) {
13947 oldsh = * (face *)(* (sublists[k]))[i];
13948 shellfacedealloc(subfaces, oldsh.sh);
13949 }
13950 // Clear the list so that the subs will not get unmarked later in
13951 // routine releasebowatcavity() which only frees the memory.
13952 sublists[k]->clear();
13953 // Only do once if p is on a facet.
13954 if (splitseg == (face *) NULL) break;
13955 }
13956
13957 // Check for newly encroached subfaces if the flag is set.
13958 if (chkencsub) {
13959 // Check if new subfaces of C_i(p) are encroached by other vertices.
13960 for (k = 0; k < n; k++) {
13961 subceillist = subceillists[k];
13962 for (i = 0; i < subceillist->len(); i++) {
13963 newsh = * (face *)(* subceillist)[i];
13964 checksub4encroach(&newsh, NULL, true);
13965 if (!shell2badface(newsh)) {
13966 if (varconstraint && (areabound(newsh) > 0.0)) {
13967 checksub4badqual(&newsh, true);
13968 }
13969 }
13970 }
13971 // Only do once if p is on a facet.
13972 if (splitseg == (face *) NULL) break;
13973 }
13974 // Check if the adjacent subfaces are encroached by p.
13975 tallencsubs(bp, n, ceillists);
13976 }
13977 } // if (subceillists != (list **) NULL)
13978
13979 // Delete tets of old BC_i(p)s.
13980 for (k = 0; k < n; k++) {
13981 for (i = 0; i < tetlists[k]->len(); i++) {
13982 oldtet = * (triface *)(* (tetlists[k]))[i];
13983 tetrahedrondealloc(oldtet.tet);
13984 }
13985 // Clear the list so that the tets will not get unmarked later in
13986 // routine releasebowatcavity() which only frees the memory.
13987 tetlists[k]->clear();
13988 }
13989
13990 // check for bad quality tets if the flags is set.
13991 if (chkbadtet) {
13992 for (k = 0; k < n; k++) {
13993 ceillist = ceillists[k];
13994 for (i = 0; i < ceillist->len(); i++) {
13995 newtet = * (triface *)(* ceillist)[i];
13996 checktet4badqual(&newtet, true);
13997 }
13998 }
13999 }
14000
14001 if (flipque != (queue *) NULL) {
14002 // Newly created internal faces of BC(p) (excluding faces on C(p)s) are
14003 // in 'flipque'. Some of these faces may be locally non-Delaunay due,
14004 // to the existence of non-constrained tets. check and fix them.
14005 repairflipcount += flip(flipque, NULL);
14006 }
14007 }
14008
14009 //
14010 // End of mesh transformation routines
14011 //
14012
14013 //
14014 // Begin Delaunay tetrahedralization routines
14015 //
14016
14017 ///////////////////////////////////////////////////////////////////////////////
14018 // //
14019 // formstarpolyhedron() Get the star ployhedron of a point 'pt'. //
14020 // //
14021 // The polyhedron P is formed by faces of tets having 'pt' as a vertex. If //
14022 // 'complete' is TRUE, P is the complete star of 'pt'. Otherwise, P is boun- //
14023 // ded by subfaces, i.e. P is only part of the star of 'pt'. //
14024 // //
14025 // 'tetlist' T returns the tets, it has one of such tets on input. Moreover, //
14026 // if t is in T, then oppo(t) = p. Topologically, T is the star of p; and //
14027 // the faces of T is the link of p. 'verlist' V returns the vertices of T. //
14028 // //
14029 ///////////////////////////////////////////////////////////////////////////////
14030
14031 void tetgenmesh::formstarpolyhedron(point pt, list* tetlist, list* verlist,
14032 bool complete)
14033 {
14034 triface starttet, neightet;
14035 face checksh;
14036 point ver[3];
14037 int idx, i, j;
14038
14039 // Get a tet t containing p.
14040 starttet = * (triface *)(* tetlist)[0];
14041 // Let oppo(t) = p.
14042 for (starttet.loc = 0; starttet.loc < 4; starttet.loc++) {
14043 if (oppo(starttet) == pt) break;
14044 }
14045 assert(starttet.loc < 4);
14046 // Add t into T.
14047 * (triface *)(* tetlist)[0] = starttet;
14048 infect(starttet);
14049 // Add three verts of t into V.
14050 ver[0] = org(starttet);
14051 ver[1] = dest(starttet);
14052 ver[2] = apex(starttet);
14053 for (i = 0; i < 3; i++) {
14054 // Mark the vert by inversing the index of the vert.
14055 idx = pointmark(ver[i]);
14056 setpointmark(ver[i], -idx - 1); // -1 to distinguish the zero.
14057 verlist->append(&(ver[i]));
14058 }
14059
14060 // Find other tets by a broadth-first search.
14061 for (i = 0; i < tetlist->len(); i++) {
14062 starttet = * (triface *)(* tetlist)[i];
14063 starttet.ver = 0;
14064 for (j = 0; j < 3; j++) {
14065 fnext(starttet, neightet);
14066 tspivot(neightet, checksh);
14067 // Should we cross a subface.
14068 if ((checksh.sh == dummysh) || complete) {
14069 // Get the neighbor n.
14070 symself(neightet);
14071 if ((neightet.tet != dummytet) && !infected(neightet)) {
14072 // Let oppo(n) = p.
14073 for (neightet.loc = 0; neightet.loc < 4; neightet.loc++) {
14074 if (oppo(neightet) == pt) break;
14075 }
14076 assert(neightet.loc < 4);
14077 // Add n into T.
14078 infect(neightet);
14079 tetlist->append(&neightet);
14080 ver[0] = org(starttet);
14081 ver[1] = dest(starttet);
14082 findedge(&neightet, ver[0], ver[1]);
14083 ver[2] = apex(neightet);
14084 idx = pointmark(ver[2]);
14085 if (idx >= 0) {
14086 setpointmark(ver[2], -idx - 1);
14087 verlist->append(&(ver[2]));
14088 }
14089 }
14090 }
14091 enextself(starttet);
14092 }
14093 }
14094
14095 // Uninfect tets.
14096 for (i = 0; i < tetlist->len(); i++) {
14097 starttet = * (triface *)(* tetlist)[i];
14098 uninfect(starttet);
14099 }
14100 // Uninfect vertices.
14101 for (i = 0; i < verlist->len(); i++) {
14102 ver[0] = * (point *)(* verlist)[i];
14103 idx = pointmark(ver[0]);
14104 setpointmark(ver[0], -(idx + 1));
14105 }
14106 }
14107
14108 ///////////////////////////////////////////////////////////////////////////////
14109 // //
14110 // unifypoint() Unify two distinct points if they're very close. //
14111 // //
14112 // This function is used for dealing with inputs from CAD tools. Two points //
14113 // p and q are unified if: dist(p, q) / longest < eps. Where dist() is the //
14114 // Euclidean distance between p and q, longest is the maximum edge size of //
14115 // the input point set, eps is the tolerrence specified by user, default is //
14116 // 1e-6, it can be adjusted by '-T' switch. //
14117 // //
14118 ///////////////////////////////////////////////////////////////////////////////
14119
14120 bool tetgenmesh::unifypoint(point testpt, triface *starttet, enum locateresult
14121 loc, REAL eps)
14122 {
14123 triface symtet, spintet;
14124 point checkpt, tapex;
14125 REAL tol;
14126 bool merged;
14127 int hitbdry;
14128 int i;
14129
14130 merged = false;
14131 tol = longest * eps;
14132 if ((loc == OUTSIDE) || (loc == INTETRAHEDRON) || (loc == ONFACE)) {
14133 // Check p is close to the four corners of the tet.
14134 for (i = 0; i < 4; i++) {
14135 checkpt = (point) starttet->tet[4 + i];
14136 if (distance(testpt, checkpt) < tol) {
14137 merged = true; // Found a merge point p'.
14138 break;
14139 }
14140 }
14141 if (!merged && (loc == ONFACE)) {
14142 // Check the opposite point of the neighbor tet if it exists.
14143 sym(*starttet, symtet);
14144 if (symtet.tet != dummytet) {
14145 checkpt = oppo(symtet);
14146 if (distance(testpt, checkpt) < tol) {
14147 merged = true; // Found a merge point p'.
14148 }
14149 }
14150 }
14151 } else if (loc == ONEDGE) {
14152 // Check two endpoints of the edge.
14153 checkpt = org(*starttet);
14154 if (distance(testpt, checkpt) < tol) {
14155 merged = true; // Found a merge point p'.
14156 }
14157 if (!merged) {
14158 checkpt = dest(*starttet);
14159 if (distance(testpt, checkpt) < tol) {
14160 merged = true; // Found a merge point p'.
14161 }
14162 }
14163 if (!merged) {
14164 // Check apexes of the faces having the edge.
14165 spintet = *starttet;
14166 tapex = apex(*starttet);
14167 hitbdry = 0;
14168 do {
14169 checkpt = apex(spintet);
14170 if (distance(testpt, checkpt) < tol) {
14171 merged = true; // Found a merge point p'.
14172 break;
14173 }
14174 if (!fnextself(spintet)) {
14175 hitbdry++;
14176 if (hitbdry < 2) {
14177 esym(*starttet, spintet);
14178 if (!fnextself(spintet)) {
14179 hitbdry++;
14180 }
14181 }
14182 }
14183 } while ((apex(spintet) != tapex) && (hitbdry < 2));
14184 }
14185 }
14186 if (merged) {
14187 if (b->object != tetgenbehavior::STL) {
14188 if (!b->quiet) {
14189 printf("Warning: Point %d is unified to point %d.\n",
14190 pointmark(testpt), pointmark(checkpt));
14191 }
14192 // Count the number of duplicated points.
14193 dupverts++;
14194 }
14195 // Remember it is a duplicated point.
14196 setpointtype(testpt, DUPLICATEDVERTEX);
14197 // Set a pointer to the point it duplicates.
14198 setpoint2ppt(testpt, checkpt);
14199 }
14200 return merged;
14201 }
14202
14203 ///////////////////////////////////////////////////////////////////////////////
14204 // //
14205 // closeopenface() Close "open" faces recursively. //
14206 // //
14207 // This is the support routine of inserthullsite(). A point p which lies out-//
14208 // side of CH(T). p is inserted to T by forming a tet t from p and a visible //
14209 // CH face f. The three sides of f which have p as a vertex is called "open" //
14210 // face. Each open face will be closed by either creating a tet on top of it //
14211 // or become a new CH face. //
14212 // //
14213 ///////////////////////////////////////////////////////////////////////////////
14214
14215 void tetgenmesh::closeopenface(triface* openface, queue* flipque)
14216 {
14217 triface newtet, oldhull;
14218 triface newopenface, closeface;
14219 point inspoint, pa, pb, pc;
14220 REAL attrib, volume;
14221 int i;
14222
14223 // Get the new point p.
14224 inspoint = apex(*openface);
14225 // Find the old CH face f_o (f and f_o share the same edge).
14226 esym(*openface, oldhull);
14227 while (fnextself(oldhull)) ;
14228 if (apex(oldhull) != inspoint) {
14229 // Is f_o visible by p?
14230 pa = org(oldhull);
14231 pb = dest(oldhull);
14232 pc = apex(oldhull);
14233 if (orient3d(pa, pb, pc, inspoint) < 0.0) {
14234 // Yes. Create a new tet t above f_o.
14235 maketetrahedron(&newtet);
14236 setorg(newtet, pa);
14237 setdest(newtet, pb);
14238 setapex(newtet, pc);
14239 setoppo(newtet, inspoint);
14240 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
14241 attrib = elemattribute(oldhull.tet, i);
14242 setelemattribute(newtet.tet, i, attrib);
14243 }
14244 if (b->varvolume) {
14245 volume = volumebound(oldhull.tet);
14246 setvolumebound(newtet.tet, volume);
14247 }
14248 // Connect t to T.
14249 bond(newtet, oldhull);
14250 // Close f.
14251 fnext(newtet, newopenface);
14252 bond(newopenface, *openface);
14253 // f_o becomes an interior face.
14254 enqueueflipface(oldhull, flipque);
14255 // Hull face number decreases.
14256 hullsize--;
14257 // Two faces of t become open face.
14258 enextself(newtet);
14259 for (i = 0; i < 2; i++) {
14260 fnext(newtet, newopenface);
14261 sym(newopenface, closeface);
14262 if (closeface.tet == dummytet) {
14263 closeopenface(&newopenface, flipque);
14264 }
14265 enextself(newtet);
14266 }
14267 } else {
14268 // Inivisible. f becomes a new CH face.
14269 hullsize++;
14270 // Let 'dummytet' holds f for the next point location.
14271 dummytet[0] = encode(*openface);
14272 }
14273 } else {
14274 // f_o is co-incident with f --> f is closed by f_o.
14275 bond(*openface, oldhull);
14276 // f is an interior face.
14277 enqueueflipface(*openface, flipque);
14278 }
14279 }
14280
14281 ///////////////////////////////////////////////////////////////////////////////
14282 // //
14283 // inserthullsite() Insert a point which lies outside the convex hull. //
14284 // //
14285 // The 'inspoint' p lies outside the tetrahedralization T. The 'horiz' f is //
14286 // on the convex hull of T, CH(T), which is visible by p (Imagine f is para- //
14287 // llel to the horizon). To insert p into T we have to enlarge the CH(T) and //
14288 // update T so that p is on the new CH(T). //
14289 // //
14290 // To enlarge the CH(T). We need to find the set F of faces which are on CH //
14291 // (T) and visible by p (F can be formed by a depth-first search from f). p //
14292 // is then inserted into T by mounting new tets formed by p and these faces. //
14293 // Faces of F become interior faces and may non-locally Delaunay. They are //
14294 // queued in 'flipqueue' for flip tests. //
14295 // //
14296 ///////////////////////////////////////////////////////////////////////////////
14297
14298 void tetgenmesh::inserthullsite(point inspoint, triface* horiz, queue* flipque)
14299 {
14300 triface firstnewtet;
14301 triface openface, closeface;
14302 REAL attrib, volume;
14303 int i;
14304
14305 // Let f face to p.
14306 adjustedgering(*horiz, CW);
14307 // Create the first tet t (from f and p).
14308 maketetrahedron(&firstnewtet);
14309 setorg (firstnewtet, org(*horiz));
14310 setdest(firstnewtet, dest(*horiz));
14311 setapex(firstnewtet, apex(*horiz));
14312 setoppo(firstnewtet, inspoint);
14313 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
14314 attrib = elemattribute(horiz->tet, i);
14315 setelemattribute(firstnewtet.tet, i, attrib);
14316 }
14317 if (b->varvolume) {
14318 volume = volumebound(horiz->tet);
14319 setvolumebound(firstnewtet.tet, volume);
14320 }
14321 // Connect t to T.
14322 bond(firstnewtet, *horiz);
14323 // f is not on CH(T) anymore.
14324 enqueueflipface(*horiz, flipque);
14325 // Hull face number decreases.
14326 hullsize--;
14327
14328 // Call the faces of t which have p as a vertex "open" face.
14329 for (i = 0; i < 3; i++) {
14330 // Get an open face f_i of t.
14331 fnext(firstnewtet, openface);
14332 // Close f_i if it is still open.
14333 sym(openface, closeface);
14334 if (closeface.tet == dummytet) {
14335 closeopenface(&openface, flipque);
14336 }
14337 // Go to the next open face of t.
14338 enextself(firstnewtet);
14339 }
14340 }
14341
14342 ///////////////////////////////////////////////////////////////////////////////
14343 // //
14344 // incrflipdelaunay() Construct a delaunay tetrahedrization from a set of //
14345 // 3D points by the incremental flip algorithm. //
14346 // //
14347 // The incremental flip algorithm (by Edelsbrunner and Shah) can be describ- //
14348 // ed as follows: //
14349 // //
14350 // S be a set of points in 3D, Let 4 <= i <= n and assume that the //
14351 // Delaunay tetrahedralization of the first i-1 points in S is already //
14352 // constructed; call it D(i-1). Add the i-th point p_i (belong to S) to //
14353 // D(i-1), and restore Delaunayhood by flipping; this result in D(i). //
14354 // Repeat this procedure until i = n. //
14355 // //
14356 // This strategy always leads to the Delaunay triangulation of a point set. //
14357 // The return value is the number of convex hull faces of D. //
14358 // //
14359 ///////////////////////////////////////////////////////////////////////////////
14360
14361 void tetgenmesh::incrflipdelaunay(triface* oldtet, point* insertarray,
14362 long arraysize, bool jump, bool merge, REAL eps, queue* flipque)
14363 {
14364 triface newtet, searchtet;
14365 point swappt, lastpt;
14366 enum locateresult loc;
14367 REAL det, n[3];
14368 REAL attrib, volume;
14369 int i, j;
14370
14371 if (b->verbose > 0) {
14372 printf(" Creating initial tetrahedralization.\n");
14373 }
14374
14375 // The initial tetrahedralization T only has one tet formed by 4 affinely
14376 // linear independent vertices of the point set V = 'insertarray'. The
14377 // first point a = insertarray[0].
14378
14379 // Get the second point b, that is not identical or very close to a.
14380 for (i = 1; i < arraysize; i++) {
14381 det = distance(insertarray[0], insertarray[i]);
14382 if (det > (longest * eps)) break;
14383 }
14384 if (i == arraysize) {
14385 printf("\nAll points seem to be identical.\n");
14386 return;
14387 } else {
14388 // Swap to move b from index i to index 1.
14389 swappt = insertarray[i];
14390 insertarray[i] = insertarray[1];
14391 insertarray[1] = swappt;
14392 }
14393 // Get the third point c, that is not collinear with a and b.
14394 for (i++; i < arraysize; i++) {
14395 if (!iscollinear(insertarray[0], insertarray[1], insertarray[i], eps))
14396 break;
14397 }
14398 if (i == arraysize) {
14399 printf("\nAll points seem to be collinear.\n");
14400 return;
14401 } else {
14402 // Swap to move c from index i to index 2.
14403 swappt = insertarray[i];
14404 insertarray[i] = insertarray[2];
14405 insertarray[2] = swappt;
14406 }
14407 // Get the fourth point d, that is not coplanar with a, b, and c.
14408 for (i++; i < arraysize; i++) {
14409 det = orient3d(insertarray[0], insertarray[1], insertarray[2],
14410 insertarray[i]);
14411 if (det == 0.0) continue;
14412 if (!iscoplanar(insertarray[0], insertarray[1], insertarray[2],
14413 insertarray[i], det, eps)) break;
14414 }
14415 if (i == arraysize) {
14416 // It's a 2D problem.
14417 in->mesh_dim = 2;
14418 // All points are coplanar.
14419 if (b->plc) {
14420 // Create an abovepoint. Maybe a surface triangulation can be formed.
14421 facenormal(insertarray[0], insertarray[1], insertarray[2], n, &det);
14422 if (det != 0.0) for (j = 0; j < 3; j++) n[j] /= det;
14423 // Take the average edge length of the bounding box.
14424 det = (0.5*(xmax - xmin) + 0.5*(ymax - ymin) + 0.5*(zmax - zmin)) / 3.0;
14425 // Temporarily create a point. It will be removed by jettison();
14426 makepoint(&lastpt);
14427 for (j = 0; j < 3; j++) lastpt[j] = insertarray[0][j] + det * n[j];
14428 abovepoint = lastpt;
14429 det = orient3d(insertarray[0], insertarray[1], insertarray[2], lastpt);
14430 // The index of the next inserting point is 3.
14431 i = 3;
14432 } else {
14433 printf("\nAll points seem to be coplanar.\n");
14434 return;
14435 }
14436 } else {
14437 // Swap to move d from index i to index 3.
14438 swappt = insertarray[i];
14439 insertarray[i] = insertarray[3];
14440 insertarray[3] = swappt;
14441 lastpt = insertarray[3];
14442 // The index of the next inserting point is 4.
14443 i = 4;
14444 }
14445
14446 // Create the initial tet.
14447 maketetrahedron(&newtet);
14448 if (det > 0.0) {
14449 // For keeping the positive orientation.
14450 swappt = insertarray[0];
14451 insertarray[0] = insertarray[1];
14452 insertarray[1] = swappt;
14453 }
14454 setorg(newtet, insertarray[0]);
14455 setdest(newtet, insertarray[1]);
14456 setapex(newtet, insertarray[2]);
14457 setoppo(newtet, lastpt);
14458 if (oldtet != (triface *) NULL) {
14459 for (j = 0; j < in->numberoftetrahedronattributes; j++) {
14460 attrib = elemattribute(oldtet->tet, j);
14461 setelemattribute(newtet.tet, j, attrib);
14462 }
14463 if (b->varvolume) {
14464 volume = volumebound(oldtet->tet);
14465 setvolumebound(newtet.tet, volume);
14466 }
14467 }
14468 // Set vertex type be VOLVERTEX if it has no type yet.
14469 if (pointtype(insertarray[0]) == UNUSEDVERTEX) {
14470 setpointtype(insertarray[0], VOLVERTEX);
14471 }
14472 if (pointtype(insertarray[1]) == UNUSEDVERTEX) {
14473 setpointtype(insertarray[1], VOLVERTEX);
14474 }
14475 if (pointtype(insertarray[2]) == UNUSEDVERTEX) {
14476 setpointtype(insertarray[2], VOLVERTEX);
14477 }
14478 if (pointtype(lastpt) == UNUSEDVERTEX) {
14479 setpointtype(lastpt, VOLVERTEX);
14480 }
14481 // Bond to 'dummytet' for point location.
14482 dummytet[0] = encode(newtet);
14483 if (b->verbose > 3) {
14484 printf(" Creating tetra ");
14485 printtet(&newtet);
14486 }
14487 // At init, all faces of this tet are hull faces.
14488 hullsize = 4;
14489
14490 if (b->verbose > 0) {
14491 printf(" Incrementally inserting points.\n");
14492 }
14493
14494 flip23s = flip32s = flip22s = flip44s = 0;
14495 searchtet.tet = (tetrahedron *) NULL;
14496
14497 // Insert the rest of points, one by one.
14498 for (; i < arraysize; i++) {
14499 // Locate p_i in T.
14500 if (jump) {
14501 loc = locate(insertarray[i], &searchtet);
14502 } else {
14503 loc = preciselocate(insertarray[i], &searchtet, tetrahedrons->items);
14504 }
14505 // Keep current search state for next searching.
14506 recenttet = searchtet;
14507 if (loc == ONVERTEX) {
14508 if (b->object != tetgenbehavior::STL) {
14509 if (!b->quiet) {
14510 printf("Warning: Point %d is identical with point %d.\n",
14511 pointmark(insertarray[i]), pointmark(org(searchtet)));
14512 }
14513 }
14514 // Count the number of duplicated points.
14515 dupverts++;
14516 // Remember it is a duplicated point.
14517 setpointtype(insertarray[i], DUPLICATEDVERTEX);
14518 if (b->plc || b->refine) {
14519 // Set a pointer to the point it duplicates.
14520 setpoint2ppt(insertarray[i], org(searchtet));
14521 }
14522 continue; // p_i is not inserted.
14523 }
14524 if (merge) {
14525 // Unify p_i if it is too close to a point of T.
14526 if (unifypoint(insertarray[i], &searchtet, loc, eps)) {
14527 continue; // p_i is not inserted.
14528 }
14529 }
14530 // Insert p_i in T.
14531 if (loc != OUTSIDE) {
14532 if (b->verbose > 1) {
14533 printf(" Insert point %d in tetrahedralization.\n",
14534 pointmark(insertarray[i]));
14535 }
14536 if (loc == INTETRAHEDRON) {
14537 splittetrahedron(insertarray[i], &searchtet, flipque);
14538 } else if (loc == ONFACE) {
14539 splittetface(insertarray[i], &searchtet, flipque);
14540 } else if (loc == ONEDGE) {
14541 splittetedge(insertarray[i], &searchtet, flipque);
14542 }
14543 } else {
14544 if (b->verbose > 1) {
14545 printf(" Insert point %d on convex hull.\n",
14546 pointmark(insertarray[i]));
14547 }
14548 inserthullsite(insertarray[i], &searchtet, flipque);
14549 }
14550 if (pointtype(insertarray[i]) == UNUSEDVERTEX) {
14551 // p_i becomes a (volume) vertex of T.
14552 setpointtype(insertarray[i], VOLVERTEX);
14553 }
14554 if (!b->noflip) {
14555 // Recover Delaunayness of T by flipping.
14556 flip(flipque, NULL);
14557 } else {
14558 // T remains regular.
14559 flipque->clear();
14560 }
14561 }
14562
14563 if (!b->noflip && b->verbose > 0) {
14564 printf(" %ld Flips (T23 %ld, T32 %ld, T22 %ld, T44 %ld)\n",
14565 flip23s+flip32s+flip22s+flip44s, flip23s, flip32s, flip22s, flip44s);
14566 }
14567 }
14568
14569 ///////////////////////////////////////////////////////////////////////////////
14570 // //
14571 // delaunizevertices() Form a Delaunay tetrahedralization. //
14572 // //
14573 // Given a point set V (saved in 'points'). The Delaunay tetrahedralization //
14574 // D of V is created by incrementally inserting vertices. Returns the number //
14575 // of triangular faces bounding the convex hull of D. //
14576 // //
14577 ///////////////////////////////////////////////////////////////////////////////
14578
14579 long tetgenmesh::delaunizevertices()
14580 {
14581 queue *flipque;
14582 point *insertarray;
14583 long arraysize;
14584 int i, j;
14585
14586
14587 if (!b->quiet) {
14588 if (!b->noflip) {
14589 printf("Constructing Delaunay tetrahedralization.\n");
14590 } else {
14591 printf("Constructing regular tetrahedralization.\n");
14592 }
14593 }
14594
14595
14596 // Prepare the array of points for inserting.
14597 arraysize = points->items;
14598 insertarray = new point[arraysize];
14599 // Randomize the point order.
14600 // randomseed = b->srandseed;
14601 points->traversalinit();
14602 for (i = 0; i < arraysize; i++) {
14603 j = (int) randomnation(i + 1); // 0 <= j <= i;
14604 insertarray[i] = insertarray[j];
14605 insertarray[j] = pointtraverse();
14606 }
14607 flipque = new queue(sizeof(badface));
14608
14609 // Form the DT by incremental flip Delaunay algorithm.
14610 incrflipdelaunay(NULL, insertarray, arraysize, true, b->plc, b->epsilon,
14611 flipque);
14612
14613 delete [] insertarray;
14614 delete flipque;
14615 return hullsize;
14616 }
14617
14618 //
14619 // End Delaunay tetrahedralization routines
14620 //
14621
14622 //
14623 // Begin of surface triangulation routines
14624 //
14625
14626 ///////////////////////////////////////////////////////////////////////////////
14627 // //
14628 // formstarpolygon() Form the star polygon of a point in facet. //
14629 // //
14630 // The polygon P is formed by all coplanar subfaces having 'pt' as a vertex. //
14631 // P is bounded by segments, e.g, if no segments, P is the full star of pt. //
14632 // //
14633 // 'trilist' T returns the subfaces, it has one of such subfaces on input. //
14634 // In addition, if f is in T, then sapex(f) = p. 'vertlist' V are verts of P.//
14635 // Topologically, T is the star of p; V and the edges of T are the link of p.//
14636 // //
14637 ///////////////////////////////////////////////////////////////////////////////
14638
14639 void tetgenmesh::formstarpolygon(point pt, list* trilist, list* vertlist)
14640 {
14641 face steinsh, lnextsh, rnextsh;
14642 face checkseg;
14643 point pa, pb, pc, pd;
14644 int i;
14645
14646 // Get a subface f containing p.
14647 steinsh = * (face *)(* trilist)[0];
14648 steinsh.shver = 0; // CCW
14649 // Let sapex(f) be p.
14650 for (i = 0; i < 3; i++) {
14651 if (sapex(steinsh) == pt) break;
14652 senextself(steinsh);
14653 }
14654 assert(i < 3);
14655 * (face *)(* trilist)[0] = steinsh;
14656 // Add two verts a, b and one edge ab of f into lists,
14657 pa = sorg(steinsh);
14658 pb = sdest(steinsh);
14659 vertlist->append(&pa);
14660 vertlist->append(&pb);
14661
14662 // Rotate edge pa to the left (CW) until meet pb or a segment.
14663 lnextsh = steinsh;
14664 pc = pa;
14665 do {
14666 senext2self(lnextsh);
14667 assert(sorg(lnextsh) == pt);
14668 sspivot(lnextsh, checkseg);
14669 if (checkseg.sh != dummysh) break; // Do not cross a segment.
14670 // Get neighbor subface n (must exist).
14671 spivotself(lnextsh);
14672 if (lnextsh.sh == dummysh) break; // It's a hull edge.
14673 // Go to the edge ca opposite to p.
14674 if (sdest(lnextsh) != pt) sesymself(lnextsh);
14675 assert(sdest(lnextsh) == pt);
14676 senext2self(lnextsh);
14677 // Add n (at edge ca) to T.
14678 trilist->append(&lnextsh);
14679 // Add edge ca to E.
14680 pc = sorg(lnextsh);
14681 if (pc == pb) break; // Rotate back.
14682 // Add vert c to V.
14683 vertlist->append(&pc);
14684 } while (true);
14685
14686 if (pc != pb) {
14687 // Rotate edge bp to the right (CCW) until meet a segment.
14688 rnextsh = steinsh;
14689 do {
14690 senextself(rnextsh);
14691 assert(sdest(rnextsh) == pt);
14692 sspivot(rnextsh, checkseg);
14693 if (checkseg.sh != dummysh) break; // Do not cross a segment.
14694 // Get neighbor subface n (must exist).
14695 spivotself(rnextsh);
14696 if (rnextsh.sh == dummysh) break; // It's a hull edge.
14697 // Go to the edge bd opposite to p.
14698 if (sorg(rnextsh) != pt) sesymself(rnextsh);
14699 assert(sorg(rnextsh) == pt);
14700 senextself(rnextsh);
14701 // Add n (at edge bd) to T.
14702 trilist->append(&rnextsh);
14703 // Add edge bd to E.
14704 pd = sdest(rnextsh);
14705 if (pd == pa) break; // Rotate back.
14706 // Add vert d to V.
14707 vertlist->append(&pd);
14708 } while (true);
14709 }
14710 }
14711
14712 ///////////////////////////////////////////////////////////////////////////////
14713 // //
14714 // About the 'abovepoint' //
14715 // //
14716 // The 'abovepoint' of a facet is a point which is exactly non-coplanar with //
14717 // the plane containing that facet. With such an point, the 3D predicates: //
14718 // orient3d(), and insphere() can be used to substitute the corresponding 2D //
14719 // siblings, e.g. orient2d(), and incircle(). Its location is not critical, //
14720 // but floating-point accuracy is improved if it is nicely placed over the //
14721 // facet, not too close or too far away. //
14722 // //
14723 // We take the convention that the abovepoint of a facet always lies above //
14724 // the facet. By this convention, given three points a, b, and c in a facet, //
14725 // we say c has the counterclockwise order with ab is corresponding to say //
14726 // that c is below the plane abp, where p is the lift point. //
14727 // //
14728 ///////////////////////////////////////////////////////////////////////////////
14729
14730 ///////////////////////////////////////////////////////////////////////////////
14731 // //
14732 // getfacetabovepoint() Get a point above a plane pass through a facet. //
14733 // //
14734 // The calulcated point is saved in 'facetabovepointarray'. The 'abovepoint' //
14735 // is set on return. //
14736 // //
14737 ///////////////////////////////////////////////////////////////////////////////
14738
14739 void tetgenmesh::getfacetabovepoint(face* facetsh)
14740 {
14741 list *verlist, *trilist, *tetlist;
14742 tetrahedron tetptr;
14743 triface adjtet;
14744 face symsh;
14745 point p1, p2, p3, pa;
14746 enum locateresult loc;
14747 REAL smallcos, cosa;
14748 REAL largevol, volume;
14749 REAL v1[3], v2[3], len;
14750 int smallidx, largeidx;
14751 int shmark;
14752 int i, j;
14753
14754 abovecount++;
14755 // Initialize working lists.
14756 verlist = new list(sizeof(point *), NULL);
14757 trilist = new list(sizeof(face), NULL);
14758 tetlist = new list(sizeof(triface), NULL);
14759
14760 // Get three pivotal points p1, p2, and p3 in the facet as a base triangle
14761 // which is non-trivil and has good base angle (close to 90 degree).
14762
14763 // p1 is chosen as the one which has the smallest index in pa, pb, pc.
14764 p1 = sorg(*facetsh);
14765 pa = sdest(*facetsh);
14766 if (pointmark(pa) < pointmark(p1)) p1 = pa;
14767 pa = sapex(*facetsh);
14768 if (pointmark(pa) < pointmark(p1)) p1 = pa;
14769 // Form the star polygon of p1.
14770 trilist->append(facetsh);
14771 formstarpolygon(p1, trilist, verlist);
14772
14773 // Get the second pivotal point p2.
14774 p2 = * (point *)(* verlist)[0];
14775 // Get vector v1 = p1->p2.
14776 for (i = 0; i < 3; i++) v1[i] = p2[i] - p1[i];
14777 len = sqrt(dot(v1, v1));
14778 assert(len > 0.0); // p2 != p1.
14779 for (i = 0; i < 3; i++) v1[i] /= len;
14780
14781 // Get the third pivotal point p3. p3 is chosen as the one in 'verlist'
14782 // which forms an angle with v1 closer to 90 degree than others do.
14783 smallcos = 1.0; // The cosine value of 0 degree.
14784 smallidx = 1; // Default value.
14785 for (i = 1; i < verlist->len(); i++) {
14786 p3 = * (point *)(* verlist)[i];
14787 for (j = 0; j < 3; j++) v2[j] = p3[j] - p1[j];
14788 len = sqrt(dot(v2, v2));
14789 if (len > 0.0) { // v2 is not too small.
14790 cosa = fabs(dot(v1, v2)) / len;
14791 if (cosa < smallcos) {
14792 smallidx = i;
14793 smallcos = cosa;
14794 }
14795 }
14796 }
14797 assert(smallcos < 1.0); // p1->p3 != p1->p2.
14798 p3 = * (point *)(* verlist)[smallidx];
14799 verlist->clear();
14800
14801 if (tetrahedrons->items > 0l) {
14802 // Get a tet having p1 as a vertex.
14803 stpivot(*facetsh, adjtet);
14804 if (adjtet.tet == dummytet) {
14805 sesym(*facetsh, symsh);
14806 stpivot(symsh, adjtet);
14807 }
14808 if (adjtet.tet == dummytet) {
14809 tetptr = point2tet(p1);
14810 if (tetptr != (tetrahedron) NULL) {
14811 decode(tetptr, adjtet);
14812 if (isdead(&adjtet)) {
14813 adjtet.tet = dummytet;
14814 }
14815 }
14816 }
14817 if (adjtet.tet == dummytet) {
14818 loc = locate(p1, &adjtet);
14819 if (loc != ONVERTEX) adjtet.tet = dummytet;
14820 }
14821 if (adjtet.tet != dummytet) {
14822 // Get the star polyhedron of p1.
14823 tetlist->append(&adjtet);
14824 formstarpolyhedron(p1, tetlist, verlist, false);
14825 }
14826 }
14827
14828 // Get the abovepoint in 'verlist'. It is the one form the largest valid
14829 // volumw with the base triangle over other points in 'verlist.
14830 largevol = 0.0;
14831 largeidx = 0;
14832 for (i = 0; i < verlist->len(); i++) {
14833 pa = * (point *)(* verlist)[i];
14834 volume = orient3d(p1, p2, p3, pa);
14835 if (!iscoplanar(p1, p2, p3, pa, volume, b->epsilon * 1e+2)) {
14836 if (fabs(volume) > largevol) {
14837 largevol = fabs(volume);
14838 largeidx = i;
14839 }
14840 }
14841 }
14842
14843 // Do we have the abovepoint?
14844 if (largevol > 0.0) {
14845 abovepoint = * (point *)(* verlist)[largeidx];
14846 if (b->verbose > 1) {
14847 printf(" Chosen abovepoint %d for facet %d.\n", pointmark(abovepoint),
14848 shellmark(*facetsh));
14849 }
14850 } else {
14851 // Calculate an abovepoint for this facet.
14852 facenormal(p1, p2, p3, v1, &len);
14853 if (len != 0.0) for (i = 0; i < 3; i++) v1[i] /= len;
14854 // Take the average edge length of the bounding box.
14855 len = (0.5*(xmax - xmin) + 0.5*(ymax - ymin) + 0.5*(zmax - zmin)) / 3.0;
14856 // Temporarily create a point. It will be removed by jettison();
14857 makepoint(&abovepoint);
14858 setpointtype(abovepoint, UNUSEDVERTEX);
14859 unuverts++;
14860 for (i = 0; i < 3; i++) abovepoint[i] = p1[i] + len * v1[i];
14861 if (b->verbose > 1) {
14862 printf(" Calculated abovepoint %d for facet %d.\n",
14863 pointmark(abovepoint), shellmark(*facetsh));
14864 }
14865 }
14866 // Save the abovepoint in 'facetabovepointarray'.
14867 shmark = shellmark(*facetsh);
14868 facetabovepointarray[shmark] = abovepoint;
14869
14870 delete trilist;
14871 delete tetlist;
14872 delete verlist;
14873 }
14874
14875 ///////////////////////////////////////////////////////////////////////////////
14876 // //
14877 // collectcavsubs() Collect non-locally Delaunay subfaces wrt a point. //
14878 // //
14879 // 'cavsublist' returns the list of subfaces. On input, it conatins at least //
14880 // one subface. //
14881 // //
14882 ///////////////////////////////////////////////////////////////////////////////
14883
14884 void tetgenmesh::collectcavsubs(point newpoint, list* cavsublist)
14885 {
14886 face startsub, neighsub;
14887 face checkseg;
14888 point pa, pb, pc;
14889 REAL sign, ori;
14890 int i, j;
14891
14892 // First infect subfaces in 'cavsublist'.
14893 for (i = 0; i < cavsublist->len(); i++) {
14894 startsub = * (face *)(* cavsublist)[i];
14895 sinfect(startsub);
14896 }
14897 // Find the other subfaces by a broadth-first searching.
14898 for (i = 0; i < cavsublist->len(); i++) {
14899 startsub = * (face *)(* cavsublist)[i];
14900 for (j = 0; j < 3; j++) {
14901 sspivot(startsub, checkseg);
14902 // Is there a segment?
14903 if (checkseg.sh == dummysh) {
14904 // No segment. Get the neighbor.
14905 spivot(startsub, neighsub);
14906 if (!sinfected(neighsub)) {
14907 pa = sorg(neighsub);
14908 pb = sdest(neighsub);
14909 pc = sapex(neighsub);
14910 sign = insphere(pa, pb, pc, abovepoint, newpoint);
14911 ori = orient3d(pa, pb, pc, abovepoint);
14912 if (sign != 0.0) {
14913 // Correct the sign.
14914 sign = ori > 0.0 ? sign : -sign;
14915 }
14916 if (sign > 0.0) {
14917 // neighsub is encroached by newpoint.
14918 sinfect(neighsub);
14919 cavsublist->append(&neighsub);
14920 }
14921 }
14922 }
14923 senextself(startsub);
14924 }
14925 }
14926 // Having found all subfaces, uninfect them before return.
14927 for (i = 0; i < cavsublist->len(); i++) {
14928 startsub = * (face *)(* cavsublist)[i];
14929 suninfect(startsub);
14930 }
14931 }
14932
14933 ///////////////////////////////////////////////////////////////////////////////
14934 // //
14935 // collectvisiblesubs() Collect convex hull edges which are visible from //
14936 // the inserting point. Construct new subfaces from //
14937 // these edges and the point. //
14938 // //
14939 // Let T be the current Delaunay triangulation (of vertices of a facet F). //
14940 // 'shmark', the index of F in 'in->facetlist' (starts from 1); 'inspoint' //
14941 // lies outside of T; 'horiz' is a hull edge of T which is visible by it. //
14942 // //
14943 ///////////////////////////////////////////////////////////////////////////////
14944
14945 void tetgenmesh::collectvisiblesubs(int shmark, point inspoint, face* horiz,
14946 queue* flipqueue)
14947 {
14948 face newsh, hullsh;
14949 face rightsh, leftsh, spinedge;
14950 point horg, hdest;
14951 bool aboveflag;
14952 REAL ori, sign;
14953
14954 // Get the sign of abovepoint (so we can assume it is above the plane).
14955 adjustedgering(*horiz, CCW);
14956 horg = sorg(*horiz);
14957 hdest = sdest(*horiz);
14958 ori = orient3d(horg, hdest, sapex(*horiz), abovepoint);
14959 sign = ori > 0.0 ? -1 : 1;
14960
14961 // Create a new subface above 'horiz'.
14962 makeshellface(subfaces, &newsh);
14963 setsorg(newsh, hdest);
14964 setsdest(newsh, horg);
14965 setsapex(newsh, inspoint);
14966 setshellmark(newsh, shmark);
14967 if (b->quality && varconstraint) {
14968 setareabound(newsh, areabound(*horiz));
14969 }
14970 if (checkpbcs) {
14971 setshellpbcgroup(newsh, shellpbcgroup(*horiz));
14972 }
14973 // Make the connection.
14974 sbond(newsh, *horiz);
14975 // 'horiz' becomes interior edge.
14976 enqueueflipedge(*horiz, flipqueue);
14977
14978 // Finish the hull edges at the right side of the newsh.
14979 hullsh = *horiz;
14980 while (1) {
14981 senext(newsh, rightsh);
14982 // Get the right hull edge of 'horiz' by spinning inside edges around
14983 // 'horg' until reaching the 'dummysh'.
14984 spinedge = hullsh;
14985 do {
14986 hullsh = spinedge;
14987 senext2self(hullsh);
14988 spivot(hullsh, spinedge);
14989 if (spinedge.sh == dummysh) break;
14990 if (sorg(spinedge) != horg) sesymself(spinedge);
14991 assert(sorg(spinedge) == horg);
14992 } while (true);
14993 horg = sorg(hullsh);
14994 // Test whether 'inspoint' is visible by 'hullsh'.
14995 ori = orient3d(horg, sdest(hullsh), abovepoint, inspoint);
14996 ori *= sign;
14997 aboveflag = ori < 0.0;
14998 if (aboveflag) {
14999 // It's visible.
15000 makeshellface(subfaces, &newsh);
15001 setsorg(newsh, sdest(hullsh));
15002 setsdest(newsh, horg);
15003 setsapex(newsh, inspoint);
15004 setshellmark(newsh, shmark);
15005 if (b->quality && varconstraint) {
15006 setareabound(newsh, areabound(hullsh));
15007 }
15008 if (checkpbcs) {
15009 setshellpbcgroup(newsh, shellpbcgroup(hullsh));
15010 }
15011 // Make the connection.
15012 sbond(newsh, hullsh);
15013 senext2(newsh, leftsh);
15014 sbond(leftsh, rightsh);
15015 // 'hullsh' becomes interior edge.
15016 enqueueflipedge(hullsh, flipqueue);
15017 } else {
15018 // 'rightsh' is a new hull edge.
15019 dummysh[0] = sencode(rightsh);
15020 break;
15021 }
15022 }
15023
15024 // Finish the hull edges at the left side of the newsh.
15025 hullsh = *horiz;
15026 spivot(*horiz, newsh);
15027 while (1) {
15028 senext2(newsh, leftsh);
15029 // Get the left hull edge of 'horiz' by spinning edges around 'hdest'.
15030 spinedge = hullsh;
15031 do {
15032 hullsh = spinedge;
15033 senextself(hullsh);
15034 spivot(hullsh, spinedge);
15035 if (spinedge.sh == dummysh) break;
15036 if (sdest(spinedge) != hdest) sesymself(spinedge);
15037 assert(sdest(spinedge) == hdest);
15038 } while (true);
15039 // Update 'hdest'.
15040 hdest = sdest(hullsh);
15041 // Test whether 'inspoint' is visible from 'hullsh'.
15042 ori = orient3d(sorg(hullsh), hdest, abovepoint, inspoint);
15043 ori *= sign;
15044 aboveflag = ori < 0.0;
15045 if (aboveflag) {
15046 // It's a visible hull edge.
15047 makeshellface(subfaces, &newsh);
15048 setsorg(newsh, hdest);
15049 setsdest(newsh, sorg(hullsh));
15050 setsapex(newsh, inspoint);
15051 setshellmark(newsh, shmark);
15052 if (b->quality && varconstraint) {
15053 setareabound(newsh, areabound(hullsh));
15054 }
15055 if (checkpbcs) {
15056 setshellpbcgroup(newsh, shellpbcgroup(hullsh));
15057 }
15058 // Make the connection.
15059 sbond(newsh, hullsh);
15060 senext(newsh, rightsh);
15061 sbond(rightsh, leftsh);
15062 // 'horiz' becomes interior edge.
15063 enqueueflipedge(hullsh, flipqueue);
15064 } else {
15065 // 'leftsh' is a new hull edge.
15066 dummysh[0] = sencode(leftsh);
15067 break;
15068 }
15069 }
15070 }
15071
15072 ///////////////////////////////////////////////////////////////////////////////
15073 // //
15074 // incrflipdelaunaysub() Create a DT from a 3D coplanar point set using //
15075 // the incremental flip algorithm. //
15076 // //
15077 // Let T be the current Delaunay triangulation (of vertices of a facet F). //
15078 // 'shmark', the index of F in 'in->facetlist' (starts from 1). //
15079 // //
15080 ///////////////////////////////////////////////////////////////////////////////
15081
15082 void tetgenmesh::incrflipdelaunaysub(int shmark, REAL eps, list* ptlist,
15083 int holes, REAL* holelist, queue* flipque)
15084 {
15085 face newsh, startsh;
15086 point *insertarray;
15087 point swappt;
15088 pbcdata *pd;
15089 enum locateresult loc;
15090 REAL det, area;
15091 bool aboveflag;
15092 int arraysize;
15093 int fmarker;
15094 int idx, i, j, k;
15095
15096 // Get the point array (saved in 'ptlist').
15097 insertarray = (point *) ptlist->base;
15098 arraysize = ptlist->len();
15099 if (arraysize < 3) return;
15100
15101 // Do calculation of 'abovepoint' if number of points > 3.
15102 aboveflag = (arraysize > 3);
15103
15104 // The initial triangulation T only has one triangle formed by 3 not
15105 // cillinear points of the set V = 'insertarray'. The first point:
15106 // a = insertarray[0].
15107
15108 for (i = 1; i < arraysize; i++) {
15109 det = distance(insertarray[0], insertarray[i]);
15110 if (det > (longest * eps)) break;
15111 }
15112 if (i < arraysize) {
15113 // Swap to move b from index i to index 1.
15114 swappt = insertarray[i];
15115 insertarray[i] = insertarray[1];
15116 insertarray[1] = swappt;
15117 }
15118 // Get the third point c, that is not collinear with a and b.
15119 for (i++; i < arraysize; i++) {
15120 if (!iscollinear(insertarray[0], insertarray[1], insertarray[i], eps))
15121 break;
15122 }
15123 if (i < arraysize) {
15124 // Swap to move c from index i to index 2.
15125 swappt = insertarray[i];
15126 insertarray[i] = insertarray[2];
15127 insertarray[2] = swappt;
15128 i = 3; // The next inserting point.
15129 } else {
15130 // The set of vertices is not good (or nearly degenerate). However,
15131 // a trivial triangulation can be formed (using 3 vertices). It may
15132 // be corrected (or deleted) by mergefacet().
15133 if (eps == 0.0) {
15134 if (!b->quiet) {
15135 printf("Warning: Facet %d (%d, %d, %d", shmark,
15136 pointmark(insertarray[0]), pointmark(insertarray[1]),
15137 pointmark(insertarray[2]));
15138 if (ptlist->len() > 3) {
15139 printf(", ...");
15140 }
15141 printf(") is not a valid polygon.\n");
15142 }
15143 }
15144 // Only use the first three points.
15145 i = arraysize;
15146 // Don't do calculation of abovepoint.
15147 aboveflag = false;
15148 }
15149
15150 // Create the initial triangle.
15151 makeshellface(subfaces, &newsh);
15152 setsorg(newsh, insertarray[0]);
15153 setsdest(newsh, insertarray[1]);
15154 setsapex(newsh, insertarray[2]);
15155 // Remeber the facet it belongs to.
15156 setshellmark(newsh, shmark);
15157 // Set vertex type be FACETVERTEX if it has no type yet.
15158 if (pointtype(insertarray[0]) == VOLVERTEX) {
15159 setpointtype(insertarray[0], FACETVERTEX);
15160 }
15161 if (pointtype(insertarray[1]) == VOLVERTEX) {
15162 setpointtype(insertarray[1], FACETVERTEX);
15163 }
15164 if (pointtype(insertarray[2]) == VOLVERTEX) {
15165 setpointtype(insertarray[2], FACETVERTEX);
15166 }
15167 // Let 'dummysh' point to it (for point location).
15168 dummysh[0] = sencode(newsh);
15169
15170 // Are there area constraints?
15171 if (b->quality && (in->facetconstraintlist != (REAL *) NULL)) {
15172 idx = in->facetmarkerlist[shmark - 1]; // The actual facet marker.
15173 for (k = 0; k < in->numberoffacetconstraints; k++) {
15174 fmarker = (int) in->facetconstraintlist[k * 2];
15175 if (fmarker == idx) {
15176 area = in->facetconstraintlist[k * 2 + 1];
15177 setareabound(newsh, area);
15178 break;
15179 }
15180 }
15181 }
15182
15183 // Are there pbc conditions?
15184 if (checkpbcs) {
15185 idx = in->facetmarkerlist[shmark - 1]; // The actual facet marker.
15186 for (k = 0; k < in->numberofpbcgroups; k++) {
15187 pd = &subpbcgrouptable[k];
15188 for (j = 0; j < 2; j++) {
15189 if (pd->fmark[j] == idx) {
15190 setshellpbcgroup(newsh, k);
15191 pd->ss[j] = newsh;
15192 }
15193 }
15194 }
15195 }
15196
15197 if (aboveflag) {
15198 // Compute the 'abovepoint' for orient3d().
15199 abovepoint = facetabovepointarray[shmark];
15200 if (abovepoint == (point) NULL) {
15201 getfacetabovepoint(&newsh);
15202 }
15203 }
15204
15205 if (holes > 0) {
15206 // Project hole points onto the plane containing the facet.
15207 REAL prj[3];
15208 for (k = 0; k < holes; k++) {
15209 projpt2face(&(holelist[k * 3]), insertarray[0], insertarray[1],
15210 insertarray[2], prj);
15211 for (j = 0; j < 3; j++) holelist[k * 3 + j] = prj[j];
15212 }
15213 }
15214
15215 // Incrementally insert the rest of points into T.
15216 for (; i < arraysize; i++) {
15217 // Insert p_i.
15218 startsh.sh = dummysh;
15219 loc = locatesub(insertarray[i], &startsh, 0, 0.0);
15220 if (loc == ONFACE) {
15221 splitsubface(insertarray[i], &startsh, flipque);
15222 } else if (loc == ONEDGE) {
15223 splitsubedge(insertarray[i], &startsh, flipque);
15224 } else if (loc == OUTSIDE) {
15225 collectvisiblesubs(shmark, insertarray[i], &startsh, flipque);
15226 } else if (loc == ONVERTEX) {
15227 // !should not happen!
15228 }
15229 // Set p_i's type FACETVERTEX if it has no type yet.
15230 if (pointtype(insertarray[i]) == VOLVERTEX) {
15231 setpointtype(insertarray[i], FACETVERTEX);
15232 }
15233 flipsub(flipque);
15234 }
15235 }
15236
15237 ///////////////////////////////////////////////////////////////////////////////
15238 // //
15239 // finddirectionsub() Find the first subface in a facet on the path from //
15240 // one point to another. //
15241 // //
15242 // Finds the subface in the facet that intersects a line segment drawn from //
15243 // the origin of `searchsh' to the point `tend', and returns the result in //
15244 // `searchsh'. The origin of `searchsh' does not change, even though the //
15245 // subface returned may differ from the one passed in. //
15246 // //
15247 // The return value notes whether the destination or apex of the found face //
15248 // is collinear with the two points in question. //
15249 // //
15250 ///////////////////////////////////////////////////////////////////////////////
15251
15252 enum tetgenmesh::finddirectionresult tetgenmesh::finddirectionsub(
15253 face* searchsh, point tend)
15254 {
15255 face checksh;
15256 point startpoint, leftpoint, rightpoint;
15257 REAL leftccw, rightccw;
15258 REAL ori, sign;
15259 int leftflag, rightflag;
15260
15261 startpoint = sorg(*searchsh);
15262 // Find the sign to simulate that abovepoint is 'above' the facet.
15263 adjustedgering(*searchsh, CCW);
15264 // Make sure 'startpoint' is the origin.
15265 if (sorg(*searchsh) != startpoint) senextself(*searchsh);
15266 rightpoint = sdest(*searchsh);
15267 leftpoint = sapex(*searchsh);
15268 ori = orient3d(startpoint, rightpoint, leftpoint, abovepoint);
15269 sign = ori > 0.0 ? -1 : 1;
15270
15271 // Is `tend' to the left?
15272 ori = orient3d(tend, startpoint, abovepoint, leftpoint);
15273 leftccw = ori * sign;
15274 leftflag = leftccw > 0.0;
15275 // Is `tend' to the right?
15276 ori = orient3d(startpoint, tend, abovepoint, rightpoint);
15277 rightccw = ori * sign;
15278 rightflag = rightccw > 0.0;
15279 if (leftflag && rightflag) {
15280 // `searchsh' faces directly away from `tend'. We could go left or
15281 // right. Ask whether it's a triangle or a boundary on the left.
15282 senext2(*searchsh, checksh);
15283 spivotself(checksh);
15284 if (checksh.sh == dummysh) {
15285 leftflag = 0;
15286 } else {
15287 rightflag = 0;
15288 }
15289 }
15290 while (leftflag) {
15291 // Turn left until satisfied.
15292 senext2self(*searchsh);
15293 spivotself(*searchsh);
15294 if (searchsh->sh == dummysh) {
15295 printf("Internal error in finddirectionsub(): Unable to find a\n");
15296 printf(" subface leading from %d to %d.\n", pointmark(startpoint),
15297 pointmark(tend));
15298 internalerror();
15299 }
15300 if (sorg(*searchsh) != startpoint) sesymself(*searchsh);
15301 assert(sorg(*searchsh) == startpoint);
15302 leftpoint = sapex(*searchsh);
15303 rightccw = leftccw;
15304 ori = orient3d(tend, startpoint, abovepoint, leftpoint);
15305 leftccw = ori * sign;
15306 leftflag = leftccw > 0.0;
15307 }
15308 while (rightflag) {
15309 // Turn right until satisfied.
15310 spivotself(*searchsh);
15311 if (searchsh->sh == dummysh) {
15312 printf("Internal error in finddirectionsub(): Unable to find a\n");
15313 printf(" subface leading from %d to %d.\n", pointmark(startpoint),
15314 pointmark(tend));
15315 internalerror();
15316 }
15317 if (sdest(*searchsh) != startpoint) sesymself(*searchsh);
15318 assert(sdest(*searchsh) == startpoint);
15319 senextself(*searchsh);
15320 rightpoint = sdest(*searchsh);
15321 leftccw = rightccw;
15322 ori = orient3d(startpoint, tend, abovepoint, rightpoint);
15323 rightccw = ori * sign;
15324 rightflag = rightccw > 0.0;
15325 }
15326 if (leftccw == 0.0) {
15327 return LEFTCOLLINEAR;
15328 } else if (rightccw == 0.0) {
15329 return RIGHTCOLLINEAR;
15330 } else {
15331 return ACROSSEDGE;
15332 }
15333 }
15334
15335 ///////////////////////////////////////////////////////////////////////////////
15336 // //
15337 // insertsubseg() Create a subsegment and insert it between two subfaces. //
15338 // //
15339 // The new subsegment ab is inserted at the edge of subface 'tri'. If ab is //
15340 // not a hull edge, it is inserted between two subfaces. If 'tri' is a hull //
15341 // face, the initial face ring of ab will be set only one face which is self-//
15342 // bonded. The final face ring will be constructed in 'unifysegments()'. //
15343 // //
15344 ///////////////////////////////////////////////////////////////////////////////
15345
15346 void tetgenmesh::insertsubseg(face* tri)
15347 {
15348 face oppotri;
15349 face newsubseg;
15350 point pa, pb;
15351 REAL len;
15352 int e1, e2;
15353 int i;
15354
15355 // Check if there's already a subsegment here.
15356 sspivot(*tri, newsubseg);
15357 if (newsubseg.sh == dummysh) {
15358 // Make new subsegment and initialize its vertices.
15359 makeshellface(subsegs, &newsubseg);
15360 pa = sorg(*tri);
15361 pb = sdest(*tri);
15362 setsorg(newsubseg, pa);
15363 setsdest(newsubseg, pb);
15364 // Are there length constraints?
15365 if (b->quality && (in->segmentconstraintlist != (REAL *) NULL)) {
15366 for (i = 0; i < in->numberofsegmentconstraints; i++) {
15367 e1 = (int) in->segmentconstraintlist[i * 3];
15368 e2 = (int) in->segmentconstraintlist[i * 3 + 1];
15369 if (((pointmark(pa) == e1) && (pointmark(pb) == e2)) ||
15370 ((pointmark(pa) == e2) && (pointmark(pb) == e1))) {
15371 len = in->segmentconstraintlist[i * 3 + 2];
15372 setareabound(newsubseg, len);
15373 break;
15374 }
15375 }
15376 }
15377 // Bond new subsegment to the two subfaces it is sandwiched between.
15378 ssbond(*tri, newsubseg);
15379 spivot(*tri, oppotri);
15380 // 'oppotri' might be "out space".
15381 if (oppotri.sh != dummysh) {
15382 ssbond(oppotri, newsubseg);
15383 } /* else {
15384 // Outside! Bond '*tri' to itself.
15385 sbond(*tri, *tri);
15386 } */
15387 }
15388 }
15389
15390 ///////////////////////////////////////////////////////////////////////////////
15391 // //
15392 // scoutsegmentsub() Scout the first triangle on the path from one point //
15393 // to another, and check for completion (reaching the //
15394 // second point), a collinear point,or the intersection //
15395 // of two segments. //
15396 // //
15397 // Returns true if the entire segment is successfully inserted, and false if //
15398 // the job must be finished by constrainededge(). //
15399 // //
15400 ///////////////////////////////////////////////////////////////////////////////
15401
15402 bool tetgenmesh::scoutsegmentsub(face* searchsh, point tend)
15403 {
15404 face newsubseg;
15405 face crosssub, crosssubseg;
15406 point leftpoint, rightpoint;
15407 enum finddirectionresult collinear;
15408
15409 collinear = finddirectionsub(searchsh, tend);
15410 rightpoint = sdest(*searchsh);
15411 leftpoint = sapex(*searchsh);
15412 if (rightpoint == tend || leftpoint == tend) {
15413 // The segment is already an edge.
15414 if (leftpoint == tend) {
15415 senext2self(*searchsh);
15416 }
15417 // Insert a subsegment.
15418 insertsubseg(searchsh);
15419 return true;
15420 } else if (collinear == LEFTCOLLINEAR) {
15421 // We've collided with a vertex between the segment's endpoints.
15422 // Make the collinear vertex be the triangle's origin.
15423 senextself(*searchsh); // lprevself(*searchtri);
15424 // Insert a subsegment.
15425 insertsubseg(searchsh);
15426 // Insert the remainder of the segment.
15427 return scoutsegmentsub(searchsh, tend);
15428 } else if (collinear == RIGHTCOLLINEAR) {
15429 // We've collided with a vertex between the segment's endpoints.
15430 // Insert a subsegment.
15431 insertsubseg(searchsh);
15432 // Make the collinear vertex be the triangle's origin.
15433 senextself(*searchsh); // lnextself(*searchtri);
15434 // Insert the remainder of the segment.
15435 return scoutsegmentsub(searchsh, tend);
15436 } else {
15437 senext(*searchsh, crosssub); // lnext(*searchtri, crosstri);
15438 // Check for a crossing segment.
15439 sspivot(crosssub, crosssubseg);
15440 #ifdef SELF_CHECK
15441 assert(crosssubseg.sh == dummysh);
15442 #endif
15443 return false;
15444 }
15445 }
15446
15447 ///////////////////////////////////////////////////////////////////////////////
15448 // //
15449 // flipedgerecursive() Flip an edge. //
15450 // //
15451 // This is a support routine for inserting segments into a CDT. //
15452 // //
15453 // Let 'flipedge' be ab, and two triangles abc, abd share at it. ab may not //
15454 // flipable if the four vertices a, b, c, and d are non-convex. If it is the //
15455 // case, recursively flip ad or bd. Return when ab is flipped. //
15456 // //
15457 ///////////////////////////////////////////////////////////////////////////////
15458
15459 void tetgenmesh::flipedgerecursive(face* flipedge, queue* flipqueue)
15460 {
15461 face fixupsh;
15462 point pa, pb, pc, pd;
15463 REAL oria, orib;
15464 bool doflip;
15465
15466 pa = sorg(*flipedge);
15467 pb = sdest(*flipedge);
15468 pc = sapex(*flipedge);
15469 do {
15470 spivot(*flipedge, fixupsh);
15471 pd = sapex(fixupsh);
15472 oria = orient3d(pc, pd, abovepoint, pa);
15473 orib = orient3d(pc, pd, abovepoint, pb);
15474 doflip = (oria * orib < 0.0);
15475 if (doflip) {
15476 // Flip the edge (a, b) away.
15477 flip22sub(flipedge, flipqueue);
15478 // Fix flipedge on edge e (c, d).
15479 findedge(flipedge, pc, pd);
15480 } else {
15481 // ab is unflipable. Get the next edge (bd, or da) to flip.
15482 if (sorg(fixupsh) != pb) sesymself(fixupsh);
15483 assert(sdest(fixupsh) == pa);
15484 if (fabs(oria) > fabs(orib)) {
15485 // acd has larger area. Choose da.
15486 senextself(fixupsh);
15487 } else {
15488 // bcd has larger area. Choose bd.
15489 senext2self(fixupsh);
15490 }
15491 // Flip the edge.
15492 flipedgerecursive(&fixupsh, flipqueue);
15493 }
15494 } while (!doflip);
15495 }
15496
15497 ///////////////////////////////////////////////////////////////////////////////
15498 // //
15499 // constrainededge() Force a segment into a CDT. //
15500 // //
15501 // The segment s is recovered by flipping away the edges it intersects, and //
15502 // triangulating the polygons that form on each side of it. //
15503 // //
15504 // Generates a single subsegment connecting `tstart' to `tend'. The triangle //
15505 // `startsh' has `tstart' as its origin. //
15506 // //
15507 ///////////////////////////////////////////////////////////////////////////////
15508
15509 void tetgenmesh::constrainededge(face* startsh, point tend, queue* flipqueue)
15510 {
15511 point tstart, tright, tleft;
15512 REAL rori, lori;
15513 bool collision;
15514
15515 tstart = sorg(*startsh);
15516 do {
15517 // Loop edges oppo to tstart until find one crosses the segment.
15518 do {
15519 tright = sdest(*startsh);
15520 tleft = sapex(*startsh);
15521 // Is edge (tright, tleft) corss the segment.
15522 rori = orient3d(tstart, tright, abovepoint, tend);
15523 collision = (rori == 0.0);
15524 if (collision) break; // tright is on the segment.
15525 lori = orient3d(tstart, tleft, abovepoint, tend);
15526 collision = (lori == 0.0);
15527 if (collision) { // tleft is on the segment.
15528 senext2self(*startsh);
15529 break;
15530 }
15531 if (rori * lori < 0.0) break; // Find the crossing edge.
15532 // Both points are at one side of the segment.
15533 finddirectionsub(startsh, tend);
15534 } while (true);
15535 if (collision) break;
15536 // Get the neighbor face at edge e (tright, tleft).
15537 senextself(*startsh);
15538 // Flip the crossing edge.
15539 flipedgerecursive(startsh, flipqueue);
15540 // After flip, sorg(*startsh) == tstart.
15541 assert(sorg(*startsh) == tstart);
15542 } while (sdest(*startsh) != tend);
15543
15544 // Insert a subsegment to make the segment permanent.
15545 insertsubseg(startsh);
15546 // If there was a collision with an interceding vertex, install another
15547 // segment connecting that vertex with endpoint2.
15548 if (collision) {
15549 // Insert the remainder of the segment.
15550 if (!scoutsegmentsub(startsh, tend)) {
15551 constrainededge(startsh, tend, flipqueue);
15552 }
15553 }
15554 }
15555
15556 ///////////////////////////////////////////////////////////////////////////////
15557 // //
15558 // recoversegment() Recover a segment in the surface triangulation. //
15559 // //
15560 ///////////////////////////////////////////////////////////////////////////////
15561
15562 void tetgenmesh::recoversegment(point tstart, point tend, queue* flipqueue)
15563 {
15564 face searchsh;
15565
15566 if (b->verbose > 2) {
15567 printf(" Insert seg (%d, %d).\n", pointmark(tstart), pointmark(tend));
15568 }
15569
15570 // Find a triangle whose origin is the segment's first endpoint.
15571 searchsh.sh = dummysh;
15572 // Search for the segment's first endpoint by point location.
15573 if (locatesub(tstart, &searchsh, 0, 0.0) != ONVERTEX) {
15574 // Possibly caused by a degenerate subface. Do a brute-force search.
15575 list *newshlist;
15576 int i, j;
15577 newshlist = new list(sizeof(face), NULL, 256);
15578 // Get new subfaces, do not remove protected segments.
15579 retrievenewsubs(newshlist, false);
15580 // Search for a sub contain tstart.
15581 for (i = 0; i < newshlist->len(); i++) {
15582 searchsh = * (face *)(* newshlist)[i];
15583 for (j = 0; j < 3; j++) {
15584 if (sorg(searchsh) == tstart) break;
15585 senextself(searchsh);
15586 }
15587 if (j < 3) break;
15588 }
15589 delete newshlist;
15590 if (sorg(searchsh) != tstart) {
15591 printf("Internal error in recoversegment(): Vertex location failed.\n");
15592 internalerror();
15593 }
15594 }
15595 // Scout the segment and insert it if it is found.
15596 if (scoutsegmentsub(&searchsh, tend)) {
15597 // The segment was easily inserted.
15598 return;
15599 }
15600 // Insert the segment into the triangulation by flips.
15601 constrainededge(&searchsh, tend, flipqueue);
15602 // Some edges may need flipping.
15603 flipsub(flipqueue);
15604 }
15605
15606 ///////////////////////////////////////////////////////////////////////////////
15607 // //
15608 // infecthullsub() Virally infect all of the triangles of the convex hull //
15609 // that are not protected by subsegments. //
15610 // //
15611 ///////////////////////////////////////////////////////////////////////////////
15612
15613 void tetgenmesh::infecthullsub(memorypool* viri)
15614 {
15615 face hulltri, nexttri, starttri;
15616 face hullsubseg;
15617 shellface **deadshellface;
15618
15619 // Find a triangle handle on the hull.
15620 hulltri.sh = dummysh;
15621 hulltri.shver = 0;
15622 spivotself(hulltri);
15623 adjustedgering(hulltri, CCW);
15624 // Remember where we started so we know when to stop.
15625 starttri = hulltri;
15626 // Go once counterclockwise around the convex hull.
15627 do {
15628 // Ignore triangles that are already infected.
15629 if (!sinfected(hulltri)) {
15630 // Is the triangle protected by a subsegment?
15631 sspivot(hulltri, hullsubseg);
15632 if (hullsubseg.sh == dummysh) {
15633 // The triangle is not protected; infect it.
15634 if (!sinfected(hulltri)) {
15635 sinfect(hulltri);
15636 deadshellface = (shellface **) viri->alloc();
15637 *deadshellface = hulltri.sh;
15638 }
15639 }
15640 }
15641 // To find the next hull edge, go clockwise around the next vertex.
15642 senextself(hulltri); // lnextself(hulltri);
15643 spivot(hulltri, nexttri); // oprev(hulltri, nexttri);
15644 if (nexttri.sh == hulltri.sh) {
15645 nexttri.sh = dummysh; // 'hulltri' is self-bonded.
15646 } else {
15647 adjustedgering(nexttri, CCW);
15648 senextself(nexttri);
15649 }
15650 while (nexttri.sh != dummysh) {
15651 hulltri = nexttri;
15652 spivot(hulltri, nexttri); // oprev(hulltri, nexttri);
15653 if (nexttri.sh == hulltri.sh) {
15654 nexttri.sh = dummysh; // 'hulltri' is self-bonded.
15655 } else {
15656 adjustedgering(nexttri, CCW);
15657 senextself(nexttri);
15658 }
15659 }
15660 } while (hulltri != starttri);
15661 }
15662
15663 ///////////////////////////////////////////////////////////////////////////////
15664 // //
15665 // plaguesub() Spread the virus from all infected triangles to any //
15666 // neighbors not protected by subsegments. Delete all //
15667 // infected triangles. //
15668 // //
15669 // This is the procedure that actually creates holes and concavities. //
15670 // //
15671 ///////////////////////////////////////////////////////////////////////////////
15672
15673 void tetgenmesh::plaguesub(memorypool* viri)
15674 {
15675 face testtri, neighbor, ghostsh;
15676 face neighborsubseg;
15677 shellface **virusloop;
15678 shellface **deadshellface;
15679 int i;
15680
15681 // Loop through all the infected triangles, spreading the virus to
15682 // their neighbors, then to their neighbors' neighbors.
15683 viri->traversalinit();
15684 virusloop = (shellface **) viri->traverse();
15685 while (virusloop != (shellface **) NULL) {
15686 testtri.sh = *virusloop;
15687 // Check each of the triangle's three neighbors.
15688 for (i = 0; i < 3; i++) {
15689 // Find the neighbor.
15690 spivot(testtri, neighbor);
15691 // Check for a subsegment between the triangle and its neighbor.
15692 sspivot(testtri, neighborsubseg);
15693 // Check if the neighbor is nonexistent or already infected.
15694 if ((neighbor.sh == dummysh) || sinfected(neighbor)) {
15695 if (neighborsubseg.sh != dummysh) {
15696 // There is a subsegment separating the triangle from its
15697 // neighbor, but both triangles are dying, so the subsegment
15698 // dies too.
15699 shellfacedealloc(subsegs, neighborsubseg.sh);
15700 if (neighbor.sh != dummysh) {
15701 // Make sure the subsegment doesn't get deallocated again
15702 // later when the infected neighbor is visited.
15703 ssdissolve(neighbor);
15704 }
15705 }
15706 } else { // The neighbor exists and is not infected.
15707 if (neighborsubseg.sh == dummysh) {
15708 // There is no subsegment protecting the neighbor, so the
15709 // neighbor becomes infected.
15710 sinfect(neighbor);
15711 // Ensure that the neighbor's neighbors will be infected.
15712 deadshellface = (shellface **) viri->alloc();
15713 *deadshellface = neighbor.sh;
15714 } else { // The neighbor is protected by a subsegment.
15715 // Remove this triangle from the subsegment.
15716 ssbond(neighbor, neighborsubseg);
15717 }
15718 }
15719 senextself(testtri);
15720 }
15721 virusloop = (shellface **) viri->traverse();
15722 }
15723
15724 ghostsh.sh = dummysh; // A handle of outer space.
15725 viri->traversalinit();
15726 virusloop = (shellface **) viri->traverse();
15727 while (virusloop != (shellface **) NULL) {
15728 testtri.sh = *virusloop;
15729 // Record changes in the number of boundary edges, and disconnect
15730 // dead triangles from their neighbors.
15731 for (i = 0; i < 3; i++) {
15732 spivot(testtri, neighbor);
15733 if (neighbor.sh != dummysh) {
15734 // Disconnect the triangle from its neighbor.
15735 // sdissolve(neighbor);
15736 sbond(neighbor, ghostsh);
15737 }
15738 senextself(testtri);
15739 }
15740 // Return the dead triangle to the pool of triangles.
15741 shellfacedealloc(subfaces, testtri.sh);
15742 virusloop = (shellface **) viri->traverse();
15743 }
15744 // Empty the virus pool.
15745 viri->restart();
15746 }
15747
15748 ///////////////////////////////////////////////////////////////////////////////
15749 // //
15750 // carveholessub() Find the holes and infect them. Find the area //
15751 // constraints and infect them. Infect the convex hull. //
15752 // Spread the infection and kill triangles. Spread the //
15753 // area constraints. //
15754 // //
15755 // This routine mainly calls other routines to carry out all these functions.//
15756 // //
15757 ///////////////////////////////////////////////////////////////////////////////
15758
15759 void tetgenmesh::carveholessub(int holes, REAL* holelist, memorypool *viri)
15760 {
15761 face searchtri, triangleloop;
15762 shellface **holetri;
15763 enum locateresult intersect;
15764 int i;
15765
15766 // Mark as infected any unprotected triangles on the boundary.
15767 // This is one way by which concavities are created.
15768 infecthullsub(viri);
15769
15770 if (holes > 0) {
15771 // Infect each triangle in which a hole lies.
15772 for (i = 0; i < 3 * holes; i += 3) {
15773 // Ignore holes that aren't within the bounds of the mesh.
15774 if ((holelist[i] >= xmin) && (holelist[i] <= xmax)
15775 && (holelist[i + 1] >= ymin) && (holelist[i + 1] <= ymax)
15776 && (holelist[i + 2] >= zmin) && (holelist[i + 2] <= zmax)) {
15777 // Start searching from some triangle on the outer boundary.
15778 searchtri.sh = dummysh;
15779 // Find a triangle that contains the hole.
15780 intersect = locatesub(&holelist[i], &searchtri, 0, 0.0);
15781 if ((intersect != OUTSIDE) && (!sinfected(searchtri))) {
15782 // Infect the triangle. This is done by marking the triangle
15783 // as infected and including the triangle in the virus pool.
15784 sinfect(searchtri);
15785 holetri = (shellface **) viri->alloc();
15786 *holetri = searchtri.sh;
15787 }
15788 }
15789 }
15790 }
15791
15792 if (viri->items > 0) {
15793 // Carve the holes and concavities.
15794 plaguesub(viri);
15795 }
15796 // The virus pool should be empty now.
15797 }
15798
15799 ///////////////////////////////////////////////////////////////////////////////
15800 // //
15801 // triangulate() Triangulate a PSLG into a CDT. //
15802 // //
15803 // A Planar Straight Line Graph (PSLG) P is actually a 2D polygonal region, //
15804 // possibly contains holes, segments and vertices in its interior. P is tri- //
15805 // angulated into a set of _subfaces_ forming a CDT of P. //
15806 // //
15807 // The vertices and segments of P are found in 'ptlist' and 'conlist', resp- //
15808 // ectively. 'holelist' contains a list of hole points. 'shmark' will be set //
15809 // to all subfaces of P. //
15810 // //
15811 // The CDT is created directly in the pools 'subfaces' and 'subsegs'. It can //
15812 // be retrived by a broadth-first searching starting from 'dummysh[0]'(debug //
15813 // function 'outsurfmesh()' does it). //
15814 // //
15815 ///////////////////////////////////////////////////////////////////////////////
15816
15817 void tetgenmesh::triangulate(int shmark, REAL eps, list* ptlist, list* conlist,
15818 int holes, REAL* holelist, memorypool* viri, queue* flipqueue)
15819 {
15820 face newsh;
15821 point *cons;
15822 int i;
15823
15824 if (b->verbose > 1) {
15825 printf(" %d vertices, %d segments", ptlist->len(), conlist->len());
15826 if (holes > 0) {
15827 printf(", %d holes", holes);
15828 }
15829 printf(", shmark: %d.\n", shmark);
15830 }
15831
15832 // Create the DT of V by the 2D incremental flip algorithm.
15833 incrflipdelaunaysub(shmark, eps, ptlist, holes, holelist, flipqueue);
15834 // Recover boundary edges.
15835 if (ptlist->len() > 3) {
15836 // Insert segments into the DT.
15837 for (i = 0; i < conlist->len(); i++) {
15838 cons = (point *)(* conlist)[i];
15839 recoversegment(cons[0], cons[1], flipqueue);
15840 }
15841 // Carve holes and concavities.
15842 carveholessub(holes, holelist, viri);
15843 } else if (ptlist->len() == 3) {
15844 // Insert 3 segments directly.
15845 newsh.sh = dummysh;
15846 newsh.shver = 0;
15847 spivotself(newsh);
15848 for (i = 0; i < 3; i++) {
15849 insertsubseg(&newsh);
15850 senextself(newsh);
15851 }
15852 }
15853 }
15854
15855 ///////////////////////////////////////////////////////////////////////////////
15856 // //
15857 // retrievenewsubs() Retrieve newly created subfaces. //
15858 // //
15859 // The new subfaces created by triangulate() can be found by a broadth-first //
15860 // searching starting from 'dummysh[0]'. //
15861 // //
15862 // 'newshlist' (empty on input) returns the retrieved subfaces. Each edge on //
15863 // the hull is bound to 'dummysh' and protected by a segment. If 'removeseg' //
15864 // is TRUE, the segment is removed. //
15865 // //
15866 ///////////////////////////////////////////////////////////////////////////////
15867
15868 void tetgenmesh::retrievenewsubs(list* newshlist, bool removeseg)
15869 {
15870 face startsh, neighsh;
15871 face deadseg;
15872 int i, j;
15873
15874 // The first new subface is found at dummysh[0].
15875 startsh.sh = dummysh;
15876 startsh.shver = 0;
15877 spivotself(startsh);
15878 assert(startsh.sh != dummysh);
15879 sinfect(startsh);
15880 newshlist->append(&startsh);
15881
15882 // Find the rest of new subfaces by a broadth-first searching.
15883 for (i = 0; i < newshlist->len(); i++) {
15884 // Get a new subface s.
15885 startsh = * (face *)(* newshlist)[i];
15886 for (j = 0; j < 3; j++) {
15887 spivot(startsh, neighsh);
15888 if (neighsh.sh != dummysh) {
15889 if (!sinfected(neighsh)) {
15890 // Discovered a new subface.
15891 sinfect(neighsh);
15892 newshlist->append(&neighsh);
15893 }
15894 } else {
15895 // Found a boundary edge.
15896 if (removeseg) {
15897 // This side of s may be protected by a segment.
15898 sspivot(startsh, deadseg);
15899 if (deadseg.sh != dummysh) {
15900 // Detach it from s.
15901 ssdissolve(startsh);
15902 // Delete the segment.
15903 shellfacedealloc(subsegs, deadseg.sh);
15904 }
15905 }
15906 }
15907 senextself(startsh);
15908 }
15909 }
15910 for (i = 0; i < newshlist->len(); i++) {
15911 startsh = * (face *)(* newshlist)[i];
15912 suninfect(startsh);
15913 }
15914 }
15915
15916 ///////////////////////////////////////////////////////////////////////////////
15917 // //
15918 // unifysegments() Unify identical segments and build facet connections. //
15919 // //
15920 // After creating the surface mesh. Each facet has its own segments. There //
15921 // are duplicated segments between adjacent facets. This routine has three //
15922 // purposes: //
15923 // (1) identify the set of segments which have the same endpoints and //
15924 // unify them into one segment, remove redundant ones; //
15925 // (2) create the face rings of the unified segments, hence setup the //
15926 // connections between facets; and //
15927 // (3) set a unique marker (1-based) for each segment. //
15928 // On finish, each segment is unique and the face ring around it (right-hand //
15929 // rule) is constructed. The connections between facets-facets are setup. //
15930 // //
15931 ///////////////////////////////////////////////////////////////////////////////
15932
15933 void tetgenmesh::unifysegments()
15934 {
15935 list *sfacelist;
15936 shellface **facesperverlist;
15937 face subsegloop, testseg;
15938 face sface, sface1, sface2;
15939 point torg, tdest;
15940 REAL da1, da2;
15941 int *idx2facelist;
15942 int segmarker;
15943 int idx, k, m;
15944
15945 if (b->verbose > 0) {
15946 printf(" Unifying segments.\n");
15947 }
15948
15949 // Compute a mapping from indices of vertices to subfaces.
15950 makesubfacemap(idx2facelist, facesperverlist);
15951 // Initialize 'sfacelist' for constructing the face link of each segment.
15952 sfacelist = new list(sizeof(face), NULL);
15953
15954 segmarker = 1;
15955 subsegs->traversalinit();
15956 subsegloop.sh = shellfacetraverse(subsegs);
15957 while (subsegloop.sh != (shellface *) NULL) {
15958 subsegloop.shver = 0; // For sure.
15959 torg = sorg(subsegloop);
15960 tdest = sdest(subsegloop);
15961 idx = pointmark(torg) - in->firstnumber;
15962 // Loop through the set of subfaces containing 'torg'. Get all the
15963 // subfaces containing the edge (torg, tdest). Save and order them
15964 // in 'sfacelist', the ordering is defined by the right-hand rule
15965 // with thumb points from torg to tdest.
15966 for (k = idx2facelist[idx]; k < idx2facelist[idx + 1]; k++) {
15967 sface.sh = facesperverlist[k];
15968 sface.shver = 0;
15969 // sface may be died due to the removing of duplicated subfaces.
15970 if (!isdead(&sface) && isfacehasedge(&sface, torg, tdest)) {
15971 // 'sface' contains this segment.
15972 findedge(&sface, torg, tdest);
15973 // Save it in 'sfacelist'.
15974 if (sfacelist->len() < 2) {
15975 sfacelist->append(&sface);
15976 } else {
15977 for (m = 0; m < sfacelist->len() - 1; m++) {
15978 sface1 = * (face *)(* sfacelist)[m];
15979 sface2 = * (face *)(* sfacelist)[m + 1];
15980 da1 = facedihedral(torg, tdest, sapex(sface1), sapex(sface));
15981 da2 = facedihedral(torg, tdest, sapex(sface1), sapex(sface2));
15982 if (da1 < da2) {
15983 break; // Insert it after m.
15984 }
15985 }
15986 sfacelist->insert(m + 1, &sface);
15987 }
15988 }
15989 }
15990 if (b->verbose > 1) {
15991 printf(" Identifying %d segments of (%d %d).\n", sfacelist->len(),
15992 pointmark(torg), pointmark(tdest));
15993 }
15994 // Set the connection between this segment and faces containing it,
15995 // at the same time, remove redundant segments.
15996 for (k = 0; k < sfacelist->len(); k++) {
15997 sface = *(face *)(* sfacelist)[k];
15998 sspivot(sface, testseg);
15999 // If 'testseg' is not 'subsegloop', it is a redundant segment that
16000 // needs be removed. BE CAREFUL it may already be removed. Do not
16001 // remove it twice, i.e., do test 'isdead()' together.
16002 if ((testseg.sh != subsegloop.sh) && !isdead(&testseg)) {
16003 shellfacedealloc(subsegs, testseg.sh);
16004 }
16005 // 'ssbond' bonds the subface and the segment together, and dissloves
16006 // the old bond as well.
16007 ssbond(sface, subsegloop);
16008 }
16009 // Set connection between these faces.
16010 sface = *(face *)(* sfacelist)[0];
16011 for (k = 1; k <= sfacelist->len(); k++) {
16012 if (k < sfacelist->len()) {
16013 sface1 = *(face *)(* sfacelist)[k];
16014 } else {
16015 sface1 = *(face *)(* sfacelist)[0]; // Form a face loop.
16016 }
16017 /*
16018 // Check if these two subfaces are the same. It is possible when user
16019 // defines one facet (or polygon) two or more times. If they are,
16020 // they should not be bonded together, instead of that, one of them
16021 // should be delete from the surface mesh.
16022 if ((sfacelist->len() > 1) && sapex(sface) == sapex(sface1)) {
16023 // They are duplicated faces.
16024 if (b->verbose > 0) {
16025 printf(" A duplicated subface (%d, %d, %d) is removed.\n",
16026 pointmark(torg), pointmark(tdest), pointmark(sapex(sface)));
16027 }
16028 if (k == sfacelist->len()) {
16029 // 'sface' is the last face, however, it is same as the first one.
16030 // In order to form the ring, we have to let the second last
16031 // face bond to the first one 'sface1'.
16032 shellfacedealloc(subfaces, sface.sh);
16033 assert(sfacelist->len() >= 2);
16034 assert(k == sfacelist->len());
16035 sface = *(face *)(* sfacelist)[k - 2];
16036 } else {
16037 // 'sface1' is in the middle and may be the last one.
16038 shellfacedealloc(subfaces, sface1.sh);
16039 // Skip this face and go to the next one.
16040 continue;
16041 }
16042 }
16043 */
16044 if (b->verbose > 2) {
16045 printf(" Bond subfaces (%d, %d, %d) and (%d, %d, %d).\n",
16046 pointmark(torg), pointmark(tdest), pointmark(sapex(sface)),
16047 pointmark(torg), pointmark(tdest), pointmark(sapex(sface1)));
16048 }
16049 sbond1(sface, sface1);
16050 sface = sface1;
16051 }
16052 // Set the unique segment marker into the unified segment.
16053 setshellmark(subsegloop, segmarker);
16054 // Increase the marker.
16055 segmarker++;
16056 // Clear the working list.
16057 sfacelist->clear();
16058 subsegloop.sh = shellfacetraverse(subsegs);
16059 }
16060
16061 delete [] idx2facelist;
16062 delete [] facesperverlist;
16063 delete sfacelist;
16064 }
16065
16066 ///////////////////////////////////////////////////////////////////////////////
16067 // //
16068 // mergefacets() Merge adjacent facets to be one facet if they are //
16069 // coplanar and have the same boundary marker. //
16070 // //
16071 // Segments between two merged facets will be removed from the mesh. If all //
16072 // segments around a vertex have been removed, change its vertex type to be //
16073 // FACETVERTEX. Edge flips will be performed to ensure the Delaunay criteria //
16074 // of the triangulation of merged facets. //
16075 // //
16076 ///////////////////////////////////////////////////////////////////////////////
16077
16078 void tetgenmesh::mergefacets(queue* flipqueue)
16079 {
16080 face parentsh, neighsh, neineighsh;
16081 face segloop;
16082 point eorg, edest;
16083 REAL ori;
16084 bool mergeflag, pbcflag;
16085 int* segspernodelist;
16086 int fidx1, fidx2;
16087 int i, j;
16088
16089 if (b->verbose > 0) {
16090 printf(" Merging coplanar facets.\n");
16091 }
16092 // Create and initialize 'segspernodelist'.
16093 segspernodelist = new int[points->items + 1];
16094 for (i = 0; i < points->items + 1; i++) segspernodelist[i] = 0;
16095
16096 // Loop the segments, counter the number of segments sharing each vertex.
16097 subsegs->traversalinit();
16098 segloop.sh = shellfacetraverse(subsegs);
16099 while (segloop.sh != (shellface *) NULL) {
16100 // Increment the number of sharing segments for each endpoint.
16101 for (i = 0; i < 2; i++) {
16102 j = pointmark((point) segloop.sh[3 + i]);
16103 segspernodelist[j]++;
16104 }
16105 segloop.sh = shellfacetraverse(subsegs);
16106 }
16107
16108 // Loop the segments, find out dead segments.
16109 subsegs->traversalinit();
16110 segloop.sh = shellfacetraverse(subsegs);
16111 while (segloop.sh != (shellface *) NULL) {
16112 eorg = sorg(segloop);
16113 edest = sdest(segloop);
16114 spivot(segloop, parentsh);
16115 spivot(parentsh, neighsh);
16116 spivot(neighsh, neineighsh);
16117 if (parentsh.sh != neighsh.sh && parentsh.sh == neineighsh.sh) {
16118 // Exactly two subfaces at this segment.
16119 fidx1 = shellmark(parentsh) - 1;
16120 fidx2 = shellmark(neighsh) - 1;
16121 pbcflag = false;
16122 if (checkpbcs) {
16123 pbcflag = (shellpbcgroup(parentsh) >= 0)
16124 || (shellpbcgroup(neighsh) >= 0);
16125 }
16126 // Possibly merge them if they are not in the same facet.
16127 if ((fidx1 != fidx2) && !pbcflag) {
16128 // Test if they are coplanar.
16129 ori = orient3d(eorg, edest, sapex(parentsh), sapex(neighsh));
16130 if (ori != 0.0) {
16131 if (iscoplanar(eorg, edest, sapex(parentsh), sapex(neighsh), ori,
16132 b->epsilon)) {
16133 ori = 0.0; // They are assumed as coplanar.
16134 }
16135 }
16136 if (ori == 0.0) {
16137 mergeflag = (in->facetmarkerlist == (int *) NULL ||
16138 in->facetmarkerlist[fidx1] == in->facetmarkerlist[fidx2]);
16139 if (mergeflag) {
16140 // This segment becomes dead.
16141 if (b->verbose > 1) {
16142 printf(" Removing segment (%d, %d).\n", pointmark(eorg),
16143 pointmark(edest));
16144 }
16145 ssdissolve(parentsh);
16146 ssdissolve(neighsh);
16147 shellfacedealloc(subsegs, segloop.sh);
16148 j = pointmark(eorg);
16149 segspernodelist[j]--;
16150 if (segspernodelist[j] == 0) {
16151 setpointtype(eorg, FACETVERTEX);
16152 }
16153 j = pointmark(edest);
16154 segspernodelist[j]--;
16155 if (segspernodelist[j] == 0) {
16156 setpointtype(edest, FACETVERTEX);
16157 }
16158 // Add 'parentsh' to queue checking for flip.
16159 enqueueflipedge(parentsh, flipqueue);
16160 }
16161 }
16162 }
16163 }
16164 segloop.sh = shellfacetraverse(subsegs);
16165 }
16166
16167 if (!flipqueue->empty()) {
16168 // Restore the Delaunay property in the facet triangulation.
16169 flipsub(flipqueue);
16170 }
16171
16172 delete [] segspernodelist;
16173 }
16174
16175 ///////////////////////////////////////////////////////////////////////////////
16176 // //
16177 // meshsurface() Create the surface mesh of a PLC. //
16178 // //
16179 // Let X be the PLC, the surface mesh S of X consists of triangulated facets.//
16180 // S is created mainly in the following steps: //
16181 // //
16182 // (1) Form the CDT of each facet of X separately (by routine triangulate()).//
16183 // After it is done, the subfaces of each facet are connected to each other, //
16184 // however there is no connection between facets yet. Notice each facet has //
16185 // its own segments, some of them are duplicated. //
16186 // //
16187 // (2) Remove the redundant segments created in step (1) (by routine unify- //
16188 // segment()). The subface ring of each segment is created, the connection //
16189 // between facets are established as well. //
16190 // //
16191 // The return value indicates the number of segments of X. //
16192 // //
16193 ///////////////////////////////////////////////////////////////////////////////
16194
16195 long tetgenmesh::meshsurface()
16196 {
16197 list *ptlist, *conlist;
16198 queue *flipqueue;
16199 tetgenio::facet *f;
16200 tetgenio::polygon *p;
16201 memorypool *viri;
16202 point *idx2verlist;
16203 point tstart, tend, *cons;
16204 int *worklist;
16205 int end1, end2;
16206 int shmark, i, j;
16207
16208 if (!b->quiet) {
16209 printf("Creating surface mesh.\n");
16210 }
16211
16212 // Compute a mapping from indices to points.
16213 makeindex2pointmap(idx2verlist);
16214 // Compute a mapping from points to tets for computing abovepoints.
16215 makepoint2tetmap();
16216 // Initialize 'facetabovepointarray'.
16217 facetabovepointarray = new point[in->numberoffacets + 1];
16218 for (i = 0; i < in->numberoffacets + 1; i++) {
16219 facetabovepointarray[i] = (point) NULL;
16220 }
16221 if (checkpbcs) {
16222 // Initialize the global array 'subpbcgrouptable'.
16223 createsubpbcgrouptable();
16224 }
16225
16226 // Initialize working lists.
16227 viri = new memorypool(sizeof(shellface *), 1024, POINTER, 0);
16228 flipqueue = new queue(sizeof(badface));
16229 ptlist = new list(sizeof(point *), NULL, 256);
16230 conlist = new list(sizeof(point *) * 2, NULL, 256);
16231 worklist = new int[points->items + 1];
16232 for (i = 0; i < points->items + 1; i++) worklist[i] = 0;
16233
16234 // Loop the facet list, triangulate each facet. On finish, all subfaces
16235 // are in 'subfaces', all segments are in 'subsegs'. Notice: there're
16236 // redundant segments. Remember: All facet indices count from 1.
16237 for (shmark = 1; shmark <= in->numberoffacets; shmark++) {
16238 // Get a facet F.
16239 f = &in->facetlist[shmark - 1];
16240
16241 // Process the duplicated points first, they are marked with type
16242 // DUPLICATEDVERTEX by incrflipdelaunay(). Let p and q are dup.
16243 // and the index of p is larger than q's, p is substituted by q.
16244 // In a STL mesh, duplicated points are implicitly included.
16245 if ((b->object == tetgenbehavior::STL) || dupverts) {
16246 // Loop all polygons of this facet.
16247 for (i = 0; i < f->numberofpolygons; i++) {
16248 p = &(f->polygonlist[i]);
16249 // Loop other vertices of this polygon.
16250 for (j = 0; j < p->numberofvertices; j++) {
16251 end1 = p->vertexlist[j];
16252 tstart = idx2verlist[end1 - in->firstnumber];
16253 if (pointtype(tstart) == DUPLICATEDVERTEX) {
16254 // Reset the index of vertex-j.
16255 tend = point2ppt(tstart);
16256 end2 = pointmark(tend);
16257 p->vertexlist[j] = end2;
16258 }
16259 }
16260 }
16261 }
16262
16263 // Loop polygons of F, get the set V of vertices and S of segments.
16264 for (i = 0; i < f->numberofpolygons; i++) {
16265 // Get a polygon.
16266 p = &(f->polygonlist[i]);
16267 // Get the first vertex.
16268 end1 = p->vertexlist[0];
16269 if ((end1 < in->firstnumber) ||
16270 (end1 >= in->firstnumber + in->numberofpoints)) {
16271 if (!b->quiet) {
16272 printf("Warning: Invalid the 1st vertex %d of polygon", end1);
16273 printf(" %d in facet %d.\n", i + 1, shmark);
16274 }
16275 continue; // Skip this polygon.
16276 }
16277 tstart = idx2verlist[end1 - in->firstnumber];
16278 // Add tstart to V if it haven't been added yet.
16279 if (worklist[end1] == 0) {
16280 ptlist->append(&tstart);
16281 worklist[end1] = 1;
16282 }
16283 // Loop other vertices of this polygon.
16284 for (j = 1; j <= p->numberofvertices; j++) {
16285 // get a vertex.
16286 if (j < p->numberofvertices) {
16287 end2 = p->vertexlist[j];
16288 } else {
16289 end2 = p->vertexlist[0]; // Form a loop from last to first.
16290 }
16291 if ((end2 < in->firstnumber) ||
16292 (end2 >= in->firstnumber + in->numberofpoints)) {
16293 if (!b->quiet) {
16294 printf("Warning: Invalid vertex %d in polygon %d", end2, i + 1);
16295 printf(" in facet %d.\n", shmark);
16296 }
16297 } else {
16298 if (end1 != end2) {
16299 // 'end1' and 'end2' form a segment.
16300 tend = idx2verlist[end2 - in->firstnumber];
16301 // Add tstart to V if it haven't been added yet.
16302 if (worklist[end2] == 0) {
16303 ptlist->append(&tend);
16304 worklist[end2] = 1;
16305 }
16306 // Save the segment in S (conlist).
16307 cons = (point *) conlist->append(NULL);
16308 cons[0] = tstart;
16309 cons[1] = tend;
16310 // Set the start for next continuous segment.
16311 end1 = end2;
16312 tstart = tend;
16313 } else {
16314 // Two identical vertices represent an isolated vertex of F.
16315 if (p->numberofvertices > 2) {
16316 // This may be an error in the input, anyway, we can continue
16317 // by simply skipping this segment.
16318 if (!b->quiet) {
16319 printf("Warning: Polygon %d has two identical verts", i + 1);
16320 printf(" in facet %d.\n", shmark);
16321 }
16322 }
16323 // Ignore this vertex.
16324 }
16325 }
16326 // Is the polygon degenerate (a segment or a vertex)?
16327 if (p->numberofvertices == 2) break;
16328 }
16329 }
16330 // Unmark vertices.
16331 for (i = 0; i < ptlist->len(); i++) {
16332 tstart = * (point *)(* ptlist)[i];
16333 end1 = pointmark(tstart);
16334 assert(worklist[end1] == 1);
16335 worklist[end1] = 0;
16336 }
16337
16338 // Create a CDT of F.
16339 triangulate(shmark, b->epsilon * 1e+2, ptlist, conlist, f->numberofholes,
16340 f->holelist, viri, flipqueue);
16341 // Clear working lists.
16342 ptlist->clear();
16343 conlist->clear();
16344 viri->restart();
16345 }
16346
16347 // Unify segments in 'subsegs', remove redundant segments. Face links
16348 // of segments are also built.
16349 unifysegments();
16350
16351 if (checkpbcs) {
16352 // Create the global array 'segpbcgrouptable'.
16353 createsegpbcgrouptable();
16354 }
16355
16356 if (b->object == tetgenbehavior::STL) {
16357 // Remove redundant vertices (for .stl input mesh).
16358 jettisonnodes();
16359 }
16360
16361 if (!b->nomerge && !checkpbcs) {
16362 // No '-M' switch - merge adjacent facets if they are coplanar.
16363 mergefacets(flipqueue);
16364 }
16365
16366 delete [] idx2verlist;
16367 delete [] worklist;
16368 delete ptlist;
16369 delete conlist;
16370 delete flipqueue;
16371 delete viri;
16372
16373 return subsegs->items;
16374 }
16375
16376 //
16377 // End of surface triangulation routines
16378 //
16379
16380 ///////////////////////////////////////////////////////////////////////////////
16381 // //
16382 // interecursive() Recursively do intersection test on a set of triangles.//
16383 // //
16384 // Recursively split the set 'subfacearray' of subfaces into two sets using //
16385 // a cut plane parallel to x-, or, y-, or z-axies. The split criteria are //
16386 // follows. Assume the cut plane is H, and H+ denotes the left halfspace of //
16387 // H, and H- denotes the right halfspace of H; and s be a subface: //
16388 // //
16389 // (1) If all points of s lie at H+, put it into left array; //
16390 // (2) If all points of s lie at H-, put it into right array; //
16391 // (3) If some points of s lie at H+ and some of lie at H-, or some //
16392 // points lie on H, put it into both arraies. //
16393 // //
16394 // Partitions by x-axis if axis == '0'; by y-axis if axis == '1'; by z-axis //
16395 // if axis == '2'. If current cut plane is parallel to the x-axis, the next //
16396 // one will be parallel to y-axis, and the next one after the next is z-axis,//
16397 // and then alternately return back to x-axis. //
16398 // //
16399 // Stop splitting when the number of triangles of the input array is not //
16400 // decreased anymore. Do tests on the current set. //
16401 // //
16402 ///////////////////////////////////////////////////////////////////////////////
16403
16404 void tetgenmesh::
16405 interecursive(shellface** subfacearray, int arraysize, int axis, REAL bxmin,
16406 REAL bxmax, REAL bymin, REAL bymax, REAL bzmin, REAL bzmax,
16407 int* internum)
16408 {
16409 shellface **leftarray, **rightarray;
16410 face sface1, sface2;
16411 point p1, p2, p3;
16412 point p4, p5, p6;
16413 enum interresult intersect;
16414 REAL split;
16415 bool toleft, toright;
16416 int leftsize, rightsize;
16417 int i, j;
16418
16419 if (b->verbose > 1) {
16420 printf(" Recur %d faces. Bbox (%g, %g, %g),(%g, %g, %g). %s-axis\n",
16421 arraysize, bxmin, bymin, bzmin, bxmax, bymax, bzmax,
16422 axis == 0 ? "x" : (axis == 1 ? "y" : "z"));
16423 }
16424
16425 leftarray = new shellface*[arraysize];
16426 if (leftarray == NULL) {
16427 printf("Error in interecursive(): Insufficient memory.\n");
16428 terminatetetgen(1);
16429 }
16430 rightarray = new shellface*[arraysize];
16431 if (rightarray == NULL) {
16432 printf("Error in interecursive(): Insufficient memory.\n");
16433 terminatetetgen(1);
16434 }
16435 leftsize = rightsize = 0;
16436
16437 if (axis == 0) {
16438 // Split along x-axis.
16439 split = 0.5 * (bxmin + bxmax);
16440 } else if (axis == 1) {
16441 // Split along y-axis.
16442 split = 0.5 * (bymin + bymax);
16443 } else {
16444 // Split along z-axis.
16445 split = 0.5 * (bzmin + bzmax);
16446 }
16447
16448 for (i = 0; i < arraysize; i++) {
16449 sface1.sh = subfacearray[i];
16450 p1 = (point) sface1.sh[3];
16451 p2 = (point) sface1.sh[4];
16452 p3 = (point) sface1.sh[5];
16453 toleft = toright = false;
16454 if (p1[axis] < split) {
16455 toleft = true;
16456 if (p2[axis] >= split || p3[axis] >= split) {
16457 toright = true;
16458 }
16459 } else if (p1[axis] > split) {
16460 toright = true;
16461 if (p2[axis] <= split || p3[axis] <= split) {
16462 toleft = true;
16463 }
16464 } else {
16465 // p1[axis] == split;
16466 toleft = true;
16467 toright = true;
16468 }
16469 // At least one is true;
16470 #ifdef SELF_CHECK
16471 assert(!(toleft == false && toright == false));
16472 #endif
16473 if (toleft) {
16474 leftarray[leftsize] = sface1.sh;
16475 leftsize++;
16476 }
16477 if (toright) {
16478 rightarray[rightsize] = sface1.sh;
16479 rightsize++;
16480 }
16481 }
16482
16483 if (leftsize < arraysize && rightsize < arraysize) {
16484 // Continue to partition the input set. Now 'subfacearray' has been
16485 // split into two sets, it's memory can be freed. 'leftarray' and
16486 // 'rightarray' will be freed in the next recursive (after they're
16487 // partitioned again or performing tests).
16488 delete [] subfacearray;
16489 // Continue to split these two sets.
16490 if (axis == 0) {
16491 interecursive(leftarray, leftsize, 1, bxmin, split, bymin, bymax,
16492 bzmin, bzmax, internum);
16493 interecursive(rightarray, rightsize, 1, split, bxmax, bymin, bymax,
16494 bzmin, bzmax, internum);
16495 } else if (axis == 1) {
16496 interecursive(leftarray, leftsize, 2, bxmin, bxmax, bymin, split,
16497 bzmin, bzmax, internum);
16498 interecursive(rightarray, rightsize, 2, bxmin, bxmax, split, bymax,
16499 bzmin, bzmax, internum);
16500 } else {
16501 interecursive(leftarray, leftsize, 0, bxmin, bxmax, bymin, bymax,
16502 bzmin, split, internum);
16503 interecursive(rightarray, rightsize, 0, bxmin, bxmax, bymin, bymax,
16504 split, bzmax, internum);
16505 }
16506 } else {
16507 if (b->verbose > 1) {
16508 printf(" Checking intersecting faces.\n");
16509 }
16510 // Perform a brute-force compare on the set.
16511 for (i = 0; i < arraysize; i++) {
16512 sface1.sh = subfacearray[i];
16513 p1 = (point) sface1.sh[3];
16514 p2 = (point) sface1.sh[4];
16515 p3 = (point) sface1.sh[5];
16516 for (j = i + 1; j < arraysize; j++) {
16517 sface2.sh = subfacearray[j];
16518 p4 = (point) sface2.sh[3];
16519 p5 = (point) sface2.sh[4];
16520 p6 = (point) sface2.sh[5];
16521 intersect = tri_tri_inter(p1, p2, p3, p4, p5, p6);
16522 if (intersect == INTERSECT || intersect == SHAREFACE) {
16523 if (!b->quiet) {
16524 if (intersect == INTERSECT) {
16525 printf(" Facet #%d intersects facet #%d at triangles:\n",
16526 shellmark(sface1), shellmark(sface2));
16527 printf(" (%4d, %4d, %4d) and (%4d, %4d, %4d)\n",
16528 pointmark(p1), pointmark(p2), pointmark(p3),
16529 pointmark(p4), pointmark(p5), pointmark(p6));
16530 } else {
16531 printf(" Facet #%d duplicates facet #%d at triangle:\n",
16532 shellmark(sface1), shellmark(sface2));
16533 printf(" (%4d, %4d, %4d)\n", pointmark(p1), pointmark(p2),
16534 pointmark(p3));
16535 }
16536 }
16537 // Increase the number of intersecting pairs.
16538 (*internum)++;
16539 // Infect these two faces (although they may already be infected).
16540 sinfect(sface1);
16541 sinfect(sface2);
16542 }
16543 }
16544 }
16545 // Don't forget to free all three arrays. No further partition.
16546 delete [] leftarray;
16547 delete [] rightarray;
16548 delete [] subfacearray;
16549 }
16550 }
16551
16552 ///////////////////////////////////////////////////////////////////////////////
16553 // //
16554 // detectinterfaces() Detect intersecting triangles. //
16555 // //
16556 // Given a set of triangles, find the pairs of intersecting triangles from //
16557 // them. Here the set of triangles is in 'subfaces' which is a surface mesh //
16558 // of a PLC (.poly or .smesh). //
16559 // //
16560 // To detect whether two triangles are intersecting is done by the routine //
16561 // 'tri_tri_inter()'. The algorithm for the test is very simple and stable. //
16562 // It is based on geometric orientation test which uses exact arithmetics. //
16563 // //
16564 // Use divide-and-conquer algorithm for reducing the number of intersection //
16565 // tests. Start from the bounding box of the input point set, recursively //
16566 // partition the box into smaller boxes, until the number of triangles in a //
16567 // box is not decreased anymore. Then perform triangle-triangle tests on the //
16568 // remaining set of triangles. The memory allocated in the input set is //
16569 // freed immediately after it has been partitioned into two arrays. So it //
16570 // can be re-used for the consequent partitions. //
16571 // //
16572 // On return, the pool 'subfaces' will be cleared, and only the intersecting //
16573 // triangles remain for output (to a .face file). //
16574 // //
16575 ///////////////////////////////////////////////////////////////////////////////
16576
16577 void tetgenmesh::detectinterfaces()
16578 {
16579 shellface **subfacearray;
16580 face shloop;
16581 int internum;
16582 int i;
16583
16584 if (!b->quiet) {
16585 printf("Detecting intersecting facets.\n");
16586 }
16587
16588 // Construct a map from indices to subfaces;
16589 subfacearray = new shellface*[subfaces->items];
16590 subfaces->traversalinit();
16591 shloop.sh = shellfacetraverse(subfaces);
16592 i = 0;
16593 while (shloop.sh != (shellface *) NULL) {
16594 subfacearray[i] = shloop.sh;
16595 shloop.sh = shellfacetraverse(subfaces);
16596 i++;
16597 }
16598
16599 internum = 0;
16600 // Recursively split the set of triangles into two sets using a cut plane
16601 // parallel to x-, or, y-, or z-axies. Stop splitting when the number
16602 // of subfaces is not decreasing anymore. Do tests on the current set.
16603 interecursive(subfacearray, subfaces->items, 0, xmin, xmax, ymin, ymax,
16604 zmin, zmax, &internum);
16605
16606 if (!b->quiet) {
16607 if (internum > 0) {
16608 printf("\n!! Found %d pairs of faces are intersecting.\n\n", internum);
16609 } else {
16610 printf("\nNo faces are intersecting.\n\n");
16611 }
16612 }
16613
16614 if (internum > 0) {
16615 // Traverse all subfaces, deallocate those have not been infected (they
16616 // are not intersecting faces). Uninfect those have been infected.
16617 // After this loop, only intersecting faces remain.
16618 subfaces->traversalinit();
16619 shloop.sh = shellfacetraverse(subfaces);
16620 while (shloop.sh != (shellface *) NULL) {
16621 if (sinfected(shloop)) {
16622 suninfect(shloop);
16623 } else {
16624 shellfacedealloc(subfaces, shloop.sh);
16625 }
16626 shloop.sh = shellfacetraverse(subfaces);
16627 }
16628 } else {
16629 // Deallocate all subfaces.
16630 subfaces->restart();
16631 }
16632 }
16633
16634 //
16635 // Begin of periodic boundary condition routines
16636 //
16637
16638 ///////////////////////////////////////////////////////////////////////////////
16639 // //
16640 // createsubpbcgrouptable() Create the 'subpbcgrouptable'. //
16641 // //
16642 // Allocate the memory for 'subpbcgrouptable'. Each entry i (a pbcdata) of //
16643 // the table represents a pbcgroup. Most of the fields of a group-i are set //
16644 // in this routine. 'fmark[0]', 'fmark[1]', and 'transmat[0]' are directly //
16645 // copied from the corresponding data of 'in->numberofpbcgroups'. 'transmat //
16646 // [1]' is calculated as the inverse matrix of 'transmat[0]'. 'ss[0]' and //
16647 // 'ss[1]' are initilized be 'dummysh'. They are set in 'trangulatefacet()' //
16648 // (when -p is in use) or 'reconstructmesh()' (when -r is in use). //
16649 // //
16650 ///////////////////////////////////////////////////////////////////////////////
16651
16652 void tetgenmesh::createsubpbcgrouptable()
16653 {
16654 tetgenio::pbcgroup *pg;
16655 pbcdata *pd;
16656 REAL A[4][4], rhs[4], D;
16657 int indx[4];
16658 int i, j, k;
16659
16660 subpbcgrouptable = new pbcdata[in->numberofpbcgroups];
16661 for (i = 0; i < in->numberofpbcgroups; i++) {
16662 pg = &(in->pbcgrouplist[i]);
16663 pd = &(subpbcgrouptable[i]);
16664 // Copy data from pg to pd.
16665 pd->fmark[0] = pg->fmark1;
16666 pd->fmark[1] = pg->fmark2;
16667 // Initialize array 'pd->ss'.
16668 pd->ss[0].sh = dummysh;
16669 pd->ss[1].sh = dummysh;
16670 // Copy the transform matrix from pg to pd->transmat[0].
16671 for (j = 0; j < 4; j++) {
16672 for (k = 0; k < 4; k++) {
16673 pd->transmat[0][j][k] = pg->transmat[j][k];
16674 // Prepare for inverting the matrix.
16675 A[j][k] = pg->transmat[j][k];
16676 }
16677 }
16678 // Calculate the inverse matrix (pd->transmat[1]) of pd->transmat[0].
16679 lu_decmp(A, 4, indx, &D, 0);
16680 for (j = 0; j < 4; j++) {
16681 for (k = 0; k < 4; k++) rhs[k] = 0.0;
16682 rhs[j] = 1.0;
16683 lu_solve(A, 4, indx, rhs, 0);
16684 for (k = 0; k < 4; k++) pd->transmat[1][k][j] = rhs[k];
16685 }
16686 }
16687 }
16688
16689 ///////////////////////////////////////////////////////////////////////////////
16690 // //
16691 // getsubpbcgroup() Get the pbcgroup of a subface. //
16692 // //
16693 // 'pbcsub' has pbc defined. Its pbcgroup is returned in 'pd'. In addition, //
16694 // 'f1' (0 or 1) indicates the position of 'pbcsub' in 'pd'; 'f2' (= 1 - f1) //
16695 // is the position where the symmetric subface of 'pbcsub' is found. //
16696 // //
16697 ///////////////////////////////////////////////////////////////////////////////
16698
16699 void tetgenmesh::getsubpbcgroup(face* pbcsub, pbcdata** pd, int *f1, int *f2)
16700 {
16701 int groupid, fmark, idx;
16702
16703 groupid = shellpbcgroup(*pbcsub);
16704 *pd = &subpbcgrouptable[groupid];
16705
16706 // Get the facet index (1 - based).
16707 idx = shellmark(*pbcsub);
16708 // Get the facet marker from array (0 - based).
16709 fmark = in->facetmarkerlist[idx - 1];
16710 if ((*pd)->fmark[0] == fmark) {
16711 *f1 = 0;
16712 } else {
16713 #ifdef SELF_CHECK
16714 assert((*pd)->fmark[1] == fmark);
16715 #endif
16716 *f1 = 1;
16717 }
16718 *f2 = 1 - (*f1);
16719 }
16720
16721 ///////////////////////////////////////////////////////////////////////////////
16722 // //
16723 // getsubpbcsympoint() Compute the symmetric point for a subface point. //
16724 // //
16725 // 'newpoint' lies on 'splitsub'. This routine calculates a 'sympoint' which //
16726 // locates on 'symsplitsub' and symmtric to 'newpoint'. Return the location //
16727 // of sympoint wrt. symsplitsub. //
16728 // //
16729 ///////////////////////////////////////////////////////////////////////////////
16730
16731 enum tetgenmesh::locateresult tetgenmesh:: getsubpbcsympoint(point newpoint,
16732 face* splitsub, point sympoint, face* symsplitsub)
16733 {
16734 pbcdata *pd;
16735 face subloop;
16736 point pa, pb, pc;
16737 enum locateresult symloc;
16738 REAL ori;
16739 int f1, f2, i;
16740
16741 // Get the pbcgroup of 'splitsub'.
16742 getsubpbcgroup(splitsub, &pd, &f1, &f2);
16743
16744 // Transform newpoint from f1 -> f2.
16745 for (i = 0; i < 3; i++) {
16746 sympoint[i] = pd->transmat[f1][i][0] * newpoint[0]
16747 + pd->transmat[f1][i][1] * newpoint[1]
16748 + pd->transmat[f1][i][2] * newpoint[2]
16749 + pd->transmat[f1][i][3] * 1.0;
16750 }
16751 // Locate sympoint in f2.
16752 symloc = OUTSIDE;
16753 *symsplitsub = pd->ss[f2];
16754 // Is the stored subface valid? Hole removal may delete the subface.
16755 if ((symsplitsub->sh != dummysh) && !isdead(symsplitsub)) {
16756 // 'symsplitsub' should lie on the symmetric facet. Check it.
16757 i = shellmark(*symsplitsub);
16758 if (in->facetmarkerlist[i - 1] == pd->fmark[f2]) {
16759 // 'symsplitsub' has the symmetric boundary marker.
16760 pa = sorg(*symsplitsub);
16761 pb = sdest(*symsplitsub);
16762 pc = sapex(*symsplitsub);
16763 // Test if they are (nearly) coplanar. Some facets may have the
16764 // same boundary marker but not coplanar with this point.
16765 ori = orient3d(pa, pb, pc, sympoint);
16766 if (iscoplanar(pa, pb, pc, sympoint, ori, b->epsilon * 1e+2)) {
16767 // Locate sympoint in facet. Don't stop at subsegment.
16768 abovepoint = facetabovepointarray[shellmark(*symsplitsub)];
16769 if (abovepoint == (point) NULL) {
16770 getfacetabovepoint(symsplitsub);
16771 }
16772 symloc = locatesub(sympoint, symsplitsub, 0, b->epsilon * 1e+2);
16773 }
16774 }
16775 }
16776 if (symloc == OUTSIDE) {
16777 // Do a brute-force searching for the symmetric subface.
16778 REAL epspp = b->epsilon * 1e+2;
16779 int lcount = 0;
16780 do {
16781 // Locate sympoint in the pool of subfaces (with fmark pd->fmark[f2]).
16782 subfaces->traversalinit();
16783 subloop.sh = shellfacetraverse(subfaces);
16784 while (subloop.sh != (shellface *) NULL) {
16785 i = shellmark(subloop);
16786 if (in->facetmarkerlist[i - 1] == pd->fmark[f2]) {
16787 // Found a facet have the symmetric boundary marker.
16788 pa = sorg(subloop);
16789 pb = sdest(subloop);
16790 pc = sapex(subloop);
16791 // Test if they are (nearly) coplanar. Some facets may have the
16792 // same boundary marker but not coplanar with this point.
16793 ori = orient3d(pa, pb, pc, sympoint);
16794 if (iscoplanar(pa, pb, pc, sympoint, ori, epspp)) {
16795 // Test if sympoint is (nearly) inside this facet.
16796 // Get the abovepoint of the facet.
16797 abovepoint = facetabovepointarray[shellmark(subloop)];
16798 // Do we need to calculate the abovepoint?
16799 if (abovepoint == (point) NULL) {
16800 getfacetabovepoint(&subloop);
16801 }
16802 // subloop is on the facet, search sympoint.
16803 symloc = locatesub(sympoint, &subloop, 0, epspp);
16804 if (symloc != OUTSIDE) break;
16805 }
16806 }
16807 subloop.sh = shellfacetraverse(subfaces);
16808 }
16809 lcount++;
16810 epspp *= 10.0;
16811 } while ((symloc == OUTSIDE) && (lcount < 3));
16812 #ifdef SELF_CHECK
16813 // sympoint should be inside the facet.
16814 assert(symloc != OUTSIDE);
16815 #endif
16816 // Set the returning subface.
16817 *symsplitsub = subloop;
16818 // Update the stored subface for next searching.
16819 pd->ss[f2] = *symsplitsub;
16820 }
16821
16822 return adjustlocatesub(sympoint, symsplitsub, symloc, b->epsilon);
16823 }
16824
16825 ///////////////////////////////////////////////////////////////////////////////
16826 // //
16827 // createsegpbcgrouptable() Create the 'segpbcgrouptable'. //
16828 // //
16829 // Each segment may belong to more than one pbcgroups. For example, segment //
16830 // ab may need to be symmteric to both segments cd, and ef, then ab and cd, //
16831 // cd and ef, ef and ab form three pbcgroups. //
16832 // //
16833 // 'segpbcgrouptable' is implemented as a list of pbcdatas. Each item i is //
16834 // a pbcgroup. //
16835 // //
16836 ///////////////////////////////////////////////////////////////////////////////
16837
16838 void tetgenmesh::createsegpbcgrouptable()
16839 {
16840 pbcdata *pd, *pd1, *pd2;
16841 face segloop, symseg;
16842 face startsh, spinsh, symsh;
16843 point pa, pb;
16844 enum locateresult symloc;
16845 REAL testpt[3], sympt[3];
16846 bool inflag;
16847 int segid1, segid2;
16848 int f1, f2;
16849 int i, j, k, l;
16850
16851 // Allocate memory for 'subpbcgrouptable'.
16852 segpbcgrouptable = new list(sizeof(pbcdata), NULL, 256);
16853
16854 // Loop through the segment list.
16855 subsegs->traversalinit();
16856 segloop.sh = shellfacetraverse(subsegs);
16857 while (segloop.sh != (shellface *) NULL) {
16858 // Loop the subface ring of segloop ab.
16859 pa = sorg(segloop);
16860 pb = sdest(segloop);
16861 segid1 = shellmark(segloop);
16862 spivot(segloop, startsh);
16863 spinsh = startsh;
16864 do {
16865 // Adjust spinsh be edge ab.
16866 if (sorg(spinsh) != pa) {
16867 sesymself(spinsh);
16868 }
16869 // Does spinsh belong to a pbcgroup?
16870 if (shellpbcgroup(spinsh) != -1) {
16871 // Yes! There exists a segment cd. ab and cd form a pbcgroup.
16872 // 'testpt' is the midpoint of ab used to find cd.
16873 for (i = 0; i < 3; i++) testpt[i] = 0.5 * (pa[i] + pb[i]);
16874 symloc = getsubpbcsympoint(testpt, &spinsh, sympt, &symsh);
16875 #ifdef SELF_CHECK
16876 assert(symloc == ONEDGE);
16877 #endif
16878 sspivot(symsh, symseg);
16879 #ifdef SELF_CHECK
16880 assert(symseg.sh != dummysh);
16881 #endif
16882 // Check whether this group has already been created in list.
16883 segid2 = shellmark(symseg);
16884 inflag = false;
16885 for (i = 0; i < segpbcgrouptable->len() && !inflag; i++) {
16886 pd = (pbcdata *)(* segpbcgrouptable)[i];
16887 if (pd->segid[0] == segid1) {
16888 if (pd->segid[1] == segid2) inflag = true;
16889 } else if (pd->segid[0] == segid2) {
16890 if (pd->segid[1] == segid1) inflag = true;
16891 }
16892 }
16893 if (!inflag) {
16894 // Create a segment pbcgroup in list for ab and cd.
16895 pd = (pbcdata *) segpbcgrouptable->append(NULL);
16896 // Save the markers of ab and cd.
16897 pd->segid[0] = segid1;
16898 pd->segid[1] = segid2;
16899 // Save the handles of ab and cd.
16900 pd->ss[0] = segloop;
16901 pd->ss[1] = symseg;
16902 // Find the map from ab to cd.
16903 getsubpbcgroup(&spinsh, &pd1, &f1, &f2);
16904 pd->fmark[0] = pd1->fmark[f1];
16905 pd->fmark[1] = pd1->fmark[f2];
16906 // Set the map from ab to cd.
16907 for (i = 0; i < 4; i++) {
16908 for (j = 0; j < 4; j++) {
16909 pd->transmat[0][i][j] = pd1->transmat[f1][i][j];
16910 }
16911 }
16912 // Set the map from cd to ab.
16913 for (i = 0; i < 4; i++) {
16914 for (j = 0; j < 4; j++) {
16915 pd->transmat[1][i][j] = pd1->transmat[f2][i][j];
16916 }
16917 }
16918 }
16919 }
16920 // Go to the next subface in the ring of ab.
16921 spivotself(spinsh);
16922 } while (spinsh.sh != startsh.sh);
16923 segloop.sh = shellfacetraverse(subsegs);
16924 }
16925
16926 // Create the indirect segment pbcgroups.
16927 for (i = 0; i < segpbcgrouptable->len(); i++) {
16928 pd1 = (pbcdata *)(* segpbcgrouptable)[i];
16929 for (f1 = 0; f1 < 2; f1++) {
16930 // Search for a group (except i) contains pd1->segid[f1].
16931 for (j = 0; j < segpbcgrouptable->len(); j++) {
16932 if (j == i) continue;
16933 pd2 = (pbcdata *)(* segpbcgrouptable)[j];
16934 f2 = -1;
16935 if (pd1->segid[f1] == pd2->segid[0]) {
16936 f2 = 0;
16937 } else if (pd1->segid[f1] == pd2->segid[1]) {
16938 f2 = 1;
16939 }
16940 if (f2 != -1) {
16941 #ifdef SELF_CHECK
16942 assert(pd1->segid[f1] == pd2->segid[f2]);
16943 #endif
16944 segid1 = pd1->segid[1 - f1];
16945 segid2 = pd2->segid[1 - f2];
16946 // Search for the existence of segment pbcgroup (segid1, segid2).
16947 inflag = false;
16948 for (k = 0; k < segpbcgrouptable->len() && !inflag; k++) {
16949 pd = (pbcdata *)(* segpbcgrouptable)[k];
16950 if (pd->segid[0] == segid1) {
16951 if (pd->segid[1] == segid2) inflag = true;
16952 } else if (pd->segid[0] == segid2) {
16953 if (pd->segid[1] == segid1) inflag = true;
16954 }
16955 }
16956 if (!inflag) {
16957 pd = (pbcdata *) segpbcgrouptable->append(NULL);
16958 pd->segid[0] = pd1->segid[1 - f1];
16959 pd->segid[1] = pd2->segid[1 - f2];
16960 pd->ss[0] = pd1->ss[1 - f1];
16961 pd->ss[1] = pd2->ss[1 - f2];
16962 // Invalid the fmark[0] == fmark[1].
16963 pd->fmark[0] = pd->fmark[1] = 0;
16964 // Translate matrix pd->transmat[0] = m2 * m1, where m1 =
16965 // pd1->transmat[1 - f1], m2 = pd2->transmat[f2].
16966 for (k = 0; k < 4; k++) {
16967 for (l = 0; l < 4; l++) {
16968 pd->transmat[0][k][l] = pd2->transmat[f2][k][l];
16969 }
16970 }
16971 m4xm4(pd->transmat[0], pd1->transmat[1 - f1]);
16972 // Translate matrix pd->transmat[1] = m4 * m3, where m3 =
16973 // pd2->transmat[1 - f2], m4 = pd1->transmat[f1].
16974 for (k = 0; k < 4; k++) {
16975 for (l = 0; l < 4; l++) {
16976 pd->transmat[1][k][l] = pd1->transmat[f1][k][l];
16977 }
16978 }
16979 m4xm4(pd->transmat[1], pd2->transmat[1 - f2]);
16980 }
16981 }
16982 }
16983 }
16984 }
16985
16986 // Form a map from segment index to pbcgroup list of this segment.
16987 idx2segpglist = new int[subsegs->items + 1];
16988 for (i = 0; i < subsegs->items + 1; i++) idx2segpglist[i] = 0;
16989 // Loop through 'segpbcgrouptable', counter the number of pbcgroups of
16990 // each segment.
16991 for (i = 0; i < segpbcgrouptable->len(); i++) {
16992 pd = (pbcdata *)(* segpbcgrouptable)[i];
16993 for (j = 0; j < 2; j++) {
16994 k = pd->segid[j] - 1;
16995 idx2segpglist[k]++;
16996 }
16997 }
16998 // Calculate the total length of array 'segpglist'.
16999 j = idx2segpglist[0];
17000 idx2segpglist[0] = 0; // Array starts from 0 element.
17001 for (i = 0; i < subsegs->items; i++) {
17002 k = idx2segpglist[i + 1];
17003 idx2segpglist[i + 1] = idx2segpglist[i] + j;
17004 j = k;
17005 }
17006 // The total length is in the last unit of idx2segpglist.
17007 segpglist = new int[idx2segpglist[i]];
17008 // Loop the set of pbcgroups again, set the data into segpglist.
17009 for (i = 0; i < segpbcgrouptable->len(); i++) {
17010 pd = (pbcdata *)(* segpbcgrouptable)[i];
17011 for (j = 0; j < 2; j++) {
17012 k = pd->segid[j] - 1;
17013 segpglist[idx2segpglist[k]] = i;
17014 idx2segpglist[k]++;
17015 }
17016 }
17017 // Contents in 'idx2segpglist' are shifted, now shift them back.
17018 for (i = subsegs->items - 1; i >= 0; i--) {
17019 idx2segpglist[i + 1] = idx2segpglist[i];
17020 }
17021 idx2segpglist[0] = 0;
17022 }
17023
17024 ///////////////////////////////////////////////////////////////////////////////
17025 // //
17026 // getsegpbcsympoint() Compute the symmetric point for a segment point. //
17027 // //
17028 // 'newpoint' lies on 'splitseg'. This routine calculates a 'sympoint' which //
17029 // locates on 'symsplitseg' and symmtric to 'newpoint'. Return the location //
17030 // of sympoint wrt. symsplitseg. //
17031 // //
17032 ///////////////////////////////////////////////////////////////////////////////
17033
17034 enum tetgenmesh::locateresult tetgenmesh::
17035 getsegpbcsympoint(point newpoint, face* splitseg, point sympoint,
17036 face* symsplitseg, int groupid)
17037 {
17038 pbcdata *pd;
17039 enum locateresult symloc;
17040 int segid, f1, f2, i;
17041
17042 pd = (pbcdata *)(* segpbcgrouptable)[groupid];
17043 segid = shellmark(*splitseg);
17044 if (pd->segid[0] == segid) {
17045 f1 = 0;
17046 } else {
17047 #ifdef SELF_CHECK
17048 assert(pd->segid[1] == segid);
17049 #endif
17050 f1 = 1;
17051 }
17052 f2 = 1 - f1;
17053
17054 // Transform newpoint from f1 -> f2.
17055 for (i = 0; i < 3; i++) {
17056 sympoint[i] = pd->transmat[f1][i][0] * newpoint[0]
17057 + pd->transmat[f1][i][1] * newpoint[1]
17058 + pd->transmat[f1][i][2] * newpoint[2]
17059 + pd->transmat[f1][i][3] * 1.0;
17060 }
17061 // Locate sympoint in f2.
17062 *symsplitseg = pd->ss[f2];
17063 #ifdef SELF_CHECK
17064 assert(symsplitseg->sh != dummysh);
17065 #endif
17066 // Locate sympoint in facet. Stop at subsegment.
17067 symloc = locateseg(sympoint, symsplitseg);
17068 symloc = adjustlocateseg(sympoint, symsplitseg, symloc, b->epsilon * 1e+2);
17069 return symloc;
17070 }
17071
17072 //
17073 // End of periodic boundary condition routines
17074 //
17075
17076 //
17077 // Begin of vertex perturbation routines
17078 //
17079
17080 ///////////////////////////////////////////////////////////////////////////////
17081 // //
17082 // randgenerator() Generate a random REAL number between (0, |range|). //
17083 // //
17084 ///////////////////////////////////////////////////////////////////////////////
17085
17086 REAL tetgenmesh::randgenerator(REAL range)
17087 {
17088 REAL worknumber, result;
17089 int expo;
17090
17091 if (range == 0.0) return 0.0;
17092
17093 expo = 0;
17094 worknumber = fabs(range);
17095 // Normalize worknumber (i.e., 1.xxxExx)
17096 if (worknumber > 10.0) {
17097 while (worknumber > 10.0) {
17098 worknumber /= 10.0;
17099 expo++;
17100 }
17101 } else if (worknumber < 1.0) {
17102 while (worknumber < 1.0) {
17103 worknumber *= 10.0;
17104 expo--;
17105 }
17106 }
17107 #ifdef SELF_CHECK
17108 assert(worknumber >= 1.0 && worknumber <= 10.0);
17109 #endif
17110
17111 // Enlarge worknumber 1000 times.
17112 worknumber *= 1e+3;
17113 expo -= 3;
17114 // Generate a randome number between (0, worknumber).
17115 result = (double) randomnation((int) worknumber);
17116
17117 // Scale result back into the original size.
17118 if (expo > 0) {
17119 while (expo != 0) {
17120 result *= 10.0;
17121 expo--;
17122 }
17123 } else if (expo < 0) {
17124 while (expo != 0) {
17125 result /= 10.0;
17126 expo++;
17127 }
17128 }
17129 #ifdef SELF_CHECK
17130 assert((result >= 0.0) && (result <= fabs(range)));
17131 #endif
17132
17133 return result;
17134 }
17135
17136 ///////////////////////////////////////////////////////////////////////////////
17137 // //
17138 // checksub4cocir() Test a subface to find co-circular pair of subfaces. //
17139 // //
17140 // 'eps' is a relative tolerance for testing approximately cospherical case. //
17141 // Set it to zero if only exact test is desired. //
17142 // //
17143 // An edge(not a segment) of 'testsub' is locally degenerate if the opposite //
17144 // vertex of the adjacent subface is cocircular with the vertices of testsub.//
17145 // If 'once' is TRUE, operate on the edge only if the pointer 'testsub->sh' //
17146 // is smaller than its neighbor (for each edge is considered only once). //
17147 // //
17148 // Return TRUE if find an edge of testsub is locally degenerate. //
17149 // //
17150 ///////////////////////////////////////////////////////////////////////////////
17151
17152 bool tetgenmesh::checksub4cocir(face* testsub, REAL eps, bool once,
17153 bool enqflag)
17154 {
17155 badface *cocirsub;
17156 face subloop, neighsub;
17157 face checkseg;
17158 point pa, pb, pc, pd;
17159 REAL sign;
17160 int i;
17161
17162 subloop = *testsub;
17163 subloop.shver = 0; // Keep the CCW orientation.
17164 // Get the abovepoint of the facet.
17165 abovepoint = facetabovepointarray[shellmark(subloop)];
17166 // Do we need to calculate the abovepoint?
17167 if (abovepoint == (point) NULL) {
17168 getfacetabovepoint(&subloop);
17169 }
17170 // Check the three edges of subloop.
17171 for (i = 0; i < 3; i++) {
17172 sspivot(subloop, checkseg);
17173 if (checkseg.sh == dummysh) {
17174 // It is not a segment, get the adjacent subface.
17175 spivot(subloop, neighsub);
17176 // assert(neighsub.sh != dummysh);
17177 if (!once || (once && (neighsub.sh > subloop.sh))) {
17178 pa = sorg(subloop);
17179 pb = sdest(subloop);
17180 pc = sapex(subloop);
17181 pd = sapex(neighsub);
17182 sign = insphere(pa, pb, pc, abovepoint, pd);
17183 if ((sign != 0.0) && (eps > 0.0)) {
17184 if (iscospheric(pa, pb, pc, abovepoint, pd, sign, eps)) sign = 0.0;
17185 }
17186 if (sign == 0.0) {
17187 // It's locally degenerate!
17188 if (enqflag && badsubfaces != (memorypool *) NULL) {
17189 // Save it.
17190 cocirsub = (badface *) badsubfaces->alloc();
17191 cocirsub->ss = subloop;
17192 cocirsub->forg = pa;
17193 cocirsub->fdest = pb;
17194 cocirsub->fapex = pc;
17195 cocirsub->foppo = pd;
17196 setshell2badface(cocirsub->ss, cocirsub);
17197 }
17198 if (b->verbose > 1) {
17199 printf(" Found set (%d, %d, %d, %d).\n", pointmark(pa),
17200 pointmark(pb), pointmark(pc), pointmark(pd));
17201 }
17202 return true;
17203 }
17204 }
17205 }
17206 senextself(subloop);
17207 }
17208
17209 return false;
17210 }
17211
17212 ///////////////////////////////////////////////////////////////////////////////
17213 // //
17214 // tallcocirsubs() Find all co-circular subfaces and save them in list. //
17215 // //
17216 ///////////////////////////////////////////////////////////////////////////////
17217
17218 void tetgenmesh::tallcocirsubs(REAL eps, bool enqflag)
17219 {
17220 face subloop;
17221
17222 // Loop over all subfaces.
17223 subfaces->traversalinit();
17224 subloop.sh = shellfacetraverse(subfaces);
17225 while (subloop.sh != (shellface *) NULL) {
17226 checksub4cocir(&subloop, eps, true, enqflag);
17227 subloop.sh = shellfacetraverse(subfaces);
17228 }
17229 }
17230
17231 ///////////////////////////////////////////////////////////////////////////////
17232 // //
17233 // tallencsegsfsubs() Check for encroached segs from a list of subfaces. //
17234 // //
17235 ///////////////////////////////////////////////////////////////////////////////
17236
17237 bool tetgenmesh::tallencsegsfsubs(point testpt, list* cavsublist)
17238 {
17239 face startsub, checkseg;
17240 long oldencnum;
17241 int i, j;
17242
17243 // Remember the current number of encroached segments.
17244 oldencnum = badsubsegs->items;
17245
17246 // Check segments in the list of subfaces.
17247 for (i = 0; i < cavsublist->len(); i++) {
17248 startsub = * (face *)(* cavsublist)[i];
17249 // Test all three edges of startsub.
17250 for (j = 0; j < 3; j++) {
17251 sspivot(startsub, checkseg);
17252 if (checkseg.sh != dummysh) {
17253 if (!shell2badface(checkseg)) {
17254 checkseg4encroach(&checkseg, testpt, NULL, true);
17255 }
17256 }
17257 senextself(startsub);
17258 }
17259 }
17260
17261 return (badsubsegs->items > oldencnum);
17262 }
17263
17264 ///////////////////////////////////////////////////////////////////////////////
17265 // //
17266 // collectflipedges() Collect edges of split subfaces for flip checking. //
17267 // //
17268 // 'inspoint' is a newly inserted segment point (inserted by insertsite()). //
17269 // 'splitseg' is one of the two split subsegments. Some subfaces may be non- //
17270 // Delaunay since they're still not bonded to CDT. This routine collect all //
17271 // such possible subfaces in 'flipqueue'. //
17272 // //
17273 ///////////////////////////////////////////////////////////////////////////////
17274
17275 void tetgenmesh::
17276 collectflipedges(point inspoint, face* splitseg, queue* flipqueue)
17277 {
17278 face startsh, spinsh, checksh;
17279 face nextseg;
17280 point pa, pb;
17281
17282 // Let the dest of splitseg be inspoint.
17283 splitseg->shver = 0;
17284 if (sdest(*splitseg) != inspoint) {
17285 sesymself(*splitseg);
17286 }
17287 #ifdef SELF_CHECK
17288 assert(sdest(*splitseg) == inspoint);
17289 #endif
17290 pa = sorg(*splitseg);
17291 spivot(*splitseg, startsh);
17292 spinsh = startsh;
17293 do {
17294 findedge(&spinsh, pa, inspoint);
17295 senext2(spinsh, checksh);
17296 enqueueflipedge(checksh, flipqueue);
17297 spivotself(spinsh);
17298 } while (spinsh.sh != startsh.sh);
17299
17300 // Get the next subsegment.
17301 senext(*splitseg, nextseg);
17302 spivotself(nextseg);
17303 #ifdef SELF_CHECK
17304 assert(nextseg.sh != (shellface *) NULL);
17305 #endif
17306
17307 // Let the org of nextseg be inspoint.
17308 nextseg.shver = 0;
17309 if (sorg(nextseg) != inspoint) {
17310 sesymself(nextseg);
17311 }
17312 #ifdef SELF_CHECK
17313 assert(sorg(nextseg) == inspoint);
17314 #endif
17315 pb = sdest(nextseg);
17316 spivot(nextseg, startsh);
17317 spinsh = startsh;
17318 do {
17319 findedge(&spinsh, inspoint, pb);
17320 senext(spinsh, checksh);
17321 enqueueflipedge(checksh, flipqueue);
17322 spivotself(spinsh);
17323 } while (spinsh.sh != startsh.sh);
17324 }
17325
17326 ///////////////////////////////////////////////////////////////////////////////
17327 // //
17328 // perturbrepairencsegs() Repair all encroached segments. //
17329 // //
17330 // All encroached segments are stored in 'badsubsegs'. Each segment will be //
17331 // split by adding a perturbed point near its circumcenter. //
17332 // //
17333 ///////////////////////////////////////////////////////////////////////////////
17334
17335 void tetgenmesh::perturbrepairencsegs(queue* flipqueue)
17336 {
17337 badface *encloop;
17338 tetrahedron encodedtet;
17339 triface splittet;
17340 face splitsub, symsplitsub;
17341 face splitseg, symsplitseg;
17342 point newpoint, sympoint;
17343 point pa, pb, pc;
17344 enum insertsiteresult success;
17345 enum locateresult loc, symloc;
17346 REAL cent[3], d1, ps, rs;
17347 int i, j;
17348
17349 // Note that steinerleft == -1 if an unlimited number of Steiner points
17350 // is allowed. Loop until 'badsubsegs' is empty.
17351 badsubsegs->traversalinit();
17352 encloop = badfacetraverse(badsubsegs);
17353 while ((encloop != (badface *) NULL) && (steinerleft != 0)) {
17354 splitseg = encloop->ss;
17355 #ifdef SELF_CHECK
17356 assert(shell2badface(splitseg) == encloop);
17357 #endif
17358 setshell2badface(splitseg, NULL);
17359 pa = sorg(splitseg);
17360 pb = sdest(splitseg);
17361 if ((pa == encloop->forg) && (pb == encloop->fdest)) {
17362 if (b->verbose > 1) {
17363 printf(" Get seg (%d, %d).\n", pointmark(pa), pointmark(pb));
17364 }
17365 // Create the newpoint.
17366 makepoint(&newpoint);
17367 // Get the circumcenter and radius of ab.
17368 for (i = 0; i < 3; i++) cent[i] = 0.5 * (pa[i] + pb[i]);
17369 d1 = 0.5 * distance(pa, pb);
17370 // Add a random perturbation to newpoint along the vector ab.
17371 ps = randgenerator(d1 * 1.0e-3);
17372 rs = ps / d1;
17373 // Set newpoint (be at the perturbed circumcenter of ab).
17374 for (i = 0; i < 3; i++) newpoint[i] = cent[i] + rs * (cent[i] - pa[i]);
17375 setpointtype(newpoint, FREESEGVERTEX);
17376 // Set splitseg into the newpoint.
17377 setpoint2sh(newpoint, sencode(splitseg));
17378
17379 // Is there periodic boundary condition?
17380 if (checkpbcs) {
17381 // Insert points on other segments of incident pbcgroups.
17382 i = shellmark(splitseg) - 1;
17383 for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++) {
17384 makepoint(&sympoint);
17385 symloc = getsegpbcsympoint(newpoint, &splitseg, sympoint,
17386 &symsplitseg, segpglist[j]);
17387 #ifdef SELF_CHECK
17388 assert(symloc != OUTSIDE);
17389 #endif
17390 // Note: the symsplitseg and splitseg may be identical, in case
17391 // when the the splitseg is the axis of the rotational sym.
17392 if ((symloc == ONEDGE) && (symsplitseg.sh != splitseg.sh)) {
17393 setpointtype(sympoint, FREESEGVERTEX);
17394 setpoint2sh(sympoint, sencode(symsplitseg));
17395 // Insert sympoint into DT.
17396 pc = sorg(symsplitseg);
17397 splittet.tet = dummytet;
17398 // Find a good start point to search.
17399 encodedtet = point2tet(pc);
17400 if (encodedtet != (tetrahedron) NULL) {
17401 decode(encodedtet, splittet);
17402 if (isdead(&splittet)) {
17403 splittet.tet = dummytet;
17404 }
17405 }
17406 // Locate sympoint in DT. Do exact location.
17407 success = insertsite(sympoint, &splittet, false, flipqueue);
17408 #ifdef SELF_CHECK
17409 assert(success != DUPLICATEPOINT);
17410 #endif
17411 if (success == OUTSIDEPOINT) {
17412 inserthullsite(sympoint, &splittet, flipqueue);
17413 }
17414 if (steinerleft > 0) steinerleft--;
17415 // Let sympoint remember splittet.
17416 setpoint2tet(sympoint, encode(splittet));
17417 // Do flip in DT.
17418 flip(flipqueue, NULL);
17419 // Insert sympoint into F.
17420 symloc = locateseg(sympoint, &symsplitseg);
17421 if (symloc == ONEDGE) {
17422 symsplitseg.shver = 0;
17423 spivot(symsplitseg, symsplitsub);
17424 // sympoint should on the edge of symsplitsub.
17425 splitsubedge(sympoint, &symsplitsub, flipqueue);
17426 } else {
17427 // insertsite() has done the whole job.
17428 #ifdef SELF_CHECK
17429 assert(symloc == ONVERTEX);
17430 assert(checksubfaces);
17431 #endif
17432 // Some edges may need to be flipped.
17433 collectflipedges(sympoint, &symsplitseg, flipqueue);
17434 }
17435 // Do flip in facet.
17436 flipsub(flipqueue);
17437 } else { // if (symloc == ONVERTEX) {
17438 // The symmtric point already exists. It is possible when two
17439 // pbc group are idebtical. Omit sympoint.
17440 pointdealloc(sympoint);
17441 }
17442 }
17443 }
17444
17445 // Insert newpoint into DT.
17446 splittet.tet = dummytet;
17447 // Find a good start point to search.
17448 encodedtet = point2tet(pa);
17449 if (encodedtet != (tetrahedron) NULL) {
17450 decode(encodedtet, splittet);
17451 if (isdead(&splittet)) {
17452 splittet.tet = dummytet;
17453 }
17454 }
17455 if (splittet.tet == dummytet) { // Try pb.
17456 encodedtet = point2tet(pb);
17457 if (encodedtet != (tetrahedron) NULL) {
17458 decode(encodedtet, splittet);
17459 if (isdead(&splittet)) {
17460 splittet.tet = dummytet;
17461 }
17462 }
17463 }
17464 // Locate the newpoint in DT. Do exact location.
17465 success = insertsite(newpoint, &splittet, false, flipqueue);
17466 #ifdef SELF_CHECK
17467 assert(success != DUPLICATEPOINT);
17468 #endif
17469 if (success == OUTSIDEPOINT) {
17470 // A convex hull edge is mssing, and the inserting point lies
17471 // (slightly) outside the convex hull due to the significant
17472 // digits lost in the calculation. Enlarge the convex hull.
17473 inserthullsite(newpoint, &splittet, flipqueue);
17474 }
17475 if (steinerleft > 0) steinerleft--;
17476 // Let newpoint remember splittet.
17477 setpoint2tet(newpoint, encode(splittet));
17478 // Do flip in DT.
17479 flip(flipqueue, NULL);
17480 // Insert newpoint into F.
17481 loc = locateseg(newpoint, &splitseg);
17482 if (loc == ONEDGE) {
17483 splitseg.shver = 0;
17484 spivot(splitseg, splitsub);
17485 // newpoint should on the edge of splitsub.
17486 splitsubedge(newpoint, &splitsub, flipqueue);
17487 } else {
17488 // insertsite() has done the whole job.
17489 #ifdef SELF_CHECK
17490 assert(loc == ONVERTEX);
17491 assert(checksubfaces);
17492 #endif
17493 // Some edges may need to be flipped.
17494 collectflipedges(newpoint, &splitseg, flipqueue);
17495 }
17496 // Do flip in facet.
17497 flipsub(flipqueue);
17498 }
17499 // Remove this entry from list.
17500 badfacedealloc(badsubsegs, encloop);
17501 // Get the next encroached segments.
17502 encloop = badfacetraverse(badsubsegs);
17503 }
17504 }
17505
17506 ///////////////////////////////////////////////////////////////////////////////
17507 // //
17508 // perturbrepairencsubs() Repair all encroached subfaces. //
17509 // //
17510 // All encroached subfaces are stored in 'badsubfaces'. Each subface will be //
17511 // split by adding a perturbed point near its circumcenter. However, if the //
17512 // point encroaches some segments, it will not be inserted. Instead, the //
17513 // encroached segments are split. //
17514 // //
17515 ///////////////////////////////////////////////////////////////////////////////
17516
17517 void tetgenmesh::perturbrepairencsubs(list* cavsublist, queue* flipqueue)
17518 {
17519 badface *encloop, *encsubseg;
17520 tetrahedron encodedtet;
17521 triface splittet;
17522 face splitsub, symsplitsub;
17523 face checkseg, symsplitseg;
17524 point newpoint, sympoint;
17525 point pa, pb, pc, pd;
17526 enum insertsiteresult success;
17527 enum locateresult loc, symloc;
17528 REAL cent[3], d1, ps, rs;
17529 bool reject;
17530 int i;
17531
17532 // Note that steinerleft == -1 if an unlimited number of Steiner points
17533 // is allowed. Loop until the list 'badsubfaces' is empty.
17534 while ((badsubfaces->items > 0) && (steinerleft != 0)) {
17535 badsubfaces->traversalinit();
17536 encloop = badfacetraverse(badsubfaces);
17537 while ((encloop != (badface *) NULL) && (steinerleft != 0)) {
17538 splitsub = encloop->ss;
17539 #ifdef SELF_CHECK
17540 assert(shell2badface(splitsub) == encloop);
17541 #endif
17542 setshell2badface(splitsub, NULL);
17543 pa = sorg(splitsub);
17544 pb = sdest(splitsub);
17545 pc = sapex(splitsub);
17546 // The subface may be not the same one when it was determined to be
17547 // encroached. If its adjacent encroached subface was split, the
17548 // consequent flips may change it into another subface.
17549 if ((pa == encloop->forg) && (pb == encloop->fdest) &&
17550 (pc == encloop->fapex)) {
17551 if (b->verbose > 1) {
17552 printf(" Get subface (%d, %d, %d).\n", pointmark(pa),
17553 pointmark(pb), pointmark(pc));
17554 }
17555 // Create the newpoint.
17556 makepoint(&newpoint);
17557 // Get the circumcenter of abc.
17558 circumsphere(pa, pb, pc, NULL, cent, &d1);
17559 #ifdef SELF_CHECK
17560 assert(d1 > 0.0);
17561 #endif
17562 // Add a random perturbation to newpoint along the vector a->cent.
17563 // This way, the perturbed point still lies in the plane of abc.
17564 ps = randgenerator(d1 * 1.0e-3);
17565 rs = ps / d1;
17566 // Set newpoint (be at the perturbed circumcenter of abc).
17567 for (i = 0; i < 3; i++) newpoint[i] = cent[i] + rs * (cent[i] - pa[i]);
17568 // Get the abovepoint of the facet.
17569 abovepoint = facetabovepointarray[shellmark(splitsub)];
17570 // Do we need to calculate the abovepoint?
17571 if (abovepoint == (point) NULL) {
17572 getfacetabovepoint(&splitsub);
17573 }
17574 loc = locatesub(newpoint, &splitsub, 1, 0.0);
17575 #ifdef SELF_CHECK
17576 assert(loc != ONVERTEX);
17577 #endif
17578 if (loc != OUTSIDE) {
17579 // Add 'splitsub' into 'cavsublist'.
17580 cavsublist->append(&splitsub);
17581 // Collect all subfaces that encroached by newpoint.
17582 collectcavsubs(newpoint, cavsublist);
17583 // Find if there are encroached segments.
17584 reject = tallencsegsfsubs(newpoint, cavsublist);
17585 // Clear cavsublist for the next use.
17586 cavsublist->clear();
17587 } else {
17588 // newpoint lies outside. splitsub contains the boundary segment.
17589 sspivot(splitsub, checkseg);
17590 #ifdef SELF_CHECK
17591 assert(checkseg.sh != dummysh);
17592 #endif
17593 // Add this segment into list for splitting.
17594 if (b->verbose > 2) {
17595 printf(" Queuing boundary segment (%d, %d).\n",
17596 pointmark(sorg(checkseg)), pointmark(sdest(checkseg)));
17597 }
17598 encsubseg = (badface *) badsubsegs->alloc();
17599 encsubseg->ss = checkseg;
17600 encsubseg->forg = sorg(checkseg);
17601 encsubseg->fdest = sdest(checkseg);
17602 encsubseg->foppo = (point) NULL;
17603 setshell2badface(encsubseg->ss, encsubseg);
17604 // Reject newpoint.
17605 reject = true;
17606 }
17607
17608 if (!reject) {
17609 // newpoint is going to be inserted.
17610
17611 // Is there periodic boundary condition?
17612 if (checkpbcs) {
17613 if (shellpbcgroup(splitsub) >= 0) {
17614 // Insert a point on another facet of the pbcgroup.
17615 makepoint(&sympoint);
17616 // Note: 'abovepoint' will be changed.
17617 symloc = getsubpbcsympoint(newpoint, &splitsub, sympoint,
17618 &symsplitsub);
17619 #ifdef SELF_CHECK
17620 assert(symloc != ONVERTEX);
17621 #endif
17622 setpoint2pbcpt(newpoint, sympoint);
17623 setpoint2pbcpt(sympoint, newpoint);
17624 setpointtype(sympoint, FREESUBVERTEX);
17625 // setpoint2sh(sympoint, sencode(symsplitsub));
17626 // Insert sympoint into DT.
17627 pd = sorg(symsplitsub);
17628 splittet.tet = dummytet;
17629 // Find a good start point to search.
17630 encodedtet = point2tet(pd);
17631 if (encodedtet != (tetrahedron) NULL) {
17632 decode(encodedtet, splittet);
17633 if (isdead(&splittet)) {
17634 splittet.tet = dummytet;
17635 }
17636 }
17637 // Locate sympoint in DT. Do exact location.
17638 success = insertsite(sympoint, &splittet, false, flipqueue);
17639 #ifdef SELF_CHECK
17640 assert(success != DUPLICATEPOINT);
17641 #endif
17642 if (success == OUTSIDEPOINT) {
17643 inserthullsite(sympoint, &splittet, flipqueue);
17644 }
17645 if (steinerleft > 0) steinerleft--;
17646 // Let sympoint remember splittet.
17647 setpoint2tet(sympoint, encode(splittet));
17648 // Do flip in DT.
17649 flip(flipqueue, NULL);
17650 // Insert sympoint into F.
17651 // getabovepoint(&symsplitsub);
17652 // symloc = locatesub(sympoint, &symsplitsub, 1, 0.0);
17653 if (symloc == ONFACE) {
17654 splitsubface(sympoint, &symsplitsub, flipqueue);
17655 } else if (symloc == ONEDGE) {
17656 splitsubedge(sympoint, &symsplitsub, flipqueue);
17657 } else {
17658 // 'insertsite()' has done the whole job.
17659 #ifdef SELF_CHECK
17660 assert(symloc == ONVERTEX);
17661 assert(checksubfaces);
17662 #endif
17663 // Split subfaces have been flipped.
17664 flipqueue->clear();
17665 }
17666 // Do flip in facet.
17667 flipsub(flipqueue);
17668 }
17669 }
17670
17671 // Insert newpoint into DT.
17672 splittet.tet = dummytet;
17673 // Find a good start point to search.
17674 encodedtet = point2tet(pa);
17675 if (encodedtet != (tetrahedron) NULL) {
17676 decode(encodedtet, splittet);
17677 if (isdead(&splittet)) {
17678 splittet.tet = dummytet;
17679 }
17680 }
17681 if (splittet.tet == dummytet) { // Try pb.
17682 encodedtet = point2tet(pb);
17683 if (encodedtet != (tetrahedron) NULL) {
17684 decode(encodedtet, splittet);
17685 if (isdead(&splittet)) {
17686 splittet.tet = dummytet;
17687 }
17688 }
17689 }
17690 // Locate the newpoint in DT. Do exact location.
17691 success = insertsite(newpoint, &splittet, false, flipqueue);
17692 #ifdef SELF_CHECK
17693 assert(success != DUPLICATEPOINT);
17694 #endif
17695 if (success == OUTSIDEPOINT) {
17696 inserthullsite(newpoint, &splittet, flipqueue);
17697 }
17698 if (steinerleft > 0) steinerleft--;
17699 // Let newpoint remember splittet.
17700 setpoint2tet(newpoint, encode(splittet));
17701 // Do flip in DT.
17702 flip(flipqueue, NULL);
17703 // Insert newpoint into F.
17704 // if (checkpbcs) {
17705 // 'abovepoint' has been changed.
17706 // getabovepoint(&splitsub);
17707 // loc = locatesub(newpoint, &splitsub, 1, 0.0);
17708 // }
17709 if (loc == ONFACE) {
17710 // Insert the newpoint in facet.
17711 splitsubface(newpoint, &splitsub, flipqueue);
17712 } else if (loc == ONEDGE) {
17713 // Insert the newpoint in facet.
17714 splitsubedge(newpoint, &splitsub, flipqueue);
17715 } else {
17716 // 'insertsite()' has done the whole job.
17717 #ifdef SELF_CHECK
17718 assert(loc == ONVERTEX);
17719 assert(checksubfaces);
17720 #endif
17721 // Split subfaces have been flipped.
17722 flipqueue->clear();
17723 }
17724 // Set the type of the newpoint.
17725 setpointtype(newpoint, FREESUBVERTEX);
17726 // Set splitsub into the newpoint.
17727 // setpoint2sh(newpoint, sencode(splitsub));
17728 // Do flip in the facet.
17729 flipsub(flipqueue);
17730
17731 // Remove this entry from list.
17732 badfacedealloc(badsubfaces, encloop);
17733 } else {
17734 // newpoint is rejected. Remove it from points.
17735 pointdealloc(newpoint);
17736 // Repair all encroached segments.
17737 perturbrepairencsegs(flipqueue);
17738 // Do not remove 'encloop'. Later it will be tested again.
17739 setshell2badface(encloop->ss, encloop);
17740 }
17741 } else {
17742 // This subface has been changed. Remove this entry from list.
17743 badfacedealloc(badsubfaces, encloop);
17744 // It may be co-circular with its neighbors.
17745 // checksub4cocir(&splitsub, eps, false, true);
17746 }
17747 // Get the next encroached subfaces.
17748 encloop = badfacetraverse(badsubfaces);
17749 }
17750 }
17751 }
17752
17753 ///////////////////////////////////////////////////////////////////////////////
17754 // //
17755 // incrperturbvertices() Remove the local degeneracies in DT. //
17756 // //
17757 // A local degeneracy of a DT D is a set of 5 or more vertices which share a //
17758 // common sphere S and no other vertex of D in S. D is not unique if it has //
17759 // local degeneracies. This routine removes the local degeneracies from D by //
17760 // inserting break points (as described in reference [2]). //
17761 // //
17762 // 'eps' is a user-provided error tolerance. It is used to detect whether or //
17763 // not five points are approximate cospherical (evaluated in iscospheric()). //
17764 // Set it to 0.0 to disable it, i.e., only test pure degenerate point set. //
17765 // //
17766 ///////////////////////////////////////////////////////////////////////////////
17767
17768 void tetgenmesh::incrperturbvertices(REAL eps)
17769 {
17770 queue *flipqueue;
17771 list *cavsublist;
17772 long vertcount;
17773
17774 if (!b->quiet) {
17775 printf("Perturbing vertices.\n");
17776 }
17777
17778 vertcount = points->items;
17779 // Create a map from points to tets for fastening search.
17780 // makepoint2tetmap(); // This has been done in meshsurface().
17781
17782 // Initialize working queues, lists.
17783 flipqueue = new queue(sizeof(badface));
17784 cavsublist = new list(sizeof(face), NULL, 256);
17785 // Initialize the pool of encroached subfaces and subsegments.
17786 badsubsegs = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
17787 badsubfaces = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
17788 // Find all pairs of co-circular subfaces.
17789 tallcocirsubs(eps, true);
17790 if (b->verbose && badsubfaces->items > 0) {
17791 printf(" Removing degenerate subfaces.\n");
17792 }
17793 perturbrepairencsubs(cavsublist, flipqueue);
17794
17795 if (b->verbose > 0) {
17796 printf(" %ld break points.\n", points->items - vertcount);
17797 }
17798
17799 delete cavsublist;
17800 delete flipqueue;
17801 delete badsubfaces;
17802 delete badsubsegs;
17803 badsubsegs = (memorypool *) NULL;
17804 badsubfaces = (memorypool *) NULL;
17805 }
17806
17807 //
17808 // End of vertex perturbation routines
17809 //
17810
17811 //
17812 // Begin of segment recovery routines
17813 //
17814
17815 ///////////////////////////////////////////////////////////////////////////////
17816 // //
17817 // markacutevertices() Mark each vertex to be ACUTE or NACUTE. //
17818 // //
17819 // A vertex is acute if at least two segments incident at it with an angle //
17820 // smaller than a given angle bound (e.g. 90 degree). //
17821 // //
17822 ///////////////////////////////////////////////////////////////////////////////
17823
17824 void tetgenmesh::markacutevertices(REAL acuteangle)
17825 {
17826 shellface **segsperverlist;
17827 face segloop, workseg, inciseg;
17828 point eorg, edest, eapex;
17829 REAL cosbound, anglearc;
17830 REAL v1[3], v2[3], L, D;
17831 bool isacute;
17832 int *idx2seglist;
17833 int idx, i, j, k;
17834
17835 if (b->verbose > 0) {
17836 printf(" Marking segments have acute corners.\n");
17837 }
17838
17839 anglearc = acuteangle * PI / 180.0;
17840 cosbound = cos(anglearc);
17841 // Constructing a map from vertex to segments.
17842 makesegmentmap(idx2seglist, segsperverlist);
17843
17844 // Loop over the set of subsegments.
17845 subsegs->traversalinit();
17846 segloop.sh = shellfacetraverse(subsegs);
17847 while (segloop.sh != (shellface *) NULL) {
17848 // Check and set types for the two ends of this segment.
17849 for (segloop.shver = 0; segloop.shver < 2; segloop.shver++) {
17850 eorg = sorg(segloop);
17851 if ((pointtype(eorg) != ACUTEVERTEX) &&
17852 (pointtype(eorg) != NACUTEVERTEX) &&
17853 (pointtype(eorg) != FREESEGVERTEX)) {
17854 // This vertex has no type be set yet.
17855 idx = pointmark(eorg) - in->firstnumber;
17856 isacute = false;
17857 for (i = idx2seglist[idx]; i < idx2seglist[idx + 1] && !isacute; i++) {
17858 workseg.sh = segsperverlist[i];
17859 workseg.shver = 0;
17860 if (sorg(workseg) != eorg) sesymself(workseg);
17861 #ifdef SELF_CHECK
17862 assert(sorg(workseg) == eorg);
17863 #endif
17864 edest = sdest(workseg);
17865 for (j = i + 1; j < idx2seglist[idx + 1] && !isacute; j++) {
17866 inciseg.sh = segsperverlist[j];
17867 inciseg.shver = 0;
17868 #ifdef SELF_CHECK
17869 assert(inciseg.sh != workseg.sh);
17870 #endif
17871 if (sorg(inciseg) != eorg) sesymself(inciseg);
17872 #ifdef SELF_CHECK
17873 assert(sorg(inciseg) == eorg);
17874 #endif
17875 eapex = sdest(inciseg);
17876 // Check angles between segs (eorg, edest) and (eorg, eapex).
17877 for (k = 0; k < 3; k++) {
17878 v1[k] = edest[k] - eorg[k];
17879 v2[k] = eapex[k] - eorg[k];
17880 }
17881 L = sqrt(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2]);
17882 for (k = 0; k < 3; k++) v1[k] /= L;
17883 L = sqrt(v2[0] * v2[0] + v2[1] * v2[1] + v2[2] * v2[2]);
17884 for (k = 0; k < 3; k++) v2[k] /= L;
17885 D = v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
17886 if (D >= cosbound) {
17887 isacute = true;
17888 }
17889 }
17890 }
17891 if (isacute) {
17892 setpointtype(eorg, ACUTEVERTEX);
17893 } else {
17894 setpointtype(eorg, NACUTEVERTEX);
17895 }
17896 }
17897 }
17898 segloop.sh = shellfacetraverse(subsegs);
17899 }
17900
17901 delete [] idx2seglist;
17902 delete [] segsperverlist;
17903 }
17904
17905 ///////////////////////////////////////////////////////////////////////////////
17906 // //
17907 // finddirection() Find the first tetrahedron on the path from one point //
17908 // to another. //
17909 // //
17910 // Find the tetrahedron that intersects a line segment L (from the origin of //
17911 // 'searchtet' to the point 'tend'), and returns the result in 'searchtet'. //
17912 // The origin of 'searchtet' does not change, even though the tetrahedron //
17913 // returned may differ from the one passed in. This routine is used to find //
17914 // the direction to move in to get from one point to another. //
17915 // //
17916 // The return value notes the location of the line segment L with respect to //
17917 // 'searchtet': //
17918 // - Returns RIGHTCOLLINEAR indicates L is collinear with the line segment //
17919 // from the origin to the destination of 'searchtet'. //
17920 // - Returns LEFTCOLLINEAR indicates L is collinear with the line segment //
17921 // from the origin to the apex of 'searchtet'. //
17922 // - Returns TOPCOLLINEAR indicates L is collinear with the line segment //
17923 // from the origin to the opposite of 'searchtet'. //
17924 // - Returns ACROSSEDGE indicates L intersects with the line segment from //
17925 // the destination to the apex of 'searchtet'. //
17926 // - Returns ACROSSFACE indicates L intersects with the face opposite to //
17927 // the origin of 'searchtet'. //
17928 // - Returns BELOWHULL indicates L crosses outside the mesh domain. This //
17929 // can only happen when the domain is non-convex. //
17930 // //
17931 // NOTE: This routine only works correctly when the mesh is exactly Delaunay.//
17932 // //
17933 // If 'maxtetnumber' > 0, stop the searching process if the number of passed //
17934 // tets is larger than it. Return BELOWHULL. //
17935 // //
17936 ///////////////////////////////////////////////////////////////////////////////
17937
17938 enum tetgenmesh::finddirectionresult tetgenmesh::
17939 finddirection(triface *searchtet, point tend, long maxtetnumber)
17940 {
17941 triface neightet;
17942 point tstart, tdest, tapex, toppo;
17943 REAL ori1, ori2, ori3;
17944 long tetnumber;
17945
17946 tstart = org(*searchtet);
17947 #ifdef SELF_CHECK
17948 assert(tstart != tend);
17949 #endif
17950 adjustedgering(*searchtet, CCW);
17951 if (tstart != org(*searchtet)) {
17952 enextself(*searchtet); // For keeping the same origin.
17953 }
17954 tdest = dest(*searchtet);
17955 if (tdest == tend) {
17956 return RIGHTCOLLINEAR;
17957 }
17958 tapex = apex(*searchtet);
17959 if (tapex == tend) {
17960 return LEFTCOLLINEAR;
17961 }
17962
17963 ori1 = orient3d(tstart, tdest, tapex, tend);
17964 if (ori1 > 0.0) {
17965 // 'tend' is below the face, get the neighbor of this side.
17966 sym(*searchtet, neightet);
17967 if (neightet.tet != dummytet) {
17968 findorg(&neightet, tstart);
17969 adjustedgering(neightet, CCW);
17970 if (org(neightet) != tstart) {
17971 enextself(neightet); // keep the same origin.
17972 }
17973 // Set the changed configuratiuon.
17974 *searchtet = neightet;
17975 ori1 = -1.0;
17976 tdest = dest(*searchtet);
17977 tapex = apex(*searchtet);
17978 } else {
17979 // A hull face. Only possible for a nonconvex mesh.
17980 #ifdef SELF_CHECK
17981 assert(nonconvex);
17982 #endif
17983 return BELOWHULL;
17984 }
17985 }
17986
17987 // Repeatedly change the 'searchtet', remain 'tstart' be its origin, until
17988 // find a tetrahedron contains 'tend' or is crossed by the line segment
17989 // from 'tstart' to 'tend'.
17990 tetnumber = 0l;
17991 while ((maxtetnumber > 0) && (tetnumber <= maxtetnumber)) {
17992 tetnumber++;
17993 toppo = oppo(*searchtet);
17994 if (toppo == tend) {
17995 return TOPCOLLINEAR;
17996 }
17997 ori2 = orient3d(tstart, toppo, tdest, tend);
17998 if (ori2 > 0.0) {
17999 // 'tend' is below the face, get the neighbor at this side.
18000 fnext(*searchtet, neightet);
18001 symself(neightet);
18002 if (neightet.tet != dummytet) {
18003 findorg(&neightet, tstart);
18004 adjustedgering(neightet, CCW);
18005 if (org(neightet) != tstart) {
18006 enextself(neightet); // keep the same origin.
18007 }
18008 // Set the changed configuration.
18009 *searchtet = neightet;
18010 ori1 = -1.0;
18011 tdest = dest(*searchtet);
18012 tapex = apex(*searchtet);
18013 // Continue the search from the changed 'searchtet'.
18014 continue;
18015 } else {
18016 // A hull face. Only possible for a nonconvex mesh.
18017 #ifdef SELF_CHECK
18018 assert(nonconvex);
18019 #endif
18020 return BELOWHULL;
18021 }
18022 }
18023 ori3 = orient3d(tapex, toppo, tstart, tend);
18024 if (ori3 > 0.0) {
18025 // 'tend' is below the face, get the neighbor at this side.
18026 enext2fnext(*searchtet, neightet);
18027 symself(neightet);
18028 if (neightet.tet != dummytet) {
18029 findorg(&neightet, tstart);
18030 adjustedgering(neightet, CCW);
18031 if (org(neightet) != tstart) {
18032 enextself(neightet); // keep the same origin.
18033 }
18034 // Set the changed configuration.
18035 *searchtet = neightet;
18036 ori1 = -1.0;
18037 tdest = dest(*searchtet);
18038 tapex = apex(*searchtet);
18039 // Continue the search from the changed 'searchtet'.
18040 continue;
18041 } else {
18042 // A hull face. Only possible for a nonconvex mesh.
18043 #ifdef SELF_CHECK
18044 assert(nonconvex);
18045 #endif
18046 return BELOWHULL;
18047 }
18048 }
18049 // Now 'ori1', 'ori2' and 'ori3' are possible be 0.0 or all < 0.0;
18050 if (ori1 < 0.0) {
18051 // Possible cases are: ACROSSFACE, ACROSSEDGE, TOPCOLLINEAR.
18052 if (ori2 < 0.0) {
18053 if (ori3 < 0.0) {
18054 return ACROSSFACE;
18055 } else { // ori3 == 0.0;
18056 // Cross edge (apex, oppo)
18057 enext2fnextself(*searchtet);
18058 esymself(*searchtet); // org(*searchtet) == tstart;
18059 return ACROSSEDGE;
18060 }
18061 } else { // ori2 == 0.0;
18062 if (ori3 < 0.0) {
18063 // Cross edge (dest, oppo)
18064 fnextself(*searchtet);
18065 esymself(*searchtet);
18066 enextself(*searchtet); // org(*searchtet) == tstart;
18067 return ACROSSEDGE;
18068 } else { // ori3 == 0.0;
18069 // Collinear with edge (org, oppo)
18070 return TOPCOLLINEAR;
18071 }
18072 }
18073 } else { // ori1 == 0.0;
18074 // Possible cases are: RIGHTCOLLINEAR, LEFTCOLLINEAR, ACROSSEDGE.
18075 if (ori2 < 0.0) {
18076 if (ori3 < 0.0) {
18077 // Cross edge (tdest, tapex)
18078 return ACROSSEDGE;
18079 } else { // ori3 == 0.0
18080 // Collinear with edge (torg, tapex)
18081 return LEFTCOLLINEAR;
18082 }
18083 } else { // ori2 == 0.0;
18084 #ifdef SELF_CHECK
18085 assert(ori3 != 0.0);
18086 #endif
18087 // Collinear with edge (torg, tdest)
18088 return RIGHTCOLLINEAR;
18089 }
18090 }
18091 }
18092 // Loop breakout. It may happen when the mesh is non-Delaunay.
18093 return BELOWHULL;
18094 }
18095
18096 ///////////////////////////////////////////////////////////////////////////////
18097 // //
18098 // getsearchtet() Find a tetrahedron whose origin is either 'p1' or 'p2'. //
18099 // //
18100 // On return, the origin of 'searchtet' is either 'p1' or 'p2', and 'tend' //
18101 // returns the other point. 'searchtet' serves as the starting tetrahedron //
18102 // for searching of the line segment from 'p1' to 'p2' or vice versa. //
18103 // //
18104 ///////////////////////////////////////////////////////////////////////////////
18105
18106 void tetgenmesh::getsearchtet(point p1, point p2, triface* searchtet,
18107 point* tend)
18108 {
18109 tetrahedron encodedtet1, encodedtet2;
18110
18111 // Is there a valid handle provided by the user?
18112 if ((searchtet->tet != (tetrahedron *) NULL) && !isdead(searchtet)) {
18113 // Find which endpoint the handle holds.
18114 if (findorg(searchtet, p1)) {
18115 *tend = p2;
18116 return;
18117 } else {
18118 if (findorg(searchtet, p2)) {
18119 *tend = p1;
18120 return;
18121 }
18122 }
18123 }
18124 // If not, search the tet handle stored in 'p1' or 'p2'.
18125 *tend = (point) NULL;
18126 encodedtet1 = point2tet(p1);
18127 encodedtet2 = point2tet(p2);
18128 if (encodedtet1 != (tetrahedron) NULL) {
18129 decode(encodedtet1, *searchtet);
18130 // Be careful, here 'searchtet' may be dead.
18131 if (findorg(searchtet, p1)) {
18132 *tend = p2;
18133 }
18134 } else if (encodedtet2 != (tetrahedron) NULL) {
18135 decode(encodedtet2, *searchtet);
18136 // Be careful, here 'searchtet' may be dead.
18137 if (findorg(searchtet, p2)) {
18138 *tend = p1;
18139 }
18140 }
18141 // If still not, perform a full point location. The starting tet is
18142 // chosen as follows: Use the handle stored in 'p1' or 'p2' if it is
18143 // alive; otherwise, start from a tet on the convex hull.
18144 if (*tend == (point) NULL) {
18145 if (encodedtet1 != (tetrahedron) NULL) {
18146 decode(encodedtet1, *searchtet);
18147 // Be careful, here 'searchtet' may be dead.
18148 }
18149 if (isdead(searchtet)) {
18150 if (encodedtet2 != (tetrahedron) NULL) {
18151 decode(encodedtet2, *searchtet);
18152 // Be careful, here 'searchtet' may be dead.
18153 }
18154 if (isdead(searchtet)) {
18155 searchtet->tet = dummytet;
18156 searchtet->loc = 0;
18157 symself(*searchtet);
18158 }
18159 #ifdef SELF_CHECK
18160 assert(!isdead(searchtet));
18161 #endif
18162 }
18163 if (locate(p1, searchtet) != ONVERTEX) {
18164 printf("Internal error in getsearchtet(): Failed to locate point\n");
18165 internalerror();
18166 }
18167 // Remember this handle in 'p1' to enhance the search speed.
18168 setpoint2tet(p1, encode(*searchtet));
18169 *tend = p2;
18170 }
18171 }
18172
18173 ///////////////////////////////////////////////////////////////////////////////
18174 // //
18175 // isedgeencroached() Check whether or not a subsegment is encroached. //
18176 // //
18177 // A segment with endpoints 'p1' and 'p2' is encroached by the point 'testpt'//
18178 // if it lies in the diametral sphere of this segment. The degenerate case //
18179 // that 'testpt' lies on the sphere is treated as encroached if 'degflag' is //
18180 // set to be TRUE. //
18181 // //
18182 ///////////////////////////////////////////////////////////////////////////////
18183
18184 bool tetgenmesh::isedgeencroached(point p1, point p2, point testpt,
18185 bool degflag)
18186 {
18187 REAL dotproduct;
18188
18189 // Check if the segment is facing an angle larger than 90 degree?
18190 dotproduct = (p1[0] - testpt[0]) * (p2[0] - testpt[0])
18191 + (p1[1] - testpt[1]) * (p2[1] - testpt[1])
18192 + (p1[2] - testpt[2]) * (p2[2] - testpt[2]);
18193 if (dotproduct < 0) {
18194 return true;
18195 } else if (dotproduct == 0 && degflag) {
18196 return true;
18197 } else {
18198 return false;
18199 }
18200 }
18201
18202 ///////////////////////////////////////////////////////////////////////////////
18203 // //
18204 // scoutrefpoint() Search the reference point of a missing segment. //
18205 // //
18206 // A segment S is missing in current Delaunay tetrahedralization DT and will //
18207 // be split by inserting a point V in it. The two end points of S are the //
18208 // origin of 'searchtet' and 'tend'. And we know that S is crossing the face //
18209 // of 'searchtet' opposite to its origin (may be intersecting with the edge //
18210 // from the destination to the apex of the 'searchtet'). The search of P is //
18211 // completed by walking through all faces of DT across by S. //
18212 // //
18213 // Warning: This routine is correct when the tetrahedralization is Delaunay //
18214 // and convex. Otherwise, the search loop may not terminate. //
18215 // //
18216 ///////////////////////////////////////////////////////////////////////////////
18217
18218 tetgenmesh::point tetgenmesh::scoutrefpoint(triface* searchtet, point tend)
18219 {
18220 triface checkface;
18221 point tstart, testpt, refpoint;
18222 REAL cent[3], radius, largest;
18223 REAL ahead;
18224 bool ncollinear;
18225 int sides;
18226
18227 if (b->verbose > 2) {
18228 printf(" Scout the reference point of segment (%d, %d).\n",
18229 pointmark(org(*searchtet)), pointmark(tend));
18230 }
18231
18232 tstart = org(*searchtet);
18233 refpoint = (point) NULL;
18234 largest = 0; // avoid compile warning.
18235
18236 // Check the three vertices of the crossing face.
18237 testpt = apex(*searchtet);
18238 if (isedgeencroached(tstart, tend, testpt, true)) {
18239 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18240 #ifdef SELF_CHECK
18241 assert(ncollinear);
18242 #endif
18243 refpoint = testpt;
18244 largest = radius;
18245 }
18246 testpt = dest(*searchtet);
18247 if (isedgeencroached(tstart, tend, testpt, true)) {
18248 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18249 #ifdef SELF_CHECK
18250 assert(ncollinear);
18251 #endif
18252 if (refpoint == (point) NULL) {
18253 refpoint = testpt;
18254 largest = radius;
18255 } else {
18256 if (radius > largest) {
18257 refpoint = testpt;
18258 largest = radius;
18259 }
18260 }
18261 }
18262 testpt = oppo(*searchtet);
18263 if (isedgeencroached(tstart, tend, testpt, true)) {
18264 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18265 #ifdef SELF_CHECK
18266 assert(ncollinear);
18267 #endif
18268 if (refpoint == (point) NULL) {
18269 refpoint = testpt;
18270 largest = radius;
18271 } else {
18272 if (radius > largest) {
18273 refpoint = testpt;
18274 largest = radius;
18275 }
18276 }
18277 }
18278 // Check the opposite vertex of the neighboring tet in case the segment
18279 // crosses the edge (leftpoint, rightpoint) of the crossing face.
18280 sym(*searchtet, checkface);
18281 if (checkface.tet != dummytet) {
18282 testpt = oppo(checkface);
18283 if (isedgeencroached(tstart, tend, testpt, true)) {
18284 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18285 #ifdef SELF_CHECK
18286 assert(ncollinear);
18287 #endif
18288 if (refpoint == (point) NULL) {
18289 refpoint = testpt;
18290 largest = radius;
18291 } else {
18292 if (radius > largest) {
18293 refpoint = testpt;
18294 largest = radius;
18295 }
18296 }
18297 }
18298 }
18299
18300 // Walk through all crossing faces.
18301 enextfnext(*searchtet, checkface);
18302 sym(checkface, *searchtet);
18303 while (true) {
18304 // Check if we are reaching the boundary of the triangulation.
18305 #ifdef SELF_CHECK
18306 assert(searchtet->tet != dummytet);
18307 #endif
18308 // Search for an adjoining tetrahedron we can walk through.
18309 searchtet->ver = 0;
18310 // 'testpt' is the shared vertex for the following orientation tests.
18311 testpt = oppo(*searchtet);
18312 if (testpt == tend) {
18313 // The searching is finished.
18314 break;
18315 } else {
18316 // 'testpt' may encroach the segment.
18317 if ((testpt != tstart) && (testpt != refpoint)) {
18318 if (isedgeencroached(tstart, tend, testpt, true)) {
18319 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18320 if (!ncollinear) {
18321 // 'testpt' is collinear with the segment. It may happen when a
18322 // set of collinear and continuous segments is defined by two
18323 // extreme endpoints. In this case, we should choose 'testpt'
18324 // as the splitting point immediately. No new point should be
18325 // created.
18326 refpoint = testpt;
18327 break;
18328 }
18329 if (refpoint == (point) NULL) {
18330 refpoint = testpt;
18331 largest = radius;
18332 } else {
18333 if (radius > largest) {
18334 refpoint = testpt;
18335 largest = radius;
18336 }
18337 }
18338 }
18339 }
18340 }
18341 // Check three side-faces of 'searchtet' to find the one through
18342 // which we can walk next.
18343 for (sides = 0; sides < 3; sides++) {
18344 fnext(*searchtet, checkface);
18345 ahead = orient3d(org(checkface), dest(checkface), testpt, tend);
18346 if (ahead < 0.0) {
18347 // We can walk through this face and continue the searching.
18348 sym(checkface, *searchtet);
18349 break;
18350 }
18351 enextself(*searchtet);
18352 }
18353 #ifdef SELF_CHECK
18354 assert (sides < 3);
18355 #endif
18356 }
18357
18358 #ifdef SELF_CHECK
18359 assert(refpoint != (point) NULL);
18360 #endif
18361 return refpoint;
18362 }
18363
18364 ///////////////////////////////////////////////////////////////////////////////
18365 // //
18366 // getsegmentorigin() Return the origin of the (unsplit) segment. //
18367 // //
18368 // After a segment (or a subsegment) is split. Two resulting subsegments are //
18369 // connecting each other through the pointers saved in their data fields. //
18370 // With these pointers, the whole (unsplit) segment can be found. 'splitseg' //
18371 // may be a split subsegment. Returns the origin of the unsplit segment. //
18372 // //
18373 ///////////////////////////////////////////////////////////////////////////////
18374
18375 tetgenmesh::point tetgenmesh::getsegmentorigin(face* splitseg)
18376 {
18377 face workseg;
18378 point farorg;
18379
18380 farorg = sorg(*splitseg);
18381 if ((pointtype(farorg) != ACUTEVERTEX) &&
18382 (pointtype(farorg) != NACUTEVERTEX)) {
18383 workseg = *splitseg;
18384 do {
18385 senext2self(workseg);
18386 spivotself(workseg);
18387 if (workseg.sh != dummysh) {
18388 workseg.shver = 0; // It's a subsegment.
18389 if (sdest(workseg) != farorg) {
18390 sesymself(workseg);
18391 #ifdef SELF_CHECK
18392 assert(sdest(workseg) == farorg);
18393 #endif
18394 }
18395 farorg = sorg(workseg);
18396 if ((pointtype(farorg) == ACUTEVERTEX) ||
18397 (pointtype(farorg) == NACUTEVERTEX)) break;
18398 }
18399 } while (workseg.sh != dummysh);
18400 }
18401 #ifdef SELF_CHECK
18402 assert((pointtype(farorg) == ACUTEVERTEX) ||
18403 (pointtype(farorg) == NACUTEVERTEX));
18404 #endif
18405 return farorg;
18406 }
18407
18408 ///////////////////////////////////////////////////////////////////////////////
18409 // //
18410 // getsplitpoint() Get a point for splitting a segment. //
18411 // //
18412 // 'splitseg' is the segment will be split. 'refpoint' is a reference point //
18413 // for splitting this segment. Moreover, it should not collinear with the //
18414 // splitting segment. (The collinear case will be detected by iscollinear() //
18415 // before entering this routine.) The calculation of the splitting point is //
18416 // governed by three rules introduced in my paper. //
18417 // //
18418 // After the position is calculated, a new point is created at this location.//
18419 // The new point has one of the two pointtypes: FREESEGVERTEX indicating it //
18420 // is an inserting vertex on segment, and NACUTEVERTEX indicating it is an //
18421 // endpoint of a segment which original has type-3 now becomes type-2. //
18422 // //
18423 ///////////////////////////////////////////////////////////////////////////////
18424
18425 tetgenmesh::point tetgenmesh::getsplitpoint(face* splitseg, point refpoint)
18426 {
18427 point splitpoint;
18428 point farorg, fardest;
18429 point ei, ej, ek, c;
18430 REAL v[3], r, split;
18431 REAL d1, ps, rs;
18432 bool acuteorg, acutedest;
18433 int stype, rule;
18434 int i;
18435
18436 // First determine the type of the segment (type-1, type-2, or type-3).
18437 farorg = getsegmentorigin(splitseg);
18438 acuteorg = (pointtype(farorg) == ACUTEVERTEX);
18439 sesymself(*splitseg);
18440 fardest = getsegmentorigin(splitseg);
18441 acutedest = (pointtype(fardest) == ACUTEVERTEX);
18442 sesymself(*splitseg);
18443
18444 ek = (point) NULL; // avoid a compilation warning.
18445
18446 if (acuteorg) {
18447 if (acutedest) {
18448 stype = 3;
18449 } else {
18450 stype = 2;
18451 ek = farorg;
18452 }
18453 } else {
18454 if (acutedest) {
18455 stype = 2;
18456 // Adjust splitseg, so that its origin is acute.
18457 sesymself(*splitseg);
18458 ek = fardest;
18459 } else {
18460 stype = 1;
18461 }
18462 }
18463 ei = sorg(*splitseg);
18464 ej = sdest(*splitseg);
18465
18466 if (b->verbose > 1) {
18467 printf(" Splitting segment (%d, %d) type-%d with refpoint %d.\n",
18468 pointmark(ei), pointmark(ej), stype, pointmark(refpoint));
18469 }
18470
18471 if (stype == 1 || stype == 3) {
18472 // Use rule-1.
18473 REAL eij, eip, ejp;
18474 eij = distance(ei, ej);
18475 eip = distance(ei, refpoint);
18476 ejp = distance(ej, refpoint);
18477 if ((eip < ejp) && (eip < 0.5 * eij)) {
18478 c = ei;
18479 r = eip;
18480 } else if ((eip > ejp) && (ejp < 0.5 * eij)) {
18481 c = ej;
18482 ej = ei;
18483 r = ejp;
18484 } else {
18485 c = ei;
18486 r = 0.5 * eij;
18487 }
18488 split = r / eij;
18489 for (i = 0; i < 3; i++) {
18490 v[i] = c[i] + split * (ej[i] - c[i]);
18491 }
18492 rule = 1;
18493 } else {
18494 // Use rule-2 or rule-3.
18495 REAL eki, ekj, ekp, evj, evp, eiv;
18496 c = ek;
18497 eki = distance(ek, ei); // eki may equal zero.
18498 ekj = distance(ek, ej);
18499 ekp = distance(ek, refpoint);
18500 // Calculate v (the going to split position between ei, ej).
18501 r = ekp;
18502 // Check the validity of the position.
18503 if (!(eki < r && r < ekj)) {
18504 printf("Error: Invalid PLC.\n");
18505 printf(" Hint: Use -d switch to check it.\n");
18506 terminatetetgen(1);
18507 }
18508 split = r / ekj;
18509 for (i = 0; i < 3; i++) {
18510 v[i] = c[i] + split * (ej[i] - c[i]);
18511 }
18512 rule = 2;
18513 evj = ekj - r; // distance(v, ej);
18514 evp = distance(v, refpoint);
18515 if (evj < evp) {
18516 // v is rejected, use rule-3.
18517 eiv = distance(ei, v);
18518 if (evp <= 0.5 * eiv) {
18519 r = eki + eiv - evp;
18520 } else {
18521 r = eki + 0.5 * eiv;
18522 }
18523 #ifdef SELF_CHECK
18524 assert(eki < r && r < ekj);
18525 #endif
18526 split = r / ekj;
18527 for (i = 0; i < 3; i++) {
18528 v[i] = c[i] + split * (ej[i] - c[i]);
18529 }
18530 if (b->verbose > 1) {
18531 printf(" Using rule-3.\n");
18532 }
18533 rule = 3;
18534 }
18535 }
18536
18537 // Accumulate the corresponding counters.
18538 if (rule == 1) r1count++;
18539 else if (rule == 2) r2count++;
18540 else if (rule == 3) r3count++;
18541 else if (rule == 4) r4count++;
18542
18543 if (b->verbose > 1) {
18544 if (stype == 2) {
18545 printf(" Split = %.12g.\n", distance(ei, v) / distance(ei, ej));
18546 } else {
18547 printf(" Split = %.12g.\n", distance(c, v) / distance(c, ej));
18548 }
18549 }
18550
18551 // Create the newpoint.
18552 makepoint(&splitpoint);
18553 // Add a random perturbation on splitpoint.
18554 d1 = distance(c, v);
18555 if (stype == 1 || stype == 3) {
18556 ps = randgenerator(d1 * 1.0e-3);
18557 } else {
18558 // For type-2 segment, add a smaller perturbation.
18559 // ps = randgenerator(d1 * 1.0e-5);
18560 REAL d2 = distance(refpoint, v);
18561 ps = randgenerator(d2 * 1.0e-5);
18562 }
18563 rs = ps / d1;
18564 // Perturb splitpoint away from c.
18565 for (i = 0; i < 3; i++) {
18566 splitpoint[i] = c[i] + (1.0 + rs) * (v[i] - c[i]);
18567 }
18568 // for (i = 0; i < in->numberofpointattributes; i++) {
18569 // splitpoint[i + 3] = c[i + 3] + (split + rs) * (ej[i + 3] - c[i + 3]);
18570 // }
18571 if (stype == 3) {
18572 // Change a type-3 segment into two type-2 segments.
18573 setpointtype(splitpoint, NACUTEVERTEX);
18574 } else {
18575 // Set it's type be FREESEGVERTEX.
18576 setpointtype(splitpoint, FREESEGVERTEX);
18577 }
18578 setpoint2sh(splitpoint, sencode(*splitseg));
18579
18580 return splitpoint;
18581 }
18582
18583 ///////////////////////////////////////////////////////////////////////////////
18584 // //
18585 // delaunizesegments() Split segments repeatedly until they appear in a //
18586 // Delaunay tetrahedralization. //
18587 // //
18588 // Given a PLC X, which has a set V of vertices and a set of segments. Start //
18589 // from a Delaunay tetrahedralization D of V, this routine recovers segments //
18590 // of X in D by incrementally inserting points on missing segments, updating //
18591 // D with the newly inserted points into D', which remains to be a Delaunay //
18592 // tetrahedralization and respects the segments of X. Hence, each segment of //
18593 // X appears as a union of edges in D'. //
18594 // //
18595 // This routine dynamically maintains two meshes, one is DT, another is the //
18596 // surface mesh F of X. DT and F have exactly the same vertices. They are //
18597 // updated simultaneously with the newly inserted points. //
18598 // //
18599 // Missing segments are found by looping the set S of segments, checking the //
18600 // existence of each segment in DT. Once a segment is found missing in DT, //
18601 // it is split into two subsegments by inserting a point into both DT and F, //
18602 // and S is updated accordingly. However, the inserted point may cause some //
18603 // other existing segments be non-Delaunay, hence are missing from the DT. //
18604 // In order to force all segments to appear in DT, we have to loop S again //
18605 // after some segments are split. (A little ugly method) Use a handle to //
18606 // remember the last segment be split in one loop, hence all segments after //
18607 // it are existing and need not be checked. //
18608 // //
18609 // In priciple, a segment on the convex hull should exist in DT. However, if //
18610 // there are four coplanar points on the convex hull, and the DT only can //
18611 // contain one diagonal edge which is unfortunately not the segment, then it //
18612 // is missing. During the recovery of the segment, it is possible that the //
18613 // calculated inserting point for recovering this convex hull segment is not //
18614 // exact enough and lies (slightly) outside the DT. In order to insert the //
18615 // point, we enlarge the convex hull of the DT, so it can contain the point //
18616 // and remains convex. 'inserthullsite()' is called for this case. //
18617 // //
18618 ///////////////////////////////////////////////////////////////////////////////
18619
18620 void tetgenmesh::delaunizesegments()
18621 {
18622 queue *flipqueue;
18623 tetrahedron encodedtet;
18624 triface searchtet, splittet;
18625 face splitsh, symsplitsub;
18626 face segloop, symsplitseg;
18627 face lastsplit;
18628 point refpoint, splitpoint, sympoint;
18629 point tend, checkpoint;
18630 point p1, p2, pa;
18631 enum finddirectionresult collinear;
18632 enum insertsiteresult success;
18633 enum locateresult symloc;
18634 bool finish, coll;
18635 long vertcount;
18636 int i, j;
18637
18638 if (!b->quiet) {
18639 printf("Delaunizing segments.\n");
18640 }
18641
18642 // Mark segment vertices (acute or not) for determining segment types.
18643 markacutevertices(89.0);
18644 // Construct a map from points to tetrahedra for speeding point location.
18645 // makepoint2tetmap(); // This is done in above routine.
18646 // Initialize a queue for returning non-Delaunay faces and edges.
18647 flipqueue = new queue(sizeof(badface));
18648 // 'lastsplit' is the last segment be split in one loop, all segments
18649 // after it are existing. At first, set it be NULL;
18650 lastsplit.sh = (shellface *) NULL;
18651 // Remember the current number of points.
18652 vertcount = points->items;
18653 // Initialize the counters.
18654 r1count = r2count = r3count = r4count = 0l;
18655
18656 finish = false;
18657 while (!finish && (steinerleft != 0)) {
18658 subsegs->traversalinit();
18659 segloop.sh = shellfacetraverse(subsegs);
18660 while ((segloop.sh != (shellface *) NULL) && (steinerleft != 0)) {
18661 // Search segment ab in DT.
18662 p1 = sorg(segloop); // p1 = a;
18663 p2 = sdest(segloop); // p2 = b;
18664 if (b->verbose > 2) {
18665 printf(" Checking segment (%d, %d).\n", pointmark(p1), pointmark(p2));
18666 }
18667 getsearchtet(p1, p2, &searchtet, &tend);
18668 collinear = finddirection(&searchtet, tend, tetrahedrons->items);
18669 if (collinear == LEFTCOLLINEAR) {
18670 checkpoint = apex(searchtet);
18671 } else if (collinear == RIGHTCOLLINEAR) {
18672 checkpoint = dest(searchtet);
18673 } else if (collinear == TOPCOLLINEAR) {
18674 checkpoint = oppo(searchtet);
18675 } else {
18676 #ifdef SELF_CHECK
18677 assert(collinear == ACROSSFACE || collinear == ACROSSEDGE);
18678 #endif
18679 checkpoint = (point) NULL;
18680 }
18681 if (checkpoint != tend) {
18682 // ab is missing.
18683 splitpoint = (point) NULL;
18684 if (checkpoint != (point) NULL) {
18685 // An existing point c is found on the segment. It can happen when
18686 // ab is defined by a long segment with c inside it. Use c to
18687 // split ab. No new point is created.
18688 splitpoint = checkpoint;
18689 if (pointtype(checkpoint) == VOLVERTEX) {
18690 // c is not a segment vertex yet. It becomes NACUTEVERTEX.
18691 setpointtype(splitpoint, NACUTEVERTEX);
18692 } else if (pointtype(checkpoint) == ACUTEVERTEX) {
18693 // c is an acute vertex. The definition of PLC is wrong.
18694 } else if (pointtype(checkpoint) == NACUTEVERTEX) {
18695 // c is an nonacute vertex. The definition of PLC is wrong.
18696 } else {
18697 // assert(0);
18698 }
18699 } else {
18700 // Find a reference point p of ab.
18701 refpoint = scoutrefpoint(&searchtet, tend);
18702 if (pointtype(refpoint) == VOLVERTEX) {
18703 // p is an input point, check if it is nearly collinear with ab.
18704 coll = iscollinear(p1, p2, refpoint, b->epsilon);
18705 if (coll) {
18706 // a, b, and p are collinear. We insert p into ab. p becomes
18707 // a segment vertex with type NACUTEVERTEX.
18708 splitpoint = refpoint;
18709 setpointtype(splitpoint, NACUTEVERTEX);
18710 }
18711 }
18712 if (splitpoint == (point) NULL) {
18713 // Calculate a split point v using rule 1, or 2, or 3.
18714 splitpoint = getsplitpoint(&segloop, refpoint);
18715
18716 // Is there periodic boundary conditions?
18717 if (checkpbcs) {
18718 // Yes! Insert points on other segments of incident pbcgroups.
18719 i = shellmark(segloop) - 1;
18720 for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++) {
18721 makepoint(&sympoint);
18722 symloc = getsegpbcsympoint(splitpoint, &segloop, sympoint,
18723 &symsplitseg, segpglist[j]);
18724 #ifdef SELF_CHECK
18725 assert(symloc != OUTSIDE);
18726 #endif
18727 if ((symloc == ONEDGE) && (symsplitseg.sh != segloop.sh)) {
18728 #ifdef SELF_CHECK
18729 assert(symsplitseg.sh != dummysh);
18730 #endif
18731 setpointtype(sympoint, FREESEGVERTEX);
18732 setpoint2sh(sympoint, sencode(symsplitseg));
18733 // Insert sympoint into DT.
18734 pa = sorg(symsplitseg);
18735 splittet.tet = dummytet;
18736 // Find a good start point to search.
18737 encodedtet = point2tet(pa);
18738 if (encodedtet != (tetrahedron) NULL) {
18739 decode(encodedtet, splittet);
18740 if (isdead(&splittet)) {
18741 splittet.tet = dummytet;
18742 }
18743 }
18744 // Locate sympoint in DT. Do exact location.
18745 success = insertsite(sympoint, &splittet, false, flipqueue);
18746 #ifdef SELF_CHECK
18747 assert(success != DUPLICATEPOINT);
18748 #endif
18749 if (success == OUTSIDEPOINT) {
18750 inserthullsite(sympoint, &splittet, flipqueue);
18751 }
18752 if (steinerleft > 0) steinerleft--;
18753 // Let sympoint remember splittet.
18754 setpoint2tet(sympoint, encode(splittet));
18755 // Do flip in DT.
18756 flip(flipqueue, NULL);
18757 // Insert sympoint into F.
18758 symsplitseg.shver = 0;
18759 spivot(symsplitseg, symsplitsub);
18760 // sympoint should on the edge of symsplitsub.
18761 splitsubedge(sympoint, &symsplitsub, flipqueue);
18762 // Do flip in facet.
18763 flipsub(flipqueue);
18764 } else { // if (symloc == ONVERTEX) {
18765 // The sympoint already exists. It is possible when two
18766 // pbc groups are exactly the same. Omit this point.
18767 pointdealloc(sympoint);
18768 }
18769 }
18770 }
18771
18772 // Insert 'splitpoint' into DT.
18773 if (isdead(&searchtet)) searchtet.tet = dummytet;
18774 success = insertsite(splitpoint, &searchtet, false, flipqueue);
18775 if (success == OUTSIDEPOINT) {
18776 // A convex hull edge is missing, and the inserting point lies
18777 // (slightly) outside the convex hull due to the significant
18778 // digits lost in the calculation. Enlarge the convex hull.
18779 inserthullsite(splitpoint, &searchtet, flipqueue);
18780 }
18781 if (steinerleft > 0) steinerleft--;
18782 // Remember a handle in 'splitpoint' to enhance the speed of
18783 // consequent point location.
18784 setpoint2tet(splitpoint, encode(searchtet));
18785 // Maintain Delaunayness in DT.
18786 flip(flipqueue, NULL);
18787 }
18788 }
18789 // Insert 'splitpoint' into F.
18790 spivot(segloop, splitsh);
18791 splitsubedge(splitpoint, &splitsh, flipqueue);
18792 flipsub(flipqueue);
18793 // Remember 'segloop'.
18794 lastsplit = segloop;
18795 } else {
18796 // ab exists. Is it the last one we've checked?
18797 if (segloop.sh == lastsplit.sh) {
18798 finish = true;
18799 break;
18800 }
18801 }
18802 segloop.sh = shellfacetraverse(subsegs);
18803 }
18804 if (lastsplit.sh == (shellface *) NULL) {
18805 // No missing segment!
18806 finish = true;
18807 }
18808 }
18809
18810 if (b->verbose > 0) {
18811 printf(" %ld protect points.\n", points->items - vertcount);
18812 }
18813
18814 delete flipqueue;
18815 }
18816
18817 //
18818 // End of segments recovery routines
18819 //
18820
18821 //
18822 // Begin of facet recovery routines
18823 //
18824
18825 ///////////////////////////////////////////////////////////////////////////////
18826 // //
18827 // insertsubface() Fix a subface in place. //
18828 // //
18829 // Search a subface s in current tetrahedralization T. If s is found a face //
18830 // face of T, it is inserted into T. Return FALSE if s is not found in T. //
18831 // //
18832 ///////////////////////////////////////////////////////////////////////////////
18833
18834 bool tetgenmesh::insertsubface(face* insertsh, triface* searchtet)
18835 {
18836 triface spintet, symtet;
18837 face testsh, testseg;
18838 face spinsh, casin, casout;
18839 point tapex, checkpoint;
18840 enum finddirectionresult collinear;
18841 int hitbdry;
18842
18843 // Search an edge of s.
18844 getsearchtet(sorg(*insertsh), sdest(*insertsh), searchtet, &checkpoint);
18845 collinear = finddirection(searchtet, checkpoint, tetrahedrons->items);
18846 if (collinear == LEFTCOLLINEAR) {
18847 enext2self(*searchtet);
18848 esymself(*searchtet);
18849 } else if (collinear == TOPCOLLINEAR) {
18850 fnextself(*searchtet);
18851 enext2self(*searchtet);
18852 esymself(*searchtet);
18853 }
18854 if (dest(*searchtet) != checkpoint) {
18855 // The edge doesn't exist => s is missing.
18856 return false;
18857 }
18858
18859 // Search s by spinning faces around the edge.
18860 tapex = sapex(*insertsh);
18861 spintet = *searchtet;
18862 hitbdry = 0;
18863 do {
18864 if (apex(spintet) == tapex) {
18865 // Found s in T. Check if s has already been inserted.
18866 tspivot(spintet, testsh);
18867 if (testsh.sh == dummysh) {
18868 adjustedgering(spintet, CCW);
18869 findedge(insertsh, org(spintet), dest(spintet));
18870 tsbond(spintet, *insertsh);
18871 sym(spintet, symtet); // 'symtet' maybe outside, use it anyway.
18872 sesymself(*insertsh);
18873 tsbond(symtet, *insertsh);
18874 } else {
18875 // Found a duplicated subface (due to the redundant input).
18876 if (!b->quiet) {
18877 printf("Warning: Two subfaces are found duplicated at ");
18878 printf("(%d, %d, %d)\n", pointmark(sorg(testsh)),
18879 pointmark(sdest(testsh)), pointmark(sapex(testsh)));
18880 printf(" Subface of facet #%d is deleted.\n", shellmark(*insertsh));
18881 // printf(" Hint: -d switch can find all duplicated facets.\n");
18882 }
18883 shellfacedealloc(subfaces, insertsh->sh);
18884 }
18885 return true;
18886 }
18887 if (!fnextself(spintet)) {
18888 hitbdry ++;
18889 if (hitbdry < 2) {
18890 esym(*searchtet, spintet);
18891 if (!fnextself(spintet)) {
18892 hitbdry ++;
18893 }
18894 }
18895 }
18896 } while (hitbdry < 2 && apex(spintet) != apex(*searchtet));
18897
18898 // s is missing.
18899 return false;
18900 }
18901
18902 ///////////////////////////////////////////////////////////////////////////////
18903 // //
18904 // tritritest() Test if two triangles are intersecting in their interior. //
18905 // //
18906 // One triangle t1 is the face of 'checktet', the other t2 is given by three //
18907 // corners 'p1', 'p2' and 'p3'. This routine calls tri_tri_inter() to detect //
18908 // whether t1 and t2 exactly intersect in their interior. Cases like share a //
18909 // vertex, share an edge, or coincidence are considered not intersect. //
18910 // //
18911 ///////////////////////////////////////////////////////////////////////////////
18912
18913 bool tetgenmesh::tritritest(triface* checktet, point p1, point p2, point p3)
18914 {
18915 point forg, fdest, fapex;
18916 enum interresult intersect;
18917
18918 forg = org(*checktet);
18919 fdest = dest(*checktet);
18920 fapex = apex(*checktet);
18921
18922 #ifdef SELF_CHECK
18923 REAL ax, ay, az, bx, by, bz;
18924 REAL n[3];
18925 // face (torg, tdest, tapex) should not be degenerate. However p1, p2,
18926 // and p3 may be collinear. Check it.
18927 ax = forg[0] - fdest[0];
18928 ay = forg[1] - fdest[1];
18929 az = forg[2] - fdest[2];
18930 bx = forg[0] - fapex[0];
18931 by = forg[1] - fapex[1];
18932 bz = forg[2] - fapex[2];
18933 n[0] = ay * bz - by * az;
18934 n[1] = az * bx - bz * ax;
18935 n[2] = ax * by - bx * ay;
18936 assert(fabs(n[0]) + fabs(n[1]) + fabs(n[2]) > 0.0);
18937 // The components of n should not smaller than the machine epsilon.
18938
18939 ax = p1[0] - p2[0];
18940 ay = p1[1] - p2[1];
18941 az = p1[2] - p2[2];
18942 bx = p1[0] - p3[0];
18943 by = p1[1] - p3[1];
18944 bz = p1[2] - p3[2];
18945 n[0] = ay * bz - by * az;
18946 n[1] = az * bx - bz * ax;
18947 n[2] = ax * by - bx * ay;
18948 assert(fabs(n[0]) + fabs(n[1]) + fabs(n[2]) > 0.0);
18949 // The components of n should not smaller than the machine epsilon.
18950 #endif
18951
18952 intersect = tri_tri_inter(forg, fdest, fapex, p1, p2, p3);
18953 return intersect == INTERSECT;
18954 }
18955
18956 ///////////////////////////////////////////////////////////////////////////////
18957 // //
18958 // initializecavity() Initialize the cavity. //
18959 // //
18960 // A cavity C is bounded by a list of faces, called fronts. Each front f is //
18961 // hold by a tet t adjacent to C, t is not in C (uninfected). If f is a hull //
18962 // face, t does't exist, a fake tet t' is created to hold f. t' has the same //
18963 // vertices as f but no opposite. t' will be removed automatically after C //
18964 // is filled with new tets (by carvecavity()). //
18965 // //
18966 // The faces of C are given in two lists. 'floorlist' is a set of subfaces, //
18967 // each subface has been oriented to face to the inside of C. 'ceillist' is //
18968 // a set of tetrahedral faces. 'frontlist' returns the initialized fronts. //
18969 // //
18970 ///////////////////////////////////////////////////////////////////////////////
18971
18972 void tetgenmesh::initializecavity(list* floorlist, list* ceillist,
18973 list* frontlist)
18974 {
18975 triface neightet, casingtet;
18976 triface faketet;
18977 face worksh;
18978 int i;
18979
18980 // Initialize subfaces of C.
18981 for (i = 0; i < floorlist->len(); i++) {
18982 // Get a subface s.
18983 worksh = * (face *)(* floorlist)[i];
18984 #ifdef SELF_CHECK
18985 // Current side of s should be empty.
18986 stpivot(worksh, neightet);
18987 assert(neightet.tet == dummytet);
18988 #endif
18989 // Get the adjacent tet t.
18990 sesymself(worksh);
18991 stpivot(worksh, casingtet);
18992 // Does t exist?
18993 if (casingtet.tet == dummytet) {
18994 // Create a fake tet t' to hold f temporarily.
18995 maketetrahedron(&faketet);
18996 setorg(faketet, sorg(worksh));
18997 setdest(faketet, sdest(worksh));
18998 setapex(faketet, sapex(worksh));
18999 setoppo(faketet, (point) NULL); // Indicates it is 'fake'.
19000 tsbond(faketet, worksh);
19001 frontlist->append(&faketet);
19002 } else {
19003 frontlist->append(&casingtet);
19004 }
19005 }
19006 // Initialize tet faces of C.
19007 for (i = 0; i < ceillist->len(); i++) {
19008 // Get a tet face c.
19009 neightet = * (triface *) (* ceillist)[i];
19010 #ifdef SELF_CHECK
19011 // The tet of c must be inside C (going to be deleted).
19012 assert(infected(neightet));
19013 #endif
19014 // Get the adjacent tet t.
19015 sym(neightet, casingtet);
19016 // Does t exist?
19017 if (casingtet.tet == dummytet) {
19018 // No. Create a fake tet t' to hold f temporarily.
19019 maketetrahedron(&faketet);
19020 // Be sure that the vertices of t' are CCW oriented.
19021 adjustedgering(neightet, CW); // CW edge ring.
19022 setorg(faketet, org(neightet));
19023 setdest(faketet, dest(neightet));
19024 setapex(faketet, apex(neightet));
19025 setoppo(faketet, (point) NULL); // Indicates it is 'fake'.
19026 // Bond t' to a subface if it exists.
19027 tspivot(neightet, worksh);
19028 if (worksh.sh != dummysh) {
19029 sesymself(worksh);
19030 tsbond(faketet, worksh);
19031 }
19032 // Bond c <--> t'. So we're able to find t' and remove it.
19033 bond(faketet, neightet);
19034 // c may become uninfected due to the bond().
19035 infect(neightet);
19036 frontlist->append(&faketet);
19037 } else {
19038 frontlist->append(&casingtet);
19039 }
19040 }
19041 }
19042
19043 ///////////////////////////////////////////////////////////////////////////////
19044 // //
19045 // retrievenewtets() Retrieve the newly created tets. //
19046 // //
19047 // On input, 'newtetlist' contains at least one alive new tet. From this tet,//
19048 // other new tets can be found by a broadth-first searching. //
19049 // //
19050 ///////////////////////////////////////////////////////////////////////////////
19051
19052 void tetgenmesh::retrievenewtets(list* newtetlist)
19053 {
19054 triface searchtet, casingtet;
19055 int i;
19056
19057 // There may be dead tets due to flip32(). Delete them first.
19058 for (i = 0; i < newtetlist->len(); i++) {
19059 searchtet = * (triface *)(* newtetlist)[i];
19060 if (isdead(&searchtet)) {
19061 newtetlist->del(i, 0); i--;
19062 continue;
19063 }
19064 infect(searchtet);
19065 }
19066 // Find all new tets.
19067 for (i = 0; i < newtetlist->len(); i++) {
19068 searchtet = * (triface *)(* newtetlist)[i];
19069 for (searchtet.loc = 0; searchtet.loc < 4; searchtet.loc++) {
19070 sym(searchtet, casingtet);
19071 if ((casingtet.tet != dummytet) && !infected(casingtet)) {
19072 infect(casingtet);
19073 newtetlist->append(&casingtet);
19074 }
19075 }
19076 }
19077 // Uninfect new tets.
19078 for (i = 0; i < newtetlist->len(); i++) {
19079 searchtet = * (triface *)(* newtetlist)[i];
19080 uninfect(searchtet);
19081 }
19082 }
19083
19084 ///////////////////////////////////////////////////////////////////////////////
19085 // //
19086 // delaunizecavvertices() Form a DT of the vertices of a cavity. //
19087 // //
19088 // 'floorptlist' and 'ceilptlist' are the vertices of the cavity. //
19089 // //
19090 // The tets of the DT are created directly in the pool 'tetrahedrons', i.e., //
19091 // no auxiliary data structure and memory are required. The trick is at the //
19092 // time they're created, there are no connections between them to the other //
19093 // tets in the pool. You can imagine they form an ioslated island. //
19094 // //
19095 ///////////////////////////////////////////////////////////////////////////////
19096
19097 void tetgenmesh::delaunizecavvertices(triface* oldtet, list* floorptlist,
19098 list* ceilptlist, list* newtetlist, queue* flipque)
19099 {
19100 point *insertarray;
19101 triface bakhulltet, newtet;
19102 long bakhullsize;
19103 long arraysize;
19104 int bakchksub;
19105 int i, j;
19106
19107 // Prepare the array of points for inserting.
19108 arraysize = floorptlist->len();
19109 if (ceilptlist != (list *) NULL) {
19110 arraysize += ceilptlist->len();
19111 }
19112 insertarray = new point[arraysize];
19113 for (i = 0; i < floorptlist->len(); i++) {
19114 insertarray[i] = * (point *)(* floorptlist)[i];
19115 }
19116 if (ceilptlist != (list *) NULL) {
19117 for (j = 0; j < ceilptlist->len(); j++) {
19118 insertarray[i + j] = * (point *)(* ceilptlist)[j];
19119 }
19120 }
19121
19122 // The incrflipdelaunay() is re-used. Backup global variables.
19123 decode(dummytet[0], bakhulltet);
19124 bakhullsize = hullsize;
19125 bakchksub = checksubfaces;
19126 checksubfaces = 0;
19127 b->verbose--;
19128
19129 // Form the DT by incremental flip Delaunay algorithm. Do not jump for
19130 // point location, do not merge points.
19131 incrflipdelaunay(oldtet, insertarray, arraysize, false, false, 0.0, flipque);
19132
19133 // Get a tet in D.
19134 decode(dummytet[0], newtet);
19135 newtetlist->append(&newtet);
19136 // Get all tets of D.
19137 retrievenewtets(newtetlist);
19138
19139 // Restore global variables.
19140 dummytet[0] = encode(bakhulltet);
19141 hullsize = bakhullsize;
19142 checksubfaces = bakchksub;
19143 b->verbose++;
19144
19145 delete [] insertarray;
19146 }
19147
19148 ///////////////////////////////////////////////////////////////////////////////
19149 // //
19150 // insertauxsubface() Fix an auxilary subface in place. //
19151 // //
19152 // An auxilary subface s is fixed in D as it is a real subface, but s has no //
19153 // vertices and neighbors. It has two uses: (1) it protects an identfied //
19154 // front f in D; (2) it serves the link to bond a tet in C and f later. The //
19155 // first neighbor of s (s->sh[0]) stores a pointer to f. //
19156 // //
19157 // 'front' is a front f of C. idfront' t is a tet in D where f is identified //
19158 // be a face of it. s will be fixed between t and its neighbor. //
19159 // //
19160 ///////////////////////////////////////////////////////////////////////////////
19161
19162 void tetgenmesh::insertauxsubface(triface* front, triface* idfront)
19163 {
19164 triface neightet;
19165 face auxsh;
19166
19167 // Create the aux subface s.
19168 makeshellface(subfaces, &auxsh);
19169 // Bond s <--> t.
19170 tsbond(*idfront, auxsh);
19171 // Does t's neighbor n exist?
19172 sym(*idfront, neightet);
19173 if (neightet.tet != dummytet) {
19174 // Bond s <--> n.
19175 sesymself(auxsh);
19176 tsbond(neightet, auxsh);
19177 }
19178 // Let s remember f.
19179 auxsh.sh[0] = (shellface) encode(*front);
19180 }
19181
19182 ///////////////////////////////////////////////////////////////////////////////
19183 // //
19184 // scoutfront() Scout a face in D. //
19185 // //
19186 // Search a 'front' f in D. If f is found, return TRUE and the face of D is //
19187 // returned in 'idfront'. Otherwise, return FALSE. //
19188 // //
19189 ///////////////////////////////////////////////////////////////////////////////
19190
19191 bool tetgenmesh::scoutfront(triface* front, triface* idfront, list* newtetlist)
19192 {
19193 triface spintet;
19194 point pa, pb, pc;
19195 enum locateresult loc;
19196 enum finddirectionresult col;
19197 int hitbdry;
19198 int i;
19199
19200 // Let the front we're searching is abc.
19201 pa = org(*front);
19202 pb = dest(*front);
19203 // Get a tet in D for searching.
19204 *idfront = recenttet;
19205 // Make sure the tet is valid (it may be killed by flips).
19206 if (isdead(idfront)) {
19207 // The tet is dead. Search a live tet in D. !!!
19208 for (i = 0; i < newtetlist->len(); i++) {
19209 recenttet = * (triface *)(* newtetlist)[i];
19210 if (!isdead(&recenttet)) break;
19211 }
19212 assert(i < newtetlist->len());
19213 }
19214
19215 // Search a tet having vertex a.
19216 loc = preciselocate(pa, idfront, (long) newtetlist->len());
19217 assert(loc == ONVERTEX);
19218 recenttet = *idfront;
19219 // Search a tet having edge ab.
19220 col = finddirection(idfront, pb, (long) newtetlist->len());
19221 if (col == RIGHTCOLLINEAR) {
19222 // b is just the destination.
19223 } else if (col == LEFTCOLLINEAR) {
19224 enext2self(*idfront);
19225 esymself(*idfront);
19226 } else if (col == TOPCOLLINEAR) {
19227 fnextself(*idfront);
19228 enext2self(*idfront);
19229 esymself(*idfront);
19230 }
19231
19232 if (dest(*idfront) == pb) {
19233 // Search a tet having face abc
19234 pc = apex(*front);
19235 spintet = *idfront;
19236 hitbdry = 0;
19237 do {
19238 if (apex(spintet) == pc) {
19239 // Found abc. Insert an auxilary subface s at idfront.
19240 // insertauxsubface(front, &spintet);
19241 *idfront = spintet;
19242 return true;
19243 }
19244 if (!fnextself(spintet)) {
19245 hitbdry ++;
19246 if (hitbdry < 2) {
19247 esym(*idfront, spintet);
19248 if (!fnextself(spintet)) {
19249 hitbdry ++;
19250 }
19251 }
19252 }
19253 if (apex(spintet) == apex(*idfront)) break;
19254 } while (hitbdry < 2);
19255 }
19256
19257 // f is missing in D.
19258 if (b->verbose > 2) {
19259 printf(" Front (%d, %d, %d) is missing.\n", pointmark(pa),
19260 pointmark(pb), pointmark(apex(*front)));
19261 }
19262 return false;
19263 }
19264
19265 ///////////////////////////////////////////////////////////////////////////////
19266 // //
19267 // gluefronts() Glue two fronts together. //
19268 // //
19269 // This is a support routine for identifyfront(). Two fronts f and f1 are //
19270 // found indentical. This is caused by the non-coplanarity of vertices of a //
19271 // facet. Hence f and f1 are a subface and a tet. They are not fronts of the //
19272 // cavity anymore. This routine glues f and f1 together. //
19273 // //
19274 ///////////////////////////////////////////////////////////////////////////////
19275
19276 void tetgenmesh::gluefronts(triface* front, triface* front1)
19277 {
19278 face consh;
19279
19280 // Glue f and f1 together. There're four cases:
19281 // (1) both f and f1 are not fake;
19282 // (2) f is not fake, f1 is fake;
19283 // (3) f is fake and f1 is not fake;
19284 // (4) both f and f1 are fake.
19285 // Case (4) should be not possible.
19286
19287 // Is there a concrete subface c at f.
19288 tspivot(*front, consh);
19289 if (consh.sh != dummysh) {
19290 sesymself(consh);
19291 tsbond(*front1, consh); // Bond: f1 <--> c.
19292 sesymself(consh);
19293 }
19294 // Does f hold by a fake tet.
19295 if (oppo(*front) == (point) NULL) {
19296 // f is fake. Case (3) or (4).
19297 assert(oppo(*front1) != (point) NULL); // Eliminate (4).
19298 // Case (3).
19299 if (consh.sh != dummysh) {
19300 stdissolve(consh); // Dissolve: c -x-> f.
19301 }
19302 // Dealloc f.
19303 tetrahedrondealloc(front->tet);
19304 // f1 becomes a hull. let 'dummytet' bond to it.
19305 dummytet[0] = encode(*front1);
19306 } else {
19307 // Case (1) or (2).
19308 bond(*front, *front1); // Bond f1 <--> f.
19309 }
19310 // Is f a fake tet?
19311 if (!isdead(front)) {
19312 // No. Check for case (2).
19313 tspivot(*front1, consh);
19314 // Is f1 fake?
19315 if (oppo(*front1) == (point) NULL) {
19316 // Case (2) or (4)
19317 assert(oppo(*front) != (point) NULL); // Eliminate (4).
19318 // Case (2).
19319 if (consh.sh != dummysh) {
19320 stdissolve(consh); // Dissolve: c -x-> f1.
19321 sesymself(consh); // Bond: f <--> c.
19322 tsbond(*front, consh);
19323 }
19324 // Dissolve: f -x->f1.
19325 dissolve(*front);
19326 // Dealloc f1.
19327 tetrahedrondealloc(front1->tet);
19328 // f becomes a hull. let 'dummytet' bond to it.
19329 dummytet[0] = encode(*front);
19330 } else {
19331 // Case (1).
19332 if (consh.sh != dummysh) {
19333 sesymself(consh);
19334 tsbond(*front, consh); // Bond: f <--> c.
19335 }
19336 }
19337 }
19338 }
19339
19340 ///////////////////////////////////////////////////////////////////////////////
19341 // //
19342 // identifyfronts() Identify cavity faces in D. //
19343 // //
19344 // 'frontlist' are fronts of C need indentfying. This routine searches each //
19345 // front f in D. Once f is found, an auxilary subface s is inserted in D at //
19346 // the face. If f is not found in D, remove it from frontlist and save it in //
19347 // 'misfrontlist'. //
19348 // //
19349 ///////////////////////////////////////////////////////////////////////////////
19350
19351 bool tetgenmesh::identifyfronts(list* frontlist, list* misfrontlist,
19352 list* newtetlist)
19353 {
19354 triface front, front1, tfront;
19355 triface idfront, neightet;
19356 face auxsh;
19357 int len, i, j;
19358
19359 misfrontlist->clear();
19360 // Set a new tet in D for searching.
19361 recenttet = * (triface *)(* newtetlist)[0];
19362
19363 // Identify all fronts in D.
19364 for (i = 0; i < frontlist->len(); i++) {
19365 // Get a front f.
19366 front = * (triface *)( *frontlist)[i];
19367 if (scoutfront(&front, &idfront, newtetlist)) {
19368 // Found f. Insert an aux subface s.
19369 assert((idfront.tet != dummytet) && !isdead(&idfront));
19370 // Does s already exist?
19371 tspivot(idfront, auxsh);
19372 if (auxsh.sh != dummysh) {
19373 // There're two identical fronts, f (front) and f1 (s.sh[0])!
19374 decode((tetrahedron) auxsh.sh[0], front1);
19375 assert((front1.tet != dummytet) && !infected(front1));
19376 // Detach s in D.
19377 tsdissolve(idfront);
19378 sym(idfront, neightet);
19379 if (neightet.tet != dummytet) {
19380 tsdissolve(neightet);
19381 }
19382 // s has fulfilled its duty. Can be deleted.
19383 shellfacedealloc(subfaces, auxsh.sh);
19384 // Remove f from frontlist.
19385 frontlist->del(i, 1); i--;
19386 // Remove f1 from frontlist.
19387 len = frontlist->len();
19388 for (j = 0; j < frontlist->len(); j++) {
19389 tfront = * (triface *)(* frontlist)[j];
19390 if ((tfront.tet == front1.tet) && (tfront.loc == front1.loc)) {
19391 // Found f1 in list. Check f1 != f.
19392 assert((tfront.tet != front.tet) || (tfront.loc != front.loc));
19393 frontlist->del(j, 1); i--;
19394 break;
19395 }
19396 }
19397 assert((frontlist->len() + 1) == len);
19398 // Glue f and f1 together.
19399 gluefronts(&front, &front1);
19400 } else {
19401 // Insert an aux subface to protect f in D.
19402 insertauxsubface(&front, &idfront);
19403 }
19404 } else {
19405 // f is missing.
19406 frontlist->del(i, 1); i--;
19407 // Are there two identical fronts, f (front) and f1 (front1)?
19408 for (j = 0; j < misfrontlist->len(); j++) {
19409 front1 = * (triface *)(* misfrontlist)[j];
19410 if (isfacehaspoint(&front1, org(front)) &&
19411 isfacehaspoint(&front1, dest(front)) &&
19412 isfacehaspoint(&front1, apex(front))) break;
19413 }
19414 if (j < misfrontlist->len()) {
19415 // Found an identical front f1. Remove f1 from the list.
19416 misfrontlist->del(j, 1);
19417 // Glue f and f1 together.
19418 gluefronts(&front, &front1);
19419 } else {
19420 // Add f into misfrontlist.
19421 misfrontlist->append(&front);
19422 }
19423 }
19424 }
19425 return misfrontlist->len() == 0;
19426 }
19427
19428 ///////////////////////////////////////////////////////////////////////////////
19429 // //
19430 // detachauxsubfaces() Detach auxilary subfaces in D. //
19431 // //
19432 // This is a reverse routine of identifyfronts(). Some fronts are missing in //
19433 // D. C can not be easily tetrahedralized. It needs remediation (expansion, //
19434 // or constrained flips, or adding a Steiner point). This routine detaches //
19435 // the auxilary subfaces have been inserted in D and delete them. //
19436 // //
19437 ///////////////////////////////////////////////////////////////////////////////
19438
19439 void tetgenmesh::detachauxsubfaces(list* newtetlist)
19440 {
19441 triface newtet, neightet;
19442 face auxsh;
19443 int i;
19444
19445 for (i = 0; i < newtetlist->len(); i++) {
19446 // Get a new tet t.
19447 newtet = * (triface *)(* newtetlist)[i];
19448 // t may e dead due to flips.
19449 if (isdead(&newtet)) continue;
19450 assert(!infected(newtet));
19451 // Check the four faces of t.
19452 for (newtet.loc = 0; newtet.loc < 4; newtet.loc++) {
19453 tspivot(newtet, auxsh);
19454 if (auxsh.sh != dummysh) {
19455 // An auxilary subface s.
19456 assert(sorg(auxsh) == (point) NULL);
19457 tsdissolve(newtet); // t -x-> s.
19458 sym(newtet, neightet);
19459 if (neightet.tet != dummytet) {
19460 assert(!isdead(&neightet));
19461 tsdissolve(neightet); // n -x-> s.
19462 }
19463 // Delete s.
19464 shellfacedealloc(subfaces, auxsh.sh);
19465 }
19466 }
19467 }
19468 }
19469
19470 ///////////////////////////////////////////////////////////////////////////////
19471 // //
19472 // expandcavity() Expand the cavity by adding new fronts. //
19473 // //
19474 // This is the support routine for delaunizecavity(). Some fronts of C are //
19475 // missing in D since they're not strongly Delaunay. Such fronts are removed //
19476 // and the faces of the tets abutting to them are added. C is then expanded. //
19477 // Some removed faces may be subfaces, they're queued to recover later. D is //
19478 // expanded simultaneously with the new vertices of the new fronts. //
19479 // //
19480 ///////////////////////////////////////////////////////////////////////////////
19481
19482 void tetgenmesh::expandcavity(list* frontlist, list* misfrontlist,
19483 list* newtetlist, list* crosstetlist, queue* missingshqueue, queue* flipque)
19484 {
19485 triface misfront, newfront, casingtet, crosstet;
19486 triface searchtet, faketet, bakhulltet;
19487 face checksh;
19488 point pd;
19489 enum insertsiteresult success;
19490 long bakhullsize;
19491 int bakchksub;
19492 int i, j, k;
19493
19494 if (b->verbose > 1) {
19495 printf(" Expand cavity (%d missing fronts).\n", misfrontlist->len());
19496 }
19497 // Increase the number of expanded times.
19498 expcavcount++;
19499 // The incrflipdelaunay() is re-used. Backup global variables.
19500 decode(dummytet[0], bakhulltet);
19501 bakhullsize = hullsize;
19502 bakchksub = checksubfaces;
19503 checksubfaces = 0;
19504 b->verbose--;
19505
19506 // Choose a tet in D for searching.
19507 recenttet = * (triface *)(* newtetlist)[0];
19508 assert((recenttet.tet != dummytet) && !isdead(&recenttet));
19509
19510 // Loop through 'misfrontlist'.
19511 for (i = 0; i < misfrontlist->len(); i++) {
19512 // Get a missing front f.
19513 misfront = * (triface *)(* misfrontlist)[i];
19514 // C will be expanded at f.
19515 if (b->verbose > 1) {
19516 printf(" Get misfront (%d, %d, %d).\n", pointmark(org(misfront)),
19517 pointmark(dest(misfront)), pointmark(apex(misfront)));
19518 }
19519 // Is f has a subface s?
19520 tspivot(misfront, checksh);
19521 if (checksh.sh != dummysh) {
19522 // A subface s is found. Check whether f is expandable at s.
19523 sym(misfront, crosstet);
19524 if (!infected(crosstet)) {
19525 // f is not expandable. In principle is should not happen. However,
19526 // it can happen when PBC is in use.
19527 assert(checkpbcs);
19528 // Skip expanding f. It will be processed later.
19529 continue;
19530 }
19531 // Temporarily remove s. Queue and recover it later.
19532 if (b->verbose > 1) {
19533 printf(" Queuing subface (%d, %d, %d).\n",
19534 pointmark(sorg(checksh)), pointmark(sdest(checksh)),
19535 pointmark(sapex(checksh)));
19536 }
19537 // Detach s from tets at its both sides.
19538 tsdissolve(misfront);
19539 tsdissolve(crosstet);
19540 // Detach tets at from s.
19541 stdissolve(checksh);
19542 sesymself(checksh);
19543 stdissolve(checksh);
19544 // Mark and queue it.
19545 sinfect(checksh);
19546 missingshqueue->push(&checksh);
19547 }
19548 // f may already be processed (become a cross tet of C).
19549 if (infected(misfront)) continue;
19550 // Get the point p = oppo(t), t is the tet holds f.
19551 pd = oppo(misfront);
19552 #ifdef SELF_CHECK
19553 // t must not be fake.
19554 assert(pd != (point) NULL);
19555 #endif
19556 // Insert p in D. p may not be inserted if it is one of the two cases:
19557 // (1) p is already a vertex of D;
19558 // (2) p lies outside the CH of D;
19559 searchtet = recenttet;
19560 // Make sure the tet is valid (it may be killed by flips).
19561 if (isdead(&searchtet)) {
19562 // The tet is dead. Get a live tet in D. !!!
19563 for (j = 0; j < newtetlist->len(); j++) {
19564 recenttet = * (triface *)(* newtetlist)[j];
19565 if (!isdead(&recenttet)) break;
19566 }
19567 assert(j < newtetlist->len());
19568 searchtet = recenttet;
19569 }
19570 success = insertsite(pd, &searchtet, false, flipque);
19571 if (success == OUTSIDEPOINT) {
19572 // case (2). Insert p onto CH of D.
19573 inserthullsite(pd, &searchtet, flipque);
19574 }
19575 if (success != DUPLICATEPOINT) {
19576 // p is inserted. Recover Delaunness of D by flips.
19577 flip(flipque, NULL);
19578 }
19579 // Expand C by adding new fronts. The three faces of t which have p as a
19580 // vertex become new fronts. However, if a new front is coincident with
19581 // an old front of C, it is not added and the old front is removed.
19582 adjustedgering(misfront, CCW);
19583 for (j = 0; j < 3; j++) {
19584 // Notice: Below I mis-used the names. 'newfront' is not exactly a new
19585 // front, instead the 'casingtet' should be called new front.
19586 // Get a new front f_n.
19587 fnext(misfront, newfront);
19588 // Get the neighbor tet n at f_n.
19589 sym(newfront, casingtet);
19590 // Is n a cross tet?
19591 if (!infected(casingtet)) {
19592 // f_n becomes a new front of C.
19593 // Does n exist?
19594 if (casingtet.tet == dummytet) {
19595 // Create a fake tet n' to hold f_n temporarily.
19596 maketetrahedron(&faketet);
19597 // Be sure that the vertices of fake tet are CCW oriented.
19598 adjustedgering(newfront, CW); // CW edge ring.
19599 setorg(faketet, org(newfront));
19600 setdest(faketet, dest(newfront));
19601 setapex(faketet, apex(newfront));
19602 setoppo(faketet, (point) NULL); // Indicates it is 'fake'.
19603 // Bond n' to a subface if it exists.
19604 tspivot(newfront, checksh);
19605 if (checksh.sh != dummysh) {
19606 sesymself(checksh);
19607 tsbond(faketet, checksh);
19608 }
19609 // Bond f_n <--> n'. So we're able to find n' and remove it.
19610 bond(faketet, newfront);
19611 frontlist->append(&faketet);
19612 } else {
19613 // Add n to frontlist.
19614 frontlist->append(&casingtet);
19615 }
19616 } else {
19617 // f_n is coincident with an existing front f' of C. f' is no longer
19618 // a front, remove it from frontlist. Use the inverse order to
19619 // search f' (most likely, a newly added front may be f').
19620 for (k = frontlist->len() - 1; k >= 0; k--) {
19621 searchtet = * (triface *)(* frontlist)[k];
19622 if ((newfront.tet == searchtet.tet) &&
19623 (newfront.loc == searchtet.loc)) {
19624 frontlist->del(k, 0);
19625 break;
19626 }
19627 }
19628 // Is f_n a subface?
19629 tspivot(newfront, checksh);
19630 if (checksh.sh != dummysh) {
19631 // Temporarily remove checksh. Make it missing. recover it later.
19632 if (b->verbose > 2) {
19633 printf(" Queuing subface (%d, %d, %d).\n",
19634 pointmark(sorg(checksh)), pointmark(sdest(checksh)),
19635 pointmark(sapex(checksh)));
19636 }
19637 tsdissolve(newfront);
19638 tsdissolve(casingtet);
19639 // Detach tets at the both sides of checksh.
19640 stdissolve(checksh);
19641 sesymself(checksh);
19642 stdissolve(checksh);
19643 sinfect(checksh);
19644 missingshqueue->push(&checksh);
19645 }
19646 }
19647 enextself(misfront);
19648 }
19649 // C has been expanded at f. t becomes a cross tet.
19650 if (!infected(misfront)) {
19651 // t will be deleted, queue it.
19652 infect(misfront);
19653 crosstetlist->append(&misfront);
19654 }
19655 }
19656
19657 // Loop through misfrontlist, remove infected misfronts.
19658 for (i = 0; i < misfrontlist->len(); i++) {
19659 misfront = * (triface *)(* misfrontlist)[i];
19660 if (infected(misfront)) {
19661 // Remove f, keep original list order.
19662 misfrontlist->del(i, 1);
19663 i--;
19664 }
19665 }
19666
19667 // Are we done?
19668 if (misfrontlist->len() > 0) {
19669 // No. There are unexpandable fronts.
19670 // expandcavity_sos(misfrontlist);
19671 assert(0); // Not done yet.
19672 }
19673
19674 // D has been updated (by added new tets or dead tets) (due to flips).
19675 retrievenewtets(newtetlist);
19676
19677 // Restore global variables.
19678 dummytet[0] = encode(bakhulltet);
19679 hullsize = bakhullsize;
19680 checksubfaces = bakchksub;
19681 b->verbose++;
19682 }
19683
19684 ///////////////////////////////////////////////////////////////////////////////
19685 // //
19686 // carvecavity() Remove redundant (outside) tetrahedra from D. //
19687 // //
19688 // The fronts of C have been identified in D. Hence C can be tetrahedralized //
19689 // by removing the tets outside C. The CDT is then updated by filling C with //
19690 // the remaining tets (inside C) of D. //
19691 // //
19692 // Each front is protected by an auxilary subface s in D. s has a pointer to //
19693 // f (s.sh[0]). f can be used to classified the in- and out- tets of C (the //
19694 // CW orientation of f faces to the inside of C). The classified out-tets of //
19695 // C are marked (infected) for removing. //
19696 // //
19697 // Notice that the out-tets may not only the tets on the CH of C, but also //
19698 // tets completely inside D, eg., there is a "hole" in D. Such tets must be //
19699 // marked during classification. The hole tets are poped up and removed too. //
19700 // //
19701 ///////////////////////////////////////////////////////////////////////////////
19702
19703 void tetgenmesh::carvecavity(list* newtetlist, list* outtetlist,
19704 queue* flipque)
19705 {
19706 triface newtet, neightet, front, outtet;
19707 face auxsh, consh;
19708 point pointptr;
19709 REAL ori;
19710 int i;
19711
19712 // Clear work list.
19713 outtetlist->clear();
19714
19715 // Classify in- and out- tets in D. Mark and queue classified out-tets.
19716 for (i = 0; i < newtetlist->len(); i++) {
19717 // Get a new tet t.
19718 newtet = * (triface *)(* newtetlist)[i];
19719 assert(!isdead(&newtet));
19720 // Look for aux subfaces attached at t.
19721 for (newtet.loc = 0; newtet.loc < 4; newtet.loc++) {
19722 tspivot(newtet, auxsh);
19723 if (auxsh.sh != dummysh) {
19724 // Has this side a neighbor n?
19725 sym(newtet, neightet);
19726 if (neightet.tet != dummytet) {
19727 // Classify t and n (one is "in" and another is "out").
19728 // Get the front f.
19729 decode((tetrahedron) auxsh.sh[0], front);
19730 // Let f face to the inside of C.
19731 adjustedgering(front, CW);
19732 ori = orient3d(org(front), dest(front), apex(front), oppo(newtet));
19733 assert(ori != 0.0);
19734 if (ori < 0.0) {
19735 // t is in-tet. n is out-tet.
19736 outtet = neightet;
19737 } else {
19738 // n is in-tet. t is out-tet.
19739 outtet = newtet;
19740 }
19741 // Add the out-tet into list.
19742 if (!infected(outtet)) {
19743 infect(outtet);
19744 outtetlist->append(&outtet);
19745 }
19746 }
19747 }
19748 }
19749 }
19750
19751 // Find and mark all out-tets.
19752 for (i = 0; i < outtetlist->len(); i++) {
19753 outtet = * (triface *)(* outtetlist)[i];
19754 for (outtet.loc = 0; outtet.loc < 4; outtet.loc++) {
19755 sym(outtet, neightet);
19756 // Does the neighbor exist and unmarked?
19757 if ((neightet.tet != dummytet) && !infected(neightet)) {
19758 // Is it protected by an aux subface?
19759 tspivot(outtet, auxsh);
19760 if (auxsh.sh == dummysh) {
19761 // It's an out-tet.
19762 infect(neightet);
19763 outtetlist->append(&neightet);
19764 }
19765 }
19766 }
19767 }
19768
19769 // Remove the out- (and hole) tets.
19770 for (i = 0; i < outtetlist->len(); i++) {
19771 // Get an out-tet t.
19772 outtet = * (triface *)(* outtetlist)[i];
19773 // Detach t from the in-tets.
19774 for (outtet.loc = 0; outtet.loc < 4; outtet.loc++) {
19775 // Is there an aux subface s?
19776 tspivot(outtet, auxsh);
19777 if (auxsh.sh != dummysh) {
19778 // Get the neighbor n.
19779 sym(outtet, neightet);
19780 assert(!infected(neightet)); // t must be in-tet.
19781 // Detach n -x-> t.
19782 dissolve(neightet);
19783 }
19784 }
19785 // Dealloc the tet.
19786 tetrahedrondealloc(outtet.tet);
19787 }
19788
19789 // Connect the in-tets of C to fronts. Remove aux subfaces and fake tets.
19790 for (i = 0; i < newtetlist->len(); i++) {
19791 // Get a new tet t.
19792 newtet = * (triface *)(* newtetlist)[i];
19793 // t may be an out-tet and has got deleted.
19794 if (isdead(&newtet)) continue;
19795 // t is an in-tet. Look for aux subfaces attached at t.
19796 for (newtet.loc = 0; newtet.loc < 4; newtet.loc++) {
19797 // Is there an aux subface s?
19798 tspivot(newtet, auxsh);
19799 if (auxsh.sh != dummysh) {
19800 // Get the front f.
19801 decode((tetrahedron) auxsh.sh[0], front);
19802 assert((front.tet != dummytet) && !infected(front));
19803 // s has fulfilled its duty. Can be deleted.
19804 tsdissolve(newtet); // dissolve: t -x-> s.
19805 // Delete s.
19806 shellfacedealloc(subfaces, auxsh.sh);
19807 // Connect the newtet t and front f.
19808 // Is there a concrete subface c at f.
19809 tspivot(front, consh);
19810 if (consh.sh != dummysh) {
19811 sesymself(consh);
19812 // Bond: t <--> c.
19813 tsbond(newtet, consh);
19814 }
19815 // Does f hold by a fake tet.
19816 if (oppo(front) == (point) NULL) {
19817 // f is fake.
19818 if (consh.sh != dummysh) {
19819 sesymself(consh);
19820 // Dissolve: c -x-> f.
19821 stdissolve(consh);
19822 }
19823 // Dealloc f.
19824 tetrahedrondealloc(front.tet);
19825 // f becomes a hull. let 'dummytet' bond to it.
19826 dummytet[0] = encode(newtet);
19827 } else {
19828 // Bond t <--> f.
19829 bond(newtet, front);
19830 }
19831 // t may be non-locally Delaunay and flipable.
19832 if (flipque != (queue *) NULL) {
19833 enqueueflipface(newtet, flipque);
19834 }
19835 }
19836 }
19837 // Let the corners of t2 point to it for fast searching.
19838 pointptr = org(newtet);
19839 setpoint2tet(pointptr, encode(newtet));
19840 pointptr = dest(newtet);
19841 setpoint2tet(pointptr, encode(newtet));
19842 pointptr = apex(newtet);
19843 setpoint2tet(pointptr, encode(newtet));
19844 pointptr = oppo(newtet);
19845 setpoint2tet(pointptr, encode(newtet));
19846 }
19847 // The cavity has been re-tetrahedralized.
19848 }
19849
19850 ///////////////////////////////////////////////////////////////////////////////
19851 // //
19852 // delaunizecavity() Tetrahedralize a cavity by Delaunay tetrahedra. //
19853 // //
19854 // The cavity C is bounded by a set of triangles in 'floorlist' (a list of //
19855 // coplanar subfaces) and 'ceillist' (a list of tetrahedral faces lie above //
19856 // the subfaces). 'floorptlist' and 'ceilptlist' are the vertices of C. //
19857 // //
19858 ///////////////////////////////////////////////////////////////////////////////
19859
19860 void tetgenmesh::delaunizecavity(list* floorlist, list* ceillist,
19861 list* ceilptlist, list* floorptlist, list* frontlist, list* misfrontlist,
19862 list* newtetlist, list* crosstetlist, queue* missingshqueue, queue* flipque)
19863 {
19864 int vertnum;
19865
19866 vertnum = floorptlist->len();
19867 vertnum += (ceilptlist != (list *) NULL ? ceilptlist->len() : 0);
19868 if (b->verbose > 1) {
19869 printf(" Delaunizing cavity (%d floors, %d ceilings, %d vertices).\n",
19870 floorlist->len(), ceillist->len(), vertnum);
19871 }
19872 // Save the size of the largest cavity.
19873 if ((floorlist->len() + ceillist->len()) > maxcavfaces) {
19874 maxcavfaces = floorlist->len() + ceillist->len();
19875 }
19876 if (vertnum > maxcavverts) {
19877 maxcavverts = vertnum;
19878 }
19879
19880 // Clear these lists.
19881 frontlist->clear();
19882 misfrontlist->clear();
19883 newtetlist->clear();
19884
19885 // Initialize the cavity C.
19886 initializecavity(floorlist, ceillist, frontlist);
19887 // Form the D of the vertices of C.
19888 delaunizecavvertices(NULL, floorptlist, ceilptlist, newtetlist, flipque);
19889 // Identify faces of C in D.
19890 while (!identifyfronts(frontlist, misfrontlist, newtetlist)) {
19891 // Remove protecting subfaces, keep new tets.
19892 detachauxsubfaces(newtetlist);
19893 // Expand C and updateing D.
19894 expandcavity(frontlist, misfrontlist, newtetlist, crosstetlist,
19895 missingshqueue, flipque);
19896 }
19897 // All fronts have identified in D. Get the shape of C by removing out
19898 // tets of C. 'misfrontlist' is reused for removing out tets.
19899 carvecavity(newtetlist, misfrontlist, NULL);
19900 }
19901
19902 ///////////////////////////////////////////////////////////////////////////////
19903 // //
19904 // formmissingregion() Form the missing region. //
19905 // //
19906 // 'missingsh' is a missing subface. Start from it we can form the missing //
19907 // region R (a set of connected missing subfaces). Because all missing sub- //
19908 // faces have been marked (infected) before. R can be formed by checking the //
19909 // neighbors of 'missingsh', and the neighbors of the neighbors, and so on. //
19910 // Stop checking further at either a segment or an unmarked subface. //
19911 // //
19912 // 'missingshlist' returns R. The edge ring of subfaces of R are oriented in //
19913 // the same direction. 'equatptlist' returns the vertices of R, each vertex //
19914 // is marked with '1' (in 'worklist'). //
19915 // //
19916 ///////////////////////////////////////////////////////////////////////////////
19917
19918 void tetgenmesh::formmissingregion(face* missingsh, list* missingshlist,
19919 list* equatptlist, int* worklist)
19920 {
19921 face neighsh, worksh, workseg;
19922 point workpt[3];
19923 int idx, i, j;
19924
19925 // Add 'missingsh' into 'missingshlist'.
19926 missingshlist->append(missingsh);
19927 // Save and mark its three vertices.
19928 workpt[0] = sorg(*missingsh);
19929 workpt[1] = sdest(*missingsh);
19930 workpt[2] = sapex(*missingsh);
19931 for (i = 0; i < 3; i++) {
19932 idx = pointmark(workpt[i]) - in->firstnumber;
19933 worklist[idx] = 1;
19934 equatptlist->append(&workpt[i]);
19935 }
19936 // Temporarily uninfect it (avoid to save it again).
19937 suninfect(*missingsh);
19938
19939 // Find the other missing subfaces.
19940 for (i = 0; i < missingshlist->len(); i++) {
19941 // Get a missing subface.
19942 worksh = * (face *)(* missingshlist)[i];
19943 // Check three neighbors of this face.
19944 for (j = 0; j < 3; j++) {
19945 sspivot(worksh, workseg);
19946 if (workseg.sh == dummysh) {
19947 spivot(worksh, neighsh);
19948 if (sinfected(neighsh)) {
19949 // Find a missing subface, adjust the face orientation.
19950 if (sorg(neighsh) != sdest(worksh)) {
19951 sesymself(neighsh);
19952 }
19953 if (b->verbose > 2) {
19954 printf(" Add missing subface (%d, %d, %d).\n",
19955 pointmark(sorg(neighsh)), pointmark(sdest(neighsh)),
19956 pointmark(sapex(neighsh)));
19957 }
19958 missingshlist->append(&neighsh);
19959 // Save and mark its apex.
19960 workpt[0] = sapex(neighsh);
19961 idx = pointmark(workpt[0]) - in->firstnumber;
19962 // Has workpt[0] been added?
19963 if (worklist[idx] == 0) {
19964 worklist[idx] = 1;
19965 equatptlist->append(&workpt[0]);
19966 }
19967 // Temporarily uninfect it (avoid to save it again).
19968 suninfect(neighsh);
19969 }
19970 }
19971 senextself(worksh);
19972 }
19973 }
19974
19975 // R has been formed. Infect missing subfaces again.
19976 for (i = 0; i < missingshlist->len(); i++) {
19977 worksh = * (face *)(* missingshlist)[i];
19978 sinfect(worksh);
19979 }
19980 }
19981
19982 ///////////////////////////////////////////////////////////////////////////////
19983 // //
19984 // rearrangesubfaces() Rearrange the set of subfaces of a missing region //
19985 // so that they conform to the faces of DT. //
19986 // //
19987 // The missing region formed by subfaces of 'missingshlist' contains a set //
19988 // of degenerate vertices, hence the set of subfaces don't match the set of //
19989 // faces in DT. Instead of forcing them to present in DT, we re-arrange the //
19990 // connection of them so that the new subfaces conform to the faces of DT. //
19991 // 'boundedgelist' is a set of boundary edges of the region, these edges(may //
19992 // be subsegments) must exist in DT. //
19993 // //
19994 // On completion, we have created and inserted a set of new subfaces which //
19995 // conform to faces of DT. The set of old subfaces in 'missingshlist' are //
19996 // deleted. The region vertices in 'equatptlist' are unmarked. //
19997 // //
19998 ///////////////////////////////////////////////////////////////////////////////
19999
20000 void tetgenmesh::rearrangesubfaces(list* missingshlist, list* boundedgelist,
20001 list* equatptlist, int* worklist)
20002 {
20003 link *boundedgelink;
20004 link *newshlink;
20005 triface starttet, spintet, neightet, worktet;
20006 face shloop, newsh, neighsh, spinsh, worksh;
20007 face workseg, casingin, casingout;
20008 point torg, tdest, workpt;
20009 point spt1, spt2, spt3;
20010 enum finddirectionresult collinear;
20011 enum shestype shtype;
20012 REAL area;
20013 bool matchflag, finishflag;
20014 int shmark, pbcgp, idx, hitbdry;
20015 int i, j;
20016
20017 // Initialize the boundary edge link.
20018 boundedgelink = new link(sizeof(face), NULL, 256);
20019 // Initialize the new subface link.
20020 newshlink = new link(sizeof(face), NULL, 256);
20021 // Remember the type (skinny or not) of replaced subfaces. They should
20022 // all have the same type since there is no segment inside the region.
20023 worksh = * (face *)(* missingshlist)[0];
20024 shtype = shelltype(worksh);
20025 // The following loop is only for checking purpose.
20026 for (i = 1; i < missingshlist->len(); i++) {
20027 worksh = * (face *)(* missingshlist)[i];
20028 assert(shelltype(worksh) == shtype);
20029 }
20030 // To avoid compilation warnings.
20031 shmark = pbcgp = 0;
20032 area = 0.0;
20033
20034 // Create an initial boundary link.
20035 for (i = 0; i < boundedgelist->len(); i++) {
20036 shloop = * (face *)(* boundedgelist)[i];
20037 if (i == 0) {
20038 // 'shmark' will be set to all new created subfaces.
20039 shmark = shellmark(shloop);
20040 if (b->quality && varconstraint) {
20041 // area will be copied to all new created subfaces.
20042 area = areabound(shloop);
20043 }
20044 if (checkpbcs) {
20045 // pbcgp will be copied to all new created subfaces.
20046 pbcgp = shellpbcgroup(shloop);
20047 }
20048 // Get the abovepoint of this facet.
20049 abovepoint = facetabovepointarray[shellmark(shloop)];
20050 if (abovepoint == (point) NULL) {
20051 getfacetabovepoint(&shloop);
20052 }
20053 }
20054 sspivot(shloop, workseg);
20055 if (workseg.sh == dummysh) {
20056 // This edge is an interior edge.
20057 spivot(shloop, neighsh);
20058 boundedgelink->add(&neighsh);
20059 } else {
20060 // This side has a segment, the edge exists.
20061 boundedgelink->add(&shloop);
20062 }
20063 }
20064
20065 // Each edge ab of boundedgelink will be finished by finding a vertex c
20066 // which is a vertex of the missing region, such that:
20067 // (1) abc is inside the missing region, i.e., abc intersects at least
20068 // one of missing subfaces (saved in missingshlist);
20069 // (2) abc is not intersect with any previously created new subfaces
20070 // in the missing region (saved in newshlink).
20071 // After abc is created, it will be inserted into both the surface mesh
20072 // and the DT. The boundedgelink will be updated, ab is removed, bc and
20073 // ca will be added if they are open.
20074
20075 while (boundedgelink->len() > 0) {
20076 // Remove an edge (ab) from the link.
20077 shloop = * (face *) boundedgelink->del(1);
20078 // 'workseg' indicates it is a segment or not.
20079 sspivot(shloop, workseg);
20080 torg = sorg(shloop); // torg = a;
20081 tdest = sdest(shloop); // tdest = b;
20082 // Find a tetrahedron containing ab.
20083 getsearchtet(torg, tdest, &starttet, &workpt);
20084 collinear = finddirection(&starttet, workpt, tetrahedrons->items);
20085 if (collinear == LEFTCOLLINEAR) {
20086 enext2self(starttet);
20087 esymself(starttet);
20088 } else if (collinear == TOPCOLLINEAR) {
20089 fnextself(starttet);
20090 enext2self(starttet);
20091 esymself(starttet);
20092 }
20093 assert(dest(starttet) == workpt);
20094 // Checking faces around ab until a valid face is found.
20095 matchflag = false;
20096 spintet = starttet;
20097 hitbdry = 0;
20098 do {
20099 workpt = apex(spintet);
20100 idx = pointmark(workpt) - in->firstnumber;
20101 if (worklist[idx] == 1) {
20102 // (trog, tdest, workpt) is on the facet. Check if it satisfies (1).
20103 finishflag = false;
20104 for (i = 0; i < missingshlist->len(); i++) {
20105 worksh = * (face *)(* missingshlist)[i];
20106 spt1 = sorg(worksh);
20107 spt2 = sdest(worksh);
20108 spt3 = sapex(worksh);
20109 // Does bc intersect the face?
20110 if (tri_edge_cop_inter(spt1, spt2, spt3, tdest, workpt, abovepoint)
20111 == INTERSECT) {
20112 finishflag = true; break;
20113 }
20114 // Does ca intersect the face?
20115 if (tri_edge_cop_inter(spt1, spt2, spt3, workpt, torg, abovepoint)
20116 == INTERSECT) {
20117 finishflag = true; break;
20118 }
20119 // Does c inside the face?
20120 if (tri_vert_cop_inter(spt1, spt2, spt3, workpt, abovepoint)
20121 == INTERSECT) {
20122 finishflag = true; break;
20123 }
20124 }
20125 if (finishflag) {
20126 // Satisfying (1). Check if it satisfies (2).
20127 matchflag = true;
20128 for (i = 0; i < newshlink->len() && matchflag; i++) {
20129 worksh = * (face *) newshlink->getnitem(i + 1);
20130 spt1 = sorg(worksh);
20131 spt2 = sdest(worksh);
20132 spt3 = sapex(worksh);
20133 // Does bc intersect the face?
20134 if (tri_edge_cop_inter(spt1, spt2, spt3, tdest, workpt, abovepoint)
20135 == INTERSECT) {
20136 matchflag = false; break;
20137 }
20138 // Does ca intersect the face?
20139 if (tri_edge_cop_inter(spt1, spt2, spt3, workpt, torg, abovepoint)
20140 == INTERSECT) {
20141 matchflag = false; break;
20142 }
20143 // Does c inside the face?
20144 if (tri_vert_cop_inter(spt1, spt2, spt3, workpt, abovepoint)
20145 == INTERSECT) {
20146 matchflag = false; break;
20147 }
20148 }
20149 }
20150 if (matchflag == true) {
20151 // Satisfying both (1) and (2). Find abc.
20152 break;
20153 }
20154 }
20155 if (!fnextself(spintet)) {
20156 hitbdry ++;
20157 if (hitbdry < 2) {
20158 esym(starttet, spintet);
20159 if (!fnextself(spintet)) {
20160 hitbdry ++;
20161 }
20162 }
20163 }
20164 } while (hitbdry < 2 && apex(spintet) != apex(starttet));
20165 assert(matchflag == true);
20166 tspivot(spintet, neighsh);
20167 if (neighsh.sh != dummysh) {
20168 printf("Error: Invalid PLC.\n");
20169 printf(" Facet #%d and facet #%d overlap each other.\n",
20170 shellmark(neighsh), shellmark(shloop));
20171 printf(" It might be caused by a facet is defined more than once.\n");
20172 printf(" Hint: Use -d switch to find all overlapping facets.\n");
20173 exit(1);
20174 }
20175 // The side of 'spintet' is at which a new subface will be attached.
20176 adjustedgering(spintet, CCW);
20177 // Create the new subface.
20178 makeshellface(subfaces, &newsh);
20179 setsorg(newsh, org(spintet));
20180 setsdest(newsh, dest(spintet));
20181 setsapex(newsh, apex(spintet));
20182 if (b->quality && varconstraint) {
20183 setareabound(newsh, area);
20184 }
20185 if (checkpbcs) {
20186 setshellpbcgroup(newsh, pbcgp);
20187 }
20188 setshellmark(newsh, shmark);
20189 setshelltype(newsh, shtype); // It may be a skinny subface.
20190 // Add newsh into newshlink for intersecting checking.
20191 newshlink->add(&newsh);
20192 // Insert it into the current mesh.
20193 tsbond(spintet, newsh);
20194 sym(spintet, neightet);
20195 if (neightet.tet != dummytet) {
20196 sesym(newsh, neighsh);
20197 tsbond(neightet, neighsh);
20198 }
20199 // Insert it into the surface mesh.
20200 sspivot(shloop, workseg);
20201 if (workseg.sh == dummysh) {
20202 sbond(shloop, newsh);
20203 } else {
20204 // There is a subsegment, 'shloop' is the subface which is going to
20205 // die. Insert the 'newsh' at the place of 'shloop' into its face
20206 // link, so as to dettach 'shloop'. The original connection is:
20207 // -> casingin -> shloop -> casingout ->, it will be changed with:
20208 // -> casingin -> newsh -> casingout ->. Pay attention to the
20209 // case when this subsegment is dangling in the mesh, i.e., 'shloop'
20210 // is bonded to itself.
20211 spivot(shloop, casingout);
20212 if (shloop.sh != casingout.sh) {
20213 // 'shloop' is not bonded to itself.
20214 spinsh = casingout;
20215 do {
20216 casingin = spinsh;
20217 spivotself(spinsh);
20218 } while (sapex(spinsh) != sapex(shloop));
20219 assert(casingin.sh != shloop.sh);
20220 // Bond casingin -> newsh -> casingout.
20221 sbond1(casingin, newsh);
20222 sbond1(newsh, casingout);
20223 } else {
20224 // Bond newsh -> newsh.
20225 sbond(newsh, newsh);
20226 }
20227 // Bond the segment.
20228 ssbond(newsh, workseg);
20229 }
20230 // Check other two sides of this new subface. If a side is not bonded
20231 // to any edge in the link, it will be added to the link.
20232 for (i = 0; i < 2; i++) {
20233 if (i == 0) {
20234 senext(newsh, worksh);
20235 } else {
20236 senext2(newsh, worksh);
20237 }
20238 torg = sorg(worksh);
20239 tdest = sdest(worksh);
20240 finishflag = false;
20241 for (j = 0; j < boundedgelink->len() && !finishflag; j++) {
20242 neighsh = * (face *) boundedgelink->getnitem(j + 1);
20243 if ((sorg(neighsh) == torg && sdest(neighsh) == tdest) ||
20244 (sorg(neighsh) == tdest && sdest(neighsh) == torg)) {
20245 // Find a boundary edge. Bond them and exit the loop.
20246 sspivot(neighsh, workseg);
20247 if (workseg.sh == dummysh) {
20248 sbond(neighsh, worksh);
20249 } else {
20250 // There is a subsegment, 'neighsh' is the subface which is
20251 // going to die. Do the same as above for 'worksh'.
20252 spivot(neighsh, casingout);
20253 if (neighsh.sh != casingout.sh) {
20254 // 'neighsh' is not bonded to itself.
20255 spinsh = casingout;
20256 do {
20257 casingin = spinsh;
20258 spivotself(spinsh);
20259 } while (sapex(spinsh) != sapex(neighsh));
20260 assert(casingin.sh != neighsh.sh);
20261 // Bond casingin -> worksh -> casingout.
20262 sbond1(casingin, worksh);
20263 sbond1(worksh, casingout);
20264 } else {
20265 // Bond worksh -> worksh.
20266 sbond(worksh, worksh);
20267 }
20268 // Bond the segment.
20269 ssbond(worksh, workseg);
20270 }
20271 // Remove this boundary edge from the link.
20272 boundedgelink->del(j + 1);
20273 finishflag = true;
20274 }
20275 }
20276 if (!finishflag) {
20277 // It's a new boundary edge, add it to link.
20278 boundedgelink->add(&worksh);
20279 }
20280 }
20281 }
20282
20283 // Deallocate the set of old missing subfaces.
20284 for (i = 0; i < missingshlist->len(); i++) {
20285 worksh = * (face *)(* missingshlist)[i];
20286 shellfacedealloc(subfaces, worksh.sh);
20287 }
20288 // Unmark region vertices in 'worklist'.
20289 for (i = 0; i < equatptlist->len(); i++) {
20290 workpt = * (point *)(* equatptlist)[i];
20291 idx = pointmark(workpt) - in->firstnumber;
20292 worklist[idx] = 0;
20293 }
20294
20295 delete boundedgelink;
20296 delete newshlink;
20297 }
20298
20299 ///////////////////////////////////////////////////////////////////////////////
20300 // //
20301 // scoutcrossingedge() Search an edge crossing the missing region. //
20302 // //
20303 // 'missingshlist' forms the missing region R. This routine searches for an //
20304 // edge crossing R. It first forms a 'boundedgelist' consisting of the //
20305 // boundary edges of R. Such edges are existing in CDT. A crossing edge is //
20306 // found by rotating faces around one of the boundary edges. It is possible //
20307 // there is no edge crosses R (e.g. R has a degenerate point set). //
20308 // //
20309 // If find a croosing edge, return TRUE, 'crossedgelist' contains this edge. //
20310 // Otherwise, return FALSE. //
20311 // //
20312 ///////////////////////////////////////////////////////////////////////////////
20313
20314 bool tetgenmesh::scoutcrossingedge(list* missingshlist, list* boundedgelist,
20315 list* crossedgelist, int* worklist)
20316 {
20317 triface starttet, spintet, worktet;
20318 face startsh, neighsh, worksh, workseg;
20319 point torg, tdest, tapex;
20320 point workpt[3], pa, pb, pc;
20321 enum finddirectionresult collinear;
20322 REAL ori1, ori2;
20323 bool crossflag;
20324 int hitbdry;
20325 int i, j, k;
20326
20327 // Form the 'boundedgelist'. Loop through 'missingshlist', check each
20328 // edge of these subfaces. If an edge is a segment or the neighbor
20329 // subface is uninfected, add it to 'boundedgelist'.
20330 for (i = 0; i < missingshlist->len(); i++) {
20331 worksh = * (face *)(* missingshlist)[i];
20332 for (j = 0; j < 3; j++) {
20333 sspivot(worksh, workseg);
20334 if (workseg.sh == dummysh) {
20335 spivot(worksh, neighsh);
20336 if (!sinfected(neighsh)) {
20337 boundedgelist->append(&worksh);
20338 }
20339 } else {
20340 boundedgelist->append(&worksh);
20341 }
20342 senextself(worksh);
20343 }
20344 }
20345
20346 crossflag = false;
20347 // Find a crossing edge. It is possible there is no such edge. We need to
20348 // loop through all edges of 'boundedgelist' for sure we don't miss any.
20349 for (i = 0; i < boundedgelist->len() && !crossflag; i++) {
20350 startsh = * (face *)(* boundedgelist)[i];
20351 // 'startsh' (abc) holds an existing edge of the DT, find it.
20352 torg = sorg(startsh);
20353 tdest = sdest(startsh);
20354 tapex = sapex(startsh);
20355 getsearchtet(torg, tdest, &starttet, &workpt[0]);
20356 collinear = finddirection(&starttet, workpt[0], tetrahedrons->items);
20357 if (collinear == LEFTCOLLINEAR) {
20358 enext2self(starttet);
20359 esymself(starttet);
20360 } else if (collinear == TOPCOLLINEAR) {
20361 fnextself(starttet);
20362 enext2self(starttet);
20363 esymself(starttet);
20364 }
20365 #ifdef SELF_CHECK
20366 assert(dest(starttet) == workpt[0]);
20367 #endif
20368 // Now starttet holds edge ab. Find is edge de crossing R.
20369 spintet = starttet;
20370 hitbdry = 0;
20371 do {
20372 if (fnextself(spintet)) {
20373 // splittet = abde. Check if de crosses abc.
20374 workpt[1] = apex(spintet); // workpt[1] = d.
20375 workpt[2] = oppo(spintet); // workpt[2] = e.
20376 j = pointmark(workpt[1]) - in->firstnumber;
20377 k = pointmark(workpt[2]) - in->firstnumber;
20378 if (worklist[j] == 1) {
20379 ori1 = 0.0; // d is a vertex of the missing region.
20380 } else {
20381 // Get the orientation of d wrt. abc.
20382 ori1 = orient3d(torg, tdest, tapex, workpt[1]);
20383 }
20384 if (worklist[k] == 1) {
20385 ori2 = 0.0; // e is a vertex of the missing region.
20386 } else {
20387 // Get the orientation of e wrt. abc.
20388 ori2 = orient3d(torg, tdest, tapex, workpt[2]);
20389 }
20390 // Only do check if d and e locate on different sides of abc.
20391 if (ori1 * ori2 < 0.0) {
20392 // Check if de crosses any subface of R.
20393 for (j = 0; j < missingshlist->len(); j++) {
20394 worksh = * (face *)(* missingshlist)[j];
20395 pa = sorg(worksh);
20396 pb = sdest(worksh);
20397 pc = sapex(worksh);
20398 crossflag = (tri_tri_inter(pa, pb, pc, workpt[0], workpt[1],
20399 workpt[2]) == INTERSECT);
20400 if (crossflag) {
20401 // Find a crossing edge. We're done.
20402 worktet = spintet;
20403 adjustedgering(worktet, CCW);
20404 enextfnextself(worktet);
20405 enextself(worktet);
20406 // Add this edge (worktet) into 'crossedgelist'.
20407 crossedgelist->append(&worktet);
20408 break;
20409 }
20410 }
20411 if (crossflag) break;
20412 }
20413 if (apex(spintet) == apex(starttet)) break;
20414 } else {
20415 hitbdry++;
20416 // It is only possible to hit boundary once.
20417 if (hitbdry < 2) {
20418 esym(starttet, spintet);
20419 }
20420 }
20421 } while (hitbdry < 2);
20422 }
20423
20424 return crossflag;
20425 }
20426
20427 ///////////////////////////////////////////////////////////////////////////////
20428 // //
20429 // formcavity() Form the cavity for recovering the missing region. //
20430 // //
20431 // The cavity C is bounded by faces of current CDT. All tetrahedra inside C //
20432 // will be removed, intead a set of constrained Delaunay tetrahedra will be //
20433 // filled in and the missing region are recovered. //
20434 // //
20435 // 'missingshlist' contains a set of subfaces forming the missing region R. //
20436 // C is formed by first finding all the tetrahedra in CDT that intersect the //
20437 // relative interior of R; then deleting them from the CDT, this will form C //
20438 // inside the CDT. At the beginning, 'crossedgelist' contains an edge which //
20439 // is crossing R. All tets containing this edge must cross R. Start from it, //
20440 // other crossing edges can be found incrementally. The discovered crossing //
20441 // tets are saved in 'crosstetlist'. //
20442 // //
20443 // Notice that not all tets in 'crosstetlist' are crossing R. The discovered //
20444 // tets are connected each other. However, there may be other tets crossing //
20445 // R but disjoint with the found tets. Due to this fact we need to check the //
20446 // 'missingshlist' once more. Only recover those subfaces which are crossed //
20447 // by the set of discovered tets, i.e., R may be shrinked to conform the set //
20448 // of discovered tets. The extra subfaces of R will be recovered later. //
20449 // //
20450 // Notice that some previous recovered subfaces may completely included in C.//
20451 // This can happen when R is very big and these subfaces lie above R and so //
20452 // close to it. Such subfaces have to be queued (and sinfected()) to recover //
20453 // them later. Otherwise, we lost the connection to these subfaces forever. //
20454 // //
20455 ///////////////////////////////////////////////////////////////////////////////
20456
20457 void tetgenmesh::formcavity(list* missingshlist, list* crossedgelist,
20458 list* equatptlist, list* crossshlist, list* crosstetlist,
20459 list* belowfacelist, list* abovefacelist, list* horizptlist,
20460 list* belowptlist, list* aboveptlist, queue* missingshqueue, int* worklist)
20461 {
20462 triface starttet, spintet, neightet, worktet;
20463 face startsh, neighsh, worksh, workseg;
20464 point torg, tdest, tapex, workpt[3];
20465 REAL checksign, orgori, destori;
20466 bool crossflag, inlistflag;
20467 bool belowflag, aboveflag;
20468 int idx, share;
20469 int i, j, k;
20470
20471 // Get a face at horizon.
20472 startsh = * (face *)(* missingshlist)[0];
20473 torg = sorg(startsh);
20474 tdest = sdest(startsh);
20475 tapex = sapex(startsh);
20476
20477 // Collect the set of crossing tetrahedra by rotating crossing edges.
20478 for (i = 0; i < crossedgelist->len(); i++) {
20479 // Get a tet abcd, ab is a crossing edge.
20480 starttet = * (triface *)(* crossedgelist)[i];
20481 adjustedgering(starttet, CCW);
20482 if (b->verbose > 2) {
20483 printf(" Collect tets containing edge (%d, %d).\n",
20484 pointmark(org(starttet)), pointmark(dest(starttet)));
20485 }
20486 orgori = orient3d(torg, tdest, tapex, org(starttet));
20487 destori = orient3d(torg, tdest, tapex, dest(starttet));
20488 #ifdef SELF_CHECK
20489 assert(orgori * destori < 0.0);
20490 #endif
20491 spintet = starttet;
20492 do {
20493 // The face rotation should not meet boundary.
20494 fnextself(spintet);
20495 // Check the validity of the PLC.
20496 tspivot(spintet, worksh);
20497 if (worksh.sh != dummysh) {
20498 printf("Error: Invalid PLC.\n");
20499 printf(" Two subfaces (%d, %d, %d) and (%d, %d, %d)\n",
20500 pointmark(torg), pointmark(tdest), pointmark(tapex),
20501 pointmark(sorg(worksh)), pointmark(sdest(worksh)),
20502 pointmark(sapex(worksh)));
20503 printf(" are found intersecting each other.\n");
20504 printf(" Hint: Use -d switch to find all intersecting facets.\n");
20505 terminatetetgen(1);
20506 }
20507 if (!infected(spintet)) {
20508 if (b->verbose > 2) {
20509 printf(" Add crossing tet (%d, %d, %d, %d).\n",
20510 pointmark(org(spintet)), pointmark(dest(spintet)),
20511 pointmark(apex(spintet)), pointmark(oppo(spintet)));
20512 }
20513 infect(spintet);
20514 crosstetlist->append(&spintet);
20515 }
20516 // Check whether other two edges of 'spintet' is a crossing edge.
20517 // It can be quickly checked from the apex of 'spintet', if it is
20518 // not on the facet, then there exists a crossing edge.
20519 workpt[0] = apex(spintet);
20520 idx = pointmark(workpt[0]) - in->firstnumber;
20521 if (worklist[idx] != 1) {
20522 // Either edge (dest, apex) or edge (apex, org) crosses.
20523 checksign = orient3d(torg, tdest, tapex, workpt[0]);
20524 #ifdef SELF_CHECK
20525 assert(checksign != 0.0);
20526 #endif
20527 if (checksign * orgori < 0.0) {
20528 enext2(spintet, worktet); // edge (apex, org).
20529 workpt[1] = org(spintet);
20530 } else {
20531 #ifdef SELF_CHECK
20532 assert(checksign * destori < 0.0);
20533 #endif
20534 enext(spintet, worktet); // edge (dest, apex).
20535 workpt[1] = dest(spintet);
20536 }
20537 // 'worktet' represents the crossing edge. Add it into list only
20538 // it doesn't exist in 'crossedgelist'.
20539 inlistflag = false;
20540 for (j = 0; j < crossedgelist->len() && !inlistflag; j++) {
20541 neightet = * (triface *)(* crossedgelist)[j];
20542 if (org(neightet) == workpt[0]) {
20543 if (dest(neightet) == workpt[1]) inlistflag = true;
20544 } else if (org(neightet) == workpt[1]) {
20545 if (dest(neightet) == workpt[0]) inlistflag = true;
20546 }
20547 }
20548 if (!inlistflag) {
20549 crossedgelist->append(&worktet);
20550 }
20551 }
20552 } while (apex(spintet) != apex(starttet));
20553 }
20554
20555 // Identifying the boundary faces and vertices of C. Sort them into
20556 // 'abovefacelist', 'aboveptlist, 'belowfacelist', and 'belowptlist',
20557 // respectively. "above" and "below" are wrt.(torg, tdest, tapex).
20558 for (i = 0; i < crosstetlist->len(); i++) {
20559 // Get a tet abcd, ab is the crossing edge.
20560 starttet = * (triface *)(* crosstetlist)[i];
20561 #ifdef SELF_CHECK
20562 assert(infected(starttet));
20563 #endif
20564 adjustedgering(starttet, CCW);
20565 // abc and abd are sharing the crossing edge, the two neighbors must
20566 // be crossing tetrahedra too. They can't be boundaries of C.
20567 for (j = 0; j < 2; j++) {
20568 if (j == 0) {
20569 enextfnext(starttet, worktet); // Check bcd.
20570 } else {
20571 enext2fnext(starttet, worktet); // Check acd.
20572 }
20573 sym(worktet, neightet);
20574 // If the neighbor doesn't exist or exists but doesn't be infected,
20575 // it's a boundary face of C, save it.
20576 if ((neightet.tet == dummytet) || !infected(neightet)) {
20577 workpt[0] = org(worktet);
20578 workpt[1] = dest(worktet);
20579 workpt[2] = apex(worktet);
20580 belowflag = aboveflag = false;
20581 share = 0;
20582 for (k = 0; k < 3; k++) {
20583 idx = pointmark(workpt[k]) - in->firstnumber;
20584 if (worklist[idx] == 0) {
20585 // It's not a vertices of facet, find which side it lies.
20586 checksign = orient3d(torg, tdest, tapex, workpt[k]);
20587 #ifdef SELF_CHECK
20588 assert(checksign != 0.0);
20589 #endif
20590 if (checksign > 0.0) {
20591 // It lies "below" the facet wrt. 'startsh'.
20592 worklist[idx] = 2;
20593 belowptlist->append(&workpt[k]);
20594 } else if (checksign < 0.0) {
20595 // It lies "above" the facet wrt. 'startsh'.
20596 worklist[idx] = 3;
20597 aboveptlist->append(&workpt[k]);
20598 }
20599 }
20600 if (worklist[idx] == 2) {
20601 // This face lies "below" the facet wrt. 'startsh'.
20602 belowflag = true;
20603 } else if (worklist[idx] == 3) {
20604 // This face lies "above" the facet wrt. 'startsh'.
20605 aboveflag = true;
20606 } else {
20607 #ifdef SELF_CHECK
20608 // In degenerate case, this face may just be the equator.
20609 assert(worklist[idx] == 1);
20610 #endif
20611 share++;
20612 }
20613 }
20614 #ifdef SELF_CHECK
20615 // The degenerate case has been ruled out.
20616 assert(share < 3);
20617 // Only one flag is possible for a cavity face.
20618 assert(belowflag ^ aboveflag);
20619 #endif
20620 if (belowflag) {
20621 belowfacelist->append(&worktet);
20622 } else if (aboveflag) {
20623 abovefacelist->append(&worktet);
20624 }
20625 }
20626 }
20627 }
20628
20629 // Shrink R if not all its subfaces are crossing by the discovered tets.
20630 // 'crossshlist' and 'horizptlist' represent the set of subfaces and
20631 // vertices of the shrinked missing region, respectively.
20632 for (i = 0; i < missingshlist->len(); i++) {
20633 worksh = * (face *)(* missingshlist)[i];
20634 #ifdef SELF_CHECK
20635 assert(sinfected(worksh));
20636 #endif
20637 workpt[0] = sorg(worksh);
20638 workpt[1] = sdest(worksh);
20639 workpt[2] = sapex(worksh);
20640 crossflag = false;
20641 for (j = 0; j < crosstetlist->len() && !crossflag; j++) {
20642 // Get a tet abcd, ab is a crossing edge.
20643 starttet = * (triface *)(* crosstetlist)[j];
20644 adjustedgering(starttet, CCW);
20645 // Only need to check two sides of worktet.
20646 for (k = 0; k < 2 && !crossflag; k++) {
20647 if (k == 0) {
20648 worktet = starttet; // Check abc.
20649 } else {
20650 fnext(starttet, worktet); // Check abd.
20651 }
20652 crossflag = tritritest(&worktet, workpt[0], workpt[1], workpt[2]);
20653 }
20654 }
20655 if (crossflag) {
20656 // 'worksh' is crossed by 'worktet', uninfect it.
20657 suninfect(worksh);
20658 crossshlist->append(&worksh);
20659 // Add its corners into 'horizptlist'.
20660 for (k = 0; k < 3; k++) {
20661 idx = pointmark(workpt[k]) - in->firstnumber;
20662 if (worklist[idx] != 4) {
20663 worklist[idx] = 4;
20664 horizptlist->append(&workpt[k]);
20665 }
20666 }
20667 }
20668 }
20669
20670 // Check 'crossingtetlist'. Queue subfaces inside them.
20671 for (i = 0; i < crosstetlist->len(); i++) {
20672 starttet = * (triface *)(* crosstetlist)[i];
20673 for (starttet.loc = 0; starttet.loc < 4; starttet.loc++) {
20674 sym(starttet, neightet);
20675 // If the neighbor exist and is infected, check it.
20676 if ((neightet.tet != dummytet) && infected(neightet)) {
20677 tspivot(starttet, worksh);
20678 if (worksh.sh != dummysh) {
20679 // Temporarily remove worksh. Make it missing. recover it later.
20680 if (b->verbose > 2) {
20681 printf(" Queuing subface (%d, %d, %d).\n",
20682 pointmark(sorg(worksh)), pointmark(sdest(worksh)),
20683 pointmark(sapex(worksh)));
20684 }
20685 tsdissolve(neightet);
20686 tsdissolve(starttet);
20687 // Detach tets at the both sides of this subface.
20688 stdissolve(worksh);
20689 sesymself(worksh);
20690 stdissolve(worksh);
20691 sinfect(worksh);
20692 missingshqueue->push(&worksh);
20693 }
20694 }
20695 }
20696 }
20697
20698 // Clear flags set in 'worklist'.
20699 for (i = 0; i < equatptlist->len(); i++) {
20700 workpt[0] = * (point *)(* equatptlist)[i];
20701 idx = pointmark(workpt[0]) - in->firstnumber;
20702 #ifdef SELF_CHECK
20703 assert((worklist[idx] == 1) || (worklist[idx] == 4));
20704 #endif
20705 worklist[idx] = 0;
20706 }
20707 for (i = 0; i < belowptlist->len(); i++) {
20708 workpt[0] = * (point *)(* belowptlist)[i];
20709 idx = pointmark(workpt[0]) - in->firstnumber;
20710 #ifdef SELF_CHECK
20711 assert(worklist[idx] == 2);
20712 #endif
20713 worklist[idx] = 0;
20714 }
20715 for (i = 0; i < aboveptlist->len(); i++) {
20716 workpt[0] = * (point *)(* aboveptlist)[i];
20717 idx = pointmark(workpt[0]) - in->firstnumber;
20718 #ifdef SELF_CHECK
20719 assert(worklist[idx] == 3);
20720 #endif
20721 worklist[idx] = 0;
20722 }
20723 }
20724
20725 ///////////////////////////////////////////////////////////////////////////////
20726 // //
20727 // insertallsubfaces() Insert all subfaces, queue missing subfaces. //
20728 // //
20729 // Loop through all subfaces, insert each into the DT. If one already exists,//
20730 // bond it to the tetrahedra having it. Otherwise, it is missing, infect it //
20731 // and save it in 'missingshqueue'. //
20732 // //
20733 ///////////////////////////////////////////////////////////////////////////////
20734
20735 void tetgenmesh::insertallsubfaces(queue* missingshqueue)
20736 {
20737 triface searchtet;
20738 face subloop;
20739
20740 searchtet.tet = (tetrahedron *) NULL;
20741 subfaces->traversalinit();
20742 subloop.sh = shellfacetraverse(subfaces);
20743 while (subloop.sh != (shellface *) NULL) {
20744 if (!insertsubface(&subloop, &searchtet)) {
20745 if (b->verbose > 1) {
20746 printf(" Queuing subface (%d, %d, %d).\n", pointmark(sorg(subloop)),
20747 pointmark(sdest(subloop)), pointmark(sapex(subloop)));
20748 }
20749 sinfect(subloop);
20750 missingshqueue->push(&subloop);
20751 }
20752 subloop.sh = shellfacetraverse(subfaces);
20753 }
20754 }
20755
20756 ///////////////////////////////////////////////////////////////////////////////
20757 // //
20758 // constrainedfacets() Recover subfaces in a Delaunay tetrahedralization. //
20759 // //
20760 // This routine creates a CDT by incrementally updating a DT D into a CDT T. //
20761 // The process of recovering facets can be imagined by "merging" the surface //
20762 // mesh F into D. At the beginning, F and D are completely seperated. Some //
20763 // faces of them are matching some are not because they are crossed by some //
20764 // tetrahedra of D. The non-matching subfaces will be forced to appear in T //
20765 // by locally retetrahedralizing the regions where F and D are intersecting. //
20766 // //
20767 // When a subface s of F is found missing in D, probably some other subfaces //
20768 // near to s are missing too. The set of adjoining coplanar missing faces //
20769 // forms a missing region R (R may not simply connected). //
20770 // //
20771 // There are two possibilities can result a mssing region R: (1) Some edges //
20772 // of D cross R; (2) No edge of D crosses R, but some faces of D spans R, ie,//
20773 // D is locally degenerate at R. In case (1), D is modified so that it resp- //
20774 // ects R (done by a cavity retetrahedralization algorithm). In case (2), F //
20775 // is modified so that the set of subfaces of R matches faces in D (done by //
20776 // a face rearrangment algorithm). //
20777 // //
20778 ///////////////////////////////////////////////////////////////////////////////
20779
20780 void tetgenmesh::constrainedfacets()
20781 {
20782 queue *missingshqueue, *flipque;
20783 list *missingshlist, *equatptlist;
20784 list *boundedgelist, *crossedgelist, *crosstetlist;
20785 list *crossshlist, *belowfacelist, *abovefacelist;
20786 list *horizptlist, *belowptlist, *aboveptlist;
20787 list *frontlist, *misfrontlist, *newtetlist;
20788 triface searchtet, worktet;
20789 face subloop, worksh;
20790 int *worklist;
20791 int i;
20792
20793 if (!b->quiet) {
20794 printf("Constraining facets.\n");
20795 }
20796
20797 // Initialize queues.
20798 missingshqueue = new queue(sizeof(face));
20799 flipque = new queue(sizeof(badface));
20800 // Initialize the working lists.
20801 missingshlist = new list(sizeof(face), NULL);
20802 boundedgelist = new list(sizeof(face), NULL);
20803 crossedgelist = new list(sizeof(triface), NULL);
20804 equatptlist = new list("point *");
20805 crossshlist = new list(sizeof(face), NULL);
20806 crosstetlist = new list(sizeof(triface), NULL);
20807 belowfacelist = new list(sizeof(triface), NULL);
20808 abovefacelist = new list(sizeof(triface), NULL);
20809 horizptlist = new list("point *");
20810 belowptlist = new list("point *");
20811 aboveptlist = new list("point *");
20812 frontlist = new list(sizeof(triface), NULL);
20813 misfrontlist = new list(sizeof(triface), NULL);
20814 newtetlist = new list(sizeof(triface), NULL);
20815 // Initialize the array for marking vertices.
20816 worklist = new int[points->items + 1];
20817 for (i = 0; i < points->items + 1; i++) worklist[i] = 0;
20818
20819 // Compute a mapping from points to tetrahedra for fast searching.
20820 makepoint2tetmap();
20821
20822 // Match subfaces in D, queue all missing subfaces.
20823 insertallsubfaces(missingshqueue);
20824
20825 // Recover all missing subfaces.
20826 while (!missingshqueue->empty()) {
20827 // Get a queued face s.
20828 subloop = * (face *) missingshqueue->pop();
20829 // s may have been deleted in a face rearrangment operation.
20830 if (isdead(&subloop)) continue;
20831 // s may have been recovered in a previous missing region.
20832 if (!sinfected(subloop)) continue;
20833 // s may match a face in D now due to previous transformations.
20834 if (insertsubface(&subloop, &searchtet)) {
20835 suninfect(subloop);
20836 continue;
20837 }
20838 if (b->verbose > 1) {
20839 printf(" Recover subface (%d, %d, %d).\n", pointmark(sorg(subloop)),
20840 pointmark(sdest(subloop)), pointmark(sapex(subloop)));
20841 }
20842 // Form the missing region R containing s.
20843 formmissingregion(&subloop, missingshlist, equatptlist, worklist);
20844 // Is R crossing by any tetrahedron?
20845 if (scoutcrossingedge(missingshlist, boundedgelist, crossedgelist,
20846 worklist)) {
20847 // Form the cavity C containing R.
20848 formcavity(missingshlist, crossedgelist, equatptlist, crossshlist,
20849 crosstetlist, belowfacelist, abovefacelist, horizptlist,
20850 belowptlist, aboveptlist, missingshqueue, worklist);
20851 // Recover the above part of C.
20852 delaunizecavity(crossshlist, abovefacelist, aboveptlist, horizptlist,
20853 frontlist, misfrontlist, newtetlist, crosstetlist,
20854 missingshqueue, flipque);
20855 // Inverse the direction of subfaces in R.
20856 for (i = 0; i < crossshlist->len(); i++) {
20857 worksh = * (face *)(* crossshlist)[i];
20858 sesymself(worksh);
20859 * (face *)(* crossshlist)[i] = worksh;
20860 }
20861 // Recover the below part of C.
20862 delaunizecavity(crossshlist, belowfacelist, belowptlist, horizptlist,
20863 frontlist, misfrontlist, newtetlist, crosstetlist,
20864 missingshqueue, flipque);
20865 // Delete tetrahedra in C.
20866 for (i = 0; i < crosstetlist->len(); i++) {
20867 worktet = * (triface *)(* crosstetlist)[i];
20868 tetrahedrondealloc(worktet.tet);
20869 }
20870 // There may have some un-recovered subfaces of R. Put them back into
20871 // queue. Otherwise, they will be missing on the boundary.
20872 for (i = 0; i < missingshlist->len(); i++) {
20873 worksh = * (face *)(* missingshlist)[i];
20874 if (sinfected(worksh)) {
20875 // An unrecovered subface, put it back into queue.
20876 missingshqueue->push(&worksh);
20877 }
20878 }
20879 crossshlist->clear();
20880 belowfacelist->clear();
20881 abovefacelist->clear();
20882 horizptlist->clear();
20883 belowptlist->clear();
20884 aboveptlist->clear();
20885 crosstetlist->clear();
20886 } else {
20887 // No. Rearrange subfaces of F conforming to that of D in R. It can
20888 // happen when the facet has non-coplanar vertices.
20889 rearrangesubfaces(missingshlist, boundedgelist, equatptlist, worklist);
20890 }
20891 // Clear all working lists.
20892 missingshlist->clear();
20893 boundedgelist->clear();
20894 crossedgelist->clear();
20895 equatptlist->clear();
20896 }
20897
20898 // Subfaces have been merged into D.
20899 checksubfaces = 1;
20900
20901 if (b->verbose > 0) {
20902 printf(" The biggest cavity: %d faces, %d vertices\n", maxcavfaces,
20903 maxcavverts);
20904 printf(" Enlarged %d times\n", expcavcount);
20905 }
20906
20907 delete missingshqueue;
20908 delete flipque;
20909 delete missingshlist;
20910 delete boundedgelist;
20911 delete crossedgelist;
20912 delete equatptlist;
20913 delete crossshlist;
20914 delete crosstetlist;
20915 delete belowfacelist;
20916 delete abovefacelist;
20917 delete horizptlist;
20918 delete belowptlist;
20919 delete aboveptlist;
20920 delete frontlist;
20921 delete misfrontlist;
20922 delete newtetlist;
20923 delete [] worklist;
20924 }
20925
20926 //
20927 // End of facet recovery routines
20928 //
20929
20930 //
20931 // Begin of carving out holes and concavities routines
20932 //
20933
20934 ///////////////////////////////////////////////////////////////////////////////
20935 // //
20936 // infecthull() Virally infect all of the tetrahedra of the convex hull //
20937 // that are not protected by subfaces. Where there are //
20938 // subfaces, set boundary markers as appropriate. //
20939 // //
20940 // Memorypool 'viri' is used to return all the infected tetrahedra. //
20941 // //
20942 ///////////////////////////////////////////////////////////////////////////////
20943
20944 void tetgenmesh::infecthull(memorypool *viri)
20945 {
20946 triface tetloop, tsymtet;
20947 tetrahedron **deadtet;
20948 face hullface;
20949 // point horg, hdest, hapex;
20950
20951 if (b->verbose > 0) {
20952 printf(" Marking concavities for elimination.\n");
20953 }
20954 tetrahedrons->traversalinit();
20955 tetloop.tet = tetrahedrontraverse();
20956 while (tetloop.tet != (tetrahedron *) NULL) {
20957 // Is this tetrahedron on the hull?
20958 for (tetloop.loc = 0; tetloop.loc < 4; tetloop.loc++) {
20959 sym(tetloop, tsymtet);
20960 if (tsymtet.tet == dummytet) {
20961 // Is the tetrahedron protected by a subface?
20962 tspivot(tetloop, hullface);
20963 if (hullface.sh == dummysh) {
20964 // The tetrahedron is not protected; infect it.
20965 if (!infected(tetloop)) {
20966 infect(tetloop);
20967 deadtet = (tetrahedron **) viri->alloc();
20968 *deadtet = tetloop.tet;
20969 break; // Go and get next tet.
20970 }
20971 } else {
20972 // The tetrahedron is protected; set boundary markers if appropriate.
20973 if (shellmark(hullface) == 0) {
20974 setshellmark(hullface, 1);
20975 /*
20976 horg = sorg(hullface);
20977 hdest = sdest(hullface);
20978 hapex = sapex(hullface);
20979 if (pointmark(horg) == 0) {
20980 setpointmark(horg, 1);
20981 }
20982 if (pointmark(hdest) == 0) {
20983 setpointmark(hdest, 1);
20984 }
20985 if (pointmark(hapex) == 0) {
20986 setpointmark(hapex, 1);
20987 }
20988 */
20989 }
20990 }
20991 }
20992 }
20993 tetloop.tet = tetrahedrontraverse();
20994 }
20995 }
20996
20997 ///////////////////////////////////////////////////////////////////////////////
20998 // //
20999 // plague() Spread the virus from all infected tets to any neighbors not //
21000 // protected by subfaces. //
21001 // //
21002 // This routine identifies all the tetrahedra that will die, and marks them //
21003 // as infected. They are marked to ensure that each tetrahedron is added to //
21004 // the virus pool only once, so the procedure will terminate. 'viri' returns //
21005 // all infected tetrahedra which are outside the domian. //
21006 // //
21007 ///////////////////////////////////////////////////////////////////////////////
21008
21009 void tetgenmesh::plague(memorypool *viri)
21010 {
21011 tetrahedron **virusloop;
21012 tetrahedron **deadtet;
21013 triface testtet, neighbor;
21014 face neighsh, testseg;
21015 face spinsh, casingin, casingout;
21016 int firstdadsub;
21017 int i;
21018
21019 if (b->verbose > 0) {
21020 printf(" Marking neighbors of marked tetrahedra.\n");
21021 }
21022 firstdadsub = 0;
21023 // Loop through all the infected tetrahedra, spreading the virus to
21024 // their neighbors, then to their neighbors' neighbors.
21025 viri->traversalinit();
21026 virusloop = (tetrahedron **) viri->traverse();
21027 while (virusloop != (tetrahedron **) NULL) {
21028 testtet.tet = *virusloop;
21029 // Temporarily uninfect this tetrahedron, not necessary.
21030 uninfect(testtet);
21031 // Check each of the tetrahedron's four neighbors.
21032 for (testtet.loc = 0; testtet.loc < 4; testtet.loc++) {
21033 // Find the neighbor.
21034 sym(testtet, neighbor);
21035 // Check for a shell between the tetrahedron and its neighbor.
21036 tspivot(testtet, neighsh);
21037 // Check if the neighbor is nonexistent or already infected.
21038 if ((neighbor.tet == dummytet) || infected(neighbor)) {
21039 if (neighsh.sh != dummysh) {
21040 // There is a subface separating the tetrahedron from its neighbor,
21041 // but both tetrahedra are dying, so the subface dies too.
21042 // Before deallocte this subface, dissolve the connections between
21043 // other subfaces, subsegments and tetrahedra.
21044 neighsh.shver = 0;
21045 if (!firstdadsub) {
21046 firstdadsub = 1; // Report the problem once.
21047 if (!b->quiet) {
21048 printf("Warning: Detecting an open face (%d, %d, %d).\n",
21049 pointmark(sorg(neighsh)), pointmark(sdest(neighsh)),
21050 pointmark(sapex(neighsh)));
21051 }
21052 }
21053 // For keep the same enext() direction.
21054 findedge(&testtet, sorg(neighsh), sdest(neighsh));
21055 for (i = 0; i < 3; i++) {
21056 sspivot(neighsh, testseg);
21057 if (testseg.sh != dummysh) {
21058 // A subsegment is found at this side, dissolve this subface
21059 // from the face link of this subsegment.
21060 testseg.shver = 0;
21061 spinsh = neighsh;
21062 if (sorg(spinsh) != sorg(testseg)) {
21063 sesymself(spinsh);
21064 }
21065 spivot(spinsh, casingout);
21066 if (casingout.sh == spinsh.sh) {
21067 // This is a trivial face link, only 'neighsh' itself,
21068 // the subsegment at this side is also died.
21069 shellfacedealloc(subsegs, testseg.sh);
21070 } else {
21071 spinsh = casingout;
21072 do {
21073 casingin = spinsh;
21074 spivotself(spinsh);
21075 } while (spinsh.sh != neighsh.sh);
21076 // Set the link casingin->casingout.
21077 sbond1(casingin, casingout);
21078 // Bond the subsegment anyway.
21079 ssbond(casingin, testseg);
21080 }
21081 }
21082 senextself(neighsh);
21083 enextself(testtet);
21084 }
21085 if (neighbor.tet != dummytet) {
21086 // Make sure the subface doesn't get deallocated again later
21087 // when the infected neighbor is visited.
21088 tsdissolve(neighbor);
21089 }
21090 // This subface has been separated.
21091 if (in->mesh_dim > 2) {
21092 shellfacedealloc(subfaces, neighsh.sh);
21093 } else {
21094 // Dimension is 2. keep it for output.
21095 // Dissolve tets at both sides of this subface.
21096 stdissolve(neighsh);
21097 sesymself(neighsh);
21098 stdissolve(neighsh);
21099 }
21100 }
21101 } else { // The neighbor exists and is not infected.
21102 if (neighsh.sh == dummysh) {
21103 // There is no subface protecting the neighbor, infect it.
21104 infect(neighbor);
21105 // Ensure that the neighbor's neighbors will be infected.
21106 deadtet = (tetrahedron **) viri->alloc();
21107 *deadtet = neighbor.tet;
21108 } else { // The neighbor is protected by a subface.
21109 // Remove this tetrahedron from the subface.
21110 stdissolve(neighsh);
21111 // The subface becomes a boundary. Set markers accordingly.
21112 if (shellmark(neighsh) == 0) {
21113 setshellmark(neighsh, 1);
21114 }
21115 }
21116 }
21117 }
21118 // Remark the tetrahedron as infected, so it doesn't get added to the
21119 // virus pool again.
21120 infect(testtet);
21121 virusloop = (tetrahedron **) viri->traverse();
21122 }
21123 }
21124
21125 ///////////////////////////////////////////////////////////////////////////////
21126 // //
21127 // regionplague() Spread regional attributes and/or volume constraints //
21128 // (from a .poly file) throughout the mesh. //
21129 // //
21130 // This procedure operates in two phases. The first phase spreads an attri- //
21131 // bute and/or a volume constraint through a (facet-bounded) region. The //
21132 // second phase uninfects all infected tetrahedra, returning them to normal. //
21133 // //
21134 ///////////////////////////////////////////////////////////////////////////////
21135
21136 void tetgenmesh::
21137 regionplague(memorypool *regionviri, REAL attribute, REAL volume)
21138 {
21139 tetrahedron **virusloop;
21140 tetrahedron **regiontet;
21141 triface testtet, neighbor;
21142 face neighsh;
21143
21144 if (b->verbose > 1) {
21145 printf(" Marking neighbors of marked tetrahedra.\n");
21146 }
21147 // Loop through all the infected tetrahedra, spreading the attribute
21148 // and/or volume constraint to their neighbors, then to their neighbors'
21149 // neighbors.
21150 regionviri->traversalinit();
21151 virusloop = (tetrahedron **) regionviri->traverse();
21152 while (virusloop != (tetrahedron **) NULL) {
21153 testtet.tet = *virusloop;
21154 // Temporarily uninfect this tetrahedron, not necessary.
21155 uninfect(testtet);
21156 if (b->regionattrib) {
21157 // Set an attribute.
21158 setelemattribute(testtet.tet, in->numberoftetrahedronattributes,
21159 attribute);
21160 }
21161 if (b->varvolume) {
21162 // Set a volume constraint.
21163 setvolumebound(testtet.tet, volume);
21164 }
21165 // Check each of the tetrahedron's four neighbors.
21166 for (testtet.loc = 0; testtet.loc < 4; testtet.loc++) {
21167 // Find the neighbor.
21168 sym(testtet, neighbor);
21169 // Check for a subface between the tetrahedron and its neighbor.
21170 tspivot(testtet, neighsh);
21171 // Make sure the neighbor exists, is not already infected, and
21172 // isn't protected by a subface, or is protected by a nonsolid
21173 // subface.
21174 if ((neighbor.tet != dummytet) && !infected(neighbor)
21175 && (neighsh.sh == dummysh)) {
21176 // Infect the neighbor.
21177 infect(neighbor);
21178 // Ensure that the neighbor's neighbors will be infected.
21179 regiontet = (tetrahedron **) regionviri->alloc();
21180 *regiontet = neighbor.tet;
21181 }
21182 }
21183 // Remark the tetrahedron as infected, so it doesn't get added to the
21184 // virus pool again.
21185 infect(testtet);
21186 virusloop = (tetrahedron **) regionviri->traverse();
21187 }
21188
21189 // Uninfect all tetrahedra.
21190 if (b->verbose > 1) {
21191 printf(" Unmarking marked tetrahedra.\n");
21192 }
21193 regionviri->traversalinit();
21194 virusloop = (tetrahedron **) regionviri->traverse();
21195 while (virusloop != (tetrahedron **) NULL) {
21196 testtet.tet = *virusloop;
21197 uninfect(testtet);
21198 virusloop = (tetrahedron **) regionviri->traverse();
21199 }
21200 // Empty the virus pool.
21201 regionviri->restart();
21202 }
21203
21204 ///////////////////////////////////////////////////////////////////////////////
21205 // //
21206 // removeholetets() Remove tetrahedra which are outside the domain. //
21207 // //
21208 ///////////////////////////////////////////////////////////////////////////////
21209
21210 void tetgenmesh::removeholetets(memorypool* viri)
21211 {
21212 tetrahedron **virusloop;
21213 triface testtet, neighbor;
21214 point checkpt;
21215 int *tetspernodelist;
21216 int i, j;
21217
21218 if (b->verbose > 0) {
21219 printf(" Deleting marked tetrahedra.\n");
21220 }
21221
21222 // Create and initialize 'tetspernodelist'.
21223 tetspernodelist = new int[points->items + 1];
21224 for (i = 0; i < points->items + 1; i++) tetspernodelist[i] = 0;
21225
21226 // Loop the tetrahedra list, counter the number of tets sharing each node.
21227 tetrahedrons->traversalinit();
21228 testtet.tet = tetrahedrontraverse();
21229 while (testtet.tet != (tetrahedron *) NULL) {
21230 // Increment the number of sharing tets for each endpoint.
21231 for (i = 0; i < 4; i++) {
21232 j = pointmark((point) testtet.tet[4 + i]);
21233 tetspernodelist[j]++;
21234 }
21235 testtet.tet = tetrahedrontraverse();
21236 }
21237
21238 viri->traversalinit();
21239 virusloop = (tetrahedron **) viri->traverse();
21240 while (virusloop != (tetrahedron **) NULL) {
21241 testtet.tet = *virusloop;
21242 // Record changes in the number of boundary faces, and disconnect
21243 // dead tetrahedra from their neighbors.
21244 for (testtet.loc = 0; testtet.loc < 4; testtet.loc++) {
21245 sym(testtet, neighbor);
21246 if (neighbor.tet == dummytet) {
21247 // There is no neighboring tetrahedron on this face, so this face
21248 // is a boundary face. This tetrahedron is being deleted, so this
21249 // boundary face is deleted.
21250 hullsize--;
21251 } else {
21252 // Disconnect the tetrahedron from its neighbor.
21253 dissolve(neighbor);
21254 // There is a neighboring tetrahedron on this face, so this face
21255 // becomes a boundary face when this tetrahedron is deleted.
21256 hullsize++;
21257 }
21258 }
21259 // Check the four corners of this tet if they're isolated.
21260 for (i = 0; i < 4; i++) {
21261 checkpt = (point) testtet.tet[4 + i];
21262 j = pointmark(checkpt);
21263 tetspernodelist[j]--;
21264 if (tetspernodelist[j] == 0) {
21265 // If it is a volume vertex, mark to delete it.
21266 if ((pointtype(checkpt) == VOLVERTEX) ||
21267 (pointtype(checkpt) == FREEVOLVERTEX)) {
21268 setpointtype(checkpt, UNUSEDVERTEX);
21269 unuverts++;
21270 }
21271 }
21272 }
21273 // Return the dead tetrahedron to the pool of tetrahedra.
21274 tetrahedrondealloc(testtet.tet);
21275 virusloop = (tetrahedron **) viri->traverse();
21276 }
21277
21278 delete [] tetspernodelist;
21279 }
21280
21281 ///////////////////////////////////////////////////////////////////////////////
21282 // //
21283 // assignregionattribs() Assign each tetrahedron a region number. //
21284 // //
21285 // This routine is called when '-AA' switch is specified. Every tetrahedron //
21286 // of a (bounded) region will get a integer number to that region. Default, //
21287 // regions are numbered as 1, 2, 3, etc. However, if a number has already //
21288 // been used (set by user in the region section in .poly or .smesh), it is //
21289 // skipped and the next available number will be used. //
21290 // //
21291 ///////////////////////////////////////////////////////////////////////////////
21292
21293 void tetgenmesh::assignregionattribs()
21294 {
21295 list *regionnumlist;
21296 list *regiontetlist;
21297 triface tetloop, regiontet, neightet;
21298 face checksh;
21299 bool flag;
21300 int regionnum, num;
21301 int attridx, count;
21302 int i;
21303
21304 if (b->verbose > 0) {
21305 printf(" Assign region numbers.\n");
21306 }
21307
21308 regionnumlist = new list(sizeof(int), NULL, 256);
21309 regiontetlist = new list(sizeof(triface), NULL, 1024);
21310 attridx = in->numberoftetrahedronattributes;
21311
21312 // Loop through all tets. Infect tets which already have a region number,
21313 // and save the used numbers in 'regionnumlist'.
21314 tetrahedrons->traversalinit();
21315 tetloop.tet = tetrahedrontraverse();
21316 while (tetloop.tet != (tetrahedron *) NULL) {
21317 if (!infected(tetloop)) {
21318 regionnum = (int) elemattribute(tetloop.tet, attridx);
21319 if (regionnum != 0.0) {
21320 // Found a numbered region tet.
21321 infect(tetloop);
21322 regiontetlist->append(&tetloop);
21323 // Found and infect all tets in this region.
21324 for (i = 0; i < regiontetlist->len(); i++) {
21325 regiontet = * (triface *)(* regiontetlist)[i];
21326 for (regiontet.loc = 0; regiontet.loc < 4; regiontet.loc++) {
21327 // Is there a boundary face?
21328 tspivot(regiontet, checksh);
21329 if (checksh.sh == dummysh) {
21330 sym(regiontet, neightet);
21331 if ((neightet.tet != dummytet) && !infected(neightet)) {
21332 #ifdef SELF_CHECK
21333 // neightet should have the same region number. Check it.
21334 num = (int) elemattribute(neightet.tet, attridx);
21335 assert(num == regionnum);
21336 #endif
21337 infect(neightet);
21338 regiontetlist->append(&neightet);
21339 }
21340 }
21341 }
21342 }
21343 // Add regionnum to list if it is not exist.
21344 flag = false;
21345 for (i = 0; i < regionnumlist->len() && !flag; i++) {
21346 num = * (int *)(* regionnumlist)[i];
21347 flag = (num == regionnum);
21348 }
21349 if (!flag) regionnumlist->append(&regionnum);
21350 // Clear list for the next region.
21351 regiontetlist->clear();
21352 }
21353 }
21354 tetloop.tet = tetrahedrontraverse();
21355 }
21356
21357 if (b->verbose > 0) {
21358 printf(" %d user-specified regions.\n", regionnumlist->len());
21359 }
21360
21361 // Now loop the tets again. Assign region numbers to uninfected tets.
21362 tetrahedrons->traversalinit();
21363 tetloop.tet = tetrahedrontraverse();
21364 regionnum = 1; // Start region number.
21365 count = 0;
21366 while (tetloop.tet != (tetrahedron *) NULL) {
21367 if (!infected(tetloop)) {
21368 // An unassigned region tet.
21369 count++;
21370 do {
21371 flag = false;
21372 // Check if the region number has been used.
21373 for (i = 0; i < regionnumlist->len() && !flag; i++) {
21374 num = * (int *)(* regionnumlist)[i];
21375 flag = (num == regionnum);
21376 }
21377 if (flag) regionnum++;
21378 } while (flag);
21379 setelemattribute(tetloop.tet, attridx, (REAL) regionnum);
21380 infect(tetloop);
21381 regiontetlist->append(&tetloop);
21382 // Found and infect all tets in this region.
21383 for (i = 0; i < regiontetlist->len(); i++) {
21384 regiontet = * (triface *)(* regiontetlist)[i];
21385 for (regiontet.loc = 0; regiontet.loc < 4; regiontet.loc++) {
21386 // Is there a boundary face?
21387 tspivot(regiontet, checksh);
21388 if (checksh.sh == dummysh) {
21389 sym(regiontet, neightet);
21390 if ((neightet.tet != dummytet) && !infected(neightet)) {
21391 #ifdef SELF_CHECK
21392 // neightet should have not been assigned yet. Check it.
21393 num = (int) elemattribute(neightet.tet, attridx);
21394 assert(num == 0);
21395 #endif
21396 setelemattribute(neightet.tet, attridx, (REAL) regionnum);
21397 infect(neightet);
21398 regiontetlist->append(&neightet);
21399 }
21400 }
21401 }
21402 }
21403 regiontetlist->clear();
21404 regionnum++; // The next region number.
21405 }
21406 tetloop.tet = tetrahedrontraverse();
21407 }
21408
21409 // Uninfect all tets.
21410 tetrahedrons->traversalinit();
21411 tetloop.tet = tetrahedrontraverse();
21412 while (tetloop.tet != (tetrahedron *) NULL) {
21413 #ifdef SELF_CHECK
21414 assert(infected(tetloop));
21415 #endif
21416 uninfect(tetloop);
21417 tetloop.tet = tetrahedrontraverse();
21418 }
21419
21420 if (b->verbose > 0) {
21421 printf(" %d regions are numbered.\n", count);
21422 }
21423
21424 delete regionnumlist;
21425 delete regiontetlist;
21426 }
21427
21428 ///////////////////////////////////////////////////////////////////////////////
21429 // //
21430 // carveholes() Find the holes and infect them. Find the volume //
21431 // constraints and infect them. Infect the convex hull. //
21432 // Spread the infection and kill tetrahedra. Spread the //
21433 // volume constraints. //
21434 // //
21435 // This routine mainly calls other routines to carry out all these functions.//
21436 // //
21437 ///////////////////////////////////////////////////////////////////////////////
21438
21439 void tetgenmesh::carveholes()
21440 {
21441 memorypool *holeviri, *regionviri;
21442 tetrahedron *tptr, **holetet, **regiontet;
21443 triface searchtet, *holetets, *regiontets;
21444 enum locateresult intersect;
21445 int i;
21446
21447 if (!b->quiet) {
21448 printf("Removing unwanted tetrahedra.\n");
21449 if (b->verbose && (in->numberofholes > 0)) {
21450 printf(" Marking holes for elimination.\n");
21451 }
21452 }
21453
21454 // Initialize a pool of viri to be used for holes, concavities.
21455 holeviri = new memorypool(sizeof(tetrahedron *), 1024, POINTER, 0);
21456 // Mark as infected any unprotected tetrahedra on the boundary.
21457 infecthull(holeviri);
21458
21459 if (in->numberofholes > 0) {
21460 // Allocate storage for the tetrahedra in which hole points fall.
21461 holetets = (triface *) new triface[in->numberofholes];
21462 // Infect each tetrahedron in which a hole lies.
21463 for (i = 0; i < 3 * in->numberofholes; i += 3) {
21464 // Ignore holes that aren't within the bounds of the mesh.
21465 if ((in->holelist[i] >= xmin) && (in->holelist[i] <= xmax)
21466 && (in->holelist[i + 1] >= ymin)
21467 && (in->holelist[i + 1] <= ymax)
21468 && (in->holelist[i + 2] >= zmin)
21469 && (in->holelist[i + 2] <= zmax)) {
21470 searchtet.tet = dummytet;
21471 // Find a tetrahedron that contains the hole.
21472 intersect = locate(&in->holelist[i], &searchtet);
21473 if ((intersect != OUTSIDE) && (!infected(searchtet))) {
21474 // Record the tetrahedron for processing carve hole.
21475 holetets[i / 3] = searchtet;
21476 }
21477 }
21478 }
21479 // Infect the hole tetrahedron. This is done by marking the tet as
21480 // infected and including the tetrahedron in the virus pool.
21481 for (i = 0; i < in->numberofholes; i++) {
21482 infect(holetets[i]);
21483 holetet = (tetrahedron **) holeviri->alloc();
21484 *holetet = holetets[i].tet;
21485 }
21486 // Free up memory.
21487 delete [] holetets;
21488 }
21489
21490 // Mark as infected all tets of the holes and concavities.
21491 plague(holeviri);
21492 // The virus pool contains all outside tets now.
21493
21494 // Is -A switch in use.
21495 if (b->regionattrib) {
21496 // Assign every tetrahedron a regional attribute of zero.
21497 tetrahedrons->traversalinit();
21498 tptr = tetrahedrontraverse();
21499 while (tptr != (tetrahedron *) NULL) {
21500 setelemattribute(tptr, in->numberoftetrahedronattributes, 0.0);
21501 tptr = tetrahedrontraverse();
21502 }
21503 }
21504
21505 if (in->numberofregions > 0) {
21506 if (!b->quiet) {
21507 if (b->regionattrib) {
21508 if (b->varvolume) {
21509 printf("Spreading regional attributes and volume constraints.\n");
21510 } else {
21511 printf("Spreading regional attributes.\n");
21512 }
21513 } else {
21514 printf("Spreading regional volume constraints.\n");
21515 }
21516 }
21517 // Allocate storage for the tetrahedra in which region points fall.
21518 regiontets = (triface *) new triface[in->numberofregions];
21519 // Find the starting tetrahedron for each region.
21520 for (i = 0; i < in->numberofregions; i++) {
21521 regiontets[i].tet = dummytet;
21522 // Ignore region points that aren't within the bounds of the mesh.
21523 if ((in->regionlist[5 * i] >= xmin)
21524 && (in->regionlist[5 * i] <= xmax)
21525 && (in->regionlist[5 * i + 1] >= ymin)
21526 && (in->regionlist[5 * i + 1] <= ymax)
21527 && (in->regionlist[5 * i + 2] >= zmin)
21528 && (in->regionlist[5 * i + 2] <= zmax)) {
21529 searchtet.tet = dummytet;
21530 // Find a tetrahedron that contains the region point.
21531 intersect = locate(&in->regionlist[5 * i], &searchtet);
21532 if ((intersect != OUTSIDE) && (!infected(searchtet))) {
21533 // Record the tetrahedron for processing after the
21534 // holes have been carved.
21535 regiontets[i] = searchtet;
21536 }
21537 }
21538 }
21539 // Initialize a pool to be used for regional attrs, and/or regional
21540 // volume constraints.
21541 regionviri = new memorypool(sizeof(tetrahedron *), 1024, POINTER, 0);
21542 // Find and set all regions.
21543 for (i = 0; i < in->numberofregions; i++) {
21544 if (regiontets[i].tet != dummytet) {
21545 // Make sure the tetrahedron under consideration still exists.
21546 // It may have been eaten by the virus.
21547 if (!isdead(&(regiontets[i]))) {
21548 // Put one tetrahedron in the virus pool.
21549 infect(regiontets[i]);
21550 regiontet = (tetrahedron **) regionviri->alloc();
21551 *regiontet = regiontets[i].tet;
21552 // Apply one region's attribute and/or volume constraint.
21553 regionplague(regionviri, in->regionlist[5 * i + 3],
21554 in->regionlist[5 * i + 4]);
21555 // The virus pool should be empty now.
21556 }
21557 }
21558 }
21559 // Free up memory.
21560 delete [] regiontets;
21561 delete regionviri;
21562 }
21563
21564 // Now acutually remove the outside and hole tets.
21565 removeholetets(holeviri);
21566 // The mesh is nonconvex now.
21567 nonconvex = 1;
21568
21569 if (b->regionattrib) {
21570 if (b->regionattrib > 1) {
21571 // -AA switch. Assign each tet a region number (> 0).
21572 assignregionattribs();
21573 }
21574 // Note the fact that each tetrahedron has an additional attribute.
21575 in->numberoftetrahedronattributes++;
21576 }
21577
21578 // Free up memory.
21579 delete holeviri;
21580 }
21581
21582 //
21583 // End of carving out holes and concavities routines
21584 //
21585
21586 //
21587 // Begin of boundary Steiner points removing routines
21588 //
21589
21590 ///////////////////////////////////////////////////////////////////////////////
21591 // //
21592 // replacepolygonsubs() Substitute the subfaces of a polygon. //
21593 // //
21594 // 'oldshlist' (T_old) contains the old subfaces of P. It will be replaced //
21595 // by 'newshlist' (T_new) of new subfaces. Each boundary edge of P is bonded //
21596 // to 'dummysh' in T_new. //
21597 // //
21598 // Notice that Not every boundary edge of T_new is able to bond to a subface,//
21599 // e.g., when it is a segment recovered by removing a Steiner point in it. //
21600 // //
21601 ///////////////////////////////////////////////////////////////////////////////
21602
21603 void tetgenmesh::replacepolygonsubs(list* oldshlist, list* newshlist)
21604 {
21605 face newsh, oldsh, spinsh;
21606 face casingout, casingin;
21607 face checkseg;
21608 point pa, pb;
21609 int i, j, k, l;
21610
21611 for (i = 0; i < newshlist->len(); i++) {
21612 // Get a new subface s.
21613 newsh = * (face *)(* newshlist)[i];
21614 // Check the three edges of s.
21615 for (k = 0; k < 3; k++) {
21616 spivot(newsh, casingout);
21617 // Is it a boundary edge?
21618 if (casingout.sh == dummysh) {
21619 // Find the old subface s_o having the same edge as s.
21620 pa = sorg(newsh);
21621 pb = sdest(newsh);
21622 for (j = 0; j < oldshlist->len(); j++) {
21623 oldsh = * (face *)(* oldshlist)[j];
21624 for (l = 0; l < 3; l++) {
21625 if (((sorg(oldsh) == pa) && (sdest(oldsh) == pb)) ||
21626 ((sorg(oldsh) == pb) && (sdest(oldsh) == pa))) break;
21627 senextself(oldsh);
21628 }
21629 if (l < 3) break;
21630 }
21631 // Is there a matched edge?
21632 if (j < oldshlist->len()) {
21633 // Get the neighbor subface s_out.
21634 spivot(oldsh, casingout);
21635 sspivot(oldsh, checkseg);
21636 if (checkseg.sh != dummysh) {
21637 // A segment. Insert s into the face ring, ie, s_in -> s -> s_out.
21638 if (oldsh.sh != casingout.sh) {
21639 // s is not bonded to itself.
21640 spinsh = casingout;
21641 do {
21642 casingin = spinsh;
21643 spivotself(spinsh);
21644 } while (sapex(spinsh) != sapex(oldsh));
21645 assert(casingin.sh != oldsh.sh);
21646 // Bond s_in -> s -> s_out (and dissolve s_in -> s_old -> s_out).
21647 sbond1(casingin, newsh);
21648 sbond1(newsh, casingout);
21649 } else {
21650 // Bond newsh -> newsh.
21651 sbond(newsh, newsh);
21652 }
21653 // Bond the segment.
21654 ssbond(newsh, checkseg);
21655 } else {
21656 // Bond s <-> s_out (and dissolve s_out -> s_old).
21657 sbond(newsh, casingout);
21658 }
21659 // Unbound oldsh to indicate it's neighbor has been replaced.
21660 // It will be used to indentfy the edge in the inverse.
21661 sdissolve(oldsh);
21662 ssdissolve(oldsh);
21663 }
21664 }
21665 // Go to the next edge of s.
21666 senextself(newsh);
21667 }
21668 }
21669 }
21670
21671 ///////////////////////////////////////////////////////////////////////////////
21672 // //
21673 // orientnewsubs() Orient new subfaces facing to the inside of cavity. //
21674 // //
21675 // 'newshlist' contains new subfaces of the cavity C (created by re-triangu- //
21676 // lation the polygon P). They're not necessary facing to the inside of C. //
21677 // 'orientsh', faces to the inside of C, is used to adjust new subfaces. The //
21678 // normal of the new subfaces is returned in 'norm'. //
21679 // //
21680 ///////////////////////////////////////////////////////////////////////////////
21681
21682 void tetgenmesh::orientnewsubs(list* newshlist, face* orientsh, REAL* norm)
21683 {
21684 face *newsh;
21685 point pa, pb, pc;
21686 REAL ref[3], ori, len;
21687 int i;
21688
21689 // Calculate the normal of 'orientsh'.
21690 pa = sorg(*orientsh);
21691 pb = sdest(*orientsh);
21692 pc = sapex(*orientsh);
21693 facenormal(pa, pb, pc, norm, &len);
21694 for (i = 0; i < 3; i++) ref[i] = pa[i] + norm[i];
21695 for (i = 0; i < 3; i++) norm[i] /= len;
21696
21697 // Orient new subfaces. Let the normal above each one.
21698 for (i = 0; i < newshlist->len(); i++) {
21699 newsh = (face *)(* newshlist)[i];
21700 pa = sorg(*newsh);
21701 pb = sdest(*newsh);
21702 pc = sapex(*newsh);
21703 ori = orient3d(pa, pb, pc, ref);
21704 assert(ori != 0.0);
21705 if (ori > 0.0) {
21706 sesymself(*newsh);
21707 }
21708 }
21709 }
21710
21711 ///////////////////////////////////////////////////////////////////////////////
21712 // //
21713 // constrainedflip() Flip a non-constrained face. //
21714 // //
21715 // 'flipface' f (abc) is a face we want to flip. In addition, if 'front' is //
21716 // given (not a NULL), f is a crossface. f may not be flippable if it is one //
21717 // of the following cases: //
21718 // (1) f has an aux subface attached; //
21719 // (2) f is on the convex hull; //
21720 // (3) f is not locally Delaunay (f must be recovered by a previous flip, //
21721 // we should keep it, otherwise, we may fall into a flip loop); //
21722 // (4) f is T32 at ab, but abd or abe has an aux subface attached; //
21723 // (5) f is T22 or T44 at ab, but abd, or abe, or abf has an aux subface //
21724 // attached; //
21725 // (6) f is unflipable at ab, and abd, abe, ... are all unflippable due to //
21726 // the cases (1) - (5). //
21727 // If f is a crssface ('front' != NULL) and it is unflipable due to case (3),//
21728 // (4), (5) and (6). Try to flip the next crossing face of front first. //
21729 // //
21730 ///////////////////////////////////////////////////////////////////////////////
21731
21732 bool tetgenmesh::constrainedflip(triface* flipface, triface* front,
21733 queue* flipque)
21734 {
21735 triface symface, spintet;
21736 face checksh;
21737 point pa, pb, pc, pd, pe;
21738 enum fliptype fc;
21739 REAL sign;
21740 bool doflip;
21741 int ia, ib, ic, id, ie;
21742 int i;
21743
21744 // (1) Is f protected by an (auxilary) subface?
21745 tspivot(*flipface, checksh);
21746 if (checksh.sh != dummysh) return false;
21747 // (2) Is f on the convex hull?
21748 sym(*flipface, symface);
21749 if (symface.tet == dummytet) return false;
21750 // (3) Is f not locally Delaunay?
21751 adjustedgering(*flipface, CCW);
21752 pa = dest(*flipface);
21753 pb = org(*flipface);
21754 pc = apex(*flipface);
21755 pd = oppo(*flipface);
21756 pe = oppo(symface);
21757 // if (symbolic) {
21758 ia = pointmark(pa);
21759 ib = pointmark(pb);
21760 ic = pointmark(pc);
21761 id = pointmark(pd);
21762 ie = pointmark(pe);
21763 sign = insphere_sos(pa, pb, pc, pd, pe, ia, ib, ic, id, ie);
21764 assert(sign != 0.0);
21765 // } else {
21766 // sign = insphere(pa, pb, pc, pd, pe);
21767 // }
21768 if (sign <= 0.0) {
21769 // Get the fliptype of f.
21770 checksubfaces = 0; // switch off subface test.
21771 fc = categorizeface(*flipface);
21772 checksubfaces = 1; // switch on subface test.
21773 if (fc == T23) {
21774 doflip = true;
21775 // Avoid one tet created by the 2-3 flip is nearly degenerate.
21776 /* pc = oppo(*flipface);
21777 pd = oppo(symface);
21778 adjustedgering(*flipface, CCW);
21779 for (i = 0; i < 3; i++) {
21780 pa = org(*flipface);
21781 pb = dest(*flipface);
21782 ori = orient3d(pa, pb, pc, pd);
21783 if (iscoplanar(pa, pb, pc, pd, ori, b->epsilon)) {
21784 doflip = false; break;
21785 }
21786 enextself(*flipface);
21787 } */
21788 if (doflip) {
21789 flip23(flipface, flipque);
21790 return true;
21791 }
21792 } else if (fc == T32) {
21793 // (4) Is abd, or abe protected?
21794 doflip = true;
21795 spintet = *flipface;
21796 for (i = 0; i < 2; i++) {
21797 fnextself(spintet);
21798 tspivot(spintet, checksh);
21799 if (checksh.sh != dummysh) {
21800 doflip = false; break; // f is protected. Unflipable.
21801 }
21802 }
21803 if (doflip) {
21804 flip32(flipface, flipque);
21805 return true;
21806 }
21807 } else if (fc == T22 || fc == T44) {
21808 // (5) Is abd, abe, or abf protected?
21809 doflip = true;
21810 if (fc == T22) {
21811 for (i = 0; i < 2; i++) {
21812 spintet = *flipface;
21813 if (i == 1) {
21814 esymself(spintet);
21815 }
21816 fnextself(spintet);
21817 tspivot(spintet, checksh);
21818 if (checksh.sh != dummysh) {
21819 doflip = false; break; // f is protected. Unflipable.
21820 }
21821 }
21822 } else if (fc == T44) {
21823 spintet = *flipface;
21824 for (i = 0; i < 3; i++) {
21825 fnextself(spintet);
21826 tspivot(spintet, checksh);
21827 if (checksh.sh != dummysh) {
21828 doflip = false; break; // f is protected. Unflipable.
21829 }
21830 }
21831 }
21832 if (doflip) {
21833 flip22(flipface, flipque);
21834 return true;
21835 }
21836 } else if (fc == UNFLIPABLE) {
21837 // Is f a crossface?
21838 if (front != (triface *) NULL) {
21839 // (6) Is any obstacle face (abd, or abe, ...) flipable?
21840 spintet = *flipface;
21841 while (fnextself(spintet)) {
21842 if (apex(spintet) == apex(*flipface)) break;
21843 // Check if spintet is flipable, no recursive.
21844 if (constrainedflip(&spintet, NULL, flipque)) {
21845 // One obstacle face has been flipped.
21846 return true;
21847 }
21848 // Unflipable. Go to the next obstacle face.
21849 findedge(&spintet, org(*flipface), dest(*flipface));
21850 }
21851 }
21852 }
21853 }
21854
21855 // f is unflipable. Is f a crossface?
21856 if (front != (triface *) NULL) {
21857 // Look if there is another crossface.
21858 pa = org(*front);
21859 pb = dest(*front);
21860 pc = apex(*front);
21861 // sym(*flipface, symface);
21862 // Have we reach the end of abc (We've started from edge ab).
21863 if (oppo(symface) != pc) {
21864 adjustedgering(symface, CCW);
21865 for (i = 0; i < 3; i++) {
21866 fnext(symface, spintet);
21867 // Is c ahead of this face?
21868 sign = orient3d(org(spintet), dest(spintet), apex(spintet), pc);
21869 if (sign < 0.0) {
21870 if (tritritest(&spintet, pa, pb, pc)) {
21871 if (b->verbose > 2) {
21872 printf(" Next crossface (%d, %d, %d).\n",
21873 pointmark(org(spintet)), pointmark(dest(spintet)),
21874 pointmark(apex(spintet)));
21875 }
21876 return constrainedflip(&spintet, front, flipque);
21877 // return constrainedflip(&spintet, NULL, flipque);
21878 }
21879 }
21880 enextself(symface);
21881 }
21882 }
21883 }
21884 return false;
21885 }
21886
21887 ///////////////////////////////////////////////////////////////////////////////
21888 // //
21889 // recoverfront() Recover a missing front by flips. //
21890 // //
21891 // 'front' f is missing in D - it was crossed by faces of D. The cross faces //
21892 // may be flippable, so f can be recovered by flipping them away. //
21893 // //
21894 ///////////////////////////////////////////////////////////////////////////////
21895
21896 bool tetgenmesh::recoverfront(triface* front, list* newtetlist, queue* flipque)
21897 {
21898 triface idfront, starttet, spintet;
21899 point pa, pb, pc, pd, ref;
21900 enum locateresult loc;
21901 enum finddirectionresult col;
21902 REAL ori, ori1, ori2, sign;
21903 int hitbdry;
21904 int i, j;
21905
21906 // Find an existing edge of f in D to start with.
21907 for (i = 0; i < 3; i++) {
21908 pa = org(*front);
21909 pb = dest(*front);
21910 // Get a tet for searching.
21911 idfront = recenttet;
21912 // Make sure the tet is valid (flip32() may kill a tet).
21913 if (isdead(&idfront)) {
21914 // The tet is dead. Get a live tet in D. !!!
21915 for (j = 0; j < newtetlist->len(); j++) {
21916 recenttet = * (triface *)(* newtetlist)[j];
21917 if (!isdead(&recenttet)) break;
21918 }
21919 assert(j < newtetlist->len());
21920 }
21921 loc = preciselocate(pa, &idfront, (long) newtetlist->len());
21922 if (loc != ONVERTEX) {
21923 // Do a brute-force search in D.
21924 for (j = 0; j < newtetlist->len(); j++) {
21925 idfront = * (triface *)(* newtetlist)[j];
21926 if (isdead(&idfront)) continue;
21927 if (findorg(&idfront, pa)) break;
21928 }
21929 assert(j < newtetlist->len()); // a must belong to one tet.
21930 }
21931 recenttet = idfront;
21932 // Search for a tet having edge ab.
21933 col = finddirection(&idfront, pb, (long) newtetlist->len());
21934 if (col == BELOWHULL) {
21935 // Do a brute-force search in D.
21936 for (j = 0; j < newtetlist->len(); j++) {
21937 idfront = * (triface *)(* newtetlist)[j];
21938 if (isdead(&idfront)) continue;
21939 if (findorg(&idfront, pa)) {
21940 assert(org(idfront) == pa);
21941 if (dest(idfront) == pb) {
21942 col = RIGHTCOLLINEAR; break;
21943 } else if (apex(idfront) == pb) {
21944 col = LEFTCOLLINEAR; break;
21945 } else if (oppo(idfront) == pb) {
21946 col = TOPCOLLINEAR; break;
21947 }
21948 }
21949 }
21950 }
21951 if (col == RIGHTCOLLINEAR) {
21952 // b is just the destination.
21953 } else if (col == LEFTCOLLINEAR) {
21954 enext2self(idfront);
21955 esymself(idfront);
21956 } else if (col == TOPCOLLINEAR) {
21957 fnextself(idfront);
21958 enext2self(idfront);
21959 esymself(idfront);
21960 }
21961 if (dest(idfront) == pb) break; // Found.
21962 // Missing. Go to the next edge of f.
21963 enextself(*front);
21964 }
21965 if (i == 3) {
21966 // All three edges of f are missing - unrecoverable.
21967 return false;
21968 }
21969
21970 // Search for a tet having f (abc).
21971 pc = apex(*front);
21972 spintet = idfront;
21973 hitbdry = 0;
21974 do {
21975 if (apex(spintet) == pc) {
21976 // Found abc. Insert an auxilary subface s at idfront.
21977 insertauxsubface(front, &spintet);
21978 return true;
21979 }
21980 if (!fnextself(spintet)) {
21981 hitbdry ++;
21982 if (hitbdry < 2) {
21983 esym(idfront, spintet);
21984 if (!fnextself(spintet)) {
21985 hitbdry ++;
21986 }
21987 }
21988 }
21989 if (apex(spintet) == apex(idfront)) break;
21990 } while (hitbdry < 2);
21991
21992 // Search for a crossing face to flip.
21993 pd = apex(idfront);
21994 assert(pd != pc);
21995 // Decide the orientation of d with abc.
21996 ori = orient3d(pa, pb, pc, pd);
21997 if (ori < 0.0) {
21998 // d is above abc. Rotate downwards.
21999 esym(idfront, starttet);
22000 sign = -1.0;
22001 } else if (ori > 0.0) {
22002 // d is below abc. Rotate upwards.
22003 starttet = idfront;
22004 sign = 1.0;
22005 } else {
22006 assert(ori == 0.0);
22007 // d is coplanar with abc. Do abc and abd intersect?
22008 ref = oppo(idfront);
22009 ori1 = orient3d(pa, pb, ref, pc);
22010 ori2 = orient3d(pa, pb, ref, pd);
22011 assert(ori1 * ori2 != 0.0);
22012 if (ori1 * ori2 > 0) {
22013 // abc and abd intersect. There're two possible intersections:
22014 // ad and bc, or ac and bd. Find it out.
22015 ori1 = orient3d(pb, pc, ref, pd);
22016 ori2 = orient3d(pb, pc, ref, pa);
22017 assert(ori1 * ori2 != 0.0);
22018 if (ori1 * ori2 > 0) {
22019 // ac intersects bd.
22020 enextself(idfront); // go to edge bd.
22021 } else {
22022 // ad intersects bc.
22023 enext2self(idfront); // go to edge ad.
22024 }
22025 adjustedgering(idfront, CCW);
22026 fnextself(idfront); // face ade or bce need a 4-to-4 flip.
22027 if (b->verbose > 2) {
22028 printf(" Get crossface (%d, %d, %d).\n", pointmark(org(idfront)),
22029 pointmark(dest(idfront)), pointmark(apex(idfront)));
22030 }
22031 if (constrainedflip(&idfront, front, flipque)) {
22032 // A crossface has been flipped. Continue to recover f.
22033 return recoverfront(front, newtetlist, flipque);
22034 }
22035 // Unable to recover f.
22036 return false; // sign = 0.0;
22037 } else {
22038 // Not intersect. We can go either direction.
22039 starttet = idfront;
22040 if (fnextself(starttet)) {
22041 // Choose to rotate upwards.
22042 sign = 1.0;
22043 } else {
22044 // Hit convex hull. Choose to rotate downwrads.
22045 esym(idfront, starttet);
22046 sign = -1.0;
22047 }
22048 }
22049 }
22050
22051 assert(sign != 0.0);
22052 if (sign == -1) {
22053 // The edge ab has be changed. Reverse it.
22054 pa = org(starttet);
22055 pb = dest(starttet);
22056 // The sign has been reversed as well.
22057 sign = -sign;
22058 }
22059 // Rotate face abd around edge ab. Moreover, we've chosen the rotate
22060 // direction such that no convex hull face will be reach.
22061 spintet = starttet;
22062 while (fnextself(spintet)) {
22063 pd = apex(spintet);
22064 assert(pd != pc);
22065 // Check if the orientation of d (with abc) has changed.
22066 ori = orient3d(pa, pb, pc, pd);
22067 if (ori == 0.0) {
22068 // abc and abd must coplanar intersect (4-to-4 flip is needed).
22069 ref = oppo(spintet);
22070 ori1 = orient3d(pb, pc, ref, pd);
22071 ori2 = orient3d(pb, pc, ref, pa);
22072 assert(ori1 * ori2 != 0.0);
22073 if (ori1 * ori2 > 0) {
22074 // ac intersects bd.
22075 enextself(spintet); // go to edge bd.
22076 } else {
22077 // ad intersects bc.
22078 enext2self(spintet); // go to edge ad.
22079 }
22080 adjustedgering(spintet, CCW);
22081 fnextself(spintet); // face ade or bce need a 4-to-4 flip.
22082 if (b->verbose > 2) {
22083 printf(" Get crossface (%d, %d, %d).\n", pointmark(org(spintet)),
22084 pointmark(dest(spintet)), pointmark(apex(spintet)));
22085 }
22086 if (constrainedflip(&spintet, front, flipque)) {
22087 // A crossface has been flipped. Continue to recover f.
22088 return recoverfront(front, newtetlist, flipque);
22089 }
22090 // Unable to recover f.
22091 return false; // sign = 0.0;
22092 } else if (ori * sign < 0.0) {
22093 // Sign has changed. The face dea or deb must cross abc.
22094 adjustedgering(spintet, CCW);
22095 enextself(spintet);
22096 for (i = 0; i < 2; i++) {
22097 // Get the face dea or deb.
22098 fnext(spintet, starttet);
22099 if (tritritest(&starttet, pa, pb, pc)) {
22100 if (b->verbose > 2) {
22101 printf(" Get crossface (%d, %d, %d).\n",
22102 pointmark(org(starttet)), pointmark(dest(starttet)),
22103 pointmark(apex(starttet)));
22104 }
22105 if (constrainedflip(&starttet, front, flipque)) {
22106 // A crossface has been flipped. Continue to recover f.
22107 return recoverfront(front, newtetlist, flipque);
22108 }
22109 }
22110 enextself(spintet);
22111 }
22112 // Unable to recover f.
22113 return false;
22114 }
22115 }
22116 // Impossible to be here.
22117 assert(0);
22118 return false;
22119 }
22120
22121 ///////////////////////////////////////////////////////////////////////////////
22122 // //
22123 // repairflips() Flip non-Delaunay and non-constrained faces. //
22124 // //
22125 ///////////////////////////////////////////////////////////////////////////////
22126
22127 void tetgenmesh::repairflips(queue* flipque)
22128 {
22129 badface *qface;
22130 triface flipface, symface, spintet;
22131 face checksh;
22132 point pa, pb, pc, pd, pe;
22133 enum fliptype fc;
22134 REAL sign;
22135 long flipcount;
22136 bool doflip;
22137 int ia, ib, ic, id, ie;
22138 int i;
22139
22140 if (b->verbose > 1) {
22141 printf(" Repair flip %ld faces.\n", flipque->len());
22142 }
22143 flipcount = flip23s + flip32s + flip22s + flip44s;
22144 // Loop until the queue is empty.
22145 while (!flipque->empty()) {
22146 qface = (badface *) flipque->pop();
22147 flipface = qface->tt;
22148 // Check the validity of this face.
22149 if (isdead(&flipface) || flipface.tet == dummytet ||
22150 (org(flipface) != qface->forg) ||
22151 (dest(flipface) != qface->fdest) ||
22152 (apex(flipface) != qface->fapex) ||
22153 (oppo(flipface) == (point) NULL)) continue;
22154 // (1) Is f protected by an (auxilary) subface?
22155 tspivot(flipface, checksh);
22156 if (checksh.sh != dummysh) continue;
22157 // (2) Is f on the convex hull?
22158 sym(flipface, symface);
22159 if (symface.tet == dummytet) continue;
22160 // For positive orientation that insphere() test requires.
22161 adjustedgering(flipface, CW);
22162 pa = org(flipface);
22163 pb = dest(flipface);
22164 pc = apex(flipface);
22165 pd = oppo(flipface);
22166 pe = oppo(symface);
22167 // if (symbolic) {
22168 ia = pointmark(pa);
22169 ib = pointmark(pb);
22170 ic = pointmark(pc);
22171 id = pointmark(pd);
22172 ie = pointmark(pe);
22173 sign = insphere_sos(pa, pb, pc, pd, pe, ia, ib, ic, id, ie);
22174 assert(sign != 0.0);
22175 // } else {
22176 // sign = insphere(pa, pb, pc, pd, pe);
22177 // }
22178 if (sign > 0.0) {
22179 // f is non-lcally Delaunay. Get the fliptype of f.
22180 checksubfaces = 0; // switch off subface test.
22181 fc = categorizeface(flipface);
22182 checksubfaces = 1; // switch on subface test.
22183 if (fc == T23) {
22184 doflip = true;
22185 // Avoid to create a nearly degenerate tet.
22186 /* pc = oppo(flipface);
22187 pd = oppo(symface);
22188 adjustedgering(flipface, CCW);
22189 for (i = 0; i < 3; i++) {
22190 pa = org(flipface);
22191 pb = dest(flipface);
22192 ori = orient3d(pa, pb, pc, pd);
22193 if (iscoplanar(pa, pb, pc, pd, ori, b->epsilon)) {
22194 doflip = false; break;
22195 }
22196 enextself(flipface);
22197 } */
22198 if (doflip) {
22199 flip23(&flipface, flipque);
22200 }
22201 } else if (fc == T32) {
22202 // (4) Is abd, or abe protected?
22203 doflip = true;
22204 spintet = flipface;
22205 for (i = 0; i < 2; i++) {
22206 fnextself(spintet);
22207 tspivot(spintet, checksh);
22208 if (checksh.sh != dummysh) {
22209 doflip = false; break; // f is protected. Unflipable.
22210 }
22211 }
22212 if (doflip) {
22213 flip32(&flipface, flipque);
22214 }
22215 } else if (fc == T22 || fc == T44) {
22216 // (5) Is abd, abe, or abf protected?
22217 doflip = true;
22218 if (fc == T22) {
22219 for (i = 0; i < 2; i++) {
22220 spintet = flipface;
22221 if (i == 1) {
22222 esymself(spintet);
22223 }
22224 fnextself(spintet);
22225 tspivot(spintet, checksh);
22226 if (checksh.sh != dummysh) {
22227 doflip = false; break; // f is protected. Unflipable.
22228 }
22229 }
22230 } else if (fc == T44) {
22231 spintet = flipface;
22232 for (i = 0; i < 3; i++) {
22233 fnextself(spintet);
22234 tspivot(spintet, checksh);
22235 if (checksh.sh != dummysh) {
22236 doflip = false; break; // f is protected. Unflipable.
22237 }
22238 }
22239 }
22240 if (doflip) {
22241 flip22(&flipface, flipque);
22242 }
22243 }
22244 }
22245 }
22246 flipcount = flip23s + flip32s + flip22s + flip44s - flipcount;
22247 if (b->verbose > 1) {
22248 printf(" %ld flips.\n", flipcount);
22249 }
22250 }
22251
22252 ///////////////////////////////////////////////////////////////////////////////
22253 // //
22254 // constrainedcavity() Tetrahedralize a cavity by constrained tetrahedra. //
22255 // //
22256 // The cavity C is bounded by faces F in 'floorlist' and 'ceillist'. 'ptlist'//
22257 // V is the set of vertices of C. //
22258 // //
22259 ///////////////////////////////////////////////////////////////////////////////
22260
22261 bool tetgenmesh::constrainedcavity(triface* oldtet, list* floorlist,
22262 list* ceillist, list* ptlist, list* frontlist, list* misfrontlist,
22263 list* newtetlist, queue* flipque)
22264 {
22265 triface misfront, newtet;
22266 long facenum;
22267 int i;
22268
22269 if (b->verbose > 1) {
22270 printf(" Constrained cavity (%d floors, %d ceilings, %d vertices).\n",
22271 floorlist->len(), ceillist->len(), ptlist->len());
22272 }
22273
22274 symbolic = 1;
22275
22276 // Initialize the cavity C.
22277 initializecavity(floorlist, ceillist, frontlist);
22278 // Form the D of the vertices of C.
22279 delaunizecavvertices(oldtet, ptlist, NULL, newtetlist, flipque);
22280
22281 // Identify faces of C in D.
22282 if (!identifyfronts(frontlist, misfrontlist, newtetlist)) {
22283 // Some faces are missing.
22284 recenttet = * (triface *)(* newtetlist)[0];
22285 assert((recenttet.tet != dummytet) && !isdead(&recenttet));
22286 // Try to recover missing faces by flips.
22287 do {
22288 facenum = misfrontlist->len();
22289 for (i = 0; i < misfrontlist->len(); i++) {
22290 // Get a missing front f.
22291 misfront = * (triface *)(* misfrontlist)[i];
22292 // Let f face toward the inside of C.
22293 adjustedgering(misfront, CW);
22294 if (b->verbose > 1) {
22295 printf(" Recover face (%d, %d, %d).\n", pointmark(org(misfront)),
22296 pointmark(dest(misfront)), pointmark(apex(misfront)));
22297 }
22298 if (recoverfront(&misfront, newtetlist, flipque)) {
22299 // f has been recovered.
22300 frontlist->append(&misfront);
22301 misfrontlist->del(i, 0); i--;
22302 }
22303 // Flip non-locally non-constrained Delaunay faces.
22304 repairflips(flipque);
22305 }
22306 // Have all faces been recovered?
22307 if (misfrontlist->len() == 0) break;
22308 // No! There are still un-recovered faces. Continue the loop if any
22309 // face has been recovered.
22310 } while (misfrontlist->len() < facenum);
22311 // Retrieve new tets and purge dead tets in D.
22312 retrievenewtets(newtetlist);
22313 }
22314
22315 symbolic = 0;
22316
22317 if (misfrontlist->len() == 0) {
22318 // All fronts have identified in D. Get the shape of C by removing out
22319 // tets of C. 'misfrontlist' is reused for removing out tets.
22320 // Don't do flip since the new tets may get deleted later.
22321 carvecavity(newtetlist, misfrontlist, NULL);
22322 // Recover locally Delaunay faces.
22323 // flip(flipque, NULL);
22324 return true;
22325 } else {
22326 // Fail to tetrahedralize C.
22327 // Remove aux subfaces.
22328 detachauxsubfaces(newtetlist);
22329 // Remove new tets.
22330 for (i = 0; i < newtetlist->len(); i++) {
22331 newtet = * (triface *)(* newtetlist)[i];
22332 assert(!isdead(&newtet));
22333 tetrahedrondealloc(newtet.tet);
22334 }
22335 newtetlist->clear();
22336 // Restore faces of C in frontlist.
22337 for (i = 0; i < misfrontlist->len(); i++) {
22338 misfront = * (triface *)(* misfrontlist)[i];
22339 frontlist->append(&misfront);
22340 }
22341 return false;
22342 }
22343 }
22344
22345 ///////////////////////////////////////////////////////////////////////////////
22346 // //
22347 // expandsteinercavity() Expand the cavity of a Steiner point. //
22348 // //
22349 // Expand the cavity C if there fronts (except fronts having subfaces) which //
22350 // are either (nearly) coplanar or invisible by the Steiner point. //
22351 // //
22352 ///////////////////////////////////////////////////////////////////////////////
22353
22354 void tetgenmesh::expandsteinercavity(point steinpt, REAL eps, list* frontlist,
22355 list* oldtetlist)
22356 {
22357 triface front, symfront, newfront, oldfront;
22358 face frontsh;
22359 point pa, pb, pc;
22360 REAL ori;
22361 bool expflag, newflag;
22362 int i, j;
22363
22364 do {
22365 expflag = false;
22366 for (i = 0; i < frontlist->len(); i++) {
22367 // Get a front f.
22368 front = * (triface *)(* frontlist)[i];
22369 // f can be expanded if it is not a subface.
22370 tspivot(front, frontsh);
22371 if (frontsh.sh == dummysh) {
22372 // Let f face to the inside of C.
22373 adjustedgering(front, CW);
22374 pa = org(front);
22375 pb = dest(front);
22376 pc = apex(front);
22377 ori = orient3d(pa, pb, pc, steinpt);
22378 if (ori != 0.0) {
22379 if (iscoplanar(pa, pb, pc, steinpt, ori, eps)) {
22380 ori = 0.0; // f is nearly coplanar with p.
22381 }
22382 }
22383 if (ori >= 0.0) {
22384 // f is either invisible or coplanar with p.
22385 if (b->verbose > 2) {
22386 printf(" Remove front (%d, %d, %d).\n", pointmark(pa),
22387 pointmark(pb), pointmark(pc));
22388 }
22389 frontlist->del(i, 1);
22390 expflag = true;
22391 break;
22392 }
22393 }
22394 }
22395 if (expflag) {
22396 assert(!infected(front) && (oppo(front) != NULL));
22397 // Expand C at f by including new fronts.
22398 adjustedgering(front, CCW);
22399 for (i = 0; i < 3; i++) {
22400 newflag = true;
22401 // Get a new boundary n of the cavity.
22402 fnext(front, symfront);
22403 tspivot(symfront, frontsh);
22404 sym(symfront, newfront);
22405 if (frontsh.sh == dummysh) {
22406 assert(newfront.tet != dummytet);
22407 // Is n a front of the unexp. cavity?
22408 if (infected(newfront)) {
22409 for (j = 0; j < frontlist->len(); j++) {
22410 oldfront = * (triface *)(* frontlist)[j];
22411 if ((oldfront.tet == symfront.tet) &&
22412 (oldfront.loc == symfront.loc)) {
22413 // n is not a front anymore.
22414 if (b->verbose > 2) {
22415 printf(" Remove front (%d, %d, %d).\n",
22416 pointmark(org(oldfront)), pointmark(dest(oldfront)),
22417 pointmark(apex(oldfront)));
22418 }
22419 frontlist->del(j, 1);
22420 newflag = false;
22421 break;
22422 }
22423 }
22424 }
22425 } else {
22426 // n is a subface.
22427 if (newfront.tet == dummytet) {
22428 sesymself(frontsh);
22429 // Create a fake tet to hold n.
22430 maketetrahedron(&newfront);
22431 setorg(newfront, sorg(frontsh));
22432 setdest(newfront, sdest(frontsh));
22433 setapex(newfront, sapex(frontsh));
22434 setoppo(newfront, (point) NULL);
22435 tsbond(newfront, frontsh);
22436 } else {
22437 // n should not be a front of cavity yet.
22438 assert(!infected(newfront));
22439 }
22440 }
22441 if (newflag) {
22442 if (b->verbose > 2) {
22443 printf(" Add front (%d, %d, %d).\n", pointmark(org(newfront)),
22444 pointmark(dest(newfront)), pointmark(apex(newfront)));
22445 }
22446 frontlist->append(&newfront);
22447 }
22448 enextself(front);
22449 }
22450 // Add f into oldtetlist (to be deleted).
22451 infect(front);
22452 oldtetlist->append(&front);
22453 expcavcount++;
22454 }
22455 } while (expflag);
22456 }
22457
22458 ///////////////////////////////////////////////////////////////////////////////
22459 // //
22460 // findrelocatepoint() Find new location for relocating a point. //
22461 // //
22462 // 'frontlist' contains the boundary faces of the cavity C. Some fronts are //
22463 // visible by 'stpt' p, some are coplanar with p. //
22464 // //
22465 ///////////////////////////////////////////////////////////////////////////////
22466
22467 bool tetgenmesh::findrelocatepoint(point sp, point np, REAL* n,
22468 list* frontlist, list* oldtetlist)
22469 {
22470 triface front;
22471 point pa, pb, pc;
22472 REAL tp[3], tvol, mvol;
22473 REAL ori, eps;
22474 bool visible;
22475 int i, j, k;
22476
22477 if (b->verbose > 1) {
22478 printf(" Find new location for point %d.\n", pointmark(sp));
22479 }
22480
22481 // Avoid compilation warnings.
22482 tvol = mvol = 0.0;
22483 visible = false;
22484
22485 eps = b->epsilon;
22486 // Initialize np far enough from p (outside C).
22487 for (i = 0; i < 3; i++) np[i] = sp[i] + longest * n[i];
22488 // Let tp = np;
22489 for (i = 0; i < 3; i++) tp[i] = np[i];
22490 // Interation to adjust np until it is visible by all fronts.
22491 j = 0;
22492 do {
22493 for (i = 0; i < frontlist->len(); i++) {
22494 // Get a front face f.
22495 front = * (triface *)(* frontlist)[i];
22496 // Let f face to the interior of C.
22497 adjustedgering(front, CW);
22498 pa = org(front);
22499 pb = dest(front);
22500 pc = apex(front);
22501 ori = orient3d(pa, pb, pc, np);
22502 visible = (ori < 0.0);
22503 if (!visible) {
22504 // A front is invisible by np. Move it towards p along the normal.
22505 for (i = 0; i < 3; i++) np[i] = sp[i] + 0.5 * (sp[i] - np[i]);
22506 // Failed if tp = np.
22507 if ((tp[0] == np[0]) && (tp[1] == np[1]) && (tp[2] == np[2])) {
22508 // Try to expand the cavity.
22509 expandsteinercavity(sp, eps, frontlist, oldtetlist);
22510 eps *= 10.0;
22511 if (eps > b->epsilon * 1000.0) {
22512 // printf("Internal error: Fail to relocate pt %d.\n",pointmark(sp));
22513 // internalerror();
22514 return false;
22515 }
22516 // Restart the point relocation.
22517 for (i = 0; i < 3; i++) np[i] = sp[i] + longest * n[i];
22518 }
22519 if (j % 2) {
22520 // Set tp = np (at every 2 steps) to catch the stop state.
22521 for (i = 0; i < 3; i++) tp[i] = np[i];
22522 }
22523 break;
22524 } else {
22525 // Save the smallest volume.
22526 if (i == 0) {
22527 mvol = fabs(ori);
22528 } else {
22529 mvol = fabs(ori) < mvol ? fabs(ori) : mvol;
22530 }
22531 }
22532 }
22533 j++;
22534 } while (!visible);
22535
22536 if (b->verbose > 1) {
22537 printf(" %d iterations. minvol = %.12g.\n", j, mvol);
22538 }
22539
22540 // Continue to adjust np until the minimal volume of tets formed by
22541 // fronts and np doesn't increase (all fronts are visible by np).
22542 k = 0;
22543 do {
22544 j = 0;
22545 do {
22546 if (k == 0) {
22547 // Initial tp := np + 0.9 * (p - np). Move toward p.
22548 for (i = 0; i < 3; i++) tp[i] = sp[i] + 0.9 * (np[i] - sp[i]);
22549 } else {
22550 // Initial tp := np + 1.1 * (p - np). Move away from p.
22551 for (i = 0; i < 3; i++) tp[i] = sp[i] + 1.1 * (np[i] - sp[i]);
22552 }
22553 // Get the minial volume formed by tp with one of the fronts.
22554 for (i = 0; i < frontlist->len(); i++) {
22555 // Get a front face f.
22556 front = * (triface *)(* frontlist)[i];
22557 // Let f face to the interior of C.
22558 adjustedgering(front, CW);
22559 pa = org(front);
22560 pb = dest(front);
22561 pc = apex(front);
22562 ori = orient3d(pa, pb, pc, tp);
22563 visible = (ori < 0.0);
22564 if (visible) {
22565 // Save the smallest volume.
22566 if (i == 0) {
22567 tvol = fabs(ori);
22568 } else {
22569 tvol = fabs(ori) < tvol ? fabs(ori) : tvol;
22570 }
22571 } else {
22572 // A front is invisible by tp. Stop.
22573 tvol = 0.0;
22574 break;
22575 }
22576 }
22577 if (tvol > mvol) {
22578 // Get a larger minimal volume.
22579 for (i = 0; i < 3; i++) np[i] = tp[i];
22580 mvol = tvol;
22581 } else {
22582 // Minimal volume decreases. Stop.
22583 break;
22584 }
22585 // Continue to adjust np.
22586 j++;
22587 } while (true);
22588 // Has np been adjusted?
22589 if (j > 0) break;
22590 // Try to move np to anoter direction.
22591 k++;
22592 } while (k < 2);
22593
22594 if (b->verbose > 1) {
22595 printf(" %d adjust iterations. minvol = %.12g.\n", j, mvol);
22596 }
22597 return true;
22598 }
22599
22600 ///////////////////////////////////////////////////////////////////////////////
22601 // //
22602 // relocatepoint() Relocate a point into the cavity. //
22603 // //
22604 // 'frontlist' contains the boundary faces of the cavity C. All fronts must //
22605 // be visible by 'steinpt'. Some fronts may hold by 'fake' tets (they are //
22606 // hull faces). Fake tets will be removed when they're finished. //
22607 // //
22608 ///////////////////////////////////////////////////////////////////////////////
22609
22610 void tetgenmesh::relocatepoint(point steinpt, triface* oldtet, list* frontlist,
22611 list* newtetlist, queue* flipque)
22612 {
22613 triface front, newtet, newface, neightet;
22614 face checksh;
22615 point pa, pb;
22616 REAL attrib, volume;
22617 bool bdflag;
22618 int i, j, k, l;
22619
22620 if (b->verbose > 1) {
22621 printf(" Insert Steiner point (%.12g, %.12g, %.12g) %d.\n",
22622 steinpt[0], steinpt[1], steinpt[2], pointmark(steinpt));
22623 }
22624 // Clear the list first.
22625 newtetlist->clear();
22626
22627 // Create the tets formed by fronts and 'steinpt'.
22628 for (i = 0; i < frontlist->len(); i++) {
22629 // Get a front f.
22630 front = * (triface *)(* frontlist)[i];
22631 // Let f face inside C. (f is a face of tet adjacent to C).
22632 adjustedgering(front, CW);
22633 if (b->verbose > 2) {
22634 printf(" Get front (%d, %d, %d).\n", pointmark(org(front)),
22635 pointmark(dest(front)), pointmark(apex(front)));
22636 }
22637 maketetrahedron(&newtet);
22638 newtetlist->append(&newtet);
22639 setorg(newtet, org(front));
22640 setdest(newtet, dest(front));
22641 setapex(newtet, apex(front));
22642 setoppo(newtet, steinpt);
22643 if (oldtet != (triface *) NULL) {
22644 for (j = 0; j < in->numberoftetrahedronattributes; j++) {
22645 attrib = elemattribute(oldtet->tet, j);
22646 setelemattribute(newtet.tet, j, attrib);
22647 }
22648 if (b->varvolume) {
22649 volume = volumebound(oldtet->tet);
22650 setvolumebound(newtet.tet, volume);
22651 }
22652 }
22653 // 'front' may be a 'fake' tet.
22654 tspivot(front, checksh);
22655 if (oppo(front) == (point) NULL) {
22656 if (checksh.sh != dummysh) {
22657 stdissolve(checksh);
22658 }
22659 // Dealloc the 'fake' tet.
22660 tetrahedrondealloc(front.tet);
22661 // This side (newtet) is a boundary face, let 'dummytet' bond to it.
22662 // Otherwise, 'dummytet' may point to a dead tetrahedron after the
22663 // old cavity tets are removed.
22664 dummytet[0] = encode(newtet);
22665 } else {
22666 // Bond two tetrahedra, also dissolve the old bond at 'front'.
22667 bond(newtet, front);
22668 }
22669 if (checksh.sh != dummysh) {
22670 sesymself(checksh);
22671 tsbond(newtet, checksh);
22672 }
22673 if (flipque != (queue *) NULL) {
22674 // f may be non-locally Delaunay and flipable.
22675 enqueueflipface(newtet, flipque);
22676 }
22677 // The three neighbors are open. Will be finished later.
22678 }
22679
22680 // Connect new tets in C. All connecting faces must contain 'steinpt'.
22681 for (i = 0; i < newtetlist->len(); i++) {
22682 newtet = * (triface *)(* newtetlist)[i];
22683 newtet.ver = 0;
22684 for (j = 0; j < 3; j++) {
22685 fnext(newtet, newface);
22686 sym(newface, neightet);
22687 if (neightet.tet == dummytet) {
22688 // Find a neightet to connect it.
22689 bdflag = false;
22690 pa = org(newface);
22691 pb = dest(newface);
22692 assert(apex(newface) == steinpt);
22693 for (k = i + 1; k < newtetlist->len() && !bdflag; k++) {
22694 neightet = * (triface *)(* newtetlist)[k];
22695 neightet.ver = 0;
22696 for (l = 0; l < 3; l++) {
22697 if ((org(neightet) == pa && dest(neightet) == pb) ||
22698 (org(neightet) == pb && dest(neightet) == pa)) {
22699 // Find the neighbor.
22700 fnextself(neightet);
22701 assert(apex(neightet) == steinpt);
22702 // Now neightet is a face same as newface, bond them.
22703 bond(newface, neightet);
22704 bdflag = true;
22705 break;
22706 }
22707 enextself(neightet);
22708 }
22709 }
22710 assert(bdflag);
22711 }
22712 enextself(newtet);
22713 }
22714 // Let the corners of newtet point to it for fast searching.
22715 pa = org(newtet);
22716 setpoint2tet(pa, encode(newtet));
22717 pa = dest(newtet);
22718 setpoint2tet(pa, encode(newtet));
22719 pa = apex(newtet);
22720 setpoint2tet(pa, encode(newtet));
22721 pa = oppo(newtet);
22722 setpoint2tet(pa, encode(newtet));
22723 }
22724
22725 if (flipque != (queue *) NULL) {
22726 // Recover locally Delaunay faces.
22727 flip(flipque, NULL);
22728 }
22729 }
22730
22731 ///////////////////////////////////////////////////////////////////////////////
22732 // //
22733 // findcollapseedge() Find collapseable edge to suppress an endpoint. //
22734 // //
22735 ///////////////////////////////////////////////////////////////////////////////
22736
22737 bool tetgenmesh::findcollapseedge(point suppt, point *conpt, list* oldtetlist,
22738 list* ptlist)
22739 {
22740 triface front;
22741 point pt, pa, pb, pc;
22742 REAL *lenarray, ltmp, ori;
22743 bool visflag;
22744 int *idxarray, itmp;
22745 int n, i, j;
22746
22747 if (b->verbose > 2) {
22748 printf(" Search an edge (in %d edges) for collapse %d.\n",
22749 ptlist->len(), pointmark(suppt));
22750 }
22751
22752 // Candidate edges are p to the points of B(p) (in 'ptlist').
22753 n = ptlist->len();
22754 lenarray = new REAL[n];
22755 idxarray = new int[n];
22756 // Sort the points of B(p) by distance to p.
22757 for (i = 0; i < n; i++) {
22758 pt = * (point *)(* ptlist)[i];
22759 lenarray[i] = distance(suppt, pt);
22760 idxarray[i] = i;
22761 }
22762 // Bubble sort.
22763 for (i = 0; i < n - 1; i++) {
22764 for (j = 0; j < n - 1 - i; j++) {
22765 if (lenarray[j + 1] < lenarray[j]) { // compare the two neighbors
22766 ltmp = lenarray[j]; // swap a[j] and a[j + 1]
22767 lenarray[j] = lenarray[j + 1];
22768 lenarray[j + 1] = ltmp;
22769 itmp = idxarray[j]; // swap a[j] and a[j + 1]
22770 idxarray[j] = idxarray[j + 1];
22771 idxarray[j + 1] = itmp;
22772 }
22773 }
22774 }
22775 // For each point q of B(p), test if the edge (p, q) can be collapseed.
22776 for (i = 0; i < n; i++) {
22777 pt = * (point *)(* ptlist)[idxarray[i]];
22778 // Is q visible by faces of B(p) not with q as a vertex.
22779 lenarray[i] = 0.0; // zero volume.
22780 visflag = true;
22781 for (j = 0; j < oldtetlist->len() && visflag; j++) {
22782 front = * (triface *)(* oldtetlist)[j];
22783 // Let f face to inside of B(p).
22784 adjustedgering(front, CCW);
22785 pa = org(front);
22786 pb = dest(front);
22787 pc = apex(front);
22788 // Is f contains q?
22789 if ((pa != pt) && (pb != pt) && (pc != pt)) {
22790 ori = orient3d(pa, pb, pc, pt);
22791 if (ori != 0.0) {
22792 if (iscoplanar(pa, pb, pc, pt, ori, b->epsilon * 1e+2)) ori = 0.0;
22793 }
22794 visflag = ori < 0.0;
22795 if (visflag) {
22796 // Visible, set the smallest volume.
22797 if (j == 0) {
22798 lenarray[i] = fabs(ori);
22799 } else {
22800 lenarray[i] = fabs(ori) < lenarray[i] ? fabs(ori) : lenarray[i];
22801 }
22802 } else {
22803 // Invisible. Do not collapse (p, q).
22804 lenarray[i] = 0.0;
22805 }
22806 }
22807 }
22808 if ((b->verbose > 2) && visflag) {
22809 printf(" Got candidate %d vol(%g).\n", pointmark(pt), lenarray[i]);
22810 }
22811 }
22812
22813 // Select the largest non-zero volume (result in ltmp).
22814 ltmp = lenarray[0];
22815 itmp = idxarray[0];
22816 for (i = 1; i < n; i++) {
22817 if (lenarray[i] != 0.0) {
22818 if (lenarray[i] > ltmp) {
22819 ltmp = lenarray[i];
22820 itmp = idxarray[i]; // The index to find the point.
22821 }
22822 }
22823 }
22824
22825 delete [] lenarray;
22826 delete [] idxarray;
22827
22828 if (ltmp == 0.0) {
22829 // No edge can be collapseed.
22830 *conpt = (point) NULL;
22831 return false;
22832 } else {
22833 pt = * (point *)(* ptlist)[itmp];
22834 *conpt = pt;
22835 return true;
22836 }
22837 }
22838
22839 ///////////////////////////////////////////////////////////////////////////////
22840 // //
22841 // collapseedge() Remove a point by edge collapse. //
22842 // //
22843 ///////////////////////////////////////////////////////////////////////////////
22844
22845 void tetgenmesh::collapseedge(point suppt, point conpt, list* oldtetlist,
22846 list* deadtetlist)
22847 {
22848 triface oldtet, deadtet;
22849 triface adjtet1, adjtet2;
22850 face adjsh;
22851 point pa, pb, pc;
22852 int i, j;
22853
22854 if (b->verbose > 2) {
22855 printf(" Collapse edge (%d,%d).\n", pointmark(suppt), pointmark(conpt));
22856 }
22857
22858 // Loop in B(p), replace p with np, queue dead tets, uninfect old tets.
22859 for (i = 0; i < oldtetlist->len(); i++) {
22860 oldtet = * (triface *)(* oldtetlist)[i];
22861 assert(!infected(oldtet));
22862 pa = org(oldtet);
22863 pb = dest(oldtet);
22864 pc = apex(oldtet);
22865 assert(oppo(oldtet) == suppt);
22866 setoppo(oldtet, conpt);
22867 if ((pa == conpt) || (pb == conpt) || (pc == conpt)) {
22868 deadtetlist->append(&oldtet); // a collpased tet.
22869 }
22870 }
22871 // Loop in deadtetlist, glue adjacent tets of dead tets.
22872 for (i = 0; i < deadtetlist->len(); i++) {
22873 deadtet = * (triface *)(* deadtetlist)[i];
22874 // Get the adjacent tet n1 (outside B(p)).
22875 sym(deadtet, adjtet1);
22876 tspivot(deadtet, adjsh);
22877 // Find the edge in deadtet opposite to conpt.
22878 adjustedgering(deadtet, CCW);
22879 for (j = 0; j < 3; j++) {
22880 if (apex(deadtet) == conpt) break;
22881 enextself(deadtet);
22882 }
22883 assert(j < 3);
22884 // Get another adjacent tet n2.
22885 fnext(deadtet, adjtet2);
22886 symself(adjtet2);
22887 assert(adjtet2.tet != dummytet); // n2 is inside B(p).
22888 if (adjtet1.tet != dummytet) {
22889 bond(adjtet1, adjtet2); // Bond n1 <--> n2.
22890 } else {
22891 dissolve(adjtet2); // Dissolve at n2.
22892 dummytet[0] = encode(adjtet2); // Let dummytet holds n2.
22893 }
22894 if (adjsh.sh != dummysh) {
22895 tsbond(adjtet2, adjsh); // Bond s <--> n2.
22896 }
22897 // Collapse deadtet.
22898 tetrahedrondealloc(deadtet.tet);
22899 }
22900 deadtetlist->clear();
22901 }
22902
22903 ///////////////////////////////////////////////////////////////////////////////
22904 // //
22905 // deallocfaketets() Deleted fake tets at fronts. //
22906 // //
22907 // This routine is only called when the findrelocatepoint() routine fails. //
22908 // In other cases, the fake tets are removed automatically in carvecavity() //
22909 // or relocatepoint(). //
22910 // //
22911 ///////////////////////////////////////////////////////////////////////////////
22912
22913 void tetgenmesh::deallocfaketets(list* frontlist)
22914 {
22915 triface front, neightet;
22916 face checksh;
22917 bool infectflag;
22918 int i;
22919
22920 for (i = 0; i < frontlist->len(); i++) {
22921 // Get a front f.
22922 front = * (triface *)(* frontlist)[i];
22923 // Let f face inside C. (f is a face of tet adjacent to C).
22924 adjustedgering(front, CW);
22925 sym(front, neightet);
22926 tspivot(front, checksh);
22927 if (oppo(front) == (point) NULL) {
22928 if (b->verbose > 2) {
22929 printf(" Get fake tet (%d, %d, %d).\n", pointmark(org(front)),
22930 pointmark(dest(front)), pointmark(apex(front)));
22931 }
22932 if (neightet.tet != dummytet) {
22933 // The neightet may be infected. After dissolve it, the infect flag
22934 // will be lost. Save the flag and restore it later.
22935 infectflag = infected(neightet);
22936 dissolve(neightet);
22937 if (infectflag) {
22938 infect(neightet);
22939 }
22940 }
22941 if (checksh.sh != dummysh) {
22942 infectflag = sinfected(checksh);
22943 stdissolve(checksh);
22944 if (infectflag) {
22945 sinfect(checksh);
22946 }
22947 }
22948 // Dealloc the 'fake' tet.
22949 tetrahedrondealloc(front.tet);
22950 // This side (neightet) is a boundary face, let 'dummytet' bond to it.
22951 dummytet[0] = encode(neightet);
22952 }
22953 }
22954 }
22955
22956 ///////////////////////////////////////////////////////////////////////////////
22957 // //
22958 // restorepolyhedron() Restore the tetrahedralization in a polyhedron. //
22959 // //
22960 // This routine is only called when the operation of suppressing a point is //
22961 // aborted (eg., findrelocatepoint() routine fails). The polyhedron has been //
22962 // remeshed by new tets. This routine restore the old tets in it. //
22963 // //
22964 // 'oldtetlist' contains the list of old tets. Each old tet t_o assumes that //
22965 // it still connects to a tet t_b of the mesh, however, t_b does not connect //
22966 // to t_o, this routine resets the connection such that t_b <--> t_o. //
22967 // //
22968 ///////////////////////////////////////////////////////////////////////////////
22969
22970 void tetgenmesh::restorepolyhedron(list* oldtetlist)
22971 {
22972 triface oldtet, neightet, neineitet;
22973 face checksh;
22974 int i;
22975
22976 for (i = 0; i < oldtetlist->len(); i++) {
22977 // Get an old tet t_o.
22978 oldtet = * (triface *)(* oldtetlist)[i];
22979 // Check the four sides of t_o.
22980 for (oldtet.loc = 0; oldtet.loc < 4; oldtet.loc++) {
22981 sym(oldtet, neightet);
22982 tspivot(oldtet, checksh);
22983 if (neightet.tet != dummytet) {
22984 sym(neightet, neineitet);
22985 if (neineitet.tet != oldtet.tet) {
22986 // This face of t_o is a boundary of P.
22987 bond(neightet, oldtet);
22988 if (checksh.sh != dummysh) {
22989 tsbond(oldtet, checksh);
22990 }
22991 }
22992 } else {
22993 // t_o has a hull face. It should be the boundary of P.
22994 #ifdef SELF_CHECK
22995 assert(checksh.sh != dummysh);
22996 stpivot(checksh, neineitet);
22997 assert(neineitet.tet != oldtet.tet);
22998 #endif
22999 tsbond(oldtet, checksh);
23000 // Let dummytet[0] points to it.
23001 dummytet[0] = encode(oldtet);
23002 }
23003 }
23004 }
23005 }
23006
23007 ///////////////////////////////////////////////////////////////////////////////
23008 // //
23009 // suppressfacetpoint() Suppress a point inside a facet. //
23010 // //
23011 // The point p inside a facet F will be suppressed from F by either being //
23012 // deleted from the mesh or being relocated into the volume. //
23013 // //
23014 // 'supsh' is a subface f of F, and p = sapex(f); the other parameters are //
23015 // working lists which are empty at the beginning and the end. //
23016 // //
23017 ///////////////////////////////////////////////////////////////////////////////
23018
23019 bool tetgenmesh::suppressfacetpoint(face* supsh, list* frontlist,
23020 list* misfrontlist, list* ptlist, list* conlist, memorypool* viri,
23021 queue* flipque)
23022 {
23023 list *oldtetlist[2], *newtetlist[2];
23024 list *oldshlist, *newshlist;
23025 triface oldtet, newtet;
23026 face oldsh, newsh;
23027 point suppt, newpt[2];
23028 point *cons;
23029 REAL norm[3];
23030 bool success;
23031 int shmark;
23032 int i, j;
23033
23034 suppt = sapex(*supsh);
23035 if (b->verbose > 1) {
23036 printf(" Suppress point %d in facet.\n", pointmark(suppt));
23037 }
23038
23039 // Initialize working lists, variables.
23040 for (i = 0; i < 2; i++) {
23041 oldtetlist[i] = (list *) NULL;
23042 newtetlist[i] = (list *) NULL;
23043 newpt[i] = (point) NULL;
23044 }
23045 oldshlist = new list(sizeof(face), NULL, 256);
23046 newshlist = new list(sizeof(face), NULL, 256);
23047 success = true; // Assume p can be suppressed.
23048
23049 // Find subs of C(p).
23050 oldshlist->append(supsh);
23051 formstarpolygon(suppt, oldshlist, ptlist);
23052 // Get the edges of C(p). They form a closed polygon.
23053 for (i = 0; i < oldshlist->len(); i++) {
23054 oldsh = * (face *)(* oldshlist)[i];
23055 cons = (point *) conlist->append(NULL);
23056 cons[0] = sorg(oldsh);
23057 cons[1] = sdest(oldsh);
23058 }
23059 // Re-triangulate the old C(p).
23060 shmark = shellmark(*supsh);
23061 triangulate(shmark, b->epsilon, ptlist, conlist, 0, NULL, viri, flipque);
23062 // Get new subs of C(p), remove protected segments.
23063 retrievenewsubs(newshlist, true);
23064 // Substitute the old C(p) with the new C(p)
23065 replacepolygonsubs(oldshlist, newshlist);
23066 // Clear work lists.
23067 ptlist->clear();
23068 conlist->clear();
23069 flipque->clear();
23070 viri->restart();
23071
23072 // B(p) (tets with p as a vertex) has been separated into two parts
23073 // (B_0(p) and B_1(p)) by F. Process them individually.
23074 for (i = 0; i < 2 && success; i++) {
23075 if (i == 1) sesymself(*supsh);
23076 // Get a tet containing p.
23077 stpivot(*supsh, oldtet);
23078 // Is this part empty?
23079 if (oldtet.tet == dummytet) continue;
23080 // Allocate spaces for storing (old and new) B_i(p).
23081 oldtetlist[i] = new list(sizeof(triface), NULL, 256);
23082 newtetlist[i] = new list(sizeof(triface), NULL, 256);
23083 // Form old B_i(p) in oldtetlist[i].
23084 assert(!isdead(&oldtet));
23085 oldtetlist[i]->append(&oldtet);
23086 formstarpolyhedron(suppt, oldtetlist[i], ptlist, false);
23087 // Infect the tets in old B_i(p) (they're going to be delete).
23088 for (j = 0; j < oldtetlist[i]->len(); j++) {
23089 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23090 infect(oldtet);
23091 }
23092 // Preparation for re-tetrahedralzing old B_i(p).
23093 orientnewsubs(newshlist, supsh, norm);
23094 // Tetrahedralize old B_i(p).
23095 if (!constrainedcavity(&oldtet, newshlist, oldtetlist[i], ptlist,
23096 frontlist, misfrontlist, newtetlist[i], flipque)) {
23097 // Unable to mesh old B_i(p), try to relocate p into it.
23098 makepoint(&(newpt[i]));
23099 success = findrelocatepoint(suppt, newpt[i], norm, frontlist,
23100 oldtetlist[i]);
23101 if (success) {
23102 // p is relocated by newpt[i]. Now insert it. Don't do flip since
23103 // the new tets may get deleted again.
23104 relocatepoint(newpt[i], &oldtet, frontlist, newtetlist[i], NULL);
23105 setpointtype(newpt[i], FREEVOLVERTEX);
23106 relverts++;
23107 } else {
23108 // Fail to relocate p. Clean fake tets and quit this option.
23109 deallocfaketets(frontlist);
23110 pointdealloc(newpt[i]);
23111 newpt[i] = (point) NULL;
23112 assert(newtetlist[i]->len() == 0);
23113 }
23114 }
23115 // Clear work lists.
23116 ptlist->clear();
23117 frontlist->clear();
23118 misfrontlist->clear();
23119 flipque->clear();
23120 }
23121
23122 if (success) {
23123 // p has been removed! (Still in the pool).
23124 setpointtype(suppt, UNUSEDVERTEX);
23125 unuverts++;
23126 // Delete old C(p).
23127 for (i = 0; i < oldshlist->len(); i++) {
23128 oldsh = * (face *)(* oldshlist)[i];
23129 if (i == 0) {
23130 // Update the 'hullsize' if C(p) is on the hull.
23131 stpivot(oldsh, oldtet);
23132 if (oldtet.tet != dummytet) {
23133 sesymself(oldsh);
23134 stpivot(oldsh, oldtet);
23135 }
23136 if (oldtet.tet == dummytet) {
23137 // A boundary face. Update the 'hullsize'.
23138 j = oldshlist->len() - newshlist->len();
23139 assert(j > 0);
23140 hullsize -= j;
23141 }
23142 }
23143 shellfacedealloc(subfaces, oldsh.sh);
23144 }
23145 // Delete old B_i(p).
23146 for (i = 0; i < 2; i++) {
23147 if (oldtetlist[i] != (list *) NULL) {
23148 // Delete tets of the old B_i(p).
23149 for (j = 0; j < oldtetlist[i]->len(); j++) {
23150 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23151 assert(!isdead(&oldtet));
23152 tetrahedrondealloc(oldtet.tet);
23153 }
23154 }
23155 }
23156 } else {
23157 // p is not suppressed. Recover the original state.
23158 unsupverts++;
23159 // Restore the old C(p).
23160 replacepolygonsubs(newshlist, oldshlist);
23161 // Delete subs of the new C(p)
23162 for (i = 0; i < newshlist->len(); i++) {
23163 newsh = * (face *)(* newshlist)[i];
23164 shellfacedealloc(subfaces, newsh.sh);
23165 }
23166 // Restore old B_i(p).
23167 for (i = 0; i < 2; i++) {
23168 if (oldtetlist[i] != (list *) NULL) {
23169 // Uninfect tets of old B_i(p).
23170 for (j = 0; j < oldtetlist[i]->len(); j++) {
23171 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23172 assert(infected(oldtet));
23173 uninfect(oldtet);
23174 }
23175 // Has it been re-meshed?
23176 if (newtetlist[i]->len() > 0) {
23177 // Restore the old B_i(p).
23178 restorepolyhedron(oldtetlist[i]);
23179 // Delete tets of the new B_i(p);
23180 for (j = 0; j < newtetlist[i]->len(); j++) {
23181 newtet = * (triface *)(* (newtetlist[i]))[j];
23182 // Some new tets may already be deleted (by carvecavity()).
23183 if (!isdead(&newtet)) {
23184 tetrahedrondealloc(newtet.tet);
23185 }
23186 }
23187 }
23188 // Dealloc newpt[i] if it exists.
23189 if (newpt[i] != (point) NULL) {
23190 pointdealloc(newpt[i]);
23191 relverts--;
23192 }
23193 }
23194 }
23195 }
23196
23197 // Delete work lists.
23198 delete oldshlist;
23199 delete newshlist;
23200 for (i = 0; i < 2; i++) {
23201 if (oldtetlist[i] != (list *) NULL) {
23202 delete oldtetlist[i];
23203 delete newtetlist[i];
23204 }
23205 }
23206
23207 return success;
23208 }
23209
23210 ///////////////////////////////////////////////////////////////////////////////
23211 // //
23212 // suppresssegpoint() Suppress a point on a segment. //
23213 // //
23214 // The point p on a segment S will be suppressed from S by either being //
23215 // deleted from the mesh or being relocated into the volume. //
23216 // //
23217 // 'supseg' is the segment S, and p = sdest(S); the other parameters are //
23218 // working lists which are empty at the beginning and the end. //
23219 // //
23220 ///////////////////////////////////////////////////////////////////////////////
23221
23222 bool tetgenmesh::suppresssegpoint(face* supseg, list* spinshlist,
23223 list* newsegshlist, list* frontlist, list* misfrontlist, list* ptlist,
23224 list* conlist, memorypool* viri, queue* flipque)
23225 {
23226 list **oldtetlist, **newtetlist;
23227 list **oldshlist, **newshlist;
23228 list *pnewshlist, *dnewshlist;
23229 triface oldtet, newtet;
23230 face oldsh, newsh;
23231 face startsh, spinsh, segsh1, segsh2;
23232 face nsupseg, newseg, prevseg, nextseg;
23233 point suppt, *newpt;
23234 point pa, pb, *cons;
23235 REAL norm[3], pnorm[2][3];
23236 bool success;
23237 int shmark;
23238 int n, i, j, k;
23239
23240 // Get the Steiner point p.
23241 assert(supseg->shver == 0);
23242 suppt = sdest(*supseg);
23243 // Find the segment ab split by p.
23244 senext(*supseg, nsupseg);
23245 spivotself(nsupseg);
23246 assert(nsupseg.sh != dummysh);
23247 nsupseg.shver = 0;
23248 assert(sorg(nsupseg) == suppt);
23249 pa = sorg(*supseg);
23250 pb = sdest(nsupseg);
23251 if (b->verbose > 1) {
23252 printf(" Remove point %d on segment (%d, %d).\n",
23253 pointmark(suppt), pointmark(pa), pointmark(pb));
23254 }
23255
23256 // Let startsh s containing p.
23257 spivot(*supseg, startsh);
23258 spinsh = startsh;
23259 do {
23260 // Save it in list.
23261 spinshlist->append(&spinsh);
23262 // Go to the next facet.
23263 spivotself(spinsh);
23264 } while (spinsh.sh != startsh.sh);
23265 if (spinshlist->len() == 1) {
23266 // This case has not handled yet.
23267 // printf("Unhandled case: segment only belongs to one facet.\n");
23268 spinshlist->clear();
23269 unsupverts++;
23270 return false;
23271 }
23272
23273 // Suppose ab is shared by n facets (n > 1), then there are n B(p) (tets
23274 // with p as a vertex). Some B(p) may be empty, eg, outside.
23275 n = spinshlist->len();
23276 oldtetlist = new list*[n];
23277 newtetlist = new list*[n];
23278 oldshlist = new list*[n];
23279 newshlist = new list*[n];
23280 newpt = new point[n];
23281 for (i = 0; i < n; i++) {
23282 oldtetlist[i] = (list *) NULL;
23283 newtetlist[i] = (list *) NULL;
23284 oldshlist[i] = (list *) NULL;
23285 newshlist[i] = (list *) NULL;
23286 newpt[i] = (point) NULL;
23287 }
23288
23289 // Create a new segment ab (result in newseg).
23290 makeshellface(subsegs, &newseg);
23291 setsorg(newseg, pa);
23292 setsdest(newseg, pb);
23293 // ab gets the same mark and segment type as ap.
23294 setshellmark(newseg, shellmark(*supseg));
23295 setshelltype(newseg, shelltype(*supseg));
23296 if (b->quality && varconstraint) {
23297 // Copy the areabound into the new subsegment.
23298 setareabound(newseg, areabound(*supseg));
23299 }
23300 // Save the old connection at a.
23301 senext2(*supseg, prevseg);
23302 spivotself(prevseg);
23303 if (prevseg.sh != dummysh) {
23304 prevseg.shver = 0;
23305 assert(sdest(prevseg) == pa);
23306 senextself(prevseg);
23307 senext2self(newseg);
23308 sbond(newseg, prevseg);
23309 newseg.shver = 0;
23310 }
23311 // Save the old connection at b.
23312 senext(nsupseg, nextseg);
23313 spivotself(nextseg);
23314 if (nextseg.sh != dummysh) {
23315 nextseg.shver = 0;
23316 assert(sorg(nextseg) == pb);
23317 senext2self(nextseg);
23318 senextself(newseg);
23319 sbond(newseg, nextseg);
23320 newseg.shver = 0;
23321 }
23322
23323 // Re-triangulate C(p) (subs with p as a vertex) to remove p.
23324 for (i = 0; i < spinshlist->len(); i++) {
23325 spinsh = * (face *)(* spinshlist)[i];
23326 // Allocate spaces for C_i(p).
23327 oldshlist[i] = new list(sizeof(face), NULL, 256);
23328 newshlist[i] = new list(sizeof(face), NULL, 256);
23329 // Get the subs of C_i(p).
23330 oldshlist[i]->append(&spinsh);
23331 formstarpolygon(suppt, oldshlist[i], ptlist);
23332 // Find the edges of C_i(p). It DOES NOT form a closed polygon.
23333 for (j = 0; j < oldshlist[i]->len(); j++) {
23334 oldsh = * (face *)(* (oldshlist[i]))[j];
23335 cons = (point *) conlist->append(NULL);
23336 cons[0] = sorg(oldsh);
23337 cons[1] = sdest(oldsh);
23338 }
23339 // The C_i(p) isn't closed without ab. Add it to it.
23340 cons = (point *) conlist->append(NULL);
23341 cons[0] = pa;
23342 cons[1] = pb;
23343 // Re-triangulate C_i(p).
23344 shmark = shellmark(spinsh);
23345 triangulate(shmark, b->epsilon, ptlist, conlist, 0, NULL, viri, flipque);
23346 // Get new subs of C_i(p), remove protected segments.
23347 retrievenewsubs(newshlist[i], true);
23348 // Substitute old C_i(p) with the new C_i(p). !IT IS NOT COMPLETE!
23349 replacepolygonsubs(oldshlist[i], newshlist[i]);
23350 // Find the new subface s having edge ab.
23351 for (j = 0; j < newshlist[i]->len(); j++) {
23352 segsh1 = * (face *)(* (newshlist[i]))[j];
23353 for (k = 0; k < 3; k++) {
23354 if (((sorg(segsh1) == pa) && (sdest(segsh1) == pb)) ||
23355 ((sorg(segsh1) == pb) && (sdest(segsh1) == pa))) break;
23356 senextself(segsh1);
23357 }
23358 if (k < 3) break; // Found.
23359 }
23360 assert(j < newshlist[i]->len()); // ab must exist.
23361 // Bond s and ab together. The C_i(p) is completedly substituted.
23362 ssbond(segsh1, newseg);
23363 // Save s for forming the face ring of ab.
23364 newsegshlist->append(&segsh1);
23365 // Clear work lists.
23366 ptlist->clear();
23367 conlist->clear();
23368 flipque->clear();
23369 viri->restart();
23370 }
23371 // Form the face ring of ab.
23372 for (i = 0; i < newsegshlist->len(); i++) {
23373 segsh1 = * (face *)(* newsegshlist)[i];
23374 if ((i + 1) == newsegshlist->len()) {
23375 segsh2 = * (face *)(* newsegshlist)[0];
23376 } else {
23377 segsh2 = * (face *)(* newsegshlist)[i + 1];
23378 }
23379 sbond1(segsh1, segsh2);
23380 }
23381
23382 // A work list for keeping subfaces from two facets.
23383 dnewshlist = new list(sizeof(face), NULL, 256);
23384 success = true; // Assume p is suppressable.
23385
23386 // Suppress p in all B(p). B_i(p) is looped wrt the right-hand rule of ab.
23387 for (i = 0; i < spinshlist->len() && success; i++) {
23388 // Get an old subface s (ap) of a facet.
23389 spinsh = * (face *)(* spinshlist)[i];
23390 // Let the edge direction of s be a->b. Hence all subfaces follow
23391 // the right-hand rule of ab.
23392 if (sorg(spinsh) != pa) sesymself(spinsh);
23393 // Get a tet t of B_i(p).
23394 stpivot(spinsh, oldtet);
23395 // Is B_i(p) empty?
23396 if (oldtet.tet == dummytet) continue;
23397 // Allocate spaces for B_i(p).
23398 oldtetlist[i] = new list(sizeof(triface), NULL, 256);
23399 newtetlist[i] = new list(sizeof(triface), NULL, 256);
23400 // Find all tets of old B_i(p).
23401 oldtetlist[i]->append(&oldtet);
23402 formstarpolyhedron(suppt, oldtetlist[i], ptlist, false);
23403 // Infect tets of old B_i(p) (they're going to be deleted).
23404 for (j = 0; j < oldtetlist[i]->len(); j++) {
23405 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23406 infect(oldtet);
23407 }
23408 // Collect new subfaces (of two facets) bounded B_i(p).
23409 for (k = 0; k < 2; k++) {
23410 if ((i + k) < spinshlist->len()) {
23411 pnewshlist = newshlist[i + k];
23412 segsh1 = * (face *)(* spinshlist)[i + k];
23413 } else {
23414 pnewshlist = newshlist[0];
23415 segsh1 = * (face *)(* spinshlist)[0];
23416 }
23417 // Adjust the orientation of segsh1 to face to the inside of C.
23418 if (k == 0) {
23419 if (sorg(segsh1) != pa) sesymself(segsh1);
23420 assert(sorg(segsh1) == pa);
23421 } else {
23422 if (sdest(segsh1) != pa) sesymself(segsh1);
23423 assert(sdest(segsh1) == pa);
23424 }
23425 // Preparation for re-tetrahedralzing old B_i(p).
23426 orientnewsubs(pnewshlist, &segsh1, pnorm[k]);
23427 for (j = 0; j < pnewshlist->len(); j++) {
23428 dnewshlist->append((face *)(* pnewshlist)[j]);
23429 }
23430 }
23431 // Tetrahedralize B_i(p).
23432 if (!constrainedcavity(&oldtet, dnewshlist, oldtetlist[i], ptlist,
23433 frontlist, misfrontlist, newtetlist[i], flipque)) {
23434 // C must be finished by re-locating the steiner point.
23435 makepoint(&(newpt[i]));
23436 for (j = 0; j < 3; j++) norm[j] = 0.5 * (pnorm[0][j] + pnorm[1][j]);
23437 success = findrelocatepoint(suppt, newpt[i], norm, frontlist,
23438 oldtetlist[i]);
23439 if (success) {
23440 // p is relocated by newpt[i]. Now insert it. Don't do flip since
23441 // the new tets may get deleted again.
23442 relocatepoint(newpt[i], &oldtet, frontlist, newtetlist[i], NULL);
23443 setpointtype(newpt[i], FREEVOLVERTEX);
23444 relverts++;
23445 } else {
23446 // Fail to relocate p. Clean fake tets and quit this option.
23447 deallocfaketets(frontlist);
23448 pointdealloc(newpt[i]);
23449 newpt[i] = (point) NULL;
23450 assert(newtetlist[i]->len() == 0);
23451 }
23452 }
23453 // Clear work lists.
23454 dnewshlist->clear();
23455 ptlist->clear();
23456 frontlist->clear();
23457 misfrontlist->clear();
23458 flipque->clear();
23459 }
23460
23461 if (success) {
23462 // p has been suppressed. (Still in the pool).
23463 setpointtype(suppt, UNUSEDVERTEX);
23464 unuverts++;
23465 // Delete old segments ap, pb.
23466 shellfacedealloc(subsegs, supseg->sh);
23467 shellfacedealloc(subsegs, nsupseg.sh);
23468 // Delete subs of old C_i(p).
23469 for (i = 0; i < spinshlist->len(); i++) {
23470 for (j = 0; j < oldshlist[i]->len(); j++) {
23471 oldsh = * (face *)(* (oldshlist[i]))[j];
23472 if (j == 0) {
23473 // Update 'hullsize' if C_i(p) is on the hull.
23474 stpivot(oldsh, oldtet);
23475 if (oldtet.tet != dummytet) {
23476 sesymself(oldsh);
23477 stpivot(oldsh, oldtet);
23478 }
23479 if (oldtet.tet == dummytet) {
23480 // Update 'hullsize'.
23481 k = oldshlist[i]->len() - newshlist[i]->len();
23482 assert(k > 0);
23483 hullsize -= k;
23484 }
23485 }
23486 shellfacedealloc(subfaces, oldsh.sh);
23487 }
23488 }
23489 // Delete tets old B_i(p).
23490 for (i = 0; i < spinshlist->len(); i++) {
23491 // Delete them if it is not empty.
23492 if (oldtetlist[i] != (list *) NULL) {
23493 for (j = 0; j < oldtetlist[i]->len(); j++) {
23494 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23495 assert(!isdead(&oldtet));
23496 tetrahedrondealloc(oldtet.tet);
23497 }
23498 }
23499 }
23500 } else {
23501 // p is not suppressed. Recover the original state.
23502 unsupverts++;
23503 // Restore old connection at a.
23504 senext2(*supseg, prevseg);
23505 spivotself(prevseg);
23506 if (prevseg.sh != dummysh) {
23507 prevseg.shver = 0;
23508 assert(sdest(prevseg) == pa);
23509 senextself(prevseg);
23510 senext2self(*supseg);
23511 sbond(*supseg, prevseg);
23512 supseg->shver = 0;
23513 }
23514 // Restore old connection at b.
23515 senext(nsupseg, nextseg);
23516 spivotself(nextseg);
23517 if (nextseg.sh != dummysh) {
23518 nextseg.shver = 0;
23519 assert(sorg(nextseg) == pb);
23520 senext2self(nextseg);
23521 senextself(nsupseg);
23522 sbond(nsupseg, nextseg);
23523 nsupseg.shver = 0;
23524 }
23525 // Delete the new segment ab.
23526 shellfacedealloc(subsegs, newseg.sh);
23527 // Restore old C_i(p).
23528 for (i = 0; i < spinshlist->len(); i++) {
23529 replacepolygonsubs(newshlist[i], oldshlist[i]);
23530 // Delete subs of the new C_i(p)
23531 for (j = 0; j < newshlist[i]->len(); j++) {
23532 newsh = * (face *)(* (newshlist[i]))[j];
23533 shellfacedealloc(subfaces, newsh.sh);
23534 }
23535 }
23536 // Restore old B_i(p).
23537 for (i = 0; i < spinshlist->len(); i++) {
23538 if (oldtetlist[i] != (list *) NULL) {
23539 // Uninfect tets of old B_i(p).
23540 for (j = 0; j < oldtetlist[i]->len(); j++) {
23541 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23542 assert(infected(oldtet));
23543 uninfect(oldtet);
23544 }
23545 // Has it been re-meshed?
23546 if (newtetlist[i]->len() > 0) {
23547 // Restore the old B_i(p).
23548 restorepolyhedron(oldtetlist[i]);
23549 // Delete tets of the new B_i(p);
23550 for (j = 0; j < newtetlist[i]->len(); j++) {
23551 newtet = * (triface *)(* (newtetlist[i]))[j];
23552 // Some new tets may already be deleted (by carvecavity()).
23553 if (!isdead(&newtet)) {
23554 tetrahedrondealloc(newtet.tet);
23555 }
23556 }
23557 }
23558
23559 // Dealloc newpt[i] if it exists.
23560 if (newpt[i] != (point) NULL) {
23561 pointdealloc(newpt[i]);
23562 relverts--;
23563 }
23564 }
23565 }
23566 }
23567
23568 // Delete work lists.
23569 delete dnewshlist;
23570 for (i = 0; i < spinshlist->len(); i++) {
23571 delete oldshlist[i];
23572 delete newshlist[i];
23573 }
23574 delete [] oldshlist;
23575 delete [] newshlist;
23576 for (i = 0; i < spinshlist->len(); i++) {
23577 if (oldtetlist[i] != (list *) NULL) {
23578 delete oldtetlist[i];
23579 delete newtetlist[i];
23580 }
23581 }
23582 delete [] oldtetlist;
23583 delete [] newtetlist;
23584 // Clear work lists.
23585 newsegshlist->clear();
23586 spinshlist->clear();
23587
23588 return success;
23589 }
23590
23591 ///////////////////////////////////////////////////////////////////////////////
23592 // //
23593 // suppressvolpoint() Suppress a point inside mesh. //
23594 // //
23595 // The point p inside the mesh will be suppressed by being deleted from the //
23596 // mesh. p may not be suppressed. //
23597 // //
23598 ///////////////////////////////////////////////////////////////////////////////
23599
23600 bool tetgenmesh::suppressvolpoint(point suppt, list* frontlist,
23601 list* misfrontlist, list* ptlist, queue* flipque)
23602 {
23603 list *oldtetlist, *newtetlist;
23604 list *newshlist; // a dummy list.
23605 tetrahedron tetptr;
23606 triface oldtet, newtet;
23607 bool success;
23608 int j;
23609
23610 if (b->verbose > 1) {
23611 printf(" Remove point %d in mesh.\n", pointmark(suppt));
23612 }
23613
23614 // Get a tet with p as a vertex.
23615 oldtet.tet = (tetrahedron *) NULL;
23616 tetptr = point2tet(suppt);
23617 if (tetptr != (tetrahedron) NULL) {
23618 decode(tetptr, oldtet);
23619 }
23620 // Make sure oldtet contains p.
23621 if (isdead(&oldtet) || !findorg(&oldtet, suppt)) {
23622 // The pointer is invalid. Recreate the map.
23623 makepoint2tetmap();
23624 tetptr = point2tet(suppt);
23625 decode(tetptr, oldtet);
23626 if (isdead(&oldtet)) {
23627 // There is no tet contain p, it is indeed an unused point.
23628 // expandsteinercavity() deleted all tets of p.
23629 setpointtype(suppt, UNUSEDVERTEX);
23630 unuverts++;
23631 return true;
23632 }
23633 }
23634
23635 // Allocate spaces for storing (old and new) B(p).
23636 oldtetlist = new list(sizeof(triface), NULL, 256);
23637 newtetlist = new list(sizeof(triface), NULL, 256);
23638 newshlist = new list(sizeof(face), NULL, 256);
23639 success = true; // Assume p can be suppressed.
23640
23641 // Form old B(p) in oldtetlist.
23642 oldtetlist->append(&oldtet);
23643 formstarpolyhedron(suppt, oldtetlist, ptlist, false);
23644 // Infect the tets in old B(p) (they're going to be delete).
23645 for (j = 0; j < oldtetlist->len(); j++) {
23646 oldtet = * (triface *)(* oldtetlist)[j];
23647 infect(oldtet);
23648 }
23649 // Tetrahedralize old B(p).
23650 if (!constrainedcavity(&oldtet, newshlist, oldtetlist, ptlist, frontlist,
23651 misfrontlist, newtetlist, flipque)) {
23652 // Unable to suppress p.
23653 success = false;
23654 // Clean fake tets and quit this option.
23655 deallocfaketets(frontlist);
23656 assert(newtetlist->len() == 0);
23657 }
23658 // Clear work lists.
23659 ptlist->clear();
23660 frontlist->clear();
23661 misfrontlist->clear();
23662 flipque->clear();
23663
23664 if (success) {
23665 // p has been removed! (Still in the pool).
23666 setpointtype(suppt, UNUSEDVERTEX);
23667 unuverts++;
23668 suprelverts++;
23669 // Delete old B(p).
23670 for (j = 0; j < oldtetlist->len(); j++) {
23671 oldtet = * (triface *)(* oldtetlist)[j];
23672 assert(!isdead(&oldtet));
23673 tetrahedrondealloc(oldtet.tet);
23674 }
23675 } else {
23676 // p is not suppressed. Recover the original state.
23677 // Uninfect tets of old B(p).
23678 for (j = 0; j < oldtetlist->len(); j++) {
23679 oldtet = * (triface *)(* oldtetlist)[j];
23680 assert(infected(oldtet));
23681 uninfect(oldtet);
23682 }
23683 }
23684
23685 delete oldtetlist;
23686 delete newtetlist;
23687 delete newshlist;
23688
23689 return success;
23690 }
23691
23692 ///////////////////////////////////////////////////////////////////////////////
23693 // //
23694 // collapseedgepoint() Delete a point by edge collapse. //
23695 // //
23696 ///////////////////////////////////////////////////////////////////////////////
23697
23698 bool tetgenmesh::collapseedgepoint(point colpt, list *oldtetlist,
23699 list* deadtetlist, list *ptlist)
23700 {
23701 tetrahedron tetptr;
23702 triface oldtet, newtet;
23703 point conpt;
23704 bool success;
23705
23706 if (b->verbose > 1) {
23707 printf(" Collapse point %d.\n", pointmark(colpt));
23708 }
23709
23710 // Get a tet with p as a vertex.
23711 oldtet.tet = (tetrahedron *) NULL;
23712 tetptr = point2tet(colpt);
23713 if (tetptr != (tetrahedron) NULL) {
23714 decode(tetptr, oldtet);
23715 }
23716 // Make sure oldtet contains p.
23717 if (isdead(&oldtet) || !findorg(&oldtet, colpt)) {
23718 // The pointer is invalid. Recreate the map.
23719 makepoint2tetmap();
23720 tetptr = point2tet(colpt);
23721 decode(tetptr, oldtet);
23722 if (isdead(&oldtet)) {
23723 // There is no tet contain p, it is indeed an unused point.
23724 // expandsteinercavity() deleted all tets of p.
23725 setpointtype(colpt, UNUSEDVERTEX);
23726 unuverts++;
23727 return true;
23728 }
23729 }
23730
23731 // Form old B(p) in oldtetlist.
23732 oldtetlist->append(&oldtet);
23733 formstarpolyhedron(colpt, oldtetlist, ptlist, false);
23734 // Try to collapse p.
23735 success = findcollapseedge(colpt, &conpt, oldtetlist, ptlist);
23736 if (success) {
23737 // Collapse p by edge contraction.
23738 collapseedge(colpt, conpt, oldtetlist, deadtetlist);
23739 collapverts++;
23740 // p has been removed! (Still in the pool).
23741 setpointtype(colpt, UNUSEDVERTEX);
23742 unuverts++;
23743 deadtetlist->clear();
23744 }
23745 oldtetlist->clear();
23746 ptlist->clear();
23747
23748 return success;
23749 }
23750
23751 ///////////////////////////////////////////////////////////////////////////////
23752 // //
23753 // removesteiners() Delete or relocate Steiner points on facets. //
23754 // //
23755 ///////////////////////////////////////////////////////////////////////////////
23756
23757 void tetgenmesh::removesteiners()
23758 {
23759 list *frontlist, *misfrontlist;
23760 list *spinshlist, *newsegshlist;
23761 list *ptlist, *conlist;
23762 memorypool *viri;
23763 queue *flipque;
23764 triface checktet;
23765 face shloop;
23766 face segloop, nextseg;
23767 point pa;
23768 bool remflag;
23769 int oldnum, rmstein;
23770 int i;
23771
23772 // Initiliaze work lists.
23773 frontlist = new list(sizeof(triface), NULL);
23774 misfrontlist = new list(sizeof(triface), NULL);
23775 spinshlist = new list(sizeof(face), NULL);
23776 newsegshlist = new list(sizeof(face), NULL);
23777 ptlist = new list(sizeof(point *), NULL);
23778 conlist = new list(sizeof(point *) * 2, NULL);
23779 flipque = new queue(sizeof(badface));
23780 viri = new memorypool(sizeof(shellface *), 1024, POINTER, 0);
23781 oldnum = unuverts;
23782 relverts = suprelverts = collapverts = unsupverts = 0;
23783 expcavcount = 0;
23784
23785 if (!b->quiet) {
23786 printf("Removing Steiner points.\n");
23787 }
23788
23789 // Suppress Steiner points inside facets.
23790 do {
23791 rmstein = unuverts;
23792 subfaces->traversalinit();
23793 shloop.sh = shellfacetraverse(subfaces);
23794 while (shloop.sh != (shellface *) NULL) {
23795 remflag = false;
23796 // Is s contains a Steiner point?
23797 shloop.shver = 0;
23798 for (i = 0; i < 3; i++) {
23799 pa = sapex(shloop);
23800 if (pointtype(pa) == FREESUBVERTEX) {
23801 // Find a Steiner point p.
23802 if (b->nobisect == 1) {
23803 // '-Y'. Remove p if s is a hull face.
23804 stpivot(shloop, checktet);
23805 if (checktet.tet != dummytet) {
23806 sesymself(shloop);
23807 stpivot(shloop, checktet);
23808 }
23809 remflag = (checktet.tet == dummytet);
23810 } else {
23811 // '-YY'. Remove p whatever s is a hull face or not.
23812 remflag = true;
23813 }
23814 break;
23815 }
23816 senextself(shloop);
23817 }
23818 if (remflag) {
23819 suppressfacetpoint(&shloop, frontlist, misfrontlist, ptlist, conlist,
23820 viri, flipque);
23821 }
23822 shloop.sh = shellfacetraverse(subfaces);
23823 }
23824 // Continue if any Steiner point has been removed.
23825 } while (unuverts > rmstein);
23826
23827 // Suppress Steiner points on segments.
23828 do {
23829 rmstein = unuverts;
23830 subsegs->traversalinit();
23831 segloop.sh = shellfacetraverse(subsegs);
23832 while (segloop.sh != (shellface *) NULL) {
23833 remflag = false;
23834 // Don't check the poinytype of pa, it may be a Steiner point but has
23835 // type NACUTEVERTEX due to splitting a type-3 segment.
23836 // if (pointtype(pa) == FREESEGVERTEX) {
23837 segloop.shver = 0;
23838 senext(segloop, nextseg);
23839 spivotself(nextseg);
23840 if (nextseg.sh != dummysh) {
23841 // Find a Steiner point p.
23842 pa = sdest(segloop); // For checking.
23843 nextseg.shver = 0;
23844 assert(sorg(nextseg) == pa);
23845 if (b->nobisect == 1) {
23846 // '-Y'. Remove p if it is on the hull.
23847 sstpivot(&segloop, &checktet);
23848 assert(checktet.tet != dummytet);
23849 pa = apex(checktet);
23850 do {
23851 if (!fnextself(checktet)) {
23852 // Meet a boundary face - p is on the hull.
23853 remflag = true; break;
23854 }
23855 } while (pa != apex(checktet));
23856 } else {
23857 // '-YY'. Remove p whatever it is on the hull or not.
23858 remflag = true;
23859 }
23860 }
23861 if (remflag) {
23862 suppresssegpoint(&segloop, spinshlist, newsegshlist, frontlist,
23863 misfrontlist, ptlist, conlist, viri, flipque);
23864 }
23865 segloop.sh = shellfacetraverse(subsegs);
23866 }
23867 // Continue if any Steiner point has been removed.
23868 } while (unuverts > rmstein);
23869
23870 if (relverts > 0) {
23871 // Suppress relocated points.
23872 do {
23873 rmstein = unuverts;
23874 points->traversalinit();
23875 pa = pointtraverse();
23876 while (pa != (point) NULL) {
23877 remflag = (pointtype(pa) == FREEVOLVERTEX);
23878 if (remflag) {
23879 suppressvolpoint(pa, frontlist, misfrontlist, ptlist, flipque);
23880 }
23881 pa = pointtraverse();
23882 }
23883 // Continue if any relocated point has been suppressed.
23884 } while (unuverts > rmstein);
23885 }
23886
23887 /* if ((relverts - suprelverts) > 0) {
23888 // Try to collapse relocated points.
23889 do {
23890 rmstein = unuverts;
23891 points->traversalinit();
23892 pa = pointtraverse();
23893 while (pa != (point) NULL) {
23894 remflag = (pointtype(pa) == FREEVOLVERTEX);
23895 if (remflag) {
23896 collapseedgepoint(pa, frontlist, misfrontlist, ptlist);
23897 }
23898 pa = pointtraverse();
23899 }
23900 // Continue if any relocated point has been suppressed.
23901 } while (unuverts > rmstein);
23902 } */
23903
23904 if (b->verbose > 0) {
23905 printf(" %d points removed from boundary.\n", unuverts - oldnum);
23906 if (relverts > 0) {
23907 printf(" %d points relocated into volume.\n", relverts);
23908 }
23909 if (suprelverts > 0) {
23910 printf(" %d relocated points are suppressed.\n", suprelverts);
23911 }
23912 if (collapverts > 0) {
23913 printf(" %d relocated points are collapsed.\n", collapverts);
23914 }
23915 if (unsupverts > 0) {
23916 printf(" %d points are unsuppressed.\n", unsupverts);
23917 }
23918 if (expcavcount > 0) {
23919 printf(" %d cavity corrections.\n", expcavcount);
23920 }
23921 }
23922
23923 // Delete work lists.
23924 delete frontlist;
23925 delete misfrontlist;
23926 delete spinshlist;
23927 delete newsegshlist;
23928 delete ptlist;
23929 delete conlist;
23930 delete flipque;
23931 delete viri;
23932 }
23933
23934 //
23935 // End of boundary Steiner points removing routines
23936 //
23937
23938 //
23939 // Begin of mesh reconstruction routines
23940 //
23941
23942 ///////////////////////////////////////////////////////////////////////////////
23943 // //
23944 // reconstructmesh() Reconstruct a tetrahedral mesh from a list of //
23945 // tetrahedra and possibly a list of boundary faces. //
23946 // //
23947 // The list of tetrahedra is stored in 'in->tetrahedronlist', the list of //
23948 // boundary faces is stored in 'in->trifacelist'. The tetrahedral mesh is //
23949 // reconstructed in memorypool 'tetrahedrons', its boundary faces (subfaces) //
23950 // are reconstructed in 'subfaces', its boundary edges (subsegments) are //
23951 // reconstructed in 'subsegs'. If the -a switch is used, this procedure will //
23952 // also read a list of REALs from 'in->tetrahedronvolumelist' and set a //
23953 // maximum volume constraint on each tetrahedron. //
23954 // //
23955 // If the user has provided the boundary faces in 'in->trifacelist', they //
23956 // will be inserted the mesh. Otherwise subfaces will be identified from the //
23957 // mesh. All hull faces (including faces of the internal holes) will be //
23958 // recognized as subfaces, internal faces between two tetrahedra which have //
23959 // different attributes will also be recognized as subfaces. //
23960 // //
23961 // Subsegments will be identified after subfaces are reconstructed. Edges at //
23962 // the intersections of non-coplanar subfaces are recognized as subsegments. //
23963 // Edges between two coplanar subfaces with different boundary markers are //
23964 // also recognized as subsegments. //
23965 // //
23966 // The facet index of each subface will be set automatically after we have //
23967 // recovered subfaces and subsegments. That is, the set of subfaces, which //
23968 // are coplanar and have the same boundary marker will be recognized as a //
23969 // facet and has a unique index, stored as the facet marker in each subface //
23970 // of the set, the real boundary marker of each subface will be found in //
23971 // 'in->facetmarkerlist' by the index. Facet index will be used in Delaunay //
23972 // refinement for detecting two incident facets. //
23973 // //
23974 // Points which are not corners of tetrahedra will be inserted into the mesh.//
23975 // Return the number of faces on the hull after the reconstruction. //
23976 // //
23977 ///////////////////////////////////////////////////////////////////////////////
23978
23979 long tetgenmesh::reconstructmesh()
23980 {
23981 tetrahedron **tetsperverlist;
23982 shellface **facesperverlist;
23983 triface tetloop, neightet, neineightet, spintet;
23984 face subloop, neighsh, neineighsh, subseg;
23985 face sface1, sface2;
23986 point *idx2verlist;
23987 point torg, tdest, tapex, toppo;
23988 point norg, ndest, napex;
23989 list *neighshlist, *markerlist;
23990 REAL sign, attrib, volume;
23991 REAL da1, da2;
23992 bool bondflag, insertsegflag;
23993 int *idx2tetlist;
23994 int *idx2facelist;
23995 int *worklist;
23996 int facetidx, marker;
23997 int iorg, idest, iapex, ioppo;
23998 int inorg, indest, inapex;
23999 int index, i, j;
24000
24001 if (!b->quiet) {
24002 printf("Reconstructing mesh.\n");
24003 }
24004
24005 // Create a map from index to points.
24006 makeindex2pointmap(idx2verlist);
24007
24008 // Create the tetrahedra.
24009 for (i = 0; i < in->numberoftetrahedra; i++) {
24010 // Create a new tetrahedron and set its four corners, make sure that
24011 // four corners form a positive orientation.
24012 maketetrahedron(&tetloop);
24013 index = i * in->numberofcorners;
24014 // Although there may be 10 nodes, we only read the first 4.
24015 iorg = in->tetrahedronlist[index] - in->firstnumber;
24016 idest = in->tetrahedronlist[index + 1] - in->firstnumber;
24017 iapex = in->tetrahedronlist[index + 2] - in->firstnumber;
24018 ioppo = in->tetrahedronlist[index + 3] - in->firstnumber;
24019 torg = idx2verlist[iorg];
24020 tdest = idx2verlist[idest];
24021 tapex = idx2verlist[iapex];
24022 toppo = idx2verlist[ioppo];
24023 sign = orient3d(torg, tdest, tapex, toppo);
24024 if (sign > 0.0) {
24025 norg = torg; torg = tdest; tdest = norg;
24026 } else if (sign == 0.0) {
24027 if (!b->quiet) {
24028 printf("Warning: Tet %d is degenerate.\n", i + in->firstnumber);
24029 }
24030 }
24031 setorg(tetloop, torg);
24032 setdest(tetloop, tdest);
24033 setapex(tetloop, tapex);
24034 setoppo(tetloop, toppo);
24035 // Temporarily set the vertices be type VOLVERTEX, to indicate that
24036 // they belong to the mesh. These types may be changed later.
24037 setpointtype(torg, VOLVERTEX);
24038 setpointtype(tdest, VOLVERTEX);
24039 setpointtype(tapex, VOLVERTEX);
24040 setpointtype(toppo, VOLVERTEX);
24041 // Set element attributes if they exist.
24042 for (j = 0; j < in->numberoftetrahedronattributes; j++) {
24043 index = i * in->numberoftetrahedronattributes;
24044 attrib = in->tetrahedronattributelist[index + j];
24045 setelemattribute(tetloop.tet, j, attrib);
24046 }
24047 // If -a switch is used (with no number follows) Set a volume
24048 // constraint if it exists.
24049 if (b->varvolume) {
24050 if (in->tetrahedronvolumelist != (REAL *) NULL) {
24051 volume = in->tetrahedronvolumelist[i];
24052 } else {
24053 volume = -1.0;
24054 }
24055 setvolumebound(tetloop.tet, volume);
24056 }
24057 }
24058
24059 // Set the connection between tetrahedra.
24060 hullsize = 0l;
24061 // Create a map from nodes to tetrahedra.
24062 maketetrahedronmap(idx2tetlist, tetsperverlist);
24063 // Initialize the worklist.
24064 worklist = new int[points->items];
24065 for (i = 0; i < points->items; i++) worklist[i] = 0;
24066
24067 // Loop all tetrahedra, bond two tetrahedra if they share a common face.
24068 tetrahedrons->traversalinit();
24069 tetloop.tet = tetrahedrontraverse();
24070 while (tetloop.tet != (tetrahedron *) NULL) {
24071 // Loop the four sides of the tetrahedron.
24072 for (tetloop.loc = 0; tetloop.loc < 4; tetloop.loc++) {
24073 sym(tetloop, neightet);
24074 if (neightet.tet != dummytet) continue; // This side has finished.
24075 torg = org(tetloop);
24076 tdest = dest(tetloop);
24077 tapex = apex(tetloop);
24078 iorg = pointmark(torg) - in->firstnumber;
24079 idest = pointmark(tdest) - in->firstnumber;
24080 iapex = pointmark(tapex) - in->firstnumber;
24081 worklist[iorg] = 1;
24082 worklist[idest] = 1;
24083 worklist[iapex] = 1;
24084 bondflag = false;
24085 // Search its neighbor in the adjacent tets of torg.
24086 for (j = idx2tetlist[iorg]; j < idx2tetlist[iorg + 1] && !bondflag;
24087 j++) {
24088 if (tetsperverlist[j] == tetloop.tet) continue; // Skip myself.
24089 neightet.tet = tetsperverlist[j];
24090 for (neightet.loc = 0; neightet.loc < 4; neightet.loc++) {
24091 sym(neightet, neineightet);
24092 if (neineightet.tet == dummytet) {
24093 norg = org(neightet);
24094 ndest = dest(neightet);
24095 napex = apex(neightet);
24096 inorg = pointmark(norg) - in->firstnumber;
24097 indest = pointmark(ndest) - in->firstnumber;
24098 inapex = pointmark(napex) - in->firstnumber;
24099 if ((worklist[inorg] + worklist[indest] + worklist[inapex]) == 3) {
24100 // Find! Bond them together and break the loop.
24101 bond(tetloop, neightet);
24102 bondflag = true;
24103 break;
24104 }
24105 }
24106 }
24107 }
24108 if (!bondflag) {
24109 hullsize++; // It's a hull face.
24110 // Bond this side to outer space.
24111 dummytet[0] = encode(tetloop);
24112 if (in->pointmarkerlist != (int *) NULL) {
24113 // Set its three corners's markers be boundary (hull) vertices.
24114 if (in->pointmarkerlist[iorg] == 0) {
24115 in->pointmarkerlist[iorg] = 1;
24116 }
24117 if (in->pointmarkerlist[idest] == 0) {
24118 in->pointmarkerlist[idest] = 1;
24119 }
24120 if (in->pointmarkerlist[iapex] == 0) {
24121 in->pointmarkerlist[iapex] = 1;
24122 }
24123 }
24124 }
24125 worklist[iorg] = 0;
24126 worklist[idest] = 0;
24127 worklist[iapex] = 0;
24128 }
24129 tetloop.tet = tetrahedrontraverse();
24130 }
24131
24132 // Subfaces will be inserted into the mesh. It has two phases:
24133 // (1) Insert subfaces provided by user (in->trifacelist);
24134 // (2) Create subfaces for hull faces (if they're not subface yet) and
24135 // interior faces which separate two different materials.
24136
24137 // Phase (1). Is there a list of user-provided subfaces?
24138 if (in->trifacelist != (int *) NULL) {
24139 // Recover subfaces from 'in->trifacelist'.
24140 for (i = 0; i < in->numberoftrifaces; i++) {
24141 index = i * 3;
24142 iorg = in->trifacelist[index] - in->firstnumber;
24143 idest = in->trifacelist[index + 1] - in->firstnumber;
24144 iapex = in->trifacelist[index + 2] - in->firstnumber;
24145 // Look for the location of this subface.
24146 worklist[iorg] = 1;
24147 worklist[idest] = 1;
24148 worklist[iapex] = 1;
24149 bondflag = false;
24150 // Search its neighbor in the adjacent tets of torg.
24151 for (j = idx2tetlist[iorg]; j < idx2tetlist[iorg + 1] && !bondflag;
24152 j++) {
24153 neightet.tet = tetsperverlist[j];
24154 for (neightet.loc = 0; neightet.loc < 4; neightet.loc++) {
24155 norg = org(neightet);
24156 ndest = dest(neightet);
24157 napex = apex(neightet);
24158 inorg = pointmark(norg) - in->firstnumber;
24159 indest = pointmark(ndest) - in->firstnumber;
24160 inapex = pointmark(napex) - in->firstnumber;
24161 if ((worklist[inorg] + worklist[indest] + worklist[inapex]) == 3) {
24162 bondflag = true; // Find!
24163 break;
24164 }
24165 }
24166 }
24167 if (bondflag) {
24168 // Create a new subface and insert it into the mesh.
24169 makeshellface(subfaces, &subloop);
24170 torg = idx2verlist[iorg];
24171 tdest = idx2verlist[idest];
24172 tapex = idx2verlist[iapex];
24173 setsorg(subloop, torg);
24174 setsdest(subloop, tdest);
24175 setsapex(subloop, tapex);
24176 // Set the vertices be FREESUBVERTEX to indicate they belong to a
24177 // facet of the domain. They may be changed later.
24178 setpointtype(torg, FREESUBVERTEX);
24179 setpointtype(tdest, FREESUBVERTEX);
24180 setpointtype(tapex, FREESUBVERTEX);
24181 if (in->trifacemarkerlist != (int *) NULL) {
24182 setshellmark(subloop, in->trifacemarkerlist[i]);
24183 }
24184 adjustedgering(neightet, CCW);
24185 findedge(&subloop, org(neightet), dest(neightet));
24186 tsbond(neightet, subloop);
24187 sym(neightet, neineightet);
24188 if (neineightet.tet != dummytet) {
24189 sesymself(subloop);
24190 tsbond(neineightet, subloop);
24191 }
24192 } else {
24193 if (!b->quiet) {
24194 printf("Warning: Subface %d is discarded.\n", i + in->firstnumber);
24195 }
24196 }
24197 worklist[iorg] = 0;
24198 worklist[idest] = 0;
24199 worklist[iapex] = 0;
24200 }
24201 }
24202
24203 // Phase (2). Indentify subfaces from the mesh.
24204 tetrahedrons->traversalinit();
24205 tetloop.tet = tetrahedrontraverse();
24206 while (tetloop.tet != (tetrahedron *) NULL) {
24207 // Loop the four sides of the tetrahedron.
24208 for (tetloop.loc = 0; tetloop.loc < 4; tetloop.loc++) {
24209 tspivot(tetloop, subloop);
24210 if (subloop.sh != dummysh) continue;
24211 bondflag = false;
24212 sym(tetloop, neightet);
24213 if (neightet.tet == dummytet) {
24214 // It's a hull face. Insert a subface at here.
24215 bondflag = true;
24216 } else {
24217 // It's an interior face. Insert a subface if two tetrahedra have
24218 // different attributes (i.e., they belong to two regions).
24219 if (in->numberoftetrahedronattributes > 0) {
24220 if (elemattribute(neightet.tet,
24221 in->numberoftetrahedronattributes - 1) !=
24222 elemattribute(tetloop.tet,
24223 in->numberoftetrahedronattributes - 1)) {
24224 bondflag = true;
24225 }
24226 }
24227 }
24228 if (bondflag) {
24229 adjustedgering(tetloop, CCW);
24230 makeshellface(subfaces, &subloop);
24231 torg = org(tetloop);
24232 tdest = dest(tetloop);
24233 tapex = apex(tetloop);
24234 setsorg(subloop, torg);
24235 setsdest(subloop, tdest);
24236 setsapex(subloop, tapex);
24237 // Set the vertices be FACETVERTEX to indicate they belong to a
24238 // facet of the domain. They may be changed later.
24239 setpointtype(torg, FACETVERTEX);
24240 setpointtype(tdest, FACETVERTEX);
24241 setpointtype(tapex, FACETVERTEX);
24242 tsbond(tetloop, subloop);
24243 if (neightet.tet != dummytet) {
24244 sesymself(subloop);
24245 tsbond(neightet, subloop);
24246 }
24247 }
24248 }
24249 tetloop.tet = tetrahedrontraverse();
24250 }
24251
24252 // Set the connection between subfaces. A subsegment may have more than
24253 // two subfaces sharing it, 'neighshlist' stores all subfaces sharing
24254 // one edge.
24255 neighshlist = new list(sizeof(face), NULL);
24256 // Create a map from nodes to subfaces.
24257 makesubfacemap(idx2facelist, facesperverlist);
24258
24259 // Loop over the set of subfaces, setup the connection between subfaces.
24260 subfaces->traversalinit();
24261 subloop.sh = shellfacetraverse(subfaces);
24262 while (subloop.sh != (shellface *) NULL) {
24263 for (i = 0; i < 3; i++) {
24264 spivot(subloop, neighsh);
24265 if (neighsh.sh == dummysh) {
24266 // This side is 'empty', operate on it.
24267 torg = sorg(subloop);
24268 tdest = sdest(subloop);
24269 tapex = sapex(subloop);
24270 neighshlist->append(&subloop);
24271 iorg = pointmark(torg) - in->firstnumber;
24272 // Search its neighbor in the adjacent list of torg.
24273 for (j = idx2facelist[iorg]; j < idx2facelist[iorg + 1]; j++) {
24274 neighsh.sh = facesperverlist[j];
24275 if (neighsh.sh == subloop.sh) continue;
24276 neighsh.shver = 0;
24277 if (isfacehasedge(&neighsh, torg, tdest)) {
24278 findedge(&neighsh, torg, tdest);
24279 // Insert 'neighsh' into 'neighshlist'.
24280 if (neighshlist->len() < 2) {
24281 neighshlist->append(&neighsh);
24282 } else {
24283 for (index = 0; index < neighshlist->len() - 1; index++) {
24284 sface1 = * (face *)(* neighshlist)[index];
24285 sface2 = * (face *)(* neighshlist)[index + 1];
24286 da1 = facedihedral(torg, tdest, sapex(sface1), sapex(neighsh));
24287 da2 = facedihedral(torg, tdest, sapex(sface1), sapex(sface2));
24288 if (da1 < da2) {
24289 break; // Insert it after index.
24290 }
24291 }
24292 neighshlist->insert(index + 1, &neighsh);
24293 }
24294 }
24295 }
24296 // Bond the subfaces in 'neighshlist'.
24297 if (neighshlist->len() > 1) {
24298 neighsh = * (face *)(* neighshlist)[0];
24299 for (j = 1; j <= neighshlist->len(); j++) {
24300 if (j < neighshlist->len()) {
24301 neineighsh = * (face *)(* neighshlist)[j];
24302 } else {
24303 neineighsh = * (face *)(* neighshlist)[0];
24304 }
24305 sbond1(neighsh, neineighsh);
24306 neighsh = neineighsh;
24307 }
24308 } else {
24309 // No neighbor subface be found, bond 'subloop' to itself.
24310 sbond(subloop, subloop);
24311 }
24312 neighshlist->clear();
24313 }
24314 senextself(subloop);
24315 }
24316 subloop.sh = shellfacetraverse(subfaces);
24317 }
24318
24319 // Segments will be introudced. Each segment has a unique marker (1-based).
24320 marker = 1;
24321 subfaces->traversalinit();
24322 subloop.sh = shellfacetraverse(subfaces);
24323 while (subloop.sh != (shellface *) NULL) {
24324 for (i = 0; i < 3; i++) {
24325 sspivot(subloop, subseg);
24326 if (subseg.sh == dummysh) {
24327 // This side has no subsegment bonded, check it.
24328 torg = sorg(subloop);
24329 tdest = sdest(subloop);
24330 tapex = sapex(subloop);
24331 spivot(subloop, neighsh);
24332 spivot(neighsh, neineighsh);
24333 insertsegflag = false;
24334 if (subloop.sh == neighsh.sh || subloop.sh != neineighsh.sh) {
24335 // This side is either self-bonded or more than two subfaces,
24336 // insert a subsegment at this side.
24337 insertsegflag = true;
24338 } else {
24339 // Only two subfaces case.
24340 #ifdef SELF_CHECK
24341 assert(subloop.sh != neighsh.sh);
24342 #endif
24343 napex = sapex(neighsh);
24344 sign = orient3d(torg, tdest, tapex, napex);
24345 if (iscoplanar(torg, tdest, tapex, napex, sign, b->epsilon)) {
24346 // Although they are coplanar, we still need to check if they
24347 // have the same boundary marker.
24348 insertsegflag = (shellmark(subloop) != shellmark(neighsh));
24349 } else {
24350 // Non-coplanar.
24351 insertsegflag = true;
24352 }
24353 }
24354 if (insertsegflag) {
24355 // Create a subsegment at this side.
24356 makeshellface(subsegs, &subseg);
24357 setsorg(subseg, torg);
24358 setsdest(subseg, tdest);
24359 // At the moment, all segment vertices have type FACETVERTEX.
24360 // They will be set to type ACUTEVERTEX or NACUTEVERTEX by
24361 // routine markacutevertices() later.
24362 // setpointtype(torg, SEGMENTVERTEX);
24363 // setpointtype(tdest, SEGMENTVERTEX);
24364 setshellmark(subseg, marker);
24365 marker++;
24366 // Bond all subfaces to this subsegment.
24367 neighsh = subloop;
24368 do {
24369 ssbond(neighsh, subseg);
24370 spivotself(neighsh);
24371 } while (neighsh.sh != subloop.sh);
24372 }
24373 }
24374 senextself(subloop);
24375 }
24376 subloop.sh = shellfacetraverse(subfaces);
24377 }
24378 // Remember the number of input segments.
24379 insegments = subsegs->items;
24380 // Find the acute vertices and set them be type ACUTEVERTEX.
24381
24382 // Indentify facets and set the facet marker (1-based) for subfaces.
24383 markerlist = new list("int");
24384
24385 subfaces->traversalinit();
24386 subloop.sh = shellfacetraverse(subfaces);
24387 while (subloop.sh != (shellface *) NULL) {
24388 // Only operate on uninfected subface, after operating, infect it.
24389 if (!sinfected(subloop)) {
24390 // A new facet is found.
24391 marker = shellmark(subloop);
24392 markerlist->append(&marker);
24393 facetidx = markerlist->len(); // 'facetidx' starts from 1.
24394 setshellmark(subloop, facetidx);
24395 sinfect(subloop);
24396 neighshlist->append(&subloop);
24397 // Find out all subfaces of this facet (bounded by subsegments).
24398 for (i = 0; i < neighshlist->len(); i++) {
24399 neighsh = * (face *) (* neighshlist)[i];
24400 for (j = 0; j < 3; j++) {
24401 sspivot(neighsh, subseg);
24402 if (subseg.sh == dummysh) {
24403 spivot(neighsh, neineighsh);
24404 if (!sinfected(neineighsh)) {
24405 // 'neineighsh' is in the same facet as 'subloop'.
24406 #ifdef SELF_CHECK
24407 assert(shellmark(neineighsh) == marker);
24408 #endif
24409 setshellmark(neineighsh, facetidx);
24410 sinfect(neineighsh);
24411 neighshlist->append(&neineighsh);
24412 }
24413 }
24414 senextself(neighsh);
24415 }
24416 }
24417 neighshlist->clear();
24418 }
24419 subloop.sh = shellfacetraverse(subfaces);
24420 }
24421 // Uninfect all subfaces.
24422 subfaces->traversalinit();
24423 subloop.sh = shellfacetraverse(subfaces);
24424 while (subloop.sh != (shellface *) NULL) {
24425 #ifdef SELF_CHECK
24426 assert(sinfected(subloop));
24427 #endif
24428 suninfect(subloop);
24429 subloop.sh = shellfacetraverse(subfaces);
24430 }
24431 // Save the facet markers in 'in->facetmarkerlist'.
24432 in->numberoffacets = markerlist->len();
24433 in->facetmarkerlist = new int[in->numberoffacets];
24434 for (i = 0; i < in->numberoffacets; i++) {
24435 marker = * (int *) (* markerlist)[i];
24436 in->facetmarkerlist[i] = marker;
24437 }
24438 // Initialize the 'facetabovepointlist'.
24439 facetabovepointarray = new point[in->numberoffacets + 1];
24440 for (i = 0; i < in->numberoffacets + 1; i++) {
24441 facetabovepointarray[i] = (point) NULL;
24442 }
24443
24444 // The mesh contains boundary now.
24445 checksubfaces = 1;
24446 // The mesh is nonconvex now.
24447 nonconvex = 1;
24448
24449 // Is there periodic boundary confitions?
24450 if (checkpbcs) {
24451 tetgenio::pbcgroup *pg;
24452 pbcdata *pd;
24453 // Initialize the global array 'subpbcgrouptable'.
24454 createsubpbcgrouptable();
24455 // Loop for each pbcgroup i.
24456 for (i = 0; i < in->numberofpbcgroups; i++) {
24457 pg = &(in->pbcgrouplist[i]);
24458 pd = &(subpbcgrouptable[i]);
24459 // Find all subfaces of pd, set each subface's group id be i.
24460 for (j = 0; j < 2; j++) {
24461 subfaces->traversalinit();
24462 subloop.sh = shellfacetraverse(subfaces);
24463 while (subloop.sh != (shellface *) NULL) {
24464 facetidx = shellmark(subloop);
24465 marker = in->facetmarkerlist[facetidx - 1];
24466 if (marker == pd->fmark[j]) {
24467 setshellpbcgroup(subloop, i);
24468 pd->ss[j] = subloop;
24469 }
24470 subloop.sh = shellfacetraverse(subfaces);
24471 }
24472 }
24473 if (pg->pointpairlist != (int *) NULL) {
24474 // Set the connections between pbc point pairs.
24475 for (j = 0; j < pg->numberofpointpairs; j++) {
24476 iorg = pg->pointpairlist[j * 2] - in->firstnumber;
24477 idest = pg->pointpairlist[j * 2 + 1] - in->firstnumber;
24478 torg = idx2verlist[iorg];
24479 tdest = idx2verlist[idest];
24480 setpoint2pbcpt(torg, tdest);
24481 setpoint2pbcpt(tdest, torg);
24482 }
24483 }
24484 }
24485 // Create the global array 'segpbcgrouptable'.
24486 createsegpbcgrouptable();
24487 }
24488
24489 // if (b->quality && varconstraint) {
24490 // // Assign constraints on facets, segments, and nodes.
24491 // assignvarconstraints(idx2verlist);
24492 // }
24493
24494 /*
24495 if (b->quality) {
24496 // Check and recover the Delaunay property.
24497 queue* flipqueue = new queue(sizeof(badface));
24498 checkdelaunay(0.0, flipqueue);
24499 if (!flipqueue->empty()) {
24500 // Call flip algorithm to recover Delaunayness.
24501 flip(flipqueue, NULL);
24502 }
24503 delete flipqueue;
24504 }
24505 */
24506
24507 delete markerlist;
24508 delete neighshlist;
24509 delete [] worklist;
24510 delete [] idx2tetlist;
24511 delete [] tetsperverlist;
24512 delete [] idx2facelist;
24513 delete [] facesperverlist;
24514 delete [] idx2verlist;
24515
24516 return hullsize;
24517 }
24518
24519 ///////////////////////////////////////////////////////////////////////////////
24520 // //
24521 // intettest() Test if a point is inside (or on) a tetrahedron. //
24522 // //
24523 // Return TRUE if the point p and the tet t has one of the relations: (1) p //
24524 // is inside t; (2) p is on a faces of t; (3) p is on an edge of t; (4) p is //
24525 // a vertex of t. Otherwise, return FALSE. //
24526 // //
24527 // An relative tolerance is used to determine coplanar case when a face of t //
24528 // is on the hull. To bring back a boundary point inside the mesh. //
24529 // //
24530 ///////////////////////////////////////////////////////////////////////////////
24531
24532 bool tetgenmesh::intettest(point testpt, triface* testtet, REAL eps)
24533 {
24534 triface checktet;
24535 point p1, p2, p3;
24536 REAL ori;
24537
24538 testtet->ver = 0;
24539 for (testtet->loc = 0; testtet->loc < 4; testtet->loc++) {
24540 // Get points of the side f.
24541 p1 = org(*testtet);
24542 p2 = dest(*testtet);
24543 p3 = apex(*testtet);
24544 ori = orient3d(p1, p2, p3, testpt);
24545 if (ori > 0.0) {
24546 if (eps > 0.0) {
24547 // Is f on the hull.
24548 sym(*testtet, checktet);
24549 if (checktet.tet == dummytet) {
24550 if (iscoplanar(p1, p2, p3, testpt, ori, eps)) continue;
24551 }
24552 }
24553 // p is below f. outside.
24554 return false;
24555 }
24556 }
24557 testtet->loc = 0;
24558
24559 return true;
24560 }
24561
24562 ///////////////////////////////////////////////////////////////////////////////
24563 // //
24564 // insertaddpoints() Insert additional points in 'in->addpointlist'. //
24565 // //
24566 ///////////////////////////////////////////////////////////////////////////////
24567
24568 void tetgenmesh::insertaddpoints()
24569 {
24570 queue *flipqueue;
24571 triface searchtet;
24572 face checksh, checkseg;
24573 point newpoint;
24574 enum locateresult loc;
24575 REAL *attr;
24576 int index;
24577 int i, j;
24578
24579 if (!b->quiet) {
24580 printf("Insert additional points into mesh.\n");
24581 }
24582 // Initialize 'flipqueue'.
24583 flipqueue = new queue(sizeof(badface));
24584 recenttet.tet = dummytet;
24585
24586 index = 0;
24587 for (i = 0; i < in->numberofaddpoints; i++) {
24588 // Create a newpoint.
24589 makepoint(&newpoint);
24590 newpoint[0] = in->addpointlist[index++];
24591 newpoint[1] = in->addpointlist[index++];
24592 newpoint[2] = in->addpointlist[index++];
24593 // Copy new attributes (if available).
24594 if(in->addpointattributelist != (REAL *) NULL) {
24595 attr = in->addpointattributelist + in->numberofpointattributes * i;
24596 for (j = 0; j < in->numberofpointattributes; j++)
24597 newpoint[3 + j] = attr[j];
24598 }
24599 // Find the location of the inserted point.
24600 searchtet = recenttet;
24601 loc = locate(newpoint, &searchtet);
24602 if (loc != OUTSIDE) {
24603 if (loc != ONVERTEX) {
24604 loc = adjustlocate(newpoint, &searchtet, loc, b->epsilon);
24605 }
24606 }
24607 if (loc == OUTSIDE) {
24608 // Perform a brute-force search.
24609 tetrahedrons->traversalinit();
24610 searchtet.tet = tetrahedrontraverse();
24611 while (searchtet.tet != (tetrahedron *) NULL) {
24612 if (intettest(newpoint, &searchtet, b->epsilon)) {
24613 loc = adjustlocate(newpoint, &searchtet, OUTSIDE, b->epsilon);
24614 assert(loc != OUTSIDE);
24615 break;
24616 }
24617 searchtet.tet = tetrahedrontraverse();
24618 }
24619 }
24620 // Insert the point if it not lies outside or on a vertex.
24621 switch (loc) {
24622 case INTETRAHEDRON:
24623 setpointtype(newpoint, VOLVERTEX);
24624 splittetrahedron(newpoint, &searchtet, flipqueue);
24625 break;
24626 case ONFACE:
24627 tspivot(searchtet, checksh);
24628 if (checksh.sh != dummysh) {
24629 setpointtype(newpoint, FREESUBVERTEX);
24630 } else {
24631 setpointtype(newpoint, FREEVOLVERTEX);
24632 }
24633 splittetface(newpoint, &searchtet, flipqueue);
24634 break;
24635 case ONEDGE:
24636 tsspivot(&searchtet, &checkseg);
24637 if (checkseg.sh != dummysh) {
24638 setpointtype(newpoint, FREESEGVERTEX);
24639 setpoint2sh(newpoint, sencode(checkseg));
24640 } else {
24641 tspivot(searchtet, checksh);
24642 if (checksh.sh != dummysh) {
24643 setpointtype(newpoint, FREESUBVERTEX);
24644 } else {
24645 setpointtype(newpoint, VOLVERTEX);
24646 }
24647 }
24648 splittetedge(newpoint, &searchtet, flipqueue);
24649 break;
24650 case ONVERTEX:
24651 if (!b->quiet) {
24652 printf("Warning: Point (%.17g, %.17g, %.17g) falls on a vertex.\n",
24653 newpoint[0], newpoint[1], newpoint[2]);
24654 }
24655 break;
24656 case OUTSIDE:
24657 if (!b->quiet) {
24658 printf("Warning: Point (%.17g, %.17g, %.17g) lies outside the mesh.\n",
24659 newpoint[0], newpoint[1], newpoint[2]);
24660 }
24661 break;
24662 }
24663 // Remember the tetrahedron for next point searching.
24664 recenttet = searchtet;
24665 if (loc == ONVERTEX || loc == OUTSIDE) {
24666 pointdealloc(newpoint);
24667 } else {
24668 flip(flipqueue, NULL);
24669 }
24670 }
24671
24672 delete flipqueue;
24673 }
24674
24675 //
24676 // End of mesh reconstruction routines
24677 //
24678
24679 //
24680 // Begin of background mesh routines
24681 //
24682
24683 ///////////////////////////////////////////////////////////////////////////////
24684 // //
24685 // interpolatepointsize() Set a point size by interpolating in bgmesh. //
24686 // //
24687 // This function first finds the tet t in background mesh contains 'pt, then //
24688 // set the size of 'pt' by interpolating the sizes of the corners of t. //
24689 // //
24690 // 'bgmtet' is a suggesting tet in background mesh for locating 'pt' in it. //
24691 // It returns the tet containing 'pt'. //
24692 // //
24693 ///////////////////////////////////////////////////////////////////////////////
24694
24695 bool tetgenmesh::interpolatepointsize(point pt, triface* bgmtet, long *scount)
24696 {
24697 point bgmpt[4];
24698 enum locateresult loc;
24699 REAL vol, volpt[4], weights[4];
24700 int i;
24701
24702 loc = bgm->preciselocate(pt, bgmtet, bgm->tetrahedrons->items);
24703 if (loc == OUTSIDE) {
24704 // Perform a brute-force search.
24705 if (scount) (*scount)++;
24706 bgm->tetrahedrons->traversalinit(); // in bgm
24707 bgmtet->tet = bgm->tetrahedrontraverse(); // in bgm
24708 while (bgmtet->tet != (tetrahedron *) NULL) {
24709 if (bgm->intettest(pt, bgmtet, b->epsilon)) {
24710 loc = bgm->adjustlocate(pt, bgmtet, OUTSIDE, b->epsilon);
24711 assert(loc != OUTSIDE);
24712 break;
24713 }
24714 bgmtet->tet = bgm->tetrahedrontraverse(); // in bgm
24715 }
24716 }
24717 if (loc != OUTSIDE) {
24718 // Let p remember t.
24719 setpoint2bgmtet(pt, encode(*bgmtet)); // in m
24720 // Interpolate the point size.
24721 // get the corners of t.
24722 for (i = 0; i < 4; i++) bgmpt[i] = (point) bgmtet->tet[4 + i];
24723 // Calculate the weighted coordinates of p in t.
24724 vol = orient3d(bgmpt[0], bgmpt[1], bgmpt[2], bgmpt[3]);
24725 volpt[0] = orient3d(pt, bgmpt[1], bgmpt[2], bgmpt[3]);
24726 volpt[1] = orient3d(bgmpt[0], pt, bgmpt[2], bgmpt[3]);
24727 volpt[2] = orient3d(bgmpt[0], bgmpt[1], pt, bgmpt[3]);
24728 volpt[3] = orient3d(bgmpt[0], bgmpt[1], bgmpt[2], pt);
24729 for (i = 0; i < 4; i++) weights[i] = fabs(volpt[i] / vol);
24730 // Interpolate the solution for p.
24731 for (i = 0; i < bgm->in->numberofpointattributes; i++) {
24732 pt[3 + i] = weights[0] * bgmpt[0][3 + i]
24733 + weights[1] * bgmpt[1][3 + i]
24734 + weights[2] * bgmpt[2][3 + i]
24735 + weights[3] * bgmpt[3][3 + i];
24736 }
24737 } else {
24738 setpoint2bgmtet(pt, (tetrahedron) NULL); // in m
24739 }
24740 return loc != OUTSIDE;
24741 }
24742
24743 ///////////////////////////////////////////////////////////////////////////////
24744 // //
24745 // searchpointrecursive() Search point in background mesh recursively. //
24746 // //
24747 ///////////////////////////////////////////////////////////////////////////////
24748
24749 void tetgenmesh::searchpointrecursive(triface *curtet, long *scount)
24750 {
24751 triface searchtet, bgmtet;
24752 point searchpt;
24753 int idx, i;
24754
24755 // Mark t as proceed.
24756 infect(*curtet);
24757 // Get the opposite point of t.
24758 searchpt = oppo(*curtet);
24759 // Has p already been processed?
24760 if (pointmark(searchpt) >= 0) {
24761 // Find the location of p.
24762 bgmtet = bgm->recenttet;
24763 if (interpolatepointsize(searchpt, &bgmtet, scount)) {
24764 bgm->recenttet = bgmtet; // in bgm
24765 }
24766 // Mark p as processed.
24767 idx = pointmark(searchpt);
24768 setpointmark(searchpt, -idx - 1);
24769 }
24770 // Recursively do the above searching.
24771 adjustedgering(*curtet, CCW);
24772 for (i = 0; i < 3; i++) {
24773 fnext(*curtet, searchtet);
24774 symself(searchtet);
24775 if ((searchtet.tet != dummytet) && (!infected(searchtet))) {
24776 searchpointrecursive(&searchtet, scount);
24777 }
24778 enextself(*curtet);
24779 }
24780 }
24781
24782 ///////////////////////////////////////////////////////////////////////////////
24783 // //
24784 // interpolatesizemap() Interpolate the point sizes in the given size map.//
24785 // //
24786 // The size map is specified on each node of the background mesh. The points //
24787 // of current mesh get their sizes by interpolating. //
24788 // //
24789 // This function operation on two meshes simultaneously, the current mesh m, //
24790 // and the background mesh bgm. After this function, each point p in m will //
24791 // have a pointer to a tet of bgm. //
24792 // //
24793 ///////////////////////////////////////////////////////////////////////////////
24794
24795 void tetgenmesh::interpolatesizemap()
24796 {
24797 triface tetloop, bgmtet;
24798 point searchpt;
24799 long scount;
24800 int idx, i;
24801
24802 if (b->verbose) {
24803 printf(" Interpolating size map.\n");
24804 }
24805 scount = 0l;
24806
24807 tetrahedrons->traversalinit();
24808 tetloop.tet = tetrahedrontraverse();
24809 while (tetloop.tet != (tetrahedron *) NULL) {
24810 if (!infected(tetloop)) {
24811 // Found an traversed tet t.
24812 tetloop.loc = 0;
24813 tetloop.ver = 0;
24814 // Locate the three vertices of current face of t.
24815 for (i = 0; i < 3; i++) {
24816 searchpt = org(tetloop);
24817 // Has p already been processed?
24818 if (pointmark(searchpt) >= 0) {
24819 // Interpolate p in background mesh.
24820 bgmtet = bgm->recenttet;
24821 if (interpolatepointsize(searchpt, &bgmtet, &scount)) {
24822 bgm->recenttet = bgmtet;
24823 }
24824 // Mark p as processed.
24825 idx = pointmark(searchpt);
24826 setpointmark(searchpt, -idx - 1);
24827 }
24828 enextself(tetloop);
24829 }
24830 // Recursively do the above searching in the neighbring tets of t.
24831 searchpointrecursive(&tetloop, &scount);
24832 }
24833 tetloop.tet = tetrahedrontraverse();
24834 }
24835
24836 // Have searched all points. Unmark tets.
24837 tetrahedrons->traversalinit();
24838 tetloop.tet = tetrahedrontraverse();
24839 while (tetloop.tet != (tetrahedron *) NULL) {
24840 assert(infected(tetloop));
24841 uninfect(tetloop);
24842 tetloop.tet = tetrahedrontraverse();
24843 }
24844 // Unmark points.
24845 points->traversalinit(); // in m
24846 searchpt = pointtraverse(); // in m
24847 while (searchpt != (point) NULL) {
24848 idx = pointmark(searchpt);
24849 assert(idx < 0);
24850 setpointmark(searchpt, -(idx + 1));
24851 searchpt = pointtraverse(); // in m
24852 }
24853
24854 #ifdef SELF_CHECK
24855 if (b->verbose) {
24856 printf(" %ld brute-force searches.\n", scount);
24857 }
24858 #endif
24859 }
24860
24861 //
24862 // End of of background mesh routines
24863 //
24864
24865 //
24866 // Begin of Delaunay refinement routines
24867 //
24868
24869 ///////////////////////////////////////////////////////////////////////////////
24870 // //
24871 // calclocalfeaturesizes() Calculate local feature sizes of all points. //
24872 // //
24873 // Given a PLC X, the local feature size, lfs_d(x), of any point x in X is //
24874 // defined as the distance from x to two features of X which are of dim no //
24875 // large than d. For example, lfs_0(x) is the distance from x to the second //
24876 // nearest point of X. Let lfs(x) = lfs_2(x). //
24877 // //
24878 ///////////////////////////////////////////////////////////////////////////////
24879
24880 void tetgenmesh::calclocalfeaturesizes()
24881 {
24882 list *tetlist, *verlist;
24883 tetrahedron tetptr;
24884 triface starttet;
24885 face checksh, checkseg;
24886 point ploop, ver[3];
24887 point ptlfslarge, ptlfssmall;
24888 enum locateresult loc;
24889 REAL prj[3], lfs[3], len;
24890 REAL lfslarge, lfssmall;
24891 int i, j;
24892
24893 if (b->verbose > 0) {
24894 printf(" Calculating local feature sizes.\n");
24895 }
24896
24897 // Construct a map from points to tetrahedra.
24898 makepoint2tetmap();
24899 // Initialize working lists.
24900 tetlist = new list(sizeof(triface), NULL, 256);
24901 verlist = new list(sizeof(point *), NULL, 256);
24902 // Initialize bookkeeping variables.
24903 ptlfslarge = ptlfssmall = (point) NULL;
24904 lfslarge = lfssmall = 0.0;
24905
24906 points->traversalinit();
24907 ploop = pointtraverse();
24908 while (ploop != (point) NULL) {
24909 tetptr = point2tet(ploop);
24910 // Only calculate lfs(p) if it is in the mesh.
24911 if (tetptr != (tetrahedron) NULL) {
24912 decode(tetptr, starttet);
24913 tetlist->append(&starttet);
24914 formstarpolyhedron(ploop, tetlist, verlist, true); // Form star(p).
24915 lfs[0] = lfs[1] = lfs[2] = longest;
24916 // Calculate lfs_0(p).
24917 for (i = 0; i < verlist->len(); i++) {
24918 ver[0] = * (point *)(* verlist)[i];
24919 len = distance(ploop, ver[0]);
24920 if (lfs[0] > len) lfs[0] = len;
24921 }
24922 // Claculate lfs_1(p).
24923 for (i = 0; i < tetlist->len(); i++) {
24924 starttet = * (triface *)(* tetlist)[i];
24925 starttet.ver = 0;
24926 for (j = 0; j < 3; j++) {
24927 tsspivot(&starttet, &checkseg);
24928 if (checkseg.sh != dummysh) {
24929 checkseg.shver = 0;
24930 ver[0] = sorg(checkseg);
24931 ver[1] = sdest(checkseg);
24932 projpt2edge(ploop, ver[0], ver[1], prj);
24933 loc = locateseg(prj, &checkseg);
24934 if (loc != OUTSIDE) {
24935 len = distance(ploop, prj);
24936 if (lfs[1] > len) lfs[1] = len;
24937 }
24938 }
24939 enextself(starttet);
24940 }
24941 }
24942 // Claculate lfs_2(p).
24943 for (i = 0; i < tetlist->len(); i++) {
24944 starttet = * (triface *)(* tetlist)[i];
24945 tspivot(starttet, checksh);
24946 if (checksh.sh != dummysh) {
24947 ver[0] = sorg(checksh);
24948 ver[1] = sdest(checksh);
24949 ver[2] = sapex(checksh);
24950 projpt2face(ploop, ver[0], ver[1], ver[2], prj);
24951 abovepoint = facetabovepointarray[shellmark(checksh)];
24952 if (abovepoint == (point) NULL) {
24953 getfacetabovepoint(&checksh);
24954 }
24955 loc = locatesub(prj, &checksh, 1, b->epsilon);
24956 if (loc != OUTSIDE) {
24957 len = distance(ploop, prj);
24958 if (lfs[2] > len) lfs[2] = len;
24959 }
24960 }
24961 }
24962 // Decide lfs(p).
24963 ploop[pointlfsindex] = lfs[0];
24964 if (ploop[pointlfsindex] > lfs[1]) ploop[pointlfsindex] = lfs[1];
24965 if (ploop[pointlfsindex] > lfs[2]) ploop[pointlfsindex] = lfs[2];
24966 // Update statistics.
24967 if (ptlfslarge == (point) NULL) {
24968 ptlfslarge = ptlfssmall = ploop;
24969 lfslarge = lfssmall = ploop[pointlfsindex];
24970 } else {
24971 if (lfslarge < ploop[pointlfsindex]) {
24972 lfslarge = ploop[pointlfsindex];
24973 ptlfslarge = ploop;
24974 }
24975 if (lfssmall > ploop[pointlfsindex]) {
24976 lfssmall = ploop[pointlfsindex];
24977 ptlfssmall = ploop;
24978 }
24979 }
24980 // Clear working lists.
24981 tetlist->clear();
24982 verlist->clear();
24983 }
24984 ploop = pointtraverse();
24985 }
24986
24987 if (b->verbose > 1) {
24988 printf(" smallest lfs = %g (%d).\n", lfssmall, pointmark(ptlfssmall));
24989 printf(" largest lfs = %g (%d).\n", lfslarge, pointmark(ptlfslarge));
24990 }
24991
24992 delete tetlist;
24993 delete verlist;
24994 }
24995
24996 ///////////////////////////////////////////////////////////////////////////////
24997 // //
24998 // marksharpsubsegs() Mark all sharp subsegments. //
24999 // //
25000 // A segment is sharp if it is between two facets that form a small dihedral //
25001 // angle (< 'dihedbound', given in degrees). It is marked as SHARP. //
25002 // //
25003 ///////////////////////////////////////////////////////////////////////////////
25004
25005 void tetgenmesh::marksharpsubsegs(REAL dihedbound)
25006 {
25007 list *spinshlist;
25008 triface adjtet;
25009 face startsh, spinsh, neighsh;
25010 face segloop, prevseg, nextseg;
25011 point eorg, edest;
25012 enum shestype stype;
25013 REAL angle, smallang;
25014 bool issharp;
25015 int scount;
25016 int i;
25017
25018 if (b->verbose > 0) {
25019 printf(" Marking sharp subsegments.\n");
25020 }
25021
25022 smallang = dihedbound * PI / 180.;
25023 scount = 0;
25024 eorg = edest = (point) NULL; // avoid compilation warnings.
25025 // Initial working list.
25026 spinshlist = new list(sizeof(face), NULL, 256);
25027
25028 // A segment s may be split into many subsegments. Operate the one which
25029 // contains the origin of s. Then mark the rest of subsegments.
25030 subsegs->traversalinit();
25031 segloop.sh = shellfacetraverse(subsegs);
25032 while (segloop.sh != (shellface *) NULL) {
25033 segloop.shver = 0;
25034 senext2(segloop, prevseg);
25035 spivotself(prevseg);
25036 if (prevseg.sh == dummysh) {
25037 // Operate on this seg.
25038 issharp = false;
25039 segloop.shver = 0;
25040 spivot(segloop, startsh);
25041 if (startsh.sh != dummysh) {
25042 spivot(startsh, spinsh);
25043 if (spinsh.sh != startsh.sh) {
25044 // This subface is not self-bonded.
25045 eorg = sorg(segloop);
25046 edest = sdest(segloop);
25047 // Get all incident subfaces around the seg.
25048 spinsh = startsh;
25049 do {
25050 if (sorg(spinsh) != eorg) {
25051 sesymself(spinsh);
25052 }
25053 spinshlist->append(&spinsh);
25054 spivotself(spinsh);
25055 } while (spinsh.sh != startsh.sh);
25056 }
25057 // Check the pair of adjacent subfaces for small angle.
25058 spinsh = * (face *)(* spinshlist)[0];
25059 for (i = 1; i <= spinshlist->len() && !issharp; i++) {
25060 if (i == spinshlist->len()) {
25061 neighsh = * (face *)(* spinshlist)[0];
25062 } else {
25063 neighsh = * (face *)(* spinshlist)[i];
25064 }
25065 // Only do test when the spinsh is faceing inward.
25066 stpivot(spinsh, adjtet);
25067 if (adjtet.tet != dummytet) {
25068 angle = facedihedral(eorg, edest, sapex(spinsh), sapex(neighsh));
25069 issharp = angle < smallang;
25070 }
25071 spinsh = neighsh;
25072 }
25073 spinshlist->clear();
25074 }
25075 // Set type for this segment (inclusing subsegments).
25076 stype = issharp ? SHARP : NSHARPNSKINNY;
25077 scount += issharp ? 1 : 0;
25078 setshelltype(segloop, stype);
25079 senext(segloop, nextseg);
25080 spivotself(nextseg);
25081 while (nextseg.sh != dummysh) {
25082 nextseg.shver = 0;
25083 setshelltype(nextseg, stype);
25084 senextself(nextseg);
25085 spivotself(nextseg);
25086 }
25087 }
25088 segloop.sh = shellfacetraverse(subsegs);
25089 }
25090
25091 if (b->verbose > 0) {
25092 printf(" %d sharp segments.\n", scount);
25093 }
25094 delete spinshlist;
25095 }
25096
25097 ///////////////////////////////////////////////////////////////////////////////
25098 // //
25099 // markskinnysubfaces() Mark all skinny subfaces. //
25100 // //
25101 // A subface is skinny if it has an angle smaller than 'anglebound' and the //
25102 // two edges form the angle are both segments. Such subface is not be able //
25103 // to refine. It will be marked as type SKINNY. //
25104 // //
25105 // This procedure operates in two phases. The first phase finds some skinny //
25106 // subfaces by checking the angles of subfaces. The second phase finds all //
25107 // skinny subfaces by a neighbor-first search. //
25108 // //
25109 ///////////////////////////////////////////////////////////////////////////////
25110
25111 void tetgenmesh::markskinnysubfaces(REAL anglebound)
25112 {
25113 list *skinnyshlist;
25114 face subloop, checksub;
25115 face startsh, neighsh;
25116 face seg1, seg2, checkseg;
25117 point pa, pb, pc;
25118 enum shestype shty;
25119 REAL smallang, angle;
25120 int i, j;
25121
25122 if (b->verbose > 0) {
25123 printf(" Marking skinny subfaces.\n");
25124 }
25125
25126 smallang = anglebound * PI / 180.;
25127 // Initial working list.
25128 skinnyshlist = new list(sizeof(face), NULL, subfaces->items);
25129
25130 // Loop the set of subfaces, collect some skinny ones.
25131 subfaces->traversalinit();
25132 subloop.sh = shellfacetraverse(subfaces);
25133 while (subloop.sh != (shellface *) NULL) {
25134 // Check the three angles of subloop;
25135 for (i = 0; i < 3; i++) {
25136 sspivot(subloop, seg1);
25137 if (seg1.sh != dummysh) {
25138 senext2(subloop, checksub);
25139 sspivot(checksub, seg2);
25140 if (seg2.sh != dummysh) {
25141 pa = sorg(subloop);
25142 pb = sdest(subloop);
25143 pc = sapex(subloop);
25144 angle = interiorangle(pa, pb, pc, NULL);
25145 if (angle < smallang) {
25146 // It is skinny!
25147 setshelltype(subloop, SKINNY);
25148 skinnyshlist->append(&subloop);
25149 break;
25150 }
25151 }
25152 }
25153 senextself(subloop);
25154 }
25155 subloop.sh = shellfacetraverse(subfaces);
25156 }
25157
25158 // Next finds all skinny subfaces.
25159 for (i = 0; i < skinnyshlist->len(); i++) {
25160 startsh = * (face *)(* skinnyshlist)[i];
25161 shty = shelltype(startsh);
25162 for (j = 0; j < 3; j++) {
25163 sspivot(startsh, checkseg);
25164 if (checkseg.sh == dummysh) {
25165 spivot(startsh, neighsh);
25166 if (shelltype(neighsh) != shty) {
25167 setshelltype(neighsh, shty);
25168 skinnyshlist->append(&neighsh);
25169 }
25170 }
25171 senextself(startsh);
25172 }
25173 }
25174
25175 if (b->verbose > 0) {
25176 printf(" %d skinny subfaces.\n", skinnyshlist->len());
25177 }
25178 delete skinnyshlist;
25179 }
25180
25181 ///////////////////////////////////////////////////////////////////////////////
25182 // //
25183 // enqueuebadtet() Add a tetrahedron into the queue. //
25184 // //
25185 ///////////////////////////////////////////////////////////////////////////////
25186
25187 void tetgenmesh::enqueuebadtet(triface* testtet, REAL ratio2, REAL* cent)
25188 {
25189 badface *newbadtet;
25190 int queuenumber;
25191 int i;
25192
25193 // Allocate space for the bad tetrahedron.
25194 newbadtet = (badface *) badtetrahedrons->alloc();
25195 newbadtet->tt = *testtet;
25196 newbadtet->key = ratio2;
25197 if (cent != NULL) {
25198 for (i = 0; i < 3; i++) newbadtet->cent[i] = cent[i];
25199 } else {
25200 for (i = 0; i < 3; i++) newbadtet->cent[i] = 0.0;
25201 }
25202 newbadtet->forg = org(*testtet);
25203 newbadtet->fdest = dest(*testtet);
25204 newbadtet->fapex = apex(*testtet);
25205 newbadtet->foppo = oppo(*testtet);
25206 newbadtet->nextitem = (badface *) NULL;
25207 // Determine the appropriate queue to put the bad tetrahedron into.
25208 if (ratio2 > b->goodratio) {
25209 queuenumber = (int) ((ratio2 - b->goodratio) / 0.5);
25210 // 'queuenumber' may overflow (negative) caused by a very large ratio.
25211 if ((queuenumber > 63) || (queuenumber < 0)) {
25212 queuenumber = 63;
25213 }
25214 } else {
25215 // It's not a bad ratio; put the tet in the lowest-priority queue.
25216 queuenumber = 0;
25217 }
25218 // Add the tetrahedron to the end of a queue.
25219 *tetquetail[queuenumber] = newbadtet;
25220 // Maintain a pointer to the NULL pointer at the end of the queue.
25221 tetquetail[queuenumber] = &newbadtet->nextitem;
25222 if (b->verbose > 2) {
25223 printf(" Queueing bad tet: (%d, %d, %d, %d), ratio %g, qnum %d.\n",
25224 pointmark(newbadtet->forg), pointmark(newbadtet->fdest),
25225 pointmark(newbadtet->fapex), pointmark(newbadtet->foppo),
25226 sqrt(ratio2), queuenumber);
25227 }
25228 }
25229
25230 ///////////////////////////////////////////////////////////////////////////////
25231 // //
25232 // enqueueencsub() Add an encroached subface into the queue. //
25233 // //
25234 ///////////////////////////////////////////////////////////////////////////////
25235
25236 void tetgenmesh::enqueueencsub(face* testsub, point encpt, int quenumber,
25237 REAL* cent)
25238 {
25239 badface *encsub;
25240 int i;
25241
25242 encsub = (badface *) badsubfaces->alloc();
25243 encsub->ss = *testsub;
25244 encsub->forg = sorg(*testsub);
25245 encsub->fdest = sdest(*testsub);
25246 encsub->fapex = sapex(*testsub);
25247 encsub->foppo = (point) encpt;
25248 if (quenumber == 2) {
25249 for (i = 0; i < 3; i++) encsub->cent[i] = 0.0;
25250 } else {
25251 for (i = 0; i < 3; i++) encsub->cent[i] = cent[i];
25252 }
25253 encsub->nextitem = (badface *) NULL;
25254 // Set the pointer of 'encsubseg' into 'testsub'. It has two purposes:
25255 // (1) We can regonize it is encroached; (2) It is uniquely queued.
25256 setshell2badface(encsub->ss, encsub);
25257 // Add the subface to the end of a queue (quenumber = 2, high priority).
25258 *subquetail[quenumber] = encsub;
25259 // Maintain a pointer to the NULL pointer at the end of the queue.
25260 subquetail[quenumber] = &encsub->nextitem;
25261 if (b->verbose > 2) {
25262 printf(" Queuing subface (%d, %d, %d) [%d].\n", pointmark(encsub->forg),
25263 pointmark(encsub->fdest), pointmark(encsub->fapex), quenumber);
25264 }
25265 }
25266
25267 ///////////////////////////////////////////////////////////////////////////////
25268 // //
25269 // dequeuebadtet() Remove a tetrahedron from the front of the queue. //
25270 // //
25271 ///////////////////////////////////////////////////////////////////////////////
25272
25273 tetgenmesh::badface* tetgenmesh::dequeuebadtet()
25274 {
25275 badface *result;
25276 int queuenumber;
25277
25278 // Look for a nonempty queue.
25279 for (queuenumber = 63; queuenumber >= 0; queuenumber--) {
25280 result = tetquefront[queuenumber];
25281 if (result != (badface *) NULL) {
25282 // Remove the tetrahedron from the queue.
25283 tetquefront[queuenumber] = result->nextitem;
25284 // Maintain a pointer to the NULL pointer at the end of the queue.
25285 if (tetquefront[queuenumber] == (badface *) NULL) {
25286 tetquetail[queuenumber] = &tetquefront[queuenumber];
25287 }
25288 return result;
25289 }
25290 }
25291 return (badface *) NULL;
25292 }
25293
25294 ///////////////////////////////////////////////////////////////////////////////
25295 // //
25296 // dequeueencsub() Remove an enc-subface from the front of the queue. //
25297 // //
25298 ///////////////////////////////////////////////////////////////////////////////
25299
25300 tetgenmesh::badface* tetgenmesh::dequeueencsub(int* pquenumber)
25301 {
25302 badface *result;
25303 int quenumber;
25304
25305 // Look for a nonempty queue.
25306 for (quenumber = 2; quenumber >= 0; quenumber--) {
25307 result = subquefront[quenumber];
25308 if (result != (badface *) NULL) {
25309 // Remove the badface from the queue.
25310 subquefront[quenumber] = result->nextitem;
25311 // Maintain a pointer to the NULL pointer at the end of the queue.
25312 if (subquefront[quenumber] == (badface *) NULL) {
25313 subquetail[quenumber] = &subquefront[quenumber];
25314 }
25315 *pquenumber = quenumber;
25316 return result;
25317 }
25318 }
25319 return (badface *) NULL;
25320 }
25321
25322 ///////////////////////////////////////////////////////////////////////////////
25323 // //
25324 // checkseg4encroach() Check a subsegment to see if it is encroached. //
25325 // //
25326 // A segment s is encroached if there is a vertex lies inside or on its dia- //
25327 // metral circumsphere, i.e., s faces an angle theta >= 90 degrees. //
25328 // //
25329 // If 'testpt' (p) != NULL, only test if 'testseg' (s) is encroached by it, //
25330 // else, check all apexes of faces around s. Return TRUE if s is encroached. //
25331 // If and 'enqflag' is TRUE, add it into 'badsubsegs' if s is encroached. //
25332 // //
25333 // If 'prefpt' != NULL, it returns the reference point (defined in my paper) //
25334 // if it exists. This point is will be used to split s. //
25335 // //
25336 ///////////////////////////////////////////////////////////////////////////////
25337
25338 bool tetgenmesh::checkseg4encroach(face* testseg, point testpt, point* prefpt,
25339 bool enqflag)
25340 {
25341 badface *encsubseg;
25342 triface starttet, spintet;
25343 point eorg, edest, eapex, encpt;
25344 REAL cent[3], radius, dist, diff;
25345 REAL maxradius;
25346 bool enq;
25347 int hitbdry;
25348
25349 eorg = sorg(*testseg);
25350 edest = sdest(*testseg);
25351 cent[0] = 0.5 * (eorg[0] + edest[0]);
25352 cent[1] = 0.5 * (eorg[1] + edest[1]);
25353 cent[2] = 0.5 * (eorg[2] + edest[2]);
25354 radius = distance(cent, eorg);
25355
25356 enq = false;
25357 maxradius = 0.0;
25358 if (testpt == (point) NULL) {
25359 // Check if it is encroached by traversing all faces containing it.
25360 sstpivot(testseg, &starttet);
25361 eapex = apex(starttet);
25362 spintet = starttet;
25363 hitbdry = 0;
25364 do {
25365 dist = distance(cent, apex(spintet));
25366 diff = dist - radius;
25367 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25368 if (diff <= 0.0) {
25369 // s is encroached.
25370 enq = true;
25371 if (prefpt != (point *) NULL) {
25372 // Find the reference point.
25373 encpt = apex(spintet);
25374 circumsphere(eorg, edest, encpt, NULL, NULL, &dist);
25375 if (dist > maxradius) {
25376 // Rememebr this point.
25377 *prefpt = encpt;
25378 maxradius = dist;
25379 }
25380 } else {
25381 break;
25382 }
25383 }
25384 if (!fnextself(spintet)) {
25385 hitbdry++;
25386 if (hitbdry < 2) {
25387 esym(starttet, spintet);
25388 if (!fnextself(spintet)) {
25389 hitbdry++;
25390 }
25391 }
25392 }
25393 } while (apex(spintet) != eapex && (hitbdry < 2));
25394 } else {
25395 // Only check if 'testseg' is encroached by 'testpt'.
25396 dist = distance(cent, testpt);
25397 diff = dist - radius;
25398 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25399 enq = (diff <= 0.0);
25400 }
25401
25402 if (enq && enqflag) {
25403 if (b->verbose > 2) {
25404 printf(" Queuing encroaching subsegment (%d, %d).\n",
25405 pointmark(eorg), pointmark(edest));
25406 }
25407 encsubseg = (badface *) badsubsegs->alloc();
25408 encsubseg->ss = *testseg;
25409 encsubseg->forg = eorg;
25410 encsubseg->fdest = edest;
25411 encsubseg->foppo = (point) NULL; // Not used.
25412 // Set the pointer of 'encsubseg' into 'testseg'. It has two purposes:
25413 // (1) We can regonize it is encroached; (2) It is uniquely queued.
25414 setshell2badface(encsubseg->ss, encsubseg);
25415 }
25416
25417 return enq;
25418 }
25419
25420 ///////////////////////////////////////////////////////////////////////////////
25421 // //
25422 // checksub4encroach() Check a subface to see if it is encroached. //
25423 // //
25424 // A subface f is encroached if there is a vertex inside or on its diametral //
25425 // circumsphere. //
25426 // //
25427 // If 'testpt (p) != NULL', test if 'testsub' (f) is encroached by it, else, //
25428 // test if f is encroached by one of the two opposites of the adjacent tets. //
25429 // Return TRUE if f is encroached and queue it if 'enqflag' is set. //
25430 // //
25431 ///////////////////////////////////////////////////////////////////////////////
25432
25433 bool tetgenmesh::checksub4encroach(face* testsub, point testpt, bool enqflag)
25434 {
25435 triface abuttet;
25436 point forg, fdest, fapex, encpt;
25437 REAL cent[3];
25438 REAL radius, dist, diff;
25439 bool enq, ncollinear;
25440 int quenumber;
25441
25442 forg = sorg(*testsub);
25443 fdest = sdest(*testsub);
25444 fapex = sapex(*testsub);
25445 ncollinear = circumsphere(forg, fdest, fapex, NULL, cent, &radius);
25446 if (!ncollinear) return false; // Not a valid subface.
25447
25448 enq = false;
25449 encpt = (point) NULL;
25450 if (testpt == (point) NULL) {
25451 stpivot(*testsub, abuttet);
25452 if (abuttet.tet != dummytet) {
25453 dist = distance(cent, oppo(abuttet));
25454 diff = dist - radius;
25455 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25456 enq = (diff <= 0.0);
25457 if (enq) encpt = oppo(abuttet);
25458 }
25459 if (!enq) {
25460 sesymself(*testsub);
25461 stpivot(*testsub, abuttet);
25462 if (abuttet.tet != dummytet) {
25463 dist = distance(cent, oppo(abuttet));
25464 diff = dist - radius;
25465 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25466 enq = (diff <= 0.0);
25467 if (enq) encpt = oppo(abuttet);
25468 }
25469 }
25470 } else {
25471 dist = distance(cent, testpt);
25472 diff = dist - radius;
25473 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25474 enq = (diff <= 0.0);
25475 }
25476
25477 if (enq && enqflag) {
25478 /* REAL prj[3], ori1, ori2, ori3;
25479 bool inflag;
25480 // Test if encpt is inside the face.
25481 if (encpt) {
25482 projpt2face(encpt, forg, fdest, fapex, prj);
25483 } else {
25484 assert(testpt);
25485 projpt2face(testpt, forg, fdest, fapex, prj);
25486 }
25487 abovepoint = facetabovepointarray[shellmark(*testsub)];
25488 if (abovepoint == (point) NULL) {
25489 getfacetabovepoint(testsub);
25490 }
25491 ori1 = orient3d(forg, fdest, abovepoint, prj);
25492 ori2 = orient3d(fdest, fapex, abovepoint, prj);
25493 inflag = (ori1 * ori2 >= 0.0);
25494 if (inflag) {
25495 ori3 = orient3d(fapex, forg, abovepoint, prj);
25496 inflag = (ori2 * ori3 >= 0.0);
25497 }
25498 // Decide which queue (1 or 0) to put s (1 has higher priority).
25499 quenumber = (inflag ? 1 : 0); */
25500 quenumber = 0;
25501 enqueueencsub(testsub, encpt, quenumber, cent);
25502 }
25503
25504 return enq;
25505 }
25506
25507 ///////////////////////////////////////////////////////////////////////////////
25508 // //
25509 // checkseg4badqual() Check if a segment is longer than it is allowed. //
25510 // //
25511 ///////////////////////////////////////////////////////////////////////////////
25512
25513 bool tetgenmesh::checkseg4badqual(face* testseg, bool enqflag)
25514 {
25515 badface *encsubseg;
25516 point eorg, edest;
25517 REAL dist;
25518 bool enq;
25519
25520 eorg = sorg(*testseg);
25521 edest = sdest(*testseg);
25522 dist = distance(eorg, edest);
25523
25524 enq = dist > areabound(*testseg);
25525
25526 if (enq && enqflag) {
25527 if (b->verbose > 2) {
25528 printf(" Queuing badqual subsegment (%d, %d).\n",
25529 pointmark(eorg), pointmark(edest));
25530 }
25531 encsubseg = (badface *) badsubsegs->alloc();
25532 encsubseg->ss = *testseg;
25533 encsubseg->forg = eorg;
25534 encsubseg->fdest = edest;
25535 encsubseg->foppo = NULL;
25536 // Set the pointer of 'encsubseg' into 'testseg'. It has two purposes:
25537 // (1) We can regonize it is encroached; (2) It is uniquely queued.
25538 setshell2badface(encsubseg->ss, encsubseg);
25539 }
25540
25541 return enq;
25542 }
25543
25544 ///////////////////////////////////////////////////////////////////////////////
25545 // //
25546 // checksub4badqual() Test if the quality of a subface is bad. //
25547 // //
25548 // A subface has bad quality if: (1) its minimum internal angle is smaller //
25549 // than 20 degree; or (2) its area is larger than a maximum area condition. //
25550 // Return TRUE if it is bad. //
25551 // //
25552 ///////////////////////////////////////////////////////////////////////////////
25553
25554 bool tetgenmesh::checksub4badqual(face* testsub, bool enqflag)
25555 {
25556 face sametestsub;
25557 face subseg1, subseg2;
25558 point torg, tdest, tapex;
25559 point anglevertex;
25560 REAL dxod, dyod, dzod;
25561 REAL dxda, dyda, dzda;
25562 REAL dxao, dyao, dzao;
25563 REAL dxod2, dyod2, dzod2;
25564 REAL dxda2, dyda2, dzda2;
25565 REAL dxao2, dyao2, dzao2;
25566 REAL apexlen, orglen, destlen;
25567 REAL angle, area;
25568 bool enq;
25569
25570 enq = false;
25571 torg = sorg(*testsub);
25572 tdest = sdest(*testsub);
25573 tapex = sapex(*testsub);
25574 dxod = torg[0] - tdest[0];
25575 dyod = torg[1] - tdest[1];
25576 dzod = torg[2] - tdest[2];
25577 dxda = tdest[0] - tapex[0];
25578 dyda = tdest[1] - tapex[1];
25579 dzda = tdest[2] - tapex[2];
25580 dxao = tapex[0] - torg[0];
25581 dyao = tapex[1] - torg[1];
25582 dzao = tapex[2] - torg[2];
25583 dxod2 = dxod * dxod;
25584 dyod2 = dyod * dyod;
25585 dzod2 = dzod * dzod;
25586 dxda2 = dxda * dxda;
25587 dyda2 = dyda * dyda;
25588 dzda2 = dzda * dzda;
25589 dxao2 = dxao * dxao;
25590 dyao2 = dyao * dyao;
25591 dzao2 = dzao * dzao;
25592 // Find the lengths of the triangle's three edges.
25593 apexlen = dxod2 + dyod2 + dzod2;
25594 orglen = dxda2 + dyda2 + dzda2;
25595 destlen = dxao2 + dyao2 + dzao2;
25596 if ((apexlen < orglen) && (apexlen < destlen)) {
25597 // The edge opposite the apex is shortest.
25598 // Find the square of the cosine of the angle at the apex.
25599 angle = dxda * dxao + dyda * dyao + dzda * dzao;
25600 angle = angle * angle / (orglen * destlen);
25601 anglevertex = tapex;
25602 senext(*testsub, sametestsub);
25603 sspivot(sametestsub, subseg1);
25604 senext2(*testsub, sametestsub);
25605 sspivot(sametestsub, subseg2);
25606 } else if (orglen < destlen) {
25607 // The edge opposite the origin is shortest.
25608 // Find the square of the cosine of the angle at the origin.
25609 angle = dxod * dxao + dyod * dyao + dzod * dzao;
25610 angle = angle * angle / (apexlen * destlen);
25611 anglevertex = torg;
25612 sspivot(*testsub, subseg1);
25613 senext2(*testsub, sametestsub);
25614 sspivot(sametestsub, subseg2);
25615 } else {
25616 // The edge opposite the destination is shortest.
25617 // Find the square of the cosine of the angle at the destination.
25618 angle = dxod * dxda + dyod * dyda + dzod * dzda;
25619 angle = angle * angle / (apexlen * orglen);
25620 anglevertex = tdest;
25621 sspivot(*testsub, subseg1);
25622 senext(*testsub, sametestsub);
25623 sspivot(sametestsub, subseg2);
25624 }
25625
25626 // Check if both edges that form the angle are segments.
25627 // if ((subseg1.sh != dummysh) && (subseg2.sh != dummysh)) {
25628 if (shelltype(*testsub) == SKINNY) {
25629 // The angle is a segment intersection. Don't add this bad subface to
25630 // the list; there's nothing that can be done about a small angle
25631 // between two segments.
25632 angle = 0.0;
25633 }
25634
25635 // Check whether the angle is smaller than permitted.
25636 if (angle > b->goodangle) {
25637 enq = true;
25638 }
25639
25640 if (!enq && varconstraint && areabound(*testsub) > 0.0) {
25641 // Check whether the area is larger than desired. A variation form of
25642 // Heron's formula which only uses the squares of the edge lengthes
25643 // is used to calculated the area of a 3D triangle.
25644 area = apexlen + orglen - destlen;
25645 area = area * area;
25646 area = 4 * apexlen * orglen - area;
25647 area = 0.25 * sqrt(fabs(area));
25648 enq = area > areabound(*testsub);
25649 }
25650
25651 if (enq && enqflag) {
25652 enqueueencsub(testsub, NULL, 2, NULL);
25653 }
25654
25655 return enq;
25656 }
25657
25658 ///////////////////////////////////////////////////////////////////////////////
25659 // //
25660 // checktet4badqual() Test a tetrahedron for quality measures. //
25661 // //
25662 // Tests a tetrahedron to see if it satisfies the minimum ratio condition //
25663 // and the maximum volume condition. Tetrahedra that aren't upto spec are //
25664 // added to the bad tetrahedron queue. //
25665 // //
25666 ///////////////////////////////////////////////////////////////////////////////
25667
25668 bool tetgenmesh::checktet4badqual(triface* testtet, bool enqflag)
25669 {
25670 badface *newbadtet;
25671 point pa, pb, pc, pd, pe1, pe2;
25672 REAL vda[3], vdb[3], vdc[3];
25673 REAL vab[3], vbc[3], vca[3];
25674 REAL N[4][3], A[4][4], rhs[4], D;
25675 REAL elen[6], circumcent[3];
25676 REAL bicent[3], offcent[3];
25677 REAL volume, L, q, cosd;
25678 REAL radius2, smlen2, ratio2;
25679 REAL dist, sdist, split;
25680 bool enq;
25681 int indx[4];
25682 int queuenumber;
25683 int sidx, i, j;
25684
25685 pa = (point) testtet->tet[4];
25686 pb = (point) testtet->tet[5];
25687 pc = (point) testtet->tet[6];
25688 pd = (point) testtet->tet[7];
25689
25690 // Avoid compile warnings.
25691 pe1 = pe2 = (point) NULL;
25692 radius2 = 0.0;
25693
25694 // Get the edge vectors vda: d->a, vdb: d->b, vdc: d->c.
25695 // Set the matrix A = [vda, vdb, vdc]^T.
25696 for (i = 0; i < 3; i++) A[0][i] = vda[i] = pa[i] - pd[i];
25697 for (i = 0; i < 3; i++) A[1][i] = vdb[i] = pb[i] - pd[i];
25698 for (i = 0; i < 3; i++) A[2][i] = vdc[i] = pc[i] - pd[i];
25699 // Get the rest edge vectors
25700 for (i = 0; i < 3; i++) vab[i] = pb[i] - pa[i];
25701 for (i = 0; i < 3; i++) vbc[i] = pc[i] - pb[i];
25702 for (i = 0; i < 3; i++) vca[i] = pa[i] - pc[i];
25703
25704 // Lu-decompose the matrix A.
25705 lu_decmp(A, 3, indx, &D, 0);
25706 // Get the volume of abcd.
25707 volume = (A[indx[0]][0] * A[indx[1]][1] * A[indx[2]][2]) / 6.0;
25708 if (volume < 0.0) volume = -volume;
25709 // Compare the volume to average edge length of abcd.
25710 elen[0] = dot(vda, vda);
25711 elen[1] = dot(vdb, vdb);
25712 elen[2] = dot(vdc, vdc);
25713 elen[3] = dot(vab, vab);
25714 elen[4] = dot(vbc, vbc);
25715 elen[5] = dot(vca, vca);
25716
25717 enq = false;
25718 if (b->offcenter) {
25719 // Check if the tet is very flat.
25720 L = 0.0;
25721 for (i = 0; i < 6; i++) L += sqrt(elen[i]);
25722 L /= 6.0;
25723 q = volume / (L * L * L);
25724 enq = (q < b->epsilon * 1e+2);
25725 }
25726
25727 // Is abcd very flat?
25728 if (!enq) {
25729 rhs[0] = 0.5 * dot(vda, vda);
25730 rhs[1] = 0.5 * dot(vdb, vdb);
25731 rhs[2] = 0.5 * dot(vdc, vdc);
25732 lu_solve(A, 3, indx, rhs, 0);
25733 // Get the circumcenter.
25734 for (i = 0; i < 3; i++) circumcent[i] = pd[i] + rhs[i];
25735 // Get the square of the circumradius.
25736 radius2 = dot(rhs, rhs);
25737 // Find the square of the shortest edge length.
25738 smlen2 = elen[0]; sidx = 0;
25739 for (i = 1; i < 6; i++) {
25740 if (smlen2 > elen[i]) { smlen2 = elen[i]; sidx = i; }
25741 }
25742 // Calculate the square of radius-edge ratio.
25743 ratio2 = radius2 / smlen2;
25744 // Check whether the ratio is smaller than permitted.
25745 enq = ratio2 > b->goodratio;
25746 if (!enq) {
25747 // abcd has good ratio.
25748 if (b->offcenter) {
25749 // Test if it is a sliver.
25750 // Compute the 4 face normals (N[0], ..., N[3]).
25751 for (j = 0; j < 3; j++) {
25752 for (i = 0; i < 3; i++) rhs[i] = 0.0;
25753 rhs[j] = 1.0; // Positive means the inside direction
25754 lu_solve(A, 3, indx, rhs, 0);
25755 for (i = 0; i < 3; i++) N[j][i] = rhs[i];
25756 }
25757 // Get the fourth normal by summing up the first three.
25758 for (i = 0; i < 3; i++) N[3][i] = - N[0][i] - N[1][i] - N[2][i];
25759 // Normalized the normals.
25760 for (i = 0; i < 4; i++) {
25761 L = sqrt(dot(N[i], N[i]));
25762 if (L > 0.0) {
25763 for (j = 0; j < 3; j++) N[i][j] /= L;
25764 }
25765 }
25766 // N[0] is the normal of face bcd. Test the dihedral angles at edge
25767 // cd, bd, and bc to see if they are too small or too big.
25768 for (i = 1; i < 4 && !enq; i++) {
25769 cosd = -dot(N[0], N[i]); // Edge cd, bd, bc.
25770 enq = ((cosd > cosmindihed) || ((cosd < cosmaxdihed)));
25771 }
25772 if (enq) {
25773 // A sliver! Split it at the barycenter.
25774 for (i = 0; i < 3; i++) {
25775 circumcent[i] = 0.25 * (pa[i] + pb[i] + pc[i] + pd[i]);
25776 }
25777 ratio2 = 0.0;
25778 }
25779 }
25780 } else if (b->offcenter) {
25781 // abcd has bad-quality. Use off-center instead of circumcenter.
25782 switch (sidx) {
25783 case 0: // edge da.
25784 pe1 = pd; pe2 = pa; break;
25785 case 1: // edge db.
25786 pe1 = pd; pe2 = pb; break;
25787 case 2: // edge dc.
25788 pe1 = pd; pe2 = pc; break;
25789 case 3: // edge ab.
25790 pe1 = pa; pe2 = pb; break;
25791 case 4: // edge bc.
25792 pe1 = pb; pe2 = pc; break;
25793 case 5: // edge ca.
25794 pe1 = pc; pe2 = pa; break;
25795 default: break;
25796 }
25797 // The shortest edge is e1->e2.
25798 for (i = 0; i < 3; i++) bicent[i] = 0.5 * (pe1[i] + pe2[i]);
25799 dist = distance(bicent, circumcent);
25800 // sdist = sqrt(smlen2) * sin(PI / 3.0); // A icoso-triangle.
25801 // The following formulae is from
25802 sdist = b->alpha3 * (b->minratio + sqrt(b->goodratio - 0.25))
25803 * sqrt(smlen2);
25804 split = sdist / dist;
25805 if (split > 1.0) split = 1.0;
25806 // Get the off-center.
25807 for (i = 0; i < 3; i++) {
25808 offcent[i] = bicent[i] + split * (circumcent[i] - bicent[i]);
25809 }
25810 }
25811 } else {
25812 // A fat tet. Split it at the centroid.
25813 for (i = 0; i < 3; i++) {
25814 circumcent[i] = 0.25 * (pa[i] + pb[i] + pc[i] + pd[i]);
25815 }
25816 ratio2 = 0.0;
25817 }
25818
25819 if (!enq && (b->varvolume || b->fixedvolume)) {
25820 // The tet is in good shape.
25821 ratio2 = 0.0;
25822 enq = b->fixedvolume && (volume > b->maxvolume);
25823 if (!enq && b->varvolume) {
25824 enq = (volume > volumebound(testtet->tet)) &&
25825 (volumebound(testtet->tet) > 0.0);
25826 }
25827 }
25828 if (!enq) {
25829 // The tet is in good shape.
25830 ratio2 = 0.0;
25831 if (b->bgmesh && (b->alpha1 > 0.0)) {
25832 sdist = sqrt(radius2) / b->alpha1;
25833 // Check if the nodal size map is satisfied.
25834 for (i = 0; i < 4; i++) {
25835 pa = (point) testtet->tet[4 + i];
25836 // Get the indicated size of p.
25837 dist = pa[3]; // dist = b->alpha1 * pa[pointlfsindex];
25838 enq = ((dist < sdist) && (dist > 0.0));
25839 if (enq) break; // It is bad wrt. a node constraint.
25840 // *** Experiment ! Stop test if c is inside H(a).
25841 // if ((dist > 0.0) && (dist > sdist)) break;
25842 }
25843 // *** Experiment !
25844 // enq = (i == 4); // Does c lies outside all sparse-ball?
25845 }
25846 }
25847
25848 if (enq && enqflag) {
25849 // Allocate space for the bad tetrahedron.
25850 newbadtet = (badface *) badtetrahedrons->alloc();
25851 newbadtet->tt = *testtet;
25852 newbadtet->key = ratio2;
25853 if ((ratio2 != 0) && b->offcenter) {
25854 for (i = 0; i < 3; i++) newbadtet->cent[i] = offcent[i];
25855 } else {
25856 for (i = 0; i < 3; i++) newbadtet->cent[i] = circumcent[i];
25857 }
25858 newbadtet->forg = org(*testtet);
25859 newbadtet->fdest = dest(*testtet);
25860 newbadtet->fapex = apex(*testtet);
25861 newbadtet->foppo = oppo(*testtet);
25862 newbadtet->nextitem = (badface *) NULL;
25863 // Determine the appropriate queue to put the bad tetrahedron into.
25864 if (ratio2 > b->goodratio) {
25865 queuenumber = (int) ((ratio2 - b->goodratio) / 0.5);
25866 // 'queuenumber' may overflow (negative) caused by a very large ratio.
25867 if ((queuenumber > 63) || (queuenumber < 0)) {
25868 queuenumber = 63;
25869 }
25870 } else {
25871 // It's not a bad ratio; put the tet in the lowest-priority queue.
25872 queuenumber = 0;
25873 }
25874 // Add the tetrahedron to the end of a queue.
25875 *tetquetail[queuenumber] = newbadtet;
25876 // Maintain a pointer to the NULL pointer at the end of the queue.
25877 tetquetail[queuenumber] = &newbadtet->nextitem;
25878 if (b->verbose > 2) {
25879 printf(" Queueing bad tet: (%d, %d, %d, %d), ratio %g, qnum %d.\n",
25880 pointmark(pa), pointmark(pb), pointmark(pc), pointmark(pd),
25881 sqrt(ratio2), queuenumber);
25882 }
25883 }
25884
25885 return enq;
25886 }
25887
25888 ///////////////////////////////////////////////////////////////////////////////
25889 // //
25890 // acceptsegpt() Check if a segment point can be inserted or not. //
25891 // //
25892 // Segment(ab) is indicated to be split by a point p (\in ab). This routine //
25893 // decides whether p can be inserted or not. //
25894 // //
25895 // p can not be inserted either the '-Y' option is used and ab is a hull //
25896 // segment or '-YY' option is used. //
25897 // //
25898 // p can be inserted if it is in one of the following cases (L = |a - b|): //
25899 // (1) if ab is too long wrt the edge constraint (bad-quality); or //
25900 // (2) if a subface having ab has max. area constraint A, and L^2 > 2 * A, //
25901 // (3) if a tet having ab has maximal volume constraint V, and L^3 > 6 * V.//
25902 // (4) if |a - p| > \alpha_2 H(a) and |p - b| > \alpha_2 H(b). //
25903 // (5) if 'refpt' != NULL. //
25904 // //
25905 // The purpose of using L instead of area and volume is to avoid resulting //
25906 // too skinny triangles and tetrahedron. //
25907 // //
25908 ///////////////////////////////////////////////////////////////////////////////
25909
25910 bool tetgenmesh::acceptsegpt(point segpt, point refpt, face* splitseg)
25911 {
25912 triface spintet;
25913 face parentsh, spinsh;
25914 point pa, pb, pc;
25915 REAL ablen, palen, pblen;
25916 REAL V, A;
25917
25918 if (b->nobisect == 1) {
25919 // '-Y'. It can not be split if it is on the hull.
25920 sstpivot(splitseg, &spintet);
25921 assert(spintet.tet != dummytet);
25922 pc = apex(spintet);
25923 do {
25924 if (!fnextself(spintet)) {
25925 // Meet a boundary face - s is on the hull.
25926 return false;
25927 }
25928 } while (pc != apex(spintet));
25929 } else if (b->nobisect > 1) {
25930 // '-YY'. Do not split it.
25931 return false;
25932 }
25933
25934 pa = sorg(*splitseg);
25935 pb = sdest(*splitseg);
25936 ablen = distance(pa, pb);
25937 if (varconstraint) {
25938 A = areabound(*splitseg);
25939 if ((A > 0.0) && (ablen > A)) {
25940 return true; // case (1)
25941 }
25942 }
25943
25944 if (varconstraint && in->facetconstraintlist) {
25945 A = ablen * ablen / 2.0;
25946 spinsh = parentsh;
25947 do {
25948 if ((A > areabound(spinsh)) && (areabound(spinsh) > 0.0)) {
25949 return true; // case (2)
25950 }
25951 spivotself(spinsh);
25952 } while (spinsh.sh != parentsh.sh);
25953 }
25954
25955 if (b->varvolume || b->fixedvolume) {
25956 V = ablen * ablen * ablen / 6.0;
25957 if (b->fixedvolume && (V > b->maxvolume)) {
25958 return true; // case (3)
25959 }
25960 if (b->varvolume) {
25961 spivot(*splitseg, parentsh);
25962 if (sorg(parentsh) != pa) sesymself(parentsh);
25963 stpivot(parentsh, spintet);
25964 if (spintet.tet == dummytet) {
25965 sesymself(parentsh);
25966 stpivot(parentsh, spintet);
25967 }
25968 findedge(&spintet, pa, pb);
25969 pc = apex(spintet);
25970 while (true) {
25971 if (!fnextself(spintet)) {
25972 // Meet a boundary, walk through it.
25973 tspivot(spintet, spinsh);
25974 findedge(&spinsh, pa, pb);
25975 sfnextself(spinsh);
25976 stpivot(spinsh, spintet);
25977 findedge(&spintet, pa, pb);
25978 }
25979 if ((V > volumebound(spintet.tet)) &&
25980 (volumebound(spintet.tet) > 0.0)) {
25981 return true; // case (3)
25982 }
25983 if (apex(spintet) == pc) break;
25984 }
25985 }
25986 }
25987
25988 // If p is outside both protect balls of a and b.
25989 palen = distance(segpt, pa);
25990 pblen = distance(segpt, pb);
25991 if (!b->bgmesh) {
25992 if ((palen > (b->alpha2 * pa[pointlfsindex])) &&
25993 (pblen > (b->alpha2 * pb[pointlfsindex]))) {
25994 return true; // case (4)
25995 }
25996 } else {
25997 if ((palen > b->alpha2 * pa[3]) && (pblen > b->alpha2 * pb[3])) {
25998 return true; // case (4)
25999 }
26000 }
26001
26002 // If 'refpt' != NULL, force p to be inserted.
26003 if (refpt != (point) NULL) {
26004 cdtenforcesegpts++;
26005 return true;
26006 }
26007
26008 // Do not split it.
26009 rejsegpts++;
26010 return false;
26011 }
26012
26013 ///////////////////////////////////////////////////////////////////////////////
26014 // //
26015 // acceptfacpt() Check if a facet point can be inserted or not. //
26016 // //
26017 // 'subceillist' is CBC(p). 'verlist' (V) is empty on input, it returns the //
26018 // set of vertices of CBC(p). //
26019 // //
26020 // p can not be inserted either the '-Y' option is used and the facet is on //
26021 // the hull or '-YY' option is used. //
26022 // //
26023 // p can be inserted if it is in one of the following cases (f is a subface //
26024 // of CBC(p), L = max{|p - v|, v \in V}): //
26025 // (1) if f has maximal area constraints A, and L^2 > 2 * A. //
26026 // (2) if a tet having f has max. volume constraint V, and L^3 > 6 * V. //
26027 // (3) if |p - v| > \alpha_2 H(v), for all v \in V. //
26028 // //
26029 // The purpose of using L^3 is to avoid resulting too skinny tetrahedron. //
26030 // //
26031 ///////////////////////////////////////////////////////////////////////////////
26032
26033 bool tetgenmesh::acceptfacpt(point facpt, list* subceillist, list* verlist)
26034 {
26035 triface testtet;
26036 face *testsh;
26037 point p[3];
26038 REAL L, L2, L3, lfs;
26039 int idx, i, j;
26040
26041 if (b->nobisect == 1) {
26042 // '-Y'. p can not be inserted if CBC(p) is on the hull.
26043 testsh = (face *)(* subceillist)[0];
26044 stpivot(*testsh, testtet);
26045 if (testtet.tet != dummytet) {
26046 sesymself(*testsh);
26047 stpivot(*testsh, testtet);
26048 }
26049 if (testtet.tet == dummytet) return false;
26050 } else if (b->nobisect > 1) {
26051 // '-YY'. Do not split s.
26052 return false;
26053 }
26054
26055 // Collect the vertices of CBC(p), save them in V.
26056 for (i = 0; i < subceillist->len(); i++) {
26057 testsh = (face *)(* subceillist)[i];
26058 p[0] = sorg(*testsh);
26059 p[1] = sdest(*testsh);
26060 for (j = 0; j < 2; j++) {
26061 idx = pointmark(p[j]);
26062 if (idx >= 0) {
26063 setpointmark(p[j], -idx - 1);
26064 verlist->append(&(p[j]));
26065 }
26066 }
26067 }
26068 // Uninfect collected vertices.
26069 for (i = 0; i < verlist->len(); i++) {
26070 p[0] = * (point *)(* verlist)[i];
26071 idx = pointmark(p[0]);
26072 setpointmark(p[0], -(idx + 1));
26073 }
26074
26075 if (varconstraint && in->facetconstraintlist) {
26076 for (i = 0; i < subceillist->len(); i++) {
26077 testsh = (face *)(* subceillist)[i];
26078 if (areabound(*testsh) > 0.0) {
26079 // Get the longest edge length of testsh = L.
26080 for (j = 0; j < 3; j++) p[j] = (point) testsh->sh[j + 3];
26081 L = distance(p[0], p[1]);
26082 L2 = distance(p[1], p[2]);
26083 L = (L >= L2 ? L : L2);
26084 L2 = distance(p[2], p[0]);
26085 L = (L >= L2 ? L : L2);
26086 L2 = L * L / 2.0;
26087 if (L2 > areabound(*testsh)) {
26088 return true; // case (1)
26089 }
26090 }
26091 }
26092 }
26093
26094 // Check if it is in case (2).
26095 if (b->varvolume || b->fixedvolume) {
26096 for (i = 0; i < subceillist->len(); i++) {
26097 testsh = (face *)(* subceillist)[i];
26098 // Get the longest edge length of testsh = L.
26099 for (j = 0; j < 3; j++) p[j] = (point) testsh->sh[j + 3];
26100 L = distance(p[0], p[1]);
26101 L3 = distance(p[1], p[2]);
26102 L = (L >= L3 ? L : L3);
26103 L3 = distance(p[2], p[0]);
26104 L = (L >= L3 ? L : L3);
26105 L3 = L * L * L / 6.0;
26106 if (b->fixedvolume && (L3 > b->maxvolume)) {
26107 // This face is too large wrt. the maximum volume bound. Split it.
26108 return true; // case (2)
26109 }
26110 if (b->varvolume) {
26111 for (j = 0; j < 2; j ++) {
26112 stpivot(*testsh, testtet);
26113 if (testtet.tet != dummytet) {
26114 if ((L3 > volumebound(testtet.tet)) &&
26115 (volumebound(testtet.tet) > 0.0)) {
26116 // This face is too large wrt the maximum volume bound.
26117 return true; // case (2)
26118 }
26119 }
26120 sesymself(*testsh);
26121 }
26122 }
26123 }
26124 }
26125
26126 // Check if p is inside the protect balls of vertices of V.
26127 for (i = 0; i < verlist->len(); i++) {
26128 p[0] = * (point *)(* verlist)[i];
26129 if (!b->bgmesh) {
26130 lfs = b->alpha2 * p[0][pointlfsindex];
26131 } else {
26132 lfs = b->alpha2 * p[0][3];
26133 }
26134 L = distance(p[0], facpt);
26135 if (L < lfs) break; // p is inside ball.
26136 }
26137 if (i == verlist->len()) return true; // case (3).
26138
26139 rejsubpts++;
26140 return false;
26141 }
26142
26143 ///////////////////////////////////////////////////////////////////////////////
26144 // //
26145 // acceptvolpt() Check if a volume point can be inserted or not. //
26146 // //
26147 // 'ceillist' is B(p). 'verlist' (V) is empty on input, it returns the set //
26148 // of vertices of B(p). //
26149 // //
26150 // p can be split if it is in one of the following cases: //
26151 // (1) if the t \in B(p) has maximal volume constraint V, and vol(t) < V. //
26152 // (2) if |p - v| > \alpha_2 H(v), for all v \in V. //
26153 // //
26154 ///////////////////////////////////////////////////////////////////////////////
26155
26156 bool tetgenmesh::acceptvolpt(point volpt, list* ceillist, list* verlist)
26157 {
26158 triface* testtet;
26159 point p[4];
26160 REAL L, vol, lfs;
26161 int idx, i, j;
26162
26163 // Collect the vertices of CBC(p), save them in V.
26164 for (i = 0; i < ceillist->len(); i++) {
26165 testtet = (triface *)(* ceillist)[i];
26166 p[0] = org(*testtet);
26167 p[1] = dest(*testtet);
26168 p[2] = apex(*testtet);
26169 for (j = 0; j < 3; j++) {
26170 idx = pointmark(p[j]);
26171 if (idx >= 0) {
26172 setpointmark(p[j], -idx - 1);
26173 verlist->append(&(p[j]));
26174 }
26175 }
26176 }
26177 // Uninfect collected vertices.
26178 for (i = 0; i < verlist->len(); i++) {
26179 p[0] = * (point *)(* verlist)[i];
26180 idx = pointmark(p[0]);
26181 setpointmark(p[0], -(idx + 1));
26182 }
26183
26184 if (b->varvolume || b->fixedvolume) {
26185 for (i = 0; i < ceillist->len(); i++) {
26186 testtet = (triface *)(* ceillist)[i];
26187 for (j = 0; j < 4; j++) p[j] = (point) testtet->tet[4 + j];
26188 vol = orient3d(p[0], p[1], p[2], p[3]) / 6.0;
26189 if (vol < 0) vol = -vol;
26190 if (b->fixedvolume && (vol > b->maxvolume)) {
26191 // This tet is too large wrt. the maximum volume bound. Split it.
26192 return true; // case (1)
26193 }
26194 if (b->varvolume) {
26195 if ((vol > volumebound(testtet->tet)) &&
26196 (volumebound(testtet->tet) > 0.0)) {
26197 // This tet is too large wrt the maximum volume bound.
26198 return true; // case (1)
26199 }
26200 }
26201 }
26202 }
26203
26204 // Check if p is inside the protect balls of vertices of V.
26205 for (i = 0; i < verlist->len(); i++) {
26206 p[0] = * (point *)(* verlist)[i];
26207 if (!b->bgmesh) {
26208 lfs = b->alpha2 * p[0][pointlfsindex];
26209 } else {
26210 lfs = b->alpha2 * p[0][3];
26211 }
26212 L = distance(p[0], volpt);
26213 if (L < lfs) break; // p is inside ball.
26214 }
26215 if (i == verlist->len()) return true; // case (2).
26216
26217 rejtetpts++;
26218 return false;
26219 }
26220
26221 ///////////////////////////////////////////////////////////////////////////////
26222 // //
26223 // getsplitpoint() Get the inserting point in a segment. //
26224 // //
26225 ///////////////////////////////////////////////////////////////////////////////
26226
26227 void tetgenmesh::getsplitpoint(point e1, point e2, point refpt, point newpt)
26228 {
26229 point ei, ej;
26230 REAL split, L, d1, d2, ps, rs;
26231 bool acutea, acuteb;
26232 int i;
26233
26234 if (refpt != (point) NULL) {
26235 // Use the CDT rules to split the segment.
26236 acutea = (pointtype(e1) == ACUTEVERTEX);
26237 acuteb = (pointtype(e2) == ACUTEVERTEX);
26238 if (acutea ^ acuteb) {
26239 // Only one endpoint is acute. Use rule-2 or rule-3.
26240 ei = acutea ? e1 : e2;
26241 ej = acutea ? e2 : e1;
26242 L = distance(ei, ej);
26243 // Apply rule-2.
26244 d1 = distance(ei, refpt);
26245 split = d1 / L;
26246 for (i = 0; i < 3; i++) newpt[i] = ei[i] + split * (ej[i] - ei[i]);
26247 // Check if rule-3 is needed.
26248 d2 = distance(refpt, newpt);
26249 if (d2 > (L - d1)) {
26250 // Apply rule-3.
26251 if ((d1 - d2) > (0.5 * d1)) {
26252 split = (d1 - d2) / L;
26253 } else {
26254 split = 0.5 * d1 / L;
26255 }
26256 for (i = 0; i < 3; i++) newpt[i] = ei[i] + split * (ej[i] - ei[i]);
26257 if (b->verbose > 1) {
26258 printf(" Found by rule-3:");
26259 }
26260 r3count++;
26261 } else {
26262 if (b->verbose > 1) {
26263 printf(" Found by rule-2:");
26264 }
26265 r2count++;
26266 }
26267 if (b->verbose > 1) {
26268 printf(" center %d, split = %.12g.\n", pointmark(ei), split);
26269 }
26270 // Add a random perturbation on newpt.
26271 d1 = distance(ei, newpt);
26272 d2 = distance(newpt, refpt);
26273 ps = randgenerator(d2 * b->epsilon2);
26274 rs = ps / d1;
26275 // Perturb newpt away from ei.
26276 for (i = 0; i < 3; i++) newpt[i] = ei[i] + (1.0+rs) * (newpt[i] - ei[i]);
26277 } else {
26278 // Both endpoints are acute or not. Split it at the middle.
26279 for (i = 0; i < 3; i++) newpt[i] = 0.5 * (e1[i] + e2[i]);
26280 }
26281 } else {
26282 // Split the segment at its midpoint.
26283 for (i = 0; i < 3; i++) newpt[i] = 0.5 * (e1[i] + e2[i]);
26284 }
26285 }
26286
26287 ///////////////////////////////////////////////////////////////////////////////
26288 // //
26289 // shepardinterpolation() Interpolate the local size of a newpoint. //
26290 // //
26291 // The classical Shepard interoplation (inversed weighted distance) is used. //
26292 // (With the choice p = 2). //
26293 // //
26294 // 'verlist' contains a list vertices neighboring to 'newpt'. //
26295 // //
26296 ///////////////////////////////////////////////////////////////////////////////
26297
26298 void tetgenmesh::shepardinterpolate(point newpt, list *verlist)
26299 {
26300 point neipt;
26301 REAL *weights, sumweight;
26302 REAL vec[3];
26303 int i, j;
26304
26305 weights = new REAL[verlist->len()];
26306 sumweight = 0.0;
26307
26308 // Calculate the weight of each point.
26309 for (i = 0; i < verlist->len(); i++) {
26310 neipt = * (point *)(* verlist)[i];
26311 for (j = 0; j < 3; j++) vec[j] = neipt[j] - newpt[j];
26312 weights[i] = 1.0 / dot(vec, vec);
26313 sumweight += weights[i];
26314 }
26315 // Interpolate.
26316 newpt[pointlfsindex] = 0.0;
26317 for (i = 0; i < verlist->len(); i++) {
26318 neipt = * (point *)(* verlist)[i];
26319 newpt[pointlfsindex] += (weights[i] * neipt[pointlfsindex]) / sumweight;
26320 }
26321
26322 delete [] weights;
26323 }
26324
26325 ///////////////////////////////////////////////////////////////////////////////
26326 // //
26327 // setnewpointsize() Set the size for a new point. //
26328 // //
26329 // The size of the new point p is interpolated either from a background mesh //
26330 // (b->bgmesh) or from the sizes of the adjacent vertices of p. //
26331 // //
26332 ///////////////////////////////////////////////////////////////////////////////
26333
26334 void tetgenmesh::setnewpointsize(point newpt, list* verlist)
26335 {
26336 if (b->bgmesh) {
26337 triface bgmtet;
26338 point pa;
26339 // Get a tet in background mesh for locating p.
26340 pa = * (point *)(* verlist)[0];
26341 decode(point2bgmtet(pa), bgmtet);
26342 interpolatepointsize(newpt, &bgmtet, NULL);
26343 } else {
26344 // Interpolate a local size for p using Shepard interpolation.
26345 shepardinterpolate(newpt, verlist);
26346 }
26347 }
26348
26349 ///////////////////////////////////////////////////////////////////////////////
26350 // //
26351 // splitencseg() Split an enc-seg and recover the Delaunayness by flips. //
26352 // //
26353 ///////////////////////////////////////////////////////////////////////////////
26354
26355 void tetgenmesh::splitencseg(point newpt, face* splitseg, list* tetlist,
26356 list* sublist, list* verlist, queue* flipque, bool chkencsub, bool chkbadtet)
26357 {
26358 triface starttet;
26359 face startsh, spinsh, checksh;
26360 int i;
26361
26362 // Use the base orientation (important in this routine).
26363 splitseg->shver = 0;
26364 // Insert p, this should always success.
26365 sstpivot(splitseg, &starttet);
26366 splittetedge(newpt, &starttet, flipque);
26367 if (steinerleft > 0) steinerleft--;
26368 // Remove locally non-Delaunay faces by flipping.
26369 flip(flipque, NULL);
26370
26371 // Check the two new subsegs to see if they're encroached (not by p).
26372 for (i = 0; i < 2; i++) {
26373 if (!shell2badface(*splitseg)) {
26374 checkseg4encroach(splitseg, NULL, NULL, true);
26375 if (!shell2badface(*splitseg)) {
26376 if (varconstraint && (areabound(*splitseg) > 0.0)) {
26377 checkseg4badqual(splitseg, true);
26378 }
26379 }
26380 }
26381 if (i == 1) break; // Two new segs have been checked.
26382 senextself(*splitseg);
26383 spivotself(*splitseg);
26384 #ifdef SELF_CHECK
26385 assert(splitseg->sh != (shellface *) NULL);
26386 #endif
26387 splitseg->shver = 0;
26388 }
26389 // Check the new subfaces to see if they're encroached (not by p).
26390 if (chkencsub) {
26391 spivot(*splitseg, startsh);
26392 spinsh = startsh;
26393 do {
26394 sublist->append(&spinsh);
26395 formstarpolygon(newpt, sublist, verlist);
26396 for (i = 0; i < sublist->len(); i++) {
26397 checksh = * (face *)(* sublist)[i];
26398 if (!shell2badface(checksh)) {
26399 checksub4encroach(&checksh, NULL, true);
26400 if (!shell2badface(checksh)) {
26401 if (varconstraint && (areabound(checksh) > 0.0)) {
26402 checksub4badqual(&checksh, true);
26403 }
26404 }
26405 }
26406 }
26407 sublist->clear();
26408 verlist->clear();
26409 spivotself(spinsh);
26410 } while (spinsh.sh != startsh.sh);
26411 }
26412
26413 // Collect the new tets connecting at p.
26414 sstpivot(splitseg, &starttet);
26415 tetlist->append(&starttet);
26416 formstarpolyhedron(newpt, tetlist, verlist, true);
26417
26418 // Check if p encroaches adjacent segments.
26419 tallencsegs(newpt, 1, &tetlist);
26420 if (chkencsub) {
26421 // Check if p encroaches adjacent subfaces.
26422 tallencsubs(newpt, 1, &tetlist);
26423 }
26424 if (chkbadtet) {
26425 // Check if there are new bad quality tets at p.
26426 for (i = 0; i < tetlist->len(); i++) {
26427 starttet = * (triface *)(* tetlist)[i];
26428 checktet4badqual(&starttet, true);
26429 }
26430 }
26431 tetlist->clear();
26432 }
26433
26434 ///////////////////////////////////////////////////////////////////////////////
26435 // //
26436 // tallencsegs() Check for encroached segments and save them in list. //
26437 // //
26438 // If 'testpt' (p) != NULL, only check if segments are encroached by p, else,//
26439 // check all the nearby mesh vertices. //
26440 // //
26441 // If 'ceillists' (B_i(p)) != NULL, there are 'n' B_i(p)s, only check the //
26442 // segments which are on B_i(p)s, else, check the entire list of segments //
26443 // (in the pool 'this->subsegs'). //
26444 // //
26445 ///////////////////////////////////////////////////////////////////////////////
26446
26447 bool tetgenmesh::tallencsegs(point testpt, int n, list **ceillists)
26448 {
26449 list *ceillist;
26450 triface ceiltet;
26451 face checkseg;
26452 long oldencnum;
26453 int i, j, k;
26454
26455 // Remember the current number of encroached segments.
26456 oldencnum = badsubsegs->items;
26457
26458 if (ceillists != (list **) NULL) {
26459 for (k = 0; k < n; k++) {
26460 ceillist = ceillists[k];
26461 // Check the segments on B_i(p).
26462 for (i = 0; i < ceillist->len(); i++) {
26463 ceiltet = * (triface *)(* ceillist)[i];
26464 ceiltet.ver = 0;
26465 for (j = 0; j < 3; j++) {
26466 tsspivot(&ceiltet, &checkseg);
26467 if (checkseg.sh != dummysh) {
26468 // Found a segment. Test it if it isn't in enc-list.
26469 if (!shell2badface(checkseg)) {
26470 checkseg4encroach(&checkseg, testpt, NULL, true);
26471 if (!shell2badface(checkseg)) {
26472 if (varconstraint && (areabound(checkseg) > 0.0)) {
26473 checkseg4badqual(&checkseg, true);
26474 }
26475 }
26476 }
26477 }
26478 enextself(ceiltet);
26479 }
26480 }
26481 }
26482 } else {
26483 // Check the entire list of segments.
26484 subsegs->traversalinit();
26485 checkseg.sh = shellfacetraverse(subsegs);
26486 while (checkseg.sh != (shellface *) NULL) {
26487 // Test it if it isn't in enc-list.
26488 if (!shell2badface(checkseg)) {
26489 checkseg4encroach(&checkseg, testpt, NULL, true);
26490 if (!shell2badface(checkseg)) {
26491 if (varconstraint && (areabound(checkseg) > 0.0)) {
26492 checkseg4badqual(&checkseg, true);
26493 }
26494 }
26495 }
26496 checkseg.sh = shellfacetraverse(subsegs);
26497 }
26498 }
26499
26500 return (badsubsegs->items > oldencnum);
26501 }
26502
26503 ///////////////////////////////////////////////////////////////////////////////
26504 // //
26505 // tallencsubs() Find all encroached subfaces and save them in list. //
26506 // //
26507 // If 'testpt' (p) != NULL, only check if subfaces are encroached by p, else,//
26508 // check the adjacent vertices of subfaces. //
26509 // //
26510 // If 'ceillists' (B_i(p)) != NULL, there are 'n' B_i(p)s, only check the //
26511 // subfaces which are on B_i(p)s, else, check the entire list of subfaces //
26512 // (in the pool 'this->subfaces'). //
26513 // //
26514 ///////////////////////////////////////////////////////////////////////////////
26515
26516 bool tetgenmesh::tallencsubs(point testpt, int n, list** ceillists)
26517 {
26518 list *ceillist;
26519 triface ceiltet;
26520 face checksh;
26521 long oldencnum;
26522 int i, k;
26523
26524 // Remember the current number of encroached segments.
26525 oldencnum = badsubfaces->items;
26526
26527 if (ceillists != (list **) NULL) {
26528 for (k = 0; k < n; k++) {
26529 ceillist = ceillists[k];
26530 // Check the subfaces on B_i(p).
26531 for (i = 0; i < ceillist->len(); i++) {
26532 ceiltet = * (triface *)(* ceillist)[i];
26533 tspivot(ceiltet, checksh);
26534 if (checksh.sh != dummysh) {
26535 // Found a subface. Test it if it isn't in enc-list.
26536 if (!shell2badface(checksh)) {
26537 checksub4encroach(&checksh, testpt, true);
26538 if (!shell2badface(checksh)) {
26539 if (varconstraint && (areabound(checksh) > 0.0)) {
26540 checksub4badqual(&checksh, true);
26541 }
26542 }
26543 }
26544 }
26545 }
26546 }
26547 } else {
26548 // Check the entire list of subfaces.
26549 subfaces->traversalinit();
26550 checksh.sh = shellfacetraverse(subfaces);
26551 while (checksh.sh != (shellface *) NULL) {
26552 // Test it if it isn't in enc-list.
26553 if (!shell2badface(checksh)) {
26554 checksub4encroach(&checksh, testpt, true);
26555 if (!shell2badface(checksh)) {
26556 if (varconstraint && (areabound(checksh) > 0.0)) {
26557 checksub4badqual(&checksh, true);
26558 }
26559 }
26560 }
26561 checksh.sh = shellfacetraverse(subfaces);
26562 }
26563 }
26564
26565 return (badsubfaces->items > oldencnum);
26566 }
26567
26568 ///////////////////////////////////////////////////////////////////////////////
26569 // //
26570 // tallbadtetrahedrons() Queue all the bad-quality tetrahedra in the mesh.//
26571 // //
26572 ///////////////////////////////////////////////////////////////////////////////
26573
26574 void tetgenmesh::tallbadtetrahedrons()
26575 {
26576 triface tetloop;
26577
26578 tetrahedrons->traversalinit();
26579 tetloop.tet = tetrahedrontraverse();
26580 while (tetloop.tet != (tetrahedron *) NULL) {
26581 checktet4badqual(&tetloop, true);
26582 tetloop.tet = tetrahedrontraverse();
26583 }
26584 }
26585
26586 ///////////////////////////////////////////////////////////////////////////////
26587 // //
26588 // repairencsegs() Repair (split) all the encroached segments. //
26589 // //
26590 // Each encroached segment is repaired by splitting it - inserting a vertex //
26591 // at or near its midpoint. Newly inserted vertices may encroach upon other //
26592 // subsegments, these are also repaired. //
26593 // //
26594 // 'chkencsub' and 'chkbadtet' are two flags that specify whether one should //
26595 // take note of new encroaced subfaces and bad quality tets that result from //
26596 // inserting vertices to repair encroached subsegments. //
26597 // //
26598 ///////////////////////////////////////////////////////////////////////////////
26599
26600 void tetgenmesh::repairencsegs(bool chkencsub, bool chkbadtet)
26601 {
26602 list **tetlists, **ceillists;
26603 list **sublists, **subceillists;
26604 list *tetlist, *sublist, *verlist;
26605 queue *flipque;
26606 badface *encloop;
26607 face splitseg, symsplitseg;
26608 point newpt, sympt, refpt;
26609 enum locateresult symloc;
26610 int nmax, n, i, j;
26611
26612 n = 0;
26613 nmax = 128;
26614 tetlist = (list *) NULL;
26615 flipque = (queue *) NULL;
26616 if (!b->fliprepair) {
26617 tetlists = new list*[nmax];
26618 ceillists = new list*[nmax];
26619 sublists = new list*[nmax];
26620 subceillists = new list*[nmax];
26621 } else {
26622 tetlist = new list(sizeof(triface), NULL, 1024);
26623 sublist = new list(sizeof(face), NULL, 256);
26624 }
26625 verlist = new list(sizeof(point *), NULL, 256);
26626 if (b->fliprepair) {
26627 flipque = new queue(sizeof(badface));
26628 }
26629
26630 // Loop until the pool 'badsubsegs' is empty. Note that steinerleft == -1
26631 // if an unlimited number of Steiner points is allowed.
26632 while ((badsubsegs->items > 0) && (steinerleft != 0)) {
26633 badsubsegs->traversalinit();
26634 encloop = badfacetraverse(badsubsegs);
26635 while ((encloop != (badface *) NULL) && (steinerleft != 0)) {
26636 // Get an encroached subsegment s.
26637 splitseg = encloop->ss;
26638 // Clear the in-queue flag in s.
26639 setshell2badface(splitseg, NULL);
26640 if ((sorg(splitseg) == encloop->forg) &&
26641 (sdest(splitseg) == encloop->fdest)) {
26642 if (b->verbose > 1) {
26643 printf(" Get an enc-seg (%d, %d)\n", pointmark(encloop->forg),
26644 pointmark(encloop->fdest));
26645 }
26646 refpt = (point) NULL;
26647 if (b->conformdel) {
26648 // Look for a reference point.
26649 checkseg4encroach(&splitseg, NULL, &refpt, false);
26650 }
26651 // Create the new point p (at the middle of s).
26652 makepoint(&newpt);
26653 // for (i = 0; i < 3; i++) {
26654 // newpt[i] = 0.5 * (encloop->forg[i] + encloop->fdest[i]);
26655 // }
26656 getsplitpoint(encloop->forg, encloop->fdest, refpt, newpt);
26657 setpointtype(newpt, FREESEGVERTEX);
26658 setpoint2sh(newpt, sencode(splitseg));
26659 // Decide whether p can be inserted or not.
26660 if (acceptsegpt(newpt, refpt, &splitseg)) {
26661 // Is there periodic boundary condition?
26662 if (checkpbcs) {
26663 // Insert points on other segments of incident pbcgroups.
26664 i = shellmark(splitseg) - 1;
26665 for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++) {
26666 makepoint(&sympt);
26667 symloc = getsegpbcsympoint(newpt, &splitseg, sympt, &symsplitseg,
26668 segpglist[j]);
26669 if (symloc == ONEDGE) {
26670 if (symsplitseg.sh != splitseg.sh) {
26671 // Insert sympt.
26672 setpointtype(sympt, FREESEGVERTEX);
26673 setpoint2sh(sympt, sencode(symsplitseg));
26674 if (!b->fliprepair) {
26675 // Form BC(symp), B(symp), CBC(symp)s, C(symp)s.
26676 formbowatcavity(sympt, &symsplitseg, NULL, &n, &nmax,
26677 sublists, subceillists, tetlists, ceillists);
26678 // Validate BC(symp), B(symp), CBC(symp)s, C(symp)s.
26679 if (trimbowatcavity(sympt, &symsplitseg, n, sublists,
26680 subceillists, tetlists, ceillists, -1.0)) {
26681 bowatinsertsite(sympt, &symsplitseg, n, sublists,
26682 subceillists, tetlists, ceillists, verlist, flipque,
26683 true, chkencsub, chkbadtet);
26684 setnewpointsize(sympt, verlist);
26685 if (steinerleft > 0) steinerleft--;
26686 } else {
26687 // p did not insert for invalid BC(symp).
26688 pointdealloc(sympt);
26689 }
26690 // Free the memory allocated in formbowatcavity().
26691 releasebowatcavity(&symsplitseg, n, sublists, subceillists,
26692 tetlists, ceillists);
26693 } else {
26694 splitencseg(sympt, &symsplitseg, tetlist, sublist, verlist,
26695 flipque, chkencsub, chkbadtet);
26696 setnewpointsize(sympt, verlist);
26697 if (steinerleft > 0) steinerleft--;
26698 }
26699 verlist->clear();
26700 } else {
26701 // The sympt are on the same segment. It is possible when
26702 // splitseg is the symmetric rotating axes.
26703 pointdealloc(sympt);
26704 }
26705 } else if (symloc == ONVERTEX) {
26706 // The sympt already exists. It is possible when two pbc
26707 // groups are exactly the same. Omit this point.
26708 pointdealloc(sympt);
26709 } else {
26710 // Do not isnert symp for unknown cases: ONFACE, OUTSIDE.
26711 // assert(0);
26712 pointdealloc(sympt);
26713 }
26714 } // for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++)
26715 } // if (checkpbcs)
26716 if (!b->fliprepair) {
26717 // Form BC(p), B(p), CBC(p)s, and C(p)s.
26718 formbowatcavity(newpt, &splitseg, NULL, &n, &nmax, sublists,
26719 subceillists, tetlists, ceillists);
26720 // Validate/update BC(p), B(p), CBC(p)s, and C(p)s.
26721 if (trimbowatcavity(newpt, &splitseg, n, sublists, subceillists,
26722 tetlists, ceillists, -1.0)) {
26723 bowatinsertsite(newpt, &splitseg, n, sublists, subceillists,
26724 tetlists, ceillists, verlist, flipque, true,
26725 chkencsub, chkbadtet);
26726 setnewpointsize(newpt, verlist);
26727 if (steinerleft > 0) steinerleft--;
26728 } else {
26729 // p did not insert for invalid B(p).
26730 pointdealloc(newpt);
26731 }
26732 // Free the memory allocated in formbowatcavity().
26733 releasebowatcavity(&splitseg, n, sublists, subceillists, tetlists,
26734 ceillists);
26735 } else {
26736 splitencseg(newpt, &splitseg, tetlist, sublist, verlist, flipque,
26737 chkencsub, chkbadtet);
26738 setnewpointsize(newpt, verlist);
26739 if (steinerleft > 0) steinerleft--;
26740 }
26741 verlist->clear();
26742 } else {
26743 // p did not accept for insertion.
26744 pointdealloc(newpt);
26745 } // if (checkseg4splitting(newpt, &splitseg))
26746 } // if ((encloop->forg == pa) && (encloop->fdest == pb))
26747 badfacedealloc(badsubsegs, encloop); // Remove this entry from list.
26748 encloop = badfacetraverse(badsubsegs); // Get the next enc-segment.
26749 } // while ((encloop != (badface *) NULL) && (steinerleft != 0))
26750 } // while ((badsubsegs->items > 0) && (steinerleft != 0))
26751
26752 if (!b->fliprepair) {
26753 delete [] tetlists;
26754 delete [] ceillists;
26755 delete [] sublists;
26756 delete [] subceillists;
26757 } else {
26758 delete tetlist;
26759 delete sublist;
26760 }
26761 delete verlist;
26762 if (b->fliprepair) {
26763 delete flipque;
26764 }
26765 }
26766
26767 ///////////////////////////////////////////////////////////////////////////////
26768 // //
26769 // repairencsubs() Repair (split) all the encroached subfaces. //
26770 // //
26771 // Each encroached subface is repaired by splitting it - inserting a vertex //
26772 // at or near its circumcenter. Newly inserted vertices may encroach upon //
26773 // other subfaces, these are also repaired. //
26774 // //
26775 // 'chkbadtet' is a flag that specifies whether one should take note of new //
26776 // bad quality tets that result from inserted vertices. //
26777 // //
26778 ///////////////////////////////////////////////////////////////////////////////
26779
26780 void tetgenmesh::repairencsubs(bool chkbadtet)
26781 {
26782 list *tetlists[2], *ceillists[2];
26783 list *sublist, *subceillist;
26784 list *verlist;
26785 badface *encloop;
26786 face splitsub, symsplitsub;
26787 point newpt, sympt;
26788 enum locateresult loc, symloc;
26789 bool reject;
26790 long oldptnum;
26791 int quenumber, n, i;
26792
26793 n = 0;
26794 sublist = (list *) NULL;
26795 subceillist = (list *) NULL;
26796 verlist = new list(sizeof(point *), NULL, 256);
26797
26798 // Loop until the pool 'badsubfaces' is empty. Note that steinerleft == -1
26799 // if an unlimited number of Steiner points is allowed.
26800 while ((badsubfaces->items > 0) && (steinerleft != 0)) {
26801 // Get an encroached subface f.
26802 encloop = dequeueencsub(&quenumber);
26803 splitsub = encloop->ss;
26804 // Clear the in-queue flag of f.
26805 setshell2badface(splitsub, NULL);
26806 // f may not be the same one when it was determined to be encroached.
26807 if (!isdead(&splitsub) && (sorg(splitsub) == encloop->forg) &&
26808 (sdest(splitsub) == encloop->fdest) &&
26809 (sapex(splitsub) == encloop->fapex)) {
26810 if (b->verbose > 1) {
26811 printf(" Dequeuing ensub (%d, %d, %d) [%d].\n",
26812 pointmark(encloop->forg), pointmark(encloop->fdest),
26813 pointmark(encloop->fapex), quenumber);
26814 }
26815 // Create a new point p.
26816 makepoint(&newpt);
26817 // If f was added by checksub4badqual(), calculate its circumcenter.
26818 if (quenumber == 2) {
26819 circumsphere(encloop->forg, encloop->fdest, encloop->fapex, NULL,
26820 encloop->cent, NULL);
26821 }
26822 for (i = 0; i < 3; i++) newpt[i] = encloop->cent[i];
26823 setpointtype(newpt, FREESUBVERTEX);
26824 setpoint2sh(newpt, sencode(splitsub));
26825 // Set the abovepoint of f for point location.
26826 abovepoint = facetabovepointarray[shellmark(splitsub)];
26827 if (abovepoint == (point) NULL) {
26828 getfacetabovepoint(&splitsub);
26829 }
26830 // Locate p, start from f, stop at segment (1), use a tolerance to
26831 // detect ONVERTEX or OUTSIDE case. Update f on return.
26832 loc = locatesub(newpt, &splitsub, 1, b->epsilon * 1e+2);
26833 if ((loc != ONVERTEX) && (loc != OUTSIDE)) {
26834 // Form BC(p), B(p), CBC(p) and C(p).
26835 formbowatcavity(newpt, NULL, &splitsub, &n, NULL, &sublist,
26836 &subceillist, tetlists, ceillists);
26837 // Check for encroaching subsegments (on B(p)).
26838 reject = tallencsegs(newpt, 2, ceillists);
26839 if (!reject) {
26840 // Decide whether f is allowed to be split or not?
26841 reject = !acceptfacpt(newpt, subceillist, verlist);
26842 verlist->clear();
26843 }
26844 if (!reject) {
26845 // Validate/update cavity.
26846 reject = !trimbowatcavity(newpt, NULL, n, &sublist, &subceillist,
26847 tetlists, ceillists, -1.0);
26848 }
26849 if (!reject) {
26850 // CBC(p) should include s, so that s can be removed after CBC(p)
26851 // is remeshed. However, if there are locally non-Delaunay faces
26852 // and encroached subsegments, s may not be collected in CBC(p).
26853 // p should not be inserted in such case.
26854 reject = !sinfected(encloop->ss);
26855 }
26856 if (!reject) {
26857 if (checkpbcs) {
26858 if (shellpbcgroup(splitsub) >= 0) {
26859 // Check for splitting of the symmetric subface of f.
26860 makepoint(&sympt);
26861 symloc = getsubpbcsympoint(newpt,&splitsub,sympt,&symsplitsub);
26862 if (symloc != ONVERTEX) {
26863 // Release CBC(p) and BC(p) and free the memory..
26864 releasebowatcavity(NULL, 2, &sublist, &subceillist, tetlists,
26865 ceillists);
26866 // Form CBC(symp), C(symp), BC(sympt) and B(sympt).
26867 formbowatcavity(sympt, NULL, &symsplitsub, &n, NULL, &sublist,
26868 &subceillist, tetlists, ceillists);
26869 reject = tallencsegs(sympt, 2, ceillists);
26870 if (!reject) {
26871 reject = !acceptfacpt(sympt, subceillist, verlist);
26872 verlist->clear();
26873 }
26874 if (!reject) {
26875 reject = !trimbowatcavity(sympt,NULL,n,&sublist,&subceillist,
26876 tetlists, ceillists, -1.0);
26877 }
26878 if (!reject) {
26879 // Insert sympt.
26880 setpoint2pbcpt(newpt, sympt);
26881 setpoint2pbcpt(sympt, newpt);
26882 setpointtype(sympt, FREESUBVERTEX);
26883 setpoint2sh(sympt, sencode(symsplitsub));
26884 bowatinsertsite(sympt, NULL, n, &sublist, &subceillist,
26885 tetlists,ceillists,verlist,NULL,false,true,chkbadtet);
26886 setnewpointsize(sympt, verlist);
26887 verlist->clear();
26888 if (steinerleft > 0) steinerleft--;
26889 } else {
26890 // symp is rejected for one of the following reasons:
26891 // (1) BC(symp) is not valid; or
26892 // (2) symp encroaches upon some subsegments (queued); or
26893 // (3) symp is rejected by point accepting rule.
26894 pointdealloc(sympt);
26895 }
26896 // Release CBC(symp) and BC(symp) and free the memory..
26897 releasebowatcavity(NULL, n, &sublist, &subceillist, tetlists,
26898 ceillists);
26899 } else {
26900 // Do not insert sympt for invalid PBC data.
26901 pointdealloc(sympt);
26902 // p is rejected due to symp.
26903 reject = true;
26904 }
26905 }
26906 } // if (checkpbcs)
26907 }
26908 if (!reject) {
26909 // Insert p.
26910 if (checkpbcs) {
26911 if (shellpbcgroup(splitsub) >= 0) {
26912 // Form CBC(p), C(p), BC(p) and B(p).
26913 formbowatcavity(newpt, NULL, &splitsub, &n, NULL, &sublist,
26914 &subceillist, tetlists, ceillists);
26915 trimbowatcavity(newpt, NULL, n, &sublist, &subceillist, tetlists,
26916 ceillists, -1.0);
26917 }
26918 }
26919 bowatinsertsite(newpt, NULL, n, &sublist, &subceillist, tetlists,
26920 ceillists, verlist, NULL, true, true, chkbadtet);
26921 setnewpointsize(newpt, verlist);
26922 verlist->clear();
26923 if (steinerleft > 0) steinerleft--;
26924 } else {
26925 // p is rejected for the one of the following reasons:
26926 // (1) BC(p) is not valid.
26927 // (2) s does not in CBC(p).
26928 // (3) p encroaches upon some segments (queued); or
26929 // (4) p is rejected by point accepting rule, or
26930 // (5) due to the rejection of symp (the PBC).
26931 pointdealloc(newpt);
26932 } // if (!reject)
26933 // Release the cavity and free the memory.
26934 releasebowatcavity(NULL, n, &sublist, &subceillist, tetlists,
26935 ceillists);
26936 if (reject) {
26937 // Are there queued encroached subsegments.
26938 if (badsubsegs->items > 0) {
26939 // Repair enc-subsegments.
26940 oldptnum = points->items;
26941 repairencsegs(true, chkbadtet);
26942 if (points->items > oldptnum) {
26943 // Some enc-subsegments got split. Try to repair f later.
26944 splitsub = encloop->ss;
26945 if (!isdead(&splitsub)) {
26946 if (!shell2badface(splitsub)) {
26947 checksub4encroach(&splitsub, NULL, true);
26948 if (!shell2badface(splitsub)) {
26949 if (varconstraint && (areabound(splitsub) > 0.0)) {
26950 checksub4badqual(&splitsub, true);
26951 }
26952 }
26953 }
26954 }
26955 }
26956 }
26957 }
26958 } else {
26959 // Don't insert p for one of the following reasons:
26960 // (1) Locate on an existing vertex; or
26961 // (2) locate outside the domain.
26962 // Case (1) should not be possible. If such vertex v exists, it is
26963 // the circumcenter of f, ie., f is non-Delaunay. Either f was got
26964 // split before by v, but survived after v was inserted, or the
26965 // same for a f' which is nearly co-circular with f. Whatsoever,
26966 // there are encroached segs by v, but the routine tallencsegs()
26967 // did not find them out.
26968 if (loc == ONVERTEX) {
26969 printf("Internal error in repairencsubs():\n");
26970 printf(" During repairing encroached subface (%d, %d, %d)\n",
26971 pointmark(encloop->forg), pointmark(encloop->fdest),
26972 pointmark(encloop->fapex));
26973 printf(" New point %d is coincident with an existing vertex %d\n",
26974 pointmark(newpt), pointmark(sorg(splitsub)));
26975 internalerror();
26976 }
26977 // Case (2) can happen when thers is a segment s which is close to f
26978 // and is non-conforming Delaunay. The circumcenter of f encroaches
26979 // upon s, but the circumcenter of s is rejected for insertion.
26980 pointdealloc(newpt);
26981 } // if ((loc != ONVERTEX) && (loc != OUTSIDE))
26982 } else {
26983 if (!isdead(&splitsub)) {
26984 // The subface has been changed, re-check it.
26985 checksub4encroach(&splitsub, NULL, true);
26986 if (!shell2badface(splitsub)) {
26987 if (varconstraint && (areabound(splitsub) > 0.0)) {
26988 checksub4badqual(&splitsub, true);
26989 }
26990 }
26991 }
26992 } // if (!isdead(&splitsub) && (sorg(splitsub) == encloop->forg) &&
26993 // Remove this entry from list.
26994 badfacedealloc(badsubfaces, encloop);
26995 } // while ((badsubfaces->items > 0) && (steinerleft != 0))
26996
26997 delete verlist;
26998 }
26999
27000 ///////////////////////////////////////////////////////////////////////////////
27001 // //
27002 // repairbadtets() Repair all bad-quality tetrahedra. //
27003 // //
27004 // All bad-quality tets are stored in pool 'badtetrahedrons'. Each bad tet //
27005 // is repaired by inserting a point at or near its circumcenter. However, if //
27006 // this point encroaches any subsegment or subface, it is not inserted. Ins- //
27007 // tead the encroached segment and subface are split. Newly inserted points //
27008 // may create other bad-quality tets, these are also repaired. //
27009 // //
27010 ///////////////////////////////////////////////////////////////////////////////
27011
27012 void tetgenmesh::repairbadtets()
27013 {
27014 list *tetlist, *ceillist;
27015 list *verlist;
27016 badface *badtet;
27017 triface starttet;
27018 point newpt;
27019 enum locateresult loc;
27020 bool reject;
27021 long oldptnum;
27022 int i;
27023
27024 tetlist = new list(sizeof(triface), NULL, 1024);
27025 ceillist = new list(sizeof(triface), NULL, 1024);
27026 verlist = new list(sizeof(point *), NULL, 256);
27027
27028 // Loop until pool 'badtetrahedrons' is empty. Note that steinerleft == -1
27029 // if an unlimited number of Steiner points is allowed.
27030 while ((badtetrahedrons->items > 0) && (steinerleft != 0)) {
27031 // Get a bad-quality tet t.
27032 badtet = dequeuebadtet();
27033 // Make sure that the tet is still the same one when it was tested.
27034 // Subsequent transformations may have made it a different tet.
27035 if (!isdead(&badtet->tt) && org(badtet->tt) == badtet->forg &&
27036 dest(badtet->tt) == badtet->fdest &&
27037 apex(badtet->tt) == badtet->fapex &&
27038 oppo(badtet->tt) == badtet->foppo) {
27039 // Create the new point p.
27040 makepoint(&newpt);
27041 for (i = 0; i < 3; i++) newpt[i] = badtet->cent[i];
27042 setpointtype(newpt, FREEVOLVERTEX);
27043 // Locate p.
27044 starttet = badtet->tt;
27045 loc = preciselocate(newpt, &starttet, tetrahedrons->items);
27046 if ((loc != ONVERTEX) && (loc != OUTSIDE)) {
27047 // For BC(p) and B(p).
27048 infect(starttet);
27049 tetlist->append(&starttet);
27050 formbowatcavityquad(newpt, tetlist, ceillist);
27051 // Check for encroached subsegments.
27052 reject = tallencsegs(newpt, 1, &ceillist);
27053 if (!reject) {
27054 // Check for encroached subfaces.
27055 reject = tallencsubs(newpt, 1, &ceillist);
27056 }
27057 if (!reject) {
27058 // Does p allowed to be inseted?
27059 reject = !acceptvolpt(newpt, ceillist, verlist);
27060 }
27061 if (!reject) {
27062 reject = !trimbowatcavity(newpt, NULL, 1, NULL, NULL, &tetlist,
27063 &ceillist, -1.0);
27064 }
27065 if (!reject) {
27066 // BC(p) should include t, so that t can be removed after BC(p) is
27067 // remeshed. However, if there are locally non-Delaunay faces
27068 // and encroached subsegments/subfaces, t may not be collected
27069 // in BC(p). p should not be inserted in such case.
27070 reject = !infected(badtet->tt);
27071 if (reject) outbowatcircumcount++;
27072 }
27073 if (!reject) {
27074 // Insert p.
27075 bowatinsertsite(newpt, NULL, 1, NULL, NULL, &tetlist, &ceillist,
27076 NULL, NULL, false, false, true);
27077 setnewpointsize(newpt, verlist);
27078 if (steinerleft > 0) steinerleft--;
27079 } else {
27080 // p is rejected for one of the following reasons:
27081 // (1) BC(p) is not valid.
27082 // (2) t does not in BC(p).
27083 // (3) p encroaches upon some segments;
27084 // (4) p encroaches upon some subfaces;
27085 // (5) p is rejected by the point accepting rule.
27086 pointdealloc(newpt);
27087 // Uninfect tets of BC(p).
27088 for (i = 0; i < tetlist->len(); i++) {
27089 starttet = * (triface *)(* tetlist)[i];
27090 uninfect(starttet);
27091 }
27092 }
27093 tetlist->clear();
27094 ceillist->clear();
27095 verlist->clear();
27096 // Split encroached subsegments/subfaces if there are.
27097 if (reject) {
27098 oldptnum = points->items;
27099 if (badsubsegs->items > 0) {
27100 repairencsegs(true, true);
27101 }
27102 if (badsubfaces->items > 0) {
27103 repairencsubs(true);
27104 }
27105 if (points->items > oldptnum) {
27106 // Some encroaching subsegments/subfaces have been split.
27107 starttet = badtet->tt;
27108 if (!isdead(&starttet)) {
27109 checktet4badqual(&starttet, true);
27110 }
27111 }
27112 }
27113 } else {
27114 // Do not insert p. The reason may be one of:
27115 // (1) p is coincident (ONVERTEX) with an existing vertex; or
27116 // (2) p is outside (OUTSIDE) the mesh.
27117 // Case (1) should not be possible. If such vertex v exists, it is
27118 // the circumcenter of t, ie., t is non-Delaunay. Either t was got
27119 // split before by v, but survived after v was inserted, or the
27120 // same for a t' which is nearly co-spherical with t. Whatsoever,
27121 // there are encroached segments or subfaces by v but the routines
27122 // tallencsegs() or tallencsubs() did not find them out.
27123 if (loc == ONVERTEX) {
27124 printf("Internal error in repairbadtets():\n");
27125 printf(" During repairing bad tet (%d, %d, %d, %d)\n",
27126 pointmark(badtet->forg), pointmark(badtet->fdest),
27127 pointmark(badtet->fapex), pointmark(badtet->foppo));
27128 printf(" New point %d is coincident with an existing vertex %d\n",
27129 pointmark(newpt), pointmark(org(starttet)));
27130 internalerror();
27131 }
27132 // Case (2) can happen when there is a segment s (or subface f) which
27133 // is close to f and is non-conforming Delaunay. The circumcenter
27134 // of t encroaches upon s (or f), but the circumcenter of s (or f)
27135 // is rejected for insertion.
27136 pointdealloc(newpt);
27137 } // if ((loc != ONVERTEX) && (loc != OUTSIDE))
27138 } // if (!isdead(&badtet->tt) && org(badtet->tt) == badtet->forg &&
27139 // Remove the tet from the pool.
27140 badfacedealloc(badtetrahedrons, badtet);
27141 } // while ((badtetrahedrons->items > 0) && (steinerleft != 0))
27142
27143 delete tetlist;
27144 delete ceillist;
27145 delete verlist;
27146 }
27147
27148 ///////////////////////////////////////////////////////////////////////////////
27149 // //
27150 // enforcequality() Refine the mesh. //
27151 // //
27152 ///////////////////////////////////////////////////////////////////////////////
27153
27154 void tetgenmesh::enforcequality()
27155 {
27156 long total, vertcount;
27157 int i;
27158
27159 if (!b->quiet) {
27160 printf("Adding Steiner points to enforce quality.\n");
27161 }
27162
27163 total = vertcount = 0l;
27164 if (b->conformdel) {
27165 r2count = r3count = 0l;
27166 }
27167
27168 if (b->refine) {
27169 // Mark segment vertices (acute or not).
27170 markacutevertices(89.0);
27171 }
27172 if (!b->bgmesh) {
27173 // Calculate the node local feature sizes.
27174 calclocalfeaturesizes();
27175 }
27176 // Mark sharp subfaces (for termination).
27177 marksharpsubsegs(89.0);
27178 // Mark skinny subfaces (for reducing Steiner points).
27179 markskinnysubfaces(19.0);
27180
27181 // Initialize the pool of encroached subsegments.
27182 badsubsegs = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
27183 // Looking for encroached subsegments.
27184 tallencsegs(NULL, 0, NULL);
27185 if (b->verbose && badsubsegs->items > 0) {
27186 printf(" Splitting encroached subsegments.\n");
27187 }
27188 vertcount = points->items;
27189 // Fix encroached segments without noting any enc subfaces.
27190 repairencsegs(false, false);
27191 if (b->verbose > 0) {
27192 printf(" %ld split points.\n", points->items - vertcount);
27193 }
27194 total += points->items - vertcount;
27195
27196 // Initialize the pool of encroached subfaces.
27197 badsubfaces = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
27198 // Initialize the priority queues of badfaces.
27199 for (i = 0; i < 3; i++) subquefront[i] = (badface *) NULL;
27200 for (i = 0; i < 3; i++) subquetail[i] = &subquefront[i];
27201 // Looking for encroached subfaces.
27202 tallencsubs(NULL, 0, NULL);
27203 if (b->verbose && badsubfaces->items > 0) {
27204 printf(" Splitting encroached subfaces.\n");
27205 }
27206 vertcount = points->items;
27207 // Fix encroached subfaces without noting bad tetrahedra.
27208 repairencsubs(false);
27209 if (b->verbose > 0) {
27210 printf(" %ld split points.\n", points->items - vertcount);
27211 }
27212 total += points->items - vertcount;
27213 // At this point, the mesh should be conforming Delaunay if no input
27214 // angle is smaller than 90 degree.
27215
27216 // Next, fix bad quality tetrahedra.
27217 if ((b->minratio > 0.0) || b->varvolume || b->fixedvolume) {
27218 // Initialize the pool of bad tets
27219 badtetrahedrons = new memorypool(sizeof(badface), ELEPERBLOCK, POINTER, 0);
27220 // Initialize the priority queues of bad tets.
27221 for (i = 0; i < 64; i++) tetquefront[i] = (badface *) NULL;
27222 for (i = 0; i < 64; i++) tetquetail[i] = &tetquefront[i];
27223 // Looking for bad quality tets.
27224 tallbadtetrahedrons();
27225 if (b->verbose && badtetrahedrons->items > 0) {
27226 printf(" Splitting bad tetrahedra.\n");
27227 }
27228 vertcount = points->items;
27229 repairbadtets();
27230 if (b->verbose > 0) {
27231 printf(" %ld refinement points.\n", points->items - vertcount);
27232 }
27233 total += points->items - vertcount;
27234 delete badtetrahedrons;
27235 }
27236
27237 if (b->verbose > 0) {
27238 printf(" Totally added %ld points.\n", total);
27239 }
27240
27241 delete badsubfaces;
27242 delete badsubsegs;
27243 }
27244
27245 //
27246 // End of Delaunay refinement routines
27247 //
27248
27249 //
27250 // Begin of mesh smoothing routines
27251 //
27252
27253 ///////////////////////////////////////////////////////////////////////////////
27254 // //
27255 // checktet4ill() Check a tet to see if it is illegal. //
27256 // //
27257 // A tet is "illegal" if it spans on one input facet. Save the tet in queue //
27258 // if it is illegal and the flag 'enqflag' is set. //
27259 // //
27260 // Note: Such case can happen when the input facet has non-coplanar vertices //
27261 // and the Delaunay tetrahedralization of the vertices may creat such tets. //
27262 // //
27263 ///////////////////////////////////////////////////////////////////////////////
27264
27265 bool tetgenmesh::checktet4ill(triface* testtet, bool enqflag)
27266 {
27267 badface *newbadtet;
27268 triface checktet;
27269 face checksh1, checksh2;
27270 face checkseg;
27271 bool illflag;
27272 int i;
27273
27274 illflag = false;
27275 for (testtet->loc = 0; testtet->loc < 4; testtet->loc++) {
27276 tspivot(*testtet, checksh1);
27277 if (checksh1.sh != dummysh) {
27278 testtet->ver = 0;
27279 findedge(&checksh1, org(*testtet), dest(*testtet));
27280 for (i = 0; i < 3; i++) {
27281 fnext(*testtet, checktet);
27282 tspivot(checktet, checksh2);
27283 if (checksh2.sh != dummysh) {
27284 // Two subfaces share this edge. It should be a segment.
27285 sspivot(checksh1, checkseg);
27286 if (checkseg.sh == dummysh) {
27287 illflag = true; break;
27288 }
27289 }
27290 enextself(*testtet);
27291 senextself(checksh1);
27292 }
27293 }
27294 if (illflag) break;
27295 }
27296
27297 if (illflag && enqflag) {
27298 // Allocate space for the bad tetrahedron.
27299 newbadtet = (badface *) badtetrahedrons->alloc();
27300 newbadtet->tt = *testtet;
27301 newbadtet->key = 0.0;
27302 for (i = 0; i < 3; i++) newbadtet->cent[i] = 0.0;
27303 newbadtet->forg = org(*testtet);
27304 newbadtet->fdest = dest(*testtet);
27305 newbadtet->fapex = apex(*testtet);
27306 newbadtet->foppo = oppo(*testtet);
27307 newbadtet->nextitem = (badface *) NULL;
27308 if (b->verbose > 2) {
27309 printf(" Queueing illtet: (%d, %d, %d, %d).\n",
27310 pointmark(newbadtet->forg), pointmark(newbadtet->fdest),
27311 pointmark(newbadtet->fapex), pointmark(newbadtet->foppo));
27312 }
27313 }
27314
27315 return illflag;
27316 }
27317
27318 ///////////////////////////////////////////////////////////////////////////////
27319 // //
27320 // checktet4sliver() Check a tet to see if it is a sliver. //
27321 // //
27322 // A sliver is a tet has no small edges, but has a nearly zero volume. When //
27323 // the mesh quality is measured by radios-edge ratio, slivers can have rela- //
27324 // tively small value and are not classified as bad quality. //
27325 // //
27326 // This routine finds whether a tet is a sliver or not by checking the bigg- //
27327 // est dihedral angle of the tet. It is a sliver if the angle is larger than //
27328 // 'maxdihed' (default is 170 degree, can be adjusted by '-s' option). //
27329 // //
27330 // If the flag 'chkill' is set, only check the volume of tet. It is a sliver //
27331 // if it has a zero or negative volume. //
27332 // //
27333 ///////////////////////////////////////////////////////////////////////////////
27334
27335 bool tetgenmesh::checktet4sliver(triface* testtet, bool chkill, bool enqflag)
27336 {
27337 badface *newbadtet;
27338 point pa, pb, pc, pd;
27339 REAL N[4][3], volume, len;
27340 REAL cosd, smallcosd;
27341 bool enq;
27342 int edgeno, i, j;
27343
27344 enq = false;
27345
27346 pa = (point) testtet->tet[4];
27347 pb = (point) testtet->tet[5];
27348 pc = (point) testtet->tet[6];
27349 pd = (point) testtet->tet[7];
27350 // Compute the 4 face normals (N[0], ..., N[3]).
27351 tetallnormal(pa, pb, pc, pd, N, &volume);
27352 // Normalize the normals.
27353 for (i = 0; i < 4; i++) {
27354 len = sqrt(dot(N[i], N[i]));
27355 if (len != 0.0) {
27356 for (j = 0; j < 3; j++) N[i][j] /= len;
27357 }
27358 }
27359 // Find the largest dihedral and the edge.
27360 smallcosd = -dot(N[2], N[3]); // Edge ab.
27361 edgeno = 0;
27362 for (i = 1; i < 4; i++) {
27363 cosd = -dot(N[0], N[i]); // Edge cd, bd, bc.
27364 if (cosd < smallcosd) {
27365 smallcosd = cosd;
27366 edgeno = i;
27367 }
27368 }
27369 for (i = 2; i < 4; i++) {
27370 cosd = -dot(N[1], N[i]); // Edge ad, ac.
27371 if (cosd < smallcosd) {
27372 smallcosd = cosd;
27373 edgeno = i + 2;
27374 }
27375 }
27376 // Check if abcd is sliver.
27377 if (!chkill) {
27378 enq = ((smallcosd > cosmindihed) || ((smallcosd < cosmaxdihed)));
27379 } else {
27380 enq = (volume <= 0.0);
27381 }
27382
27383 if (enq && enqflag) {
27384 // Let t represent the edge having the biggest dihedral angle.
27385 testtet->loc = 0;
27386 testtet->ver = 0;
27387 switch (edgeno) {
27388 case 0: break; // edge ab
27389 case 1: // edge cd
27390 enextfnextself(*testtet);
27391 enextself(*testtet);
27392 break;
27393 case 2: // edge bd
27394 enextfnextself(*testtet);
27395 enext2self(*testtet);
27396 break;
27397 case 3: // edge bc
27398 enextself(*testtet);
27399 break;
27400 case 4: // edge ad
27401 enext2fnextself(*testtet);
27402 enextself(*testtet);
27403 break;
27404 case 5: // edge ac
27405 enext2self(*testtet);
27406 break;
27407 }
27408 // Allocate space for the bad tetrahedron.
27409 newbadtet = (badface *) badtetrahedrons->alloc();
27410 newbadtet->tt = *testtet;
27411 newbadtet->key = smallcosd;
27412 for (i = 0; i < 3; i++) newbadtet->cent[i] = 0.0;
27413 newbadtet->forg = org(*testtet);
27414 newbadtet->fdest = dest(*testtet);
27415 newbadtet->fapex = apex(*testtet);
27416 newbadtet->foppo = oppo(*testtet);
27417 newbadtet->nextitem = (badface *) NULL;
27418 if (b->verbose > 2) {
27419 printf(" Queueing sliver: (%d, %d, %d, %d), maxdihed %g (degree).\n",
27420 pointmark(newbadtet->forg), pointmark(newbadtet->fdest),
27421 pointmark(newbadtet->fapex), pointmark(newbadtet->foppo),
27422 acos(smallcosd) * 180.0 / PI);
27423 }
27424 }
27425
27426 return enq;
27427 }
27428
27429 ///////////////////////////////////////////////////////////////////////////////
27430 // //
27431 // removetetbystripoff() Remove a boundary tet by stripping it off. //
27432 // //
27433 // 'striptet' (abcd) is on boundary and can be removed by stripping it off. //
27434 // Let abc and bad are the external boundary faces. //
27435 // //
27436 // To strip 'abcd' from the mesh is to detach its two interal faces (dca and //
27437 // cdb) from their adjoining tets together with a 2-to-2 flip to transform //
27438 // two subfaces (abc and bad) into another two (dca and cdb). //
27439 // //
27440 ///////////////////////////////////////////////////////////////////////////////
27441
27442 void tetgenmesh::removetetbystripoff(triface *striptet)
27443 {
27444 triface abcd, badc;
27445 triface dcacasing, cdbcasing;
27446 face abc, bad;
27447
27448 if (b->verbose > 1) {
27449 printf(" by stripping it off.\n");
27450 }
27451
27452 striptetcount++;
27453
27454 abcd = *striptet;
27455 adjustedgering(abcd, CCW);
27456
27457 // Get the external subfaces abc, bad.
27458 fnext(abcd, badc);
27459 esymself(badc);
27460 tspivot(abcd, abc);
27461 tspivot(badc, bad);
27462 #ifdef SELF_CHECK
27463 assert((abc.sh != dummysh) && (bad.sh != dummysh));
27464 #endif
27465 findedge(&abc, org(abcd), dest(abcd));
27466 findedge(&bad, org(badc), dest(badc));
27467
27468 // Get the casing tets at the internal sides.
27469 enextfnext(abcd, cdbcasing);
27470 enext2fnext(abcd, dcacasing);
27471 symself(cdbcasing);
27472 symself(dcacasing);
27473 #ifdef SELF_CHECK
27474 assert(cdbcasing.tet != dummytet && dcacasing.tet != dummytet);
27475 #endif
27476
27477 // Do a 2-to-2 flip on abc and bad, transform abc->dca, bad->cdb.
27478 flip22sub(&abc, NULL);
27479 // Detach abcd from the two internal faces.
27480 dissolve(cdbcasing);
27481 dissolve(dcacasing);
27482 // The two internal faces become boundary faces.
27483 tsbond(cdbcasing, bad);
27484 tsbond(dcacasing, abc);
27485 // Delete abcd.
27486 tetrahedrondealloc(abcd.tet);
27487 }
27488
27489 ///////////////////////////////////////////////////////////////////////////////
27490 // //
27491 // removetetbyflip32() Remove a tet by a 3-to-2 flip. //
27492 // //
27493 // 'fliptet' (abcd) is going to be removed by a 3-to-2 flip. ab is the edge //
27494 // will be flipped away, i.e., abc, bad, and abe are three internal faces. //
27495 // //
27496 // Note: If abc and bad are subfaces(abe must not), a 2-to-2 flip is used to //
27497 // transform abc, bad into dca, cdb prior to the 3-to-2 flip. //
27498 // //
27499 // If 'enq' flag is set, check the two new tets after flip to see if they're //
27500 // slivers or illegal tets according to the 'chkill' flag. //
27501 // //
27502 ///////////////////////////////////////////////////////////////////////////////
27503
27504 void tetgenmesh::removetetbyflip32(triface *fliptet, bool enq, bool chkill)
27505 {
27506 triface abcd, badc;
27507 triface cdab, dcba;
27508 triface baccasing, abdcasing;
27509 triface dcacasing, cdbcasing;
27510 face abc, bad;
27511 REAL attrib, volume;
27512 int i;
27513
27514 if (b->verbose > 1) {
27515 printf(" by a 3-to-2 flip.\n");
27516 }
27517
27518 fliptetcount++;
27519
27520 abcd = *fliptet;
27521 adjustedgering(abcd, CCW);
27522 fnext(abcd, badc);
27523 esymself(badc);
27524 sym(abcd, baccasing);
27525 sym(badc, abdcasing);
27526 #ifdef SELF_CHECK
27527 assert((baccasing.tet != dummytet) && (abdcasing.tet != dummytet));
27528 assert(oppo(baccasing) == oppo(abdcasing));
27529 #endif
27530
27531 // Get subfaces abc, bad.
27532 tspivot(abcd, abc);
27533 tspivot(badc, bad);
27534 if (abc.sh != dummysh) {
27535 #ifdef SELF_CHECK
27536 // Because ab is not a subsegment.
27537 assert(bad.sh != dummysh);
27538 #endif
27539 // abc and bad are internal subfaces. tets baccasing and abdcasing must
27540 // have the same attributes (such as the region attribute if the -A
27541 // switch is in use). But abcd may not be at the same region. After
27542 // flip32, if abcd is not deleted, it will have the wrong attributes.
27543 // Set abcd be the same region attributes as baccasing and abdcasing.
27544 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
27545 attrib = elemattribute(baccasing.tet, i);
27546 #ifdef SELF_CHECK
27547 REAL testattr = elemattribute(abdcasing.tet, i);
27548 assert(attrib == testattr);
27549 #endif
27550 setelemattribute(abcd.tet, i, attrib);
27551 }
27552 if (b->varvolume) {
27553 volume = volumebound(baccasing.tet);
27554 setvolumebound(abcd.tet, volume);
27555 }
27556 findedge(&abc, org(abcd), dest(abcd));
27557 findedge(&bad, org(badc), dest(badc));
27558 // Detach abc, bad from the four tets at both sides.
27559 stdissolve(abc);
27560 stdissolve(bad);
27561 sesymself(abc);
27562 sesymself(bad);
27563 stdissolve(abc);
27564 stdissolve(bad);
27565 sesymself(abc);
27566 sesymself(bad);
27567 // Detach the four tets which hold abc and bad.
27568 tsdissolve(abcd);
27569 tsdissolve(badc);
27570 tsdissolve(baccasing);
27571 tsdissolve(abdcasing);
27572 // Perform a 2-to-2 flip on abc, bad, transform abc->dca, bad->cdb.
27573 flip22sub(&abc, NULL);
27574 // Insert the flipped subfaces abc and bad into tets.
27575 enextfnext(abcd, dcba); // dcba = bcda
27576 esymself(dcba); // dcba = cbda
27577 enext2fnext(abcd, cdab); // cdab = cadb
27578 esymself(cdab); // cdab = acdb
27579 findedge(&abc, org(cdab), dest(cdab));
27580 tsbond(cdab, abc);
27581 findedge(&bad, org(dcba), dest(dcba));
27582 tsbond(dcba, bad);
27583 // Bond the other sides of cdab, dcba, they may outer space.
27584 sym(cdab, dcacasing);
27585 sym(dcba, cdbcasing);
27586 sesymself(abc);
27587 sesymself(bad);
27588 tsbond(dcacasing, abc);
27589 tsbond(cdbcasing, bad);
27590 }
27591 // Remove abcd by a 3-to-2 flip.
27592 flip32(&abcd, NULL);
27593 // After flip abc is the internal face.
27594
27595 if (enq) {
27596 // Get the adjtet of abcd (in badc).
27597 sym(abcd, badc);
27598 if (chkill) {
27599 // Test the two new tets to see if they are illegal.
27600 checktet4ill(&abcd, true);
27601 checktet4ill(&badc, true);
27602 } else {
27603 // Test the two new tets to see if they are sliver.
27604 checktet4sliver(&abcd, false, true);
27605 checktet4sliver(&badc, false, true);
27606 }
27607 }
27608 }
27609
27610 ///////////////////////////////////////////////////////////////////////////////
27611 // //
27612 // removetetbyrecon() Remove a tet by local reconnection. //
27613 // //
27614 // 'remtet' (abcd) is wanted to be removed from the mesh. ab is the primary //
27615 // edge (which is diagonal if a, b, c, and d form a convex quadrilateral). //
27616 // //
27617 // abcd is removable if it is not a segment, and either it can be stripped //
27618 // off or it can be flipped away. //
27619 // //
27620 // The return value indicates abcd is remveable or not. Note, although abcd //
27621 // is removeable but it may not be removed when 'chkill' is FALSE. //
27622 // //
27623 ///////////////////////////////////////////////////////////////////////////////
27624
27625 bool tetgenmesh::removetetbyrecon(badface* remtet, bool chkill)
27626 {
27627 triface abcd, badc; // Tet configuration at edge ab.
27628 triface baccasing, abdcasing;
27629 face abseg;
27630 point pa, pb, pc, pd, pe;
27631 REAL ori1, ori2;
27632 REAL cosmaxd1, cosmaxd2;
27633 bool remflag;
27634 int i;
27635
27636 remflag = false;
27637 // tet 'abcd' is indicated to remove.
27638 abcd = remtet->tt;
27639 // Check if abcd is removeable (at edge ab and cd).
27640 for (i = 0; i < 2; i++) {
27641 // If ab a segment, it is unremoveable.
27642 tsspivot(&abcd, &abseg);
27643 if (abseg.sh == dummysh) {
27644 adjustedgering(abcd, CCW);
27645 // Get the tet configuration at edge ab (or cd).
27646 fnext(abcd, badc);
27647 esymself(badc);
27648 sym(abcd, baccasing);
27649 sym(badc, abdcasing);
27650 // Can 'abcd' be stripped off?
27651 if ((baccasing.tet == dummytet) && (abdcasing.tet == dummytet)) {
27652 removetetbystripoff(&abcd);
27653 remflag = true;
27654 break; // abcd has been removed.
27655 } else if (oppo(baccasing) == oppo(abdcasing)) {
27656 // Can 'abcd' be flipped away?
27657 pa = org(abcd);
27658 pb = dest(abcd);
27659 pc = apex(abcd);
27660 pd = oppo(abcd);
27661 pe = oppo(baccasing);
27662 // Check if face cde is crossed by ab.
27663 ori1 = orient3d(pc, pd, pe, pa);
27664 ori2 = orient3d(pc, pd, pe, pb);
27665 if (ori1 * ori2 < 0.0) {
27666 // ab can be flipped away.
27667 if (!chkill) {
27668 // Do flip if the maximal dihedrals of the new tets are reduced?
27669 tetalldihedral(pd, pc, pe, pa, NULL, &cosmaxd1, NULL);
27670 tetalldihedral(pc, pd, pe, pb, NULL, &cosmaxd2, NULL);
27671 if ((remtet->key <= cosmaxd1) && (remtet->key <= cosmaxd2)) {
27672 removetetbyflip32(&abcd, true, chkill);
27673 remflag = true;
27674 break; // abcd has been removed.
27675 }
27676 } else {
27677 removetetbyflip32(&abcd, true, chkill);
27678 remflag = true;
27679 break; // abcd has been removed.
27680 }
27681 }
27682 }
27683 } // if (abseg.sh == dummysh)
27684 // 'abcd' is not removed (although it may be removeable).
27685 if (i == 1) break; // Stop if both ab and cd have been checked.
27686 // Go to edge cd, re-use handle abcd.
27687 enextfnextself(abcd);
27688 esymself(abcd);
27689 enext2self(abcd);
27690 } // for (i = 0; i < 2; i++)
27691
27692 return remflag;
27693 }
27694
27695 ///////////////////////////////////////////////////////////////////////////////
27696 // //
27697 // removetetbysplit() Remove a tet by inserting a point in it. //
27698 // //
27699 ///////////////////////////////////////////////////////////////////////////////
27700
27701 bool tetgenmesh::removetetbysplit(badface* remtet)
27702 {
27703 list **tetlists, **ceillists;
27704 list **sublists, **subceillists;
27705 list *tetlist, *ceillist, *verlist;
27706 triface abcd, starttet;
27707 face abseg, abcsh;
27708 point newpt, refpt;
27709 REAL maxcosd;
27710 int nmax, n;
27711 int i, j;
27712
27713 // tet 'abcd' is indicated to remove.
27714 abcd = remtet->tt;
27715 abseg.sh = dummysh;
27716 abcsh.sh = dummysh;
27717
27718 // Check if ab or cd is a segment.
27719 tsspivot(&abcd, &abseg);
27720 if (abseg.sh == dummysh) {
27721 adjustedgering(abcd, CCW);
27722 enextfnextself(abcd);
27723 enextself(abcd);
27724 tsspivot(&abcd, &abseg);
27725 }
27726 if (abseg.sh == dummysh) {
27727 abcd = remtet->tt;
27728 adjustedgering(abcd, CCW);
27729 // Check if abc is a subface.
27730 tspivot(abcd, abcsh);
27731 if (abcsh.sh == dummysh) {
27732 // Check if bad is a subface.
27733 fnextself(abcd);
27734 tspivot(abcd, abcsh);
27735 if (abcsh.sh == dummysh) {
27736 // Check if cda is a subface
27737 abcd = remtet->tt;
27738 adjustedgering(abcd, CCW);
27739 enext2fnextself(abcd);
27740 enext2self(abcd);
27741 esymself(abcd);
27742 tspivot(abcd, abcsh);
27743 if (abcsh.sh == dummysh) {
27744 // Check if cdb is a subface
27745 fnextself(abcd);
27746 tspivot(abcd, abcsh);
27747 }
27748 }
27749 }
27750 }
27751
27752 if (abseg.sh != dummysh) {
27753 if (checkpbcs) {
27754 // Do not split ab if it belongs to any pbcgroup.
27755 i = shellmark(abseg) - 1;
27756 if (idx2segpglist[i + 1] > idx2segpglist[i]) {
27757 return false; // There are pbc facets at ab.
27758 }
27759 }
27760 // Find if segment ab is encroached by an existing point.
27761 refpt = (point) NULL;
27762 checkseg4encroach(&abseg, NULL, &refpt, false);
27763 // Find a point in segment ab.
27764 makepoint(&newpt);
27765 getsplitpoint(sorg(abseg), sdest(abseg), refpt, newpt);
27766 setpointtype(newpt, FREESEGVERTEX);
27767 setpoint2sh(newpt, sencode(abseg));
27768 maxcosd = remtet->key;
27769 if (refpt != (point) NULL) {
27770 // ab is encroached. Force p to be inserted.
27771 maxcosd = -1.0; // 180 degree
27772 }
27773 n = 0;
27774 nmax = 128;
27775 tetlists = new list*[nmax];
27776 ceillists = new list*[nmax];
27777 sublists = new list*[nmax];
27778 subceillists = new list*[nmax];
27779 verlist = new list(sizeof(point *), NULL, 256);
27780 // Form BC(p).
27781 formbowatcavity(newpt, &abseg, NULL, &n, &nmax, sublists, subceillists,
27782 tetlists, ceillists);
27783 // Can local maximal dihedral be reduced by inserting p?
27784 if (trimbowatcavity(newpt, &abseg, n, sublists, subceillists, tetlists,
27785 ceillists, maxcosd)) {
27786 // Inserting p. Ignore any new enc-seg, enc-sub, and bad tets.
27787 bowatinsertsite(newpt, &abseg, n, sublists, subceillists, tetlists,
27788 ceillists, verlist, NULL, false, false, false);
27789 setnewpointsize(newpt, verlist);
27790 // Check if there are new slivers at p.
27791 for (j = 0; j < n; j++) {
27792 tetlist = ceillists[j];
27793 for (i = 0; i < tetlist->len(); i++) {
27794 starttet = * (triface *)(* tetlist)[i];
27795 checktet4sliver(&starttet, false, true);
27796 }
27797 }
27798 refpt != (point) NULL ? smoothcdtsegpt++ : smoothsegpt++;
27799 } else {
27800 // The local quality will not be improved. Do not insert p.
27801 pointdealloc(newpt);
27802 newpt = (point) NULL;
27803 refpt != (point) NULL ? unsmoothcdtsegpt++ : unsmoothsegpt++;
27804 }
27805 // Free the memory allocated in formbowatcavity().
27806 releasebowatcavity(&abseg, n, sublists, subceillists, tetlists, ceillists);
27807 delete [] tetlists;
27808 delete [] ceillists;
27809 delete [] sublists;
27810 delete [] subceillists;
27811 delete verlist;
27812 } else if (abcsh.sh != dummysh) {
27813 if (checkpbcs) {
27814 // Do not split abc if it belongs to a pbcgroup.
27815 if (shellpbcgroup(abcsh) >= 0) {
27816 return false; // It is on a pbc facet.
27817 }
27818 }
27819 // Insert the midpoint of ab which is on a facet.
27820 makepoint(&newpt);
27821 getsplitpoint(org(abcd), dest(abcd), NULL, newpt);
27822 setpointtype(newpt, FREESUBVERTEX);
27823 setpoint2sh(newpt, sencode(abcsh));
27824 n = 2;
27825 tetlists = new list*[2];
27826 ceillists = new list*[2];
27827 sublists = new list*[2];
27828 subceillists = new list*[2];
27829 verlist = new list(sizeof(point *), NULL, 256);
27830 // Form BC(p).
27831 formbowatcavity(newpt, NULL, &abcsh, &n, NULL, sublists, subceillists,
27832 tetlists, ceillists);
27833 // Can local maximal dihedral be reduced by inserting p?
27834 if (trimbowatcavity(newpt, NULL, n, sublists, subceillists, tetlists,
27835 ceillists, remtet->key)) {
27836 // Inserting p. Ignore any new enc-seg, enc-sub, and bad tets.
27837 bowatinsertsite(newpt, NULL, n, sublists, subceillists, tetlists,
27838 ceillists, verlist, NULL, false, false, false);
27839 setnewpointsize(newpt, verlist);
27840 // Check if there are new slivers at p.
27841 for (j = 0; j < n; j++) {
27842 tetlist = ceillists[j];
27843 for (i = 0; i < tetlist->len(); i++) {
27844 starttet = * (triface *)(* tetlist)[i];
27845 checktet4sliver(&starttet, false, true);
27846 }
27847 }
27848 smoothsubpt++;
27849 } else {
27850 // The local quality will not be improved. Do not insert p.
27851 pointdealloc(newpt);
27852 newpt = (point) NULL;
27853 unsmoothsubpt++;
27854 }
27855 // Free the memory allocated in formbowatcavity().
27856 releasebowatcavity(NULL, n, sublists, subceillists, tetlists, ceillists);
27857 delete [] tetlists;
27858 delete [] ceillists;
27859 delete [] sublists;
27860 delete [] subceillists;
27861 delete verlist;
27862 } else {
27863 // Insert the midpoint of the edge having largest dihedral angle.
27864 abcd = remtet->tt;
27865 makepoint(&newpt);
27866 getsplitpoint(org(abcd), dest(abcd), NULL, newpt);
27867 setpointtype(newpt, FREEVOLVERTEX);
27868 // Form BC(p).
27869 tetlist = new list(sizeof(triface), NULL, 1024);
27870 ceillist = new list(sizeof(triface), NULL, 1024);
27871 verlist = new list(sizeof(point *), NULL, 256);
27872 starttet = abcd;
27873 infect(starttet);
27874 tetlist->append(&starttet);
27875 formbowatcavityquad(newpt, tetlist, ceillist);
27876 // Can local maximal dihedral be reduced by inserting p?
27877 if (trimbowatcavity(newpt, NULL, 1, NULL, NULL, &tetlist, &ceillist,
27878 remtet->key)) {
27879 // Inserting p. Ignore any new enc-seg, enc-sub, and bad tets.
27880 bowatinsertsite(newpt, NULL, 1, NULL, NULL, &tetlist, &ceillist, verlist,
27881 NULL, false, false, false);
27882 setnewpointsize(newpt, verlist);
27883 // Check if there are new slivers at p.
27884 for (i = 0; i < ceillist->len(); i++) {
27885 starttet = * (triface *)(* ceillist)[i];
27886 checktet4sliver(&starttet, false, true);
27887 }
27888 smoothvolpt++;
27889 } else {
27890 // The local quality will not be improved. Do not insert p.
27891 pointdealloc(newpt);
27892 newpt = (point) NULL;
27893 // Uninfect tets of BC(p).
27894 for (i = 0; i < tetlist->len(); i++) {
27895 starttet = * (triface *)(* tetlist)[i];
27896 uninfect(starttet);
27897 }
27898 unsmoothvolpt++;
27899 }
27900 delete tetlist;
27901 delete ceillist;
27902 delete verlist;
27903 }
27904
27905 return newpt != (point) NULL;
27906 }
27907
27908 ///////////////////////////////////////////////////////////////////////////////
27909 // //
27910 // tallslivers() Queue all the slivers in the mesh. //
27911 // //
27912 ///////////////////////////////////////////////////////////////////////////////
27913
27914 void tetgenmesh::tallslivers(bool chkill)
27915 {
27916 triface tetloop;
27917
27918 tetrahedrons->traversalinit();
27919 tetloop.tet = tetrahedrontraverse();
27920 while (tetloop.tet != (tetrahedron *) NULL) {
27921 if (chkill) {
27922 if (!checktet4sliver(&tetloop, true, true)) {
27923 checktet4ill(&tetloop, true);
27924 }
27925 } else {
27926 checktet4sliver(&tetloop, false, true);
27927 }
27928 tetloop.tet = tetrahedrontraverse();
27929 }
27930 }
27931
27932 ///////////////////////////////////////////////////////////////////////////////
27933 // //
27934 // repairmesh() Remove illegal tets in the mesh. //
27935 // //
27936 ///////////////////////////////////////////////////////////////////////////////
27937
27938 void tetgenmesh::repairmesh()
27939 {
27940 badface *remtet, *lastunrementry;
27941
27942 if (!b->quiet) {
27943 printf("Repairing mesh.\n");
27944 }
27945
27946 // Initialize the pool of bad tets
27947 badtetrahedrons = new memorypool(sizeof(badface), ELEPERBLOCK, POINTER, 0);
27948 lastunrementry = (badface *) NULL;
27949 striptetcount = fliptetcount = unimprovecount = 0l;
27950
27951 // Looking for illegal tets.
27952 tallslivers(true);
27953
27954 // Loop until pool 'badtetrahedrons' is empty.
27955 while (badtetrahedrons->items > 0) {
27956 badtetrahedrons->traversalinit();
27957 remtet = badfacetraverse(badtetrahedrons);
27958 while (remtet != (badface *) NULL) {
27959 // Make sure that the tet is still the same one when it was tested.
27960 // Subsequent transformations may have made it a different tet.
27961 if (!isdead(&remtet->tt) && org(remtet->tt) == remtet->forg &&
27962 dest(remtet->tt) == remtet->fdest &&
27963 apex(remtet->tt) == remtet->fapex &&
27964 oppo(remtet->tt) == remtet->foppo) {
27965 if (b->verbose > 1) {
27966 printf(" Repair tet (%d, %d, %d, %d).\n", pointmark(remtet->forg),
27967 pointmark(remtet->fdest), pointmark(remtet->fapex),
27968 pointmark(remtet->foppo));
27969 }
27970 if (!removetetbyrecon(remtet, true)) {
27971 // An unremoveable tet. Check if it forms a loop.
27972 if (lastunrementry != (badface *) NULL) {
27973 if (remtet == lastunrementry) break;
27974 } else {
27975 // Remember this tet as a breakpoint.
27976 lastunrementry = remtet;
27977 }
27978 } else {
27979 // Clear the breakpoint.
27980 lastunrementry = (badface *) NULL;
27981 // Remove the entry from the queue.
27982 badfacedealloc(badtetrahedrons, remtet);
27983 }
27984 } else {
27985 // Remove the entry from the queue.
27986 badfacedealloc(badtetrahedrons, remtet);
27987 }
27988 remtet = badfacetraverse(badtetrahedrons);
27989 }
27990 // Stop if the above loop was out by force.
27991 if (remtet != (badface *) NULL) break;
27992 }
27993
27994 if (b->verbose) {
27995 if (striptetcount > 0l) {
27996 printf(" %ld tets are stripped off.\n", striptetcount);
27997 }
27998 if (fliptetcount > 0l) {
27999 printf(" %ld tets are flipped away.\n", fliptetcount);
28000 }
28001 if (badtetrahedrons->items > 0l) {
28002 printf(" %ld tets are unremoveable.\n", badtetrahedrons->items);
28003 }
28004 }
28005
28006 delete badtetrahedrons;
28007 badtetrahedrons = (memorypool *) NULL;
28008 }
28009
28010 ///////////////////////////////////////////////////////////////////////////////
28011 // //
28012 // smoothmesh() Smooth the mesh. //
28013 // //
28014 ///////////////////////////////////////////////////////////////////////////////
28015
28016 void tetgenmesh::smoothmesh()
28017 {
28018 badface *remtet, *lastunrementry;
28019
28020 if (!b->quiet) {
28021 printf("Smoothing mesh.\n");
28022 }
28023
28024 // Initialize the pool of bad tets
28025 badtetrahedrons = new memorypool(sizeof(badface), ELEPERBLOCK, POINTER, 0);
28026 cosmaxdihed = cos(b->maxdihedral * PI / 180.0);
28027 cosmindihed = 1.0;
28028 striptetcount = fliptetcount = unimprovecount = 0l;
28029 smoothcdtsegpt = smoothsegpt = smoothsubpt = smoothvolpt = 0l;
28030 unsmoothcdtsegpt = unsmoothsegpt = unsmoothsubpt = unsmoothvolpt = 0l;
28031
28032 // Looking for bad tets.
28033 tallslivers(false);
28034
28035 lastunrementry = (badface *) NULL;
28036 // Loop until pool 'badtetrahedrons' is empty.
28037 while (badtetrahedrons->items > 0) {
28038 badtetrahedrons->traversalinit();
28039 remtet = badfacetraverse(badtetrahedrons);
28040 while (remtet != (badface *) NULL) {
28041 // Make sure that the tet is still the same one when it was tested.
28042 // Subsequent transformations may have made it a different tet.
28043 if (!isdead(&remtet->tt) && org(remtet->tt) == remtet->forg &&
28044 dest(remtet->tt) == remtet->fdest &&
28045 apex(remtet->tt) == remtet->fapex &&
28046 oppo(remtet->tt) == remtet->foppo) {
28047 if (b->verbose > 1) {
28048 printf(" Repair tet (%d, %d, %d, %d).\n", pointmark(remtet->forg),
28049 pointmark(remtet->fdest), pointmark(remtet->fapex),
28050 pointmark(remtet->foppo));
28051 }
28052 if (!removetetbyrecon(remtet, false)) {
28053 // An unremoveable tet. Check if it forms a loop.
28054 if (lastunrementry != (badface *) NULL) {
28055 if (remtet == lastunrementry) break;
28056 } else {
28057 // Remember this tet as a breakpoint.
28058 lastunrementry = remtet;
28059 }
28060 } else {
28061 // Clear the breakpoint.
28062 lastunrementry = (badface *) NULL;
28063 // Remove the entry from the queue.
28064 badfacedealloc(badtetrahedrons, remtet);
28065 }
28066 } else {
28067 // Remove the entry from the queue.
28068 badfacedealloc(badtetrahedrons, remtet);
28069 }
28070 remtet = badfacetraverse(badtetrahedrons);
28071 }
28072 // Stop if the above loop was out by force.
28073 if (remtet != (badface *) NULL) break;
28074 }
28075
28076 if (b->verbose) {
28077 if (striptetcount > 0l) {
28078 printf(" %ld tets are stripped off.\n", striptetcount);
28079 }
28080 if (fliptetcount > 0l) {
28081 printf(" %ld tets are flipped away.\n", fliptetcount);
28082 }
28083 }
28084
28085 lastunrementry = (badface *) NULL;
28086 // Loop until pool 'badtetrahedrons' is empty.
28087 while (badtetrahedrons->items > 0) {
28088 badtetrahedrons->traversalinit();
28089 remtet = badfacetraverse(badtetrahedrons);
28090 while (remtet != (badface *) NULL) {
28091 // Make sure that the tet is still the same one when it was tested.
28092 // Subsequent transformations may have made it a different tet.
28093 if (!isdead(&remtet->tt) && org(remtet->tt) == remtet->forg &&
28094 dest(remtet->tt) == remtet->fdest &&
28095 apex(remtet->tt) == remtet->fapex &&
28096 oppo(remtet->tt) == remtet->foppo) {
28097 if (b->verbose > 1) {
28098 printf(" Repair tet (%d, %d, %d, %d).\n", pointmark(remtet->forg),
28099 pointmark(remtet->fdest), pointmark(remtet->fapex),
28100 pointmark(remtet->foppo));
28101 }
28102 if (!removetetbyrecon(remtet, false)) {
28103 // An unremoveable tet. Find if a segment which can be split.
28104 if (!removetetbysplit(remtet)) {
28105 // An unremoveable tet. Check if it forms a loop.
28106 if (lastunrementry != (badface *) NULL) {
28107 if (remtet == lastunrementry) break;
28108 } else {
28109 // Remember this tet as a breakpoint.
28110 lastunrementry = remtet;
28111 }
28112 } else {
28113 // Clear the breakpoint.
28114 lastunrementry = (badface *) NULL;
28115 // Remove the entry from the queue.
28116 badfacedealloc(badtetrahedrons, remtet);
28117 }
28118 } else {
28119 // Clear the breakpoint.
28120 lastunrementry = (badface *) NULL;
28121 // Remove the entry from the queue.
28122 badfacedealloc(badtetrahedrons, remtet);
28123 }
28124 } else {
28125 // Remove the entry from the queue.
28126 badfacedealloc(badtetrahedrons, remtet);
28127 }
28128 remtet = badfacetraverse(badtetrahedrons);
28129 }
28130 // Stop if the above loop was out by force.
28131 if (remtet != (badface *) NULL) break;
28132 }
28133
28134 if (b->verbose) {
28135 if ((smoothcdtsegpt + smoothsegpt + smoothsubpt + smoothvolpt) > 0l) {
28136 printf(" %ld smooth points.\n",
28137 smoothcdtsegpt + smoothsegpt + smoothsubpt + smoothvolpt);
28138 }
28139 if (badtetrahedrons->items > 0l) {
28140 printf(" %ld remaining tets.\n", badtetrahedrons->items);
28141 }
28142 }
28143
28144 delete badtetrahedrons;
28145 badtetrahedrons = (memorypool *) NULL;
28146 }
28147
28148 //
28149 // End of mesh smoothing routines
28150 //
28151
28152 //
28153 // Begin of I/O rouitnes
28154 //
28155
28156 ///////////////////////////////////////////////////////////////////////////////
28157 // //
28158 // transfernodes() Transfer nodes from 'io->pointlist' to 'this->points'. //
28159 // //
28160 // Initializing 'this->points'. Transferring all points from 'in->pointlist'//
28161 // into it. All points are indexed (start from in->firstnumber). Each point //
28162 // is initialized be UNUSEDVERTEX. The bounding box (xmin, xmax, ymin, ymax,//
28163 // zmin, zmax) and the diameter (longest) of the point set are calculated. //
28164 // //
28165 ///////////////////////////////////////////////////////////////////////////////
28166
28167 void tetgenmesh::transfernodes()
28168 {
28169 point pointloop;
28170 REAL x, y, z;
28171 int coordindex;
28172 int attribindex;
28173 int i, j;
28174
28175 // Read the points.
28176 coordindex = 0;
28177 attribindex = 0;
28178 for (i = 0; i < in->numberofpoints; i++) {
28179 makepoint(&pointloop);
28180 // Read the point coordinates.
28181 x = pointloop[0] = in->pointlist[coordindex++];
28182 y = pointloop[1] = in->pointlist[coordindex++];
28183 z = pointloop[2] = in->pointlist[coordindex++];
28184 // Read the point attributes.
28185 for (j = 0; j < in->numberofpointattributes; j++) {
28186 pointloop[3 + j] = in->pointattributelist[attribindex++];
28187 }
28188 // Determine the smallest and largests x, y and z coordinates.
28189 if (i == 0) {
28190 xmin = xmax = x;
28191 ymin = ymax = y;
28192 zmin = zmax = z;
28193 } else {
28194 xmin = (x < xmin) ? x : xmin;
28195 xmax = (x > xmax) ? x : xmax;
28196 ymin = (y < ymin) ? y : ymin;
28197 ymax = (y > ymax) ? y : ymax;
28198 zmin = (z < zmin) ? z : zmin;
28199 zmax = (z > zmax) ? z : zmax;
28200 }
28201 }
28202 // 'longest' is the largest possible edge length formed by input vertices.
28203 // It is used as the measure to distinguish two identical points.
28204 x = xmax - xmin;
28205 y = ymax - ymin;
28206 z = zmax - zmin;
28207 longest = sqrt(x * x + y * y + z * z);
28208 if (longest == 0.0) {
28209 printf("Error: The point set is trivial.\n");
28210 terminatetetgen(1);
28211 }
28212 lengthlimit = longest * b->epsilon * 1e+2;
28213 }
28214
28215 ///////////////////////////////////////////////////////////////////////////////
28216 // //
28217 // jettisonnodes() Jettison unused or duplicated vertices. //
28218 // //
28219 // Unused points are those input points which are outside the mesh domain or //
28220 // have no connection (isolated) to the mesh. Duplicated points exist for //
28221 // example if the input PLC is read from a .stl mesh file (marked during the //
28222 // Delaunay tetrahedralization step. This routine remove these points from //
28223 // points list. All existing points are reindexed. //
28224 // //
28225 ///////////////////////////////////////////////////////////////////////////////
28226
28227 void tetgenmesh::jettisonnodes()
28228 {
28229 point pointloop;
28230 bool jetflag;
28231 int oldidx, newidx;
28232 int remcount;
28233
28234 if (!b->quiet) {
28235 printf("Jettisoning redundants points.\n");
28236 }
28237
28238 points->traversalinit();
28239 pointloop = pointtraverse();
28240 oldidx = newidx = 0; // in->firstnumber;
28241 remcount = 0;
28242 while (pointloop != (point) NULL) {
28243 jetflag = (pointtype(pointloop) == DUPLICATEDVERTEX) ||
28244 (pointtype(pointloop) == UNUSEDVERTEX);
28245 if (jetflag) {
28246 // It is a duplicated point, delete it.
28247 pointdealloc(pointloop);
28248 remcount++;
28249 } else {
28250 // Re-index it.
28251 setpointmark(pointloop, newidx + in->firstnumber);
28252 if (in->pointmarkerlist != (int *) NULL) {
28253 if (oldidx < in->numberofpoints) {
28254 // Re-index the point marker as well.
28255 in->pointmarkerlist[newidx] = in->pointmarkerlist[oldidx];
28256 }
28257 }
28258 newidx++;
28259 }
28260 oldidx++;
28261 if (oldidx == in->numberofpoints) {
28262 // Update the numbe of input points (Because some were removed).
28263 in->numberofpoints -= remcount;
28264 // Remember this number for output original input nodes.
28265 jettisoninverts = remcount;
28266 }
28267 pointloop = pointtraverse();
28268 }
28269 if (b->verbose) {
28270 printf(" %d duplicated vertices have been removed.\n", dupverts);
28271 printf(" %d unused vertices have been removed.\n", unuverts);
28272 }
28273 dupverts = 0;
28274 unuverts = 0;
28275
28276 // The following line ensures that dead items in the pool of nodes cannot
28277 // be allocated for the new created nodes. This ensures that the input
28278 // nodes will occur earlier in the output files, and have lower indices.
28279 points->deaditemstack = (void *) NULL;
28280 }
28281
28282 ///////////////////////////////////////////////////////////////////////////////
28283 // //
28284 // highorder() Create extra nodes for quadratic subparametric elements. //
28285 // //
28286 // 'highordertable' is an array (size = numberoftetrahedra * 6) for storing //
28287 // high-order nodes of each tetrahedron. This routine is used only when -o2 //
28288 // switch is used. //
28289 // //
28290 ///////////////////////////////////////////////////////////////////////////////
28291
28292 void tetgenmesh::highorder()
28293 {
28294 triface tetloop, worktet;
28295 triface spintet, adjtet;
28296 point torg, tdest, tapex;
28297 point *extralist, *adjextralist;
28298 point newpoint;
28299 int hitbdry, ptmark;
28300 int i, j;
28301
28302 // The 'edgeindex' (from 0 to 5) is list as follows:
28303 // 0 - (v0, v1), 1 - (v1, v2), 2 - (v2, v0)
28304 // 3 - (v3, v0), 4 - (v3, v1), 5 - (v3, v2)
28305 // Define an edgeindex map: (loc, ver)->edgeindex.
28306 int edgeindexmap[4][6] = {{0, 0, 1, 1, 2, 2},
28307 {3, 3, 4, 4, 0, 0},
28308 {4, 4, 5, 5, 1, 1},
28309 {5, 5, 3, 3, 2, 2}};
28310
28311 if (!b->quiet) {
28312 printf("Adding vertices for second-order tetrahedra.\n");
28313 }
28314
28315 // Initialize the 'highordertable'.
28316 highordertable = new point[tetrahedrons->items * 6];
28317 if (highordertable == (point *) NULL) {
28318 printf("Error: Out of memory.\n");
28319 terminatetetgen(1);
28320 }
28321
28322 // The following line ensures that dead items in the pool of nodes cannot
28323 // be allocated for the extra nodes associated with high order elements.
28324 // This ensures that the primary nodes (at the corners of elements) will
28325 // occur earlier in the output files, and have lower indices, than the
28326 // extra nodes.
28327 points->deaditemstack = (void *) NULL;
28328
28329 // Assign an entry for each tetrahedron to find its extra nodes. At the
28330 // mean while, initialize all extra nodes be NULL.
28331 i = 0;
28332 tetrahedrons->traversalinit();
28333 tetloop.tet = tetrahedrontraverse();
28334 while (tetloop.tet != (tetrahedron *) NULL) {
28335 tetloop.tet[highorderindex] = (tetrahedron) &highordertable[i];
28336 for (j = 0; j < 6; j++) {
28337 highordertable[i + j] = (point) NULL;
28338 }
28339 i += 6;
28340 tetloop.tet = tetrahedrontraverse();
28341 }
28342
28343 // To create a unique node on each edge. Loop over all tetrahedra, and
28344 // look at the six edges of each tetrahedron. If the extra node in
28345 // the tetrahedron corresponding to this edge is NULL, create a node
28346 // for this edge, at the same time, set the new node into the extra
28347 // node lists of all other tetrahedra sharing this edge.
28348 tetrahedrons->traversalinit();
28349 tetloop.tet = tetrahedrontraverse();
28350 while (tetloop.tet != (tetrahedron *) NULL) {
28351 // Get the list of extra nodes.
28352 extralist = (point *) tetloop.tet[highorderindex];
28353 for (i = 0; i < 6; i++) {
28354 if (extralist[i] == (point) NULL) {
28355 // Operate on this edge.
28356 worktet = tetloop;
28357 worktet.loc = 0; worktet.ver = 0;
28358 // Get the correct edge in 'worktet'.
28359 switch(i) {
28360 case 0: // (v0, v1)
28361 break;
28362 case 1: // (v1, v2)
28363 enextself(worktet);
28364 break;
28365 case 2: // (v2, v0)
28366 enext2self(worktet);
28367 break;
28368 case 3: // (v3, v0)
28369 fnextself(worktet);
28370 enext2self(worktet);
28371 break;
28372 case 4: // (v3, v1)
28373 enextself(worktet);
28374 fnextself(worktet);
28375 enext2self(worktet);
28376 break;
28377 case 5: // (v3, v2)
28378 enext2self(worktet);
28379 fnextself(worktet);
28380 enext2self(worktet);
28381 }
28382 // Create a new node on this edge.
28383 torg = org(worktet);
28384 tdest = dest(worktet);
28385 // Create a new node in the middle of the edge.
28386 newpoint = (point) points->alloc();
28387 // Interpolate its attributes.
28388 // for (j = 0; j < 3 + in->numberofpointattributes; j++) {
28389 // newpoint[j] = 0.5 * (torg[j] + tdest[j]);
28390 // }
28391 ptmark = (int) points->items - (in->firstnumber == 1 ? 0 : 1);
28392 setpointmark(newpoint, ptmark);
28393 // Add this node to its extra node list.
28394 extralist[i] = newpoint;
28395 // Set 'newpoint' into extra node lists of other tetrahedra
28396 // sharing this edge.
28397 tapex = apex(worktet);
28398 spintet = worktet;
28399 hitbdry = 0;
28400 while (hitbdry < 2) {
28401 if (fnextself(spintet)) {
28402 // Get the extra node list of 'spintet'.
28403 adjextralist = (point *) spintet.tet[highorderindex];
28404 // Find the index of its extra node list.
28405 j = edgeindexmap[spintet.loc][spintet.ver];
28406 // Only set 'newpoint' into 'adjextralist' if it is a NULL.
28407 // Because two faces can belong to the same tetrahedron.
28408 if (adjextralist[j] == (point) NULL) {
28409 adjextralist[j] = newpoint;
28410 }
28411 if (apex(spintet) == tapex) {
28412 break;
28413 }
28414 } else {
28415 hitbdry++;
28416 if (hitbdry < 2) {
28417 esym(worktet, spintet);
28418 }
28419 }
28420 }
28421 }
28422 }
28423 tetloop.tet = tetrahedrontraverse();
28424 }
28425 }
28426
28427 ///////////////////////////////////////////////////////////////////////////////
28428 // //
28429 // outnodes() Output the points to a .node file or a tetgenio structure. //
28430 // //
28431 // Note: each point has already been numbered on input (the first index is //
28432 // 'in->firstnumber'). //
28433 // //
28434 ///////////////////////////////////////////////////////////////////////////////
28435
28436 void tetgenmesh::outnodes(tetgenio* out)
28437 {
28438 FILE *outfile;
28439 char outnodefilename[FILENAMESIZE];
28440 shellface subptr;
28441 triface adjtet;
28442 face subloop;
28443 point pointloop;
28444 point *extralist, ep[3];
28445 int nextras, bmark, shmark, marker;
28446 int coordindex, attribindex;
28447 int pointnumber, firstindex;
28448 int index, i;
28449
28450 if (out == (tetgenio *) NULL) {
28451 strcpy(outnodefilename, b->outfilename);
28452 strcat(outnodefilename, ".node");
28453 }
28454
28455 if (!b->quiet) {
28456 if (out == (tetgenio *) NULL) {
28457 printf("Writing %s.\n", outnodefilename);
28458 } else {
28459 printf("Writing nodes.\n");
28460 }
28461 }
28462
28463 // nextras = in->numberofpointattributes;
28464 nextras = 0; // After version 1.4.0, don't output point attributes.
28465 bmark = !b->nobound && in->pointmarkerlist;
28466
28467 // Avoid compile warnings.
28468 outfile = (FILE *) NULL;
28469 marker = coordindex = 0;
28470
28471 if (out == (tetgenio *) NULL) {
28472 outfile = fopen(outnodefilename, "w");
28473 if (outfile == (FILE *) NULL) {
28474 printf("File I/O Error: Cannot create file %s.\n", outnodefilename);
28475 terminatetetgen(1);
28476 }
28477 // Number of points, number of dimensions, number of point attributes,
28478 // and number of boundary markers (zero or one).
28479 fprintf(outfile, "%ld %d %d %d\n", points->items, 3, nextras, bmark);
28480 } else {
28481 // Allocate space for 'pointlist';
28482 out->pointlist = new REAL[points->items * 3];
28483 if (out->pointlist == (REAL *) NULL) {
28484 printf("Error: Out of memory.\n");
28485 terminatetetgen(1);
28486 }
28487 // Allocate space for 'pointattributelist' if necessary;
28488 if (nextras > 0) {
28489 out->pointattributelist = new REAL[points->items * nextras];
28490 if (out->pointattributelist == (REAL *) NULL) {
28491 printf("Error: Out of memory.\n");
28492 terminatetetgen(1);
28493 }
28494 }
28495 // Allocate space for 'pointmarkerlist' if necessary;
28496 if (bmark) {
28497 out->pointmarkerlist = new int[points->items];
28498 if (out->pointmarkerlist == (int *) NULL) {
28499 printf("Error: Out of memory.\n");
28500 terminatetetgen(1);
28501 }
28502 }
28503 out->numberofpoints = points->items;
28504 out->numberofpointattributes = nextras;
28505 coordindex = 0;
28506 attribindex = 0;
28507 }
28508
28509 if (bmark && (b->plc || b->refine)) {
28510 // Initialize the point2tet field of each point.
28511 points->traversalinit();
28512 pointloop = pointtraverse();
28513 while (pointloop != (point) NULL) {
28514 setpoint2tet(pointloop, (tetrahedron) NULL);
28515 pointloop = pointtraverse();
28516 }
28517 // Make a map point-to-subface. Hence a boundary point will get the
28518 // facet marker from that facet where it lies on.
28519 subfaces->traversalinit();
28520 subloop.sh = shellfacetraverse(subfaces);
28521 while (subloop.sh != (shellface *) NULL) {
28522 subloop.shver = 0;
28523 // Check all three points of the subface.
28524 for (i = 0; i < 3; i++) {
28525 pointloop = (point) subloop.sh[3 + i];
28526 setpoint2tet(pointloop, (tetrahedron) sencode(subloop));
28527 }
28528 if (b->order == 2) {
28529 // '-o2' switch. Set markers for quadratic nodes of this subface.
28530 stpivot(subloop, adjtet);
28531 if (adjtet.tet == dummytet) {
28532 sesymself(subloop);
28533 stpivot(subloop, adjtet);
28534 }
28535 assert(adjtet.tet != dummytet);
28536 extralist = (point *) adjtet.tet[highorderindex];
28537 switch (adjtet.loc) {
28538 case 0:
28539 ep[0] = extralist[0];
28540 ep[1] = extralist[1];
28541 ep[2] = extralist[2];
28542 break;
28543 case 1:
28544 ep[0] = extralist[0];
28545 ep[1] = extralist[4];
28546 ep[2] = extralist[3];
28547 break;
28548 case 2:
28549 ep[0] = extralist[1];
28550 ep[1] = extralist[5];
28551 ep[2] = extralist[4];
28552 break;
28553 case 3:
28554 ep[0] = extralist[2];
28555 ep[1] = extralist[3];
28556 ep[2] = extralist[5];
28557 break;
28558 default: break;
28559 }
28560 for (i = 0; i < 3; i++) {
28561 setpoint2tet(ep[i], (tetrahedron) sencode(subloop));
28562 }
28563 }
28564 subloop.sh = shellfacetraverse(subfaces);
28565 }
28566 }
28567
28568 // Determine the first index (0 or 1).
28569 firstindex = b->zeroindex ? 0 : in->firstnumber;
28570
28571 points->traversalinit();
28572 pointloop = pointtraverse();
28573 pointnumber = firstindex; // in->firstnumber;
28574 index = 0;
28575 while (pointloop != (point) NULL) {
28576 if (bmark) {
28577 // Default the vertex has a zero marker.
28578 marker = 0;
28579 // Is it an input vertex?
28580 if (index < in->numberofpoints) {
28581 // Input point's marker is directly copied to output.
28582 marker = in->pointmarkerlist[index];
28583 }
28584 // Is it a boundary vertex has marker zero?
28585 if ((marker == 0) && (b->plc || b->refine)) {
28586 subptr = (shellface) point2tet(pointloop);
28587 if (subptr != (shellface) NULL) {
28588 // Default a boundary vertex has marker 1.
28589 marker = 1;
28590 if (in->facetmarkerlist != (int *) NULL) {
28591 // The vertex gets the marker from the facet it lies on.
28592 sdecode(subptr, subloop);
28593 shmark = shellmark(subloop);
28594 marker = in->facetmarkerlist[shmark - 1];
28595 }
28596 }
28597 }
28598 }
28599 if (out == (tetgenio *) NULL) {
28600 // Point number, x, y and z coordinates.
28601 fprintf(outfile, "%4d %.17g %.17g %.17g", pointnumber,
28602 pointloop[0], pointloop[1], pointloop[2]);
28603 for (i = 0; i < nextras; i++) {
28604 // Write an attribute.
28605 fprintf(outfile, " %.17g", pointloop[3 + i]);
28606 }
28607 if (bmark) {
28608 // Write the boundary marker.
28609 fprintf(outfile, " %d", marker);
28610 }
28611 fprintf(outfile, "\n");
28612 } else {
28613 // X, y, and z coordinates.
28614 out->pointlist[coordindex++] = pointloop[0];
28615 out->pointlist[coordindex++] = pointloop[1];
28616 out->pointlist[coordindex++] = pointloop[2];
28617 // Point attributes.
28618 for (i = 0; i < nextras; i++) {
28619 // Output an attribute.
28620 out->pointattributelist[attribindex++] = pointloop[3 + i];
28621 }
28622 if (bmark) {
28623 // Output the boundary marker.
28624 out->pointmarkerlist[index] = marker;
28625 }
28626 }
28627 pointloop = pointtraverse();
28628 pointnumber++;
28629 index++;
28630 }
28631
28632 if (out == (tetgenio *) NULL) {
28633 fprintf(outfile, "# Generated by %s\n", b->commandline);
28634 fclose(outfile);
28635 }
28636 }
28637
28638 ///////////////////////////////////////////////////////////////////////////////
28639 // //
28640 // outmetrics() Output the metric to a file (*.mtr) or a tetgenio obj. //
28641 // //
28642 ///////////////////////////////////////////////////////////////////////////////
28643
28644 void tetgenmesh::outmetrics(tetgenio* out)
28645 {
28646 FILE *outfile;
28647 char outmtrfilename[FILENAMESIZE];
28648 point pointloop;
28649 int nextras, attribindex;
28650 int i;
28651
28652 if (out == (tetgenio *) NULL) {
28653 strcpy(outmtrfilename, b->outfilename);
28654 strcat(outmtrfilename, ".mtr");
28655 }
28656
28657 if (!b->quiet) {
28658 if (out == (tetgenio *) NULL) {
28659 printf("Writing %s.\n", outmtrfilename);
28660 } else {
28661 printf("Writing metrics.\n");
28662 }
28663 }
28664
28665 // Avoid compile warnings.
28666 outfile = (FILE *) NULL;
28667 attribindex = 0;
28668
28669 nextras = 0;
28670 if (b->bgmesh) {
28671 nextras = bgm->in->numberofpointattributes;
28672 } else if (b->quality) {
28673 nextras = 1;
28674 }
28675 if (out == (tetgenio *) NULL) {
28676 outfile = fopen(outmtrfilename, "w");
28677 if (outfile == (FILE *) NULL) {
28678 printf("File I/O Error: Cannot create file %s.\n", outmtrfilename);
28679 terminatetetgen(1);
28680 }
28681 // Number of points, number of point attributes,
28682 fprintf(outfile, "%ld %d\n", points->items, nextras);
28683 } else {
28684 // Allocate space for 'pointattributelist' if necessary;
28685 if (nextras > 0) {
28686 out->pointattributelist = new REAL[points->items * nextras];
28687 if (out->pointattributelist == (REAL *) NULL) {
28688 printf("Error: Out of memory.\n");
28689 terminatetetgen(1);
28690 }
28691 }
28692 out->numberofpointattributes = nextras;
28693 attribindex = 0;
28694 }
28695
28696 points->traversalinit();
28697 pointloop = pointtraverse();
28698 while (pointloop != (point) NULL) {
28699 if (out == (tetgenio *) NULL) {
28700 for (i = 0; i < nextras; i++) {
28701 // Write an attribute.
28702 fprintf(outfile, "%-22.17e ", pointloop[3 + i]);
28703 }
28704 fprintf(outfile, "\n");
28705 } else {
28706 for (i = 0; i < nextras; i++) {
28707 // Output an attribute.
28708 out->pointattributelist[attribindex++] = pointloop[3 + i];
28709 }
28710 }
28711 pointloop = pointtraverse();
28712 }
28713
28714 if (out == (tetgenio *) NULL) {
28715 fprintf(outfile, "# Generated by %s\n", b->commandline);
28716 fclose(outfile);
28717 }
28718 }
28719
28720 ///////////////////////////////////////////////////////////////////////////////
28721 // //
28722 // outelements() Output the tetrahedra to an .ele file or a tetgenio //
28723 // structure. //
28724 // //
28725 ///////////////////////////////////////////////////////////////////////////////
28726
28727 void tetgenmesh::outelements(tetgenio* out)
28728 {
28729 FILE *outfile;
28730 char outelefilename[FILENAMESIZE];
28731 tetrahedron* tptr;
28732 int *tlist;
28733 REAL *talist;
28734 int firstindex, shift;
28735 int pointindex;
28736 int attribindex;
28737 point p1, p2, p3, p4;
28738 point *extralist;
28739 int elementnumber;
28740 int eextras;
28741 int i;
28742
28743 if (out == (tetgenio *) NULL) {
28744 strcpy(outelefilename, b->outfilename);
28745 strcat(outelefilename, ".ele");
28746 }
28747
28748 if (!b->quiet) {
28749 if (out == (tetgenio *) NULL) {
28750 printf("Writing %s.\n", outelefilename);
28751 } else {
28752 printf("Writing elements.\n");
28753 }
28754 }
28755
28756 // Avoid compile warnings.
28757 outfile = (FILE *) NULL;
28758 tlist = (int *) NULL;
28759 talist = (double *) NULL;
28760 pointindex = attribindex = 0;
28761
28762 eextras = in->numberoftetrahedronattributes;
28763 if (out == (tetgenio *) NULL) {
28764 outfile = fopen(outelefilename, "w");
28765 if (outfile == (FILE *) NULL) {
28766 printf("File I/O Error: Cannot create file %s.\n", outelefilename);
28767 terminatetetgen(1);
28768 }
28769 // Number of tetras, points per tetra, attributes per tetra.
28770 fprintf(outfile, "%ld %d %d\n", tetrahedrons->items,
28771 b->order == 1 ? 4 : 10, eextras);
28772 } else {
28773 // Allocate memory for output tetrahedra.
28774 out->tetrahedronlist = new int[tetrahedrons->items *
28775 (b->order == 1 ? 4 : 10)];
28776 if (out->tetrahedronlist == (int *) NULL) {
28777 printf("Error: Out of memory.\n");
28778 terminatetetgen(1);
28779 }
28780 // Allocate memory for output tetrahedron attributes if necessary.
28781 if (eextras > 0) {
28782 out->tetrahedronattributelist = new REAL[tetrahedrons->items * eextras];
28783 if (out->tetrahedronattributelist == (REAL *) NULL) {
28784 printf("Error: Out of memory.\n");
28785 terminatetetgen(1);
28786 }
28787 }
28788 out->numberoftetrahedra = tetrahedrons->items;
28789 out->numberofcorners = b->order == 1 ? 4 : 10;
28790 out->numberoftetrahedronattributes = eextras;
28791 tlist = out->tetrahedronlist;
28792 talist = out->tetrahedronattributelist;
28793 pointindex = 0;
28794 attribindex = 0;
28795 }
28796
28797 // Determine the first index (0 or 1).
28798 firstindex = b->zeroindex ? 0 : in->firstnumber;
28799 shift = 0; // Default no shiftment.
28800 if ((in->firstnumber == 1) && (firstindex == 0)) {
28801 shift = 1; // Shift the output indices by 1.
28802 }
28803
28804 tetrahedrons->traversalinit();
28805 tptr = tetrahedrontraverse();
28806 elementnumber = firstindex; // in->firstnumber;
28807 while (tptr != (tetrahedron *) NULL) {
28808 p1 = (point) tptr[4];
28809 p2 = (point) tptr[5];
28810 p3 = (point) tptr[6];
28811 p4 = (point) tptr[7];
28812 if (out == (tetgenio *) NULL) {
28813 // Tetrahedron number, indices for four points.
28814 fprintf(outfile, "%5d %5d %5d %5d %5d", elementnumber,
28815 pointmark(p1) - shift, pointmark(p2) - shift,
28816 pointmark(p3) - shift, pointmark(p4) - shift);
28817 if (b->order == 2) {
28818 extralist = (point *) tptr[highorderindex];
28819 // Tetrahedron number, indices for four points plus six extra points.
28820 fprintf(outfile, " %5d %5d %5d %5d %5d %5d",
28821 pointmark(extralist[0]) - shift, pointmark(extralist[1]) - shift,
28822 pointmark(extralist[2]) - shift, pointmark(extralist[3]) - shift,
28823 pointmark(extralist[4]) - shift, pointmark(extralist[5]) - shift);
28824 }
28825 for (i = 0; i < eextras; i++) {
28826 fprintf(outfile, " %.17g", elemattribute(tptr, i));
28827 }
28828 fprintf(outfile, "\n");
28829 } else {
28830 tlist[pointindex++] = pointmark(p1) - shift;
28831 tlist[pointindex++] = pointmark(p2) - shift;
28832 tlist[pointindex++] = pointmark(p3) - shift;
28833 tlist[pointindex++] = pointmark(p4) - shift;
28834 if (b->order == 2) {
28835 extralist = (point *) tptr[highorderindex];
28836 tlist[pointindex++] = pointmark(extralist[0]) - shift;
28837 tlist[pointindex++] = pointmark(extralist[1]) - shift;
28838 tlist[pointindex++] = pointmark(extralist[2]) - shift;
28839 tlist[pointindex++] = pointmark(extralist[3]) - shift;
28840 tlist[pointindex++] = pointmark(extralist[4]) - shift;
28841 tlist[pointindex++] = pointmark(extralist[5]) - shift;
28842 }
28843 for (i = 0; i < eextras; i++) {
28844 talist[attribindex++] = elemattribute(tptr, i);
28845 }
28846 }
28847 if (b->neighout) {
28848 // Remember the index of this element.
28849 * (int *) (tptr + elemmarkerindex) = elementnumber;
28850 }
28851 tptr = tetrahedrontraverse();
28852 elementnumber++;
28853 }
28854 if (b->neighout) {
28855 // Set the outside element marker.
28856 * (int *) (dummytet + elemmarkerindex) = -1;
28857 }
28858
28859 if (out == (tetgenio *) NULL) {
28860 fprintf(outfile, "# Generated by %s\n", b->commandline);
28861 fclose(outfile);
28862 }
28863 }
28864
28865 ///////////////////////////////////////////////////////////////////////////////
28866 // //
28867 // outfaces() Output all faces to a .face file or a tetgenio structure. //
28868 // //
28869 // This routines outputs all triangular faces (including outer boundary //
28870 // faces and inner faces) of this mesh. //
28871 // //
28872 ///////////////////////////////////////////////////////////////////////////////
28873
28874 void tetgenmesh::outfaces(tetgenio* out)
28875 {
28876 FILE *outfile;
28877 char facefilename[FILENAMESIZE];
28878 int *elist;
28879 int *emlist;
28880 int index;
28881 triface tface, tsymface;
28882 face checkmark;
28883 point torg, tdest, tapex;
28884 long faces;
28885 int bmark, faceid, marker;
28886 int firstindex, shift;
28887 int facenumber;
28888
28889 if (out == (tetgenio *) NULL) {
28890 strcpy(facefilename, b->outfilename);
28891 strcat(facefilename, ".face");
28892 }
28893
28894 if (!b->quiet) {
28895 if (out == (tetgenio *) NULL) {
28896 printf("Writing %s.\n", facefilename);
28897 } else {
28898 printf("Writing faces.\n");
28899 }
28900 }
28901
28902 // Avoid compile warnings.
28903 outfile = (FILE *) NULL;
28904 elist = (int *) NULL;
28905 emlist = (int *) NULL;
28906 index = marker = 0;
28907
28908 faces = (4l * tetrahedrons->items + hullsize) / 2l;
28909 bmark = !b->nobound && in->facetmarkerlist;
28910
28911 if (out == (tetgenio *) NULL) {
28912 outfile = fopen(facefilename, "w");
28913 if (outfile == (FILE *) NULL) {
28914 printf("File I/O Error: Cannot create file %s.\n", facefilename);
28915 terminatetetgen(1);
28916 }
28917 fprintf(outfile, "%ld %d\n", faces, bmark);
28918 } else {
28919 // Allocate memory for 'trifacelist'.
28920 out->trifacelist = new int[faces * 3];
28921 if (out->trifacelist == (int *) NULL) {
28922 printf("Error: Out of memory.\n");
28923 terminatetetgen(1);
28924 }
28925 // Allocate memory for 'trifacemarkerlist' if necessary.
28926 if (bmark) {
28927 out->trifacemarkerlist = new int[faces];
28928 if (out->trifacemarkerlist == (int *) NULL) {
28929 printf("Error: Out of memory.\n");
28930 terminatetetgen(1);
28931 }
28932 }
28933 out->numberoftrifaces = faces;
28934 elist = out->trifacelist;
28935 emlist = out->trifacemarkerlist;
28936 index = 0;
28937 }
28938
28939 // Determine the first index (0 or 1).
28940 firstindex = b->zeroindex ? 0 : in->firstnumber;
28941 shift = 0; // Default no shiftment.
28942 if ((in->firstnumber == 1) && (firstindex == 0)) {
28943 shift = 1; // Shift the output indices by 1.
28944 }
28945
28946 tetrahedrons->traversalinit();
28947 tface.tet = tetrahedrontraverse();
28948 facenumber = firstindex; // in->firstnumber;
28949 // To loop over the set of faces, loop over all tetrahedra, and look at
28950 // the four faces of each one. If there isn't another tetrahedron
28951 // adjacent to this face, operate on the face. If there is another
28952 // adjacent tetrahedron, operate on the face only if the current
28953 // tetrahedron has a smaller pointer than its neighbor. This way, each
28954 // face is considered only once.
28955 while (tface.tet != (tetrahedron *) NULL) {
28956 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
28957 sym(tface, tsymface);
28958 if ((tsymface.tet == dummytet) || (tface.tet < tsymface.tet)) {
28959 torg = org(tface);
28960 tdest = dest(tface);
28961 tapex = apex(tface);
28962 if (bmark) {
28963 // Get the boundary marker of this face. If it is an inner face,
28964 // it has no boundary marker, set it be zero.
28965 if (b->useshelles) {
28966 // Shell face is used.
28967 tspivot(tface, checkmark);
28968 if (checkmark.sh == dummysh) {
28969 marker = 0; // It is an inner face.
28970 } else {
28971 faceid = shellmark(checkmark) - 1;
28972 marker = in->facetmarkerlist[faceid];
28973 }
28974 } else {
28975 // Shell face is not used, only distinguish outer and inner face.
28976 marker = tsymface.tet != dummytet ? 1 : 0;
28977 }
28978 }
28979 if (out == (tetgenio *) NULL) {
28980 // Face number, indices of three vertices.
28981 fprintf(outfile, "%5d %4d %4d %4d", facenumber,
28982 pointmark(torg) - shift, pointmark(tdest) - shift,
28983 pointmark(tapex) - shift);
28984 if (bmark) {
28985 // Output a boundary marker.
28986 fprintf(outfile, " %d", marker);
28987 }
28988 fprintf(outfile, "\n");
28989 } else {
28990 // Output indices of three vertices.
28991 elist[index++] = pointmark(torg) - shift;
28992 elist[index++] = pointmark(tdest) - shift;
28993 elist[index++] = pointmark(tapex) - shift;
28994 if (bmark) {
28995 emlist[facenumber - in->firstnumber] = marker;
28996 }
28997 }
28998 facenumber++;
28999 }
29000 }
29001 tface.tet = tetrahedrontraverse();
29002 }
29003
29004 if (out == (tetgenio *) NULL) {
29005 fprintf(outfile, "# Generated by %s\n", b->commandline);
29006 fclose(outfile);
29007 }
29008 }
29009
29010 ///////////////////////////////////////////////////////////////////////////////
29011 // //
29012 // outhullfaces() Output outer boundary faces to a .face file or a //
29013 // tetgenio structure. //
29014 // //
29015 // The normal of each face is arranged to point inside of the domain (use //
29016 // right-hand rule). This routines will outputs convex hull faces if the //
29017 // mesh is a Delaunay tetrahedralization. //
29018 // //
29019 ///////////////////////////////////////////////////////////////////////////////
29020
29021 void tetgenmesh::outhullfaces(tetgenio* out)
29022 {
29023 FILE *outfile;
29024 char facefilename[FILENAMESIZE];
29025 int *elist;
29026 int index;
29027 triface tface, tsymface;
29028 face checkmark;
29029 point torg, tdest, tapex;
29030 int firstindex, shift;
29031 int facenumber;
29032
29033 if (out == (tetgenio *) NULL) {
29034 strcpy(facefilename, b->outfilename);
29035 strcat(facefilename, ".face");
29036 }
29037
29038 if (!b->quiet) {
29039 if (out == (tetgenio *) NULL) {
29040 printf("Writing %s.\n", facefilename);
29041 } else {
29042 printf("Writing faces.\n");
29043 }
29044 }
29045
29046 // Avoid compile warnings.
29047 outfile = (FILE *) NULL;
29048 elist = (int *) NULL;
29049 index = 0;
29050
29051 if (out == (tetgenio *) NULL) {
29052 outfile = fopen(facefilename, "w");
29053 if (outfile == (FILE *) NULL) {
29054 printf("File I/O Error: Cannot create file %s.\n", facefilename);
29055 terminatetetgen(1);
29056 }
29057 fprintf(outfile, "%ld 0\n", hullsize);
29058 } else {
29059 // Allocate memory for 'trifacelist'.
29060 out->trifacelist = new int[hullsize * 3];
29061 if (out->trifacelist == (int *) NULL) {
29062 printf("Error: Out of memory.\n");
29063 terminatetetgen(1);
29064 }
29065 out->numberoftrifaces = hullsize;
29066 elist = out->trifacelist;
29067 index = 0;
29068 }
29069
29070 // Determine the first index (0 or 1).
29071 firstindex = b->zeroindex ? 0 : in->firstnumber;
29072 shift = 0; // Default no shiftment.
29073 if ((in->firstnumber == 1) && (firstindex == 0)) {
29074 shift = 1; // Shift the output indices by 1.
29075 }
29076
29077 tetrahedrons->traversalinit();
29078 tface.tet = tetrahedrontraverse();
29079 facenumber = firstindex; // in->firstnumber;
29080 // To loop over the set of hull faces, loop over all tetrahedra, and look
29081 // at the four faces of each one. If there isn't another tetrahedron
29082 // adjacent to this face, operate on the face.
29083 while (tface.tet != (tetrahedron *) NULL) {
29084 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
29085 sym(tface, tsymface);
29086 if (tsymface.tet == dummytet) {
29087 torg = org(tface);
29088 tdest = dest(tface);
29089 tapex = apex(tface);
29090 if (out == (tetgenio *) NULL) {
29091 // Face number, indices of three vertices.
29092 fprintf(outfile, "%5d %4d %4d %4d", facenumber,
29093 pointmark(torg) - shift, pointmark(tdest) - shift,
29094 pointmark(tapex) - shift);
29095 fprintf(outfile, "\n");
29096 } else {
29097 // Output indices of three vertices.
29098 elist[index++] = pointmark(torg) - shift;
29099 elist[index++] = pointmark(tdest) - shift;
29100 elist[index++] = pointmark(tapex) - shift;
29101 }
29102 facenumber++;
29103 }
29104 }
29105 tface.tet = tetrahedrontraverse();
29106 }
29107
29108 if (out == (tetgenio *) NULL) {
29109 fprintf(outfile, "# Generated by %s\n", b->commandline);
29110 fclose(outfile);
29111 }
29112 }
29113
29114 ///////////////////////////////////////////////////////////////////////////////
29115 // //
29116 // outsubfaces() Output subfaces (i.e. boundary faces) to a .face file or //
29117 // a tetgenio structure. //
29118 // //
29119 // The boundary faces are exist in 'subfaces'. For listing triangle vertices //
29120 // in the same sense for all triangles in the mesh, the direction determined //
29121 // by right-hand rule is pointer to the inside of the volume. //
29122 // //
29123 ///////////////////////////////////////////////////////////////////////////////
29124
29125 void tetgenmesh::outsubfaces(tetgenio* out)
29126 {
29127 FILE *outfile;
29128 char facefilename[FILENAMESIZE];
29129 int *elist;
29130 int *emlist;
29131 int index;
29132 triface abuttingtet;
29133 face faceloop;
29134 point torg, tdest, tapex;
29135 int bmark, faceid, marker;
29136 int firstindex, shift;
29137 int neigh1, neigh2;
29138 int facenumber;
29139
29140 if (out == (tetgenio *) NULL) {
29141 strcpy(facefilename, b->outfilename);
29142 strcat(facefilename, ".face");
29143 }
29144
29145 if (!b->quiet) {
29146 if (out == (tetgenio *) NULL) {
29147 printf("Writing %s.\n", facefilename);
29148 } else {
29149 printf("Writing faces.\n");
29150 }
29151 }
29152
29153 // Avoid compile warnings.
29154 outfile = (FILE *) NULL;
29155 elist = (int *) NULL;
29156 emlist = (int *) NULL;
29157 index = marker = 0;
29158 neigh1 = neigh2 = 0;
29159
29160 bmark = !b->nobound && in->facetmarkerlist;
29161
29162 if (out == (tetgenio *) NULL) {
29163 outfile = fopen(facefilename, "w");
29164 if (outfile == (FILE *) NULL) {
29165 printf("File I/O Error: Cannot create file %s.\n", facefilename);
29166 terminatetetgen(1);
29167 }
29168 // Number of subfaces.
29169 fprintf(outfile, "%ld %d\n", subfaces->items, bmark);
29170 } else {
29171 // Allocate memory for 'trifacelist'.
29172 out->trifacelist = new int[subfaces->items * 3];
29173 if (out->trifacelist == (int *) NULL) {
29174 printf("Error: Out of memory.\n");
29175 terminatetetgen(1);
29176 }
29177 if (bmark) {
29178 // Allocate memory for 'trifacemarkerlist'.
29179 out->trifacemarkerlist = new int[subfaces->items];
29180 if (out->trifacemarkerlist == (int *) NULL) {
29181 printf("Error: Out of memory.\n");
29182 terminatetetgen(1);
29183 }
29184 }
29185 if (b->neighout > 1) {
29186 // '-nn' switch.
29187 out->adjtetlist = new int[subfaces->items * 2];
29188 if (out->adjtetlist == (int *) NULL) {
29189 printf("Error: Out of memory.\n");
29190 terminatetetgen(1);
29191 }
29192 }
29193 out->numberoftrifaces = subfaces->items;
29194 elist = out->trifacelist;
29195 emlist = out->trifacemarkerlist;
29196 index = 0;
29197 }
29198
29199 // Determine the first index (0 or 1).
29200 firstindex = b->zeroindex ? 0 : in->firstnumber;
29201 shift = 0; // Default no shiftment.
29202 if ((in->firstnumber == 1) && (firstindex == 0)) {
29203 shift = 1; // Shift the output indices by 1.
29204 }
29205
29206 subfaces->traversalinit();
29207 faceloop.sh = shellfacetraverse(subfaces);
29208 facenumber = firstindex; // in->firstnumber;
29209 while (faceloop.sh != (shellface *) NULL) {
29210 stpivot(faceloop, abuttingtet);
29211 if (abuttingtet.tet == dummytet) {
29212 sesymself(faceloop);
29213 stpivot(faceloop, abuttingtet);
29214 }
29215 if (abuttingtet.tet != dummytet) {
29216 // If there is a tetrahedron containing this subface, orient it so
29217 // that the normal of this face points to inside of the volume by
29218 // right-hand rule.
29219 adjustedgering(abuttingtet, CCW);
29220 torg = org(abuttingtet);
29221 tdest = dest(abuttingtet);
29222 tapex = apex(abuttingtet);
29223 } else {
29224 // This may happen when only a surface mesh be generated.
29225 torg = sorg(faceloop);
29226 tdest = sdest(faceloop);
29227 tapex = sapex(faceloop);
29228 }
29229 if (bmark) {
29230 faceid = shellmark(faceloop) - 1;
29231 marker = in->facetmarkerlist[faceid];
29232 }
29233 if (b->neighout > 1) {
29234 // '-nn' switch. Output adjacent tets indices.
29235 neigh1 = -1;
29236 stpivot(faceloop, abuttingtet);
29237 if (abuttingtet.tet != dummytet) {
29238 neigh1 = * (int *)(abuttingtet.tet + elemmarkerindex);
29239 }
29240 neigh2 = -1;
29241 sesymself(faceloop);
29242 stpivot(faceloop, abuttingtet);
29243 if (abuttingtet.tet != dummytet) {
29244 neigh2 = * (int *)(abuttingtet.tet + elemmarkerindex);
29245 }
29246 }
29247 if (out == (tetgenio *) NULL) {
29248 fprintf(outfile, "%5d %4d %4d %4d", facenumber,
29249 pointmark(torg) - shift, pointmark(tdest) - shift,
29250 pointmark(tapex) - shift);
29251 if (bmark) {
29252 fprintf(outfile, " %d", marker);
29253 }
29254 if (b->neighout > 1) {
29255 fprintf(outfile, " %5d %5d", neigh1, neigh2);
29256 }
29257 fprintf(outfile, "\n");
29258 } else {
29259 // Output three vertices of this face;
29260 elist[index++] = pointmark(torg) - shift;
29261 elist[index++] = pointmark(tdest) - shift;
29262 elist[index++] = pointmark(tapex) - shift;
29263 if (bmark) {
29264 emlist[facenumber - in->firstnumber] = marker;
29265 }
29266 if (b->neighout > 1) {
29267 out->adjtetlist[(facenumber - in->firstnumber) * 2] = neigh1;
29268 out->adjtetlist[(facenumber - in->firstnumber) * 2 + 1] = neigh2;
29269 }
29270 }
29271 facenumber++;
29272 faceloop.sh = shellfacetraverse(subfaces);
29273 }
29274
29275 if (out == (tetgenio *) NULL) {
29276 fprintf(outfile, "# Generated by %s\n", b->commandline);
29277 fclose(outfile);
29278 }
29279 }
29280
29281 ///////////////////////////////////////////////////////////////////////////////
29282 // //
29283 // outsubsegments() Output segments to a .edge file or a structure. //
29284 // //
29285 ///////////////////////////////////////////////////////////////////////////////
29286
29287 void tetgenmesh::outsubsegments(tetgenio* out)
29288 {
29289 FILE *outfile;
29290 char edgefilename[FILENAMESIZE];
29291 int *elist;
29292 int index;
29293 face edgeloop;
29294 point torg, tdest;
29295 int firstindex, shift;
29296 int edgenumber;
29297
29298 if (out == (tetgenio *) NULL) {
29299 strcpy(edgefilename, b->outfilename);
29300 strcat(edgefilename, ".edge");
29301 }
29302
29303 if (!b->quiet) {
29304 if (out == (tetgenio *) NULL) {
29305 printf("Writing %s.\n", edgefilename);
29306 } else {
29307 printf("Writing faces.\n");
29308 }
29309 }
29310
29311 // Avoid compile warnings.
29312 outfile = (FILE *) NULL;
29313 elist = (int *) NULL;
29314 index = 0;
29315
29316 if (out == (tetgenio *) NULL) {
29317 outfile = fopen(edgefilename, "w");
29318 if (outfile == (FILE *) NULL) {
29319 printf("File I/O Error: Cannot create file %s.\n", edgefilename);
29320 terminatetetgen(1);
29321 }
29322 // Number of subsegments.
29323 fprintf(outfile, "%ld\n", subsegs->items);
29324 } else {
29325 // Allocate memory for 'edgelist'.
29326 out->edgelist = new int[subsegs->items * 2];
29327 if (out->edgelist == (int *) NULL) {
29328 printf("Error: Out of memory.\n");
29329 terminatetetgen(1);
29330 }
29331 out->numberofedges = subsegs->items;
29332 elist = out->edgelist;
29333 index = 0;
29334 }
29335
29336 // Determine the first index (0 or 1).
29337 firstindex = b->zeroindex ? 0 : in->firstnumber;
29338 shift = 0; // Default no shiftment.
29339 if ((in->firstnumber == 1) && (firstindex == 0)) {
29340 shift = 1; // Shift the output indices by 1.
29341 }
29342
29343 subsegs->traversalinit();
29344 edgeloop.sh = shellfacetraverse(subsegs);
29345 edgenumber = firstindex; // in->firstnumber;
29346 while (edgeloop.sh != (shellface *) NULL) {
29347 torg = sorg(edgeloop);
29348 tdest = sdest(edgeloop);
29349 if (out == (tetgenio *) NULL) {
29350 fprintf(outfile, "%5d %4d %4d\n", edgenumber,
29351 pointmark(torg) - shift, pointmark(tdest) - shift);
29352 } else {
29353 // Output three vertices of this face;
29354 elist[index++] = pointmark(torg) - shift;
29355 elist[index++] = pointmark(tdest) - shift;
29356 }
29357 edgenumber++;
29358 edgeloop.sh = shellfacetraverse(subsegs);
29359 }
29360
29361 if (out == (tetgenio *) NULL) {
29362 fprintf(outfile, "# Generated by %s\n", b->commandline);
29363 fclose(outfile);
29364 }
29365 }
29366
29367 ///////////////////////////////////////////////////////////////////////////////
29368 // //
29369 // outneighbors() Output tet neighbors to a .neigh file or a structure. //
29370 // //
29371 ///////////////////////////////////////////////////////////////////////////////
29372
29373 void tetgenmesh::outneighbors(tetgenio* out)
29374 {
29375 FILE *outfile;
29376 char neighborfilename[FILENAMESIZE];
29377 int *nlist;
29378 int index;
29379 triface tetloop, tetsym;
29380 int neighbor1, neighbor2, neighbor3, neighbor4;
29381 int firstindex;
29382 int elementnumber;
29383
29384 if (out == (tetgenio *) NULL) {
29385 strcpy(neighborfilename, b->outfilename);
29386 strcat(neighborfilename, ".neigh");
29387 }
29388
29389 if (!b->quiet) {
29390 if (out == (tetgenio *) NULL) {
29391 printf("Writing %s.\n", neighborfilename);
29392 } else {
29393 printf("Writing neighbors.\n");
29394 }
29395 }
29396
29397 // Avoid compile warnings.
29398 outfile = (FILE *) NULL;
29399 nlist = (int *) NULL;
29400 index = 0;
29401
29402 if (out == (tetgenio *) NULL) {
29403 outfile = fopen(neighborfilename, "w");
29404 if (outfile == (FILE *) NULL) {
29405 printf("File I/O Error: Cannot create file %s.\n", neighborfilename);
29406 terminatetetgen(1);
29407 }
29408 // Number of tetrahedra, four faces per tetrahedron.
29409 fprintf(outfile, "%ld %d\n", tetrahedrons->items, 4);
29410 } else {
29411 // Allocate memory for 'neighborlist'.
29412 out->neighborlist = new int[tetrahedrons->items * 4];
29413 if (out->neighborlist == (int *) NULL) {
29414 printf("Error: Out of memory.\n");
29415 terminatetetgen(1);
29416 }
29417 nlist = out->neighborlist;
29418 index = 0;
29419 }
29420
29421 // Determine the first index (0 or 1).
29422 firstindex = b->zeroindex ? 0 : in->firstnumber;
29423
29424 tetrahedrons->traversalinit();
29425 tetloop.tet = tetrahedrontraverse();
29426 elementnumber = firstindex; // in->firstnumber;
29427 while (tetloop.tet != (tetrahedron *) NULL) {
29428 tetloop.loc = 2;
29429 sym(tetloop, tetsym);
29430 neighbor1 = * (int *) (tetsym.tet + elemmarkerindex);
29431 tetloop.loc = 3;
29432 sym(tetloop, tetsym);
29433 neighbor2 = * (int *) (tetsym.tet + elemmarkerindex);
29434 tetloop.loc = 1;
29435 sym(tetloop, tetsym);
29436 neighbor3 = * (int *) (tetsym.tet + elemmarkerindex);
29437 tetloop.loc = 0;
29438 sym(tetloop, tetsym);
29439 neighbor4 = * (int *) (tetsym.tet + elemmarkerindex);
29440 if (out == (tetgenio *) NULL) {
29441 // Tetrahedra number, neighboring tetrahedron numbers.
29442 fprintf(outfile, "%4d %4d %4d %4d %4d\n", elementnumber,
29443 neighbor1, neighbor2, neighbor3, neighbor4);
29444 } else {
29445 nlist[index++] = neighbor1;
29446 nlist[index++] = neighbor2;
29447 nlist[index++] = neighbor3;
29448 nlist[index++] = neighbor4;
29449 }
29450 tetloop.tet = tetrahedrontraverse();
29451 elementnumber++;
29452 }
29453
29454 if (out == (tetgenio *) NULL) {
29455 fprintf(outfile, "# Generated by %s\n", b->commandline);
29456 fclose(outfile);
29457 }
29458 }
29459
29460 ///////////////////////////////////////////////////////////////////////////////
29461 // //
29462 // outpbcnodes() Output pbc node pairs to a .pbc file or a structure. //
29463 // //
29464 ///////////////////////////////////////////////////////////////////////////////
29465
29466 void tetgenmesh::outpbcnodes(tetgenio* out)
29467 {
29468 FILE *outfile;
29469 char pbcfilename[FILENAMESIZE];
29470 list *ptpairlist;
29471 tetgenio::pbcgroup *pgi, *pgo;
29472 pbcdata *pd;
29473 face faceloop;
29474 face checkseg, symseg;
29475 point *ptpair, pa, pb;
29476 enum locateresult loc;
29477 REAL sympt[3], d1, d2;
29478 int *worklist;
29479 int firstindex, shift;
29480 int index, idx;
29481 int i, j, k, l;
29482
29483 if (out == (tetgenio *) NULL) {
29484 strcpy(pbcfilename, b->outfilename);
29485 strcat(pbcfilename, ".pbc");
29486 }
29487
29488 if (!b->quiet) {
29489 if (out == (tetgenio *) NULL) {
29490 printf("Writing %s.\n", pbcfilename);
29491 } else {
29492 printf("Writing pbc nodes.\n");
29493 }
29494 }
29495
29496 // Avoid compilation warnings.
29497 outfile = (FILE *) NULL;
29498 pgo = (tetgenio::pbcgroup *) NULL;
29499 index = 0;
29500
29501 if (out == (tetgenio *) NULL) {
29502 outfile = fopen(pbcfilename, "w");
29503 if (outfile == (FILE *) NULL) {
29504 printf("File I/O Error: Cannot create file %s.\n", pbcfilename);
29505 terminatetetgen(1);
29506 }
29507 // Number of pbc groups.
29508 fprintf(outfile, "# number of PBCs.\n");
29509 fprintf(outfile, "%d\n\n", in->numberofpbcgroups);
29510 } else {
29511 out->numberofpbcgroups = in->numberofpbcgroups;
29512 // Allocate memory for 'out->pbcgrouplist'.
29513 out->pbcgrouplist = new tetgenio::pbcgroup[in->numberofpbcgroups];
29514 // (Next line was a bug, reported by Murry Nigel).
29515 if (out->pbcgrouplist == (tetgenio::pbcgroup *) NULL) {
29516 printf("Error: Out of memory.\n");
29517 terminatetetgen(1);
29518 }
29519 }
29520
29521 ptpairlist = new list(2 * sizeof(point *), NULL, 256);
29522 worklist = new int[points->items + 1];
29523 for (i = 0; i < points->items + 1; i++) worklist[i] = 0;
29524
29525 // Determine the first index (0 or 1).
29526 firstindex = b->zeroindex ? 0 : in->firstnumber;
29527 shift = 0; // Default no shiftment.
29528 if ((in->firstnumber == 1) && (firstindex == 0)) {
29529 shift = 1; // Shift the output indices by 1.
29530 }
29531
29532 for (i = 0; i < in->numberofpbcgroups; i++) {
29533 // Group i.
29534 pgi = &(in->pbcgrouplist[i]);
29535 if (out == (tetgenio *) NULL) {
29536 fprintf(outfile, "# PBC %d\n", in->firstnumber + i);
29537 // Output facet markers.
29538 fprintf(outfile, "%d %d\n", pgi->fmark1, pgi->fmark2);
29539 // Output transformation matrix.
29540 fprintf(outfile, "[\n");
29541 for (j = 0; j < 4; j++) {
29542 fprintf(outfile, " %.12g %.12g %.12g %.12g\n", pgi->transmat[j][0],
29543 pgi->transmat[j][1], pgi->transmat[j][2], pgi->transmat[j][3]);
29544 }
29545 fprintf(outfile, "]\n");
29546 } else {
29547 pgo = &(out->pbcgrouplist[i]);
29548 // Copy data from pgi to pgo.
29549 pgo->fmark1 = pgi->fmark1;
29550 pgo->fmark2 = pgi->fmark2;
29551 for (j = 0; j < 4; j++) {
29552 for (k = 0; k < 4; k++) pgo->transmat[j][k] = pgi->transmat[j][k];
29553 }
29554 }
29555
29556 // Find the point pairs of group i.
29557 subfaces->traversalinit();
29558 faceloop.sh = shellfacetraverse(subfaces);
29559 while (faceloop.sh != (shellface *) NULL) {
29560 if (shellpbcgroup(faceloop) == i) {
29561 // It is in group i. Operate on it if it has pgi->fmark1.
29562 idx = shellmark(faceloop) - 1;
29563 if (in->facetmarkerlist[idx] == pgi->fmark1) {
29564 // Loop three edges of the subface.
29565 for (j = 0; j < 3; j++) {
29566 sspivot(faceloop, checkseg);
29567 // Loop two vertices of the edge.
29568 for (k = 0; k < 2; k++) {
29569 if (k == 0) pa = sorg(faceloop);
29570 else pa = sdest(faceloop);
29571 if (worklist[pointmark(pa)] == 0) {
29572 pb = (point) NULL;
29573 if (checkseg.sh != dummysh) {
29574 // pa is on a segment. Find pb.
29575 // Find the incident pbcgroup of checkseg.
29576 idx = shellmark(checkseg) - 1;
29577 for (l = idx2segpglist[idx]; l < idx2segpglist[idx + 1];
29578 l++) {
29579 pd = (pbcdata *)(* segpbcgrouptable)[segpglist[l]];
29580 if (((pd->fmark[0] == pgi->fmark1) &&
29581 (pd->fmark[1] == pgi->fmark2)) ||
29582 ((pd->fmark[0] == pgi->fmark2) &&
29583 (pd->fmark[1] == pgi->fmark1))) break;
29584 }
29585 #ifdef SELF_CHECK
29586 assert(l < idx2segpglist[idx + 1]);
29587 #endif
29588 loc = getsegpbcsympoint(pa, &checkseg, sympt, &symseg,
29589 segpglist[l]);
29590 if (loc != ONVERTEX) {
29591 // Not found a match point! It may be caused by the
29592 // pair of input vertices don't have enough digits.
29593 // Choose a near vertex.
29594 d1 = distance(sympt, sorg(symseg));
29595 d2 = distance(sympt, sdest(symseg));
29596 if (d1 > d2) sesymself(symseg);
29597 }
29598 pb = sorg(symseg);
29599 } else {
29600 // Operate on pa if it is inside the facet.
29601 if (pointtype(pa) == FREESUBVERTEX) {
29602 pb = point2pbcpt(pa);
29603 }
29604 }
29605 if (pb != (point) NULL) {
29606 // Add the pair (pa, pb) into list.
29607 ptpair = (point *) ptpairlist->append(NULL);
29608 ptpair[0] = pa;
29609 ptpair[1] = pb;
29610 // Mark pa (avoid to operate on it later).
29611 worklist[pointmark(pa)] = 1;
29612 }
29613 }
29614 }
29615 // Get the next edge.
29616 senextself(faceloop);
29617 }
29618 }
29619 }
29620 faceloop.sh = shellfacetraverse(subfaces);
29621 }
29622
29623 // Output the list of pbc points.
29624 if (out == (tetgenio *) NULL) {
29625 fprintf(outfile, "%d\n", ptpairlist->len());
29626 } else {
29627 pgo->numberofpointpairs = ptpairlist->len();
29628 pgo->pointpairlist = new int[pgo->numberofpointpairs * 2];
29629 index = 0;
29630 }
29631 for (j = 0; j < ptpairlist->len(); j++) {
29632 ptpair = (point *)(* ptpairlist)[j];
29633 pa = ptpair[0];
29634 pb = ptpair[1];
29635 if (out == (tetgenio *) NULL) {
29636 fprintf(outfile, " %4d %4d\n", pointmark(pa) - shift,
29637 pointmark(pb) - shift);
29638 } else {
29639 pgo->pointpairlist[index++] = pointmark(pa) - shift;
29640 pgo->pointpairlist[index++] = pointmark(pb) - shift;
29641 }
29642 // Unmark pa.
29643 worklist[pointmark(pa)] = 0;
29644 }
29645 if (out == (tetgenio *) NULL) {
29646 fprintf(outfile, "\n");
29647 }
29648 ptpairlist->clear();
29649 }
29650
29651 delete [] worklist;
29652 delete ptpairlist;
29653
29654 if (out == (tetgenio *) NULL) {
29655 fprintf(outfile, "# Generated by %s\n", b->commandline);
29656 fclose(outfile);
29657 }
29658 }
29659
29660 ///////////////////////////////////////////////////////////////////////////////
29661 // //
29662 // outsmesh() Write surface mesh to a .smesh file, which can be read and //
29663 // tetrahedralized by TetGen. //
29664 // //
29665 // You can specify a filename (without suffix) in 'smfilename'. If you don't //
29666 // supply a filename (let smfilename be NULL), the default name stored in //
29667 // 'tetgenbehavior' will be used. //
29668 // //
29669 ///////////////////////////////////////////////////////////////////////////////
29670
29671 void tetgenmesh::outsmesh(char* smfilename)
29672 {
29673 FILE *outfile;
29674 char nodfilename[FILENAMESIZE];
29675 char smefilename[FILENAMESIZE];
29676 face faceloop;
29677 point p1, p2, p3;
29678 int firstindex, shift;
29679 int bmark;
29680 int faceid, marker;
29681 int i;
29682
29683 if (smfilename != (char *) NULL && smfilename[0] != '\0') {
29684 strcpy(smefilename, smfilename);
29685 } else if (b->outfilename[0] != '\0') {
29686 strcpy(smefilename, b->outfilename);
29687 } else {
29688 strcpy(smefilename, "unnamed");
29689 }
29690 strcpy(nodfilename, smefilename);
29691 strcat(smefilename, ".smesh");
29692 strcat(nodfilename, ".node");
29693
29694 if (!b->quiet) {
29695 printf("Writing %s.\n", smefilename);
29696 }
29697 outfile = fopen(smefilename, "w");
29698 if (outfile == (FILE *) NULL) {
29699 printf("File I/O Error: Cannot create file %s.\n", smefilename);
29700 return;
29701 }
29702
29703 // Determine the first index (0 or 1).
29704 firstindex = b->zeroindex ? 0 : in->firstnumber;
29705 shift = 0; // Default no shiftment.
29706 if ((in->firstnumber == 1) && (firstindex == 0)) {
29707 shift = 1; // Shift the output indices by 1.
29708 }
29709
29710 fprintf(outfile, "# %s. TetGen's input file.\n", smefilename);
29711 fprintf(outfile, "\n# part 1: node list.\n");
29712 fprintf(outfile, "0 3 0 0 # nodes are found in %s.\n", nodfilename);
29713
29714 marker = 0; // avoid compile warning.
29715 bmark = !b->nobound && in->facetmarkerlist;
29716
29717 fprintf(outfile, "\n# part 2: facet list.\n");
29718 // Number of facets, boundary marker.
29719 fprintf(outfile, "%ld %d\n", subfaces->items, bmark);
29720
29721 subfaces->traversalinit();
29722 faceloop.sh = shellfacetraverse(subfaces);
29723 while (faceloop.sh != (shellface *) NULL) {
29724 p1 = sorg(faceloop);
29725 p2 = sdest(faceloop);
29726 p3 = sapex(faceloop);
29727 if (bmark) {
29728 faceid = shellmark(faceloop) - 1;
29729 if (faceid >= 0) {
29730 marker = in->facetmarkerlist[faceid];
29731 } else {
29732 marker = 0; // This subface must be added manually later.
29733 }
29734 }
29735 fprintf(outfile, "3 %4d %4d %4d", pointmark(p1) - shift,
29736 pointmark(p2) - shift, pointmark(p3) - shift);
29737 if (bmark) {
29738 fprintf(outfile, " %d", marker);
29739 }
29740 fprintf(outfile, "\n");
29741 faceloop.sh = shellfacetraverse(subfaces);
29742 }
29743
29744 // Copy input holelist.
29745 fprintf(outfile, "\n# part 3: hole list.\n");
29746 fprintf(outfile, "%d\n", in->numberofholes);
29747 for (i = 0; i < in->numberofholes; i++) {
29748 fprintf(outfile, "%d %g %g %g\n", i + in->firstnumber,
29749 in->holelist[i * 3], in->holelist[i * 3 + 1],
29750 in->holelist[i * 3 + 2]);
29751 }
29752
29753 // Copy input regionlist.
29754 fprintf(outfile, "\n# part 4: region list.\n");
29755 fprintf(outfile, "%d\n", in->numberofregions);
29756 for (i = 0; i < in->numberofregions; i++) {
29757 fprintf(outfile, "%d %g %g %g %d %g\n", i + in->firstnumber,
29758 in->regionlist[i * 5], in->regionlist[i * 5 + 1],
29759 in->regionlist[i * 5 + 2], (int) in->regionlist[i * 5 + 3],
29760 in->regionlist[i * 5 + 4]);
29761 }
29762
29763 fprintf(outfile, "# Generated by %s\n", b->commandline);
29764 fclose(outfile);
29765 }
29766
29767 ///////////////////////////////////////////////////////////////////////////////
29768 // //
29769 // outmesh2medit() Write mesh to a .mesh file, which can be read and //
29770 // rendered by Medit (a free mesh viewer from INRIA). //
29771 // //
29772 // You can specify a filename (without suffix) in 'mfilename'. If you don't //
29773 // supply a filename (let mfilename be NULL), the default name stored in //
29774 // 'tetgenbehavior' will be used. The output file will have the suffix .mesh.//
29775 // //
29776 ///////////////////////////////////////////////////////////////////////////////
29777
29778 void tetgenmesh::outmesh2medit(char* mfilename)
29779 {
29780 FILE *outfile;
29781 char mefilename[FILENAMESIZE];
29782 tetrahedron* tetptr;
29783 triface tface, tsymface;
29784 face segloop, checkmark;
29785 point pointloop, p1, p2, p3, p4;
29786 long faces;
29787 int pointnumber;
29788 int i;
29789
29790 if (mfilename != (char *) NULL && mfilename[0] != '\0') {
29791 strcpy(mefilename, mfilename);
29792 } else if (b->outfilename[0] != '\0') {
29793 strcpy(mefilename, b->outfilename);
29794 } else {
29795 strcpy(mefilename, "unnamed");
29796 }
29797 strcat(mefilename, ".mesh");
29798
29799 if (!b->quiet) {
29800 printf("Writing %s.\n", mefilename);
29801 }
29802 outfile = fopen(mefilename, "w");
29803 if (outfile == (FILE *) NULL) {
29804 printf("File I/O Error: Cannot create file %s.\n", mefilename);
29805 return;
29806 }
29807
29808 fprintf(outfile, "MeshVersionFormatted 1\n");
29809 fprintf(outfile, "\n");
29810 fprintf(outfile, "Dimension\n");
29811 fprintf(outfile, "3\n");
29812 fprintf(outfile, "\n");
29813
29814 fprintf(outfile, "\n# Set of mesh vertices\n");
29815 fprintf(outfile, "Vertices\n");
29816 fprintf(outfile, "%ld\n", points->items);
29817
29818 points->traversalinit();
29819 pointloop = pointtraverse();
29820 pointnumber = 1; // Medit need start number form 1.
29821 while (pointloop != (point) NULL) {
29822 // Point coordinates.
29823 fprintf(outfile, "%.17g %.17g %.17g",
29824 pointloop[0], pointloop[1], pointloop[2]);
29825 if (in->numberofpointattributes > 0) {
29826 // Write an attribute, ignore others if more than one.
29827 fprintf(outfile, " %.17g\n", pointloop[3]);
29828 } else {
29829 fprintf(outfile, " 0\n");
29830 }
29831 setpointmark(pointloop, pointnumber);
29832 pointloop = pointtraverse();
29833 pointnumber++;
29834 }
29835
29836 // Compute the number of edges.
29837 faces = (4l * tetrahedrons->items + hullsize) / 2l;
29838
29839 fprintf(outfile, "\n# Set of Triangles\n");
29840 fprintf(outfile, "Triangles\n");
29841 fprintf(outfile, "%ld\n", faces);
29842
29843 tetrahedrons->traversalinit();
29844 tface.tet = tetrahedrontraverse();
29845 // To loop over the set of faces, loop over all tetrahedra, and look at
29846 // the four faces of each tetrahedron. If there isn't another tetrahedron
29847 // adjacent to the face, operate on the face. If there is another adj-
29848 // acent tetrahedron, operate on the face only if the current tetrahedron
29849 // has a smaller pointer than its neighbor. This way, each face is
29850 // considered only once.
29851 while (tface.tet != (tetrahedron *) NULL) {
29852 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
29853 sym(tface, tsymface);
29854 if (tface.tet < tsymface.tet || tsymface.tet == dummytet) {
29855 p1 = org (tface);
29856 p2 = dest(tface);
29857 p3 = apex(tface);
29858 fprintf(outfile, "%5d %5d %5d",
29859 pointmark(p1), pointmark(p2), pointmark(p3));
29860 fprintf(outfile, " 0\n");
29861 }
29862 }
29863 tface.tet = tetrahedrontraverse();
29864 }
29865
29866 fprintf(outfile, "\n# Set of Tetrahedra\n");
29867 fprintf(outfile, "Tetrahedra\n");
29868 fprintf(outfile, "%ld\n", tetrahedrons->items);
29869
29870 tetrahedrons->traversalinit();
29871 tetptr = tetrahedrontraverse();
29872 while (tetptr != (tetrahedron *) NULL) {
29873 p1 = (point) tetptr[4];
29874 p2 = (point) tetptr[5];
29875 p3 = (point) tetptr[6];
29876 p4 = (point) tetptr[7];
29877 fprintf(outfile, "%5d %5d %5d %5d",
29878 pointmark(p1), pointmark(p2), pointmark(p3), pointmark(p4));
29879 if (in->numberoftetrahedronattributes > 0) {
29880 fprintf(outfile, " %.17g", elemattribute(tetptr, 0));
29881 } else {
29882 fprintf(outfile, " 0");
29883 }
29884 fprintf(outfile, "\n");
29885 tetptr = tetrahedrontraverse();
29886 }
29887
29888 fprintf(outfile, "\nCorners\n");
29889 fprintf(outfile, "%d\n", in->numberofpoints);
29890
29891 for (i = 0; i < in->numberofpoints; i++) {
29892 fprintf(outfile, "%4d\n", i + 1);
29893 }
29894
29895 if (b->useshelles) {
29896 fprintf(outfile, "\nEdges\n");
29897 fprintf(outfile, "%ld\n", subsegs->items);
29898
29899 subsegs->traversalinit();
29900 segloop.sh = shellfacetraverse(subsegs);
29901 while (segloop.sh != (shellface *) NULL) {
29902 p1 = sorg(segloop);
29903 p2 = sdest(segloop);
29904 fprintf(outfile, "%5d %5d", pointmark(p1), pointmark(p2));
29905 fprintf(outfile, " 0\n");
29906 segloop.sh = shellfacetraverse(subsegs);
29907 }
29908 }
29909
29910 fprintf(outfile, "\nEnd\n");
29911 fclose(outfile);
29912 }
29913
29914 ///////////////////////////////////////////////////////////////////////////////
29915 // //
29916 // outmesh2gid() Write mesh to a .ele.msh file and a .face.msh file, //
29917 // which can be imported and rendered by Gid. //
29918 // //
29919 // You can specify a filename (without suffix) in 'gfilename'. If you don't //
29920 // supply a filename (let gfilename be NULL), the default name stored in //
29921 // 'tetgenbehavior' will be used. The suffixes (.ele.msh and .face.msh) will //
29922 // be automatically added. //
29923 // //
29924 ///////////////////////////////////////////////////////////////////////////////
29925
29926 void tetgenmesh::outmesh2gid(char* gfilename)
29927 {
29928 FILE *outfile;
29929 char gidfilename[FILENAMESIZE];
29930 tetrahedron* tetptr;
29931 triface tface, tsymface;
29932 face sface;
29933 point pointloop, p1, p2, p3, p4;
29934 int pointnumber;
29935 int elementnumber;
29936
29937 if (gfilename != (char *) NULL && gfilename[0] != '\0') {
29938 strcpy(gidfilename, gfilename);
29939 } else if (b->outfilename[0] != '\0') {
29940 strcpy(gidfilename, b->outfilename);
29941 } else {
29942 strcpy(gidfilename, "unnamed");
29943 }
29944 strcat(gidfilename, ".ele.msh");
29945
29946 if (!b->quiet) {
29947 printf("Writing %s.\n", gidfilename);
29948 }
29949 outfile = fopen(gidfilename, "w");
29950 if (outfile == (FILE *) NULL) {
29951 printf("File I/O Error: Cannot create file %s.\n", gidfilename);
29952 return;
29953 }
29954
29955 fprintf(outfile, "mesh dimension = 3 elemtype tetrahedron nnode = 4\n");
29956 fprintf(outfile, "coordinates\n");
29957
29958 points->traversalinit();
29959 pointloop = pointtraverse();
29960 pointnumber = 1; // Gid need start number form 1.
29961 while (pointloop != (point) NULL) {
29962 // Point coordinates.
29963 fprintf(outfile, "%4d %.17g %.17g %.17g", pointnumber,
29964 pointloop[0], pointloop[1], pointloop[2]);
29965 if (in->numberofpointattributes > 0) {
29966 // Write an attribute, ignore others if more than one.
29967 fprintf(outfile, " %.17g", pointloop[3]);
29968 }
29969 fprintf(outfile, "\n");
29970 setpointmark(pointloop, pointnumber);
29971 pointloop = pointtraverse();
29972 pointnumber++;
29973 }
29974
29975 fprintf(outfile, "end coordinates\n");
29976 fprintf(outfile, "elements\n");
29977
29978 tetrahedrons->traversalinit();
29979 tetptr = tetrahedrontraverse();
29980 elementnumber = 1;
29981 while (tetptr != (tetrahedron *) NULL) {
29982 p1 = (point) tetptr[4];
29983 p2 = (point) tetptr[5];
29984 p3 = (point) tetptr[6];
29985 p4 = (point) tetptr[7];
29986 fprintf(outfile, "%5d %5d %5d %5d %5d", elementnumber,
29987 pointmark(p1), pointmark(p2), pointmark(p3), pointmark(p4));
29988 if (in->numberoftetrahedronattributes > 0) {
29989 fprintf(outfile, " %.17g", elemattribute(tetptr, 0));
29990 }
29991 fprintf(outfile, "\n");
29992 tetptr = tetrahedrontraverse();
29993 elementnumber++;
29994 }
29995
29996 fprintf(outfile, "end elements\n");
29997 fclose(outfile);
29998
29999 if (gfilename != (char *) NULL && gfilename[0] != '\0') {
30000 strcpy(gidfilename, gfilename);
30001 } else if (b->outfilename[0] != '\0') {
30002 strcpy(gidfilename, b->outfilename);
30003 } else {
30004 strcpy(gidfilename, "unnamed");
30005 }
30006 strcat(gidfilename, ".face.msh");
30007
30008 if (!b->quiet) {
30009 printf("Writing %s.\n", gidfilename);
30010 }
30011 outfile = fopen(gidfilename, "w");
30012 if (outfile == (FILE *) NULL) {
30013 printf("File I/O Error: Cannot create file %s.\n", gidfilename);
30014 return;
30015 }
30016
30017 fprintf(outfile, "mesh dimension = 3 elemtype triangle nnode = 3\n");
30018 fprintf(outfile, "coordinates\n");
30019
30020 points->traversalinit();
30021 pointloop = pointtraverse();
30022 pointnumber = 1; // Gid need start number form 1.
30023 while (pointloop != (point) NULL) {
30024 // Point coordinates.
30025 fprintf(outfile, "%4d %.17g %.17g %.17g", pointnumber,
30026 pointloop[0], pointloop[1], pointloop[2]);
30027 if (in->numberofpointattributes > 0) {
30028 // Write an attribute, ignore others if more than one.
30029 fprintf(outfile, " %.17g", pointloop[3]);
30030 }
30031 fprintf(outfile, "\n");
30032 setpointmark(pointloop, pointnumber);
30033 pointloop = pointtraverse();
30034 pointnumber++;
30035 }
30036
30037 fprintf(outfile, "end coordinates\n");
30038 fprintf(outfile, "elements\n");
30039
30040 tetrahedrons->traversalinit();
30041 tface.tet = tetrahedrontraverse();
30042 elementnumber = 1;
30043 while (tface.tet != (tetrahedron *) NULL) {
30044 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
30045 sym(tface, tsymface);
30046 if ((tface.tet < tsymface.tet) || (tsymface.tet == dummytet)) {
30047 p1 = org(tface);
30048 p2 = dest(tface);
30049 p3 = apex(tface);
30050 if (tsymface.tet == dummytet) {
30051 // It's a hull face, output it.
30052 fprintf(outfile, "%5d %d %d %d\n", elementnumber,
30053 pointmark(p1), pointmark(p2), pointmark(p3));
30054 elementnumber++;
30055 } else if (b->useshelles) {
30056 // Only output it if it's a subface.
30057 tspivot(tface, sface);
30058 if (sface.sh != dummysh) {
30059 fprintf(outfile, "%5d %d %d %d\n", elementnumber,
30060 pointmark(p1), pointmark(p2), pointmark(p3));
30061 elementnumber++;
30062 }
30063 }
30064 }
30065 }
30066 tface.tet = tetrahedrontraverse();
30067 }
30068
30069 fprintf(outfile, "end elements\n");
30070 fclose(outfile);
30071 }
30072
30073 ///////////////////////////////////////////////////////////////////////////////
30074 // //
30075 // outmesh2off() Write the mesh to an .off file. //
30076 // //
30077 // .off, the Object File Format, is one of the popular file formats from the //
30078 // Geometry Center's Geomview package (http://www.geomview.org). //
30079 // //
30080 ///////////////////////////////////////////////////////////////////////////////
30081
30082 void tetgenmesh::outmesh2off(char* ofilename)
30083 {
30084 FILE *outfile;
30085 char offfilename[FILENAMESIZE];
30086 triface tface, tsymface;
30087 point pointloop, p1, p2, p3;
30088 long faces;
30089 int shift;
30090
30091 if (ofilename != (char *) NULL && ofilename[0] != '\0') {
30092 strcpy(offfilename, ofilename);
30093 } else if (b->outfilename[0] != '\0') {
30094 strcpy(offfilename, b->outfilename);
30095 } else {
30096 strcpy(offfilename, "unnamed");
30097 }
30098 strcat(offfilename, ".off");
30099
30100 if (!b->quiet) {
30101 printf("Writing %s.\n", offfilename);
30102 }
30103 outfile = fopen(offfilename, "w");
30104 if (outfile == (FILE *) NULL) {
30105 printf("File I/O Error: Cannot create file %s.\n", offfilename);
30106 return;
30107 }
30108
30109 // Calculate the number of triangular faces in the tetrahedral mesh.
30110 faces = (4l * tetrahedrons->items + hullsize) / 2l;
30111
30112 // Number of points, faces, and edges(not used, here show hullsize).
30113 fprintf(outfile, "OFF\n%ld %ld %ld\n", points->items, faces, hullsize);
30114
30115 // Write the points.
30116 points->traversalinit();
30117 pointloop = pointtraverse();
30118 while (pointloop != (point) NULL) {
30119 fprintf(outfile, " %.17g %.17g %.17g\n", pointloop[0], pointloop[1],
30120 pointloop[2]);
30121 pointloop = pointtraverse();
30122 }
30123
30124 // OFF always use zero as the first index.
30125 shift = in->firstnumber == 1 ? 1 : 0;
30126
30127 tetrahedrons->traversalinit();
30128 tface.tet = tetrahedrontraverse();
30129 // To loop over the set of faces, loop over all tetrahedra, and look at
30130 // the four faces of each tetrahedron. If there isn't another tetrahedron
30131 // adjacent to the face, operate on the face. If there is another adj-
30132 // acent tetrahedron, operate on the face only if the current tetrahedron
30133 // has a smaller pointer than its neighbor. This way, each face is
30134 // considered only once.
30135 while (tface.tet != (tetrahedron *) NULL) {
30136 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
30137 sym(tface, tsymface);
30138 if ((tface.tet < tsymface.tet) || (tsymface.tet == dummytet)) {
30139 p1 = org(tface);
30140 p2 = dest(tface);
30141 p3 = apex(tface);
30142 // Face number, indices of three vertexs.
30143 fprintf(outfile, "3 %4d %4d %4d\n", pointmark(p1) - shift,
30144 pointmark(p2) - shift, pointmark(p3) - shift);
30145 }
30146 }
30147 tface.tet = tetrahedrontraverse();
30148 }
30149
30150 fprintf(outfile, "# Generated by %s\n", b->commandline);
30151 fclose(outfile);
30152 }
30153
30154 //
30155 // End of I/O rouitnes
30156 //
30157
30158 //
30159 // Begin of user interaction routines
30160 //
30161
30162 ///////////////////////////////////////////////////////////////////////////////
30163 // //
30164 // internalerror() Ask the user to send me the defective product. Exit. //
30165 // //
30166 ///////////////////////////////////////////////////////////////////////////////
30167
30168 void tetgenmesh::internalerror()
30169 {
30170 printf(" Please report this bug to [email protected]. Include the\n");
30171 printf(" message above, your input data set, and the exact command\n");
30172 printf(" line you used to run this program, thank you.\n");
30173 terminatetetgen(2);
30174 }
30175
30176 ///////////////////////////////////////////////////////////////////////////////
30177 // //
30178 // checkmesh() Test the mesh for topological consistency. //
30179 // //
30180 ///////////////////////////////////////////////////////////////////////////////
30181
30182 void tetgenmesh::checkmesh()
30183 {
30184 triface tetraloop;
30185 triface oppotet, oppooppotet;
30186 point tetorg, tetdest, tetapex, tetoppo;
30187 REAL oritest;
30188 int horrors;
30189
30190 if (!b->quiet) {
30191 printf(" Checking consistency of mesh...\n");
30192 }
30193
30194 horrors = 0;
30195 // Run through the list of tetrahedra, checking each one.
30196 tetrahedrons->traversalinit();
30197 tetraloop.tet = tetrahedrontraverse();
30198 while (tetraloop.tet != (tetrahedron *) NULL) {
30199 // Check all four faces of the tetrahedron.
30200 for (tetraloop.loc = 0; tetraloop.loc < 4; tetraloop.loc++) {
30201 tetorg = org(tetraloop);
30202 tetdest = dest(tetraloop);
30203 tetapex = apex(tetraloop);
30204 tetoppo = oppo(tetraloop);
30205 if (tetraloop.loc == 0) { // Only test for inversion once.
30206 oritest = orient3d(tetorg, tetdest, tetapex, tetoppo);
30207 if (oritest >= 0.0) {
30208 printf(" !! !! %s ", oritest > 0.0 ? "Inverted" : "Degenerated");
30209 printtet(&tetraloop);
30210 printf(" orient3d = %.17g.\n", oritest);
30211 horrors++;
30212 }
30213 }
30214 // Find the neighboring tetrahedron on this face.
30215 sym(tetraloop, oppotet);
30216 if (oppotet.tet != dummytet) {
30217 // Check that the tetrahedron's neighbor knows it's a neighbor.
30218 sym(oppotet, oppooppotet);
30219 if ((tetraloop.tet != oppooppotet.tet)
30220 || (tetraloop.loc != oppooppotet.loc)) {
30221 printf(" !! !! Asymmetric tetra-tetra bond:\n");
30222 if (tetraloop.tet == oppooppotet.tet) {
30223 printf(" (Right tetrahedron, wrong orientation)\n");
30224 }
30225 printf(" First ");
30226 printtet(&tetraloop);
30227 printf(" Second (nonreciprocating) ");
30228 printtet(&oppotet);
30229 horrors++;
30230 }
30231 }
30232 }
30233 tetraloop.tet = tetrahedrontraverse();
30234 }
30235 if (horrors == 0) {
30236 if (!b->quiet) {
30237 printf(" In my studied opinion, the mesh appears to be consistent.\n");
30238 }
30239 } else if (horrors == 1) {
30240 printf(" !! !! !! !! Precisely one festering wound discovered.\n");
30241 } else {
30242 printf(" !! !! !! !! %d abominations witnessed.\n", horrors);
30243 }
30244 }
30245
30246 ///////////////////////////////////////////////////////////////////////////////
30247 // //
30248 // checkshells() Test the boundary mesh for topological consistency. //
30249 // //
30250 ///////////////////////////////////////////////////////////////////////////////
30251
30252 void tetgenmesh::checkshells()
30253 {
30254 triface oppotet, oppooppotet, testtet;
30255 face shloop, segloop, spin;
30256 face testsh, testseg, testshsh;
30257 point shorg, shdest, segorg, segdest;
30258 REAL checksign;
30259 bool same;
30260 int horrors;
30261 int i;
30262
30263 if (!b->quiet) {
30264 printf(" Checking consistency of the mesh boundary...\n");
30265 }
30266 horrors = 0;
30267
30268 // Run through the list of subfaces, checking each one.
30269 subfaces->traversalinit();
30270 shloop.sh = shellfacetraverse(subfaces);
30271 while (shloop.sh != (shellface *) NULL) {
30272 // Check two connected tetrahedra if they exist.
30273 shloop.shver = 0;
30274 stpivot(shloop, oppotet);
30275 if (oppotet.tet != dummytet) {
30276 tspivot(oppotet, testsh);
30277 if (testsh.sh != shloop.sh) {
30278 printf(" !! !! Wrong tetra-subface connection.\n");
30279 printf(" Tetra: ");
30280 printtet(&oppotet);
30281 printf(" Subface: ");
30282 printsh(&shloop);
30283 horrors++;
30284 }
30285 if (oppo(oppotet) != (point) NULL) {
30286 adjustedgering(oppotet, CCW);
30287 checksign = orient3d(sorg(shloop), sdest(shloop), sapex(shloop),
30288 oppo(oppotet));
30289 if (checksign >= 0.0) {
30290 printf(" !! !! Wrong subface orientation.\n");
30291 printf(" Subface: ");
30292 printsh(&shloop);
30293 horrors++;
30294 }
30295 }
30296 }
30297 sesymself(shloop);
30298 stpivot(shloop, oppooppotet);
30299 if (oppooppotet.tet != dummytet) {
30300 tspivot(oppooppotet, testsh);
30301 if (testsh.sh != shloop.sh) {
30302 printf(" !! !! Wrong tetra-subface connection.\n");
30303 printf(" Tetra: ");
30304 printtet(&oppooppotet);
30305 printf(" Subface: ");
30306 printsh(&shloop);
30307 horrors++;
30308 }
30309 if (oppotet.tet != dummytet) {
30310 sym(oppotet, testtet);
30311 if (testtet.tet != oppooppotet.tet) {
30312 printf(" !! !! Wrong tetra-subface-tetra connection.\n");
30313 printf(" Tetra 1: ");
30314 printtet(&oppotet);
30315 printf(" Subface: ");
30316 printsh(&shloop);
30317 printf(" Tetra 2: ");
30318 printtet(&oppooppotet);
30319 horrors++;
30320 }
30321 }
30322 if (oppo(oppooppotet) != (point) NULL) {
30323 adjustedgering(oppooppotet, CCW);
30324 checksign = orient3d(sorg(shloop), sdest(shloop), sapex(shloop),
30325 oppo(oppooppotet));
30326 if (checksign >= 0.0) {
30327 printf(" !! !! Wrong subface orientation.\n");
30328 printf(" Subface: ");
30329 printsh(&shloop);
30330 horrors++;
30331 }
30332 }
30333 }
30334 // Check connection between subfaces.
30335 shloop.shver = 0;
30336 for (i = 0; i < 3; i++) {
30337 shorg = sorg(shloop);
30338 shdest = sdest(shloop);
30339 sspivot(shloop, testseg);
30340 if (testseg.sh != dummysh) {
30341 segorg = sorg(testseg);
30342 segdest = sdest(testseg);
30343 same = ((shorg == segorg) && (shdest == segdest))
30344 || ((shorg == segdest) && (shdest == segorg));
30345 if (!same) {
30346 printf(" !! !! Wrong subface-subsegment connection.\n");
30347 printf(" Subface: ");
30348 printsh(&shloop);
30349 printf(" Subsegment: ");
30350 printsh(&testseg);
30351 horrors++;
30352 }
30353 }
30354 spivot(shloop, testsh);
30355 if (testsh.sh != dummysh) {
30356 segorg = sorg(testsh);
30357 segdest = sdest(testsh);
30358 same = ((shorg == segorg) && (shdest == segdest))
30359 || ((shorg == segdest) && (shdest == segorg));
30360 if (!same) {
30361 printf(" !! !! Wrong subface-subface connection.\n");
30362 printf(" Subface 1: ");
30363 printsh(&shloop);
30364 printf(" Subface 2: ");
30365 printsh(&testsh);
30366 horrors++;
30367 }
30368 spivot(testsh, testshsh);
30369 shorg = sorg(testshsh);
30370 shdest = sdest(testshsh);
30371 same = ((shorg == segorg) && (shdest == segdest))
30372 || ((shorg == segdest) && (shdest == segorg));
30373 if (!same) {
30374 printf(" !! !! Wrong subface-subface connection.\n");
30375 printf(" Subface 1: ");
30376 printsh(&testsh);
30377 printf(" Subface 2: ");
30378 printsh(&testshsh);
30379 horrors++;
30380 }
30381 if (testseg.sh == dummysh) {
30382 if (testshsh.sh != shloop.sh) {
30383 printf(" !! !! Wrong subface-subface connection.\n");
30384 printf(" Subface 1: ");
30385 printsh(&shloop);
30386 printf(" Subface 2: ");
30387 printsh(&testsh);
30388 horrors++;
30389 }
30390 }
30391 }
30392 senextself(shloop);
30393 }
30394 shloop.sh = shellfacetraverse(subfaces);
30395 }
30396
30397 // Run through the list of subsegs, checking each one.
30398 subsegs->traversalinit();
30399 segloop.sh = shellfacetraverse(subsegs);
30400 while (segloop.sh != (shellface *) NULL) {
30401 segorg = sorg(segloop);
30402 segdest = sdest(segloop);
30403 spivot(segloop, testsh);
30404 if (testsh.sh == dummysh) {
30405 printf(" !! !! Wrong subsegment-subface connection.\n");
30406 printf(" Subsegment: ");
30407 printsh(&segloop);
30408 horrors++;
30409 segloop.sh = shellfacetraverse(subsegs);
30410 continue;
30411 }
30412 shorg = sorg(testsh);
30413 shdest = sdest(testsh);
30414 same = ((shorg == segorg) && (shdest == segdest))
30415 || ((shorg == segdest) && (shdest == segorg));
30416 if (!same) {
30417 printf(" !! !! Wrong subsegment-subface connection.\n");
30418 printf(" Subsegment : ");
30419 printsh(&segloop);
30420 printf(" Subface : ");
30421 printsh(&testsh);
30422 horrors++;
30423 segloop.sh = shellfacetraverse(subsegs);
30424 continue;
30425 }
30426 // Check the connection of face loop around this subsegment.
30427 spin = testsh;
30428 i = 0;
30429 do {
30430 spivotself(spin);
30431 shorg = sorg(spin);
30432 shdest = sdest(spin);
30433 same = ((shorg == segorg) && (shdest == segdest))
30434 || ((shorg == segdest) && (shdest == segorg));
30435 if (!same) {
30436 printf(" !! !! Wrong subsegment-subface connection.\n");
30437 printf(" Subsegment : ");
30438 printsh(&segloop);
30439 printf(" Subface : ");
30440 printsh(&testsh);
30441 horrors++;
30442 break;
30443 }
30444 i++;
30445 } while (spin.sh != testsh.sh && i < 1000);
30446 if (i >= 1000) {
30447 printf(" !! !! Wrong subsegment-subface connection.\n");
30448 printf(" Subsegment : ");
30449 printsh(&segloop);
30450 horrors++;
30451 }
30452 segloop.sh = shellfacetraverse(subsegs);
30453 }
30454 if (horrors == 0) {
30455 if (!b->quiet) {
30456 printf(" Mesh boundaries connected correctly.\n");
30457 }
30458 } else {
30459 printf(" !! !! !! !! %d boundary connection viewed with horror.\n",
30460 horrors);
30461 return;
30462 }
30463 }
30464
30465 ///////////////////////////////////////////////////////////////////////////////
30466 // //
30467 // checkdelaunay() Ensure that the mesh is constrained Delaunay. //
30468 // //
30469 // If 'flipqueue' is not NULL, non-locally Delaunay faces are saved in it. //
30470 // //
30471 ///////////////////////////////////////////////////////////////////////////////
30472
30473 void tetgenmesh::checkdelaunay(REAL eps, queue* flipqueue)
30474 {
30475 triface tetraloop;
30476 triface oppotet;
30477 face opposhelle;
30478 point tetorg, tetdest, tetapex, tetoppo;
30479 point oppooppo;
30480 enum fliptype fc;
30481 REAL sign;
30482 int shouldbedelaunay;
30483 int horrors;
30484
30485 if (!b->quiet) {
30486 printf(" Checking Delaunay property of the mesh...\n");
30487 }
30488 horrors = 0;
30489 // Run through the list of triangles, checking each one.
30490 tetrahedrons->traversalinit();
30491 tetraloop.tet = tetrahedrontraverse();
30492 while (tetraloop.tet != (tetrahedron *) NULL) {
30493 // Check all four faces of the tetrahedron.
30494 for (tetraloop.loc = 0; tetraloop.loc < 4; tetraloop.loc++) {
30495 tetorg = org(tetraloop);
30496 tetdest = dest(tetraloop);
30497 tetapex = apex(tetraloop);
30498 tetoppo = oppo(tetraloop);
30499 sym(tetraloop, oppotet);
30500 oppooppo = oppo(oppotet);
30501 // Only do testif there is an adjoining tetrahedron whose pointer is
30502 // larger (to ensure that each pair isn't tested twice).
30503 shouldbedelaunay = (oppotet.tet != dummytet)
30504 && (tetoppo != (point) NULL)
30505 && (oppooppo != (point) NULL)
30506 && (tetraloop.tet < oppotet.tet);
30507 if (checksubfaces && shouldbedelaunay) {
30508 // If a shell face separates the tetrahedra, then the face is
30509 // constrained, so no local Delaunay test should be done.
30510 tspivot(tetraloop, opposhelle);
30511 if (opposhelle.sh != dummysh){
30512 shouldbedelaunay = 0;
30513 }
30514 }
30515 if (shouldbedelaunay) {
30516 sign = insphere(tetdest, tetorg, tetapex, tetoppo, oppooppo);
30517 if ((sign > 0.0) && (eps > 0.0)) {
30518 if (iscospheric(tetdest, tetorg, tetapex, tetoppo, oppooppo, sign,
30519 eps)) sign = 0.0;
30520 }
30521 if (sign > 0.0) {
30522 if (flipqueue) {
30523 enqueueflipface(tetraloop, flipqueue);
30524 } else {
30525 printf(" !! Non-locally Delaunay face (%d, %d, %d) ",
30526 pointmark(tetorg), pointmark(tetdest), pointmark(tetapex));
30527 fc = categorizeface(tetraloop);
30528 switch (fc) {
30529 case T23: printf("\"T23\""); break;
30530 case T32: printf("\"T32\""); break;
30531 case T22: printf("\"T22\""); break;
30532 case T44: printf("\"T44\""); break;
30533 case UNFLIPABLE: printf("\"UNFLIPABLE\""); break;
30534 case FORBIDDENFACE:printf("\"FORBIDDENFACE\""); break;
30535 case FORBIDDENEDGE:printf("\"FORBIDDENEDGE\""); break;
30536 case NONCONVEX:printf("\"NONCONVEX\""); break;
30537 }
30538 printf("\n");
30539 }
30540 horrors++;
30541 }
30542 }
30543 }
30544 tetraloop.tet = tetrahedrontraverse();
30545 }
30546 if (flipqueue == (queue *) NULL) {
30547 if (horrors == 0) {
30548 if (!b->quiet) {
30549 printf(" The mesh is %s.\n",
30550 checksubfaces ? "constrained Delaunay" : "Delaunay");
30551 }
30552 } else {
30553 printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors);
30554 }
30555 }
30556 }
30557
30558 ///////////////////////////////////////////////////////////////////////////////
30559 // //
30560 // checkdegeneracy() Check if the point set contains degeneracies. //
30561 // //
30562 // 'eps' is a relative error tolerance for testing approximatly degeneracies.//
30563 // Set it to zero if only exact test is desired. //
30564 // //
30565 ///////////////////////////////////////////////////////////////////////////////
30566
30567 void tetgenmesh::checkdegeneracy(REAL eps)
30568 {
30569 triface tetraloop;
30570 triface oppotet;
30571 point tetorg, tetdest, tetapex, tetoppo;
30572 point oppooppo;
30573 REAL sign;
30574 int horrors;
30575
30576 if (!b->quiet) {
30577 printf(" Checking degeneracies in the point set...\n");
30578 }
30579 horrors = 0;
30580 // Run through the list of triangles, checking each one.
30581 tetrahedrons->traversalinit();
30582 tetraloop.tet = tetrahedrontraverse();
30583 while (tetraloop.tet != (tetrahedron *) NULL) {
30584 // Check all four faces of the tetrahedron.
30585 for (tetraloop.loc = 0; tetraloop.loc < 4; tetraloop.loc++) {
30586 tetorg = org(tetraloop);
30587 tetdest = dest(tetraloop);
30588 tetapex = apex(tetraloop);
30589 tetoppo = oppo(tetraloop);
30590 sym(tetraloop, oppotet);
30591 oppooppo = oppo(oppotet);
30592 // Only do test if there is an adjoining tetrahedron whose pointer is
30593 // larger (to ensure that each pair isn't tested twice).
30594 if ((oppotet.tet != dummytet) && (tetoppo != (point) NULL) &&
30595 (oppooppo != (point) NULL) && (tetraloop.tet < oppotet.tet)) {
30596 sign = insphere(tetdest, tetorg, tetapex, tetoppo, oppooppo);
30597 if ((sign != 0.0) && (eps > 0.0)) {
30598 if (iscospheric(tetdest, tetorg, tetapex, tetoppo, oppooppo, sign,
30599 eps)) sign = 0.0;
30600 }
30601 if (sign == 0.0) {
30602 printf(" !! Degenerate set (%d, %d, %d, %d, %d).\n",
30603 pointmark(tetorg), pointmark(tetdest), pointmark(tetapex),
30604 pointmark(tetoppo), pointmark(oppooppo));
30605 horrors++;
30606 }
30607 }
30608 }
30609 tetraloop.tet = tetrahedrontraverse();
30610 }
30611
30612 if (horrors == 0) {
30613 if (!b->quiet) {
30614 printf(" The point set is non-degenerate.\n");
30615 }
30616 } else {
30617 printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors);
30618 }
30619 }
30620
30621 ///////////////////////////////////////////////////////////////////////////////
30622 // //
30623 // checkconforming() Ensure that the mesh is conforming Delaunay. //
30624 // //
30625 ///////////////////////////////////////////////////////////////////////////////
30626
30627 void tetgenmesh::checkconforming()
30628 {
30629 face segloop, shloop;
30630 int encsubsegs, encsubfaces;
30631
30632 if (!b->quiet) {
30633 printf(" Checking conforming Delaunay property of mesh...\n");
30634 }
30635 encsubsegs = encsubfaces = 0;
30636 // Run through the list of subsegments, check each one.
30637 subsegs->traversalinit();
30638 segloop.sh = shellfacetraverse(subsegs);
30639 while (segloop.sh != (shellface *) NULL) {
30640 if (checkseg4encroach(&segloop, NULL, NULL, false)) {
30641 printf(" !! !! Non-conforming subsegment: (%d, %d)\n",
30642 pointmark(sorg(segloop)), pointmark(sdest(segloop)));
30643 encsubsegs++;
30644 }
30645 segloop.sh = shellfacetraverse(subsegs);
30646 }
30647 // Run through the list of subfaces, check each one.
30648 subfaces->traversalinit();
30649 shloop.sh = shellfacetraverse(subfaces);
30650 while (shloop.sh != (shellface *) NULL) {
30651 if (checksub4encroach(&shloop, NULL, false)) {
30652 printf(" !! !! Non-conforming subface: (%d, %d, %d)\n",
30653 pointmark(sorg(shloop)), pointmark(sdest(shloop)),
30654 pointmark(sapex(shloop)));
30655 encsubfaces++;
30656 }
30657 shloop.sh = shellfacetraverse(subfaces);
30658 }
30659 if (encsubsegs == 0 && encsubfaces == 0) {
30660 if (!b->quiet) {
30661 printf(" The mesh is conforming Delaunay.\n");
30662 }
30663 } else {
30664 if (encsubsegs > 0) {
30665 printf(" !! !! %d subsegments are non-conforming.\n", encsubsegs);
30666 }
30667 if (encsubfaces > 0) {
30668 printf(" !! !! %d subfaces are non-conforming.\n", encsubfaces);
30669 }
30670 }
30671 }
30672
30673 ///////////////////////////////////////////////////////////////////////////////
30674 // //
30675 // algorithmicstatistics() Print statistics about the mesh algorithms. //
30676 // //
30677 ///////////////////////////////////////////////////////////////////////////////
30678
30679 void tetgenmesh::algorithmicstatistics()
30680 {
30681 printf("Algorithmic statistics:\n\n");
30682 if (b->plc || b->refine) {
30683 printf(" Number of facet above points calculations: %ld\n", abovecount);
30684 }
30685 if (b->plc) {
30686 printf(" Segment split rules: R1 %ld, R2 %ld, R3 %ld\n", r1count, r2count,
30687 r3count);
30688 }
30689 if (b->quality) {
30690 printf(" Bowyer-Watson counts (seg, sub, vol)\n");
30691 printf(" Insert vertices: %ld, %ld, %ld\n",
30692 bowatsegcount, bowatsubcount, bowatvolcount);
30693 printf(" Update cavities: %ld, %ld, %ld\n",
30694 updsegcount, updsubcount, updvolcount);
30695 printf(" Failed cavities: %ld, %ld, %ld\n",
30696 failsegcount, failsubcount, failvolcount);
30697 printf(" Number of repair flips: %ld.\n", repairflipcount);
30698 printf(" Number of circumcenters outside Bowat-cav.: %ld.\n",
30699 outbowatcircumcount);
30700 if (b->conformdel) {
30701 printf(" Segment split rules: R2 %ld, R3 %ld\n", r2count, r3count);
30702 printf(" Number of CDT enforcement points: %ld.\n", cdtenforcesegpts);
30703 }
30704 printf(" Reject vertices counts:\n");
30705 printf(" Rejected seg splits: %ld.\n", rejsegpts);
30706 printf(" Rejected sub splits: %ld.\n", rejsubpts);
30707 printf(" Rejected tet splits: %ld.\n", rejtetpts);
30708 if (b->smooth) {
30709 printf(" Mesh smooth counts:\n");
30710 printf(" %4ld cdt enforcement points.\n", smoothcdtsegpt);
30711 printf(" %4ld segment points.\n", smoothsegpt);
30712 printf(" %4ld facet points.\n", smoothsubpt);
30713 printf(" %4ld volume points.\n", smoothvolpt);
30714 printf(" %4ld failed cdt enforcement points.\n", unsmoothcdtsegpt);
30715 printf(" %4ld unimproved segment points.\n", unsmoothsegpt);
30716 printf(" %4ld unimproved facet points.\n", unsmoothsubpt);
30717 printf(" %4ld unimproved volume points.\n", unsmoothvolpt);
30718 }
30719 }
30720 printf("\n");
30721 }
30722
30723 ///////////////////////////////////////////////////////////////////////////////
30724 // //
30725 // qualitystatistics() Print statistics about the quality of the mesh. //
30726 // //
30727 ///////////////////////////////////////////////////////////////////////////////
30728
30729 void tetgenmesh::qualitystatistics()
30730 {
30731 triface tetloop;
30732 point p[4];
30733 char sbuf[128];
30734 REAL radiusratiotable[12];
30735 REAL aspectratiotable[12];
30736 REAL A[4][4], rhs[4], D;
30737 REAL V[6][3], N[4][3], H[4]; // edge-vectors, face-normals, face-heights.
30738 REAL edgelength[6], alldihed[6];
30739 REAL shortest, longest;
30740 REAL smallestvolume, biggestvolume;
30741 REAL smallestdiangle, biggestdiangle;
30742 REAL tetvol, minaltitude;
30743 REAL cirradius, minheightinv; // insradius;
30744 REAL shortlen, longlen;
30745 REAL tetaspect, tetradius;
30746 REAL smalldiangle, bigdiangle;
30747 int radiustable[12];
30748 int aspecttable[16];
30749 int dihedangletable[18];
30750 int indx[4];
30751 int radiusindex;
30752 int aspectindex;
30753 int tendegree;
30754 int i, j;
30755
30756 printf("Mesh quality statistics:\n\n");
30757
30758 // Avoid compile warnings.
30759 shortlen = longlen = 0.0;
30760 smalldiangle = bigdiangle = 0.0;
30761
30762 radiusratiotable[0] = 0.707; radiusratiotable[1] = 1.0;
30763 radiusratiotable[2] = 1.1; radiusratiotable[3] = 1.2;
30764 radiusratiotable[4] = 1.4; radiusratiotable[5] = 1.6;
30765 radiusratiotable[6] = 1.8; radiusratiotable[7] = 2.0;
30766 radiusratiotable[8] = 2.5; radiusratiotable[9] = 3.0;
30767 radiusratiotable[10] = 10.0; radiusratiotable[11] = 0.0;
30768
30769 aspectratiotable[0] = 1.5; aspectratiotable[1] = 2.0;
30770 aspectratiotable[2] = 2.5; aspectratiotable[3] = 3.0;
30771 aspectratiotable[4] = 4.0; aspectratiotable[5] = 6.0;
30772 aspectratiotable[6] = 10.0; aspectratiotable[7] = 15.0;
30773 aspectratiotable[8] = 25.0; aspectratiotable[9] = 50.0;
30774 aspectratiotable[10] = 100.0; aspectratiotable[11] = 0.0;
30775
30776 for (i = 0; i < 12; i++) radiustable[i] = 0;
30777 for (i = 0; i < 12; i++) aspecttable[i] = 0;
30778 for (i = 0; i < 18; i++) dihedangletable[i] = 0;
30779
30780 minaltitude = xmax - xmin + ymax - ymin + zmax - zmin;
30781 minaltitude = minaltitude * minaltitude;
30782 shortest = minaltitude;
30783 longest = 0.0;
30784 smallestvolume = minaltitude;
30785 biggestvolume = 0.0;
30786 smallestdiangle = 180.0;
30787 biggestdiangle = 0.0;
30788
30789 // Loop all elements, calculate quality parameters for each element.
30790 tetrahedrons->traversalinit();
30791 tetloop.tet = tetrahedrontraverse();
30792 while (tetloop.tet != (tetrahedron *) NULL) {
30793
30794 // Get four vertices: p0, p1, p2, p3.
30795 for (i = 0; i < 4; i++) p[i] = (point) tetloop.tet[4 + i];
30796 // Set the edge vectors: V[0], ..., V[5]
30797 for (i = 0; i < 3; i++) V[0][i] = p[0][i] - p[3][i]; // V[0]: p3->p0.
30798 for (i = 0; i < 3; i++) V[1][i] = p[1][i] - p[3][i]; // V[1]: p3->p1.
30799 for (i = 0; i < 3; i++) V[2][i] = p[2][i] - p[3][i]; // V[2]: p3->p2.
30800 for (i = 0; i < 3; i++) V[3][i] = p[1][i] - p[0][i]; // V[3]: p0->p1.
30801 for (i = 0; i < 3; i++) V[4][i] = p[2][i] - p[1][i]; // V[4]: p1->p2.
30802 for (i = 0; i < 3; i++) V[5][i] = p[0][i] - p[2][i]; // V[5]: p2->p0.
30803 // Set the matrix A = [V[0], V[1], V[2]]^T.
30804 for (j = 0; j < 3; j++) {
30805 for (i = 0; i < 3; i++) A[j][i] = V[j][i];
30806 }
30807 // Decompose A just once.
30808 lu_decmp(A, 3, indx, &D, 0);
30809 // Get the tet volume.
30810 tetvol = fabs(A[indx[0]][0] * A[indx[1]][1] * A[indx[2]][2]) / 6.0;
30811 // Get the three faces normals.
30812 for (j = 0; j < 3; j++) {
30813 for (i = 0; i < 3; i++) rhs[i] = 0.0;
30814 rhs[j] = 1.0; // Positive means the inside direction
30815 lu_solve(A, 3, indx, rhs, 0);
30816 for (i = 0; i < 3; i++) N[j][i] = rhs[i];
30817 }
30818 // Get the fourth face normal by summing up the first three.
30819 for (i = 0; i < 3; i++) N[3][i] = - N[0][i] - N[1][i] - N[2][i];
30820 // Get the radius of the circumsphere.
30821 for (i = 0; i < 3; i++) rhs[i] = 0.5 * dot(V[i], V[i]);
30822 lu_solve(A, 3, indx, rhs, 0);
30823 cirradius = sqrt(dot(rhs, rhs));
30824 // Normalize the face normals.
30825 for (i = 0; i < 4; i++) {
30826 // H[i] is the inverse of height of its corresponding face.
30827 H[i] = sqrt(dot(N[i], N[i]));
30828 for (j = 0; j < 3; j++) N[i][j] /= H[i];
30829 }
30830 // Get the radius of the inscribed sphere.
30831 // insradius = 1.0 / (H[0] + H[1] + H[2] + H[3]);
30832 // Get the biggest H[i] (corresponding to the smallest height).
30833 minheightinv = H[0];
30834 for (i = 1; i < 3; i++) {
30835 if (H[i] > minheightinv) minheightinv = H[i];
30836 }
30837 // Get the squares of the edge lengthes.
30838 for (i = 0; i < 6; i++) edgelength[i] = dot(V[i], V[i]);
30839 // Get the dihedrals (in degree) at each edges.
30840 j = 0;
30841 for (i = 1; i < 4; i++) {
30842 alldihed[j] = -dot(N[0], N[i]); // Edge cd, bd, bc.
30843 if (alldihed[j] < -1.0) alldihed[j] = -1; // Rounding.
30844 else if (alldihed[j] > 1.0) alldihed[j] = 1;
30845 alldihed[j] = acos(alldihed[j]) / PI * 180.0;
30846 j++;
30847 }
30848 for (i = 2; i < 4; i++) {
30849 alldihed[j] = -dot(N[1], N[i]); // Edge ad, ac.
30850 if (alldihed[j] < -1.0) alldihed[j] = -1; // Rounding.
30851 else if (alldihed[j] > 1.0) alldihed[j] = 1;
30852 alldihed[j] = acos(alldihed[j]) / PI * 180.0;
30853 j++;
30854 }
30855 alldihed[j] = -dot(N[2], N[3]); // Edge ab.
30856 if (alldihed[j] < -1.0) alldihed[j] = -1; // Rounding.
30857 else if (alldihed[j] > 1.0) alldihed[j] = 1;
30858 alldihed[j] = acos(alldihed[j]) / PI * 180.0;
30859
30860 // Calculate the longest and shortest edge length.
30861 for (i = 0; i < 6; i++) {
30862 if (i == 0) {
30863 shortlen = longlen = edgelength[i];
30864 } else {
30865 shortlen = edgelength[i] < shortlen ? edgelength[i] : shortlen;
30866 longlen = edgelength[i] > longlen ? edgelength[i] : longlen;
30867 }
30868 if (edgelength[i] > longest) {
30869 longest = edgelength[i];
30870 }
30871 if (edgelength[i] < shortest) {
30872 shortest = edgelength[i];
30873 }
30874 }
30875
30876 // Calculate the largest and smallest volume.
30877 if (tetvol < smallestvolume) {
30878 smallestvolume = tetvol;
30879 }
30880 if (tetvol > biggestvolume) {
30881 biggestvolume = tetvol;
30882 }
30883
30884 // Calculate the largest and smallest dihedral angles.
30885 for (i = 0; i < 6; i++) {
30886 if (i == 0) {
30887 smalldiangle = bigdiangle = alldihed[i];
30888 } else {
30889 smalldiangle = alldihed[i] < smalldiangle ? alldihed[i] : smalldiangle;
30890 bigdiangle = alldihed[i] > bigdiangle ? alldihed[i] : bigdiangle;
30891 }
30892 if (alldihed[i] < smallestdiangle) {
30893 smallestdiangle = alldihed[i];
30894 }
30895 if (alldihed[i] > biggestdiangle) {
30896 biggestdiangle = alldihed[i];
30897 }
30898 }
30899 // Accumulate the corresponding number in the dihedral angle histogram.
30900 if (smalldiangle < 5.0) {
30901 tendegree = 0;
30902 } else if (smalldiangle >= 5.0 && smalldiangle < 10.0) {
30903 tendegree = 1;
30904 } else if (smalldiangle >= 80.0 && smalldiangle < 110.0) {
30905 tendegree = 9; // Angles between 80 to 110 degree are in one entry.
30906 } else {
30907 tendegree = (int) (smalldiangle / 10.);
30908 if (smalldiangle < 80.0) {
30909 tendegree++; // In the left column.
30910 } else {
30911 tendegree--; // In the right column.
30912 }
30913 }
30914 dihedangletable[tendegree]++;
30915 if (bigdiangle >= 80.0 && bigdiangle < 110.0) {
30916 tendegree = 9; // Angles between 80 to 110 degree are in one entry.
30917 } else if (bigdiangle >= 170.0 && bigdiangle < 175.0) {
30918 tendegree = 16;
30919 } else if (bigdiangle >= 175.0) {
30920 tendegree = 17;
30921 } else {
30922 tendegree = (int) (bigdiangle / 10.);
30923 if (bigdiangle < 80.0) {
30924 tendegree++; // In the left column.
30925 } else {
30926 tendegree--; // In the right column.
30927 }
30928 }
30929 dihedangletable[tendegree]++;
30930
30931 // Calculate aspect ratio and radius-edge ratio for this element.
30932 tetradius = cirradius / sqrt(shortlen);
30933 // tetaspect = sqrt(longlen) / (2.0 * insradius);
30934 tetaspect = sqrt(longlen) * minheightinv;
30935 aspectindex = 0;
30936 while ((tetaspect > aspectratiotable[aspectindex]) && (aspectindex < 11)) {
30937 aspectindex++;
30938 }
30939 aspecttable[aspectindex]++;
30940 radiusindex = 0;
30941 while ((tetradius > radiusratiotable[radiusindex]) && (radiusindex < 11)) {
30942 radiusindex++;
30943 }
30944 radiustable[radiusindex]++;
30945
30946 tetloop.tet = tetrahedrontraverse();
30947 }
30948
30949 shortest = sqrt(shortest);
30950 longest = sqrt(longest);
30951 minaltitude = sqrt(minaltitude);
30952
30953 printf(" Smallest volume: %16.5g | Largest volume: %16.5g\n",
30954 smallestvolume, biggestvolume);
30955 printf(" Shortest edge: %16.5g | Longest edge: %16.5g\n",
30956 shortest, longest);
30957 sprintf(sbuf, "%.17g", biggestdiangle);
30958 if (strlen(sbuf) > 8) {
30959 sbuf[8] = '\0';
30960 }
30961 printf(" Smallest dihedral: %14.5g | Largest dihedral: %s\n\n",
30962 smallestdiangle, sbuf);
30963
30964 printf(" Radius-edge ratio histogram:\n");
30965 printf(" < %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30966 radiusratiotable[0], radiustable[0], radiusratiotable[5],
30967 radiusratiotable[6], radiustable[6]);
30968 for (i = 1; i < 5; i++) {
30969 printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30970 radiusratiotable[i - 1], radiusratiotable[i], radiustable[i],
30971 radiusratiotable[i + 5], radiusratiotable[i + 6],
30972 radiustable[i + 6]);
30973 }
30974 printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n",
30975 radiusratiotable[4], radiusratiotable[5], radiustable[5],
30976 radiusratiotable[10], radiustable[11]);
30977 printf(" (A tetrahedron's radius-edge ratio is its radius of ");
30978 printf("circumsphere divided\n");
30979 printf(" by its shortest edge length)\n\n");
30980
30981 printf(" Aspect ratio histogram:\n");
30982 printf(" < %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30983 aspectratiotable[0], aspecttable[0], aspectratiotable[5],
30984 aspectratiotable[6], aspecttable[6]);
30985 for (i = 1; i < 5; i++) {
30986 printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30987 aspectratiotable[i - 1], aspectratiotable[i], aspecttable[i],
30988 aspectratiotable[i + 5], aspectratiotable[i + 6],
30989 aspecttable[i + 6]);
30990 }
30991 printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n",
30992 aspectratiotable[4], aspectratiotable[5], aspecttable[5],
30993 aspectratiotable[10], aspecttable[11]);
30994 printf(" (A tetrahedron's aspect ratio is its longest edge length");
30995 printf(" divided by its\n");
30996 printf(" smallest side height)\n\n");
30997
30998 printf(" Dihedral angle histogram:\n");
30999 // Print the three two rows:
31000 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31001 0, 5, dihedangletable[0], 80, 110, dihedangletable[9]);
31002 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31003 5, 10, dihedangletable[1], 110, 120, dihedangletable[10]);
31004 // Print the third to seventh rows.
31005 for (i = 2; i < 7; i++) {
31006 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31007 (i - 1) * 10, (i - 1) * 10 + 10, dihedangletable[i],
31008 (i - 1) * 10 + 110, (i - 1) * 10 + 120, dihedangletable[i + 9]);
31009 }
31010 // Print the last two rows.
31011 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31012 60, 70, dihedangletable[7], 170, 175, dihedangletable[16]);
31013 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31014 70, 80, dihedangletable[8], 175, 180, dihedangletable[17]);
31015
31016 printf("\n");
31017 }
31018
31019 ///////////////////////////////////////////////////////////////////////////////
31020 // //
31021 // statistics() Print all sorts of cool facts. //
31022 // //
31023 ///////////////////////////////////////////////////////////////////////////////
31024
31025 void tetgenmesh::statistics()
31026 {
31027 printf("Statistics:\n");
31028 printf(" Input points: %d\n", in->numberofpoints + jettisoninverts);
31029 if (b->refine) {
31030 printf(" Input tetrahedra: %d\n", in->numberoftetrahedra);
31031 }
31032 if (b->plc) {
31033 printf(" Input facets: %d\n", in->numberoffacets);
31034 printf(" Input holes: %d\n", in->numberofholes);
31035 printf(" Input regions: %d\n", in->numberofregions);
31036 }
31037
31038 printf(" Mesh points: %ld\n", points->items);
31039 printf(" Mesh tetrahedra: %ld\n", tetrahedrons->items);
31040 if (b->plc || b->refine) {
31041 printf(" Mesh faces: %ld\n", (4l * tetrahedrons->items + hullsize) / 2l);
31042 }
31043 if (b->plc || b->refine) {
31044 printf(" Mesh subfaces: %ld\n", subfaces->items);
31045 printf(" Mesh subsegments: %ld\n", subsegs->items);
31046 } else {
31047 printf(" Convex hull faces: %ld\n", hullsize);
31048 }
31049 if (b->verbose > 0) {
31050 #ifdef SELF_CHECK
31051 // algorithmicstatistics();
31052 #endif
31053 qualitystatistics();
31054 printf("\n");
31055 }
31056 }
31057
31058 //
31059 // End of user interaction routines
31060 //
31061
31062 //
31063 // Begin of constructor and destructor of tetgenmesh
31064 //
31065
31066 ///////////////////////////////////////////////////////////////////////////////
31067 // //
31068 // ~tetgenmesh() Deallocte memory occupied by a tetgenmesh object. //
31069 // //
31070 ///////////////////////////////////////////////////////////////////////////////
31071
31072 tetgenmesh::~tetgenmesh()
31073 {
31074 bgm = (tetgenmesh *) NULL;
31075 in = (tetgenio *) NULL;
31076 b = (tetgenbehavior *) NULL;
31077
31078 if (tetrahedrons != (memorypool *) NULL) {
31079 delete tetrahedrons;
31080 }
31081 if (subfaces != (memorypool *) NULL) {
31082 delete subfaces;
31083 }
31084 if (subsegs != (memorypool *) NULL) {
31085 delete subsegs;
31086 }
31087 if (points != (memorypool *) NULL) {
31088 delete points;
31089 }
31090 if (dummytetbase != (tetrahedron *) NULL) {
31091 delete [] dummytetbase;
31092 }
31093 if (dummyshbase != (shellface *) NULL) {
31094 delete [] dummyshbase;
31095 }
31096 if (facetabovepointarray != (point *) NULL) {
31097 delete [] facetabovepointarray;
31098 }
31099 if (highordertable != (point *) NULL) {
31100 delete [] highordertable;
31101 }
31102 if (subpbcgrouptable != (pbcdata *) NULL) {
31103 delete [] subpbcgrouptable;
31104 }
31105 if (segpbcgrouptable != (list *) NULL) {
31106 delete segpbcgrouptable;
31107 delete [] idx2segpglist;
31108 delete [] segpglist;
31109 }
31110 }
31111
31112 ///////////////////////////////////////////////////////////////////////////////
31113 // //
31114 // tetgenmesh() Initialize a tetgenmesh object. //
31115 // //
31116 ///////////////////////////////////////////////////////////////////////////////
31117
31118 tetgenmesh::tetgenmesh()
31119 {
31120 bgm = (tetgenmesh *) NULL;
31121 in = (tetgenio *) NULL;
31122 b = (tetgenbehavior *) NULL;
31123
31124 tetrahedrons = (memorypool *) NULL;
31125 subfaces = (memorypool *) NULL;
31126 subsegs = (memorypool *) NULL;
31127 points = (memorypool *) NULL;
31128 badsubsegs = (memorypool *) NULL;
31129 badsubfaces = (memorypool *) NULL;
31130 badtetrahedrons = (memorypool *) NULL;
31131 flipstackers = (memorypool *) NULL;
31132
31133 dummytet = (tetrahedron *) NULL;
31134 dummytetbase = (tetrahedron *) NULL;
31135 dummysh = (shellface *) NULL;
31136 dummyshbase = (shellface *) NULL;
31137
31138 facetabovepointarray = (point *) NULL;
31139 abovepoint = (point) NULL;
31140 highordertable = (point *) NULL;
31141 subpbcgrouptable = (pbcdata *) NULL;
31142 segpbcgrouptable = (list *) NULL;
31143 idx2segpglist = (int *) NULL;
31144 segpglist = (int *) NULL;
31145
31146 xmax = xmin = ymax = ymin = zmax = zmin = 0.0;
31147 longest = 0.0;
31148 hullsize = 0l;
31149 insegments = 0l;
31150 pointlfsindex = 0;
31151 pointmarkindex = 0;
31152 point2simindex = 0;
31153 point2pbcptindex = 0;
31154 highorderindex = 0;
31155 elemattribindex = 0;
31156 volumeboundindex = 0;
31157 shmarkindex = 0;
31158 areaboundindex = 0;
31159 checksubfaces = 0;
31160 checkpbcs = 0;
31161 varconstraint = 0;
31162 nonconvex = 0;
31163 dupverts = 0;
31164 unuverts = 0;
31165 relverts = 0;
31166 suprelverts = 0;
31167 collapverts = 0;
31168 unsupverts = 0;
31169 jettisoninverts = 0;
31170 symbolic = 0;
31171 samples = 0l;
31172 randomseed = 0l;
31173 macheps = 0.0;
31174 maxcavfaces = maxcavverts = 0;
31175 expcavcount = 0;
31176 abovecount = 0l;
31177 bowatvolcount = bowatsubcount = bowatsegcount = 0l;
31178 updvolcount = updsubcount = updsegcount = 0l;
31179 repairflipcount = 0l;
31180 outbowatcircumcount = 0l;
31181 failvolcount = failsubcount = failsegcount = 0l;
31182 r1count = r2count = r3count = r4count = 0l;
31183 cdtenforcesegpts = 0l;
31184 rejsegpts = rejsubpts = rejtetpts = 0l;
31185 flip23s = flip32s = flip22s = flip44s = 0l;
31186 }
31187
31188 //
31189 // End of constructor and destructor of tetgenmesh
31190 //
31191
31192 //
31193 // End of class 'tetgenmesh' implementation.
31194 //
31195
31196 ///////////////////////////////////////////////////////////////////////////////
31197 // //
31198 // tetrahedralize() The interface for users using TetGen library to //
31199 // generate tetrahedral meshes with all features. //
31200 // //
31201 // The sequence is roughly as follows. Many of these steps can be skipped, //
31202 // depending on the command line switches. //
31203 // //
31204 // - Initialize constants and parse the command line. //
31205 // - Read the vertices from a file and either //
31206 // - tetrahedralize them (no -r), or //
31207 // - read an old mesh from files and reconstruct it (-r). //
31208 // - Insert the PLC segments and facets (-p). //
31209 // - Read the holes (-p), regional attributes (-pA), and regional volume //
31210 // constraints (-pa). Carve the holes and concavities, and spread the //
31211 // regional attributes and volume constraints. //
31212 // - Enforce the constraints on minimum quality bound (-q) and maximum //
31213 // volume (-a). Also enforce the conforming Delaunay property (-q and -a). //
31214 // - Promote the mesh's linear tetrahedra to higher order elements (-o). //
31215 // - Write the output files and print the statistics. //
31216 // - Check the consistency and Delaunay property of the mesh (-C). //
31217 // //
31218 ///////////////////////////////////////////////////////////////////////////////
31219
31220 #if 0
31221 #include <time.h> // Defined type clock_t, constant CLOCKS_PER_SEC.
31222 #endif
31223
31224 void tetrahedralize(tetgenbehavior *b, tetgenio *in, tetgenio *out,
31225 tetgenio *bgmesh)
31226 {
31227 tetgenmesh m;
31228 clock_t tv0, tv1, tv2, tv3, tv4, tv5, tv6, tv7, tv8, tv9, tv10, tv11;
31229
31230 tv0 = clock();
31231
31232 m.b = b;
31233 m.in = in;
31234 m.macheps = exactinit2(); //renamed by Zeyun Yu, originally exactinit()
31235 m.steinerleft = b->steiner;
31236 if (b->bgmesh) {
31237 // '-m' switch
31238 m.bgm = new tetgenmesh();
31239 m.bgm->b = b;
31240 m.bgm->in = bgmesh;
31241 m.bgm->macheps = exactinit2(); //renamed by Zeyun Yu, originally exactinit()
31242 }
31243 m.initializepools();
31244 m.transfernodes();
31245
31246 tv1 = clock();
31247
31248 if (b->refine) {
31249 m.reconstructmesh();
31250 } else {
31251 m.delaunizevertices();
31252 }
31253
31254 tv2 = clock();
31255 if (!b->quiet) {
31256 if (b->refine) {
31257 printf("Mesh reconstruction seconds: %g\n",
31258 (tv2 - tv1) / (REAL) CLOCKS_PER_SEC);
31259 } else {
31260 printf("Delaunay seconds: %g\n", (tv2 - tv1) / (REAL) CLOCKS_PER_SEC);
31261 }
31262 }
31263
31264 if (b->useshelles && !b->refine) {
31265 m.insegments = m.meshsurface();
31266 if (b->diagnose != 1) {
31267 m.incrperturbvertices(b->epsilon); // '-p' switch.
31268 m.delaunizesegments();
31269 m.constrainedfacets();
31270 } else {
31271 m.detectinterfaces(); // '-d' switch.
31272 }
31273 }
31274
31275 tv3 = clock();
31276 if (!b->quiet) {
31277 if (b->useshelles && !b->refine) {
31278 if (b->diagnose != 1) {
31279 printf("Segment and facet seconds: %g\n",
31280 (tv3 - tv2) / (REAL) CLOCKS_PER_SEC);
31281 } else {
31282 printf("Intersection seconds: %g\n",
31283 (tv3 - tv2) / (REAL) CLOCKS_PER_SEC);
31284 }
31285 }
31286 }
31287
31288 if (b->plc && !(b->diagnose == 1)) {
31289 m.carveholes();
31290 }
31291
31292 tv4 = clock();
31293 if (!b->quiet) {
31294 if (b->plc && !(b->diagnose == 1)) {
31295 printf("Hole seconds: %g\n", (tv4 - tv3) / (REAL) CLOCKS_PER_SEC);
31296 }
31297 }
31298
31299 if ((b->plc || b->refine) && !(b->diagnose == 1)) {
31300 m.repairmesh();
31301 }
31302
31303 tv5 = clock();
31304 if (!b->quiet) {
31305 if ((b->plc || b->refine) && !(b->diagnose == 1)) {
31306 printf("Repair seconds: %g\n", (tv5 - tv4) / (REAL) CLOCKS_PER_SEC);
31307 }
31308 }
31309
31310 if ((b->plc && b->nobisect) && !(b->diagnose == 1)) {
31311 m.removesteiners();
31312 }
31313
31314 tv6 = clock();
31315 if (!b->quiet) {
31316 if ((b->plc && b->nobisect) && !(b->diagnose == 1)) {
31317 printf("Steiner removal seconds: %g\n",
31318 (tv6 - tv5) / (REAL) CLOCKS_PER_SEC);
31319 }
31320 }
31321
31322 if (b->insertaddpoints) {
31323 if (in->numberofaddpoints == 0) {
31324 in->load_addnodes(b->infilename);
31325 }
31326 if (in->numberofaddpoints > 0) {
31327 m.insertaddpoints();
31328 }
31329 }
31330
31331 tv7 = clock();
31332 if (!b->quiet) {
31333 if ((b->plc || b->refine) && (in->numberofaddpoints > 0)) {
31334 printf("Add points seconds: %g\n", (tv7 - tv6) / (REAL) CLOCKS_PER_SEC);
31335 }
31336 }
31337
31338 if (b->bgmesh) {
31339 // '-b' switch
31340 m.bgm->initializepools();
31341 m.bgm->transfernodes();
31342 m.bgm->reconstructmesh();
31343 m.interpolatesizemap();
31344 }
31345
31346 tv8 = clock();
31347 if (!b->quiet) {
31348 if (b->bgmesh) {
31349 printf("Background mesh reconstruct seconds: %g\n",
31350 (tv8 - tv7) / (REAL) CLOCKS_PER_SEC);
31351 }
31352 }
31353
31354 if (b->quality) {
31355 m.enforcequality();
31356 }
31357
31358 tv9 = clock();
31359 if (!b->quiet) {
31360 if (b->quality) {
31361 printf("Quality seconds: %g\n", (tv9 - tv8) / (REAL) CLOCKS_PER_SEC);
31362 }
31363 }
31364
31365 if (b->quality && b->smooth) {
31366 m.smoothmesh();
31367 }
31368
31369 tv10 = clock();
31370 if (!b->quiet) {
31371 if (b->quality && b->smooth) {
31372 printf("Smooth seconds: %g\n", (tv10 - tv9) / (REAL) CLOCKS_PER_SEC);
31373 }
31374 }
31375
31376 if (!b->nojettison && ((m.dupverts > 0) || (m.unuverts > 0)
31377 || (b->refine && (in->numberofcorners == 10)))) {
31378 m.jettisonnodes();
31379 }
31380
31381 if (b->order > 1) {
31382 m.highorder();
31383 }
31384
31385 if (!b->quiet) {
31386 printf("\n");
31387 }
31388
31389 if (out != (tetgenio *) NULL) {
31390 out->firstnumber = in->firstnumber;
31391 out->mesh_dim = in->mesh_dim;
31392 }
31393
31394 if (b->nonodewritten || b->noiterationnum) {
31395 if (!b->quiet) {
31396 printf("NOT writing a .node file.\n");
31397 }
31398 } else {
31399 if (b->diagnose == 1) {
31400 if (m.subfaces->items > 0l) {
31401 // Only output when there are intersecting faces.
31402 m.outnodes(out);
31403 }
31404 } else {
31405 m.outnodes(out);
31406 if (b->metric) {
31407 m.outmetrics(out);
31408 }
31409 }
31410 }
31411
31412 if (b->noelewritten) {
31413 if (!b->quiet) {
31414 printf("NOT writing an .ele file.\n");
31415 }
31416 } else {
31417 if (!(b->diagnose == 1)) {
31418 if (m.tetrahedrons->items > 0l) {
31419 m.outelements(out);
31420 }
31421 }
31422 }
31423
31424 if (b->nofacewritten) {
31425 if (!b->quiet) {
31426 printf("NOT writing an .face file.\n");
31427 }
31428 } else {
31429 if (b->facesout) {
31430 if (m.tetrahedrons->items > 0l) {
31431 // Output all faces.
31432 m.outfaces(out);
31433 }
31434 } else {
31435 if (b->diagnose == 1) {
31436 if (m.subfaces->items > 0l) {
31437 // Only output when there are intersecting faces.
31438 m.outsubfaces(out);
31439 }
31440 } else if (b->plc || b->refine) {
31441 if (m.subfaces->items > 0l) {
31442 // Output boundary faces.
31443 m.outsubfaces(out);
31444 }
31445 } else {
31446 if (m.tetrahedrons->items > 0l) {
31447 // Output convex hull faces.
31448 m.outhullfaces(out);
31449 }
31450 }
31451 }
31452 }
31453
31454 if (m.checkpbcs) {
31455 m.outpbcnodes(out);
31456 }
31457
31458 if (b->edgesout && b->plc) {
31459 if (m.subsegs->items > 0l) {
31460 m.outsubsegments(out);
31461 }
31462 }
31463
31464 if (!out && b->plc &&
31465 ((b->object == tetgenbehavior::OFF) ||
31466 (b->object == tetgenbehavior::PLY) ||
31467 (b->object == tetgenbehavior::STL))) {
31468 m.outsmesh(b->outfilename);
31469 }
31470
31471 if (!out && b->meditview) {
31472 m.outmesh2medit(b->outfilename);
31473 }
31474
31475 if (!out && b->gidview) {
31476 m.outmesh2gid(b->outfilename);
31477 }
31478
31479 if (!out && b->geomview) {
31480 m.outmesh2off(b->outfilename);
31481 }
31482
31483 if (b->neighout) {
31484 m.outneighbors(out);
31485 }
31486
31487 tv11 = clock();
31488 if (!b->quiet) {
31489 printf("\nOutput seconds: %g\n", (tv11 - tv10) / (REAL) CLOCKS_PER_SEC);
31490 printf("Total running seconds: %g\n",
31491 (tv11 - tv0) / (REAL) CLOCKS_PER_SEC);
31492 }
31493
31494 if (b->docheck) {
31495 m.checkmesh();
31496 if (m.checksubfaces) {
31497 m.checkshells();
31498 }
31499 if (b->docheck > 1) {
31500 m.checkdelaunay(0.0, NULL);
31501 if (b->docheck > 2) {
31502 if (b->quality || b->refine) {
31503 m.checkconforming();
31504 }
31505 }
31506 }
31507 }
31508
31509 /* Zeyun Yu
31510 if (!b->quiet) {
31511 m.statistics();
31512 }
31513 */
31514 m.statistics(); // Zeyun Yu
31515
31516
31517 if (bgmesh) {
31518 delete m.bgm;
31519 }
31520 }
31521
31522 #ifndef TETLIBRARY
31523
31524 ///////////////////////////////////////////////////////////////////////////////
31525 // //
31526 // main() The entrance for running TetGen from command line. //
31527 // //
31528 ///////////////////////////////////////////////////////////////////////////////
31529
31530 int main(int argc, char *argv[])
31531
31532 #else // with TETLIBRARY
31533
31534 ///////////////////////////////////////////////////////////////////////////////
31535 // //
31536 // tetrahedralize() The entrance for calling TetGen from another program. //
31537 // //
31538 ///////////////////////////////////////////////////////////////////////////////
31539
31540 void tetrahedralize(char *switches, tetgenio *in, tetgenio *out,
31541 tetgenio *bgmesh)
31542
31543 #endif // not TETLIBRARY
31544
31545 {
31546 tetgenbehavior b;
31547
31548 #ifndef TETLIBRARY
31549
31550 tetgenio in, bgmesh;
31551
31552 if (!b.parse_commandline(argc, argv)) {
31553 terminatetetgen(1);
31554 }
31555 if (b.refine) {
31556 if (!in.load_tetmesh(b.infilename)) {
31557 terminatetetgen(1);
31558 }
31559 } else {
31560 if (!in.load_plc(b.infilename, (int) b.object)) {
31561 terminatetetgen(1);
31562 }
31563 }
31564 if (b.bgmesh) {
31565 if (!bgmesh.load_tetmesh(b.bgmeshfilename)) {
31566 bgmesh.numberoftetrahedra = 0l;
31567 }
31568 }
31569
31570 if (bgmesh.numberoftetrahedra > 0l) {
31571 tetrahedralize(&b, &in, NULL, &bgmesh);
31572 } else {
31573 tetrahedralize(&b, &in, NULL, NULL);
31574 }
31575
31576 return 0;
31577
31578 #else // with TETLIBRARY
31579
31580 if (!b.parse_commandline(switches)) {
31581 terminatetetgen(1);
31582 }
31583 tetrahedralize(&b, in, out, bgmesh);
31584
31585 #endif // not TETLIBRARY
31586 }
31587