Debian Codegraph @

debian/external_deps/fetk/gamer/src/tetgen/src_c/tetgen.cxx

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.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 = 0;
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 if (!b->quiet) {
14587 if (!b->noflip) {
14588 printf("Constructing Delaunay tetrahedralization.\n");
14589 } else {
14590 printf("Constructing regular tetrahedralization.\n");
14591 }
14592 }
14593
14594 // Prepare the array of points for inserting.
14595 arraysize = points->items;
14596 insertarray = new point[arraysize];
14597 // Randomize the point order.
14598 // randomseed = b->srandseed;
14599 points->traversalinit();
14600 for (i = 0; i < arraysize; i++) {
14601 j = (int) randomnation(i + 1); // 0 <= j <= i;
14602 insertarray[i] = insertarray[j];
14603 insertarray[j] = pointtraverse();
14604 }
14605 flipque = new queue(sizeof(badface));
14606
14607 // Form the DT by incremental flip Delaunay algorithm.
14608 incrflipdelaunay(NULL, insertarray, arraysize, true, b->plc, b->epsilon,
14609 flipque);
14610
14611 delete [] insertarray;
14612 delete flipque;
14613 return hullsize;
14614 }
14615
14616 //
14617 // End Delaunay tetrahedralization routines
14618 //
14619
14620 //
14621 // Begin of surface triangulation routines
14622 //
14623
14624 ///////////////////////////////////////////////////////////////////////////////
14625 // //
14626 // formstarpolygon() Form the star polygon of a point in facet. //
14627 // //
14628 // The polygon P is formed by all coplanar subfaces having 'pt' as a vertex. //
14629 // P is bounded by segments, e.g, if no segments, P is the full star of pt. //
14630 // //
14631 // 'trilist' T returns the subfaces, it has one of such subfaces on input. //
14632 // In addition, if f is in T, then sapex(f) = p. 'vertlist' V are verts of P.//
14633 // Topologically, T is the star of p; V and the edges of T are the link of p.//
14634 // //
14635 ///////////////////////////////////////////////////////////////////////////////
14636
14637 void tetgenmesh::formstarpolygon(point pt, list* trilist, list* vertlist)
14638 {
14639 face steinsh, lnextsh, rnextsh;
14640 face checkseg;
14641 point pa, pb, pc, pd;
14642 int i;
14643
14644 // Get a subface f containing p.
14645 steinsh = * (face *)(* trilist)[0];
14646 steinsh.shver = 0; // CCW
14647 // Let sapex(f) be p.
14648 for (i = 0; i < 3; i++) {
14649 if (sapex(steinsh) == pt) break;
14650 senextself(steinsh);
14651 }
14652 assert(i < 3);
14653 * (face *)(* trilist)[0] = steinsh;
14654 // Add two verts a, b and one edge ab of f into lists,
14655 pa = sorg(steinsh);
14656 pb = sdest(steinsh);
14657 vertlist->append(&pa);
14658 vertlist->append(&pb);
14659
14660 // Rotate edge pa to the left (CW) until meet pb or a segment.
14661 lnextsh = steinsh;
14662 pc = pa;
14663 do {
14664 senext2self(lnextsh);
14665 assert(sorg(lnextsh) == pt);
14666 sspivot(lnextsh, checkseg);
14667 if (checkseg.sh != dummysh) break; // Do not cross a segment.
14668 // Get neighbor subface n (must exist).
14669 spivotself(lnextsh);
14670 if (lnextsh.sh == dummysh) break; // It's a hull edge.
14671 // Go to the edge ca opposite to p.
14672 if (sdest(lnextsh) != pt) sesymself(lnextsh);
14673 assert(sdest(lnextsh) == pt);
14674 senext2self(lnextsh);
14675 // Add n (at edge ca) to T.
14676 trilist->append(&lnextsh);
14677 // Add edge ca to E.
14678 pc = sorg(lnextsh);
14679 if (pc == pb) break; // Rotate back.
14680 // Add vert c to V.
14681 vertlist->append(&pc);
14682 } while (true);
14683
14684 if (pc != pb) {
14685 // Rotate edge bp to the right (CCW) until meet a segment.
14686 rnextsh = steinsh;
14687 do {
14688 senextself(rnextsh);
14689 assert(sdest(rnextsh) == pt);
14690 sspivot(rnextsh, checkseg);
14691 if (checkseg.sh != dummysh) break; // Do not cross a segment.
14692 // Get neighbor subface n (must exist).
14693 spivotself(rnextsh);
14694 if (rnextsh.sh == dummysh) break; // It's a hull edge.
14695 // Go to the edge bd opposite to p.
14696 if (sorg(rnextsh) != pt) sesymself(rnextsh);
14697 assert(sorg(rnextsh) == pt);
14698 senextself(rnextsh);
14699 // Add n (at edge bd) to T.
14700 trilist->append(&rnextsh);
14701 // Add edge bd to E.
14702 pd = sdest(rnextsh);
14703 if (pd == pa) break; // Rotate back.
14704 // Add vert d to V.
14705 vertlist->append(&pd);
14706 } while (true);
14707 }
14708 }
14709
14710 ///////////////////////////////////////////////////////////////////////////////
14711 // //
14712 // About the 'abovepoint' //
14713 // //
14714 // The 'abovepoint' of a facet is a point which is exactly non-coplanar with //
14715 // the plane containing that facet. With such an point, the 3D predicates: //
14716 // orient3d(), and insphere() can be used to substitute the corresponding 2D //
14717 // siblings, e.g. orient2d(), and incircle(). Its location is not critical, //
14718 // but floating-point accuracy is improved if it is nicely placed over the //
14719 // facet, not too close or too far away. //
14720 // //
14721 // We take the convention that the abovepoint of a facet always lies above //
14722 // the facet. By this convention, given three points a, b, and c in a facet, //
14723 // we say c has the counterclockwise order with ab is corresponding to say //
14724 // that c is below the plane abp, where p is the lift point. //
14725 // //
14726 ///////////////////////////////////////////////////////////////////////////////
14727
14728 ///////////////////////////////////////////////////////////////////////////////
14729 // //
14730 // getfacetabovepoint() Get a point above a plane pass through a facet. //
14731 // //
14732 // The calulcated point is saved in 'facetabovepointarray'. The 'abovepoint' //
14733 // is set on return. //
14734 // //
14735 ///////////////////////////////////////////////////////////////////////////////
14736
14737 void tetgenmesh::getfacetabovepoint(face* facetsh)
14738 {
14739 list *verlist, *trilist, *tetlist;
14740 tetrahedron tetptr;
14741 triface adjtet;
14742 face symsh;
14743 point p1, p2, p3, pa;
14744 enum locateresult loc;
14745 REAL smallcos, cosa;
14746 REAL largevol, volume;
14747 REAL v1[3], v2[3], len;
14748 int smallidx, largeidx;
14749 int shmark;
14750 int i, j;
14751
14752 abovecount++;
14753 // Initialize working lists.
14754 verlist = new list(sizeof(point *), NULL);
14755 trilist = new list(sizeof(face), NULL);
14756 tetlist = new list(sizeof(triface), NULL);
14757
14758 // Get three pivotal points p1, p2, and p3 in the facet as a base triangle
14759 // which is non-trivil and has good base angle (close to 90 degree).
14760
14761 // p1 is chosen as the one which has the smallest index in pa, pb, pc.
14762 p1 = sorg(*facetsh);
14763 pa = sdest(*facetsh);
14764 if (pointmark(pa) < pointmark(p1)) p1 = pa;
14765 pa = sapex(*facetsh);
14766 if (pointmark(pa) < pointmark(p1)) p1 = pa;
14767 // Form the star polygon of p1.
14768 trilist->append(facetsh);
14769 formstarpolygon(p1, trilist, verlist);
14770
14771 // Get the second pivotal point p2.
14772 p2 = * (point *)(* verlist)[0];
14773 // Get vector v1 = p1->p2.
14774 for (i = 0; i < 3; i++) v1[i] = p2[i] - p1[i];
14775 len = sqrt(dot(v1, v1));
14776 assert(len > 0.0); // p2 != p1.
14777 for (i = 0; i < 3; i++) v1[i] /= len;
14778
14779 // Get the third pivotal point p3. p3 is chosen as the one in 'verlist'
14780 // which forms an angle with v1 closer to 90 degree than others do.
14781 smallcos = 1.0; // The cosine value of 0 degree.
14782 smallidx = 1; // Default value.
14783 for (i = 1; i < verlist->len(); i++) {
14784 p3 = * (point *)(* verlist)[i];
14785 for (j = 0; j < 3; j++) v2[j] = p3[j] - p1[j];
14786 len = sqrt(dot(v2, v2));
14787 if (len > 0.0) { // v2 is not too small.
14788 cosa = fabs(dot(v1, v2)) / len;
14789 if (cosa < smallcos) {
14790 smallidx = i;
14791 smallcos = cosa;
14792 }
14793 }
14794 }
14795 assert(smallcos < 1.0); // p1->p3 != p1->p2.
14796 p3 = * (point *)(* verlist)[smallidx];
14797 verlist->clear();
14798
14799 if (tetrahedrons->items > 0l) {
14800 // Get a tet having p1 as a vertex.
14801 stpivot(*facetsh, adjtet);
14802 if (adjtet.tet == dummytet) {
14803 sesym(*facetsh, symsh);
14804 stpivot(symsh, adjtet);
14805 }
14806 if (adjtet.tet == dummytet) {
14807 tetptr = point2tet(p1);
14808 if (tetptr != (tetrahedron) NULL) {
14809 decode(tetptr, adjtet);
14810 if (isdead(&adjtet)) {
14811 adjtet.tet = dummytet;
14812 }
14813 }
14814 }
14815 if (adjtet.tet == dummytet) {
14816 loc = locate(p1, &adjtet);
14817 if (loc != ONVERTEX) adjtet.tet = dummytet;
14818 }
14819 if (adjtet.tet != dummytet) {
14820 // Get the star polyhedron of p1.
14821 tetlist->append(&adjtet);
14822 formstarpolyhedron(p1, tetlist, verlist, false);
14823 }
14824 }
14825
14826 // Get the abovepoint in 'verlist'. It is the one form the largest valid
14827 // volumw with the base triangle over other points in 'verlist.
14828 largevol = 0.0;
14829 largeidx = 0;
14830 for (i = 0; i < verlist->len(); i++) {
14831 pa = * (point *)(* verlist)[i];
14832 volume = orient3d(p1, p2, p3, pa);
14833 if (!iscoplanar(p1, p2, p3, pa, volume, b->epsilon * 1e+2)) {
14834 if (fabs(volume) > largevol) {
14835 largevol = fabs(volume);
14836 largeidx = i;
14837 }
14838 }
14839 }
14840
14841 // Do we have the abovepoint?
14842 if (largevol > 0.0) {
14843 abovepoint = * (point *)(* verlist)[largeidx];
14844 if (b->verbose > 1) {
14845 printf(" Chosen abovepoint %d for facet %d.\n", pointmark(abovepoint),
14846 shellmark(*facetsh));
14847 }
14848 } else {
14849 // Calculate an abovepoint for this facet.
14850 facenormal(p1, p2, p3, v1, &len);
14851 if (len != 0.0) for (i = 0; i < 3; i++) v1[i] /= len;
14852 // Take the average edge length of the bounding box.
14853 len = (0.5*(xmax - xmin) + 0.5*(ymax - ymin) + 0.5*(zmax - zmin)) / 3.0;
14854 // Temporarily create a point. It will be removed by jettison();
14855 makepoint(&abovepoint);
14856 setpointtype(abovepoint, UNUSEDVERTEX);
14857 unuverts++;
14858 for (i = 0; i < 3; i++) abovepoint[i] = p1[i] + len * v1[i];
14859 if (b->verbose > 1) {
14860 printf(" Calculated abovepoint %d for facet %d.\n",
14861 pointmark(abovepoint), shellmark(*facetsh));
14862 }
14863 }
14864 // Save the abovepoint in 'facetabovepointarray'.
14865 shmark = shellmark(*facetsh);
14866 facetabovepointarray[shmark] = abovepoint;
14867
14868 delete trilist;
14869 delete tetlist;
14870 delete verlist;
14871 }
14872
14873 ///////////////////////////////////////////////////////////////////////////////
14874 // //
14875 // collectcavsubs() Collect non-locally Delaunay subfaces wrt a point. //
14876 // //
14877 // 'cavsublist' returns the list of subfaces. On input, it conatins at least //
14878 // one subface. //
14879 // //
14880 ///////////////////////////////////////////////////////////////////////////////
14881
14882 void tetgenmesh::collectcavsubs(point newpoint, list* cavsublist)
14883 {
14884 face startsub, neighsub;
14885 face checkseg;
14886 point pa, pb, pc;
14887 REAL sign, ori;
14888 int i, j;
14889
14890 // First infect subfaces in 'cavsublist'.
14891 for (i = 0; i < cavsublist->len(); i++) {
14892 startsub = * (face *)(* cavsublist)[i];
14893 sinfect(startsub);
14894 }
14895 // Find the other subfaces by a broadth-first searching.
14896 for (i = 0; i < cavsublist->len(); i++) {
14897 startsub = * (face *)(* cavsublist)[i];
14898 for (j = 0; j < 3; j++) {
14899 sspivot(startsub, checkseg);
14900 // Is there a segment?
14901 if (checkseg.sh == dummysh) {
14902 // No segment. Get the neighbor.
14903 spivot(startsub, neighsub);
14904 if (!sinfected(neighsub)) {
14905 pa = sorg(neighsub);
14906 pb = sdest(neighsub);
14907 pc = sapex(neighsub);
14908 sign = insphere(pa, pb, pc, abovepoint, newpoint);
14909 ori = orient3d(pa, pb, pc, abovepoint);
14910 if (sign != 0.0) {
14911 // Correct the sign.
14912 sign = ori > 0.0 ? sign : -sign;
14913 }
14914 if (sign > 0.0) {
14915 // neighsub is encroached by newpoint.
14916 sinfect(neighsub);
14917 cavsublist->append(&neighsub);
14918 }
14919 }
14920 }
14921 senextself(startsub);
14922 }
14923 }
14924 // Having found all subfaces, uninfect them before return.
14925 for (i = 0; i < cavsublist->len(); i++) {
14926 startsub = * (face *)(* cavsublist)[i];
14927 suninfect(startsub);
14928 }
14929 }
14930
14931 ///////////////////////////////////////////////////////////////////////////////
14932 // //
14933 // collectvisiblesubs() Collect convex hull edges which are visible from //
14934 // the inserting point. Construct new subfaces from //
14935 // these edges and the point. //
14936 // //
14937 // Let T be the current Delaunay triangulation (of vertices of a facet F). //
14938 // 'shmark', the index of F in 'in->facetlist' (starts from 1); 'inspoint' //
14939 // lies outside of T; 'horiz' is a hull edge of T which is visible by it. //
14940 // //
14941 ///////////////////////////////////////////////////////////////////////////////
14942
14943 void tetgenmesh::collectvisiblesubs(int shmark, point inspoint, face* horiz,
14944 queue* flipqueue)
14945 {
14946 face newsh, hullsh;
14947 face rightsh, leftsh, spinedge;
14948 point horg, hdest;
14949 bool aboveflag;
14950 REAL ori, sign;
14951
14952 // Get the sign of abovepoint (so we can assume it is above the plane).
14953 adjustedgering(*horiz, CCW);
14954 horg = sorg(*horiz);
14955 hdest = sdest(*horiz);
14956 ori = orient3d(horg, hdest, sapex(*horiz), abovepoint);
14957 sign = ori > 0.0 ? -1 : 1;
14958
14959 // Create a new subface above 'horiz'.
14960 makeshellface(subfaces, &newsh);
14961 setsorg(newsh, hdest);
14962 setsdest(newsh, horg);
14963 setsapex(newsh, inspoint);
14964 setshellmark(newsh, shmark);
14965 if (b->quality && varconstraint) {
14966 setareabound(newsh, areabound(*horiz));
14967 }
14968 if (checkpbcs) {
14969 setshellpbcgroup(newsh, shellpbcgroup(*horiz));
14970 }
14971 // Make the connection.
14972 sbond(newsh, *horiz);
14973 // 'horiz' becomes interior edge.
14974 enqueueflipedge(*horiz, flipqueue);
14975
14976 // Finish the hull edges at the right side of the newsh.
14977 hullsh = *horiz;
14978 while (1) {
14979 senext(newsh, rightsh);
14980 // Get the right hull edge of 'horiz' by spinning inside edges around
14981 // 'horg' until reaching the 'dummysh'.
14982 spinedge = hullsh;
14983 do {
14984 hullsh = spinedge;
14985 senext2self(hullsh);
14986 spivot(hullsh, spinedge);
14987 if (spinedge.sh == dummysh) break;
14988 if (sorg(spinedge) != horg) sesymself(spinedge);
14989 assert(sorg(spinedge) == horg);
14990 } while (true);
14991 horg = sorg(hullsh);
14992 // Test whether 'inspoint' is visible by 'hullsh'.
14993 ori = orient3d(horg, sdest(hullsh), abovepoint, inspoint);
14994 ori *= sign;
14995 aboveflag = ori < 0.0;
14996 if (aboveflag) {
14997 // It's visible.
14998 makeshellface(subfaces, &newsh);
14999 setsorg(newsh, sdest(hullsh));
15000 setsdest(newsh, horg);
15001 setsapex(newsh, inspoint);
15002 setshellmark(newsh, shmark);
15003 if (b->quality && varconstraint) {
15004 setareabound(newsh, areabound(hullsh));
15005 }
15006 if (checkpbcs) {
15007 setshellpbcgroup(newsh, shellpbcgroup(hullsh));
15008 }
15009 // Make the connection.
15010 sbond(newsh, hullsh);
15011 senext2(newsh, leftsh);
15012 sbond(leftsh, rightsh);
15013 // 'hullsh' becomes interior edge.
15014 enqueueflipedge(hullsh, flipqueue);
15015 } else {
15016 // 'rightsh' is a new hull edge.
15017 dummysh[0] = sencode(rightsh);
15018 break;
15019 }
15020 }
15021
15022 // Finish the hull edges at the left side of the newsh.
15023 hullsh = *horiz;
15024 spivot(*horiz, newsh);
15025 while (1) {
15026 senext2(newsh, leftsh);
15027 // Get the left hull edge of 'horiz' by spinning edges around 'hdest'.
15028 spinedge = hullsh;
15029 do {
15030 hullsh = spinedge;
15031 senextself(hullsh);
15032 spivot(hullsh, spinedge);
15033 if (spinedge.sh == dummysh) break;
15034 if (sdest(spinedge) != hdest) sesymself(spinedge);
15035 assert(sdest(spinedge) == hdest);
15036 } while (true);
15037 // Update 'hdest'.
15038 hdest = sdest(hullsh);
15039 // Test whether 'inspoint' is visible from 'hullsh'.
15040 ori = orient3d(sorg(hullsh), hdest, abovepoint, inspoint);
15041 ori *= sign;
15042 aboveflag = ori < 0.0;
15043 if (aboveflag) {
15044 // It's a visible hull edge.
15045 makeshellface(subfaces, &newsh);
15046 setsorg(newsh, hdest);
15047 setsdest(newsh, sorg(hullsh));
15048 setsapex(newsh, inspoint);
15049 setshellmark(newsh, shmark);
15050 if (b->quality && varconstraint) {
15051 setareabound(newsh, areabound(hullsh));
15052 }
15053 if (checkpbcs) {
15054 setshellpbcgroup(newsh, shellpbcgroup(hullsh));
15055 }
15056 // Make the connection.
15057 sbond(newsh, hullsh);
15058 senext(newsh, rightsh);
15059 sbond(rightsh, leftsh);
15060 // 'horiz' becomes interior edge.
15061 enqueueflipedge(hullsh, flipqueue);
15062 } else {
15063 // 'leftsh' is a new hull edge.
15064 dummysh[0] = sencode(leftsh);
15065 break;
15066 }
15067 }
15068 }
15069
15070 ///////////////////////////////////////////////////////////////////////////////
15071 // //
15072 // incrflipdelaunaysub() Create a DT from a 3D coplanar point set using //
15073 // the incremental flip algorithm. //
15074 // //
15075 // Let T be the current Delaunay triangulation (of vertices of a facet F). //
15076 // 'shmark', the index of F in 'in->facetlist' (starts from 1). //
15077 // //
15078 ///////////////////////////////////////////////////////////////////////////////
15079
15080 void tetgenmesh::incrflipdelaunaysub(int shmark, REAL eps, list* ptlist,
15081 int holes, REAL* holelist, queue* flipque)
15082 {
15083 face newsh, startsh;
15084 point *insertarray;
15085 point swappt;
15086 pbcdata *pd;
15087 enum locateresult loc;
15088 REAL det, area;
15089 bool aboveflag;
15090 int arraysize;
15091 int fmarker;
15092 int idx, i, j, k;
15093
15094 // Get the point array (saved in 'ptlist').
15095 insertarray = (point *) ptlist->base;
15096 arraysize = ptlist->len();
15097 if (arraysize < 3) return;
15098
15099 // Do calculation of 'abovepoint' if number of points > 3.
15100 aboveflag = (arraysize > 3);
15101
15102 // The initial triangulation T only has one triangle formed by 3 not
15103 // cillinear points of the set V = 'insertarray'. The first point:
15104 // a = insertarray[0].
15105
15106 for (i = 1; i < arraysize; i++) {
15107 det = distance(insertarray[0], insertarray[i]);
15108 if (det > (longest * eps)) break;
15109 }
15110 if (i < arraysize) {
15111 // Swap to move b from index i to index 1.
15112 swappt = insertarray[i];
15113 insertarray[i] = insertarray[1];
15114 insertarray[1] = swappt;
15115 }
15116 // Get the third point c, that is not collinear with a and b.
15117 for (i++; i < arraysize; i++) {
15118 if (!iscollinear(insertarray[0], insertarray[1], insertarray[i], eps))
15119 break;
15120 }
15121 if (i < arraysize) {
15122 // Swap to move c from index i to index 2.
15123 swappt = insertarray[i];
15124 insertarray[i] = insertarray[2];
15125 insertarray[2] = swappt;
15126 i = 3; // The next inserting point.
15127 } else {
15128 // The set of vertices is not good (or nearly degenerate). However,
15129 // a trivial triangulation can be formed (using 3 vertices). It may
15130 // be corrected (or deleted) by mergefacet().
15131 if (eps == 0.0) {
15132 if (!b->quiet) {
15133 printf("Warning: Facet %d (%d, %d, %d", shmark,
15134 pointmark(insertarray[0]), pointmark(insertarray[1]),
15135 pointmark(insertarray[2]));
15136 if (ptlist->len() > 3) {
15137 printf(", ...");
15138 }
15139 printf(") is not a valid polygon.\n");
15140 }
15141 }
15142 // Only use the first three points.
15143 i = arraysize;
15144 // Don't do calculation of abovepoint.
15145 aboveflag = false;
15146 }
15147
15148 // Create the initial triangle.
15149 makeshellface(subfaces, &newsh);
15150 setsorg(newsh, insertarray[0]);
15151 setsdest(newsh, insertarray[1]);
15152 setsapex(newsh, insertarray[2]);
15153 // Remeber the facet it belongs to.
15154 setshellmark(newsh, shmark);
15155 // Set vertex type be FACETVERTEX if it has no type yet.
15156 if (pointtype(insertarray[0]) == VOLVERTEX) {
15157 setpointtype(insertarray[0], FACETVERTEX);
15158 }
15159 if (pointtype(insertarray[1]) == VOLVERTEX) {
15160 setpointtype(insertarray[1], FACETVERTEX);
15161 }
15162 if (pointtype(insertarray[2]) == VOLVERTEX) {
15163 setpointtype(insertarray[2], FACETVERTEX);
15164 }
15165 // Let 'dummysh' point to it (for point location).
15166 dummysh[0] = sencode(newsh);
15167
15168 // Are there area constraints?
15169 if (b->quality && (in->facetconstraintlist != (REAL *) NULL)) {
15170 idx = in->facetmarkerlist[shmark - 1]; // The actual facet marker.
15171 for (k = 0; k < in->numberoffacetconstraints; k++) {
15172 fmarker = (int) in->facetconstraintlist[k * 2];
15173 if (fmarker == idx) {
15174 area = in->facetconstraintlist[k * 2 + 1];
15175 setareabound(newsh, area);
15176 break;
15177 }
15178 }
15179 }
15180
15181 // Are there pbc conditions?
15182 if (checkpbcs) {
15183 idx = in->facetmarkerlist[shmark - 1]; // The actual facet marker.
15184 for (k = 0; k < in->numberofpbcgroups; k++) {
15185 pd = &subpbcgrouptable[k];
15186 for (j = 0; j < 2; j++) {
15187 if (pd->fmark[j] == idx) {
15188 setshellpbcgroup(newsh, k);
15189 pd->ss[j] = newsh;
15190 }
15191 }
15192 }
15193 }
15194
15195 if (aboveflag) {
15196 // Compute the 'abovepoint' for orient3d().
15197 abovepoint = facetabovepointarray[shmark];
15198 if (abovepoint == (point) NULL) {
15199 getfacetabovepoint(&newsh);
15200 }
15201 }
15202
15203 if (holes > 0) {
15204 // Project hole points onto the plane containing the facet.
15205 REAL prj[3];
15206 for (k = 0; k < holes; k++) {
15207 projpt2face(&(holelist[k * 3]), insertarray[0], insertarray[1],
15208 insertarray[2], prj);
15209 for (j = 0; j < 3; j++) holelist[k * 3 + j] = prj[j];
15210 }
15211 }
15212
15213 // Incrementally insert the rest of points into T.
15214 for (; i < arraysize; i++) {
15215 // Insert p_i.
15216 startsh.sh = dummysh;
15217 loc = locatesub(insertarray[i], &startsh, 0, 0.0);
15218 if (loc == ONFACE) {
15219 splitsubface(insertarray[i], &startsh, flipque);
15220 } else if (loc == ONEDGE) {
15221 splitsubedge(insertarray[i], &startsh, flipque);
15222 } else if (loc == OUTSIDE) {
15223 collectvisiblesubs(shmark, insertarray[i], &startsh, flipque);
15224 } else if (loc == ONVERTEX) {
15225 // !should not happen!
15226 }
15227 // Set p_i's type FACETVERTEX if it has no type yet.
15228 if (pointtype(insertarray[i]) == VOLVERTEX) {
15229 setpointtype(insertarray[i], FACETVERTEX);
15230 }
15231 flipsub(flipque);
15232 }
15233 }
15234
15235 ///////////////////////////////////////////////////////////////////////////////
15236 // //
15237 // finddirectionsub() Find the first subface in a facet on the path from //
15238 // one point to another. //
15239 // //
15240 // Finds the subface in the facet that intersects a line segment drawn from //
15241 // the origin of `searchsh' to the point `tend', and returns the result in //
15242 // `searchsh'. The origin of `searchsh' does not change, even though the //
15243 // subface returned may differ from the one passed in. //
15244 // //
15245 // The return value notes whether the destination or apex of the found face //
15246 // is collinear with the two points in question. //
15247 // //
15248 ///////////////////////////////////////////////////////////////////////////////
15249
15250 enum tetgenmesh::finddirectionresult tetgenmesh::finddirectionsub(
15251 face* searchsh, point tend)
15252 {
15253 face checksh;
15254 point startpoint, leftpoint, rightpoint;
15255 REAL leftccw, rightccw;
15256 REAL ori, sign;
15257 int leftflag, rightflag;
15258
15259 startpoint = sorg(*searchsh);
15260 // Find the sign to simulate that abovepoint is 'above' the facet.
15261 adjustedgering(*searchsh, CCW);
15262 // Make sure 'startpoint' is the origin.
15263 if (sorg(*searchsh) != startpoint) senextself(*searchsh);
15264 rightpoint = sdest(*searchsh);
15265 leftpoint = sapex(*searchsh);
15266 ori = orient3d(startpoint, rightpoint, leftpoint, abovepoint);
15267 sign = ori > 0.0 ? -1 : 1;
15268
15269 // Is `tend' to the left?
15270 ori = orient3d(tend, startpoint, abovepoint, leftpoint);
15271 leftccw = ori * sign;
15272 leftflag = leftccw > 0.0;
15273 // Is `tend' to the right?
15274 ori = orient3d(startpoint, tend, abovepoint, rightpoint);
15275 rightccw = ori * sign;
15276 rightflag = rightccw > 0.0;
15277 if (leftflag && rightflag) {
15278 // `searchsh' faces directly away from `tend'. We could go left or
15279 // right. Ask whether it's a triangle or a boundary on the left.
15280 senext2(*searchsh, checksh);
15281 spivotself(checksh);
15282 if (checksh.sh == dummysh) {
15283 leftflag = 0;
15284 } else {
15285 rightflag = 0;
15286 }
15287 }
15288 while (leftflag) {
15289 // Turn left until satisfied.
15290 senext2self(*searchsh);
15291 spivotself(*searchsh);
15292 if (searchsh->sh == dummysh) {
15293 printf("Internal error in finddirectionsub(): Unable to find a\n");
15294 printf(" subface leading from %d to %d.\n", pointmark(startpoint),
15295 pointmark(tend));
15296 internalerror();
15297 }
15298 if (sorg(*searchsh) != startpoint) sesymself(*searchsh);
15299 assert(sorg(*searchsh) == startpoint);
15300 leftpoint = sapex(*searchsh);
15301 rightccw = leftccw;
15302 ori = orient3d(tend, startpoint, abovepoint, leftpoint);
15303 leftccw = ori * sign;
15304 leftflag = leftccw > 0.0;
15305 }
15306 while (rightflag) {
15307 // Turn right until satisfied.
15308 spivotself(*searchsh);
15309 if (searchsh->sh == dummysh) {
15310 printf("Internal error in finddirectionsub(): Unable to find a\n");
15311 printf(" subface leading from %d to %d.\n", pointmark(startpoint),
15312 pointmark(tend));
15313 internalerror();
15314 }
15315 if (sdest(*searchsh) != startpoint) sesymself(*searchsh);
15316 assert(sdest(*searchsh) == startpoint);
15317 senextself(*searchsh);
15318 rightpoint = sdest(*searchsh);
15319 leftccw = rightccw;
15320 ori = orient3d(startpoint, tend, abovepoint, rightpoint);
15321 rightccw = ori * sign;
15322 rightflag = rightccw > 0.0;
15323 }
15324 if (leftccw == 0.0) {
15325 return LEFTCOLLINEAR;
15326 } else if (rightccw == 0.0) {
15327 return RIGHTCOLLINEAR;
15328 } else {
15329 return ACROSSEDGE;
15330 }
15331 }
15332
15333 ///////////////////////////////////////////////////////////////////////////////
15334 // //
15335 // insertsubseg() Create a subsegment and insert it between two subfaces. //
15336 // //
15337 // The new subsegment ab is inserted at the edge of subface 'tri'. If ab is //
15338 // not a hull edge, it is inserted between two subfaces. If 'tri' is a hull //
15339 // face, the initial face ring of ab will be set only one face which is self-//
15340 // bonded. The final face ring will be constructed in 'unifysegments()'. //
15341 // //
15342 ///////////////////////////////////////////////////////////////////////////////
15343
15344 void tetgenmesh::insertsubseg(face* tri)
15345 {
15346 face oppotri;
15347 face newsubseg;
15348 point pa, pb;
15349 REAL len;
15350 int e1, e2;
15351 int i;
15352
15353 // Check if there's already a subsegment here.
15354 sspivot(*tri, newsubseg);
15355 if (newsubseg.sh == dummysh) {
15356 // Make new subsegment and initialize its vertices.
15357 makeshellface(subsegs, &newsubseg);
15358 pa = sorg(*tri);
15359 pb = sdest(*tri);
15360 setsorg(newsubseg, pa);
15361 setsdest(newsubseg, pb);
15362 // Are there length constraints?
15363 if (b->quality && (in->segmentconstraintlist != (REAL *) NULL)) {
15364 for (i = 0; i < in->numberofsegmentconstraints; i++) {
15365 e1 = (int) in->segmentconstraintlist[i * 3];
15366 e2 = (int) in->segmentconstraintlist[i * 3 + 1];
15367 if (((pointmark(pa) == e1) && (pointmark(pb) == e2)) ||
15368 ((pointmark(pa) == e2) && (pointmark(pb) == e1))) {
15369 len = in->segmentconstraintlist[i * 3 + 2];
15370 setareabound(newsubseg, len);
15371 break;
15372 }
15373 }
15374 }
15375 // Bond new subsegment to the two subfaces it is sandwiched between.
15376 ssbond(*tri, newsubseg);
15377 spivot(*tri, oppotri);
15378 // 'oppotri' might be "out space".
15379 if (oppotri.sh != dummysh) {
15380 ssbond(oppotri, newsubseg);
15381 } /* else {
15382 // Outside! Bond '*tri' to itself.
15383 sbond(*tri, *tri);
15384 } */
15385 }
15386 }
15387
15388 ///////////////////////////////////////////////////////////////////////////////
15389 // //
15390 // scoutsegmentsub() Scout the first triangle on the path from one point //
15391 // to another, and check for completion (reaching the //
15392 // second point), a collinear point,or the intersection //
15393 // of two segments. //
15394 // //
15395 // Returns true if the entire segment is successfully inserted, and false if //
15396 // the job must be finished by constrainededge(). //
15397 // //
15398 ///////////////////////////////////////////////////////////////////////////////
15399
15400 bool tetgenmesh::scoutsegmentsub(face* searchsh, point tend)
15401 {
15402 face newsubseg;
15403 face crosssub, crosssubseg;
15404 point leftpoint, rightpoint;
15405 enum finddirectionresult collinear;
15406
15407 collinear = finddirectionsub(searchsh, tend);
15408 rightpoint = sdest(*searchsh);
15409 leftpoint = sapex(*searchsh);
15410 if (rightpoint == tend || leftpoint == tend) {
15411 // The segment is already an edge.
15412 if (leftpoint == tend) {
15413 senext2self(*searchsh);
15414 }
15415 // Insert a subsegment.
15416 insertsubseg(searchsh);
15417 return true;
15418 } else if (collinear == LEFTCOLLINEAR) {
15419 // We've collided with a vertex between the segment's endpoints.
15420 // Make the collinear vertex be the triangle's origin.
15421 senextself(*searchsh); // lprevself(*searchtri);
15422 // Insert a subsegment.
15423 insertsubseg(searchsh);
15424 // Insert the remainder of the segment.
15425 return scoutsegmentsub(searchsh, tend);
15426 } else if (collinear == RIGHTCOLLINEAR) {
15427 // We've collided with a vertex between the segment's endpoints.
15428 // Insert a subsegment.
15429 insertsubseg(searchsh);
15430 // Make the collinear vertex be the triangle's origin.
15431 senextself(*searchsh); // lnextself(*searchtri);
15432 // Insert the remainder of the segment.
15433 return scoutsegmentsub(searchsh, tend);
15434 } else {
15435 senext(*searchsh, crosssub); // lnext(*searchtri, crosstri);
15436 // Check for a crossing segment.
15437 sspivot(crosssub, crosssubseg);
15438 #ifdef SELF_CHECK
15439 assert(crosssubseg.sh == dummysh);
15440 #endif
15441 return false;
15442 }
15443 }
15444
15445 ///////////////////////////////////////////////////////////////////////////////
15446 // //
15447 // flipedgerecursive() Flip an edge. //
15448 // //
15449 // This is a support routine for inserting segments into a CDT. //
15450 // //
15451 // Let 'flipedge' be ab, and two triangles abc, abd share at it. ab may not //
15452 // flipable if the four vertices a, b, c, and d are non-convex. If it is the //
15453 // case, recursively flip ad or bd. Return when ab is flipped. //
15454 // //
15455 ///////////////////////////////////////////////////////////////////////////////
15456
15457 void tetgenmesh::flipedgerecursive(face* flipedge, queue* flipqueue)
15458 {
15459 face fixupsh;
15460 point pa, pb, pc, pd;
15461 REAL oria, orib;
15462 bool doflip;
15463
15464 pa = sorg(*flipedge);
15465 pb = sdest(*flipedge);
15466 pc = sapex(*flipedge);
15467 do {
15468 spivot(*flipedge, fixupsh);
15469 pd = sapex(fixupsh);
15470 oria = orient3d(pc, pd, abovepoint, pa);
15471 orib = orient3d(pc, pd, abovepoint, pb);
15472 doflip = (oria * orib < 0.0);
15473 if (doflip) {
15474 // Flip the edge (a, b) away.
15475 flip22sub(flipedge, flipqueue);
15476 // Fix flipedge on edge e (c, d).
15477 findedge(flipedge, pc, pd);
15478 } else {
15479 // ab is unflipable. Get the next edge (bd, or da) to flip.
15480 if (sorg(fixupsh) != pb) sesymself(fixupsh);
15481 assert(sdest(fixupsh) == pa);
15482 if (fabs(oria) > fabs(orib)) {
15483 // acd has larger area. Choose da.
15484 senextself(fixupsh);
15485 } else {
15486 // bcd has larger area. Choose bd.
15487 senext2self(fixupsh);
15488 }
15489 // Flip the edge.
15490 flipedgerecursive(&fixupsh, flipqueue);
15491 }
15492 } while (!doflip);
15493 }
15494
15495 ///////////////////////////////////////////////////////////////////////////////
15496 // //
15497 // constrainededge() Force a segment into a CDT. //
15498 // //
15499 // The segment s is recovered by flipping away the edges it intersects, and //
15500 // triangulating the polygons that form on each side of it. //
15501 // //
15502 // Generates a single subsegment connecting `tstart' to `tend'. The triangle //
15503 // `startsh' has `tstart' as its origin. //
15504 // //
15505 ///////////////////////////////////////////////////////////////////////////////
15506
15507 void tetgenmesh::constrainededge(face* startsh, point tend, queue* flipqueue)
15508 {
15509 point tstart, tright, tleft;
15510 REAL rori, lori;
15511 bool collision;
15512
15513 tstart = sorg(*startsh);
15514 do {
15515 // Loop edges oppo to tstart until find one crosses the segment.
15516 do {
15517 tright = sdest(*startsh);
15518 tleft = sapex(*startsh);
15519 // Is edge (tright, tleft) corss the segment.
15520 rori = orient3d(tstart, tright, abovepoint, tend);
15521 collision = (rori == 0.0);
15522 if (collision) break; // tright is on the segment.
15523 lori = orient3d(tstart, tleft, abovepoint, tend);
15524 collision = (lori == 0.0);
15525 if (collision) { // tleft is on the segment.
15526 senext2self(*startsh);
15527 break;
15528 }
15529 if (rori * lori < 0.0) break; // Find the crossing edge.
15530 // Both points are at one side of the segment.
15531 finddirectionsub(startsh, tend);
15532 } while (true);
15533 if (collision) break;
15534 // Get the neighbor face at edge e (tright, tleft).
15535 senextself(*startsh);
15536 // Flip the crossing edge.
15537 flipedgerecursive(startsh, flipqueue);
15538 // After flip, sorg(*startsh) == tstart.
15539 assert(sorg(*startsh) == tstart);
15540 } while (sdest(*startsh) != tend);
15541
15542 // Insert a subsegment to make the segment permanent.
15543 insertsubseg(startsh);
15544 // If there was a collision with an interceding vertex, install another
15545 // segment connecting that vertex with endpoint2.
15546 if (collision) {
15547 // Insert the remainder of the segment.
15548 if (!scoutsegmentsub(startsh, tend)) {
15549 constrainededge(startsh, tend, flipqueue);
15550 }
15551 }
15552 }
15553
15554 ///////////////////////////////////////////////////////////////////////////////
15555 // //
15556 // recoversegment() Recover a segment in the surface triangulation. //
15557 // //
15558 ///////////////////////////////////////////////////////////////////////////////
15559
15560 void tetgenmesh::recoversegment(point tstart, point tend, queue* flipqueue)
15561 {
15562 face searchsh;
15563
15564 if (b->verbose > 2) {
15565 printf(" Insert seg (%d, %d).\n", pointmark(tstart), pointmark(tend));
15566 }
15567
15568 // Find a triangle whose origin is the segment's first endpoint.
15569 searchsh.sh = dummysh;
15570 // Search for the segment's first endpoint by point location.
15571 if (locatesub(tstart, &searchsh, 0, 0.0) != ONVERTEX) {
15572 // Possibly caused by a degenerate subface. Do a brute-force search.
15573 list *newshlist;
15574 int i, j;
15575 newshlist = new list(sizeof(face), NULL, 256);
15576 // Get new subfaces, do not remove protected segments.
15577 retrievenewsubs(newshlist, false);
15578 // Search for a sub contain tstart.
15579 for (i = 0; i < newshlist->len(); i++) {
15580 searchsh = * (face *)(* newshlist)[i];
15581 for (j = 0; j < 3; j++) {
15582 if (sorg(searchsh) == tstart) break;
15583 senextself(searchsh);
15584 }
15585 if (j < 3) break;
15586 }
15587 delete newshlist;
15588 if (sorg(searchsh) != tstart) {
15589 printf("Internal error in recoversegment(): Vertex location failed.\n");
15590 internalerror();
15591 }
15592 }
15593 // Scout the segment and insert it if it is found.
15594 if (scoutsegmentsub(&searchsh, tend)) {
15595 // The segment was easily inserted.
15596 return;
15597 }
15598 // Insert the segment into the triangulation by flips.
15599 constrainededge(&searchsh, tend, flipqueue);
15600 // Some edges may need flipping.
15601 flipsub(flipqueue);
15602 }
15603
15604 ///////////////////////////////////////////////////////////////////////////////
15605 // //
15606 // infecthullsub() Virally infect all of the triangles of the convex hull //
15607 // that are not protected by subsegments. //
15608 // //
15609 ///////////////////////////////////////////////////////////////////////////////
15610
15611 void tetgenmesh::infecthullsub(memorypool* viri)
15612 {
15613 face hulltri, nexttri, starttri;
15614 face hullsubseg;
15615 shellface **deadshellface;
15616
15617 // Find a triangle handle on the hull.
15618 hulltri.sh = dummysh;
15619 hulltri.shver = 0;
15620 spivotself(hulltri);
15621 adjustedgering(hulltri, CCW);
15622 // Remember where we started so we know when to stop.
15623 starttri = hulltri;
15624 // Go once counterclockwise around the convex hull.
15625 do {
15626 // Ignore triangles that are already infected.
15627 if (!sinfected(hulltri)) {
15628 // Is the triangle protected by a subsegment?
15629 sspivot(hulltri, hullsubseg);
15630 if (hullsubseg.sh == dummysh) {
15631 // The triangle is not protected; infect it.
15632 if (!sinfected(hulltri)) {
15633 sinfect(hulltri);
15634 deadshellface = (shellface **) viri->alloc();
15635 *deadshellface = hulltri.sh;
15636 }
15637 }
15638 }
15639 // To find the next hull edge, go clockwise around the next vertex.
15640 senextself(hulltri); // lnextself(hulltri);
15641 spivot(hulltri, nexttri); // oprev(hulltri, nexttri);
15642 if (nexttri.sh == hulltri.sh) {
15643 nexttri.sh = dummysh; // 'hulltri' is self-bonded.
15644 } else {
15645 adjustedgering(nexttri, CCW);
15646 senextself(nexttri);
15647 }
15648 while (nexttri.sh != dummysh) {
15649 hulltri = nexttri;
15650 spivot(hulltri, nexttri); // oprev(hulltri, nexttri);
15651 if (nexttri.sh == hulltri.sh) {
15652 nexttri.sh = dummysh; // 'hulltri' is self-bonded.
15653 } else {
15654 adjustedgering(nexttri, CCW);
15655 senextself(nexttri);
15656 }
15657 }
15658 } while (hulltri != starttri);
15659 }
15660
15661 ///////////////////////////////////////////////////////////////////////////////
15662 // //
15663 // plaguesub() Spread the virus from all infected triangles to any //
15664 // neighbors not protected by subsegments. Delete all //
15665 // infected triangles. //
15666 // //
15667 // This is the procedure that actually creates holes and concavities. //
15668 // //
15669 ///////////////////////////////////////////////////////////////////////////////
15670
15671 void tetgenmesh::plaguesub(memorypool* viri)
15672 {
15673 face testtri, neighbor, ghostsh;
15674 face neighborsubseg;
15675 shellface **virusloop;
15676 shellface **deadshellface;
15677 int i;
15678
15679 // Loop through all the infected triangles, spreading the virus to
15680 // their neighbors, then to their neighbors' neighbors.
15681 viri->traversalinit();
15682 virusloop = (shellface **) viri->traverse();
15683 while (virusloop != (shellface **) NULL) {
15684 testtri.sh = *virusloop;
15685 // Check each of the triangle's three neighbors.
15686 for (i = 0; i < 3; i++) {
15687 // Find the neighbor.
15688 spivot(testtri, neighbor);
15689 // Check for a subsegment between the triangle and its neighbor.
15690 sspivot(testtri, neighborsubseg);
15691 // Check if the neighbor is nonexistent or already infected.
15692 if ((neighbor.sh == dummysh) || sinfected(neighbor)) {
15693 if (neighborsubseg.sh != dummysh) {
15694 // There is a subsegment separating the triangle from its
15695 // neighbor, but both triangles are dying, so the subsegment
15696 // dies too.
15697 shellfacedealloc(subsegs, neighborsubseg.sh);
15698 if (neighbor.sh != dummysh) {
15699 // Make sure the subsegment doesn't get deallocated again
15700 // later when the infected neighbor is visited.
15701 ssdissolve(neighbor);
15702 }
15703 }
15704 } else { // The neighbor exists and is not infected.
15705 if (neighborsubseg.sh == dummysh) {
15706 // There is no subsegment protecting the neighbor, so the
15707 // neighbor becomes infected.
15708 sinfect(neighbor);
15709 // Ensure that the neighbor's neighbors will be infected.
15710 deadshellface = (shellface **) viri->alloc();
15711 *deadshellface = neighbor.sh;
15712 } else { // The neighbor is protected by a subsegment.
15713 // Remove this triangle from the subsegment.
15714 ssbond(neighbor, neighborsubseg);
15715 }
15716 }
15717 senextself(testtri);
15718 }
15719 virusloop = (shellface **) viri->traverse();
15720 }
15721
15722 ghostsh.sh = dummysh; // A handle of outer space.
15723 viri->traversalinit();
15724 virusloop = (shellface **) viri->traverse();
15725 while (virusloop != (shellface **) NULL) {
15726 testtri.sh = *virusloop;
15727 // Record changes in the number of boundary edges, and disconnect
15728 // dead triangles from their neighbors.
15729 for (i = 0; i < 3; i++) {
15730 spivot(testtri, neighbor);
15731 if (neighbor.sh != dummysh) {
15732 // Disconnect the triangle from its neighbor.
15733 // sdissolve(neighbor);
15734 sbond(neighbor, ghostsh);
15735 }
15736 senextself(testtri);
15737 }
15738 // Return the dead triangle to the pool of triangles.
15739 shellfacedealloc(subfaces, testtri.sh);
15740 virusloop = (shellface **) viri->traverse();
15741 }
15742 // Empty the virus pool.
15743 viri->restart();
15744 }
15745
15746 ///////////////////////////////////////////////////////////////////////////////
15747 // //
15748 // carveholessub() Find the holes and infect them. Find the area //
15749 // constraints and infect them. Infect the convex hull. //
15750 // Spread the infection and kill triangles. Spread the //
15751 // area constraints. //
15752 // //
15753 // This routine mainly calls other routines to carry out all these functions.//
15754 // //
15755 ///////////////////////////////////////////////////////////////////////////////
15756
15757 void tetgenmesh::carveholessub(int holes, REAL* holelist, memorypool *viri)
15758 {
15759 face searchtri, triangleloop;
15760 shellface **holetri;
15761 enum locateresult intersect;
15762 int i;
15763
15764 // Mark as infected any unprotected triangles on the boundary.
15765 // This is one way by which concavities are created.
15766 infecthullsub(viri);
15767
15768 if (holes > 0) {
15769 // Infect each triangle in which a hole lies.
15770 for (i = 0; i < 3 * holes; i += 3) {
15771 // Ignore holes that aren't within the bounds of the mesh.
15772 if ((holelist[i] >= xmin) && (holelist[i] <= xmax)
15773 && (holelist[i + 1] >= ymin) && (holelist[i + 1] <= ymax)
15774 && (holelist[i + 2] >= zmin) && (holelist[i + 2] <= zmax)) {
15775 // Start searching from some triangle on the outer boundary.
15776 searchtri.sh = dummysh;
15777 // Find a triangle that contains the hole.
15778 intersect = locatesub(&holelist[i], &searchtri, 0, 0.0);
15779 if ((intersect != OUTSIDE) && (!sinfected(searchtri))) {
15780 // Infect the triangle. This is done by marking the triangle
15781 // as infected and including the triangle in the virus pool.
15782 sinfect(searchtri);
15783 holetri = (shellface **) viri->alloc();
15784 *holetri = searchtri.sh;
15785 }
15786 }
15787 }
15788 }
15789
15790 if (viri->items > 0) {
15791 // Carve the holes and concavities.
15792 plaguesub(viri);
15793 }
15794 // The virus pool should be empty now.
15795 }
15796
15797 ///////////////////////////////////////////////////////////////////////////////
15798 // //
15799 // triangulate() Triangulate a PSLG into a CDT. //
15800 // //
15801 // A Planar Straight Line Graph (PSLG) P is actually a 2D polygonal region, //
15802 // possibly contains holes, segments and vertices in its interior. P is tri- //
15803 // angulated into a set of _subfaces_ forming a CDT of P. //
15804 // //
15805 // The vertices and segments of P are found in 'ptlist' and 'conlist', resp- //
15806 // ectively. 'holelist' contains a list of hole points. 'shmark' will be set //
15807 // to all subfaces of P. //
15808 // //
15809 // The CDT is created directly in the pools 'subfaces' and 'subsegs'. It can //
15810 // be retrived by a broadth-first searching starting from 'dummysh[0]'(debug //
15811 // function 'outsurfmesh()' does it). //
15812 // //
15813 ///////////////////////////////////////////////////////////////////////////////
15814
15815 void tetgenmesh::triangulate(int shmark, REAL eps, list* ptlist, list* conlist,
15816 int holes, REAL* holelist, memorypool* viri, queue* flipqueue)
15817 {
15818 face newsh;
15819 point *cons;
15820 int i;
15821
15822 if (b->verbose > 1) {
15823 printf(" %d vertices, %d segments", ptlist->len(), conlist->len());
15824 if (holes > 0) {
15825 printf(", %d holes", holes);
15826 }
15827 printf(", shmark: %d.\n", shmark);
15828 }
15829
15830 // Create the DT of V by the 2D incremental flip algorithm.
15831 incrflipdelaunaysub(shmark, eps, ptlist, holes, holelist, flipqueue);
15832 // Recover boundary edges.
15833 if (ptlist->len() > 3) {
15834 // Insert segments into the DT.
15835 for (i = 0; i < conlist->len(); i++) {
15836 cons = (point *)(* conlist)[i];
15837 recoversegment(cons[0], cons[1], flipqueue);
15838 }
15839 // Carve holes and concavities.
15840 carveholessub(holes, holelist, viri);
15841 } else if (ptlist->len() == 3) {
15842 // Insert 3 segments directly.
15843 newsh.sh = dummysh;
15844 newsh.shver = 0;
15845 spivotself(newsh);
15846 for (i = 0; i < 3; i++) {
15847 insertsubseg(&newsh);
15848 senextself(newsh);
15849 }
15850 }
15851 }
15852
15853 ///////////////////////////////////////////////////////////////////////////////
15854 // //
15855 // retrievenewsubs() Retrieve newly created subfaces. //
15856 // //
15857 // The new subfaces created by triangulate() can be found by a broadth-first //
15858 // searching starting from 'dummysh[0]'. //
15859 // //
15860 // 'newshlist' (empty on input) returns the retrieved subfaces. Each edge on //
15861 // the hull is bound to 'dummysh' and protected by a segment. If 'removeseg' //
15862 // is TRUE, the segment is removed. //
15863 // //
15864 ///////////////////////////////////////////////////////////////////////////////
15865
15866 void tetgenmesh::retrievenewsubs(list* newshlist, bool removeseg)
15867 {
15868 face startsh, neighsh;
15869 face deadseg;
15870 int i, j;
15871
15872 // The first new subface is found at dummysh[0].
15873 startsh.sh = dummysh;
15874 startsh.shver = 0;
15875 spivotself(startsh);
15876 assert(startsh.sh != dummysh);
15877 sinfect(startsh);
15878 newshlist->append(&startsh);
15879
15880 // Find the rest of new subfaces by a broadth-first searching.
15881 for (i = 0; i < newshlist->len(); i++) {
15882 // Get a new subface s.
15883 startsh = * (face *)(* newshlist)[i];
15884 for (j = 0; j < 3; j++) {
15885 spivot(startsh, neighsh);
15886 if (neighsh.sh != dummysh) {
15887 if (!sinfected(neighsh)) {
15888 // Discovered a new subface.
15889 sinfect(neighsh);
15890 newshlist->append(&neighsh);
15891 }
15892 } else {
15893 // Found a boundary edge.
15894 if (removeseg) {
15895 // This side of s may be protected by a segment.
15896 sspivot(startsh, deadseg);
15897 if (deadseg.sh != dummysh) {
15898 // Detach it from s.
15899 ssdissolve(startsh);
15900 // Delete the segment.
15901 shellfacedealloc(subsegs, deadseg.sh);
15902 }
15903 }
15904 }
15905 senextself(startsh);
15906 }
15907 }
15908 for (i = 0; i < newshlist->len(); i++) {
15909 startsh = * (face *)(* newshlist)[i];
15910 suninfect(startsh);
15911 }
15912 }
15913
15914 ///////////////////////////////////////////////////////////////////////////////
15915 // //
15916 // unifysegments() Unify identical segments and build facet connections. //
15917 // //
15918 // After creating the surface mesh. Each facet has its own segments. There //
15919 // are duplicated segments between adjacent facets. This routine has three //
15920 // purposes: //
15921 // (1) identify the set of segments which have the same endpoints and //
15922 // unify them into one segment, remove redundant ones; //
15923 // (2) create the face rings of the unified segments, hence setup the //
15924 // connections between facets; and //
15925 // (3) set a unique marker (1-based) for each segment. //
15926 // On finish, each segment is unique and the face ring around it (right-hand //
15927 // rule) is constructed. The connections between facets-facets are setup. //
15928 // //
15929 ///////////////////////////////////////////////////////////////////////////////
15930
15931 void tetgenmesh::unifysegments()
15932 {
15933 list *sfacelist;
15934 shellface **facesperverlist;
15935 face subsegloop, testseg;
15936 face sface, sface1, sface2;
15937 point torg, tdest;
15938 REAL da1, da2;
15939 int *idx2facelist;
15940 int segmarker;
15941 int idx, k, m;
15942
15943 if (b->verbose > 0) {
15944 printf(" Unifying segments.\n");
15945 }
15946
15947 // Compute a mapping from indices of vertices to subfaces.
15948 makesubfacemap(idx2facelist, facesperverlist);
15949 // Initialize 'sfacelist' for constructing the face link of each segment.
15950 sfacelist = new list(sizeof(face), NULL);
15951
15952 segmarker = 1;
15953 subsegs->traversalinit();
15954 subsegloop.sh = shellfacetraverse(subsegs);
15955 while (subsegloop.sh != (shellface *) NULL) {
15956 subsegloop.shver = 0; // For sure.
15957 torg = sorg(subsegloop);
15958 tdest = sdest(subsegloop);
15959 idx = pointmark(torg) - in->firstnumber;
15960 // Loop through the set of subfaces containing 'torg'. Get all the
15961 // subfaces containing the edge (torg, tdest). Save and order them
15962 // in 'sfacelist', the ordering is defined by the right-hand rule
15963 // with thumb points from torg to tdest.
15964 for (k = idx2facelist[idx]; k < idx2facelist[idx + 1]; k++) {
15965 sface.sh = facesperverlist[k];
15966 sface.shver = 0;
15967 // sface may be died due to the removing of duplicated subfaces.
15968 if (!isdead(&sface) && isfacehasedge(&sface, torg, tdest)) {
15969 // 'sface' contains this segment.
15970 findedge(&sface, torg, tdest);
15971 // Save it in 'sfacelist'.
15972 if (sfacelist->len() < 2) {
15973 sfacelist->append(&sface);
15974 } else {
15975 for (m = 0; m < sfacelist->len() - 1; m++) {
15976 sface1 = * (face *)(* sfacelist)[m];
15977 sface2 = * (face *)(* sfacelist)[m + 1];
15978 da1 = facedihedral(torg, tdest, sapex(sface1), sapex(sface));
15979 da2 = facedihedral(torg, tdest, sapex(sface1), sapex(sface2));
15980 if (da1 < da2) {
15981 break; // Insert it after m.
15982 }
15983 }
15984 sfacelist->insert(m + 1, &sface);
15985 }
15986 }
15987 }
15988 if (b->verbose > 1) {
15989 printf(" Identifying %d segments of (%d %d).\n", sfacelist->len(),
15990 pointmark(torg), pointmark(tdest));
15991 }
15992 // Set the connection between this segment and faces containing it,
15993 // at the same time, remove redundant segments.
15994 for (k = 0; k < sfacelist->len(); k++) {
15995 sface = *(face *)(* sfacelist)[k];
15996 sspivot(sface, testseg);
15997 // If 'testseg' is not 'subsegloop', it is a redundant segment that
15998 // needs be removed. BE CAREFUL it may already be removed. Do not
15999 // remove it twice, i.e., do test 'isdead()' together.
16000 if ((testseg.sh != subsegloop.sh) && !isdead(&testseg)) {
16001 shellfacedealloc(subsegs, testseg.sh);
16002 }
16003 // 'ssbond' bonds the subface and the segment together, and dissloves
16004 // the old bond as well.
16005 ssbond(sface, subsegloop);
16006 }
16007 // Set connection between these faces.
16008 sface = *(face *)(* sfacelist)[0];
16009 for (k = 1; k <= sfacelist->len(); k++) {
16010 if (k < sfacelist->len()) {
16011 sface1 = *(face *)(* sfacelist)[k];
16012 } else {
16013 sface1 = *(face *)(* sfacelist)[0]; // Form a face loop.
16014 }
16015 /*
16016 // Check if these two subfaces are the same. It is possible when user
16017 // defines one facet (or polygon) two or more times. If they are,
16018 // they should not be bonded together, instead of that, one of them
16019 // should be delete from the surface mesh.
16020 if ((sfacelist->len() > 1) && sapex(sface) == sapex(sface1)) {
16021 // They are duplicated faces.
16022 if (b->verbose > 0) {
16023 printf(" A duplicated subface (%d, %d, %d) is removed.\n",
16024 pointmark(torg), pointmark(tdest), pointmark(sapex(sface)));
16025 }
16026 if (k == sfacelist->len()) {
16027 // 'sface' is the last face, however, it is same as the first one.
16028 // In order to form the ring, we have to let the second last
16029 // face bond to the first one 'sface1'.
16030 shellfacedealloc(subfaces, sface.sh);
16031 assert(sfacelist->len() >= 2);
16032 assert(k == sfacelist->len());
16033 sface = *(face *)(* sfacelist)[k - 2];
16034 } else {
16035 // 'sface1' is in the middle and may be the last one.
16036 shellfacedealloc(subfaces, sface1.sh);
16037 // Skip this face and go to the next one.
16038 continue;
16039 }
16040 }
16041 */
16042 if (b->verbose > 2) {
16043 printf(" Bond subfaces (%d, %d, %d) and (%d, %d, %d).\n",
16044 pointmark(torg), pointmark(tdest), pointmark(sapex(sface)),
16045 pointmark(torg), pointmark(tdest), pointmark(sapex(sface1)));
16046 }
16047 sbond1(sface, sface1);
16048 sface = sface1;
16049 }
16050 // Set the unique segment marker into the unified segment.
16051 setshellmark(subsegloop, segmarker);
16052 // Increase the marker.
16053 segmarker++;
16054 // Clear the working list.
16055 sfacelist->clear();
16056 subsegloop.sh = shellfacetraverse(subsegs);
16057 }
16058
16059 delete [] idx2facelist;
16060 delete [] facesperverlist;
16061 delete sfacelist;
16062 }
16063
16064 ///////////////////////////////////////////////////////////////////////////////
16065 // //
16066 // mergefacets() Merge adjacent facets to be one facet if they are //
16067 // coplanar and have the same boundary marker. //
16068 // //
16069 // Segments between two merged facets will be removed from the mesh. If all //
16070 // segments around a vertex have been removed, change its vertex type to be //
16071 // FACETVERTEX. Edge flips will be performed to ensure the Delaunay criteria //
16072 // of the triangulation of merged facets. //
16073 // //
16074 ///////////////////////////////////////////////////////////////////////////////
16075
16076 void tetgenmesh::mergefacets(queue* flipqueue)
16077 {
16078 face parentsh, neighsh, neineighsh;
16079 face segloop;
16080 point eorg, edest;
16081 REAL ori;
16082 bool mergeflag, pbcflag;
16083 int* segspernodelist;
16084 int fidx1, fidx2;
16085 int i, j;
16086
16087 if (b->verbose > 0) {
16088 printf(" Merging coplanar facets.\n");
16089 }
16090 // Create and initialize 'segspernodelist'.
16091 segspernodelist = new int[points->items + 1];
16092 for (i = 0; i < points->items + 1; i++) segspernodelist[i] = 0;
16093
16094 // Loop the segments, counter the number of segments sharing each vertex.
16095 subsegs->traversalinit();
16096 segloop.sh = shellfacetraverse(subsegs);
16097 while (segloop.sh != (shellface *) NULL) {
16098 // Increment the number of sharing segments for each endpoint.
16099 for (i = 0; i < 2; i++) {
16100 j = pointmark((point) segloop.sh[3 + i]);
16101 segspernodelist[j]++;
16102 }
16103 segloop.sh = shellfacetraverse(subsegs);
16104 }
16105
16106 // Loop the segments, find out dead segments.
16107 subsegs->traversalinit();
16108 segloop.sh = shellfacetraverse(subsegs);
16109 while (segloop.sh != (shellface *) NULL) {
16110 eorg = sorg(segloop);
16111 edest = sdest(segloop);
16112 spivot(segloop, parentsh);
16113 spivot(parentsh, neighsh);
16114 spivot(neighsh, neineighsh);
16115 if (parentsh.sh != neighsh.sh && parentsh.sh == neineighsh.sh) {
16116 // Exactly two subfaces at this segment.
16117 fidx1 = shellmark(parentsh) - 1;
16118 fidx2 = shellmark(neighsh) - 1;
16119 pbcflag = false;
16120 if (checkpbcs) {
16121 pbcflag = (shellpbcgroup(parentsh) >= 0)
16122 || (shellpbcgroup(neighsh) >= 0);
16123 }
16124 // Possibly merge them if they are not in the same facet.
16125 if ((fidx1 != fidx2) && !pbcflag) {
16126 // Test if they are coplanar.
16127 ori = orient3d(eorg, edest, sapex(parentsh), sapex(neighsh));
16128 if (ori != 0.0) {
16129 if (iscoplanar(eorg, edest, sapex(parentsh), sapex(neighsh), ori,
16130 b->epsilon)) {
16131 ori = 0.0; // They are assumed as coplanar.
16132 }
16133 }
16134 if (ori == 0.0) {
16135 mergeflag = (in->facetmarkerlist == (int *) NULL ||
16136 in->facetmarkerlist[fidx1] == in->facetmarkerlist[fidx2]);
16137 if (mergeflag) {
16138 // This segment becomes dead.
16139 if (b->verbose > 1) {
16140 printf(" Removing segment (%d, %d).\n", pointmark(eorg),
16141 pointmark(edest));
16142 }
16143 ssdissolve(parentsh);
16144 ssdissolve(neighsh);
16145 shellfacedealloc(subsegs, segloop.sh);
16146 j = pointmark(eorg);
16147 segspernodelist[j]--;
16148 if (segspernodelist[j] == 0) {
16149 setpointtype(eorg, FACETVERTEX);
16150 }
16151 j = pointmark(edest);
16152 segspernodelist[j]--;
16153 if (segspernodelist[j] == 0) {
16154 setpointtype(edest, FACETVERTEX);
16155 }
16156 // Add 'parentsh' to queue checking for flip.
16157 enqueueflipedge(parentsh, flipqueue);
16158 }
16159 }
16160 }
16161 }
16162 segloop.sh = shellfacetraverse(subsegs);
16163 }
16164
16165 if (!flipqueue->empty()) {
16166 // Restore the Delaunay property in the facet triangulation.
16167 flipsub(flipqueue);
16168 }
16169
16170 delete [] segspernodelist;
16171 }
16172
16173 ///////////////////////////////////////////////////////////////////////////////
16174 // //
16175 // meshsurface() Create the surface mesh of a PLC. //
16176 // //
16177 // Let X be the PLC, the surface mesh S of X consists of triangulated facets.//
16178 // S is created mainly in the following steps: //
16179 // //
16180 // (1) Form the CDT of each facet of X separately (by routine triangulate()).//
16181 // After it is done, the subfaces of each facet are connected to each other, //
16182 // however there is no connection between facets yet. Notice each facet has //
16183 // its own segments, some of them are duplicated. //
16184 // //
16185 // (2) Remove the redundant segments created in step (1) (by routine unify- //
16186 // segment()). The subface ring of each segment is created, the connection //
16187 // between facets are established as well. //
16188 // //
16189 // The return value indicates the number of segments of X. //
16190 // //
16191 ///////////////////////////////////////////////////////////////////////////////
16192
16193 long tetgenmesh::meshsurface()
16194 {
16195 list *ptlist, *conlist;
16196 queue *flipqueue;
16197 tetgenio::facet *f;
16198 tetgenio::polygon *p;
16199 memorypool *viri;
16200 point *idx2verlist;
16201 point tstart, tend, *cons;
16202 int *worklist;
16203 int end1, end2;
16204 int shmark, i, j;
16205
16206 if (!b->quiet) {
16207 printf("Creating surface mesh.\n");
16208 }
16209
16210 // Compute a mapping from indices to points.
16211 makeindex2pointmap(idx2verlist);
16212 // Compute a mapping from points to tets for computing abovepoints.
16213 makepoint2tetmap();
16214 // Initialize 'facetabovepointarray'.
16215 facetabovepointarray = new point[in->numberoffacets + 1];
16216 for (i = 0; i < in->numberoffacets + 1; i++) {
16217 facetabovepointarray[i] = (point) NULL;
16218 }
16219 if (checkpbcs) {
16220 // Initialize the global array 'subpbcgrouptable'.
16221 createsubpbcgrouptable();
16222 }
16223
16224 // Initialize working lists.
16225 viri = new memorypool(sizeof(shellface *), 1024, POINTER, 0);
16226 flipqueue = new queue(sizeof(badface));
16227 ptlist = new list(sizeof(point *), NULL, 256);
16228 conlist = new list(sizeof(point *) * 2, NULL, 256);
16229 worklist = new int[points->items + 1];
16230 for (i = 0; i < points->items + 1; i++) worklist[i] = 0;
16231
16232 // Loop the facet list, triangulate each facet. On finish, all subfaces
16233 // are in 'subfaces', all segments are in 'subsegs'. Notice: there're
16234 // redundant segments. Remember: All facet indices count from 1.
16235 for (shmark = 1; shmark <= in->numberoffacets; shmark++) {
16236 // Get a facet F.
16237 f = &in->facetlist[shmark - 1];
16238
16239 // Process the duplicated points first, they are marked with type
16240 // DUPLICATEDVERTEX by incrflipdelaunay(). Let p and q are dup.
16241 // and the index of p is larger than q's, p is substituted by q.
16242 // In a STL mesh, duplicated points are implicitly included.
16243 if ((b->object == tetgenbehavior::STL) || dupverts) {
16244 // Loop all polygons of this facet.
16245 for (i = 0; i < f->numberofpolygons; i++) {
16246 p = &(f->polygonlist[i]);
16247 // Loop other vertices of this polygon.
16248 for (j = 0; j < p->numberofvertices; j++) {
16249 end1 = p->vertexlist[j];
16250 tstart = idx2verlist[end1 - in->firstnumber];
16251 if (pointtype(tstart) == DUPLICATEDVERTEX) {
16252 // Reset the index of vertex-j.
16253 tend = point2ppt(tstart);
16254 end2 = pointmark(tend);
16255 p->vertexlist[j] = end2;
16256 }
16257 }
16258 }
16259 }
16260
16261 // Loop polygons of F, get the set V of vertices and S of segments.
16262 for (i = 0; i < f->numberofpolygons; i++) {
16263 // Get a polygon.
16264 p = &(f->polygonlist[i]);
16265 // Get the first vertex.
16266 end1 = p->vertexlist[0];
16267 if ((end1 < in->firstnumber) ||
16268 (end1 >= in->firstnumber + in->numberofpoints)) {
16269 if (!b->quiet) {
16270 printf("Warning: Invalid the 1st vertex %d of polygon", end1);
16271 printf(" %d in facet %d.\n", i + 1, shmark);
16272 }
16273 continue; // Skip this polygon.
16274 }
16275 tstart = idx2verlist[end1 - in->firstnumber];
16276 // Add tstart to V if it haven't been added yet.
16277 if (worklist[end1] == 0) {
16278 ptlist->append(&tstart);
16279 worklist[end1] = 1;
16280 }
16281 // Loop other vertices of this polygon.
16282 for (j = 1; j <= p->numberofvertices; j++) {
16283 // get a vertex.
16284 if (j < p->numberofvertices) {
16285 end2 = p->vertexlist[j];
16286 } else {
16287 end2 = p->vertexlist[0]; // Form a loop from last to first.
16288 }
16289 if ((end2 < in->firstnumber) ||
16290 (end2 >= in->firstnumber + in->numberofpoints)) {
16291 if (!b->quiet) {
16292 printf("Warning: Invalid vertex %d in polygon %d", end2, i + 1);
16293 printf(" in facet %d.\n", shmark);
16294 }
16295 } else {
16296 if (end1 != end2) {
16297 // 'end1' and 'end2' form a segment.
16298 tend = idx2verlist[end2 - in->firstnumber];
16299 // Add tstart to V if it haven't been added yet.
16300 if (worklist[end2] == 0) {
16301 ptlist->append(&tend);
16302 worklist[end2] = 1;
16303 }
16304 // Save the segment in S (conlist).
16305 cons = (point *) conlist->append(NULL);
16306 cons[0] = tstart;
16307 cons[1] = tend;
16308 // Set the start for next continuous segment.
16309 end1 = end2;
16310 tstart = tend;
16311 } else {
16312 // Two identical vertices represent an isolated vertex of F.
16313 if (p->numberofvertices > 2) {
16314 // This may be an error in the input, anyway, we can continue
16315 // by simply skipping this segment.
16316 if (!b->quiet) {
16317 printf("Warning: Polygon %d has two identical verts", i + 1);
16318 printf(" in facet %d.\n", shmark);
16319 }
16320 }
16321 // Ignore this vertex.
16322 }
16323 }
16324 // Is the polygon degenerate (a segment or a vertex)?
16325 if (p->numberofvertices == 2) break;
16326 }
16327 }
16328 // Unmark vertices.
16329 for (i = 0; i < ptlist->len(); i++) {
16330 tstart = * (point *)(* ptlist)[i];
16331 end1 = pointmark(tstart);
16332 assert(worklist[end1] == 1);
16333 worklist[end1] = 0;
16334 }
16335
16336 // Create a CDT of F.
16337 triangulate(shmark, b->epsilon * 1e+2, ptlist, conlist, f->numberofholes,
16338 f->holelist, viri, flipqueue);
16339 // Clear working lists.
16340 ptlist->clear();
16341 conlist->clear();
16342 viri->restart();
16343 }
16344
16345 // Unify segments in 'subsegs', remove redundant segments. Face links
16346 // of segments are also built.
16347 unifysegments();
16348
16349 if (checkpbcs) {
16350 // Create the global array 'segpbcgrouptable'.
16351 createsegpbcgrouptable();
16352 }
16353
16354 if (b->object == tetgenbehavior::STL) {
16355 // Remove redundant vertices (for .stl input mesh).
16356 jettisonnodes();
16357 }
16358
16359 if (!b->nomerge && !checkpbcs) {
16360 // No '-M' switch - merge adjacent facets if they are coplanar.
16361 mergefacets(flipqueue);
16362 }
16363
16364 delete [] idx2verlist;
16365 delete [] worklist;
16366 delete ptlist;
16367 delete conlist;
16368 delete flipqueue;
16369 delete viri;
16370
16371 return subsegs->items;
16372 }
16373
16374 //
16375 // End of surface triangulation routines
16376 //
16377
16378 ///////////////////////////////////////////////////////////////////////////////
16379 // //
16380 // interecursive() Recursively do intersection test on a set of triangles.//
16381 // //
16382 // Recursively split the set 'subfacearray' of subfaces into two sets using //
16383 // a cut plane parallel to x-, or, y-, or z-axies. The split criteria are //
16384 // follows. Assume the cut plane is H, and H+ denotes the left halfspace of //
16385 // H, and H- denotes the right halfspace of H; and s be a subface: //
16386 // //
16387 // (1) If all points of s lie at H+, put it into left array; //
16388 // (2) If all points of s lie at H-, put it into right array; //
16389 // (3) If some points of s lie at H+ and some of lie at H-, or some //
16390 // points lie on H, put it into both arraies. //
16391 // //
16392 // Partitions by x-axis if axis == '0'; by y-axis if axis == '1'; by z-axis //
16393 // if axis == '2'. If current cut plane is parallel to the x-axis, the next //
16394 // one will be parallel to y-axis, and the next one after the next is z-axis,//
16395 // and then alternately return back to x-axis. //
16396 // //
16397 // Stop splitting when the number of triangles of the input array is not //
16398 // decreased anymore. Do tests on the current set. //
16399 // //
16400 ///////////////////////////////////////////////////////////////////////////////
16401
16402 void tetgenmesh::
16403 interecursive(shellface** subfacearray, int arraysize, int axis, REAL bxmin,
16404 REAL bxmax, REAL bymin, REAL bymax, REAL bzmin, REAL bzmax,
16405 int* internum)
16406 {
16407 shellface **leftarray, **rightarray;
16408 face sface1, sface2;
16409 point p1, p2, p3;
16410 point p4, p5, p6;
16411 enum interresult intersect;
16412 REAL split;
16413 bool toleft, toright;
16414 int leftsize, rightsize;
16415 int i, j;
16416
16417 if (b->verbose > 1) {
16418 printf(" Recur %d faces. Bbox (%g, %g, %g),(%g, %g, %g). %s-axis\n",
16419 arraysize, bxmin, bymin, bzmin, bxmax, bymax, bzmax,
16420 axis == 0 ? "x" : (axis == 1 ? "y" : "z"));
16421 }
16422
16423 leftarray = new shellface*[arraysize];
16424 if (leftarray == NULL) {
16425 printf("Error in interecursive(): Insufficient memory.\n");
16426 terminatetetgen(1);
16427 }
16428 rightarray = new shellface*[arraysize];
16429 if (rightarray == NULL) {
16430 printf("Error in interecursive(): Insufficient memory.\n");
16431 terminatetetgen(1);
16432 }
16433 leftsize = rightsize = 0;
16434
16435 if (axis == 0) {
16436 // Split along x-axis.
16437 split = 0.5 * (bxmin + bxmax);
16438 } else if (axis == 1) {
16439 // Split along y-axis.
16440 split = 0.5 * (bymin + bymax);
16441 } else {
16442 // Split along z-axis.
16443 split = 0.5 * (bzmin + bzmax);
16444 }
16445
16446 for (i = 0; i < arraysize; i++) {
16447 sface1.sh = subfacearray[i];
16448 p1 = (point) sface1.sh[3];
16449 p2 = (point) sface1.sh[4];
16450 p3 = (point) sface1.sh[5];
16451 toleft = toright = false;
16452 if (p1[axis] < split) {
16453 toleft = true;
16454 if (p2[axis] >= split || p3[axis] >= split) {
16455 toright = true;
16456 }
16457 } else if (p1[axis] > split) {
16458 toright = true;
16459 if (p2[axis] <= split || p3[axis] <= split) {
16460 toleft = true;
16461 }
16462 } else {
16463 // p1[axis] == split;
16464 toleft = true;
16465 toright = true;
16466 }
16467 // At least one is true;
16468 #ifdef SELF_CHECK
16469 assert(!(toleft == false && toright == false));
16470 #endif
16471 if (toleft) {
16472 leftarray[leftsize] = sface1.sh;
16473 leftsize++;
16474 }
16475 if (toright) {
16476 rightarray[rightsize] = sface1.sh;
16477 rightsize++;
16478 }
16479 }
16480
16481 if (leftsize < arraysize && rightsize < arraysize) {
16482 // Continue to partition the input set. Now 'subfacearray' has been
16483 // split into two sets, it's memory can be freed. 'leftarray' and
16484 // 'rightarray' will be freed in the next recursive (after they're
16485 // partitioned again or performing tests).
16486 delete [] subfacearray;
16487 // Continue to split these two sets.
16488 if (axis == 0) {
16489 interecursive(leftarray, leftsize, 1, bxmin, split, bymin, bymax,
16490 bzmin, bzmax, internum);
16491 interecursive(rightarray, rightsize, 1, split, bxmax, bymin, bymax,
16492 bzmin, bzmax, internum);
16493 } else if (axis == 1) {
16494 interecursive(leftarray, leftsize, 2, bxmin, bxmax, bymin, split,
16495 bzmin, bzmax, internum);
16496 interecursive(rightarray, rightsize, 2, bxmin, bxmax, split, bymax,
16497 bzmin, bzmax, internum);
16498 } else {
16499 interecursive(leftarray, leftsize, 0, bxmin, bxmax, bymin, bymax,
16500 bzmin, split, internum);
16501 interecursive(rightarray, rightsize, 0, bxmin, bxmax, bymin, bymax,
16502 split, bzmax, internum);
16503 }
16504 } else {
16505 if (b->verbose > 1) {
16506 printf(" Checking intersecting faces.\n");
16507 }
16508 // Perform a brute-force compare on the set.
16509 for (i = 0; i < arraysize; i++) {
16510 sface1.sh = subfacearray[i];
16511 p1 = (point) sface1.sh[3];
16512 p2 = (point) sface1.sh[4];
16513 p3 = (point) sface1.sh[5];
16514 for (j = i + 1; j < arraysize; j++) {
16515 sface2.sh = subfacearray[j];
16516 p4 = (point) sface2.sh[3];
16517 p5 = (point) sface2.sh[4];
16518 p6 = (point) sface2.sh[5];
16519 intersect = tri_tri_inter(p1, p2, p3, p4, p5, p6);
16520 if (intersect == INTERSECT || intersect == SHAREFACE) {
16521 if (!b->quiet) {
16522 if (intersect == INTERSECT) {
16523 printf(" Facet #%d intersects facet #%d at triangles:\n",
16524 shellmark(sface1), shellmark(sface2));
16525 printf(" (%4d, %4d, %4d) and (%4d, %4d, %4d)\n",
16526 pointmark(p1), pointmark(p2), pointmark(p3),
16527 pointmark(p4), pointmark(p5), pointmark(p6));
16528 } else {
16529 printf(" Facet #%d duplicates facet #%d at triangle:\n",
16530 shellmark(sface1), shellmark(sface2));
16531 printf(" (%4d, %4d, %4d)\n", pointmark(p1), pointmark(p2),
16532 pointmark(p3));
16533 }
16534 }
16535 // Increase the number of intersecting pairs.
16536 (*internum)++;
16537 // Infect these two faces (although they may already be infected).
16538 sinfect(sface1);
16539 sinfect(sface2);
16540 }
16541 }
16542 }
16543 // Don't forget to free all three arrays. No further partition.
16544 delete [] leftarray;
16545 delete [] rightarray;
16546 delete [] subfacearray;
16547 }
16548 }
16549
16550 ///////////////////////////////////////////////////////////////////////////////
16551 // //
16552 // detectinterfaces() Detect intersecting triangles. //
16553 // //
16554 // Given a set of triangles, find the pairs of intersecting triangles from //
16555 // them. Here the set of triangles is in 'subfaces' which is a surface mesh //
16556 // of a PLC (.poly or .smesh). //
16557 // //
16558 // To detect whether two triangles are intersecting is done by the routine //
16559 // 'tri_tri_inter()'. The algorithm for the test is very simple and stable. //
16560 // It is based on geometric orientation test which uses exact arithmetics. //
16561 // //
16562 // Use divide-and-conquer algorithm for reducing the number of intersection //
16563 // tests. Start from the bounding box of the input point set, recursively //
16564 // partition the box into smaller boxes, until the number of triangles in a //
16565 // box is not decreased anymore. Then perform triangle-triangle tests on the //
16566 // remaining set of triangles. The memory allocated in the input set is //
16567 // freed immediately after it has been partitioned into two arrays. So it //
16568 // can be re-used for the consequent partitions. //
16569 // //
16570 // On return, the pool 'subfaces' will be cleared, and only the intersecting //
16571 // triangles remain for output (to a .face file). //
16572 // //
16573 ///////////////////////////////////////////////////////////////////////////////
16574
16575 void tetgenmesh::detectinterfaces()
16576 {
16577 shellface **subfacearray;
16578 face shloop;
16579 int internum;
16580 int i;
16581
16582 if (!b->quiet) {
16583 printf("Detecting intersecting facets.\n");
16584 }
16585
16586 // Construct a map from indices to subfaces;
16587 subfacearray = new shellface*[subfaces->items];
16588 subfaces->traversalinit();
16589 shloop.sh = shellfacetraverse(subfaces);
16590 i = 0;
16591 while (shloop.sh != (shellface *) NULL) {
16592 subfacearray[i] = shloop.sh;
16593 shloop.sh = shellfacetraverse(subfaces);
16594 i++;
16595 }
16596
16597 internum = 0;
16598 // Recursively split the set of triangles into two sets using a cut plane
16599 // parallel to x-, or, y-, or z-axies. Stop splitting when the number
16600 // of subfaces is not decreasing anymore. Do tests on the current set.
16601 interecursive(subfacearray, subfaces->items, 0, xmin, xmax, ymin, ymax,
16602 zmin, zmax, &internum);
16603
16604 if (!b->quiet) {
16605 if (internum > 0) {
16606 printf("\n!! Found %d pairs of faces are intersecting.\n\n", internum);
16607 } else {
16608 printf("\nNo faces are intersecting.\n\n");
16609 }
16610 }
16611
16612 if (internum > 0) {
16613 // Traverse all subfaces, deallocate those have not been infected (they
16614 // are not intersecting faces). Uninfect those have been infected.
16615 // After this loop, only intersecting faces remain.
16616 subfaces->traversalinit();
16617 shloop.sh = shellfacetraverse(subfaces);
16618 while (shloop.sh != (shellface *) NULL) {
16619 if (sinfected(shloop)) {
16620 suninfect(shloop);
16621 } else {
16622 shellfacedealloc(subfaces, shloop.sh);
16623 }
16624 shloop.sh = shellfacetraverse(subfaces);
16625 }
16626 } else {
16627 // Deallocate all subfaces.
16628 subfaces->restart();
16629 }
16630 }
16631
16632 //
16633 // Begin of periodic boundary condition routines
16634 //
16635
16636 ///////////////////////////////////////////////////////////////////////////////
16637 // //
16638 // createsubpbcgrouptable() Create the 'subpbcgrouptable'. //
16639 // //
16640 // Allocate the memory for 'subpbcgrouptable'. Each entry i (a pbcdata) of //
16641 // the table represents a pbcgroup. Most of the fields of a group-i are set //
16642 // in this routine. 'fmark[0]', 'fmark[1]', and 'transmat[0]' are directly //
16643 // copied from the corresponding data of 'in->numberofpbcgroups'. 'transmat //
16644 // [1]' is calculated as the inverse matrix of 'transmat[0]'. 'ss[0]' and //
16645 // 'ss[1]' are initilized be 'dummysh'. They are set in 'trangulatefacet()' //
16646 // (when -p is in use) or 'reconstructmesh()' (when -r is in use). //
16647 // //
16648 ///////////////////////////////////////////////////////////////////////////////
16649
16650 void tetgenmesh::createsubpbcgrouptable()
16651 {
16652 tetgenio::pbcgroup *pg;
16653 pbcdata *pd;
16654 REAL A[4][4], rhs[4], D;
16655 int indx[4];
16656 int i, j, k;
16657
16658 subpbcgrouptable = new pbcdata[in->numberofpbcgroups];
16659 for (i = 0; i < in->numberofpbcgroups; i++) {
16660 pg = &(in->pbcgrouplist[i]);
16661 pd = &(subpbcgrouptable[i]);
16662 // Copy data from pg to pd.
16663 pd->fmark[0] = pg->fmark1;
16664 pd->fmark[1] = pg->fmark2;
16665 // Initialize array 'pd->ss'.
16666 pd->ss[0].sh = dummysh;
16667 pd->ss[1].sh = dummysh;
16668 // Copy the transform matrix from pg to pd->transmat[0].
16669 for (j = 0; j < 4; j++) {
16670 for (k = 0; k < 4; k++) {
16671 pd->transmat[0][j][k] = pg->transmat[j][k];
16672 // Prepare for inverting the matrix.
16673 A[j][k] = pg->transmat[j][k];
16674 }
16675 }
16676 // Calculate the inverse matrix (pd->transmat[1]) of pd->transmat[0].
16677 lu_decmp(A, 4, indx, &D, 0);
16678 for (j = 0; j < 4; j++) {
16679 for (k = 0; k < 4; k++) rhs[k] = 0.0;
16680 rhs[j] = 1.0;
16681 lu_solve(A, 4, indx, rhs, 0);
16682 for (k = 0; k < 4; k++) pd->transmat[1][k][j] = rhs[k];
16683 }
16684 }
16685 }
16686
16687 ///////////////////////////////////////////////////////////////////////////////
16688 // //
16689 // getsubpbcgroup() Get the pbcgroup of a subface. //
16690 // //
16691 // 'pbcsub' has pbc defined. Its pbcgroup is returned in 'pd'. In addition, //
16692 // 'f1' (0 or 1) indicates the position of 'pbcsub' in 'pd'; 'f2' (= 1 - f1) //
16693 // is the position where the symmetric subface of 'pbcsub' is found. //
16694 // //
16695 ///////////////////////////////////////////////////////////////////////////////
16696
16697 void tetgenmesh::getsubpbcgroup(face* pbcsub, pbcdata** pd, int *f1, int *f2)
16698 {
16699 int groupid, fmark, idx;
16700
16701 groupid = shellpbcgroup(*pbcsub);
16702 *pd = &subpbcgrouptable[groupid];
16703
16704 // Get the facet index (1 - based).
16705 idx = shellmark(*pbcsub);
16706 // Get the facet marker from array (0 - based).
16707 fmark = in->facetmarkerlist[idx - 1];
16708 if ((*pd)->fmark[0] == fmark) {
16709 *f1 = 0;
16710 } else {
16711 #ifdef SELF_CHECK
16712 assert((*pd)->fmark[1] == fmark);
16713 #endif
16714 *f1 = 1;
16715 }
16716 *f2 = 1 - (*f1);
16717 }
16718
16719 ///////////////////////////////////////////////////////////////////////////////
16720 // //
16721 // getsubpbcsympoint() Compute the symmetric point for a subface point. //
16722 // //
16723 // 'newpoint' lies on 'splitsub'. This routine calculates a 'sympoint' which //
16724 // locates on 'symsplitsub' and symmtric to 'newpoint'. Return the location //
16725 // of sympoint wrt. symsplitsub. //
16726 // //
16727 ///////////////////////////////////////////////////////////////////////////////
16728
16729 enum tetgenmesh::locateresult tetgenmesh:: getsubpbcsympoint(point newpoint,
16730 face* splitsub, point sympoint, face* symsplitsub)
16731 {
16732 pbcdata *pd;
16733 face subloop;
16734 point pa, pb, pc;
16735 enum locateresult symloc;
16736 REAL ori;
16737 int f1, f2, i;
16738
16739 // Get the pbcgroup of 'splitsub'.
16740 getsubpbcgroup(splitsub, &pd, &f1, &f2);
16741
16742 // Transform newpoint from f1 -> f2.
16743 for (i = 0; i < 3; i++) {
16744 sympoint[i] = pd->transmat[f1][i][0] * newpoint[0]
16745 + pd->transmat[f1][i][1] * newpoint[1]
16746 + pd->transmat[f1][i][2] * newpoint[2]
16747 + pd->transmat[f1][i][3] * 1.0;
16748 }
16749 // Locate sympoint in f2.
16750 symloc = OUTSIDE;
16751 *symsplitsub = pd->ss[f2];
16752 // Is the stored subface valid? Hole removal may delete the subface.
16753 if ((symsplitsub->sh != dummysh) && !isdead(symsplitsub)) {
16754 // 'symsplitsub' should lie on the symmetric facet. Check it.
16755 i = shellmark(*symsplitsub);
16756 if (in->facetmarkerlist[i - 1] == pd->fmark[f2]) {
16757 // 'symsplitsub' has the symmetric boundary marker.
16758 pa = sorg(*symsplitsub);
16759 pb = sdest(*symsplitsub);
16760 pc = sapex(*symsplitsub);
16761 // Test if they are (nearly) coplanar. Some facets may have the
16762 // same boundary marker but not coplanar with this point.
16763 ori = orient3d(pa, pb, pc, sympoint);
16764 if (iscoplanar(pa, pb, pc, sympoint, ori, b->epsilon * 1e+2)) {
16765 // Locate sympoint in facet. Don't stop at subsegment.
16766 abovepoint = facetabovepointarray[shellmark(*symsplitsub)];
16767 if (abovepoint == (point) NULL) {
16768 getfacetabovepoint(symsplitsub);
16769 }
16770 symloc = locatesub(sympoint, symsplitsub, 0, b->epsilon * 1e+2);
16771 }
16772 }
16773 }
16774 if (symloc == OUTSIDE) {
16775 // Do a brute-force searching for the symmetric subface.
16776 REAL epspp = b->epsilon * 1e+2;
16777 int lcount = 0;
16778 do {
16779 // Locate sympoint in the pool of subfaces (with fmark pd->fmark[f2]).
16780 subfaces->traversalinit();
16781 subloop.sh = shellfacetraverse(subfaces);
16782 while (subloop.sh != (shellface *) NULL) {
16783 i = shellmark(subloop);
16784 if (in->facetmarkerlist[i - 1] == pd->fmark[f2]) {
16785 // Found a facet have the symmetric boundary marker.
16786 pa = sorg(subloop);
16787 pb = sdest(subloop);
16788 pc = sapex(subloop);
16789 // Test if they are (nearly) coplanar. Some facets may have the
16790 // same boundary marker but not coplanar with this point.
16791 ori = orient3d(pa, pb, pc, sympoint);
16792 if (iscoplanar(pa, pb, pc, sympoint, ori, epspp)) {
16793 // Test if sympoint is (nearly) inside this facet.
16794 // Get the abovepoint of the facet.
16795 abovepoint = facetabovepointarray[shellmark(subloop)];
16796 // Do we need to calculate the abovepoint?
16797 if (abovepoint == (point) NULL) {
16798 getfacetabovepoint(&subloop);
16799 }
16800 // subloop is on the facet, search sympoint.
16801 symloc = locatesub(sympoint, &subloop, 0, epspp);
16802 if (symloc != OUTSIDE) break;
16803 }
16804 }
16805 subloop.sh = shellfacetraverse(subfaces);
16806 }
16807 lcount++;
16808 epspp *= 10.0;
16809 } while ((symloc == OUTSIDE) && (lcount < 3));
16810 #ifdef SELF_CHECK
16811 // sympoint should be inside the facet.
16812 assert(symloc != OUTSIDE);
16813 #endif
16814 // Set the returning subface.
16815 *symsplitsub = subloop;
16816 // Update the stored subface for next searching.
16817 pd->ss[f2] = *symsplitsub;
16818 }
16819
16820 return adjustlocatesub(sympoint, symsplitsub, symloc, b->epsilon);
16821 }
16822
16823 ///////////////////////////////////////////////////////////////////////////////
16824 // //
16825 // createsegpbcgrouptable() Create the 'segpbcgrouptable'. //
16826 // //
16827 // Each segment may belong to more than one pbcgroups. For example, segment //
16828 // ab may need to be symmteric to both segments cd, and ef, then ab and cd, //
16829 // cd and ef, ef and ab form three pbcgroups. //
16830 // //
16831 // 'segpbcgrouptable' is implemented as a list of pbcdatas. Each item i is //
16832 // a pbcgroup. //
16833 // //
16834 ///////////////////////////////////////////////////////////////////////////////
16835
16836 void tetgenmesh::createsegpbcgrouptable()
16837 {
16838 pbcdata *pd, *pd1, *pd2;
16839 face segloop, symseg;
16840 face startsh, spinsh, symsh;
16841 point pa, pb;
16842 enum locateresult symloc;
16843 REAL testpt[3], sympt[3];
16844 bool inflag;
16845 int segid1, segid2;
16846 int f1, f2;
16847 int i, j, k, l;
16848
16849 // Allocate memory for 'subpbcgrouptable'.
16850 segpbcgrouptable = new list(sizeof(pbcdata), NULL, 256);
16851
16852 // Loop through the segment list.
16853 subsegs->traversalinit();
16854 segloop.sh = shellfacetraverse(subsegs);
16855 while (segloop.sh != (shellface *) NULL) {
16856 // Loop the subface ring of segloop ab.
16857 pa = sorg(segloop);
16858 pb = sdest(segloop);
16859 segid1 = shellmark(segloop);
16860 spivot(segloop, startsh);
16861 spinsh = startsh;
16862 do {
16863 // Adjust spinsh be edge ab.
16864 if (sorg(spinsh) != pa) {
16865 sesymself(spinsh);
16866 }
16867 // Does spinsh belong to a pbcgroup?
16868 if (shellpbcgroup(spinsh) != -1) {
16869 // Yes! There exists a segment cd. ab and cd form a pbcgroup.
16870 // 'testpt' is the midpoint of ab used to find cd.
16871 for (i = 0; i < 3; i++) testpt[i] = 0.5 * (pa[i] + pb[i]);
16872 symloc = getsubpbcsympoint(testpt, &spinsh, sympt, &symsh);
16873 #ifdef SELF_CHECK
16874 assert(symloc == ONEDGE);
16875 #endif
16876 sspivot(symsh, symseg);
16877 #ifdef SELF_CHECK
16878 assert(symseg.sh != dummysh);
16879 #endif
16880 // Check whether this group has already been created in list.
16881 segid2 = shellmark(symseg);
16882 inflag = false;
16883 for (i = 0; i < segpbcgrouptable->len() && !inflag; i++) {
16884 pd = (pbcdata *)(* segpbcgrouptable)[i];
16885 if (pd->segid[0] == segid1) {
16886 if (pd->segid[1] == segid2) inflag = true;
16887 } else if (pd->segid[0] == segid2) {
16888 if (pd->segid[1] == segid1) inflag = true;
16889 }
16890 }
16891 if (!inflag) {
16892 // Create a segment pbcgroup in list for ab and cd.
16893 pd = (pbcdata *) segpbcgrouptable->append(NULL);
16894 // Save the markers of ab and cd.
16895 pd->segid[0] = segid1;
16896 pd->segid[1] = segid2;
16897 // Save the handles of ab and cd.
16898 pd->ss[0] = segloop;
16899 pd->ss[1] = symseg;
16900 // Find the map from ab to cd.
16901 getsubpbcgroup(&spinsh, &pd1, &f1, &f2);
16902 pd->fmark[0] = pd1->fmark[f1];
16903 pd->fmark[1] = pd1->fmark[f2];
16904 // Set the map from ab to cd.
16905 for (i = 0; i < 4; i++) {
16906 for (j = 0; j < 4; j++) {
16907 pd->transmat[0][i][j] = pd1->transmat[f1][i][j];
16908 }
16909 }
16910 // Set the map from cd to ab.
16911 for (i = 0; i < 4; i++) {
16912 for (j = 0; j < 4; j++) {
16913 pd->transmat[1][i][j] = pd1->transmat[f2][i][j];
16914 }
16915 }
16916 }
16917 }
16918 // Go to the next subface in the ring of ab.
16919 spivotself(spinsh);
16920 } while (spinsh.sh != startsh.sh);
16921 segloop.sh = shellfacetraverse(subsegs);
16922 }
16923
16924 // Create the indirect segment pbcgroups.
16925 for (i = 0; i < segpbcgrouptable->len(); i++) {
16926 pd1 = (pbcdata *)(* segpbcgrouptable)[i];
16927 for (f1 = 0; f1 < 2; f1++) {
16928 // Search for a group (except i) contains pd1->segid[f1].
16929 for (j = 0; j < segpbcgrouptable->len(); j++) {
16930 if (j == i) continue;
16931 pd2 = (pbcdata *)(* segpbcgrouptable)[j];
16932 f2 = -1;
16933 if (pd1->segid[f1] == pd2->segid[0]) {
16934 f2 = 0;
16935 } else if (pd1->segid[f1] == pd2->segid[1]) {
16936 f2 = 1;
16937 }
16938 if (f2 != -1) {
16939 #ifdef SELF_CHECK
16940 assert(pd1->segid[f1] == pd2->segid[f2]);
16941 #endif
16942 segid1 = pd1->segid[1 - f1];
16943 segid2 = pd2->segid[1 - f2];
16944 // Search for the existence of segment pbcgroup (segid1, segid2).
16945 inflag = false;
16946 for (k = 0; k < segpbcgrouptable->len() && !inflag; k++) {
16947 pd = (pbcdata *)(* segpbcgrouptable)[k];
16948 if (pd->segid[0] == segid1) {
16949 if (pd->segid[1] == segid2) inflag = true;
16950 } else if (pd->segid[0] == segid2) {
16951 if (pd->segid[1] == segid1) inflag = true;
16952 }
16953 }
16954 if (!inflag) {
16955 pd = (pbcdata *) segpbcgrouptable->append(NULL);
16956 pd->segid[0] = pd1->segid[1 - f1];
16957 pd->segid[1] = pd2->segid[1 - f2];
16958 pd->ss[0] = pd1->ss[1 - f1];
16959 pd->ss[1] = pd2->ss[1 - f2];
16960 // Invalid the fmark[0] == fmark[1].
16961 pd->fmark[0] = pd->fmark[1] = 0;
16962 // Translate matrix pd->transmat[0] = m2 * m1, where m1 =
16963 // pd1->transmat[1 - f1], m2 = pd2->transmat[f2].
16964 for (k = 0; k < 4; k++) {
16965 for (l = 0; l < 4; l++) {
16966 pd->transmat[0][k][l] = pd2->transmat[f2][k][l];
16967 }
16968 }
16969 m4xm4(pd->transmat[0], pd1->transmat[1 - f1]);
16970 // Translate matrix pd->transmat[1] = m4 * m3, where m3 =
16971 // pd2->transmat[1 - f2], m4 = pd1->transmat[f1].
16972 for (k = 0; k < 4; k++) {
16973 for (l = 0; l < 4; l++) {
16974 pd->transmat[1][k][l] = pd1->transmat[f1][k][l];
16975 }
16976 }
16977 m4xm4(pd->transmat[1], pd2->transmat[1 - f2]);
16978 }
16979 }
16980 }
16981 }
16982 }
16983
16984 // Form a map from segment index to pbcgroup list of this segment.
16985 idx2segpglist = new int[subsegs->items + 1];
16986 for (i = 0; i < subsegs->items + 1; i++) idx2segpglist[i] = 0;
16987 // Loop through 'segpbcgrouptable', counter the number of pbcgroups of
16988 // each segment.
16989 for (i = 0; i < segpbcgrouptable->len(); i++) {
16990 pd = (pbcdata *)(* segpbcgrouptable)[i];
16991 for (j = 0; j < 2; j++) {
16992 k = pd->segid[j] - 1;
16993 idx2segpglist[k]++;
16994 }
16995 }
16996 // Calculate the total length of array 'segpglist'.
16997 j = idx2segpglist[0];
16998 idx2segpglist[0] = 0; // Array starts from 0 element.
16999 for (i = 0; i < subsegs->items; i++) {
17000 k = idx2segpglist[i + 1];
17001 idx2segpglist[i + 1] = idx2segpglist[i] + j;
17002 j = k;
17003 }
17004 // The total length is in the last unit of idx2segpglist.
17005 segpglist = new int[idx2segpglist[i]];
17006 // Loop the set of pbcgroups again, set the data into segpglist.
17007 for (i = 0; i < segpbcgrouptable->len(); i++) {
17008 pd = (pbcdata *)(* segpbcgrouptable)[i];
17009 for (j = 0; j < 2; j++) {
17010 k = pd->segid[j] - 1;
17011 segpglist[idx2segpglist[k]] = i;
17012 idx2segpglist[k]++;
17013 }
17014 }
17015 // Contents in 'idx2segpglist' are shifted, now shift them back.
17016 for (i = subsegs->items - 1; i >= 0; i--) {
17017 idx2segpglist[i + 1] = idx2segpglist[i];
17018 }
17019 idx2segpglist[0] = 0;
17020 }
17021
17022 ///////////////////////////////////////////////////////////////////////////////
17023 // //
17024 // getsegpbcsympoint() Compute the symmetric point for a segment point. //
17025 // //
17026 // 'newpoint' lies on 'splitseg'. This routine calculates a 'sympoint' which //
17027 // locates on 'symsplitseg' and symmtric to 'newpoint'. Return the location //
17028 // of sympoint wrt. symsplitseg. //
17029 // //
17030 ///////////////////////////////////////////////////////////////////////////////
17031
17032 enum tetgenmesh::locateresult tetgenmesh::
17033 getsegpbcsympoint(point newpoint, face* splitseg, point sympoint,
17034 face* symsplitseg, int groupid)
17035 {
17036 pbcdata *pd;
17037 enum locateresult symloc;
17038 int segid, f1, f2, i;
17039
17040 pd = (pbcdata *)(* segpbcgrouptable)[groupid];
17041 segid = shellmark(*splitseg);
17042 if (pd->segid[0] == segid) {
17043 f1 = 0;
17044 } else {
17045 #ifdef SELF_CHECK
17046 assert(pd->segid[1] == segid);
17047 #endif
17048 f1 = 1;
17049 }
17050 f2 = 1 - f1;
17051
17052 // Transform newpoint from f1 -> f2.
17053 for (i = 0; i < 3; i++) {
17054 sympoint[i] = pd->transmat[f1][i][0] * newpoint[0]
17055 + pd->transmat[f1][i][1] * newpoint[1]
17056 + pd->transmat[f1][i][2] * newpoint[2]
17057 + pd->transmat[f1][i][3] * 1.0;
17058 }
17059 // Locate sympoint in f2.
17060 *symsplitseg = pd->ss[f2];
17061 #ifdef SELF_CHECK
17062 assert(symsplitseg->sh != dummysh);
17063 #endif
17064 // Locate sympoint in facet. Stop at subsegment.
17065 symloc = locateseg(sympoint, symsplitseg);
17066 symloc = adjustlocateseg(sympoint, symsplitseg, symloc, b->epsilon * 1e+2);
17067 return symloc;
17068 }
17069
17070 //
17071 // End of periodic boundary condition routines
17072 //
17073
17074 //
17075 // Begin of vertex perturbation routines
17076 //
17077
17078 ///////////////////////////////////////////////////////////////////////////////
17079 // //
17080 // randgenerator() Generate a random REAL number between (0, |range|). //
17081 // //
17082 ///////////////////////////////////////////////////////////////////////////////
17083
17084 REAL tetgenmesh::randgenerator(REAL range)
17085 {
17086 REAL worknumber, result;
17087 int expo;
17088
17089 if (range == 0.0) return 0.0;
17090
17091 expo = 0;
17092 worknumber = fabs(range);
17093 // Normalize worknumber (i.e., 1.xxxExx)
17094 if (worknumber > 10.0) {
17095 while (worknumber > 10.0) {
17096 worknumber /= 10.0;
17097 expo++;
17098 }
17099 } else if (worknumber < 1.0) {
17100 while (worknumber < 1.0) {
17101 worknumber *= 10.0;
17102 expo--;
17103 }
17104 }
17105 #ifdef SELF_CHECK
17106 assert(worknumber >= 1.0 && worknumber <= 10.0);
17107 #endif
17108
17109 // Enlarge worknumber 1000 times.
17110 worknumber *= 1e+3;
17111 expo -= 3;
17112 // Generate a randome number between (0, worknumber).
17113 result = (double) randomnation((int) worknumber);
17114
17115 // Scale result back into the original size.
17116 if (expo > 0) {
17117 while (expo != 0) {
17118 result *= 10.0;
17119 expo--;
17120 }
17121 } else if (expo < 0) {
17122 while (expo != 0) {
17123 result /= 10.0;
17124 expo++;
17125 }
17126 }
17127 #ifdef SELF_CHECK
17128 assert((result >= 0.0) && (result <= fabs(range)));
17129 #endif
17130
17131 return result;
17132 }
17133
17134 ///////////////////////////////////////////////////////////////////////////////
17135 // //
17136 // checksub4cocir() Test a subface to find co-circular pair of subfaces. //
17137 // //
17138 // 'eps' is a relative tolerance for testing approximately cospherical case. //
17139 // Set it to zero if only exact test is desired. //
17140 // //
17141 // An edge(not a segment) of 'testsub' is locally degenerate if the opposite //
17142 // vertex of the adjacent subface is cocircular with the vertices of testsub.//
17143 // If 'once' is TRUE, operate on the edge only if the pointer 'testsub->sh' //
17144 // is smaller than its neighbor (for each edge is considered only once). //
17145 // //
17146 // Return TRUE if find an edge of testsub is locally degenerate. //
17147 // //
17148 ///////////////////////////////////////////////////////////////////////////////
17149
17150 bool tetgenmesh::checksub4cocir(face* testsub, REAL eps, bool once,
17151 bool enqflag)
17152 {
17153 badface *cocirsub;
17154 face subloop, neighsub;
17155 face checkseg;
17156 point pa, pb, pc, pd;
17157 REAL sign;
17158 int i;
17159
17160 subloop = *testsub;
17161 subloop.shver = 0; // Keep the CCW orientation.
17162 // Get the abovepoint of the facet.
17163 abovepoint = facetabovepointarray[shellmark(subloop)];
17164 // Do we need to calculate the abovepoint?
17165 if (abovepoint == (point) NULL) {
17166 getfacetabovepoint(&subloop);
17167 }
17168 // Check the three edges of subloop.
17169 for (i = 0; i < 3; i++) {
17170 sspivot(subloop, checkseg);
17171 if (checkseg.sh == dummysh) {
17172 // It is not a segment, get the adjacent subface.
17173 spivot(subloop, neighsub);
17174 // assert(neighsub.sh != dummysh);
17175 if (!once || (once && (neighsub.sh > subloop.sh))) {
17176 pa = sorg(subloop);
17177 pb = sdest(subloop);
17178 pc = sapex(subloop);
17179 pd = sapex(neighsub);
17180 sign = insphere(pa, pb, pc, abovepoint, pd);
17181 if ((sign != 0.0) && (eps > 0.0)) {
17182 if (iscospheric(pa, pb, pc, abovepoint, pd, sign, eps)) sign = 0.0;
17183 }
17184 if (sign == 0.0) {
17185 // It's locally degenerate!
17186 if (enqflag && badsubfaces != (memorypool *) NULL) {
17187 // Save it.
17188 cocirsub = (badface *) badsubfaces->alloc();
17189 cocirsub->ss = subloop;
17190 cocirsub->forg = pa;
17191 cocirsub->fdest = pb;
17192 cocirsub->fapex = pc;
17193 cocirsub->foppo = pd;
17194 setshell2badface(cocirsub->ss, cocirsub);
17195 }
17196 if (b->verbose > 1) {
17197 printf(" Found set (%d, %d, %d, %d).\n", pointmark(pa),
17198 pointmark(pb), pointmark(pc), pointmark(pd));
17199 }
17200 return true;
17201 }
17202 }
17203 }
17204 senextself(subloop);
17205 }
17206
17207 return false;
17208 }
17209
17210 ///////////////////////////////////////////////////////////////////////////////
17211 // //
17212 // tallcocirsubs() Find all co-circular subfaces and save them in list. //
17213 // //
17214 ///////////////////////////////////////////////////////////////////////////////
17215
17216 void tetgenmesh::tallcocirsubs(REAL eps, bool enqflag)
17217 {
17218 face subloop;
17219
17220 // Loop over all subfaces.
17221 subfaces->traversalinit();
17222 subloop.sh = shellfacetraverse(subfaces);
17223 while (subloop.sh != (shellface *) NULL) {
17224 checksub4cocir(&subloop, eps, true, enqflag);
17225 subloop.sh = shellfacetraverse(subfaces);
17226 }
17227 }
17228
17229 ///////////////////////////////////////////////////////////////////////////////
17230 // //
17231 // tallencsegsfsubs() Check for encroached segs from a list of subfaces. //
17232 // //
17233 ///////////////////////////////////////////////////////////////////////////////
17234
17235 bool tetgenmesh::tallencsegsfsubs(point testpt, list* cavsublist)
17236 {
17237 face startsub, checkseg;
17238 long oldencnum;
17239 int i, j;
17240
17241 // Remember the current number of encroached segments.
17242 oldencnum = badsubsegs->items;
17243
17244 // Check segments in the list of subfaces.
17245 for (i = 0; i < cavsublist->len(); i++) {
17246 startsub = * (face *)(* cavsublist)[i];
17247 // Test all three edges of startsub.
17248 for (j = 0; j < 3; j++) {
17249 sspivot(startsub, checkseg);
17250 if (checkseg.sh != dummysh) {
17251 if (!shell2badface(checkseg)) {
17252 checkseg4encroach(&checkseg, testpt, NULL, true);
17253 }
17254 }
17255 senextself(startsub);
17256 }
17257 }
17258
17259 return (badsubsegs->items > oldencnum);
17260 }
17261
17262 ///////////////////////////////////////////////////////////////////////////////
17263 // //
17264 // collectflipedges() Collect edges of split subfaces for flip checking. //
17265 // //
17266 // 'inspoint' is a newly inserted segment point (inserted by insertsite()). //
17267 // 'splitseg' is one of the two split subsegments. Some subfaces may be non- //
17268 // Delaunay since they're still not bonded to CDT. This routine collect all //
17269 // such possible subfaces in 'flipqueue'. //
17270 // //
17271 ///////////////////////////////////////////////////////////////////////////////
17272
17273 void tetgenmesh::
17274 collectflipedges(point inspoint, face* splitseg, queue* flipqueue)
17275 {
17276 face startsh, spinsh, checksh;
17277 face nextseg;
17278 point pa, pb;
17279
17280 // Let the dest of splitseg be inspoint.
17281 splitseg->shver = 0;
17282 if (sdest(*splitseg) != inspoint) {
17283 sesymself(*splitseg);
17284 }
17285 #ifdef SELF_CHECK
17286 assert(sdest(*splitseg) == inspoint);
17287 #endif
17288 pa = sorg(*splitseg);
17289 spivot(*splitseg, startsh);
17290 spinsh = startsh;
17291 do {
17292 findedge(&spinsh, pa, inspoint);
17293 senext2(spinsh, checksh);
17294 enqueueflipedge(checksh, flipqueue);
17295 spivotself(spinsh);
17296 } while (spinsh.sh != startsh.sh);
17297
17298 // Get the next subsegment.
17299 senext(*splitseg, nextseg);
17300 spivotself(nextseg);
17301 #ifdef SELF_CHECK
17302 assert(nextseg.sh != (shellface *) NULL);
17303 #endif
17304
17305 // Let the org of nextseg be inspoint.
17306 nextseg.shver = 0;
17307 if (sorg(nextseg) != inspoint) {
17308 sesymself(nextseg);
17309 }
17310 #ifdef SELF_CHECK
17311 assert(sorg(nextseg) == inspoint);
17312 #endif
17313 pb = sdest(nextseg);
17314 spivot(nextseg, startsh);
17315 spinsh = startsh;
17316 do {
17317 findedge(&spinsh, inspoint, pb);
17318 senext(spinsh, checksh);
17319 enqueueflipedge(checksh, flipqueue);
17320 spivotself(spinsh);
17321 } while (spinsh.sh != startsh.sh);
17322 }
17323
17324 ///////////////////////////////////////////////////////////////////////////////
17325 // //
17326 // perturbrepairencsegs() Repair all encroached segments. //
17327 // //
17328 // All encroached segments are stored in 'badsubsegs'. Each segment will be //
17329 // split by adding a perturbed point near its circumcenter. //
17330 // //
17331 ///////////////////////////////////////////////////////////////////////////////
17332
17333 void tetgenmesh::perturbrepairencsegs(queue* flipqueue)
17334 {
17335 badface *encloop;
17336 tetrahedron encodedtet;
17337 triface splittet;
17338 face splitsub, symsplitsub;
17339 face splitseg, symsplitseg;
17340 point newpoint, sympoint;
17341 point pa, pb, pc;
17342 enum insertsiteresult success;
17343 enum locateresult loc, symloc;
17344 REAL cent[3], d1, ps, rs;
17345 int i, j;
17346
17347 // Note that steinerleft == -1 if an unlimited number of Steiner points
17348 // is allowed. Loop until 'badsubsegs' is empty.
17349 badsubsegs->traversalinit();
17350 encloop = badfacetraverse(badsubsegs);
17351 while ((encloop != (badface *) NULL) && (steinerleft != 0)) {
17352 splitseg = encloop->ss;
17353 #ifdef SELF_CHECK
17354 assert(shell2badface(splitseg) == encloop);
17355 #endif
17356 setshell2badface(splitseg, NULL);
17357 pa = sorg(splitseg);
17358 pb = sdest(splitseg);
17359 if ((pa == encloop->forg) && (pb == encloop->fdest)) {
17360 if (b->verbose > 1) {
17361 printf(" Get seg (%d, %d).\n", pointmark(pa), pointmark(pb));
17362 }
17363 // Create the newpoint.
17364 makepoint(&newpoint);
17365 // Get the circumcenter and radius of ab.
17366 for (i = 0; i < 3; i++) cent[i] = 0.5 * (pa[i] + pb[i]);
17367 d1 = 0.5 * distance(pa, pb);
17368 // Add a random perturbation to newpoint along the vector ab.
17369 ps = randgenerator(d1 * 1.0e-3);
17370 rs = ps / d1;
17371 // Set newpoint (be at the perturbed circumcenter of ab).
17372 for (i = 0; i < 3; i++) newpoint[i] = cent[i] + rs * (cent[i] - pa[i]);
17373 setpointtype(newpoint, FREESEGVERTEX);
17374 // Set splitseg into the newpoint.
17375 setpoint2sh(newpoint, sencode(splitseg));
17376
17377 // Is there periodic boundary condition?
17378 if (checkpbcs) {
17379 // Insert points on other segments of incident pbcgroups.
17380 i = shellmark(splitseg) - 1;
17381 for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++) {
17382 makepoint(&sympoint);
17383 symloc = getsegpbcsympoint(newpoint, &splitseg, sympoint,
17384 &symsplitseg, segpglist[j]);
17385 #ifdef SELF_CHECK
17386 assert(symloc != OUTSIDE);
17387 #endif
17388 // Note: the symsplitseg and splitseg may be identical, in case
17389 // when the the splitseg is the axis of the rotational sym.
17390 if ((symloc == ONEDGE) && (symsplitseg.sh != splitseg.sh)) {
17391 setpointtype(sympoint, FREESEGVERTEX);
17392 setpoint2sh(sympoint, sencode(symsplitseg));
17393 // Insert sympoint into DT.
17394 pc = sorg(symsplitseg);
17395 splittet.tet = dummytet;
17396 // Find a good start point to search.
17397 encodedtet = point2tet(pc);
17398 if (encodedtet != (tetrahedron) NULL) {
17399 decode(encodedtet, splittet);
17400 if (isdead(&splittet)) {
17401 splittet.tet = dummytet;
17402 }
17403 }
17404 // Locate sympoint in DT. Do exact location.
17405 success = insertsite(sympoint, &splittet, false, flipqueue);
17406 #ifdef SELF_CHECK
17407 assert(success != DUPLICATEPOINT);
17408 #endif
17409 if (success == OUTSIDEPOINT) {
17410 inserthullsite(sympoint, &splittet, flipqueue);
17411 }
17412 if (steinerleft > 0) steinerleft--;
17413 // Let sympoint remember splittet.
17414 setpoint2tet(sympoint, encode(splittet));
17415 // Do flip in DT.
17416 flip(flipqueue, NULL);
17417 // Insert sympoint into F.
17418 symloc = locateseg(sympoint, &symsplitseg);
17419 if (symloc == ONEDGE) {
17420 symsplitseg.shver = 0;
17421 spivot(symsplitseg, symsplitsub);
17422 // sympoint should on the edge of symsplitsub.
17423 splitsubedge(sympoint, &symsplitsub, flipqueue);
17424 } else {
17425 // insertsite() has done the whole job.
17426 #ifdef SELF_CHECK
17427 assert(symloc == ONVERTEX);
17428 assert(checksubfaces);
17429 #endif
17430 // Some edges may need to be flipped.
17431 collectflipedges(sympoint, &symsplitseg, flipqueue);
17432 }
17433 // Do flip in facet.
17434 flipsub(flipqueue);
17435 } else { // if (symloc == ONVERTEX) {
17436 // The symmtric point already exists. It is possible when two
17437 // pbc group are idebtical. Omit sympoint.
17438 pointdealloc(sympoint);
17439 }
17440 }
17441 }
17442
17443 // Insert newpoint into DT.
17444 splittet.tet = dummytet;
17445 // Find a good start point to search.
17446 encodedtet = point2tet(pa);
17447 if (encodedtet != (tetrahedron) NULL) {
17448 decode(encodedtet, splittet);
17449 if (isdead(&splittet)) {
17450 splittet.tet = dummytet;
17451 }
17452 }
17453 if (splittet.tet == dummytet) { // Try pb.
17454 encodedtet = point2tet(pb);
17455 if (encodedtet != (tetrahedron) NULL) {
17456 decode(encodedtet, splittet);
17457 if (isdead(&splittet)) {
17458 splittet.tet = dummytet;
17459 }
17460 }
17461 }
17462 // Locate the newpoint in DT. Do exact location.
17463 success = insertsite(newpoint, &splittet, false, flipqueue);
17464 #ifdef SELF_CHECK
17465 assert(success != DUPLICATEPOINT);
17466 #endif
17467 if (success == OUTSIDEPOINT) {
17468 // A convex hull edge is mssing, and the inserting point lies
17469 // (slightly) outside the convex hull due to the significant
17470 // digits lost in the calculation. Enlarge the convex hull.
17471 inserthullsite(newpoint, &splittet, flipqueue);
17472 }
17473 if (steinerleft > 0) steinerleft--;
17474 // Let newpoint remember splittet.
17475 setpoint2tet(newpoint, encode(splittet));
17476 // Do flip in DT.
17477 flip(flipqueue, NULL);
17478 // Insert newpoint into F.
17479 loc = locateseg(newpoint, &splitseg);
17480 if (loc == ONEDGE) {
17481 splitseg.shver = 0;
17482 spivot(splitseg, splitsub);
17483 // newpoint should on the edge of splitsub.
17484 splitsubedge(newpoint, &splitsub, flipqueue);
17485 } else {
17486 // insertsite() has done the whole job.
17487 #ifdef SELF_CHECK
17488 assert(loc == ONVERTEX);
17489 assert(checksubfaces);
17490 #endif
17491 // Some edges may need to be flipped.
17492 collectflipedges(newpoint, &splitseg, flipqueue);
17493 }
17494 // Do flip in facet.
17495 flipsub(flipqueue);
17496 }
17497 // Remove this entry from list.
17498 badfacedealloc(badsubsegs, encloop);
17499 // Get the next encroached segments.
17500 encloop = badfacetraverse(badsubsegs);
17501 }
17502 }
17503
17504 ///////////////////////////////////////////////////////////////////////////////
17505 // //
17506 // perturbrepairencsubs() Repair all encroached subfaces. //
17507 // //
17508 // All encroached subfaces are stored in 'badsubfaces'. Each subface will be //
17509 // split by adding a perturbed point near its circumcenter. However, if the //
17510 // point encroaches some segments, it will not be inserted. Instead, the //
17511 // encroached segments are split. //
17512 // //
17513 ///////////////////////////////////////////////////////////////////////////////
17514
17515 void tetgenmesh::perturbrepairencsubs(list* cavsublist, queue* flipqueue)
17516 {
17517 badface *encloop, *encsubseg;
17518 tetrahedron encodedtet;
17519 triface splittet;
17520 face splitsub, symsplitsub;
17521 face checkseg, symsplitseg;
17522 point newpoint, sympoint;
17523 point pa, pb, pc, pd;
17524 enum insertsiteresult success;
17525 enum locateresult loc, symloc;
17526 REAL cent[3], d1, ps, rs;
17527 bool reject;
17528 int i;
17529
17530 // Note that steinerleft == -1 if an unlimited number of Steiner points
17531 // is allowed. Loop until the list 'badsubfaces' is empty.
17532 while ((badsubfaces->items > 0) && (steinerleft != 0)) {
17533 badsubfaces->traversalinit();
17534 encloop = badfacetraverse(badsubfaces);
17535 while ((encloop != (badface *) NULL) && (steinerleft != 0)) {
17536 splitsub = encloop->ss;
17537 #ifdef SELF_CHECK
17538 assert(shell2badface(splitsub) == encloop);
17539 #endif
17540 setshell2badface(splitsub, NULL);
17541 pa = sorg(splitsub);
17542 pb = sdest(splitsub);
17543 pc = sapex(splitsub);
17544 // The subface may be not the same one when it was determined to be
17545 // encroached. If its adjacent encroached subface was split, the
17546 // consequent flips may change it into another subface.
17547 if ((pa == encloop->forg) && (pb == encloop->fdest) &&
17548 (pc == encloop->fapex)) {
17549 if (b->verbose > 1) {
17550 printf(" Get subface (%d, %d, %d).\n", pointmark(pa),
17551 pointmark(pb), pointmark(pc));
17552 }
17553 // Create the newpoint.
17554 makepoint(&newpoint);
17555 // Get the circumcenter of abc.
17556 circumsphere(pa, pb, pc, NULL, cent, &d1);
17557 #ifdef SELF_CHECK
17558 assert(d1 > 0.0);
17559 #endif
17560 // Add a random perturbation to newpoint along the vector a->cent.
17561 // This way, the perturbed point still lies in the plane of abc.
17562 ps = randgenerator(d1 * 1.0e-3);
17563 rs = ps / d1;
17564 // Set newpoint (be at the perturbed circumcenter of abc).
17565 for (i = 0; i < 3; i++) newpoint[i] = cent[i] + rs * (cent[i] - pa[i]);
17566 // Get the abovepoint of the facet.
17567 abovepoint = facetabovepointarray[shellmark(splitsub)];
17568 // Do we need to calculate the abovepoint?
17569 if (abovepoint == (point) NULL) {
17570 getfacetabovepoint(&splitsub);
17571 }
17572 loc = locatesub(newpoint, &splitsub, 1, 0.0);
17573 #ifdef SELF_CHECK
17574 assert(loc != ONVERTEX);
17575 #endif
17576 if (loc != OUTSIDE) {
17577 // Add 'splitsub' into 'cavsublist'.
17578 cavsublist->append(&splitsub);
17579 // Collect all subfaces that encroached by newpoint.
17580 collectcavsubs(newpoint, cavsublist);
17581 // Find if there are encroached segments.
17582 reject = tallencsegsfsubs(newpoint, cavsublist);
17583 // Clear cavsublist for the next use.
17584 cavsublist->clear();
17585 } else {
17586 // newpoint lies outside. splitsub contains the boundary segment.
17587 sspivot(splitsub, checkseg);
17588 #ifdef SELF_CHECK
17589 assert(checkseg.sh != dummysh);
17590 #endif
17591 // Add this segment into list for splitting.
17592 if (b->verbose > 2) {
17593 printf(" Queuing boundary segment (%d, %d).\n",
17594 pointmark(sorg(checkseg)), pointmark(sdest(checkseg)));
17595 }
17596 encsubseg = (badface *) badsubsegs->alloc();
17597 encsubseg->ss = checkseg;
17598 encsubseg->forg = sorg(checkseg);
17599 encsubseg->fdest = sdest(checkseg);
17600 encsubseg->foppo = (point) NULL;
17601 setshell2badface(encsubseg->ss, encsubseg);
17602 // Reject newpoint.
17603 reject = true;
17604 }
17605
17606 if (!reject) {
17607 // newpoint is going to be inserted.
17608
17609 // Is there periodic boundary condition?
17610 if (checkpbcs) {
17611 if (shellpbcgroup(splitsub) >= 0) {
17612 // Insert a point on another facet of the pbcgroup.
17613 makepoint(&sympoint);
17614 // Note: 'abovepoint' will be changed.
17615 symloc = getsubpbcsympoint(newpoint, &splitsub, sympoint,
17616 &symsplitsub);
17617 #ifdef SELF_CHECK
17618 assert(symloc != ONVERTEX);
17619 #endif
17620 setpoint2pbcpt(newpoint, sympoint);
17621 setpoint2pbcpt(sympoint, newpoint);
17622 setpointtype(sympoint, FREESUBVERTEX);
17623 // setpoint2sh(sympoint, sencode(symsplitsub));
17624 // Insert sympoint into DT.
17625 pd = sorg(symsplitsub);
17626 splittet.tet = dummytet;
17627 // Find a good start point to search.
17628 encodedtet = point2tet(pd);
17629 if (encodedtet != (tetrahedron) NULL) {
17630 decode(encodedtet, splittet);
17631 if (isdead(&splittet)) {
17632 splittet.tet = dummytet;
17633 }
17634 }
17635 // Locate sympoint in DT. Do exact location.
17636 success = insertsite(sympoint, &splittet, false, flipqueue);
17637 #ifdef SELF_CHECK
17638 assert(success != DUPLICATEPOINT);
17639 #endif
17640 if (success == OUTSIDEPOINT) {
17641 inserthullsite(sympoint, &splittet, flipqueue);
17642 }
17643 if (steinerleft > 0) steinerleft--;
17644 // Let sympoint remember splittet.
17645 setpoint2tet(sympoint, encode(splittet));
17646 // Do flip in DT.
17647 flip(flipqueue, NULL);
17648 // Insert sympoint into F.
17649 // getabovepoint(&symsplitsub);
17650 // symloc = locatesub(sympoint, &symsplitsub, 1, 0.0);
17651 if (symloc == ONFACE) {
17652 splitsubface(sympoint, &symsplitsub, flipqueue);
17653 } else if (symloc == ONEDGE) {
17654 splitsubedge(sympoint, &symsplitsub, flipqueue);
17655 } else {
17656 // 'insertsite()' has done the whole job.
17657 #ifdef SELF_CHECK
17658 assert(symloc == ONVERTEX);
17659 assert(checksubfaces);
17660 #endif
17661 // Split subfaces have been flipped.
17662 flipqueue->clear();
17663 }
17664 // Do flip in facet.
17665 flipsub(flipqueue);
17666 }
17667 }
17668
17669 // Insert newpoint into DT.
17670 splittet.tet = dummytet;
17671 // Find a good start point to search.
17672 encodedtet = point2tet(pa);
17673 if (encodedtet != (tetrahedron) NULL) {
17674 decode(encodedtet, splittet);
17675 if (isdead(&splittet)) {
17676 splittet.tet = dummytet;
17677 }
17678 }
17679 if (splittet.tet == dummytet) { // Try pb.
17680 encodedtet = point2tet(pb);
17681 if (encodedtet != (tetrahedron) NULL) {
17682 decode(encodedtet, splittet);
17683 if (isdead(&splittet)) {
17684 splittet.tet = dummytet;
17685 }
17686 }
17687 }
17688 // Locate the newpoint in DT. Do exact location.
17689 success = insertsite(newpoint, &splittet, false, flipqueue);
17690 #ifdef SELF_CHECK
17691 assert(success != DUPLICATEPOINT);
17692 #endif
17693 if (success == OUTSIDEPOINT) {
17694 inserthullsite(newpoint, &splittet, flipqueue);
17695 }
17696 if (steinerleft > 0) steinerleft--;
17697 // Let newpoint remember splittet.
17698 setpoint2tet(newpoint, encode(splittet));
17699 // Do flip in DT.
17700 flip(flipqueue, NULL);
17701 // Insert newpoint into F.
17702 // if (checkpbcs) {
17703 // 'abovepoint' has been changed.
17704 // getabovepoint(&splitsub);
17705 // loc = locatesub(newpoint, &splitsub, 1, 0.0);
17706 // }
17707 if (loc == ONFACE) {
17708 // Insert the newpoint in facet.
17709 splitsubface(newpoint, &splitsub, flipqueue);
17710 } else if (loc == ONEDGE) {
17711 // Insert the newpoint in facet.
17712 splitsubedge(newpoint, &splitsub, flipqueue);
17713 } else {
17714 // 'insertsite()' has done the whole job.
17715 #ifdef SELF_CHECK
17716 assert(loc == ONVERTEX);
17717 assert(checksubfaces);
17718 #endif
17719 // Split subfaces have been flipped.
17720 flipqueue->clear();
17721 }
17722 // Set the type of the newpoint.
17723 setpointtype(newpoint, FREESUBVERTEX);
17724 // Set splitsub into the newpoint.
17725 // setpoint2sh(newpoint, sencode(splitsub));
17726 // Do flip in the facet.
17727 flipsub(flipqueue);
17728
17729 // Remove this entry from list.
17730 badfacedealloc(badsubfaces, encloop);
17731 } else {
17732 // newpoint is rejected. Remove it from points.
17733 pointdealloc(newpoint);
17734 // Repair all encroached segments.
17735 perturbrepairencsegs(flipqueue);
17736 // Do not remove 'encloop'. Later it will be tested again.
17737 setshell2badface(encloop->ss, encloop);
17738 }
17739 } else {
17740 // This subface has been changed. Remove this entry from list.
17741 badfacedealloc(badsubfaces, encloop);
17742 // It may be co-circular with its neighbors.
17743 // checksub4cocir(&splitsub, eps, false, true);
17744 }
17745 // Get the next encroached subfaces.
17746 encloop = badfacetraverse(badsubfaces);
17747 }
17748 }
17749 }
17750
17751 ///////////////////////////////////////////////////////////////////////////////
17752 // //
17753 // incrperturbvertices() Remove the local degeneracies in DT. //
17754 // //
17755 // A local degeneracy of a DT D is a set of 5 or more vertices which share a //
17756 // common sphere S and no other vertex of D in S. D is not unique if it has //
17757 // local degeneracies. This routine removes the local degeneracies from D by //
17758 // inserting break points (as described in reference [2]). //
17759 // //
17760 // 'eps' is a user-provided error tolerance. It is used to detect whether or //
17761 // not five points are approximate cospherical (evaluated in iscospheric()). //
17762 // Set it to 0.0 to disable it, i.e., only test pure degenerate point set. //
17763 // //
17764 ///////////////////////////////////////////////////////////////////////////////
17765
17766 void tetgenmesh::incrperturbvertices(REAL eps)
17767 {
17768 queue *flipqueue;
17769 list *cavsublist;
17770 long vertcount;
17771
17772 if (!b->quiet) {
17773 printf("Perturbing vertices.\n");
17774 }
17775
17776 vertcount = points->items;
17777 // Create a map from points to tets for fastening search.
17778 // makepoint2tetmap(); // This has been done in meshsurface().
17779
17780 // Initialize working queues, lists.
17781 flipqueue = new queue(sizeof(badface));
17782 cavsublist = new list(sizeof(face), NULL, 256);
17783 // Initialize the pool of encroached subfaces and subsegments.
17784 badsubsegs = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
17785 badsubfaces = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
17786 // Find all pairs of co-circular subfaces.
17787 tallcocirsubs(eps, true);
17788 if (b->verbose && badsubfaces->items > 0) {
17789 printf(" Removing degenerate subfaces.\n");
17790 }
17791 perturbrepairencsubs(cavsublist, flipqueue);
17792
17793 if (b->verbose > 0) {
17794 printf(" %ld break points.\n", points->items - vertcount);
17795 }
17796
17797 delete cavsublist;
17798 delete flipqueue;
17799 delete badsubfaces;
17800 delete badsubsegs;
17801 badsubsegs = (memorypool *) NULL;
17802 badsubfaces = (memorypool *) NULL;
17803 }
17804
17805 //
17806 // End of vertex perturbation routines
17807 //
17808
17809 //
17810 // Begin of segment recovery routines
17811 //
17812
17813 ///////////////////////////////////////////////////////////////////////////////
17814 // //
17815 // markacutevertices() Mark each vertex to be ACUTE or NACUTE. //
17816 // //
17817 // A vertex is acute if at least two segments incident at it with an angle //
17818 // smaller than a given angle bound (e.g. 90 degree). //
17819 // //
17820 ///////////////////////////////////////////////////////////////////////////////
17821
17822 void tetgenmesh::markacutevertices(REAL acuteangle)
17823 {
17824 shellface **segsperverlist;
17825 face segloop, workseg, inciseg;
17826 point eorg, edest, eapex;
17827 REAL cosbound, anglearc;
17828 REAL v1[3], v2[3], L, D;
17829 bool isacute;
17830 int *idx2seglist;
17831 int idx, i, j, k;
17832
17833 if (b->verbose > 0) {
17834 printf(" Marking segments have acute corners.\n");
17835 }
17836
17837 anglearc = acuteangle * PI / 180.0;
17838 cosbound = cos(anglearc);
17839 // Constructing a map from vertex to segments.
17840 makesegmentmap(idx2seglist, segsperverlist);
17841
17842 // Loop over the set of subsegments.
17843 subsegs->traversalinit();
17844 segloop.sh = shellfacetraverse(subsegs);
17845 while (segloop.sh != (shellface *) NULL) {
17846 // Check and set types for the two ends of this segment.
17847 for (segloop.shver = 0; segloop.shver < 2; segloop.shver++) {
17848 eorg = sorg(segloop);
17849 if ((pointtype(eorg) != ACUTEVERTEX) &&
17850 (pointtype(eorg) != NACUTEVERTEX) &&
17851 (pointtype(eorg) != FREESEGVERTEX)) {
17852 // This vertex has no type be set yet.
17853 idx = pointmark(eorg) - in->firstnumber;
17854 isacute = false;
17855 for (i = idx2seglist[idx]; i < idx2seglist[idx + 1] && !isacute; i++) {
17856 workseg.sh = segsperverlist[i];
17857 workseg.shver = 0;
17858 if (sorg(workseg) != eorg) sesymself(workseg);
17859 #ifdef SELF_CHECK
17860 assert(sorg(workseg) == eorg);
17861 #endif
17862 edest = sdest(workseg);
17863 for (j = i + 1; j < idx2seglist[idx + 1] && !isacute; j++) {
17864 inciseg.sh = segsperverlist[j];
17865 inciseg.shver = 0;
17866 #ifdef SELF_CHECK
17867 assert(inciseg.sh != workseg.sh);
17868 #endif
17869 if (sorg(inciseg) != eorg) sesymself(inciseg);
17870 #ifdef SELF_CHECK
17871 assert(sorg(inciseg) == eorg);
17872 #endif
17873 eapex = sdest(inciseg);
17874 // Check angles between segs (eorg, edest) and (eorg, eapex).
17875 for (k = 0; k < 3; k++) {
17876 v1[k] = edest[k] - eorg[k];
17877 v2[k] = eapex[k] - eorg[k];
17878 }
17879 L = sqrt(v1[0] * v1[0] + v1[1] * v1[1] + v1[2] * v1[2]);
17880 for (k = 0; k < 3; k++) v1[k] /= L;
17881 L = sqrt(v2[0] * v2[0] + v2[1] * v2[1] + v2[2] * v2[2]);
17882 for (k = 0; k < 3; k++) v2[k] /= L;
17883 D = v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
17884 if (D >= cosbound) {
17885 isacute = true;
17886 }
17887 }
17888 }
17889 if (isacute) {
17890 setpointtype(eorg, ACUTEVERTEX);
17891 } else {
17892 setpointtype(eorg, NACUTEVERTEX);
17893 }
17894 }
17895 }
17896 segloop.sh = shellfacetraverse(subsegs);
17897 }
17898
17899 delete [] idx2seglist;
17900 delete [] segsperverlist;
17901 }
17902
17903 ///////////////////////////////////////////////////////////////////////////////
17904 // //
17905 // finddirection() Find the first tetrahedron on the path from one point //
17906 // to another. //
17907 // //
17908 // Find the tetrahedron that intersects a line segment L (from the origin of //
17909 // 'searchtet' to the point 'tend'), and returns the result in 'searchtet'. //
17910 // The origin of 'searchtet' does not change, even though the tetrahedron //
17911 // returned may differ from the one passed in. This routine is used to find //
17912 // the direction to move in to get from one point to another. //
17913 // //
17914 // The return value notes the location of the line segment L with respect to //
17915 // 'searchtet': //
17916 // - Returns RIGHTCOLLINEAR indicates L is collinear with the line segment //
17917 // from the origin to the destination of 'searchtet'. //
17918 // - Returns LEFTCOLLINEAR indicates L is collinear with the line segment //
17919 // from the origin to the apex of 'searchtet'. //
17920 // - Returns TOPCOLLINEAR indicates L is collinear with the line segment //
17921 // from the origin to the opposite of 'searchtet'. //
17922 // - Returns ACROSSEDGE indicates L intersects with the line segment from //
17923 // the destination to the apex of 'searchtet'. //
17924 // - Returns ACROSSFACE indicates L intersects with the face opposite to //
17925 // the origin of 'searchtet'. //
17926 // - Returns BELOWHULL indicates L crosses outside the mesh domain. This //
17927 // can only happen when the domain is non-convex. //
17928 // //
17929 // NOTE: This routine only works correctly when the mesh is exactly Delaunay.//
17930 // //
17931 // If 'maxtetnumber' > 0, stop the searching process if the number of passed //
17932 // tets is larger than it. Return BELOWHULL. //
17933 // //
17934 ///////////////////////////////////////////////////////////////////////////////
17935
17936 enum tetgenmesh::finddirectionresult tetgenmesh::
17937 finddirection(triface *searchtet, point tend, long maxtetnumber)
17938 {
17939 triface neightet;
17940 point tstart, tdest, tapex, toppo;
17941 REAL ori1, ori2, ori3;
17942 long tetnumber;
17943
17944 tstart = org(*searchtet);
17945 #ifdef SELF_CHECK
17946 assert(tstart != tend);
17947 #endif
17948 adjustedgering(*searchtet, CCW);
17949 if (tstart != org(*searchtet)) {
17950 enextself(*searchtet); // For keeping the same origin.
17951 }
17952 tdest = dest(*searchtet);
17953 if (tdest == tend) {
17954 return RIGHTCOLLINEAR;
17955 }
17956 tapex = apex(*searchtet);
17957 if (tapex == tend) {
17958 return LEFTCOLLINEAR;
17959 }
17960
17961 ori1 = orient3d(tstart, tdest, tapex, tend);
17962 if (ori1 > 0.0) {
17963 // 'tend' is below the face, get the neighbor of this side.
17964 sym(*searchtet, neightet);
17965 if (neightet.tet != dummytet) {
17966 findorg(&neightet, tstart);
17967 adjustedgering(neightet, CCW);
17968 if (org(neightet) != tstart) {
17969 enextself(neightet); // keep the same origin.
17970 }
17971 // Set the changed configuratiuon.
17972 *searchtet = neightet;
17973 ori1 = -1.0;
17974 tdest = dest(*searchtet);
17975 tapex = apex(*searchtet);
17976 } else {
17977 // A hull face. Only possible for a nonconvex mesh.
17978 #ifdef SELF_CHECK
17979 assert(nonconvex);
17980 #endif
17981 return BELOWHULL;
17982 }
17983 }
17984
17985 // Repeatedly change the 'searchtet', remain 'tstart' be its origin, until
17986 // find a tetrahedron contains 'tend' or is crossed by the line segment
17987 // from 'tstart' to 'tend'.
17988 tetnumber = 0l;
17989 while ((maxtetnumber > 0) && (tetnumber <= maxtetnumber)) {
17990 tetnumber++;
17991 toppo = oppo(*searchtet);
17992 if (toppo == tend) {
17993 return TOPCOLLINEAR;
17994 }
17995 ori2 = orient3d(tstart, toppo, tdest, tend);
17996 if (ori2 > 0.0) {
17997 // 'tend' is below the face, get the neighbor at this side.
17998 fnext(*searchtet, neightet);
17999 symself(neightet);
18000 if (neightet.tet != dummytet) {
18001 findorg(&neightet, tstart);
18002 adjustedgering(neightet, CCW);
18003 if (org(neightet) != tstart) {
18004 enextself(neightet); // keep the same origin.
18005 }
18006 // Set the changed configuration.
18007 *searchtet = neightet;
18008 ori1 = -1.0;
18009 tdest = dest(*searchtet);
18010 tapex = apex(*searchtet);
18011 // Continue the search from the changed 'searchtet'.
18012 continue;
18013 } else {
18014 // A hull face. Only possible for a nonconvex mesh.
18015 #ifdef SELF_CHECK
18016 assert(nonconvex);
18017 #endif
18018 return BELOWHULL;
18019 }
18020 }
18021 ori3 = orient3d(tapex, toppo, tstart, tend);
18022 if (ori3 > 0.0) {
18023 // 'tend' is below the face, get the neighbor at this side.
18024 enext2fnext(*searchtet, neightet);
18025 symself(neightet);
18026 if (neightet.tet != dummytet) {
18027 findorg(&neightet, tstart);
18028 adjustedgering(neightet, CCW);
18029 if (org(neightet) != tstart) {
18030 enextself(neightet); // keep the same origin.
18031 }
18032 // Set the changed configuration.
18033 *searchtet = neightet;
18034 ori1 = -1.0;
18035 tdest = dest(*searchtet);
18036 tapex = apex(*searchtet);
18037 // Continue the search from the changed 'searchtet'.
18038 continue;
18039 } else {
18040 // A hull face. Only possible for a nonconvex mesh.
18041 #ifdef SELF_CHECK
18042 assert(nonconvex);
18043 #endif
18044 return BELOWHULL;
18045 }
18046 }
18047 // Now 'ori1', 'ori2' and 'ori3' are possible be 0.0 or all < 0.0;
18048 if (ori1 < 0.0) {
18049 // Possible cases are: ACROSSFACE, ACROSSEDGE, TOPCOLLINEAR.
18050 if (ori2 < 0.0) {
18051 if (ori3 < 0.0) {
18052 return ACROSSFACE;
18053 } else { // ori3 == 0.0;
18054 // Cross edge (apex, oppo)
18055 enext2fnextself(*searchtet);
18056 esymself(*searchtet); // org(*searchtet) == tstart;
18057 return ACROSSEDGE;
18058 }
18059 } else { // ori2 == 0.0;
18060 if (ori3 < 0.0) {
18061 // Cross edge (dest, oppo)
18062 fnextself(*searchtet);
18063 esymself(*searchtet);
18064 enextself(*searchtet); // org(*searchtet) == tstart;
18065 return ACROSSEDGE;
18066 } else { // ori3 == 0.0;
18067 // Collinear with edge (org, oppo)
18068 return TOPCOLLINEAR;
18069 }
18070 }
18071 } else { // ori1 == 0.0;
18072 // Possible cases are: RIGHTCOLLINEAR, LEFTCOLLINEAR, ACROSSEDGE.
18073 if (ori2 < 0.0) {
18074 if (ori3 < 0.0) {
18075 // Cross edge (tdest, tapex)
18076 return ACROSSEDGE;
18077 } else { // ori3 == 0.0
18078 // Collinear with edge (torg, tapex)
18079 return LEFTCOLLINEAR;
18080 }
18081 } else { // ori2 == 0.0;
18082 #ifdef SELF_CHECK
18083 assert(ori3 != 0.0);
18084 #endif
18085 // Collinear with edge (torg, tdest)
18086 return RIGHTCOLLINEAR;
18087 }
18088 }
18089 }
18090 // Loop breakout. It may happen when the mesh is non-Delaunay.
18091 return BELOWHULL;
18092 }
18093
18094 ///////////////////////////////////////////////////////////////////////////////
18095 // //
18096 // getsearchtet() Find a tetrahedron whose origin is either 'p1' or 'p2'. //
18097 // //
18098 // On return, the origin of 'searchtet' is either 'p1' or 'p2', and 'tend' //
18099 // returns the other point. 'searchtet' serves as the starting tetrahedron //
18100 // for searching of the line segment from 'p1' to 'p2' or vice versa. //
18101 // //
18102 ///////////////////////////////////////////////////////////////////////////////
18103
18104 void tetgenmesh::getsearchtet(point p1, point p2, triface* searchtet,
18105 point* tend)
18106 {
18107 tetrahedron encodedtet1, encodedtet2;
18108
18109 // Is there a valid handle provided by the user?
18110 if ((searchtet->tet != (tetrahedron *) NULL) && !isdead(searchtet)) {
18111 // Find which endpoint the handle holds.
18112 if (findorg(searchtet, p1)) {
18113 *tend = p2;
18114 return;
18115 } else {
18116 if (findorg(searchtet, p2)) {
18117 *tend = p1;
18118 return;
18119 }
18120 }
18121 }
18122 // If not, search the tet handle stored in 'p1' or 'p2'.
18123 *tend = (point) NULL;
18124 encodedtet1 = point2tet(p1);
18125 encodedtet2 = point2tet(p2);
18126 if (encodedtet1 != (tetrahedron) NULL) {
18127 decode(encodedtet1, *searchtet);
18128 // Be careful, here 'searchtet' may be dead.
18129 if (findorg(searchtet, p1)) {
18130 *tend = p2;
18131 }
18132 } else if (encodedtet2 != (tetrahedron) NULL) {
18133 decode(encodedtet2, *searchtet);
18134 // Be careful, here 'searchtet' may be dead.
18135 if (findorg(searchtet, p2)) {
18136 *tend = p1;
18137 }
18138 }
18139 // If still not, perform a full point location. The starting tet is
18140 // chosen as follows: Use the handle stored in 'p1' or 'p2' if it is
18141 // alive; otherwise, start from a tet on the convex hull.
18142 if (*tend == (point) NULL) {
18143 if (encodedtet1 != (tetrahedron) NULL) {
18144 decode(encodedtet1, *searchtet);
18145 // Be careful, here 'searchtet' may be dead.
18146 }
18147 if (isdead(searchtet)) {
18148 if (encodedtet2 != (tetrahedron) NULL) {
18149 decode(encodedtet2, *searchtet);
18150 // Be careful, here 'searchtet' may be dead.
18151 }
18152 if (isdead(searchtet)) {
18153 searchtet->tet = dummytet;
18154 searchtet->loc = 0;
18155 symself(*searchtet);
18156 }
18157 #ifdef SELF_CHECK
18158 assert(!isdead(searchtet));
18159 #endif
18160 }
18161 if (locate(p1, searchtet) != ONVERTEX) {
18162 printf("Internal error in getsearchtet(): Failed to locate point\n");
18163 internalerror();
18164 }
18165 // Remember this handle in 'p1' to enhance the search speed.
18166 setpoint2tet(p1, encode(*searchtet));
18167 *tend = p2;
18168 }
18169 }
18170
18171 ///////////////////////////////////////////////////////////////////////////////
18172 // //
18173 // isedgeencroached() Check whether or not a subsegment is encroached. //
18174 // //
18175 // A segment with endpoints 'p1' and 'p2' is encroached by the point 'testpt'//
18176 // if it lies in the diametral sphere of this segment. The degenerate case //
18177 // that 'testpt' lies on the sphere is treated as encroached if 'degflag' is //
18178 // set to be TRUE. //
18179 // //
18180 ///////////////////////////////////////////////////////////////////////////////
18181
18182 bool tetgenmesh::isedgeencroached(point p1, point p2, point testpt,
18183 bool degflag)
18184 {
18185 REAL dotproduct;
18186
18187 // Check if the segment is facing an angle larger than 90 degree?
18188 dotproduct = (p1[0] - testpt[0]) * (p2[0] - testpt[0])
18189 + (p1[1] - testpt[1]) * (p2[1] - testpt[1])
18190 + (p1[2] - testpt[2]) * (p2[2] - testpt[2]);
18191 if (dotproduct < 0) {
18192 return true;
18193 } else if (dotproduct == 0 && degflag) {
18194 return true;
18195 } else {
18196 return false;
18197 }
18198 }
18199
18200 ///////////////////////////////////////////////////////////////////////////////
18201 // //
18202 // scoutrefpoint() Search the reference point of a missing segment. //
18203 // //
18204 // A segment S is missing in current Delaunay tetrahedralization DT and will //
18205 // be split by inserting a point V in it. The two end points of S are the //
18206 // origin of 'searchtet' and 'tend'. And we know that S is crossing the face //
18207 // of 'searchtet' opposite to its origin (may be intersecting with the edge //
18208 // from the destination to the apex of the 'searchtet'). The search of P is //
18209 // completed by walking through all faces of DT across by S. //
18210 // //
18211 // Warning: This routine is correct when the tetrahedralization is Delaunay //
18212 // and convex. Otherwise, the search loop may not terminate. //
18213 // //
18214 ///////////////////////////////////////////////////////////////////////////////
18215
18216 tetgenmesh::point tetgenmesh::scoutrefpoint(triface* searchtet, point tend)
18217 {
18218 triface checkface;
18219 point tstart, testpt, refpoint;
18220 REAL cent[3], radius, largest;
18221 REAL ahead;
18222 bool ncollinear;
18223 int sides;
18224
18225 if (b->verbose > 2) {
18226 printf(" Scout the reference point of segment (%d, %d).\n",
18227 pointmark(org(*searchtet)), pointmark(tend));
18228 }
18229
18230 tstart = org(*searchtet);
18231 refpoint = (point) NULL;
18232 largest = 0; // avoid compile warning.
18233
18234 // Check the three vertices of the crossing face.
18235 testpt = apex(*searchtet);
18236 if (isedgeencroached(tstart, tend, testpt, true)) {
18237 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18238 #ifdef SELF_CHECK
18239 assert(ncollinear);
18240 #endif
18241 refpoint = testpt;
18242 largest = radius;
18243 }
18244 testpt = dest(*searchtet);
18245 if (isedgeencroached(tstart, tend, testpt, true)) {
18246 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18247 #ifdef SELF_CHECK
18248 assert(ncollinear);
18249 #endif
18250 if (refpoint == (point) NULL) {
18251 refpoint = testpt;
18252 largest = radius;
18253 } else {
18254 if (radius > largest) {
18255 refpoint = testpt;
18256 largest = radius;
18257 }
18258 }
18259 }
18260 testpt = oppo(*searchtet);
18261 if (isedgeencroached(tstart, tend, testpt, true)) {
18262 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18263 #ifdef SELF_CHECK
18264 assert(ncollinear);
18265 #endif
18266 if (refpoint == (point) NULL) {
18267 refpoint = testpt;
18268 largest = radius;
18269 } else {
18270 if (radius > largest) {
18271 refpoint = testpt;
18272 largest = radius;
18273 }
18274 }
18275 }
18276 // Check the opposite vertex of the neighboring tet in case the segment
18277 // crosses the edge (leftpoint, rightpoint) of the crossing face.
18278 sym(*searchtet, checkface);
18279 if (checkface.tet != dummytet) {
18280 testpt = oppo(checkface);
18281 if (isedgeencroached(tstart, tend, testpt, true)) {
18282 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18283 #ifdef SELF_CHECK
18284 assert(ncollinear);
18285 #endif
18286 if (refpoint == (point) NULL) {
18287 refpoint = testpt;
18288 largest = radius;
18289 } else {
18290 if (radius > largest) {
18291 refpoint = testpt;
18292 largest = radius;
18293 }
18294 }
18295 }
18296 }
18297
18298 // Walk through all crossing faces.
18299 enextfnext(*searchtet, checkface);
18300 sym(checkface, *searchtet);
18301 while (true) {
18302 // Check if we are reaching the boundary of the triangulation.
18303 #ifdef SELF_CHECK
18304 assert(searchtet->tet != dummytet);
18305 #endif
18306 // Search for an adjoining tetrahedron we can walk through.
18307 searchtet->ver = 0;
18308 // 'testpt' is the shared vertex for the following orientation tests.
18309 testpt = oppo(*searchtet);
18310 if (testpt == tend) {
18311 // The searching is finished.
18312 break;
18313 } else {
18314 // 'testpt' may encroach the segment.
18315 if ((testpt != tstart) && (testpt != refpoint)) {
18316 if (isedgeencroached(tstart, tend, testpt, true)) {
18317 ncollinear = circumsphere(tstart, tend, testpt, NULL, cent, &radius);
18318 if (!ncollinear) {
18319 // 'testpt' is collinear with the segment. It may happen when a
18320 // set of collinear and continuous segments is defined by two
18321 // extreme endpoints. In this case, we should choose 'testpt'
18322 // as the splitting point immediately. No new point should be
18323 // created.
18324 refpoint = testpt;
18325 break;
18326 }
18327 if (refpoint == (point) NULL) {
18328 refpoint = testpt;
18329 largest = radius;
18330 } else {
18331 if (radius > largest) {
18332 refpoint = testpt;
18333 largest = radius;
18334 }
18335 }
18336 }
18337 }
18338 }
18339 // Check three side-faces of 'searchtet' to find the one through
18340 // which we can walk next.
18341 for (sides = 0; sides < 3; sides++) {
18342 fnext(*searchtet, checkface);
18343 ahead = orient3d(org(checkface), dest(checkface), testpt, tend);
18344 if (ahead < 0.0) {
18345 // We can walk through this face and continue the searching.
18346 sym(checkface, *searchtet);
18347 break;
18348 }
18349 enextself(*searchtet);
18350 }
18351 #ifdef SELF_CHECK
18352 assert (sides < 3);
18353 #endif
18354 }
18355
18356 #ifdef SELF_CHECK
18357 assert(refpoint != (point) NULL);
18358 #endif
18359 return refpoint;
18360 }
18361
18362 ///////////////////////////////////////////////////////////////////////////////
18363 // //
18364 // getsegmentorigin() Return the origin of the (unsplit) segment. //
18365 // //
18366 // After a segment (or a subsegment) is split. Two resulting subsegments are //
18367 // connecting each other through the pointers saved in their data fields. //
18368 // With these pointers, the whole (unsplit) segment can be found. 'splitseg' //
18369 // may be a split subsegment. Returns the origin of the unsplit segment. //
18370 // //
18371 ///////////////////////////////////////////////////////////////////////////////
18372
18373 tetgenmesh::point tetgenmesh::getsegmentorigin(face* splitseg)
18374 {
18375 face workseg;
18376 point farorg;
18377
18378 farorg = sorg(*splitseg);
18379 if ((pointtype(farorg) != ACUTEVERTEX) &&
18380 (pointtype(farorg) != NACUTEVERTEX)) {
18381 workseg = *splitseg;
18382 do {
18383 senext2self(workseg);
18384 spivotself(workseg);
18385 if (workseg.sh != dummysh) {
18386 workseg.shver = 0; // It's a subsegment.
18387 if (sdest(workseg) != farorg) {
18388 sesymself(workseg);
18389 #ifdef SELF_CHECK
18390 assert(sdest(workseg) == farorg);
18391 #endif
18392 }
18393 farorg = sorg(workseg);
18394 if ((pointtype(farorg) == ACUTEVERTEX) ||
18395 (pointtype(farorg) == NACUTEVERTEX)) break;
18396 }
18397 } while (workseg.sh != dummysh);
18398 }
18399 #ifdef SELF_CHECK
18400 assert((pointtype(farorg) == ACUTEVERTEX) ||
18401 (pointtype(farorg) == NACUTEVERTEX));
18402 #endif
18403 return farorg;
18404 }
18405
18406 ///////////////////////////////////////////////////////////////////////////////
18407 // //
18408 // getsplitpoint() Get a point for splitting a segment. //
18409 // //
18410 // 'splitseg' is the segment will be split. 'refpoint' is a reference point //
18411 // for splitting this segment. Moreover, it should not collinear with the //
18412 // splitting segment. (The collinear case will be detected by iscollinear() //
18413 // before entering this routine.) The calculation of the splitting point is //
18414 // governed by three rules introduced in my paper. //
18415 // //
18416 // After the position is calculated, a new point is created at this location.//
18417 // The new point has one of the two pointtypes: FREESEGVERTEX indicating it //
18418 // is an inserting vertex on segment, and NACUTEVERTEX indicating it is an //
18419 // endpoint of a segment which original has type-3 now becomes type-2. //
18420 // //
18421 ///////////////////////////////////////////////////////////////////////////////
18422
18423 tetgenmesh::point tetgenmesh::getsplitpoint(face* splitseg, point refpoint)
18424 {
18425 point splitpoint;
18426 point farorg, fardest;
18427 point ei, ej, ek, c;
18428 REAL v[3], r, split;
18429 REAL d1, ps, rs;
18430 bool acuteorg, acutedest;
18431 int stype, rule;
18432 int i;
18433
18434 // First determine the type of the segment (type-1, type-2, or type-3).
18435 farorg = getsegmentorigin(splitseg);
18436 acuteorg = (pointtype(farorg) == ACUTEVERTEX);
18437 sesymself(*splitseg);
18438 fardest = getsegmentorigin(splitseg);
18439 acutedest = (pointtype(fardest) == ACUTEVERTEX);
18440 sesymself(*splitseg);
18441
18442 ek = (point) NULL; // avoid a compilation warning.
18443
18444 if (acuteorg) {
18445 if (acutedest) {
18446 stype = 3;
18447 } else {
18448 stype = 2;
18449 ek = farorg;
18450 }
18451 } else {
18452 if (acutedest) {
18453 stype = 2;
18454 // Adjust splitseg, so that its origin is acute.
18455 sesymself(*splitseg);
18456 ek = fardest;
18457 } else {
18458 stype = 1;
18459 }
18460 }
18461 ei = sorg(*splitseg);
18462 ej = sdest(*splitseg);
18463
18464 if (b->verbose > 1) {
18465 printf(" Splitting segment (%d, %d) type-%d with refpoint %d.\n",
18466 pointmark(ei), pointmark(ej), stype, pointmark(refpoint));
18467 }
18468
18469 if (stype == 1 || stype == 3) {
18470 // Use rule-1.
18471 REAL eij, eip, ejp;
18472 eij = distance(ei, ej);
18473 eip = distance(ei, refpoint);
18474 ejp = distance(ej, refpoint);
18475 if ((eip < ejp) && (eip < 0.5 * eij)) {
18476 c = ei;
18477 r = eip;
18478 } else if ((eip > ejp) && (ejp < 0.5 * eij)) {
18479 c = ej;
18480 ej = ei;
18481 r = ejp;
18482 } else {
18483 c = ei;
18484 r = 0.5 * eij;
18485 }
18486 split = r / eij;
18487 for (i = 0; i < 3; i++) {
18488 v[i] = c[i] + split * (ej[i] - c[i]);
18489 }
18490 rule = 1;
18491 } else {
18492 // Use rule-2 or rule-3.
18493 REAL eki, ekj, ekp, evj, evp, eiv;
18494 c = ek;
18495 eki = distance(ek, ei); // eki may equal zero.
18496 ekj = distance(ek, ej);
18497 ekp = distance(ek, refpoint);
18498 // Calculate v (the going to split position between ei, ej).
18499 r = ekp;
18500 // Check the validity of the position.
18501 if (!(eki < r && r < ekj)) {
18502 printf("Error: Invalid PLC.\n");
18503 printf(" Hint: Use -d switch to check it.\n");
18504 terminatetetgen(1);
18505 }
18506 split = r / ekj;
18507 for (i = 0; i < 3; i++) {
18508 v[i] = c[i] + split * (ej[i] - c[i]);
18509 }
18510 rule = 2;
18511 evj = ekj - r; // distance(v, ej);
18512 evp = distance(v, refpoint);
18513 if (evj < evp) {
18514 // v is rejected, use rule-3.
18515 eiv = distance(ei, v);
18516 if (evp <= 0.5 * eiv) {
18517 r = eki + eiv - evp;
18518 } else {
18519 r = eki + 0.5 * eiv;
18520 }
18521 #ifdef SELF_CHECK
18522 assert(eki < r && r < ekj);
18523 #endif
18524 split = r / ekj;
18525 for (i = 0; i < 3; i++) {
18526 v[i] = c[i] + split * (ej[i] - c[i]);
18527 }
18528 if (b->verbose > 1) {
18529 printf(" Using rule-3.\n");
18530 }
18531 rule = 3;
18532 }
18533 }
18534
18535 // Accumulate the corresponding counters.
18536 if (rule == 1) r1count++;
18537 else if (rule == 2) r2count++;
18538 else if (rule == 3) r3count++;
18539 else if (rule == 4) r4count++;
18540
18541 if (b->verbose > 1) {
18542 if (stype == 2) {
18543 printf(" Split = %.12g.\n", distance(ei, v) / distance(ei, ej));
18544 } else {
18545 printf(" Split = %.12g.\n", distance(c, v) / distance(c, ej));
18546 }
18547 }
18548
18549 // Create the newpoint.
18550 makepoint(&splitpoint);
18551 // Add a random perturbation on splitpoint.
18552 d1 = distance(c, v);
18553 if (stype == 1 || stype == 3) {
18554 ps = randgenerator(d1 * 1.0e-3);
18555 } else {
18556 // For type-2 segment, add a smaller perturbation.
18557 // ps = randgenerator(d1 * 1.0e-5);
18558 REAL d2 = distance(refpoint, v);
18559 ps = randgenerator(d2 * 1.0e-5);
18560 }
18561 rs = ps / d1;
18562 // Perturb splitpoint away from c.
18563 for (i = 0; i < 3; i++) {
18564 splitpoint[i] = c[i] + (1.0 + rs) * (v[i] - c[i]);
18565 }
18566 // for (i = 0; i < in->numberofpointattributes; i++) {
18567 // splitpoint[i + 3] = c[i + 3] + (split + rs) * (ej[i + 3] - c[i + 3]);
18568 // }
18569 if (stype == 3) {
18570 // Change a type-3 segment into two type-2 segments.
18571 setpointtype(splitpoint, NACUTEVERTEX);
18572 } else {
18573 // Set it's type be FREESEGVERTEX.
18574 setpointtype(splitpoint, FREESEGVERTEX);
18575 }
18576 setpoint2sh(splitpoint, sencode(*splitseg));
18577
18578 return splitpoint;
18579 }
18580
18581 ///////////////////////////////////////////////////////////////////////////////
18582 // //
18583 // delaunizesegments() Split segments repeatedly until they appear in a //
18584 // Delaunay tetrahedralization. //
18585 // //
18586 // Given a PLC X, which has a set V of vertices and a set of segments. Start //
18587 // from a Delaunay tetrahedralization D of V, this routine recovers segments //
18588 // of X in D by incrementally inserting points on missing segments, updating //
18589 // D with the newly inserted points into D', which remains to be a Delaunay //
18590 // tetrahedralization and respects the segments of X. Hence, each segment of //
18591 // X appears as a union of edges in D'. //
18592 // //
18593 // This routine dynamically maintains two meshes, one is DT, another is the //
18594 // surface mesh F of X. DT and F have exactly the same vertices. They are //
18595 // updated simultaneously with the newly inserted points. //
18596 // //
18597 // Missing segments are found by looping the set S of segments, checking the //
18598 // existence of each segment in DT. Once a segment is found missing in DT, //
18599 // it is split into two subsegments by inserting a point into both DT and F, //
18600 // and S is updated accordingly. However, the inserted point may cause some //
18601 // other existing segments be non-Delaunay, hence are missing from the DT. //
18602 // In order to force all segments to appear in DT, we have to loop S again //
18603 // after some segments are split. (A little ugly method) Use a handle to //
18604 // remember the last segment be split in one loop, hence all segments after //
18605 // it are existing and need not be checked. //
18606 // //
18607 // In priciple, a segment on the convex hull should exist in DT. However, if //
18608 // there are four coplanar points on the convex hull, and the DT only can //
18609 // contain one diagonal edge which is unfortunately not the segment, then it //
18610 // is missing. During the recovery of the segment, it is possible that the //
18611 // calculated inserting point for recovering this convex hull segment is not //
18612 // exact enough and lies (slightly) outside the DT. In order to insert the //
18613 // point, we enlarge the convex hull of the DT, so it can contain the point //
18614 // and remains convex. 'inserthullsite()' is called for this case. //
18615 // //
18616 ///////////////////////////////////////////////////////////////////////////////
18617
18618 void tetgenmesh::delaunizesegments()
18619 {
18620 queue *flipqueue;
18621 tetrahedron encodedtet;
18622 triface searchtet, splittet;
18623 face splitsh, symsplitsub;
18624 face segloop, symsplitseg;
18625 face lastsplit;
18626 point refpoint, splitpoint, sympoint;
18627 point tend, checkpoint;
18628 point p1, p2, pa;
18629 enum finddirectionresult collinear;
18630 enum insertsiteresult success;
18631 enum locateresult symloc;
18632 bool finish, coll;
18633 long vertcount;
18634 int i, j;
18635
18636 if (!b->quiet) {
18637 printf("Delaunizing segments.\n");
18638 }
18639
18640 // Mark segment vertices (acute or not) for determining segment types.
18641 markacutevertices(89.0);
18642 // Construct a map from points to tetrahedra for speeding point location.
18643 // makepoint2tetmap(); // This is done in above routine.
18644 // Initialize a queue for returning non-Delaunay faces and edges.
18645 flipqueue = new queue(sizeof(badface));
18646 // 'lastsplit' is the last segment be split in one loop, all segments
18647 // after it are existing. At first, set it be NULL;
18648 lastsplit.sh = (shellface *) NULL;
18649 // Remember the current number of points.
18650 vertcount = points->items;
18651 // Initialize the counters.
18652 r1count = r2count = r3count = r4count = 0l;
18653
18654 finish = false;
18655 while (!finish && (steinerleft != 0)) {
18656 subsegs->traversalinit();
18657 segloop.sh = shellfacetraverse(subsegs);
18658 while ((segloop.sh != (shellface *) NULL) && (steinerleft != 0)) {
18659 // Search segment ab in DT.
18660 p1 = sorg(segloop); // p1 = a;
18661 p2 = sdest(segloop); // p2 = b;
18662 if (b->verbose > 2) {
18663 printf(" Checking segment (%d, %d).\n", pointmark(p1), pointmark(p2));
18664 }
18665 getsearchtet(p1, p2, &searchtet, &tend);
18666 collinear = finddirection(&searchtet, tend, tetrahedrons->items);
18667 if (collinear == LEFTCOLLINEAR) {
18668 checkpoint = apex(searchtet);
18669 } else if (collinear == RIGHTCOLLINEAR) {
18670 checkpoint = dest(searchtet);
18671 } else if (collinear == TOPCOLLINEAR) {
18672 checkpoint = oppo(searchtet);
18673 } else {
18674 #ifdef SELF_CHECK
18675 assert(collinear == ACROSSFACE || collinear == ACROSSEDGE);
18676 #endif
18677 checkpoint = (point) NULL;
18678 }
18679 if (checkpoint != tend) {
18680 // ab is missing.
18681 splitpoint = (point) NULL;
18682 if (checkpoint != (point) NULL) {
18683 // An existing point c is found on the segment. It can happen when
18684 // ab is defined by a long segment with c inside it. Use c to
18685 // split ab. No new point is created.
18686 splitpoint = checkpoint;
18687 if (pointtype(checkpoint) == VOLVERTEX) {
18688 // c is not a segment vertex yet. It becomes NACUTEVERTEX.
18689 setpointtype(splitpoint, NACUTEVERTEX);
18690 } else if (pointtype(checkpoint) == ACUTEVERTEX) {
18691 // c is an acute vertex. The definition of PLC is wrong.
18692 } else if (pointtype(checkpoint) == NACUTEVERTEX) {
18693 // c is an nonacute vertex. The definition of PLC is wrong.
18694 } else {
18695 // assert(0);
18696 }
18697 } else {
18698 // Find a reference point p of ab.
18699 refpoint = scoutrefpoint(&searchtet, tend);
18700 if (pointtype(refpoint) == VOLVERTEX) {
18701 // p is an input point, check if it is nearly collinear with ab.
18702 coll = iscollinear(p1, p2, refpoint, b->epsilon);
18703 if (coll) {
18704 // a, b, and p are collinear. We insert p into ab. p becomes
18705 // a segment vertex with type NACUTEVERTEX.
18706 splitpoint = refpoint;
18707 setpointtype(splitpoint, NACUTEVERTEX);
18708 }
18709 }
18710 if (splitpoint == (point) NULL) {
18711 // Calculate a split point v using rule 1, or 2, or 3.
18712 splitpoint = getsplitpoint(&segloop, refpoint);
18713
18714 // Is there periodic boundary conditions?
18715 if (checkpbcs) {
18716 // Yes! Insert points on other segments of incident pbcgroups.
18717 i = shellmark(segloop) - 1;
18718 for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++) {
18719 makepoint(&sympoint);
18720 symloc = getsegpbcsympoint(splitpoint, &segloop, sympoint,
18721 &symsplitseg, segpglist[j]);
18722 #ifdef SELF_CHECK
18723 assert(symloc != OUTSIDE);
18724 #endif
18725 if ((symloc == ONEDGE) && (symsplitseg.sh != segloop.sh)) {
18726 #ifdef SELF_CHECK
18727 assert(symsplitseg.sh != dummysh);
18728 #endif
18729 setpointtype(sympoint, FREESEGVERTEX);
18730 setpoint2sh(sympoint, sencode(symsplitseg));
18731 // Insert sympoint into DT.
18732 pa = sorg(symsplitseg);
18733 splittet.tet = dummytet;
18734 // Find a good start point to search.
18735 encodedtet = point2tet(pa);
18736 if (encodedtet != (tetrahedron) NULL) {
18737 decode(encodedtet, splittet);
18738 if (isdead(&splittet)) {
18739 splittet.tet = dummytet;
18740 }
18741 }
18742 // Locate sympoint in DT. Do exact location.
18743 success = insertsite(sympoint, &splittet, false, flipqueue);
18744 #ifdef SELF_CHECK
18745 assert(success != DUPLICATEPOINT);
18746 #endif
18747 if (success == OUTSIDEPOINT) {
18748 inserthullsite(sympoint, &splittet, flipqueue);
18749 }
18750 if (steinerleft > 0) steinerleft--;
18751 // Let sympoint remember splittet.
18752 setpoint2tet(sympoint, encode(splittet));
18753 // Do flip in DT.
18754 flip(flipqueue, NULL);
18755 // Insert sympoint into F.
18756 symsplitseg.shver = 0;
18757 spivot(symsplitseg, symsplitsub);
18758 // sympoint should on the edge of symsplitsub.
18759 splitsubedge(sympoint, &symsplitsub, flipqueue);
18760 // Do flip in facet.
18761 flipsub(flipqueue);
18762 } else { // if (symloc == ONVERTEX) {
18763 // The sympoint already exists. It is possible when two
18764 // pbc groups are exactly the same. Omit this point.
18765 pointdealloc(sympoint);
18766 }
18767 }
18768 }
18769
18770 // Insert 'splitpoint' into DT.
18771 if (isdead(&searchtet)) searchtet.tet = dummytet;
18772 success = insertsite(splitpoint, &searchtet, false, flipqueue);
18773 if (success == OUTSIDEPOINT) {
18774 // A convex hull edge is missing, and the inserting point lies
18775 // (slightly) outside the convex hull due to the significant
18776 // digits lost in the calculation. Enlarge the convex hull.
18777 inserthullsite(splitpoint, &searchtet, flipqueue);
18778 }
18779 if (steinerleft > 0) steinerleft--;
18780 // Remember a handle in 'splitpoint' to enhance the speed of
18781 // consequent point location.
18782 setpoint2tet(splitpoint, encode(searchtet));
18783 // Maintain Delaunayness in DT.
18784 flip(flipqueue, NULL);
18785 }
18786 }
18787 // Insert 'splitpoint' into F.
18788 spivot(segloop, splitsh);
18789 splitsubedge(splitpoint, &splitsh, flipqueue);
18790 flipsub(flipqueue);
18791 // Remember 'segloop'.
18792 lastsplit = segloop;
18793 } else {
18794 // ab exists. Is it the last one we've checked?
18795 if (segloop.sh == lastsplit.sh) {
18796 finish = true;
18797 break;
18798 }
18799 }
18800 segloop.sh = shellfacetraverse(subsegs);
18801 }
18802 if (lastsplit.sh == (shellface *) NULL) {
18803 // No missing segment!
18804 finish = true;
18805 }
18806 }
18807
18808 if (b->verbose > 0) {
18809 printf(" %ld protect points.\n", points->items - vertcount);
18810 }
18811
18812 delete flipqueue;
18813 }
18814
18815 //
18816 // End of segments recovery routines
18817 //
18818
18819 //
18820 // Begin of facet recovery routines
18821 //
18822
18823 ///////////////////////////////////////////////////////////////////////////////
18824 // //
18825 // insertsubface() Fix a subface in place. //
18826 // //
18827 // Search a subface s in current tetrahedralization T. If s is found a face //
18828 // face of T, it is inserted into T. Return FALSE if s is not found in T. //
18829 // //
18830 ///////////////////////////////////////////////////////////////////////////////
18831
18832 bool tetgenmesh::insertsubface(face* insertsh, triface* searchtet)
18833 {
18834 triface spintet, symtet;
18835 face testsh, testseg;
18836 face spinsh, casin, casout;
18837 point tapex, checkpoint;
18838 enum finddirectionresult collinear;
18839 int hitbdry;
18840
18841 // Search an edge of s.
18842 getsearchtet(sorg(*insertsh), sdest(*insertsh), searchtet, &checkpoint);
18843 collinear = finddirection(searchtet, checkpoint, tetrahedrons->items);
18844 if (collinear == LEFTCOLLINEAR) {
18845 enext2self(*searchtet);
18846 esymself(*searchtet);
18847 } else if (collinear == TOPCOLLINEAR) {
18848 fnextself(*searchtet);
18849 enext2self(*searchtet);
18850 esymself(*searchtet);
18851 }
18852 if (dest(*searchtet) != checkpoint) {
18853 // The edge doesn't exist => s is missing.
18854 return false;
18855 }
18856
18857 // Search s by spinning faces around the edge.
18858 tapex = sapex(*insertsh);
18859 spintet = *searchtet;
18860 hitbdry = 0;
18861 do {
18862 if (apex(spintet) == tapex) {
18863 // Found s in T. Check if s has already been inserted.
18864 tspivot(spintet, testsh);
18865 if (testsh.sh == dummysh) {
18866 adjustedgering(spintet, CCW);
18867 findedge(insertsh, org(spintet), dest(spintet));
18868 tsbond(spintet, *insertsh);
18869 sym(spintet, symtet); // 'symtet' maybe outside, use it anyway.
18870 sesymself(*insertsh);
18871 tsbond(symtet, *insertsh);
18872 } else {
18873 // Found a duplicated subface (due to the redundant input).
18874 if (!b->quiet) {
18875 printf("Warning: Two subfaces are found duplicated at ");
18876 printf("(%d, %d, %d)\n", pointmark(sorg(testsh)),
18877 pointmark(sdest(testsh)), pointmark(sapex(testsh)));
18878 printf(" Subface of facet #%d is deleted.\n", shellmark(*insertsh));
18879 // printf(" Hint: -d switch can find all duplicated facets.\n");
18880 }
18881 shellfacedealloc(subfaces, insertsh->sh);
18882 }
18883 return true;
18884 }
18885 if (!fnextself(spintet)) {
18886 hitbdry ++;
18887 if (hitbdry < 2) {
18888 esym(*searchtet, spintet);
18889 if (!fnextself(spintet)) {
18890 hitbdry ++;
18891 }
18892 }
18893 }
18894 } while (hitbdry < 2 && apex(spintet) != apex(*searchtet));
18895
18896 // s is missing.
18897 return false;
18898 }
18899
18900 ///////////////////////////////////////////////////////////////////////////////
18901 // //
18902 // tritritest() Test if two triangles are intersecting in their interior. //
18903 // //
18904 // One triangle t1 is the face of 'checktet', the other t2 is given by three //
18905 // corners 'p1', 'p2' and 'p3'. This routine calls tri_tri_inter() to detect //
18906 // whether t1 and t2 exactly intersect in their interior. Cases like share a //
18907 // vertex, share an edge, or coincidence are considered not intersect. //
18908 // //
18909 ///////////////////////////////////////////////////////////////////////////////
18910
18911 bool tetgenmesh::tritritest(triface* checktet, point p1, point p2, point p3)
18912 {
18913 point forg, fdest, fapex;
18914 enum interresult intersect;
18915
18916 forg = org(*checktet);
18917 fdest = dest(*checktet);
18918 fapex = apex(*checktet);
18919
18920 #ifdef SELF_CHECK
18921 REAL ax, ay, az, bx, by, bz;
18922 REAL n[3];
18923 // face (torg, tdest, tapex) should not be degenerate. However p1, p2,
18924 // and p3 may be collinear. Check it.
18925 ax = forg[0] - fdest[0];
18926 ay = forg[1] - fdest[1];
18927 az = forg[2] - fdest[2];
18928 bx = forg[0] - fapex[0];
18929 by = forg[1] - fapex[1];
18930 bz = forg[2] - fapex[2];
18931 n[0] = ay * bz - by * az;
18932 n[1] = az * bx - bz * ax;
18933 n[2] = ax * by - bx * ay;
18934 assert(fabs(n[0]) + fabs(n[1]) + fabs(n[2]) > 0.0);
18935 // The components of n should not smaller than the machine epsilon.
18936
18937 ax = p1[0] - p2[0];
18938 ay = p1[1] - p2[1];
18939 az = p1[2] - p2[2];
18940 bx = p1[0] - p3[0];
18941 by = p1[1] - p3[1];
18942 bz = p1[2] - p3[2];
18943 n[0] = ay * bz - by * az;
18944 n[1] = az * bx - bz * ax;
18945 n[2] = ax * by - bx * ay;
18946 assert(fabs(n[0]) + fabs(n[1]) + fabs(n[2]) > 0.0);
18947 // The components of n should not smaller than the machine epsilon.
18948 #endif
18949
18950 intersect = tri_tri_inter(forg, fdest, fapex, p1, p2, p3);
18951 return intersect == INTERSECT;
18952 }
18953
18954 ///////////////////////////////////////////////////////////////////////////////
18955 // //
18956 // initializecavity() Initialize the cavity. //
18957 // //
18958 // A cavity C is bounded by a list of faces, called fronts. Each front f is //
18959 // hold by a tet t adjacent to C, t is not in C (uninfected). If f is a hull //
18960 // face, t does't exist, a fake tet t' is created to hold f. t' has the same //
18961 // vertices as f but no opposite. t' will be removed automatically after C //
18962 // is filled with new tets (by carvecavity()). //
18963 // //
18964 // The faces of C are given in two lists. 'floorlist' is a set of subfaces, //
18965 // each subface has been oriented to face to the inside of C. 'ceillist' is //
18966 // a set of tetrahedral faces. 'frontlist' returns the initialized fronts. //
18967 // //
18968 ///////////////////////////////////////////////////////////////////////////////
18969
18970 void tetgenmesh::initializecavity(list* floorlist, list* ceillist,
18971 list* frontlist)
18972 {
18973 triface neightet, casingtet;
18974 triface faketet;
18975 face worksh;
18976 int i;
18977
18978 // Initialize subfaces of C.
18979 for (i = 0; i < floorlist->len(); i++) {
18980 // Get a subface s.
18981 worksh = * (face *)(* floorlist)[i];
18982 #ifdef SELF_CHECK
18983 // Current side of s should be empty.
18984 stpivot(worksh, neightet);
18985 assert(neightet.tet == dummytet);
18986 #endif
18987 // Get the adjacent tet t.
18988 sesymself(worksh);
18989 stpivot(worksh, casingtet);
18990 // Does t exist?
18991 if (casingtet.tet == dummytet) {
18992 // Create a fake tet t' to hold f temporarily.
18993 maketetrahedron(&faketet);
18994 setorg(faketet, sorg(worksh));
18995 setdest(faketet, sdest(worksh));
18996 setapex(faketet, sapex(worksh));
18997 setoppo(faketet, (point) NULL); // Indicates it is 'fake'.
18998 tsbond(faketet, worksh);
18999 frontlist->append(&faketet);
19000 } else {
19001 frontlist->append(&casingtet);
19002 }
19003 }
19004 // Initialize tet faces of C.
19005 for (i = 0; i < ceillist->len(); i++) {
19006 // Get a tet face c.
19007 neightet = * (triface *) (* ceillist)[i];
19008 #ifdef SELF_CHECK
19009 // The tet of c must be inside C (going to be deleted).
19010 assert(infected(neightet));
19011 #endif
19012 // Get the adjacent tet t.
19013 sym(neightet, casingtet);
19014 // Does t exist?
19015 if (casingtet.tet == dummytet) {
19016 // No. Create a fake tet t' to hold f temporarily.
19017 maketetrahedron(&faketet);
19018 // Be sure that the vertices of t' are CCW oriented.
19019 adjustedgering(neightet, CW); // CW edge ring.
19020 setorg(faketet, org(neightet));
19021 setdest(faketet, dest(neightet));
19022 setapex(faketet, apex(neightet));
19023 setoppo(faketet, (point) NULL); // Indicates it is 'fake'.
19024 // Bond t' to a subface if it exists.
19025 tspivot(neightet, worksh);
19026 if (worksh.sh != dummysh) {
19027 sesymself(worksh);
19028 tsbond(faketet, worksh);
19029 }
19030 // Bond c <--> t'. So we're able to find t' and remove it.
19031 bond(faketet, neightet);
19032 // c may become uninfected due to the bond().
19033 infect(neightet);
19034 frontlist->append(&faketet);
19035 } else {
19036 frontlist->append(&casingtet);
19037 }
19038 }
19039 }
19040
19041 ///////////////////////////////////////////////////////////////////////////////
19042 // //
19043 // retrievenewtets() Retrieve the newly created tets. //
19044 // //
19045 // On input, 'newtetlist' contains at least one alive new tet. From this tet,//
19046 // other new tets can be found by a broadth-first searching. //
19047 // //
19048 ///////////////////////////////////////////////////////////////////////////////
19049
19050 void tetgenmesh::retrievenewtets(list* newtetlist)
19051 {
19052 triface searchtet, casingtet;
19053 int i;
19054
19055 // There may be dead tets due to flip32(). Delete them first.
19056 for (i = 0; i < newtetlist->len(); i++) {
19057 searchtet = * (triface *)(* newtetlist)[i];
19058 if (isdead(&searchtet)) {
19059 newtetlist->del(i, 0); i--;
19060 continue;
19061 }
19062 infect(searchtet);
19063 }
19064 // Find all new tets.
19065 for (i = 0; i < newtetlist->len(); i++) {
19066 searchtet = * (triface *)(* newtetlist)[i];
19067 for (searchtet.loc = 0; searchtet.loc < 4; searchtet.loc++) {
19068 sym(searchtet, casingtet);
19069 if ((casingtet.tet != dummytet) && !infected(casingtet)) {
19070 infect(casingtet);
19071 newtetlist->append(&casingtet);
19072 }
19073 }
19074 }
19075 // Uninfect new tets.
19076 for (i = 0; i < newtetlist->len(); i++) {
19077 searchtet = * (triface *)(* newtetlist)[i];
19078 uninfect(searchtet);
19079 }
19080 }
19081
19082 ///////////////////////////////////////////////////////////////////////////////
19083 // //
19084 // delaunizecavvertices() Form a DT of the vertices of a cavity. //
19085 // //
19086 // 'floorptlist' and 'ceilptlist' are the vertices of the cavity. //
19087 // //
19088 // The tets of the DT are created directly in the pool 'tetrahedrons', i.e., //
19089 // no auxiliary data structure and memory are required. The trick is at the //
19090 // time they're created, there are no connections between them to the other //
19091 // tets in the pool. You can imagine they form an ioslated island. //
19092 // //
19093 ///////////////////////////////////////////////////////////////////////////////
19094
19095 void tetgenmesh::delaunizecavvertices(triface* oldtet, list* floorptlist,
19096 list* ceilptlist, list* newtetlist, queue* flipque)
19097 {
19098 point *insertarray;
19099 triface bakhulltet, newtet;
19100 long bakhullsize;
19101 long arraysize;
19102 int bakchksub;
19103 int i, j;
19104
19105 // Prepare the array of points for inserting.
19106 arraysize = floorptlist->len();
19107 if (ceilptlist != (list *) NULL) {
19108 arraysize += ceilptlist->len();
19109 }
19110 insertarray = new point[arraysize];
19111 for (i = 0; i < floorptlist->len(); i++) {
19112 insertarray[i] = * (point *)(* floorptlist)[i];
19113 }
19114 if (ceilptlist != (list *) NULL) {
19115 for (j = 0; j < ceilptlist->len(); j++) {
19116 insertarray[i + j] = * (point *)(* ceilptlist)[j];
19117 }
19118 }
19119
19120 // The incrflipdelaunay() is re-used. Backup global variables.
19121 decode(dummytet[0], bakhulltet);
19122 bakhullsize = hullsize;
19123 bakchksub = checksubfaces;
19124 checksubfaces = 0;
19125 b->verbose--;
19126
19127 // Form the DT by incremental flip Delaunay algorithm. Do not jump for
19128 // point location, do not merge points.
19129 incrflipdelaunay(oldtet, insertarray, arraysize, false, false, 0.0, flipque);
19130
19131 // Get a tet in D.
19132 decode(dummytet[0], newtet);
19133 newtetlist->append(&newtet);
19134 // Get all tets of D.
19135 retrievenewtets(newtetlist);
19136
19137 // Restore global variables.
19138 dummytet[0] = encode(bakhulltet);
19139 hullsize = bakhullsize;
19140 checksubfaces = bakchksub;
19141 b->verbose++;
19142
19143 delete [] insertarray;
19144 }
19145
19146 ///////////////////////////////////////////////////////////////////////////////
19147 // //
19148 // insertauxsubface() Fix an auxilary subface in place. //
19149 // //
19150 // An auxilary subface s is fixed in D as it is a real subface, but s has no //
19151 // vertices and neighbors. It has two uses: (1) it protects an identfied //
19152 // front f in D; (2) it serves the link to bond a tet in C and f later. The //
19153 // first neighbor of s (s->sh[0]) stores a pointer to f. //
19154 // //
19155 // 'front' is a front f of C. idfront' t is a tet in D where f is identified //
19156 // be a face of it. s will be fixed between t and its neighbor. //
19157 // //
19158 ///////////////////////////////////////////////////////////////////////////////
19159
19160 void tetgenmesh::insertauxsubface(triface* front, triface* idfront)
19161 {
19162 triface neightet;
19163 face auxsh;
19164
19165 // Create the aux subface s.
19166 makeshellface(subfaces, &auxsh);
19167 // Bond s <--> t.
19168 tsbond(*idfront, auxsh);
19169 // Does t's neighbor n exist?
19170 sym(*idfront, neightet);
19171 if (neightet.tet != dummytet) {
19172 // Bond s <--> n.
19173 sesymself(auxsh);
19174 tsbond(neightet, auxsh);
19175 }
19176 // Let s remember f.
19177 auxsh.sh[0] = (shellface) encode(*front);
19178 }
19179
19180 ///////////////////////////////////////////////////////////////////////////////
19181 // //
19182 // scoutfront() Scout a face in D. //
19183 // //
19184 // Search a 'front' f in D. If f is found, return TRUE and the face of D is //
19185 // returned in 'idfront'. Otherwise, return FALSE. //
19186 // //
19187 ///////////////////////////////////////////////////////////////////////////////
19188
19189 bool tetgenmesh::scoutfront(triface* front, triface* idfront, list* newtetlist)
19190 {
19191 triface spintet;
19192 point pa, pb, pc;
19193 enum locateresult loc;
19194 enum finddirectionresult col;
19195 int hitbdry;
19196 int i;
19197
19198 // Let the front we're searching is abc.
19199 pa = org(*front);
19200 pb = dest(*front);
19201 // Get a tet in D for searching.
19202 *idfront = recenttet;
19203 // Make sure the tet is valid (it may be killed by flips).
19204 if (isdead(idfront)) {
19205 // The tet is dead. Search a live tet in D. !!!
19206 for (i = 0; i < newtetlist->len(); i++) {
19207 recenttet = * (triface *)(* newtetlist)[i];
19208 if (!isdead(&recenttet)) break;
19209 }
19210 assert(i < newtetlist->len());
19211 }
19212
19213 // Search a tet having vertex a.
19214 loc = preciselocate(pa, idfront, (long) newtetlist->len());
19215 assert(loc == ONVERTEX);
19216 recenttet = *idfront;
19217 // Search a tet having edge ab.
19218 col = finddirection(idfront, pb, (long) newtetlist->len());
19219 if (col == RIGHTCOLLINEAR) {
19220 // b is just the destination.
19221 } else if (col == LEFTCOLLINEAR) {
19222 enext2self(*idfront);
19223 esymself(*idfront);
19224 } else if (col == TOPCOLLINEAR) {
19225 fnextself(*idfront);
19226 enext2self(*idfront);
19227 esymself(*idfront);
19228 }
19229
19230 if (dest(*idfront) == pb) {
19231 // Search a tet having face abc
19232 pc = apex(*front);
19233 spintet = *idfront;
19234 hitbdry = 0;
19235 do {
19236 if (apex(spintet) == pc) {
19237 // Found abc. Insert an auxilary subface s at idfront.
19238 // insertauxsubface(front, &spintet);
19239 *idfront = spintet;
19240 return true;
19241 }
19242 if (!fnextself(spintet)) {
19243 hitbdry ++;
19244 if (hitbdry < 2) {
19245 esym(*idfront, spintet);
19246 if (!fnextself(spintet)) {
19247 hitbdry ++;
19248 }
19249 }
19250 }
19251 if (apex(spintet) == apex(*idfront)) break;
19252 } while (hitbdry < 2);
19253 }
19254
19255 // f is missing in D.
19256 if (b->verbose > 2) {
19257 printf(" Front (%d, %d, %d) is missing.\n", pointmark(pa),
19258 pointmark(pb), pointmark(apex(*front)));
19259 }
19260 return false;
19261 }
19262
19263 ///////////////////////////////////////////////////////////////////////////////
19264 // //
19265 // gluefronts() Glue two fronts together. //
19266 // //
19267 // This is a support routine for identifyfront(). Two fronts f and f1 are //
19268 // found indentical. This is caused by the non-coplanarity of vertices of a //
19269 // facet. Hence f and f1 are a subface and a tet. They are not fronts of the //
19270 // cavity anymore. This routine glues f and f1 together. //
19271 // //
19272 ///////////////////////////////////////////////////////////////////////////////
19273
19274 void tetgenmesh::gluefronts(triface* front, triface* front1)
19275 {
19276 face consh;
19277
19278 // Glue f and f1 together. There're four cases:
19279 // (1) both f and f1 are not fake;
19280 // (2) f is not fake, f1 is fake;
19281 // (3) f is fake and f1 is not fake;
19282 // (4) both f and f1 are fake.
19283 // Case (4) should be not possible.
19284
19285 // Is there a concrete subface c at f.
19286 tspivot(*front, consh);
19287 if (consh.sh != dummysh) {
19288 sesymself(consh);
19289 tsbond(*front1, consh); // Bond: f1 <--> c.
19290 sesymself(consh);
19291 }
19292 // Does f hold by a fake tet.
19293 if (oppo(*front) == (point) NULL) {
19294 // f is fake. Case (3) or (4).
19295 assert(oppo(*front1) != (point) NULL); // Eliminate (4).
19296 // Case (3).
19297 if (consh.sh != dummysh) {
19298 stdissolve(consh); // Dissolve: c -x-> f.
19299 }
19300 // Dealloc f.
19301 tetrahedrondealloc(front->tet);
19302 // f1 becomes a hull. let 'dummytet' bond to it.
19303 dummytet[0] = encode(*front1);
19304 } else {
19305 // Case (1) or (2).
19306 bond(*front, *front1); // Bond f1 <--> f.
19307 }
19308 // Is f a fake tet?
19309 if (!isdead(front)) {
19310 // No. Check for case (2).
19311 tspivot(*front1, consh);
19312 // Is f1 fake?
19313 if (oppo(*front1) == (point) NULL) {
19314 // Case (2) or (4)
19315 assert(oppo(*front) != (point) NULL); // Eliminate (4).
19316 // Case (2).
19317 if (consh.sh != dummysh) {
19318 stdissolve(consh); // Dissolve: c -x-> f1.
19319 sesymself(consh); // Bond: f <--> c.
19320 tsbond(*front, consh);
19321 }
19322 // Dissolve: f -x->f1.
19323 dissolve(*front);
19324 // Dealloc f1.
19325 tetrahedrondealloc(front1->tet);
19326 // f becomes a hull. let 'dummytet' bond to it.
19327 dummytet[0] = encode(*front);
19328 } else {
19329 // Case (1).
19330 if (consh.sh != dummysh) {
19331 sesymself(consh);
19332 tsbond(*front, consh); // Bond: f <--> c.
19333 }
19334 }
19335 }
19336 }
19337
19338 ///////////////////////////////////////////////////////////////////////////////
19339 // //
19340 // identifyfronts() Identify cavity faces in D. //
19341 // //
19342 // 'frontlist' are fronts of C need indentfying. This routine searches each //
19343 // front f in D. Once f is found, an auxilary subface s is inserted in D at //
19344 // the face. If f is not found in D, remove it from frontlist and save it in //
19345 // 'misfrontlist'. //
19346 // //
19347 ///////////////////////////////////////////////////////////////////////////////
19348
19349 bool tetgenmesh::identifyfronts(list* frontlist, list* misfrontlist,
19350 list* newtetlist)
19351 {
19352 triface front, front1, tfront;
19353 triface idfront, neightet;
19354 face auxsh;
19355 int len, i, j;
19356
19357 misfrontlist->clear();
19358 // Set a new tet in D for searching.
19359 recenttet = * (triface *)(* newtetlist)[0];
19360
19361 // Identify all fronts in D.
19362 for (i = 0; i < frontlist->len(); i++) {
19363 // Get a front f.
19364 front = * (triface *)( *frontlist)[i];
19365 if (scoutfront(&front, &idfront, newtetlist)) {
19366 // Found f. Insert an aux subface s.
19367 assert((idfront.tet != dummytet) && !isdead(&idfront));
19368 // Does s already exist?
19369 tspivot(idfront, auxsh);
19370 if (auxsh.sh != dummysh) {
19371 // There're two identical fronts, f (front) and f1 (s.sh[0])!
19372 decode((tetrahedron) auxsh.sh[0], front1);
19373 assert((front1.tet != dummytet) && !infected(front1));
19374 // Detach s in D.
19375 tsdissolve(idfront);
19376 sym(idfront, neightet);
19377 if (neightet.tet != dummytet) {
19378 tsdissolve(neightet);
19379 }
19380 // s has fulfilled its duty. Can be deleted.
19381 shellfacedealloc(subfaces, auxsh.sh);
19382 // Remove f from frontlist.
19383 frontlist->del(i, 1); i--;
19384 // Remove f1 from frontlist.
19385 len = frontlist->len();
19386 for (j = 0; j < frontlist->len(); j++) {
19387 tfront = * (triface *)(* frontlist)[j];
19388 if ((tfront.tet == front1.tet) && (tfront.loc == front1.loc)) {
19389 // Found f1 in list. Check f1 != f.
19390 assert((tfront.tet != front.tet) || (tfront.loc != front.loc));
19391 frontlist->del(j, 1); i--;
19392 break;
19393 }
19394 }
19395 assert((frontlist->len() + 1) == len);
19396 // Glue f and f1 together.
19397 gluefronts(&front, &front1);
19398 } else {
19399 // Insert an aux subface to protect f in D.
19400 insertauxsubface(&front, &idfront);
19401 }
19402 } else {
19403 // f is missing.
19404 frontlist->del(i, 1); i--;
19405 // Are there two identical fronts, f (front) and f1 (front1)?
19406 for (j = 0; j < misfrontlist->len(); j++) {
19407 front1 = * (triface *)(* misfrontlist)[j];
19408 if (isfacehaspoint(&front1, org(front)) &&
19409 isfacehaspoint(&front1, dest(front)) &&
19410 isfacehaspoint(&front1, apex(front))) break;
19411 }
19412 if (j < misfrontlist->len()) {
19413 // Found an identical front f1. Remove f1 from the list.
19414 misfrontlist->del(j, 1);
19415 // Glue f and f1 together.
19416 gluefronts(&front, &front1);
19417 } else {
19418 // Add f into misfrontlist.
19419 misfrontlist->append(&front);
19420 }
19421 }
19422 }
19423 return misfrontlist->len() == 0;
19424 }
19425
19426 ///////////////////////////////////////////////////////////////////////////////
19427 // //
19428 // detachauxsubfaces() Detach auxilary subfaces in D. //
19429 // //
19430 // This is a reverse routine of identifyfronts(). Some fronts are missing in //
19431 // D. C can not be easily tetrahedralized. It needs remediation (expansion, //
19432 // or constrained flips, or adding a Steiner point). This routine detaches //
19433 // the auxilary subfaces have been inserted in D and delete them. //
19434 // //
19435 ///////////////////////////////////////////////////////////////////////////////
19436
19437 void tetgenmesh::detachauxsubfaces(list* newtetlist)
19438 {
19439 triface newtet, neightet;
19440 face auxsh;
19441 int i;
19442
19443 for (i = 0; i < newtetlist->len(); i++) {
19444 // Get a new tet t.
19445 newtet = * (triface *)(* newtetlist)[i];
19446 // t may e dead due to flips.
19447 if (isdead(&newtet)) continue;
19448 assert(!infected(newtet));
19449 // Check the four faces of t.
19450 for (newtet.loc = 0; newtet.loc < 4; newtet.loc++) {
19451 tspivot(newtet, auxsh);
19452 if (auxsh.sh != dummysh) {
19453 // An auxilary subface s.
19454 assert(sorg(auxsh) == (point) NULL);
19455 tsdissolve(newtet); // t -x-> s.
19456 sym(newtet, neightet);
19457 if (neightet.tet != dummytet) {
19458 assert(!isdead(&neightet));
19459 tsdissolve(neightet); // n -x-> s.
19460 }
19461 // Delete s.
19462 shellfacedealloc(subfaces, auxsh.sh);
19463 }
19464 }
19465 }
19466 }
19467
19468 ///////////////////////////////////////////////////////////////////////////////
19469 // //
19470 // expandcavity() Expand the cavity by adding new fronts. //
19471 // //
19472 // This is the support routine for delaunizecavity(). Some fronts of C are //
19473 // missing in D since they're not strongly Delaunay. Such fronts are removed //
19474 // and the faces of the tets abutting to them are added. C is then expanded. //
19475 // Some removed faces may be subfaces, they're queued to recover later. D is //
19476 // expanded simultaneously with the new vertices of the new fronts. //
19477 // //
19478 ///////////////////////////////////////////////////////////////////////////////
19479
19480 void tetgenmesh::expandcavity(list* frontlist, list* misfrontlist,
19481 list* newtetlist, list* crosstetlist, queue* missingshqueue, queue* flipque)
19482 {
19483 triface misfront, newfront, casingtet, crosstet;
19484 triface searchtet, faketet, bakhulltet;
19485 face checksh;
19486 point pd;
19487 enum insertsiteresult success;
19488 long bakhullsize;
19489 int bakchksub;
19490 int i, j, k;
19491
19492 if (b->verbose > 1) {
19493 printf(" Expand cavity (%d missing fronts).\n", misfrontlist->len());
19494 }
19495 // Increase the number of expanded times.
19496 expcavcount++;
19497 // The incrflipdelaunay() is re-used. Backup global variables.
19498 decode(dummytet[0], bakhulltet);
19499 bakhullsize = hullsize;
19500 bakchksub = checksubfaces;
19501 checksubfaces = 0;
19502 b->verbose--;
19503
19504 // Choose a tet in D for searching.
19505 recenttet = * (triface *)(* newtetlist)[0];
19506 assert((recenttet.tet != dummytet) && !isdead(&recenttet));
19507
19508 // Loop through 'misfrontlist'.
19509 for (i = 0; i < misfrontlist->len(); i++) {
19510 // Get a missing front f.
19511 misfront = * (triface *)(* misfrontlist)[i];
19512 // C will be expanded at f.
19513 if (b->verbose > 1) {
19514 printf(" Get misfront (%d, %d, %d).\n", pointmark(org(misfront)),
19515 pointmark(dest(misfront)), pointmark(apex(misfront)));
19516 }
19517 // Is f has a subface s?
19518 tspivot(misfront, checksh);
19519 if (checksh.sh != dummysh) {
19520 // A subface s is found. Check whether f is expandable at s.
19521 sym(misfront, crosstet);
19522 if (!infected(crosstet)) {
19523 // f is not expandable. In principle is should not happen. However,
19524 // it can happen when PBC is in use.
19525 assert(checkpbcs);
19526 // Skip expanding f. It will be processed later.
19527 continue;
19528 }
19529 // Temporarily remove s. Queue and recover it later.
19530 if (b->verbose > 1) {
19531 printf(" Queuing subface (%d, %d, %d).\n",
19532 pointmark(sorg(checksh)), pointmark(sdest(checksh)),
19533 pointmark(sapex(checksh)));
19534 }
19535 // Detach s from tets at its both sides.
19536 tsdissolve(misfront);
19537 tsdissolve(crosstet);
19538 // Detach tets at from s.
19539 stdissolve(checksh);
19540 sesymself(checksh);
19541 stdissolve(checksh);
19542 // Mark and queue it.
19543 sinfect(checksh);
19544 missingshqueue->push(&checksh);
19545 }
19546 // f may already be processed (become a cross tet of C).
19547 if (infected(misfront)) continue;
19548 // Get the point p = oppo(t), t is the tet holds f.
19549 pd = oppo(misfront);
19550 #ifdef SELF_CHECK
19551 // t must not be fake.
19552 assert(pd != (point) NULL);
19553 #endif
19554 // Insert p in D. p may not be inserted if it is one of the two cases:
19555 // (1) p is already a vertex of D;
19556 // (2) p lies outside the CH of D;
19557 searchtet = recenttet;
19558 // Make sure the tet is valid (it may be killed by flips).
19559 if (isdead(&searchtet)) {
19560 // The tet is dead. Get a live tet in D. !!!
19561 for (j = 0; j < newtetlist->len(); j++) {
19562 recenttet = * (triface *)(* newtetlist)[j];
19563 if (!isdead(&recenttet)) break;
19564 }
19565 assert(j < newtetlist->len());
19566 searchtet = recenttet;
19567 }
19568 success = insertsite(pd, &searchtet, false, flipque);
19569 if (success == OUTSIDEPOINT) {
19570 // case (2). Insert p onto CH of D.
19571 inserthullsite(pd, &searchtet, flipque);
19572 }
19573 if (success != DUPLICATEPOINT) {
19574 // p is inserted. Recover Delaunness of D by flips.
19575 flip(flipque, NULL);
19576 }
19577 // Expand C by adding new fronts. The three faces of t which have p as a
19578 // vertex become new fronts. However, if a new front is coincident with
19579 // an old front of C, it is not added and the old front is removed.
19580 adjustedgering(misfront, CCW);
19581 for (j = 0; j < 3; j++) {
19582 // Notice: Below I mis-used the names. 'newfront' is not exactly a new
19583 // front, instead the 'casingtet' should be called new front.
19584 // Get a new front f_n.
19585 fnext(misfront, newfront);
19586 // Get the neighbor tet n at f_n.
19587 sym(newfront, casingtet);
19588 // Is n a cross tet?
19589 if (!infected(casingtet)) {
19590 // f_n becomes a new front of C.
19591 // Does n exist?
19592 if (casingtet.tet == dummytet) {
19593 // Create a fake tet n' to hold f_n temporarily.
19594 maketetrahedron(&faketet);
19595 // Be sure that the vertices of fake tet are CCW oriented.
19596 adjustedgering(newfront, CW); // CW edge ring.
19597 setorg(faketet, org(newfront));
19598 setdest(faketet, dest(newfront));
19599 setapex(faketet, apex(newfront));
19600 setoppo(faketet, (point) NULL); // Indicates it is 'fake'.
19601 // Bond n' to a subface if it exists.
19602 tspivot(newfront, checksh);
19603 if (checksh.sh != dummysh) {
19604 sesymself(checksh);
19605 tsbond(faketet, checksh);
19606 }
19607 // Bond f_n <--> n'. So we're able to find n' and remove it.
19608 bond(faketet, newfront);
19609 frontlist->append(&faketet);
19610 } else {
19611 // Add n to frontlist.
19612 frontlist->append(&casingtet);
19613 }
19614 } else {
19615 // f_n is coincident with an existing front f' of C. f' is no longer
19616 // a front, remove it from frontlist. Use the inverse order to
19617 // search f' (most likely, a newly added front may be f').
19618 for (k = frontlist->len() - 1; k >= 0; k--) {
19619 searchtet = * (triface *)(* frontlist)[k];
19620 if ((newfront.tet == searchtet.tet) &&
19621 (newfront.loc == searchtet.loc)) {
19622 frontlist->del(k, 0);
19623 break;
19624 }
19625 }
19626 // Is f_n a subface?
19627 tspivot(newfront, checksh);
19628 if (checksh.sh != dummysh) {
19629 // Temporarily remove checksh. Make it missing. recover it later.
19630 if (b->verbose > 2) {
19631 printf(" Queuing subface (%d, %d, %d).\n",
19632 pointmark(sorg(checksh)), pointmark(sdest(checksh)),
19633 pointmark(sapex(checksh)));
19634 }
19635 tsdissolve(newfront);
19636 tsdissolve(casingtet);
19637 // Detach tets at the both sides of checksh.
19638 stdissolve(checksh);
19639 sesymself(checksh);
19640 stdissolve(checksh);
19641 sinfect(checksh);
19642 missingshqueue->push(&checksh);
19643 }
19644 }
19645 enextself(misfront);
19646 }
19647 // C has been expanded at f. t becomes a cross tet.
19648 if (!infected(misfront)) {
19649 // t will be deleted, queue it.
19650 infect(misfront);
19651 crosstetlist->append(&misfront);
19652 }
19653 }
19654
19655 // Loop through misfrontlist, remove infected misfronts.
19656 for (i = 0; i < misfrontlist->len(); i++) {
19657 misfront = * (triface *)(* misfrontlist)[i];
19658 if (infected(misfront)) {
19659 // Remove f, keep original list order.
19660 misfrontlist->del(i, 1);
19661 i--;
19662 }
19663 }
19664
19665 // Are we done?
19666 if (misfrontlist->len() > 0) {
19667 // No. There are unexpandable fronts.
19668 // expandcavity_sos(misfrontlist);
19669 assert(0); // Not done yet.
19670 }
19671
19672 // D has been updated (by added new tets or dead tets) (due to flips).
19673 retrievenewtets(newtetlist);
19674
19675 // Restore global variables.
19676 dummytet[0] = encode(bakhulltet);
19677 hullsize = bakhullsize;
19678 checksubfaces = bakchksub;
19679 b->verbose++;
19680 }
19681
19682 ///////////////////////////////////////////////////////////////////////////////
19683 // //
19684 // carvecavity() Remove redundant (outside) tetrahedra from D. //
19685 // //
19686 // The fronts of C have been identified in D. Hence C can be tetrahedralized //
19687 // by removing the tets outside C. The CDT is then updated by filling C with //
19688 // the remaining tets (inside C) of D. //
19689 // //
19690 // Each front is protected by an auxilary subface s in D. s has a pointer to //
19691 // f (s.sh[0]). f can be used to classified the in- and out- tets of C (the //
19692 // CW orientation of f faces to the inside of C). The classified out-tets of //
19693 // C are marked (infected) for removing. //
19694 // //
19695 // Notice that the out-tets may not only the tets on the CH of C, but also //
19696 // tets completely inside D, eg., there is a "hole" in D. Such tets must be //
19697 // marked during classification. The hole tets are poped up and removed too. //
19698 // //
19699 ///////////////////////////////////////////////////////////////////////////////
19700
19701 void tetgenmesh::carvecavity(list* newtetlist, list* outtetlist,
19702 queue* flipque)
19703 {
19704 triface newtet, neightet, front, outtet;
19705 face auxsh, consh;
19706 point pointptr;
19707 REAL ori;
19708 int i;
19709
19710 // Clear work list.
19711 outtetlist->clear();
19712
19713 // Classify in- and out- tets in D. Mark and queue classified out-tets.
19714 for (i = 0; i < newtetlist->len(); i++) {
19715 // Get a new tet t.
19716 newtet = * (triface *)(* newtetlist)[i];
19717 assert(!isdead(&newtet));
19718 // Look for aux subfaces attached at t.
19719 for (newtet.loc = 0; newtet.loc < 4; newtet.loc++) {
19720 tspivot(newtet, auxsh);
19721 if (auxsh.sh != dummysh) {
19722 // Has this side a neighbor n?
19723 sym(newtet, neightet);
19724 if (neightet.tet != dummytet) {
19725 // Classify t and n (one is "in" and another is "out").
19726 // Get the front f.
19727 decode((tetrahedron) auxsh.sh[0], front);
19728 // Let f face to the inside of C.
19729 adjustedgering(front, CW);
19730 ori = orient3d(org(front), dest(front), apex(front), oppo(newtet));
19731 assert(ori != 0.0);
19732 if (ori < 0.0) {
19733 // t is in-tet. n is out-tet.
19734 outtet = neightet;
19735 } else {
19736 // n is in-tet. t is out-tet.
19737 outtet = newtet;
19738 }
19739 // Add the out-tet into list.
19740 if (!infected(outtet)) {
19741 infect(outtet);
19742 outtetlist->append(&outtet);
19743 }
19744 }
19745 }
19746 }
19747 }
19748
19749 // Find and mark all out-tets.
19750 for (i = 0; i < outtetlist->len(); i++) {
19751 outtet = * (triface *)(* outtetlist)[i];
19752 for (outtet.loc = 0; outtet.loc < 4; outtet.loc++) {
19753 sym(outtet, neightet);
19754 // Does the neighbor exist and unmarked?
19755 if ((neightet.tet != dummytet) && !infected(neightet)) {
19756 // Is it protected by an aux subface?
19757 tspivot(outtet, auxsh);
19758 if (auxsh.sh == dummysh) {
19759 // It's an out-tet.
19760 infect(neightet);
19761 outtetlist->append(&neightet);
19762 }
19763 }
19764 }
19765 }
19766
19767 // Remove the out- (and hole) tets.
19768 for (i = 0; i < outtetlist->len(); i++) {
19769 // Get an out-tet t.
19770 outtet = * (triface *)(* outtetlist)[i];
19771 // Detach t from the in-tets.
19772 for (outtet.loc = 0; outtet.loc < 4; outtet.loc++) {
19773 // Is there an aux subface s?
19774 tspivot(outtet, auxsh);
19775 if (auxsh.sh != dummysh) {
19776 // Get the neighbor n.
19777 sym(outtet, neightet);
19778 assert(!infected(neightet)); // t must be in-tet.
19779 // Detach n -x-> t.
19780 dissolve(neightet);
19781 }
19782 }
19783 // Dealloc the tet.
19784 tetrahedrondealloc(outtet.tet);
19785 }
19786
19787 // Connect the in-tets of C to fronts. Remove aux subfaces and fake tets.
19788 for (i = 0; i < newtetlist->len(); i++) {
19789 // Get a new tet t.
19790 newtet = * (triface *)(* newtetlist)[i];
19791 // t may be an out-tet and has got deleted.
19792 if (isdead(&newtet)) continue;
19793 // t is an in-tet. Look for aux subfaces attached at t.
19794 for (newtet.loc = 0; newtet.loc < 4; newtet.loc++) {
19795 // Is there an aux subface s?
19796 tspivot(newtet, auxsh);
19797 if (auxsh.sh != dummysh) {
19798 // Get the front f.
19799 decode((tetrahedron) auxsh.sh[0], front);
19800 assert((front.tet != dummytet) && !infected(front));
19801 // s has fulfilled its duty. Can be deleted.
19802 tsdissolve(newtet); // dissolve: t -x-> s.
19803 // Delete s.
19804 shellfacedealloc(subfaces, auxsh.sh);
19805 // Connect the newtet t and front f.
19806 // Is there a concrete subface c at f.
19807 tspivot(front, consh);
19808 if (consh.sh != dummysh) {
19809 sesymself(consh);
19810 // Bond: t <--> c.
19811 tsbond(newtet, consh);
19812 }
19813 // Does f hold by a fake tet.
19814 if (oppo(front) == (point) NULL) {
19815 // f is fake.
19816 if (consh.sh != dummysh) {
19817 sesymself(consh);
19818 // Dissolve: c -x-> f.
19819 stdissolve(consh);
19820 }
19821 // Dealloc f.
19822 tetrahedrondealloc(front.tet);
19823 // f becomes a hull. let 'dummytet' bond to it.
19824 dummytet[0] = encode(newtet);
19825 } else {
19826 // Bond t <--> f.
19827 bond(newtet, front);
19828 }
19829 // t may be non-locally Delaunay and flipable.
19830 if (flipque != (queue *) NULL) {
19831 enqueueflipface(newtet, flipque);
19832 }
19833 }
19834 }
19835 // Let the corners of t2 point to it for fast searching.
19836 pointptr = org(newtet);
19837 setpoint2tet(pointptr, encode(newtet));
19838 pointptr = dest(newtet);
19839 setpoint2tet(pointptr, encode(newtet));
19840 pointptr = apex(newtet);
19841 setpoint2tet(pointptr, encode(newtet));
19842 pointptr = oppo(newtet);
19843 setpoint2tet(pointptr, encode(newtet));
19844 }
19845 // The cavity has been re-tetrahedralized.
19846 }
19847
19848 ///////////////////////////////////////////////////////////////////////////////
19849 // //
19850 // delaunizecavity() Tetrahedralize a cavity by Delaunay tetrahedra. //
19851 // //
19852 // The cavity C is bounded by a set of triangles in 'floorlist' (a list of //
19853 // coplanar subfaces) and 'ceillist' (a list of tetrahedral faces lie above //
19854 // the subfaces). 'floorptlist' and 'ceilptlist' are the vertices of C. //
19855 // //
19856 ///////////////////////////////////////////////////////////////////////////////
19857
19858 void tetgenmesh::delaunizecavity(list* floorlist, list* ceillist,
19859 list* ceilptlist, list* floorptlist, list* frontlist, list* misfrontlist,
19860 list* newtetlist, list* crosstetlist, queue* missingshqueue, queue* flipque)
19861 {
19862 int vertnum;
19863
19864 vertnum = floorptlist->len();
19865 vertnum += (ceilptlist != (list *) NULL ? ceilptlist->len() : 0);
19866 if (b->verbose > 1) {
19867 printf(" Delaunizing cavity (%d floors, %d ceilings, %d vertices).\n",
19868 floorlist->len(), ceillist->len(), vertnum);
19869 }
19870 // Save the size of the largest cavity.
19871 if ((floorlist->len() + ceillist->len()) > maxcavfaces) {
19872 maxcavfaces = floorlist->len() + ceillist->len();
19873 }
19874 if (vertnum > maxcavverts) {
19875 maxcavverts = vertnum;
19876 }
19877
19878 // Clear these lists.
19879 frontlist->clear();
19880 misfrontlist->clear();
19881 newtetlist->clear();
19882
19883 // Initialize the cavity C.
19884 initializecavity(floorlist, ceillist, frontlist);
19885 // Form the D of the vertices of C.
19886 delaunizecavvertices(NULL, floorptlist, ceilptlist, newtetlist, flipque);
19887 // Identify faces of C in D.
19888 while (!identifyfronts(frontlist, misfrontlist, newtetlist)) {
19889 // Remove protecting subfaces, keep new tets.
19890 detachauxsubfaces(newtetlist);
19891 // Expand C and updateing D.
19892 expandcavity(frontlist, misfrontlist, newtetlist, crosstetlist,
19893 missingshqueue, flipque);
19894 }
19895 // All fronts have identified in D. Get the shape of C by removing out
19896 // tets of C. 'misfrontlist' is reused for removing out tets.
19897 carvecavity(newtetlist, misfrontlist, NULL);
19898 }
19899
19900 ///////////////////////////////////////////////////////////////////////////////
19901 // //
19902 // formmissingregion() Form the missing region. //
19903 // //
19904 // 'missingsh' is a missing subface. Start from it we can form the missing //
19905 // region R (a set of connected missing subfaces). Because all missing sub- //
19906 // faces have been marked (infected) before. R can be formed by checking the //
19907 // neighbors of 'missingsh', and the neighbors of the neighbors, and so on. //
19908 // Stop checking further at either a segment or an unmarked subface. //
19909 // //
19910 // 'missingshlist' returns R. The edge ring of subfaces of R are oriented in //
19911 // the same direction. 'equatptlist' returns the vertices of R, each vertex //
19912 // is marked with '1' (in 'worklist'). //
19913 // //
19914 ///////////////////////////////////////////////////////////////////////////////
19915
19916 void tetgenmesh::formmissingregion(face* missingsh, list* missingshlist,
19917 list* equatptlist, int* worklist)
19918 {
19919 face neighsh, worksh, workseg;
19920 point workpt[3];
19921 int idx, i, j;
19922
19923 // Add 'missingsh' into 'missingshlist'.
19924 missingshlist->append(missingsh);
19925 // Save and mark its three vertices.
19926 workpt[0] = sorg(*missingsh);
19927 workpt[1] = sdest(*missingsh);
19928 workpt[2] = sapex(*missingsh);
19929 for (i = 0; i < 3; i++) {
19930 idx = pointmark(workpt[i]) - in->firstnumber;
19931 worklist[idx] = 1;
19932 equatptlist->append(&workpt[i]);
19933 }
19934 // Temporarily uninfect it (avoid to save it again).
19935 suninfect(*missingsh);
19936
19937 // Find the other missing subfaces.
19938 for (i = 0; i < missingshlist->len(); i++) {
19939 // Get a missing subface.
19940 worksh = * (face *)(* missingshlist)[i];
19941 // Check three neighbors of this face.
19942 for (j = 0; j < 3; j++) {
19943 sspivot(worksh, workseg);
19944 if (workseg.sh == dummysh) {
19945 spivot(worksh, neighsh);
19946 if (sinfected(neighsh)) {
19947 // Find a missing subface, adjust the face orientation.
19948 if (sorg(neighsh) != sdest(worksh)) {
19949 sesymself(neighsh);
19950 }
19951 if (b->verbose > 2) {
19952 printf(" Add missing subface (%d, %d, %d).\n",
19953 pointmark(sorg(neighsh)), pointmark(sdest(neighsh)),
19954 pointmark(sapex(neighsh)));
19955 }
19956 missingshlist->append(&neighsh);
19957 // Save and mark its apex.
19958 workpt[0] = sapex(neighsh);
19959 idx = pointmark(workpt[0]) - in->firstnumber;
19960 // Has workpt[0] been added?
19961 if (worklist[idx] == 0) {
19962 worklist[idx] = 1;
19963 equatptlist->append(&workpt[0]);
19964 }
19965 // Temporarily uninfect it (avoid to save it again).
19966 suninfect(neighsh);
19967 }
19968 }
19969 senextself(worksh);
19970 }
19971 }
19972
19973 // R has been formed. Infect missing subfaces again.
19974 for (i = 0; i < missingshlist->len(); i++) {
19975 worksh = * (face *)(* missingshlist)[i];
19976 sinfect(worksh);
19977 }
19978 }
19979
19980 ///////////////////////////////////////////////////////////////////////////////
19981 // //
19982 // rearrangesubfaces() Rearrange the set of subfaces of a missing region //
19983 // so that they conform to the faces of DT. //
19984 // //
19985 // The missing region formed by subfaces of 'missingshlist' contains a set //
19986 // of degenerate vertices, hence the set of subfaces don't match the set of //
19987 // faces in DT. Instead of forcing them to present in DT, we re-arrange the //
19988 // connection of them so that the new subfaces conform to the faces of DT. //
19989 // 'boundedgelist' is a set of boundary edges of the region, these edges(may //
19990 // be subsegments) must exist in DT. //
19991 // //
19992 // On completion, we have created and inserted a set of new subfaces which //
19993 // conform to faces of DT. The set of old subfaces in 'missingshlist' are //
19994 // deleted. The region vertices in 'equatptlist' are unmarked. //
19995 // //
19996 ///////////////////////////////////////////////////////////////////////////////
19997
19998 void tetgenmesh::rearrangesubfaces(list* missingshlist, list* boundedgelist,
19999 list* equatptlist, int* worklist)
20000 {
20001 link *boundedgelink;
20002 link *newshlink;
20003 triface starttet, spintet, neightet, worktet;
20004 face shloop, newsh, neighsh, spinsh, worksh;
20005 face workseg, casingin, casingout;
20006 point torg, tdest, workpt;
20007 point spt1, spt2, spt3;
20008 enum finddirectionresult collinear;
20009 enum shestype shtype;
20010 REAL area;
20011 bool matchflag, finishflag;
20012 int shmark, pbcgp, idx, hitbdry;
20013 int i, j;
20014
20015 // Initialize the boundary edge link.
20016 boundedgelink = new link(sizeof(face), NULL, 256);
20017 // Initialize the new subface link.
20018 newshlink = new link(sizeof(face), NULL, 256);
20019 // Remember the type (skinny or not) of replaced subfaces. They should
20020 // all have the same type since there is no segment inside the region.
20021 worksh = * (face *)(* missingshlist)[0];
20022 shtype = shelltype(worksh);
20023 // The following loop is only for checking purpose.
20024 for (i = 1; i < missingshlist->len(); i++) {
20025 worksh = * (face *)(* missingshlist)[i];
20026 assert(shelltype(worksh) == shtype);
20027 }
20028 // To avoid compilation warnings.
20029 shmark = pbcgp = 0;
20030 area = 0.0;
20031
20032 // Create an initial boundary link.
20033 for (i = 0; i < boundedgelist->len(); i++) {
20034 shloop = * (face *)(* boundedgelist)[i];
20035 if (i == 0) {
20036 // 'shmark' will be set to all new created subfaces.
20037 shmark = shellmark(shloop);
20038 if (b->quality && varconstraint) {
20039 // area will be copied to all new created subfaces.
20040 area = areabound(shloop);
20041 }
20042 if (checkpbcs) {
20043 // pbcgp will be copied to all new created subfaces.
20044 pbcgp = shellpbcgroup(shloop);
20045 }
20046 // Get the abovepoint of this facet.
20047 abovepoint = facetabovepointarray[shellmark(shloop)];
20048 if (abovepoint == (point) NULL) {
20049 getfacetabovepoint(&shloop);
20050 }
20051 }
20052 sspivot(shloop, workseg);
20053 if (workseg.sh == dummysh) {
20054 // This edge is an interior edge.
20055 spivot(shloop, neighsh);
20056 boundedgelink->add(&neighsh);
20057 } else {
20058 // This side has a segment, the edge exists.
20059 boundedgelink->add(&shloop);
20060 }
20061 }
20062
20063 // Each edge ab of boundedgelink will be finished by finding a vertex c
20064 // which is a vertex of the missing region, such that:
20065 // (1) abc is inside the missing region, i.e., abc intersects at least
20066 // one of missing subfaces (saved in missingshlist);
20067 // (2) abc is not intersect with any previously created new subfaces
20068 // in the missing region (saved in newshlink).
20069 // After abc is created, it will be inserted into both the surface mesh
20070 // and the DT. The boundedgelink will be updated, ab is removed, bc and
20071 // ca will be added if they are open.
20072
20073 while (boundedgelink->len() > 0) {
20074 // Remove an edge (ab) from the link.
20075 shloop = * (face *) boundedgelink->del(1);
20076 // 'workseg' indicates it is a segment or not.
20077 sspivot(shloop, workseg);
20078 torg = sorg(shloop); // torg = a;
20079 tdest = sdest(shloop); // tdest = b;
20080 // Find a tetrahedron containing ab.
20081 getsearchtet(torg, tdest, &starttet, &workpt);
20082 collinear = finddirection(&starttet, workpt, tetrahedrons->items);
20083 if (collinear == LEFTCOLLINEAR) {
20084 enext2self(starttet);
20085 esymself(starttet);
20086 } else if (collinear == TOPCOLLINEAR) {
20087 fnextself(starttet);
20088 enext2self(starttet);
20089 esymself(starttet);
20090 }
20091 assert(dest(starttet) == workpt);
20092 // Checking faces around ab until a valid face is found.
20093 matchflag = false;
20094 spintet = starttet;
20095 hitbdry = 0;
20096 do {
20097 workpt = apex(spintet);
20098 idx = pointmark(workpt) - in->firstnumber;
20099 if (worklist[idx] == 1) {
20100 // (trog, tdest, workpt) is on the facet. Check if it satisfies (1).
20101 finishflag = false;
20102 for (i = 0; i < missingshlist->len(); i++) {
20103 worksh = * (face *)(* missingshlist)[i];
20104 spt1 = sorg(worksh);
20105 spt2 = sdest(worksh);
20106 spt3 = sapex(worksh);
20107 // Does bc intersect the face?
20108 if (tri_edge_cop_inter(spt1, spt2, spt3, tdest, workpt, abovepoint)
20109 == INTERSECT) {
20110 finishflag = true; break;
20111 }
20112 // Does ca intersect the face?
20113 if (tri_edge_cop_inter(spt1, spt2, spt3, workpt, torg, abovepoint)
20114 == INTERSECT) {
20115 finishflag = true; break;
20116 }
20117 // Does c inside the face?
20118 if (tri_vert_cop_inter(spt1, spt2, spt3, workpt, abovepoint)
20119 == INTERSECT) {
20120 finishflag = true; break;
20121 }
20122 }
20123 if (finishflag) {
20124 // Satisfying (1). Check if it satisfies (2).
20125 matchflag = true;
20126 for (i = 0; i < newshlink->len() && matchflag; i++) {
20127 worksh = * (face *) newshlink->getnitem(i + 1);
20128 spt1 = sorg(worksh);
20129 spt2 = sdest(worksh);
20130 spt3 = sapex(worksh);
20131 // Does bc intersect the face?
20132 if (tri_edge_cop_inter(spt1, spt2, spt3, tdest, workpt, abovepoint)
20133 == INTERSECT) {
20134 matchflag = false; break;
20135 }
20136 // Does ca intersect the face?
20137 if (tri_edge_cop_inter(spt1, spt2, spt3, workpt, torg, abovepoint)
20138 == INTERSECT) {
20139 matchflag = false; break;
20140 }
20141 // Does c inside the face?
20142 if (tri_vert_cop_inter(spt1, spt2, spt3, workpt, abovepoint)
20143 == INTERSECT) {
20144 matchflag = false; break;
20145 }
20146 }
20147 }
20148 if (matchflag == true) {
20149 // Satisfying both (1) and (2). Find abc.
20150 break;
20151 }
20152 }
20153 if (!fnextself(spintet)) {
20154 hitbdry ++;
20155 if (hitbdry < 2) {
20156 esym(starttet, spintet);
20157 if (!fnextself(spintet)) {
20158 hitbdry ++;
20159 }
20160 }
20161 }
20162 } while (hitbdry < 2 && apex(spintet) != apex(starttet));
20163 assert(matchflag == true);
20164 tspivot(spintet, neighsh);
20165 if (neighsh.sh != dummysh) {
20166 printf("Error: Invalid PLC.\n");
20167 printf(" Facet #%d and facet #%d overlap each other.\n",
20168 shellmark(neighsh), shellmark(shloop));
20169 printf(" It might be caused by a facet is defined more than once.\n");
20170 printf(" Hint: Use -d switch to find all overlapping facets.\n");
20171 exit(1);
20172 }
20173 // The side of 'spintet' is at which a new subface will be attached.
20174 adjustedgering(spintet, CCW);
20175 // Create the new subface.
20176 makeshellface(subfaces, &newsh);
20177 setsorg(newsh, org(spintet));
20178 setsdest(newsh, dest(spintet));
20179 setsapex(newsh, apex(spintet));
20180 if (b->quality && varconstraint) {
20181 setareabound(newsh, area);
20182 }
20183 if (checkpbcs) {
20184 setshellpbcgroup(newsh, pbcgp);
20185 }
20186 setshellmark(newsh, shmark);
20187 setshelltype(newsh, shtype); // It may be a skinny subface.
20188 // Add newsh into newshlink for intersecting checking.
20189 newshlink->add(&newsh);
20190 // Insert it into the current mesh.
20191 tsbond(spintet, newsh);
20192 sym(spintet, neightet);
20193 if (neightet.tet != dummytet) {
20194 sesym(newsh, neighsh);
20195 tsbond(neightet, neighsh);
20196 }
20197 // Insert it into the surface mesh.
20198 sspivot(shloop, workseg);
20199 if (workseg.sh == dummysh) {
20200 sbond(shloop, newsh);
20201 } else {
20202 // There is a subsegment, 'shloop' is the subface which is going to
20203 // die. Insert the 'newsh' at the place of 'shloop' into its face
20204 // link, so as to dettach 'shloop'. The original connection is:
20205 // -> casingin -> shloop -> casingout ->, it will be changed with:
20206 // -> casingin -> newsh -> casingout ->. Pay attention to the
20207 // case when this subsegment is dangling in the mesh, i.e., 'shloop'
20208 // is bonded to itself.
20209 spivot(shloop, casingout);
20210 if (shloop.sh != casingout.sh) {
20211 // 'shloop' is not bonded to itself.
20212 spinsh = casingout;
20213 do {
20214 casingin = spinsh;
20215 spivotself(spinsh);
20216 } while (sapex(spinsh) != sapex(shloop));
20217 assert(casingin.sh != shloop.sh);
20218 // Bond casingin -> newsh -> casingout.
20219 sbond1(casingin, newsh);
20220 sbond1(newsh, casingout);
20221 } else {
20222 // Bond newsh -> newsh.
20223 sbond(newsh, newsh);
20224 }
20225 // Bond the segment.
20226 ssbond(newsh, workseg);
20227 }
20228 // Check other two sides of this new subface. If a side is not bonded
20229 // to any edge in the link, it will be added to the link.
20230 for (i = 0; i < 2; i++) {
20231 if (i == 0) {
20232 senext(newsh, worksh);
20233 } else {
20234 senext2(newsh, worksh);
20235 }
20236 torg = sorg(worksh);
20237 tdest = sdest(worksh);
20238 finishflag = false;
20239 for (j = 0; j < boundedgelink->len() && !finishflag; j++) {
20240 neighsh = * (face *) boundedgelink->getnitem(j + 1);
20241 if ((sorg(neighsh) == torg && sdest(neighsh) == tdest) ||
20242 (sorg(neighsh) == tdest && sdest(neighsh) == torg)) {
20243 // Find a boundary edge. Bond them and exit the loop.
20244 sspivot(neighsh, workseg);
20245 if (workseg.sh == dummysh) {
20246 sbond(neighsh, worksh);
20247 } else {
20248 // There is a subsegment, 'neighsh' is the subface which is
20249 // going to die. Do the same as above for 'worksh'.
20250 spivot(neighsh, casingout);
20251 if (neighsh.sh != casingout.sh) {
20252 // 'neighsh' is not bonded to itself.
20253 spinsh = casingout;
20254 do {
20255 casingin = spinsh;
20256 spivotself(spinsh);
20257 } while (sapex(spinsh) != sapex(neighsh));
20258 assert(casingin.sh != neighsh.sh);
20259 // Bond casingin -> worksh -> casingout.
20260 sbond1(casingin, worksh);
20261 sbond1(worksh, casingout);
20262 } else {
20263 // Bond worksh -> worksh.
20264 sbond(worksh, worksh);
20265 }
20266 // Bond the segment.
20267 ssbond(worksh, workseg);
20268 }
20269 // Remove this boundary edge from the link.
20270 boundedgelink->del(j + 1);
20271 finishflag = true;
20272 }
20273 }
20274 if (!finishflag) {
20275 // It's a new boundary edge, add it to link.
20276 boundedgelink->add(&worksh);
20277 }
20278 }
20279 }
20280
20281 // Deallocate the set of old missing subfaces.
20282 for (i = 0; i < missingshlist->len(); i++) {
20283 worksh = * (face *)(* missingshlist)[i];
20284 shellfacedealloc(subfaces, worksh.sh);
20285 }
20286 // Unmark region vertices in 'worklist'.
20287 for (i = 0; i < equatptlist->len(); i++) {
20288 workpt = * (point *)(* equatptlist)[i];
20289 idx = pointmark(workpt) - in->firstnumber;
20290 worklist[idx] = 0;
20291 }
20292
20293 delete boundedgelink;
20294 delete newshlink;
20295 }
20296
20297 ///////////////////////////////////////////////////////////////////////////////
20298 // //
20299 // scoutcrossingedge() Search an edge crossing the missing region. //
20300 // //
20301 // 'missingshlist' forms the missing region R. This routine searches for an //
20302 // edge crossing R. It first forms a 'boundedgelist' consisting of the //
20303 // boundary edges of R. Such edges are existing in CDT. A crossing edge is //
20304 // found by rotating faces around one of the boundary edges. It is possible //
20305 // there is no edge crosses R (e.g. R has a degenerate point set). //
20306 // //
20307 // If find a croosing edge, return TRUE, 'crossedgelist' contains this edge. //
20308 // Otherwise, return FALSE. //
20309 // //
20310 ///////////////////////////////////////////////////////////////////////////////
20311
20312 bool tetgenmesh::scoutcrossingedge(list* missingshlist, list* boundedgelist,
20313 list* crossedgelist, int* worklist)
20314 {
20315 triface starttet, spintet, worktet;
20316 face startsh, neighsh, worksh, workseg;
20317 point torg, tdest, tapex;
20318 point workpt[3], pa, pb, pc;
20319 enum finddirectionresult collinear;
20320 REAL ori1, ori2;
20321 bool crossflag;
20322 int hitbdry;
20323 int i, j, k;
20324
20325 // Form the 'boundedgelist'. Loop through 'missingshlist', check each
20326 // edge of these subfaces. If an edge is a segment or the neighbor
20327 // subface is uninfected, add it to 'boundedgelist'.
20328 for (i = 0; i < missingshlist->len(); i++) {
20329 worksh = * (face *)(* missingshlist)[i];
20330 for (j = 0; j < 3; j++) {
20331 sspivot(worksh, workseg);
20332 if (workseg.sh == dummysh) {
20333 spivot(worksh, neighsh);
20334 if (!sinfected(neighsh)) {
20335 boundedgelist->append(&worksh);
20336 }
20337 } else {
20338 boundedgelist->append(&worksh);
20339 }
20340 senextself(worksh);
20341 }
20342 }
20343
20344 crossflag = false;
20345 // Find a crossing edge. It is possible there is no such edge. We need to
20346 // loop through all edges of 'boundedgelist' for sure we don't miss any.
20347 for (i = 0; i < boundedgelist->len() && !crossflag; i++) {
20348 startsh = * (face *)(* boundedgelist)[i];
20349 // 'startsh' (abc) holds an existing edge of the DT, find it.
20350 torg = sorg(startsh);
20351 tdest = sdest(startsh);
20352 tapex = sapex(startsh);
20353 getsearchtet(torg, tdest, &starttet, &workpt[0]);
20354 collinear = finddirection(&starttet, workpt[0], tetrahedrons->items);
20355 if (collinear == LEFTCOLLINEAR) {
20356 enext2self(starttet);
20357 esymself(starttet);
20358 } else if (collinear == TOPCOLLINEAR) {
20359 fnextself(starttet);
20360 enext2self(starttet);
20361 esymself(starttet);
20362 }
20363 #ifdef SELF_CHECK
20364 assert(dest(starttet) == workpt[0]);
20365 #endif
20366 // Now starttet holds edge ab. Find is edge de crossing R.
20367 spintet = starttet;
20368 hitbdry = 0;
20369 do {
20370 if (fnextself(spintet)) {
20371 // splittet = abde. Check if de crosses abc.
20372 workpt[1] = apex(spintet); // workpt[1] = d.
20373 workpt[2] = oppo(spintet); // workpt[2] = e.
20374 j = pointmark(workpt[1]) - in->firstnumber;
20375 k = pointmark(workpt[2]) - in->firstnumber;
20376 if (worklist[j] == 1) {
20377 ori1 = 0.0; // d is a vertex of the missing region.
20378 } else {
20379 // Get the orientation of d wrt. abc.
20380 ori1 = orient3d(torg, tdest, tapex, workpt[1]);
20381 }
20382 if (worklist[k] == 1) {
20383 ori2 = 0.0; // e is a vertex of the missing region.
20384 } else {
20385 // Get the orientation of e wrt. abc.
20386 ori2 = orient3d(torg, tdest, tapex, workpt[2]);
20387 }
20388 // Only do check if d and e locate on different sides of abc.
20389 if (ori1 * ori2 < 0.0) {
20390 // Check if de crosses any subface of R.
20391 for (j = 0; j < missingshlist->len(); j++) {
20392 worksh = * (face *)(* missingshlist)[j];
20393 pa = sorg(worksh);
20394 pb = sdest(worksh);
20395 pc = sapex(worksh);
20396 crossflag = (tri_tri_inter(pa, pb, pc, workpt[0], workpt[1],
20397 workpt[2]) == INTERSECT);
20398 if (crossflag) {
20399 // Find a crossing edge. We're done.
20400 worktet = spintet;
20401 adjustedgering(worktet, CCW);
20402 enextfnextself(worktet);
20403 enextself(worktet);
20404 // Add this edge (worktet) into 'crossedgelist'.
20405 crossedgelist->append(&worktet);
20406 break;
20407 }
20408 }
20409 if (crossflag) break;
20410 }
20411 if (apex(spintet) == apex(starttet)) break;
20412 } else {
20413 hitbdry++;
20414 // It is only possible to hit boundary once.
20415 if (hitbdry < 2) {
20416 esym(starttet, spintet);
20417 }
20418 }
20419 } while (hitbdry < 2);
20420 }
20421
20422 return crossflag;
20423 }
20424
20425 ///////////////////////////////////////////////////////////////////////////////
20426 // //
20427 // formcavity() Form the cavity for recovering the missing region. //
20428 // //
20429 // The cavity C is bounded by faces of current CDT. All tetrahedra inside C //
20430 // will be removed, intead a set of constrained Delaunay tetrahedra will be //
20431 // filled in and the missing region are recovered. //
20432 // //
20433 // 'missingshlist' contains a set of subfaces forming the missing region R. //
20434 // C is formed by first finding all the tetrahedra in CDT that intersect the //
20435 // relative interior of R; then deleting them from the CDT, this will form C //
20436 // inside the CDT. At the beginning, 'crossedgelist' contains an edge which //
20437 // is crossing R. All tets containing this edge must cross R. Start from it, //
20438 // other crossing edges can be found incrementally. The discovered crossing //
20439 // tets are saved in 'crosstetlist'. //
20440 // //
20441 // Notice that not all tets in 'crosstetlist' are crossing R. The discovered //
20442 // tets are connected each other. However, there may be other tets crossing //
20443 // R but disjoint with the found tets. Due to this fact we need to check the //
20444 // 'missingshlist' once more. Only recover those subfaces which are crossed //
20445 // by the set of discovered tets, i.e., R may be shrinked to conform the set //
20446 // of discovered tets. The extra subfaces of R will be recovered later. //
20447 // //
20448 // Notice that some previous recovered subfaces may completely included in C.//
20449 // This can happen when R is very big and these subfaces lie above R and so //
20450 // close to it. Such subfaces have to be queued (and sinfected()) to recover //
20451 // them later. Otherwise, we lost the connection to these subfaces forever. //
20452 // //
20453 ///////////////////////////////////////////////////////////////////////////////
20454
20455 void tetgenmesh::formcavity(list* missingshlist, list* crossedgelist,
20456 list* equatptlist, list* crossshlist, list* crosstetlist,
20457 list* belowfacelist, list* abovefacelist, list* horizptlist,
20458 list* belowptlist, list* aboveptlist, queue* missingshqueue, int* worklist)
20459 {
20460 triface starttet, spintet, neightet, worktet;
20461 face startsh, neighsh, worksh, workseg;
20462 point torg, tdest, tapex, workpt[3];
20463 REAL checksign, orgori, destori;
20464 bool crossflag, inlistflag;
20465 bool belowflag, aboveflag;
20466 int idx, share;
20467 int i, j, k;
20468
20469 // Get a face at horizon.
20470 startsh = * (face *)(* missingshlist)[0];
20471 torg = sorg(startsh);
20472 tdest = sdest(startsh);
20473 tapex = sapex(startsh);
20474
20475 // Collect the set of crossing tetrahedra by rotating crossing edges.
20476 for (i = 0; i < crossedgelist->len(); i++) {
20477 // Get a tet abcd, ab is a crossing edge.
20478 starttet = * (triface *)(* crossedgelist)[i];
20479 adjustedgering(starttet, CCW);
20480 if (b->verbose > 2) {
20481 printf(" Collect tets containing edge (%d, %d).\n",
20482 pointmark(org(starttet)), pointmark(dest(starttet)));
20483 }
20484 orgori = orient3d(torg, tdest, tapex, org(starttet));
20485 destori = orient3d(torg, tdest, tapex, dest(starttet));
20486 #ifdef SELF_CHECK
20487 assert(orgori * destori < 0.0);
20488 #endif
20489 spintet = starttet;
20490 do {
20491 // The face rotation should not meet boundary.
20492 fnextself(spintet);
20493 // Check the validity of the PLC.
20494 tspivot(spintet, worksh);
20495 if (worksh.sh != dummysh) {
20496 printf("Error: Invalid PLC.\n");
20497 printf(" Two subfaces (%d, %d, %d) and (%d, %d, %d)\n",
20498 pointmark(torg), pointmark(tdest), pointmark(tapex),
20499 pointmark(sorg(worksh)), pointmark(sdest(worksh)),
20500 pointmark(sapex(worksh)));
20501 printf(" are found intersecting each other.\n");
20502 printf(" Hint: Use -d switch to find all intersecting facets.\n");
20503 terminatetetgen(1);
20504 }
20505 if (!infected(spintet)) {
20506 if (b->verbose > 2) {
20507 printf(" Add crossing tet (%d, %d, %d, %d).\n",
20508 pointmark(org(spintet)), pointmark(dest(spintet)),
20509 pointmark(apex(spintet)), pointmark(oppo(spintet)));
20510 }
20511 infect(spintet);
20512 crosstetlist->append(&spintet);
20513 }
20514 // Check whether other two edges of 'spintet' is a crossing edge.
20515 // It can be quickly checked from the apex of 'spintet', if it is
20516 // not on the facet, then there exists a crossing edge.
20517 workpt[0] = apex(spintet);
20518 idx = pointmark(workpt[0]) - in->firstnumber;
20519 if (worklist[idx] != 1) {
20520 // Either edge (dest, apex) or edge (apex, org) crosses.
20521 checksign = orient3d(torg, tdest, tapex, workpt[0]);
20522 #ifdef SELF_CHECK
20523 assert(checksign != 0.0);
20524 #endif
20525 if (checksign * orgori < 0.0) {
20526 enext2(spintet, worktet); // edge (apex, org).
20527 workpt[1] = org(spintet);
20528 } else {
20529 #ifdef SELF_CHECK
20530 assert(checksign * destori < 0.0);
20531 #endif
20532 enext(spintet, worktet); // edge (dest, apex).
20533 workpt[1] = dest(spintet);
20534 }
20535 // 'worktet' represents the crossing edge. Add it into list only
20536 // it doesn't exist in 'crossedgelist'.
20537 inlistflag = false;
20538 for (j = 0; j < crossedgelist->len() && !inlistflag; j++) {
20539 neightet = * (triface *)(* crossedgelist)[j];
20540 if (org(neightet) == workpt[0]) {
20541 if (dest(neightet) == workpt[1]) inlistflag = true;
20542 } else if (org(neightet) == workpt[1]) {
20543 if (dest(neightet) == workpt[0]) inlistflag = true;
20544 }
20545 }
20546 if (!inlistflag) {
20547 crossedgelist->append(&worktet);
20548 }
20549 }
20550 } while (apex(spintet) != apex(starttet));
20551 }
20552
20553 // Identifying the boundary faces and vertices of C. Sort them into
20554 // 'abovefacelist', 'aboveptlist, 'belowfacelist', and 'belowptlist',
20555 // respectively. "above" and "below" are wrt.(torg, tdest, tapex).
20556 for (i = 0; i < crosstetlist->len(); i++) {
20557 // Get a tet abcd, ab is the crossing edge.
20558 starttet = * (triface *)(* crosstetlist)[i];
20559 #ifdef SELF_CHECK
20560 assert(infected(starttet));
20561 #endif
20562 adjustedgering(starttet, CCW);
20563 // abc and abd are sharing the crossing edge, the two neighbors must
20564 // be crossing tetrahedra too. They can't be boundaries of C.
20565 for (j = 0; j < 2; j++) {
20566 if (j == 0) {
20567 enextfnext(starttet, worktet); // Check bcd.
20568 } else {
20569 enext2fnext(starttet, worktet); // Check acd.
20570 }
20571 sym(worktet, neightet);
20572 // If the neighbor doesn't exist or exists but doesn't be infected,
20573 // it's a boundary face of C, save it.
20574 if ((neightet.tet == dummytet) || !infected(neightet)) {
20575 workpt[0] = org(worktet);
20576 workpt[1] = dest(worktet);
20577 workpt[2] = apex(worktet);
20578 belowflag = aboveflag = false;
20579 share = 0;
20580 for (k = 0; k < 3; k++) {
20581 idx = pointmark(workpt[k]) - in->firstnumber;
20582 if (worklist[idx] == 0) {
20583 // It's not a vertices of facet, find which side it lies.
20584 checksign = orient3d(torg, tdest, tapex, workpt[k]);
20585 #ifdef SELF_CHECK
20586 assert(checksign != 0.0);
20587 #endif
20588 if (checksign > 0.0) {
20589 // It lies "below" the facet wrt. 'startsh'.
20590 worklist[idx] = 2;
20591 belowptlist->append(&workpt[k]);
20592 } else if (checksign < 0.0) {
20593 // It lies "above" the facet wrt. 'startsh'.
20594 worklist[idx] = 3;
20595 aboveptlist->append(&workpt[k]);
20596 }
20597 }
20598 if (worklist[idx] == 2) {
20599 // This face lies "below" the facet wrt. 'startsh'.
20600 belowflag = true;
20601 } else if (worklist[idx] == 3) {
20602 // This face lies "above" the facet wrt. 'startsh'.
20603 aboveflag = true;
20604 } else {
20605 #ifdef SELF_CHECK
20606 // In degenerate case, this face may just be the equator.
20607 assert(worklist[idx] == 1);
20608 #endif
20609 share++;
20610 }
20611 }
20612 #ifdef SELF_CHECK
20613 // The degenerate case has been ruled out.
20614 assert(share < 3);
20615 // Only one flag is possible for a cavity face.
20616 assert(belowflag ^ aboveflag);
20617 #endif
20618 if (belowflag) {
20619 belowfacelist->append(&worktet);
20620 } else if (aboveflag) {
20621 abovefacelist->append(&worktet);
20622 }
20623 }
20624 }
20625 }
20626
20627 // Shrink R if not all its subfaces are crossing by the discovered tets.
20628 // 'crossshlist' and 'horizptlist' represent the set of subfaces and
20629 // vertices of the shrinked missing region, respectively.
20630 for (i = 0; i < missingshlist->len(); i++) {
20631 worksh = * (face *)(* missingshlist)[i];
20632 #ifdef SELF_CHECK
20633 assert(sinfected(worksh));
20634 #endif
20635 workpt[0] = sorg(worksh);
20636 workpt[1] = sdest(worksh);
20637 workpt[2] = sapex(worksh);
20638 crossflag = false;
20639 for (j = 0; j < crosstetlist->len() && !crossflag; j++) {
20640 // Get a tet abcd, ab is a crossing edge.
20641 starttet = * (triface *)(* crosstetlist)[j];
20642 adjustedgering(starttet, CCW);
20643 // Only need to check two sides of worktet.
20644 for (k = 0; k < 2 && !crossflag; k++) {
20645 if (k == 0) {
20646 worktet = starttet; // Check abc.
20647 } else {
20648 fnext(starttet, worktet); // Check abd.
20649 }
20650 crossflag = tritritest(&worktet, workpt[0], workpt[1], workpt[2]);
20651 }
20652 }
20653 if (crossflag) {
20654 // 'worksh' is crossed by 'worktet', uninfect it.
20655 suninfect(worksh);
20656 crossshlist->append(&worksh);
20657 // Add its corners into 'horizptlist'.
20658 for (k = 0; k < 3; k++) {
20659 idx = pointmark(workpt[k]) - in->firstnumber;
20660 if (worklist[idx] != 4) {
20661 worklist[idx] = 4;
20662 horizptlist->append(&workpt[k]);
20663 }
20664 }
20665 }
20666 }
20667
20668 // Check 'crossingtetlist'. Queue subfaces inside them.
20669 for (i = 0; i < crosstetlist->len(); i++) {
20670 starttet = * (triface *)(* crosstetlist)[i];
20671 for (starttet.loc = 0; starttet.loc < 4; starttet.loc++) {
20672 sym(starttet, neightet);
20673 // If the neighbor exist and is infected, check it.
20674 if ((neightet.tet != dummytet) && infected(neightet)) {
20675 tspivot(starttet, worksh);
20676 if (worksh.sh != dummysh) {
20677 // Temporarily remove worksh. Make it missing. recover it later.
20678 if (b->verbose > 2) {
20679 printf(" Queuing subface (%d, %d, %d).\n",
20680 pointmark(sorg(worksh)), pointmark(sdest(worksh)),
20681 pointmark(sapex(worksh)));
20682 }
20683 tsdissolve(neightet);
20684 tsdissolve(starttet);
20685 // Detach tets at the both sides of this subface.
20686 stdissolve(worksh);
20687 sesymself(worksh);
20688 stdissolve(worksh);
20689 sinfect(worksh);
20690 missingshqueue->push(&worksh);
20691 }
20692 }
20693 }
20694 }
20695
20696 // Clear flags set in 'worklist'.
20697 for (i = 0; i < equatptlist->len(); i++) {
20698 workpt[0] = * (point *)(* equatptlist)[i];
20699 idx = pointmark(workpt[0]) - in->firstnumber;
20700 #ifdef SELF_CHECK
20701 assert((worklist[idx] == 1) || (worklist[idx] == 4));
20702 #endif
20703 worklist[idx] = 0;
20704 }
20705 for (i = 0; i < belowptlist->len(); i++) {
20706 workpt[0] = * (point *)(* belowptlist)[i];
20707 idx = pointmark(workpt[0]) - in->firstnumber;
20708 #ifdef SELF_CHECK
20709 assert(worklist[idx] == 2);
20710 #endif
20711 worklist[idx] = 0;
20712 }
20713 for (i = 0; i < aboveptlist->len(); i++) {
20714 workpt[0] = * (point *)(* aboveptlist)[i];
20715 idx = pointmark(workpt[0]) - in->firstnumber;
20716 #ifdef SELF_CHECK
20717 assert(worklist[idx] == 3);
20718 #endif
20719 worklist[idx] = 0;
20720 }
20721 }
20722
20723 ///////////////////////////////////////////////////////////////////////////////
20724 // //
20725 // insertallsubfaces() Insert all subfaces, queue missing subfaces. //
20726 // //
20727 // Loop through all subfaces, insert each into the DT. If one already exists,//
20728 // bond it to the tetrahedra having it. Otherwise, it is missing, infect it //
20729 // and save it in 'missingshqueue'. //
20730 // //
20731 ///////////////////////////////////////////////////////////////////////////////
20732
20733 void tetgenmesh::insertallsubfaces(queue* missingshqueue)
20734 {
20735 triface searchtet;
20736 face subloop;
20737
20738 searchtet.tet = (tetrahedron *) NULL;
20739 subfaces->traversalinit();
20740 subloop.sh = shellfacetraverse(subfaces);
20741 while (subloop.sh != (shellface *) NULL) {
20742 if (!insertsubface(&subloop, &searchtet)) {
20743 if (b->verbose > 1) {
20744 printf(" Queuing subface (%d, %d, %d).\n", pointmark(sorg(subloop)),
20745 pointmark(sdest(subloop)), pointmark(sapex(subloop)));
20746 }
20747 sinfect(subloop);
20748 missingshqueue->push(&subloop);
20749 }
20750 subloop.sh = shellfacetraverse(subfaces);
20751 }
20752 }
20753
20754 ///////////////////////////////////////////////////////////////////////////////
20755 // //
20756 // constrainedfacets() Recover subfaces in a Delaunay tetrahedralization. //
20757 // //
20758 // This routine creates a CDT by incrementally updating a DT D into a CDT T. //
20759 // The process of recovering facets can be imagined by "merging" the surface //
20760 // mesh F into D. At the beginning, F and D are completely seperated. Some //
20761 // faces of them are matching some are not because they are crossed by some //
20762 // tetrahedra of D. The non-matching subfaces will be forced to appear in T //
20763 // by locally retetrahedralizing the regions where F and D are intersecting. //
20764 // //
20765 // When a subface s of F is found missing in D, probably some other subfaces //
20766 // near to s are missing too. The set of adjoining coplanar missing faces //
20767 // forms a missing region R (R may not simply connected). //
20768 // //
20769 // There are two possibilities can result a mssing region R: (1) Some edges //
20770 // of D cross R; (2) No edge of D crosses R, but some faces of D spans R, ie,//
20771 // D is locally degenerate at R. In case (1), D is modified so that it resp- //
20772 // ects R (done by a cavity retetrahedralization algorithm). In case (2), F //
20773 // is modified so that the set of subfaces of R matches faces in D (done by //
20774 // a face rearrangment algorithm). //
20775 // //
20776 ///////////////////////////////////////////////////////////////////////////////
20777
20778 void tetgenmesh::constrainedfacets()
20779 {
20780 queue *missingshqueue, *flipque;
20781 list *missingshlist, *equatptlist;
20782 list *boundedgelist, *crossedgelist, *crosstetlist;
20783 list *crossshlist, *belowfacelist, *abovefacelist;
20784 list *horizptlist, *belowptlist, *aboveptlist;
20785 list *frontlist, *misfrontlist, *newtetlist;
20786 triface searchtet, worktet;
20787 face subloop, worksh;
20788 int *worklist;
20789 int i;
20790
20791 if (!b->quiet) {
20792 printf("Constraining facets.\n");
20793 }
20794
20795 // Initialize queues.
20796 missingshqueue = new queue(sizeof(face));
20797 flipque = new queue(sizeof(badface));
20798 // Initialize the working lists.
20799 missingshlist = new list(sizeof(face), NULL);
20800 boundedgelist = new list(sizeof(face), NULL);
20801 crossedgelist = new list(sizeof(triface), NULL);
20802 equatptlist = new list("point *");
20803 crossshlist = new list(sizeof(face), NULL);
20804 crosstetlist = new list(sizeof(triface), NULL);
20805 belowfacelist = new list(sizeof(triface), NULL);
20806 abovefacelist = new list(sizeof(triface), NULL);
20807 horizptlist = new list("point *");
20808 belowptlist = new list("point *");
20809 aboveptlist = new list("point *");
20810 frontlist = new list(sizeof(triface), NULL);
20811 misfrontlist = new list(sizeof(triface), NULL);
20812 newtetlist = new list(sizeof(triface), NULL);
20813 // Initialize the array for marking vertices.
20814 worklist = new int[points->items + 1];
20815 for (i = 0; i < points->items + 1; i++) worklist[i] = 0;
20816
20817 // Compute a mapping from points to tetrahedra for fast searching.
20818 makepoint2tetmap();
20819
20820 // Match subfaces in D, queue all missing subfaces.
20821 insertallsubfaces(missingshqueue);
20822
20823 // Recover all missing subfaces.
20824 while (!missingshqueue->empty()) {
20825 // Get a queued face s.
20826 subloop = * (face *) missingshqueue->pop();
20827 // s may have been deleted in a face rearrangment operation.
20828 if (isdead(&subloop)) continue;
20829 // s may have been recovered in a previous missing region.
20830 if (!sinfected(subloop)) continue;
20831 // s may match a face in D now due to previous transformations.
20832 if (insertsubface(&subloop, &searchtet)) {
20833 suninfect(subloop);
20834 continue;
20835 }
20836 if (b->verbose > 1) {
20837 printf(" Recover subface (%d, %d, %d).\n", pointmark(sorg(subloop)),
20838 pointmark(sdest(subloop)), pointmark(sapex(subloop)));
20839 }
20840 // Form the missing region R containing s.
20841 formmissingregion(&subloop, missingshlist, equatptlist, worklist);
20842 // Is R crossing by any tetrahedron?
20843 if (scoutcrossingedge(missingshlist, boundedgelist, crossedgelist,
20844 worklist)) {
20845 // Form the cavity C containing R.
20846 formcavity(missingshlist, crossedgelist, equatptlist, crossshlist,
20847 crosstetlist, belowfacelist, abovefacelist, horizptlist,
20848 belowptlist, aboveptlist, missingshqueue, worklist);
20849 // Recover the above part of C.
20850 delaunizecavity(crossshlist, abovefacelist, aboveptlist, horizptlist,
20851 frontlist, misfrontlist, newtetlist, crosstetlist,
20852 missingshqueue, flipque);
20853 // Inverse the direction of subfaces in R.
20854 for (i = 0; i < crossshlist->len(); i++) {
20855 worksh = * (face *)(* crossshlist)[i];
20856 sesymself(worksh);
20857 * (face *)(* crossshlist)[i] = worksh;
20858 }
20859 // Recover the below part of C.
20860 delaunizecavity(crossshlist, belowfacelist, belowptlist, horizptlist,
20861 frontlist, misfrontlist, newtetlist, crosstetlist,
20862 missingshqueue, flipque);
20863 // Delete tetrahedra in C.
20864 for (i = 0; i < crosstetlist->len(); i++) {
20865 worktet = * (triface *)(* crosstetlist)[i];
20866 tetrahedrondealloc(worktet.tet);
20867 }
20868 // There may have some un-recovered subfaces of R. Put them back into
20869 // queue. Otherwise, they will be missing on the boundary.
20870 for (i = 0; i < missingshlist->len(); i++) {
20871 worksh = * (face *)(* missingshlist)[i];
20872 if (sinfected(worksh)) {
20873 // An unrecovered subface, put it back into queue.
20874 missingshqueue->push(&worksh);
20875 }
20876 }
20877 crossshlist->clear();
20878 belowfacelist->clear();
20879 abovefacelist->clear();
20880 horizptlist->clear();
20881 belowptlist->clear();
20882 aboveptlist->clear();
20883 crosstetlist->clear();
20884 } else {
20885 // No. Rearrange subfaces of F conforming to that of D in R. It can
20886 // happen when the facet has non-coplanar vertices.
20887 rearrangesubfaces(missingshlist, boundedgelist, equatptlist, worklist);
20888 }
20889 // Clear all working lists.
20890 missingshlist->clear();
20891 boundedgelist->clear();
20892 crossedgelist->clear();
20893 equatptlist->clear();
20894 }
20895
20896 // Subfaces have been merged into D.
20897 checksubfaces = 1;
20898
20899 if (b->verbose > 0) {
20900 printf(" The biggest cavity: %d faces, %d vertices\n", maxcavfaces,
20901 maxcavverts);
20902 printf(" Enlarged %d times\n", expcavcount);
20903 }
20904
20905 delete missingshqueue;
20906 delete flipque;
20907 delete missingshlist;
20908 delete boundedgelist;
20909 delete crossedgelist;
20910 delete equatptlist;
20911 delete crossshlist;
20912 delete crosstetlist;
20913 delete belowfacelist;
20914 delete abovefacelist;
20915 delete horizptlist;
20916 delete belowptlist;
20917 delete aboveptlist;
20918 delete frontlist;
20919 delete misfrontlist;
20920 delete newtetlist;
20921 delete [] worklist;
20922 }
20923
20924 //
20925 // End of facet recovery routines
20926 //
20927
20928 //
20929 // Begin of carving out holes and concavities routines
20930 //
20931
20932 ///////////////////////////////////////////////////////////////////////////////
20933 // //
20934 // infecthull() Virally infect all of the tetrahedra of the convex hull //
20935 // that are not protected by subfaces. Where there are //
20936 // subfaces, set boundary markers as appropriate. //
20937 // //
20938 // Memorypool 'viri' is used to return all the infected tetrahedra. //
20939 // //
20940 ///////////////////////////////////////////////////////////////////////////////
20941
20942 void tetgenmesh::infecthull(memorypool *viri)
20943 {
20944 triface tetloop, tsymtet;
20945 tetrahedron **deadtet;
20946 face hullface;
20947 // point horg, hdest, hapex;
20948
20949 if (b->verbose > 0) {
20950 printf(" Marking concavities for elimination.\n");
20951 }
20952 tetrahedrons->traversalinit();
20953 tetloop.tet = tetrahedrontraverse();
20954 while (tetloop.tet != (tetrahedron *) NULL) {
20955 // Is this tetrahedron on the hull?
20956 for (tetloop.loc = 0; tetloop.loc < 4; tetloop.loc++) {
20957 sym(tetloop, tsymtet);
20958 if (tsymtet.tet == dummytet) {
20959 // Is the tetrahedron protected by a subface?
20960 tspivot(tetloop, hullface);
20961 if (hullface.sh == dummysh) {
20962 // The tetrahedron is not protected; infect it.
20963 if (!infected(tetloop)) {
20964 infect(tetloop);
20965 deadtet = (tetrahedron **) viri->alloc();
20966 *deadtet = tetloop.tet;
20967 break; // Go and get next tet.
20968 }
20969 } else {
20970 // The tetrahedron is protected; set boundary markers if appropriate.
20971 if (shellmark(hullface) == 0) {
20972 setshellmark(hullface, 1);
20973 /*
20974 horg = sorg(hullface);
20975 hdest = sdest(hullface);
20976 hapex = sapex(hullface);
20977 if (pointmark(horg) == 0) {
20978 setpointmark(horg, 1);
20979 }
20980 if (pointmark(hdest) == 0) {
20981 setpointmark(hdest, 1);
20982 }
20983 if (pointmark(hapex) == 0) {
20984 setpointmark(hapex, 1);
20985 }
20986 */
20987 }
20988 }
20989 }
20990 }
20991 tetloop.tet = tetrahedrontraverse();
20992 }
20993 }
20994
20995 ///////////////////////////////////////////////////////////////////////////////
20996 // //
20997 // plague() Spread the virus from all infected tets to any neighbors not //
20998 // protected by subfaces. //
20999 // //
21000 // This routine identifies all the tetrahedra that will die, and marks them //
21001 // as infected. They are marked to ensure that each tetrahedron is added to //
21002 // the virus pool only once, so the procedure will terminate. 'viri' returns //
21003 // all infected tetrahedra which are outside the domian. //
21004 // //
21005 ///////////////////////////////////////////////////////////////////////////////
21006
21007 void tetgenmesh::plague(memorypool *viri)
21008 {
21009 tetrahedron **virusloop;
21010 tetrahedron **deadtet;
21011 triface testtet, neighbor;
21012 face neighsh, testseg;
21013 face spinsh, casingin, casingout;
21014 int firstdadsub;
21015 int i;
21016
21017 if (b->verbose > 0) {
21018 printf(" Marking neighbors of marked tetrahedra.\n");
21019 }
21020 firstdadsub = 0;
21021 // Loop through all the infected tetrahedra, spreading the virus to
21022 // their neighbors, then to their neighbors' neighbors.
21023 viri->traversalinit();
21024 virusloop = (tetrahedron **) viri->traverse();
21025 while (virusloop != (tetrahedron **) NULL) {
21026 testtet.tet = *virusloop;
21027 // Temporarily uninfect this tetrahedron, not necessary.
21028 uninfect(testtet);
21029 // Check each of the tetrahedron's four neighbors.
21030 for (testtet.loc = 0; testtet.loc < 4; testtet.loc++) {
21031 // Find the neighbor.
21032 sym(testtet, neighbor);
21033 // Check for a shell between the tetrahedron and its neighbor.
21034 tspivot(testtet, neighsh);
21035 // Check if the neighbor is nonexistent or already infected.
21036 if ((neighbor.tet == dummytet) || infected(neighbor)) {
21037 if (neighsh.sh != dummysh) {
21038 // There is a subface separating the tetrahedron from its neighbor,
21039 // but both tetrahedra are dying, so the subface dies too.
21040 // Before deallocte this subface, dissolve the connections between
21041 // other subfaces, subsegments and tetrahedra.
21042 neighsh.shver = 0;
21043 if (!firstdadsub) {
21044 firstdadsub = 1; // Report the problem once.
21045 if (!b->quiet) {
21046 printf("Warning: Detecting an open face (%d, %d, %d).\n",
21047 pointmark(sorg(neighsh)), pointmark(sdest(neighsh)),
21048 pointmark(sapex(neighsh)));
21049 }
21050 }
21051 // For keep the same enext() direction.
21052 findedge(&testtet, sorg(neighsh), sdest(neighsh));
21053 for (i = 0; i < 3; i++) {
21054 sspivot(neighsh, testseg);
21055 if (testseg.sh != dummysh) {
21056 // A subsegment is found at this side, dissolve this subface
21057 // from the face link of this subsegment.
21058 testseg.shver = 0;
21059 spinsh = neighsh;
21060 if (sorg(spinsh) != sorg(testseg)) {
21061 sesymself(spinsh);
21062 }
21063 spivot(spinsh, casingout);
21064 if (casingout.sh == spinsh.sh) {
21065 // This is a trivial face link, only 'neighsh' itself,
21066 // the subsegment at this side is also died.
21067 shellfacedealloc(subsegs, testseg.sh);
21068 } else {
21069 spinsh = casingout;
21070 do {
21071 casingin = spinsh;
21072 spivotself(spinsh);
21073 } while (spinsh.sh != neighsh.sh);
21074 // Set the link casingin->casingout.
21075 sbond1(casingin, casingout);
21076 // Bond the subsegment anyway.
21077 ssbond(casingin, testseg);
21078 }
21079 }
21080 senextself(neighsh);
21081 enextself(testtet);
21082 }
21083 if (neighbor.tet != dummytet) {
21084 // Make sure the subface doesn't get deallocated again later
21085 // when the infected neighbor is visited.
21086 tsdissolve(neighbor);
21087 }
21088 // This subface has been separated.
21089 if (in->mesh_dim > 2) {
21090 shellfacedealloc(subfaces, neighsh.sh);
21091 } else {
21092 // Dimension is 2. keep it for output.
21093 // Dissolve tets at both sides of this subface.
21094 stdissolve(neighsh);
21095 sesymself(neighsh);
21096 stdissolve(neighsh);
21097 }
21098 }
21099 } else { // The neighbor exists and is not infected.
21100 if (neighsh.sh == dummysh) {
21101 // There is no subface protecting the neighbor, infect it.
21102 infect(neighbor);
21103 // Ensure that the neighbor's neighbors will be infected.
21104 deadtet = (tetrahedron **) viri->alloc();
21105 *deadtet = neighbor.tet;
21106 } else { // The neighbor is protected by a subface.
21107 // Remove this tetrahedron from the subface.
21108 stdissolve(neighsh);
21109 // The subface becomes a boundary. Set markers accordingly.
21110 if (shellmark(neighsh) == 0) {
21111 setshellmark(neighsh, 1);
21112 }
21113 }
21114 }
21115 }
21116 // Remark the tetrahedron as infected, so it doesn't get added to the
21117 // virus pool again.
21118 infect(testtet);
21119 virusloop = (tetrahedron **) viri->traverse();
21120 }
21121 }
21122
21123 ///////////////////////////////////////////////////////////////////////////////
21124 // //
21125 // regionplague() Spread regional attributes and/or volume constraints //
21126 // (from a .poly file) throughout the mesh. //
21127 // //
21128 // This procedure operates in two phases. The first phase spreads an attri- //
21129 // bute and/or a volume constraint through a (facet-bounded) region. The //
21130 // second phase uninfects all infected tetrahedra, returning them to normal. //
21131 // //
21132 ///////////////////////////////////////////////////////////////////////////////
21133
21134 void tetgenmesh::
21135 regionplague(memorypool *regionviri, REAL attribute, REAL volume)
21136 {
21137 tetrahedron **virusloop;
21138 tetrahedron **regiontet;
21139 triface testtet, neighbor;
21140 face neighsh;
21141
21142 if (b->verbose > 1) {
21143 printf(" Marking neighbors of marked tetrahedra.\n");
21144 }
21145 // Loop through all the infected tetrahedra, spreading the attribute
21146 // and/or volume constraint to their neighbors, then to their neighbors'
21147 // neighbors.
21148 regionviri->traversalinit();
21149 virusloop = (tetrahedron **) regionviri->traverse();
21150 while (virusloop != (tetrahedron **) NULL) {
21151 testtet.tet = *virusloop;
21152 // Temporarily uninfect this tetrahedron, not necessary.
21153 uninfect(testtet);
21154 if (b->regionattrib) {
21155 // Set an attribute.
21156 setelemattribute(testtet.tet, in->numberoftetrahedronattributes,
21157 attribute);
21158 }
21159 if (b->varvolume) {
21160 // Set a volume constraint.
21161 setvolumebound(testtet.tet, volume);
21162 }
21163 // Check each of the tetrahedron's four neighbors.
21164 for (testtet.loc = 0; testtet.loc < 4; testtet.loc++) {
21165 // Find the neighbor.
21166 sym(testtet, neighbor);
21167 // Check for a subface between the tetrahedron and its neighbor.
21168 tspivot(testtet, neighsh);
21169 // Make sure the neighbor exists, is not already infected, and
21170 // isn't protected by a subface, or is protected by a nonsolid
21171 // subface.
21172 if ((neighbor.tet != dummytet) && !infected(neighbor)
21173 && (neighsh.sh == dummysh)) {
21174 // Infect the neighbor.
21175 infect(neighbor);
21176 // Ensure that the neighbor's neighbors will be infected.
21177 regiontet = (tetrahedron **) regionviri->alloc();
21178 *regiontet = neighbor.tet;
21179 }
21180 }
21181 // Remark the tetrahedron as infected, so it doesn't get added to the
21182 // virus pool again.
21183 infect(testtet);
21184 virusloop = (tetrahedron **) regionviri->traverse();
21185 }
21186
21187 // Uninfect all tetrahedra.
21188 if (b->verbose > 1) {
21189 printf(" Unmarking marked tetrahedra.\n");
21190 }
21191 regionviri->traversalinit();
21192 virusloop = (tetrahedron **) regionviri->traverse();
21193 while (virusloop != (tetrahedron **) NULL) {
21194 testtet.tet = *virusloop;
21195 uninfect(testtet);
21196 virusloop = (tetrahedron **) regionviri->traverse();
21197 }
21198 // Empty the virus pool.
21199 regionviri->restart();
21200 }
21201
21202 ///////////////////////////////////////////////////////////////////////////////
21203 // //
21204 // removeholetets() Remove tetrahedra which are outside the domain. //
21205 // //
21206 ///////////////////////////////////////////////////////////////////////////////
21207
21208 void tetgenmesh::removeholetets(memorypool* viri)
21209 {
21210 tetrahedron **virusloop;
21211 triface testtet, neighbor;
21212 point checkpt;
21213 int *tetspernodelist;
21214 int i, j;
21215
21216 if (b->verbose > 0) {
21217 printf(" Deleting marked tetrahedra.\n");
21218 }
21219
21220 // Create and initialize 'tetspernodelist'.
21221 tetspernodelist = new int[points->items + 1];
21222 for (i = 0; i < points->items + 1; i++) tetspernodelist[i] = 0;
21223
21224 // Loop the tetrahedra list, counter the number of tets sharing each node.
21225 tetrahedrons->traversalinit();
21226 testtet.tet = tetrahedrontraverse();
21227 while (testtet.tet != (tetrahedron *) NULL) {
21228 // Increment the number of sharing tets for each endpoint.
21229 for (i = 0; i < 4; i++) {
21230 j = pointmark((point) testtet.tet[4 + i]);
21231 tetspernodelist[j]++;
21232 }
21233 testtet.tet = tetrahedrontraverse();
21234 }
21235
21236 viri->traversalinit();
21237 virusloop = (tetrahedron **) viri->traverse();
21238 while (virusloop != (tetrahedron **) NULL) {
21239 testtet.tet = *virusloop;
21240 // Record changes in the number of boundary faces, and disconnect
21241 // dead tetrahedra from their neighbors.
21242 for (testtet.loc = 0; testtet.loc < 4; testtet.loc++) {
21243 sym(testtet, neighbor);
21244 if (neighbor.tet == dummytet) {
21245 // There is no neighboring tetrahedron on this face, so this face
21246 // is a boundary face. This tetrahedron is being deleted, so this
21247 // boundary face is deleted.
21248 hullsize--;
21249 } else {
21250 // Disconnect the tetrahedron from its neighbor.
21251 dissolve(neighbor);
21252 // There is a neighboring tetrahedron on this face, so this face
21253 // becomes a boundary face when this tetrahedron is deleted.
21254 hullsize++;
21255 }
21256 }
21257 // Check the four corners of this tet if they're isolated.
21258 for (i = 0; i < 4; i++) {
21259 checkpt = (point) testtet.tet[4 + i];
21260 j = pointmark(checkpt);
21261 tetspernodelist[j]--;
21262 if (tetspernodelist[j] == 0) {
21263 // If it is a volume vertex, mark to delete it.
21264 if ((pointtype(checkpt) == VOLVERTEX) ||
21265 (pointtype(checkpt) == FREEVOLVERTEX)) {
21266 setpointtype(checkpt, UNUSEDVERTEX);
21267 unuverts++;
21268 }
21269 }
21270 }
21271 // Return the dead tetrahedron to the pool of tetrahedra.
21272 tetrahedrondealloc(testtet.tet);
21273 virusloop = (tetrahedron **) viri->traverse();
21274 }
21275
21276 delete [] tetspernodelist;
21277 }
21278
21279 ///////////////////////////////////////////////////////////////////////////////
21280 // //
21281 // assignregionattribs() Assign each tetrahedron a region number. //
21282 // //
21283 // This routine is called when '-AA' switch is specified. Every tetrahedron //
21284 // of a (bounded) region will get a integer number to that region. Default, //
21285 // regions are numbered as 1, 2, 3, etc. However, if a number has already //
21286 // been used (set by user in the region section in .poly or .smesh), it is //
21287 // skipped and the next available number will be used. //
21288 // //
21289 ///////////////////////////////////////////////////////////////////////////////
21290
21291 void tetgenmesh::assignregionattribs()
21292 {
21293 list *regionnumlist;
21294 list *regiontetlist;
21295 triface tetloop, regiontet, neightet;
21296 face checksh;
21297 bool flag;
21298 int regionnum, num;
21299 int attridx, count;
21300 int i;
21301
21302 if (b->verbose > 0) {
21303 printf(" Assign region numbers.\n");
21304 }
21305
21306 regionnumlist = new list(sizeof(int), NULL, 256);
21307 regiontetlist = new list(sizeof(triface), NULL, 1024);
21308 attridx = in->numberoftetrahedronattributes;
21309
21310 // Loop through all tets. Infect tets which already have a region number,
21311 // and save the used numbers in 'regionnumlist'.
21312 tetrahedrons->traversalinit();
21313 tetloop.tet = tetrahedrontraverse();
21314 while (tetloop.tet != (tetrahedron *) NULL) {
21315 if (!infected(tetloop)) {
21316 regionnum = (int) elemattribute(tetloop.tet, attridx);
21317 if (regionnum != 0.0) {
21318 // Found a numbered region tet.
21319 infect(tetloop);
21320 regiontetlist->append(&tetloop);
21321 // Found and infect all tets in this region.
21322 for (i = 0; i < regiontetlist->len(); i++) {
21323 regiontet = * (triface *)(* regiontetlist)[i];
21324 for (regiontet.loc = 0; regiontet.loc < 4; regiontet.loc++) {
21325 // Is there a boundary face?
21326 tspivot(regiontet, checksh);
21327 if (checksh.sh == dummysh) {
21328 sym(regiontet, neightet);
21329 if ((neightet.tet != dummytet) && !infected(neightet)) {
21330 #ifdef SELF_CHECK
21331 // neightet should have the same region number. Check it.
21332 num = (int) elemattribute(neightet.tet, attridx);
21333 assert(num == regionnum);
21334 #endif
21335 infect(neightet);
21336 regiontetlist->append(&neightet);
21337 }
21338 }
21339 }
21340 }
21341 // Add regionnum to list if it is not exist.
21342 flag = false;
21343 for (i = 0; i < regionnumlist->len() && !flag; i++) {
21344 num = * (int *)(* regionnumlist)[i];
21345 flag = (num == regionnum);
21346 }
21347 if (!flag) regionnumlist->append(&regionnum);
21348 // Clear list for the next region.
21349 regiontetlist->clear();
21350 }
21351 }
21352 tetloop.tet = tetrahedrontraverse();
21353 }
21354
21355 if (b->verbose > 0) {
21356 printf(" %d user-specified regions.\n", regionnumlist->len());
21357 }
21358
21359 // Now loop the tets again. Assign region numbers to uninfected tets.
21360 tetrahedrons->traversalinit();
21361 tetloop.tet = tetrahedrontraverse();
21362 regionnum = 1; // Start region number.
21363 count = 0;
21364 while (tetloop.tet != (tetrahedron *) NULL) {
21365 if (!infected(tetloop)) {
21366 // An unassigned region tet.
21367 count++;
21368 do {
21369 flag = false;
21370 // Check if the region number has been used.
21371 for (i = 0; i < regionnumlist->len() && !flag; i++) {
21372 num = * (int *)(* regionnumlist)[i];
21373 flag = (num == regionnum);
21374 }
21375 if (flag) regionnum++;
21376 } while (flag);
21377 setelemattribute(tetloop.tet, attridx, (REAL) regionnum);
21378 infect(tetloop);
21379 regiontetlist->append(&tetloop);
21380 // Found and infect all tets in this region.
21381 for (i = 0; i < regiontetlist->len(); i++) {
21382 regiontet = * (triface *)(* regiontetlist)[i];
21383 for (regiontet.loc = 0; regiontet.loc < 4; regiontet.loc++) {
21384 // Is there a boundary face?
21385 tspivot(regiontet, checksh);
21386 if (checksh.sh == dummysh) {
21387 sym(regiontet, neightet);
21388 if ((neightet.tet != dummytet) && !infected(neightet)) {
21389 #ifdef SELF_CHECK
21390 // neightet should have not been assigned yet. Check it.
21391 num = (int) elemattribute(neightet.tet, attridx);
21392 assert(num == 0);
21393 #endif
21394 setelemattribute(neightet.tet, attridx, (REAL) regionnum);
21395 infect(neightet);
21396 regiontetlist->append(&neightet);
21397 }
21398 }
21399 }
21400 }
21401 regiontetlist->clear();
21402 regionnum++; // The next region number.
21403 }
21404 tetloop.tet = tetrahedrontraverse();
21405 }
21406
21407 // Uninfect all tets.
21408 tetrahedrons->traversalinit();
21409 tetloop.tet = tetrahedrontraverse();
21410 while (tetloop.tet != (tetrahedron *) NULL) {
21411 #ifdef SELF_CHECK
21412 assert(infected(tetloop));
21413 #endif
21414 uninfect(tetloop);
21415 tetloop.tet = tetrahedrontraverse();
21416 }
21417
21418 if (b->verbose > 0) {
21419 printf(" %d regions are numbered.\n", count);
21420 }
21421
21422 delete regionnumlist;
21423 delete regiontetlist;
21424 }
21425
21426 ///////////////////////////////////////////////////////////////////////////////
21427 // //
21428 // carveholes() Find the holes and infect them. Find the volume //
21429 // constraints and infect them. Infect the convex hull. //
21430 // Spread the infection and kill tetrahedra. Spread the //
21431 // volume constraints. //
21432 // //
21433 // This routine mainly calls other routines to carry out all these functions.//
21434 // //
21435 ///////////////////////////////////////////////////////////////////////////////
21436
21437 void tetgenmesh::carveholes()
21438 {
21439 memorypool *holeviri, *regionviri;
21440 tetrahedron *tptr, **holetet, **regiontet;
21441 triface searchtet, *holetets, *regiontets;
21442 enum locateresult intersect;
21443 int i;
21444
21445 if (!b->quiet) {
21446 printf("Removing unwanted tetrahedra.\n");
21447 if (b->verbose && (in->numberofholes > 0)) {
21448 printf(" Marking holes for elimination.\n");
21449 }
21450 }
21451
21452 // Initialize a pool of viri to be used for holes, concavities.
21453 holeviri = new memorypool(sizeof(tetrahedron *), 1024, POINTER, 0);
21454 // Mark as infected any unprotected tetrahedra on the boundary.
21455 infecthull(holeviri);
21456
21457 if (in->numberofholes > 0) {
21458 // Allocate storage for the tetrahedra in which hole points fall.
21459 holetets = (triface *) new triface[in->numberofholes];
21460 // Infect each tetrahedron in which a hole lies.
21461 for (i = 0; i < 3 * in->numberofholes; i += 3) {
21462 // Ignore holes that aren't within the bounds of the mesh.
21463 if ((in->holelist[i] >= xmin) && (in->holelist[i] <= xmax)
21464 && (in->holelist[i + 1] >= ymin)
21465 && (in->holelist[i + 1] <= ymax)
21466 && (in->holelist[i + 2] >= zmin)
21467 && (in->holelist[i + 2] <= zmax)) {
21468 searchtet.tet = dummytet;
21469 // Find a tetrahedron that contains the hole.
21470 intersect = locate(&in->holelist[i], &searchtet);
21471 if ((intersect != OUTSIDE) && (!infected(searchtet))) {
21472 // Record the tetrahedron for processing carve hole.
21473 holetets[i / 3] = searchtet;
21474 }
21475 }
21476 }
21477 // Infect the hole tetrahedron. This is done by marking the tet as
21478 // infected and including the tetrahedron in the virus pool.
21479 for (i = 0; i < in->numberofholes; i++) {
21480 infect(holetets[i]);
21481 holetet = (tetrahedron **) holeviri->alloc();
21482 *holetet = holetets[i].tet;
21483 }
21484 // Free up memory.
21485 delete [] holetets;
21486 }
21487
21488 // Mark as infected all tets of the holes and concavities.
21489 plague(holeviri);
21490 // The virus pool contains all outside tets now.
21491
21492 // Is -A switch in use.
21493 if (b->regionattrib) {
21494 // Assign every tetrahedron a regional attribute of zero.
21495 tetrahedrons->traversalinit();
21496 tptr = tetrahedrontraverse();
21497 while (tptr != (tetrahedron *) NULL) {
21498 setelemattribute(tptr, in->numberoftetrahedronattributes, 0.0);
21499 tptr = tetrahedrontraverse();
21500 }
21501 }
21502
21503 if (in->numberofregions > 0) {
21504 if (!b->quiet) {
21505 if (b->regionattrib) {
21506 if (b->varvolume) {
21507 printf("Spreading regional attributes and volume constraints.\n");
21508 } else {
21509 printf("Spreading regional attributes.\n");
21510 }
21511 } else {
21512 printf("Spreading regional volume constraints.\n");
21513 }
21514 }
21515 // Allocate storage for the tetrahedra in which region points fall.
21516 regiontets = (triface *) new triface[in->numberofregions];
21517 // Find the starting tetrahedron for each region.
21518 for (i = 0; i < in->numberofregions; i++) {
21519 regiontets[i].tet = dummytet;
21520 // Ignore region points that aren't within the bounds of the mesh.
21521 if ((in->regionlist[5 * i] >= xmin)
21522 && (in->regionlist[5 * i] <= xmax)
21523 && (in->regionlist[5 * i + 1] >= ymin)
21524 && (in->regionlist[5 * i + 1] <= ymax)
21525 && (in->regionlist[5 * i + 2] >= zmin)
21526 && (in->regionlist[5 * i + 2] <= zmax)) {
21527 searchtet.tet = dummytet;
21528 // Find a tetrahedron that contains the region point.
21529 intersect = locate(&in->regionlist[5 * i], &searchtet);
21530 if ((intersect != OUTSIDE) && (!infected(searchtet))) {
21531 // Record the tetrahedron for processing after the
21532 // holes have been carved.
21533 regiontets[i] = searchtet;
21534 }
21535 }
21536 }
21537 // Initialize a pool to be used for regional attrs, and/or regional
21538 // volume constraints.
21539 regionviri = new memorypool(sizeof(tetrahedron *), 1024, POINTER, 0);
21540 // Find and set all regions.
21541 for (i = 0; i < in->numberofregions; i++) {
21542 if (regiontets[i].tet != dummytet) {
21543 // Make sure the tetrahedron under consideration still exists.
21544 // It may have been eaten by the virus.
21545 if (!isdead(&(regiontets[i]))) {
21546 // Put one tetrahedron in the virus pool.
21547 infect(regiontets[i]);
21548 regiontet = (tetrahedron **) regionviri->alloc();
21549 *regiontet = regiontets[i].tet;
21550 // Apply one region's attribute and/or volume constraint.
21551 regionplague(regionviri, in->regionlist[5 * i + 3],
21552 in->regionlist[5 * i + 4]);
21553 // The virus pool should be empty now.
21554 }
21555 }
21556 }
21557 // Free up memory.
21558 delete [] regiontets;
21559 delete regionviri;
21560 }
21561
21562 // Now acutually remove the outside and hole tets.
21563 removeholetets(holeviri);
21564 // The mesh is nonconvex now.
21565 nonconvex = 1;
21566
21567 if (b->regionattrib) {
21568 if (b->regionattrib > 1) {
21569 // -AA switch. Assign each tet a region number (> 0).
21570 assignregionattribs();
21571 }
21572 // Note the fact that each tetrahedron has an additional attribute.
21573 in->numberoftetrahedronattributes++;
21574 }
21575
21576 // Free up memory.
21577 delete holeviri;
21578 }
21579
21580 //
21581 // End of carving out holes and concavities routines
21582 //
21583
21584 //
21585 // Begin of boundary Steiner points removing routines
21586 //
21587
21588 ///////////////////////////////////////////////////////////////////////////////
21589 // //
21590 // replacepolygonsubs() Substitute the subfaces of a polygon. //
21591 // //
21592 // 'oldshlist' (T_old) contains the old subfaces of P. It will be replaced //
21593 // by 'newshlist' (T_new) of new subfaces. Each boundary edge of P is bonded //
21594 // to 'dummysh' in T_new. //
21595 // //
21596 // Notice that Not every boundary edge of T_new is able to bond to a subface,//
21597 // e.g., when it is a segment recovered by removing a Steiner point in it. //
21598 // //
21599 ///////////////////////////////////////////////////////////////////////////////
21600
21601 void tetgenmesh::replacepolygonsubs(list* oldshlist, list* newshlist)
21602 {
21603 face newsh, oldsh, spinsh;
21604 face casingout, casingin;
21605 face checkseg;
21606 point pa, pb;
21607 int i, j, k, l;
21608
21609 for (i = 0; i < newshlist->len(); i++) {
21610 // Get a new subface s.
21611 newsh = * (face *)(* newshlist)[i];
21612 // Check the three edges of s.
21613 for (k = 0; k < 3; k++) {
21614 spivot(newsh, casingout);
21615 // Is it a boundary edge?
21616 if (casingout.sh == dummysh) {
21617 // Find the old subface s_o having the same edge as s.
21618 pa = sorg(newsh);
21619 pb = sdest(newsh);
21620 for (j = 0; j < oldshlist->len(); j++) {
21621 oldsh = * (face *)(* oldshlist)[j];
21622 for (l = 0; l < 3; l++) {
21623 if (((sorg(oldsh) == pa) && (sdest(oldsh) == pb)) ||
21624 ((sorg(oldsh) == pb) && (sdest(oldsh) == pa))) break;
21625 senextself(oldsh);
21626 }
21627 if (l < 3) break;
21628 }
21629 // Is there a matched edge?
21630 if (j < oldshlist->len()) {
21631 // Get the neighbor subface s_out.
21632 spivot(oldsh, casingout);
21633 sspivot(oldsh, checkseg);
21634 if (checkseg.sh != dummysh) {
21635 // A segment. Insert s into the face ring, ie, s_in -> s -> s_out.
21636 if (oldsh.sh != casingout.sh) {
21637 // s is not bonded to itself.
21638 spinsh = casingout;
21639 do {
21640 casingin = spinsh;
21641 spivotself(spinsh);
21642 } while (sapex(spinsh) != sapex(oldsh));
21643 assert(casingin.sh != oldsh.sh);
21644 // Bond s_in -> s -> s_out (and dissolve s_in -> s_old -> s_out).
21645 sbond1(casingin, newsh);
21646 sbond1(newsh, casingout);
21647 } else {
21648 // Bond newsh -> newsh.
21649 sbond(newsh, newsh);
21650 }
21651 // Bond the segment.
21652 ssbond(newsh, checkseg);
21653 } else {
21654 // Bond s <-> s_out (and dissolve s_out -> s_old).
21655 sbond(newsh, casingout);
21656 }
21657 // Unbound oldsh to indicate it's neighbor has been replaced.
21658 // It will be used to indentfy the edge in the inverse.
21659 sdissolve(oldsh);
21660 ssdissolve(oldsh);
21661 }
21662 }
21663 // Go to the next edge of s.
21664 senextself(newsh);
21665 }
21666 }
21667 }
21668
21669 ///////////////////////////////////////////////////////////////////////////////
21670 // //
21671 // orientnewsubs() Orient new subfaces facing to the inside of cavity. //
21672 // //
21673 // 'newshlist' contains new subfaces of the cavity C (created by re-triangu- //
21674 // lation the polygon P). They're not necessary facing to the inside of C. //
21675 // 'orientsh', faces to the inside of C, is used to adjust new subfaces. The //
21676 // normal of the new subfaces is returned in 'norm'. //
21677 // //
21678 ///////////////////////////////////////////////////////////////////////////////
21679
21680 void tetgenmesh::orientnewsubs(list* newshlist, face* orientsh, REAL* norm)
21681 {
21682 face *newsh;
21683 point pa, pb, pc;
21684 REAL ref[3], ori, len;
21685 int i;
21686
21687 // Calculate the normal of 'orientsh'.
21688 pa = sorg(*orientsh);
21689 pb = sdest(*orientsh);
21690 pc = sapex(*orientsh);
21691 facenormal(pa, pb, pc, norm, &len);
21692 for (i = 0; i < 3; i++) ref[i] = pa[i] + norm[i];
21693 for (i = 0; i < 3; i++) norm[i] /= len;
21694
21695 // Orient new subfaces. Let the normal above each one.
21696 for (i = 0; i < newshlist->len(); i++) {
21697 newsh = (face *)(* newshlist)[i];
21698 pa = sorg(*newsh);
21699 pb = sdest(*newsh);
21700 pc = sapex(*newsh);
21701 ori = orient3d(pa, pb, pc, ref);
21702 assert(ori != 0.0);
21703 if (ori > 0.0) {
21704 sesymself(*newsh);
21705 }
21706 }
21707 }
21708
21709 ///////////////////////////////////////////////////////////////////////////////
21710 // //
21711 // constrainedflip() Flip a non-constrained face. //
21712 // //
21713 // 'flipface' f (abc) is a face we want to flip. In addition, if 'front' is //
21714 // given (not a NULL), f is a crossface. f may not be flippable if it is one //
21715 // of the following cases: //
21716 // (1) f has an aux subface attached; //
21717 // (2) f is on the convex hull; //
21718 // (3) f is not locally Delaunay (f must be recovered by a previous flip, //
21719 // we should keep it, otherwise, we may fall into a flip loop); //
21720 // (4) f is T32 at ab, but abd or abe has an aux subface attached; //
21721 // (5) f is T22 or T44 at ab, but abd, or abe, or abf has an aux subface //
21722 // attached; //
21723 // (6) f is unflipable at ab, and abd, abe, ... are all unflippable due to //
21724 // the cases (1) - (5). //
21725 // If f is a crssface ('front' != NULL) and it is unflipable due to case (3),//
21726 // (4), (5) and (6). Try to flip the next crossing face of front first. //
21727 // //
21728 ///////////////////////////////////////////////////////////////////////////////
21729
21730 bool tetgenmesh::constrainedflip(triface* flipface, triface* front,
21731 queue* flipque)
21732 {
21733 triface symface, spintet;
21734 face checksh;
21735 point pa, pb, pc, pd, pe;
21736 enum fliptype fc;
21737 REAL sign;
21738 bool doflip;
21739 int ia, ib, ic, id, ie;
21740 int i;
21741
21742 // (1) Is f protected by an (auxilary) subface?
21743 tspivot(*flipface, checksh);
21744 if (checksh.sh != dummysh) return false;
21745 // (2) Is f on the convex hull?
21746 sym(*flipface, symface);
21747 if (symface.tet == dummytet) return false;
21748 // (3) Is f not locally Delaunay?
21749 adjustedgering(*flipface, CCW);
21750 pa = dest(*flipface);
21751 pb = org(*flipface);
21752 pc = apex(*flipface);
21753 pd = oppo(*flipface);
21754 pe = oppo(symface);
21755 // if (symbolic) {
21756 ia = pointmark(pa);
21757 ib = pointmark(pb);
21758 ic = pointmark(pc);
21759 id = pointmark(pd);
21760 ie = pointmark(pe);
21761 sign = insphere_sos(pa, pb, pc, pd, pe, ia, ib, ic, id, ie);
21762 assert(sign != 0.0);
21763 // } else {
21764 // sign = insphere(pa, pb, pc, pd, pe);
21765 // }
21766 if (sign <= 0.0) {
21767 // Get the fliptype of f.
21768 checksubfaces = 0; // switch off subface test.
21769 fc = categorizeface(*flipface);
21770 checksubfaces = 1; // switch on subface test.
21771 if (fc == T23) {
21772 doflip = true;
21773 // Avoid one tet created by the 2-3 flip is nearly degenerate.
21774 /* pc = oppo(*flipface);
21775 pd = oppo(symface);
21776 adjustedgering(*flipface, CCW);
21777 for (i = 0; i < 3; i++) {
21778 pa = org(*flipface);
21779 pb = dest(*flipface);
21780 ori = orient3d(pa, pb, pc, pd);
21781 if (iscoplanar(pa, pb, pc, pd, ori, b->epsilon)) {
21782 doflip = false; break;
21783 }
21784 enextself(*flipface);
21785 } */
21786 if (doflip) {
21787 flip23(flipface, flipque);
21788 return true;
21789 }
21790 } else if (fc == T32) {
21791 // (4) Is abd, or abe protected?
21792 doflip = true;
21793 spintet = *flipface;
21794 for (i = 0; i < 2; i++) {
21795 fnextself(spintet);
21796 tspivot(spintet, checksh);
21797 if (checksh.sh != dummysh) {
21798 doflip = false; break; // f is protected. Unflipable.
21799 }
21800 }
21801 if (doflip) {
21802 flip32(flipface, flipque);
21803 return true;
21804 }
21805 } else if (fc == T22 || fc == T44) {
21806 // (5) Is abd, abe, or abf protected?
21807 doflip = true;
21808 if (fc == T22) {
21809 for (i = 0; i < 2; i++) {
21810 spintet = *flipface;
21811 if (i == 1) {
21812 esymself(spintet);
21813 }
21814 fnextself(spintet);
21815 tspivot(spintet, checksh);
21816 if (checksh.sh != dummysh) {
21817 doflip = false; break; // f is protected. Unflipable.
21818 }
21819 }
21820 } else if (fc == T44) {
21821 spintet = *flipface;
21822 for (i = 0; i < 3; i++) {
21823 fnextself(spintet);
21824 tspivot(spintet, checksh);
21825 if (checksh.sh != dummysh) {
21826 doflip = false; break; // f is protected. Unflipable.
21827 }
21828 }
21829 }
21830 if (doflip) {
21831 flip22(flipface, flipque);
21832 return true;
21833 }
21834 } else if (fc == UNFLIPABLE) {
21835 // Is f a crossface?
21836 if (front != (triface *) NULL) {
21837 // (6) Is any obstacle face (abd, or abe, ...) flipable?
21838 spintet = *flipface;
21839 while (fnextself(spintet)) {
21840 if (apex(spintet) == apex(*flipface)) break;
21841 // Check if spintet is flipable, no recursive.
21842 if (constrainedflip(&spintet, NULL, flipque)) {
21843 // One obstacle face has been flipped.
21844 return true;
21845 }
21846 // Unflipable. Go to the next obstacle face.
21847 findedge(&spintet, org(*flipface), dest(*flipface));
21848 }
21849 }
21850 }
21851 }
21852
21853 // f is unflipable. Is f a crossface?
21854 if (front != (triface *) NULL) {
21855 // Look if there is another crossface.
21856 pa = org(*front);
21857 pb = dest(*front);
21858 pc = apex(*front);
21859 // sym(*flipface, symface);
21860 // Have we reach the end of abc (We've started from edge ab).
21861 if (oppo(symface) != pc) {
21862 adjustedgering(symface, CCW);
21863 for (i = 0; i < 3; i++) {
21864 fnext(symface, spintet);
21865 // Is c ahead of this face?
21866 sign = orient3d(org(spintet), dest(spintet), apex(spintet), pc);
21867 if (sign < 0.0) {
21868 if (tritritest(&spintet, pa, pb, pc)) {
21869 if (b->verbose > 2) {
21870 printf(" Next crossface (%d, %d, %d).\n",
21871 pointmark(org(spintet)), pointmark(dest(spintet)),
21872 pointmark(apex(spintet)));
21873 }
21874 return constrainedflip(&spintet, front, flipque);
21875 // return constrainedflip(&spintet, NULL, flipque);
21876 }
21877 }
21878 enextself(symface);
21879 }
21880 }
21881 }
21882 return false;
21883 }
21884
21885 ///////////////////////////////////////////////////////////////////////////////
21886 // //
21887 // recoverfront() Recover a missing front by flips. //
21888 // //
21889 // 'front' f is missing in D - it was crossed by faces of D. The cross faces //
21890 // may be flippable, so f can be recovered by flipping them away. //
21891 // //
21892 ///////////////////////////////////////////////////////////////////////////////
21893
21894 bool tetgenmesh::recoverfront(triface* front, list* newtetlist, queue* flipque)
21895 {
21896 triface idfront, starttet, spintet;
21897 point pa, pb, pc, pd, ref;
21898 enum locateresult loc;
21899 enum finddirectionresult col;
21900 REAL ori, ori1, ori2, sign;
21901 int hitbdry;
21902 int i, j;
21903
21904 // Find an existing edge of f in D to start with.
21905 for (i = 0; i < 3; i++) {
21906 pa = org(*front);
21907 pb = dest(*front);
21908 // Get a tet for searching.
21909 idfront = recenttet;
21910 // Make sure the tet is valid (flip32() may kill a tet).
21911 if (isdead(&idfront)) {
21912 // The tet is dead. Get a live tet in D. !!!
21913 for (j = 0; j < newtetlist->len(); j++) {
21914 recenttet = * (triface *)(* newtetlist)[j];
21915 if (!isdead(&recenttet)) break;
21916 }
21917 assert(j < newtetlist->len());
21918 }
21919 loc = preciselocate(pa, &idfront, (long) newtetlist->len());
21920 if (loc != ONVERTEX) {
21921 // Do a brute-force search in D.
21922 for (j = 0; j < newtetlist->len(); j++) {
21923 idfront = * (triface *)(* newtetlist)[j];
21924 if (isdead(&idfront)) continue;
21925 if (findorg(&idfront, pa)) break;
21926 }
21927 assert(j < newtetlist->len()); // a must belong to one tet.
21928 }
21929 recenttet = idfront;
21930 // Search for a tet having edge ab.
21931 col = finddirection(&idfront, pb, (long) newtetlist->len());
21932 if (col == BELOWHULL) {
21933 // Do a brute-force search in D.
21934 for (j = 0; j < newtetlist->len(); j++) {
21935 idfront = * (triface *)(* newtetlist)[j];
21936 if (isdead(&idfront)) continue;
21937 if (findorg(&idfront, pa)) {
21938 assert(org(idfront) == pa);
21939 if (dest(idfront) == pb) {
21940 col = RIGHTCOLLINEAR; break;
21941 } else if (apex(idfront) == pb) {
21942 col = LEFTCOLLINEAR; break;
21943 } else if (oppo(idfront) == pb) {
21944 col = TOPCOLLINEAR; break;
21945 }
21946 }
21947 }
21948 }
21949 if (col == RIGHTCOLLINEAR) {
21950 // b is just the destination.
21951 } else if (col == LEFTCOLLINEAR) {
21952 enext2self(idfront);
21953 esymself(idfront);
21954 } else if (col == TOPCOLLINEAR) {
21955 fnextself(idfront);
21956 enext2self(idfront);
21957 esymself(idfront);
21958 }
21959 if (dest(idfront) == pb) break; // Found.
21960 // Missing. Go to the next edge of f.
21961 enextself(*front);
21962 }
21963 if (i == 3) {
21964 // All three edges of f are missing - unrecoverable.
21965 return false;
21966 }
21967
21968 // Search for a tet having f (abc).
21969 pc = apex(*front);
21970 spintet = idfront;
21971 hitbdry = 0;
21972 do {
21973 if (apex(spintet) == pc) {
21974 // Found abc. Insert an auxilary subface s at idfront.
21975 insertauxsubface(front, &spintet);
21976 return true;
21977 }
21978 if (!fnextself(spintet)) {
21979 hitbdry ++;
21980 if (hitbdry < 2) {
21981 esym(idfront, spintet);
21982 if (!fnextself(spintet)) {
21983 hitbdry ++;
21984 }
21985 }
21986 }
21987 if (apex(spintet) == apex(idfront)) break;
21988 } while (hitbdry < 2);
21989
21990 // Search for a crossing face to flip.
21991 pd = apex(idfront);
21992 assert(pd != pc);
21993 // Decide the orientation of d with abc.
21994 ori = orient3d(pa, pb, pc, pd);
21995 if (ori < 0.0) {
21996 // d is above abc. Rotate downwards.
21997 esym(idfront, starttet);
21998 sign = -1.0;
21999 } else if (ori > 0.0) {
22000 // d is below abc. Rotate upwards.
22001 starttet = idfront;
22002 sign = 1.0;
22003 } else {
22004 assert(ori == 0.0);
22005 // d is coplanar with abc. Do abc and abd intersect?
22006 ref = oppo(idfront);
22007 ori1 = orient3d(pa, pb, ref, pc);
22008 ori2 = orient3d(pa, pb, ref, pd);
22009 assert(ori1 * ori2 != 0.0);
22010 if (ori1 * ori2 > 0) {
22011 // abc and abd intersect. There're two possible intersections:
22012 // ad and bc, or ac and bd. Find it out.
22013 ori1 = orient3d(pb, pc, ref, pd);
22014 ori2 = orient3d(pb, pc, ref, pa);
22015 assert(ori1 * ori2 != 0.0);
22016 if (ori1 * ori2 > 0) {
22017 // ac intersects bd.
22018 enextself(idfront); // go to edge bd.
22019 } else {
22020 // ad intersects bc.
22021 enext2self(idfront); // go to edge ad.
22022 }
22023 adjustedgering(idfront, CCW);
22024 fnextself(idfront); // face ade or bce need a 4-to-4 flip.
22025 if (b->verbose > 2) {
22026 printf(" Get crossface (%d, %d, %d).\n", pointmark(org(idfront)),
22027 pointmark(dest(idfront)), pointmark(apex(idfront)));
22028 }
22029 if (constrainedflip(&idfront, front, flipque)) {
22030 // A crossface has been flipped. Continue to recover f.
22031 return recoverfront(front, newtetlist, flipque);
22032 }
22033 // Unable to recover f.
22034 return false; // sign = 0.0;
22035 } else {
22036 // Not intersect. We can go either direction.
22037 starttet = idfront;
22038 if (fnextself(starttet)) {
22039 // Choose to rotate upwards.
22040 sign = 1.0;
22041 } else {
22042 // Hit convex hull. Choose to rotate downwrads.
22043 esym(idfront, starttet);
22044 sign = -1.0;
22045 }
22046 }
22047 }
22048
22049 assert(sign != 0.0);
22050 if (sign == -1) {
22051 // The edge ab has be changed. Reverse it.
22052 pa = org(starttet);
22053 pb = dest(starttet);
22054 // The sign has been reversed as well.
22055 sign = -sign;
22056 }
22057 // Rotate face abd around edge ab. Moreover, we've chosen the rotate
22058 // direction such that no convex hull face will be reach.
22059 spintet = starttet;
22060 while (fnextself(spintet)) {
22061 pd = apex(spintet);
22062 assert(pd != pc);
22063 // Check if the orientation of d (with abc) has changed.
22064 ori = orient3d(pa, pb, pc, pd);
22065 if (ori == 0.0) {
22066 // abc and abd must coplanar intersect (4-to-4 flip is needed).
22067 ref = oppo(spintet);
22068 ori1 = orient3d(pb, pc, ref, pd);
22069 ori2 = orient3d(pb, pc, ref, pa);
22070 assert(ori1 * ori2 != 0.0);
22071 if (ori1 * ori2 > 0) {
22072 // ac intersects bd.
22073 enextself(spintet); // go to edge bd.
22074 } else {
22075 // ad intersects bc.
22076 enext2self(spintet); // go to edge ad.
22077 }
22078 adjustedgering(spintet, CCW);
22079 fnextself(spintet); // face ade or bce need a 4-to-4 flip.
22080 if (b->verbose > 2) {
22081 printf(" Get crossface (%d, %d, %d).\n", pointmark(org(spintet)),
22082 pointmark(dest(spintet)), pointmark(apex(spintet)));
22083 }
22084 if (constrainedflip(&spintet, front, flipque)) {
22085 // A crossface has been flipped. Continue to recover f.
22086 return recoverfront(front, newtetlist, flipque);
22087 }
22088 // Unable to recover f.
22089 return false; // sign = 0.0;
22090 } else if (ori * sign < 0.0) {
22091 // Sign has changed. The face dea or deb must cross abc.
22092 adjustedgering(spintet, CCW);
22093 enextself(spintet);
22094 for (i = 0; i < 2; i++) {
22095 // Get the face dea or deb.
22096 fnext(spintet, starttet);
22097 if (tritritest(&starttet, pa, pb, pc)) {
22098 if (b->verbose > 2) {
22099 printf(" Get crossface (%d, %d, %d).\n",
22100 pointmark(org(starttet)), pointmark(dest(starttet)),
22101 pointmark(apex(starttet)));
22102 }
22103 if (constrainedflip(&starttet, front, flipque)) {
22104 // A crossface has been flipped. Continue to recover f.
22105 return recoverfront(front, newtetlist, flipque);
22106 }
22107 }
22108 enextself(spintet);
22109 }
22110 // Unable to recover f.
22111 return false;
22112 }
22113 }
22114 // Impossible to be here.
22115 assert(0);
22116 return false;
22117 }
22118
22119 ///////////////////////////////////////////////////////////////////////////////
22120 // //
22121 // repairflips() Flip non-Delaunay and non-constrained faces. //
22122 // //
22123 ///////////////////////////////////////////////////////////////////////////////
22124
22125 void tetgenmesh::repairflips(queue* flipque)
22126 {
22127 badface *qface;
22128 triface flipface, symface, spintet;
22129 face checksh;
22130 point pa, pb, pc, pd, pe;
22131 enum fliptype fc;
22132 REAL sign;
22133 long flipcount;
22134 bool doflip;
22135 int ia, ib, ic, id, ie;
22136 int i;
22137
22138 if (b->verbose > 1) {
22139 printf(" Repair flip %ld faces.\n", flipque->len());
22140 }
22141 flipcount = flip23s + flip32s + flip22s + flip44s;
22142 // Loop until the queue is empty.
22143 while (!flipque->empty()) {
22144 qface = (badface *) flipque->pop();
22145 flipface = qface->tt;
22146 // Check the validity of this face.
22147 if (isdead(&flipface) || flipface.tet == dummytet ||
22148 (org(flipface) != qface->forg) ||
22149 (dest(flipface) != qface->fdest) ||
22150 (apex(flipface) != qface->fapex) ||
22151 (oppo(flipface) == (point) NULL)) continue;
22152 // (1) Is f protected by an (auxilary) subface?
22153 tspivot(flipface, checksh);
22154 if (checksh.sh != dummysh) continue;
22155 // (2) Is f on the convex hull?
22156 sym(flipface, symface);
22157 if (symface.tet == dummytet) continue;
22158 // For positive orientation that insphere() test requires.
22159 adjustedgering(flipface, CW);
22160 pa = org(flipface);
22161 pb = dest(flipface);
22162 pc = apex(flipface);
22163 pd = oppo(flipface);
22164 pe = oppo(symface);
22165 // if (symbolic) {
22166 ia = pointmark(pa);
22167 ib = pointmark(pb);
22168 ic = pointmark(pc);
22169 id = pointmark(pd);
22170 ie = pointmark(pe);
22171 sign = insphere_sos(pa, pb, pc, pd, pe, ia, ib, ic, id, ie);
22172 assert(sign != 0.0);
22173 // } else {
22174 // sign = insphere(pa, pb, pc, pd, pe);
22175 // }
22176 if (sign > 0.0) {
22177 // f is non-lcally Delaunay. Get the fliptype of f.
22178 checksubfaces = 0; // switch off subface test.
22179 fc = categorizeface(flipface);
22180 checksubfaces = 1; // switch on subface test.
22181 if (fc == T23) {
22182 doflip = true;
22183 // Avoid to create a nearly degenerate tet.
22184 /* pc = oppo(flipface);
22185 pd = oppo(symface);
22186 adjustedgering(flipface, CCW);
22187 for (i = 0; i < 3; i++) {
22188 pa = org(flipface);
22189 pb = dest(flipface);
22190 ori = orient3d(pa, pb, pc, pd);
22191 if (iscoplanar(pa, pb, pc, pd, ori, b->epsilon)) {
22192 doflip = false; break;
22193 }
22194 enextself(flipface);
22195 } */
22196 if (doflip) {
22197 flip23(&flipface, flipque);
22198 }
22199 } else if (fc == T32) {
22200 // (4) Is abd, or abe protected?
22201 doflip = true;
22202 spintet = flipface;
22203 for (i = 0; i < 2; i++) {
22204 fnextself(spintet);
22205 tspivot(spintet, checksh);
22206 if (checksh.sh != dummysh) {
22207 doflip = false; break; // f is protected. Unflipable.
22208 }
22209 }
22210 if (doflip) {
22211 flip32(&flipface, flipque);
22212 }
22213 } else if (fc == T22 || fc == T44) {
22214 // (5) Is abd, abe, or abf protected?
22215 doflip = true;
22216 if (fc == T22) {
22217 for (i = 0; i < 2; i++) {
22218 spintet = flipface;
22219 if (i == 1) {
22220 esymself(spintet);
22221 }
22222 fnextself(spintet);
22223 tspivot(spintet, checksh);
22224 if (checksh.sh != dummysh) {
22225 doflip = false; break; // f is protected. Unflipable.
22226 }
22227 }
22228 } else if (fc == T44) {
22229 spintet = flipface;
22230 for (i = 0; i < 3; i++) {
22231 fnextself(spintet);
22232 tspivot(spintet, checksh);
22233 if (checksh.sh != dummysh) {
22234 doflip = false; break; // f is protected. Unflipable.
22235 }
22236 }
22237 }
22238 if (doflip) {
22239 flip22(&flipface, flipque);
22240 }
22241 }
22242 }
22243 }
22244 flipcount = flip23s + flip32s + flip22s + flip44s - flipcount;
22245 if (b->verbose > 1) {
22246 printf(" %ld flips.\n", flipcount);
22247 }
22248 }
22249
22250 ///////////////////////////////////////////////////////////////////////////////
22251 // //
22252 // constrainedcavity() Tetrahedralize a cavity by constrained tetrahedra. //
22253 // //
22254 // The cavity C is bounded by faces F in 'floorlist' and 'ceillist'. 'ptlist'//
22255 // V is the set of vertices of C. //
22256 // //
22257 ///////////////////////////////////////////////////////////////////////////////
22258
22259 bool tetgenmesh::constrainedcavity(triface* oldtet, list* floorlist,
22260 list* ceillist, list* ptlist, list* frontlist, list* misfrontlist,
22261 list* newtetlist, queue* flipque)
22262 {
22263 triface misfront, newtet;
22264 long facenum;
22265 int i;
22266
22267 if (b->verbose > 1) {
22268 printf(" Constrained cavity (%d floors, %d ceilings, %d vertices).\n",
22269 floorlist->len(), ceillist->len(), ptlist->len());
22270 }
22271
22272 symbolic = 1;
22273
22274 // Initialize the cavity C.
22275 initializecavity(floorlist, ceillist, frontlist);
22276 // Form the D of the vertices of C.
22277 delaunizecavvertices(oldtet, ptlist, NULL, newtetlist, flipque);
22278
22279 // Identify faces of C in D.
22280 if (!identifyfronts(frontlist, misfrontlist, newtetlist)) {
22281 // Some faces are missing.
22282 recenttet = * (triface *)(* newtetlist)[0];
22283 assert((recenttet.tet != dummytet) && !isdead(&recenttet));
22284 // Try to recover missing faces by flips.
22285 do {
22286 facenum = misfrontlist->len();
22287 for (i = 0; i < misfrontlist->len(); i++) {
22288 // Get a missing front f.
22289 misfront = * (triface *)(* misfrontlist)[i];
22290 // Let f face toward the inside of C.
22291 adjustedgering(misfront, CW);
22292 if (b->verbose > 1) {
22293 printf(" Recover face (%d, %d, %d).\n", pointmark(org(misfront)),
22294 pointmark(dest(misfront)), pointmark(apex(misfront)));
22295 }
22296 if (recoverfront(&misfront, newtetlist, flipque)) {
22297 // f has been recovered.
22298 frontlist->append(&misfront);
22299 misfrontlist->del(i, 0); i--;
22300 }
22301 // Flip non-locally non-constrained Delaunay faces.
22302 repairflips(flipque);
22303 }
22304 // Have all faces been recovered?
22305 if (misfrontlist->len() == 0) break;
22306 // No! There are still un-recovered faces. Continue the loop if any
22307 // face has been recovered.
22308 } while (misfrontlist->len() < facenum);
22309 // Retrieve new tets and purge dead tets in D.
22310 retrievenewtets(newtetlist);
22311 }
22312
22313 symbolic = 0;
22314
22315 if (misfrontlist->len() == 0) {
22316 // All fronts have identified in D. Get the shape of C by removing out
22317 // tets of C. 'misfrontlist' is reused for removing out tets.
22318 // Don't do flip since the new tets may get deleted later.
22319 carvecavity(newtetlist, misfrontlist, NULL);
22320 // Recover locally Delaunay faces.
22321 // flip(flipque, NULL);
22322 return true;
22323 } else {
22324 // Fail to tetrahedralize C.
22325 // Remove aux subfaces.
22326 detachauxsubfaces(newtetlist);
22327 // Remove new tets.
22328 for (i = 0; i < newtetlist->len(); i++) {
22329 newtet = * (triface *)(* newtetlist)[i];
22330 assert(!isdead(&newtet));
22331 tetrahedrondealloc(newtet.tet);
22332 }
22333 newtetlist->clear();
22334 // Restore faces of C in frontlist.
22335 for (i = 0; i < misfrontlist->len(); i++) {
22336 misfront = * (triface *)(* misfrontlist)[i];
22337 frontlist->append(&misfront);
22338 }
22339 return false;
22340 }
22341 }
22342
22343 ///////////////////////////////////////////////////////////////////////////////
22344 // //
22345 // expandsteinercavity() Expand the cavity of a Steiner point. //
22346 // //
22347 // Expand the cavity C if there fronts (except fronts having subfaces) which //
22348 // are either (nearly) coplanar or invisible by the Steiner point. //
22349 // //
22350 ///////////////////////////////////////////////////////////////////////////////
22351
22352 void tetgenmesh::expandsteinercavity(point steinpt, REAL eps, list* frontlist,
22353 list* oldtetlist)
22354 {
22355 triface front, symfront, newfront, oldfront;
22356 face frontsh;
22357 point pa, pb, pc;
22358 REAL ori;
22359 bool expflag, newflag;
22360 int i, j;
22361
22362 do {
22363 expflag = false;
22364 for (i = 0; i < frontlist->len(); i++) {
22365 // Get a front f.
22366 front = * (triface *)(* frontlist)[i];
22367 // f can be expanded if it is not a subface.
22368 tspivot(front, frontsh);
22369 if (frontsh.sh == dummysh) {
22370 // Let f face to the inside of C.
22371 adjustedgering(front, CW);
22372 pa = org(front);
22373 pb = dest(front);
22374 pc = apex(front);
22375 ori = orient3d(pa, pb, pc, steinpt);
22376 if (ori != 0.0) {
22377 if (iscoplanar(pa, pb, pc, steinpt, ori, eps)) {
22378 ori = 0.0; // f is nearly coplanar with p.
22379 }
22380 }
22381 if (ori >= 0.0) {
22382 // f is either invisible or coplanar with p.
22383 if (b->verbose > 2) {
22384 printf(" Remove front (%d, %d, %d).\n", pointmark(pa),
22385 pointmark(pb), pointmark(pc));
22386 }
22387 frontlist->del(i, 1);
22388 expflag = true;
22389 break;
22390 }
22391 }
22392 }
22393 if (expflag) {
22394 assert(!infected(front) && (oppo(front) != NULL));
22395 // Expand C at f by including new fronts.
22396 adjustedgering(front, CCW);
22397 for (i = 0; i < 3; i++) {
22398 newflag = true;
22399 // Get a new boundary n of the cavity.
22400 fnext(front, symfront);
22401 tspivot(symfront, frontsh);
22402 sym(symfront, newfront);
22403 if (frontsh.sh == dummysh) {
22404 assert(newfront.tet != dummytet);
22405 // Is n a front of the unexp. cavity?
22406 if (infected(newfront)) {
22407 for (j = 0; j < frontlist->len(); j++) {
22408 oldfront = * (triface *)(* frontlist)[j];
22409 if ((oldfront.tet == symfront.tet) &&
22410 (oldfront.loc == symfront.loc)) {
22411 // n is not a front anymore.
22412 if (b->verbose > 2) {
22413 printf(" Remove front (%d, %d, %d).\n",
22414 pointmark(org(oldfront)), pointmark(dest(oldfront)),
22415 pointmark(apex(oldfront)));
22416 }
22417 frontlist->del(j, 1);
22418 newflag = false;
22419 break;
22420 }
22421 }
22422 }
22423 } else {
22424 // n is a subface.
22425 if (newfront.tet == dummytet) {
22426 sesymself(frontsh);
22427 // Create a fake tet to hold n.
22428 maketetrahedron(&newfront);
22429 setorg(newfront, sorg(frontsh));
22430 setdest(newfront, sdest(frontsh));
22431 setapex(newfront, sapex(frontsh));
22432 setoppo(newfront, (point) NULL);
22433 tsbond(newfront, frontsh);
22434 } else {
22435 // n should not be a front of cavity yet.
22436 assert(!infected(newfront));
22437 }
22438 }
22439 if (newflag) {
22440 if (b->verbose > 2) {
22441 printf(" Add front (%d, %d, %d).\n", pointmark(org(newfront)),
22442 pointmark(dest(newfront)), pointmark(apex(newfront)));
22443 }
22444 frontlist->append(&newfront);
22445 }
22446 enextself(front);
22447 }
22448 // Add f into oldtetlist (to be deleted).
22449 infect(front);
22450 oldtetlist->append(&front);
22451 expcavcount++;
22452 }
22453 } while (expflag);
22454 }
22455
22456 ///////////////////////////////////////////////////////////////////////////////
22457 // //
22458 // findrelocatepoint() Find new location for relocating a point. //
22459 // //
22460 // 'frontlist' contains the boundary faces of the cavity C. Some fronts are //
22461 // visible by 'stpt' p, some are coplanar with p. //
22462 // //
22463 ///////////////////////////////////////////////////////////////////////////////
22464
22465 bool tetgenmesh::findrelocatepoint(point sp, point np, REAL* n,
22466 list* frontlist, list* oldtetlist)
22467 {
22468 triface front;
22469 point pa, pb, pc;
22470 REAL tp[3], tvol, mvol;
22471 REAL ori, eps;
22472 bool visible;
22473 int i, j, k;
22474
22475 if (b->verbose > 1) {
22476 printf(" Find new location for point %d.\n", pointmark(sp));
22477 }
22478
22479 // Avoid compilation warnings.
22480 tvol = mvol = 0.0;
22481 visible = false;
22482
22483 eps = b->epsilon;
22484 // Initialize np far enough from p (outside C).
22485 for (i = 0; i < 3; i++) np[i] = sp[i] + longest * n[i];
22486 // Let tp = np;
22487 for (i = 0; i < 3; i++) tp[i] = np[i];
22488 // Interation to adjust np until it is visible by all fronts.
22489 j = 0;
22490 do {
22491 for (i = 0; i < frontlist->len(); i++) {
22492 // Get a front face f.
22493 front = * (triface *)(* frontlist)[i];
22494 // Let f face to the interior of C.
22495 adjustedgering(front, CW);
22496 pa = org(front);
22497 pb = dest(front);
22498 pc = apex(front);
22499 ori = orient3d(pa, pb, pc, np);
22500 visible = (ori < 0.0);
22501 if (!visible) {
22502 // A front is invisible by np. Move it towards p along the normal.
22503 for (i = 0; i < 3; i++) np[i] = sp[i] + 0.5 * (sp[i] - np[i]);
22504 // Failed if tp = np.
22505 if ((tp[0] == np[0]) && (tp[1] == np[1]) && (tp[2] == np[2])) {
22506 // Try to expand the cavity.
22507 expandsteinercavity(sp, eps, frontlist, oldtetlist);
22508 eps *= 10.0;
22509 if (eps > b->epsilon * 1000.0) {
22510 // printf("Internal error: Fail to relocate pt %d.\n",pointmark(sp));
22511 // internalerror();
22512 return false;
22513 }
22514 // Restart the point relocation.
22515 for (i = 0; i < 3; i++) np[i] = sp[i] + longest * n[i];
22516 }
22517 if (j % 2) {
22518 // Set tp = np (at every 2 steps) to catch the stop state.
22519 for (i = 0; i < 3; i++) tp[i] = np[i];
22520 }
22521 break;
22522 } else {
22523 // Save the smallest volume.
22524 if (i == 0) {
22525 mvol = fabs(ori);
22526 } else {
22527 mvol = fabs(ori) < mvol ? fabs(ori) : mvol;
22528 }
22529 }
22530 }
22531 j++;
22532 } while (!visible);
22533
22534 if (b->verbose > 1) {
22535 printf(" %d iterations. minvol = %.12g.\n", j, mvol);
22536 }
22537
22538 // Continue to adjust np until the minimal volume of tets formed by
22539 // fronts and np doesn't increase (all fronts are visible by np).
22540 k = 0;
22541 do {
22542 j = 0;
22543 do {
22544 if (k == 0) {
22545 // Initial tp := np + 0.9 * (p - np). Move toward p.
22546 for (i = 0; i < 3; i++) tp[i] = sp[i] + 0.9 * (np[i] - sp[i]);
22547 } else {
22548 // Initial tp := np + 1.1 * (p - np). Move away from p.
22549 for (i = 0; i < 3; i++) tp[i] = sp[i] + 1.1 * (np[i] - sp[i]);
22550 }
22551 // Get the minial volume formed by tp with one of the fronts.
22552 for (i = 0; i < frontlist->len(); i++) {
22553 // Get a front face f.
22554 front = * (triface *)(* frontlist)[i];
22555 // Let f face to the interior of C.
22556 adjustedgering(front, CW);
22557 pa = org(front);
22558 pb = dest(front);
22559 pc = apex(front);
22560 ori = orient3d(pa, pb, pc, tp);
22561 visible = (ori < 0.0);
22562 if (visible) {
22563 // Save the smallest volume.
22564 if (i == 0) {
22565 tvol = fabs(ori);
22566 } else {
22567 tvol = fabs(ori) < tvol ? fabs(ori) : tvol;
22568 }
22569 } else {
22570 // A front is invisible by tp. Stop.
22571 tvol = 0.0;
22572 break;
22573 }
22574 }
22575 if (tvol > mvol) {
22576 // Get a larger minimal volume.
22577 for (i = 0; i < 3; i++) np[i] = tp[i];
22578 mvol = tvol;
22579 } else {
22580 // Minimal volume decreases. Stop.
22581 break;
22582 }
22583 // Continue to adjust np.
22584 j++;
22585 } while (true);
22586 // Has np been adjusted?
22587 if (j > 0) break;
22588 // Try to move np to anoter direction.
22589 k++;
22590 } while (k < 2);
22591
22592 if (b->verbose > 1) {
22593 printf(" %d adjust iterations. minvol = %.12g.\n", j, mvol);
22594 }
22595 return true;
22596 }
22597
22598 ///////////////////////////////////////////////////////////////////////////////
22599 // //
22600 // relocatepoint() Relocate a point into the cavity. //
22601 // //
22602 // 'frontlist' contains the boundary faces of the cavity C. All fronts must //
22603 // be visible by 'steinpt'. Some fronts may hold by 'fake' tets (they are //
22604 // hull faces). Fake tets will be removed when they're finished. //
22605 // //
22606 ///////////////////////////////////////////////////////////////////////////////
22607
22608 void tetgenmesh::relocatepoint(point steinpt, triface* oldtet, list* frontlist,
22609 list* newtetlist, queue* flipque)
22610 {
22611 triface front, newtet, newface, neightet;
22612 face checksh;
22613 point pa, pb;
22614 REAL attrib, volume;
22615 bool bdflag;
22616 int i, j, k, l;
22617
22618 if (b->verbose > 1) {
22619 printf(" Insert Steiner point (%.12g, %.12g, %.12g) %d.\n",
22620 steinpt[0], steinpt[1], steinpt[2], pointmark(steinpt));
22621 }
22622 // Clear the list first.
22623 newtetlist->clear();
22624
22625 // Create the tets formed by fronts and 'steinpt'.
22626 for (i = 0; i < frontlist->len(); i++) {
22627 // Get a front f.
22628 front = * (triface *)(* frontlist)[i];
22629 // Let f face inside C. (f is a face of tet adjacent to C).
22630 adjustedgering(front, CW);
22631 if (b->verbose > 2) {
22632 printf(" Get front (%d, %d, %d).\n", pointmark(org(front)),
22633 pointmark(dest(front)), pointmark(apex(front)));
22634 }
22635 maketetrahedron(&newtet);
22636 newtetlist->append(&newtet);
22637 setorg(newtet, org(front));
22638 setdest(newtet, dest(front));
22639 setapex(newtet, apex(front));
22640 setoppo(newtet, steinpt);
22641 if (oldtet != (triface *) NULL) {
22642 for (j = 0; j < in->numberoftetrahedronattributes; j++) {
22643 attrib = elemattribute(oldtet->tet, j);
22644 setelemattribute(newtet.tet, j, attrib);
22645 }
22646 if (b->varvolume) {
22647 volume = volumebound(oldtet->tet);
22648 setvolumebound(newtet.tet, volume);
22649 }
22650 }
22651 // 'front' may be a 'fake' tet.
22652 tspivot(front, checksh);
22653 if (oppo(front) == (point) NULL) {
22654 if (checksh.sh != dummysh) {
22655 stdissolve(checksh);
22656 }
22657 // Dealloc the 'fake' tet.
22658 tetrahedrondealloc(front.tet);
22659 // This side (newtet) is a boundary face, let 'dummytet' bond to it.
22660 // Otherwise, 'dummytet' may point to a dead tetrahedron after the
22661 // old cavity tets are removed.
22662 dummytet[0] = encode(newtet);
22663 } else {
22664 // Bond two tetrahedra, also dissolve the old bond at 'front'.
22665 bond(newtet, front);
22666 }
22667 if (checksh.sh != dummysh) {
22668 sesymself(checksh);
22669 tsbond(newtet, checksh);
22670 }
22671 if (flipque != (queue *) NULL) {
22672 // f may be non-locally Delaunay and flipable.
22673 enqueueflipface(newtet, flipque);
22674 }
22675 // The three neighbors are open. Will be finished later.
22676 }
22677
22678 // Connect new tets in C. All connecting faces must contain 'steinpt'.
22679 for (i = 0; i < newtetlist->len(); i++) {
22680 newtet = * (triface *)(* newtetlist)[i];
22681 newtet.ver = 0;
22682 for (j = 0; j < 3; j++) {
22683 fnext(newtet, newface);
22684 sym(newface, neightet);
22685 if (neightet.tet == dummytet) {
22686 // Find a neightet to connect it.
22687 bdflag = false;
22688 pa = org(newface);
22689 pb = dest(newface);
22690 assert(apex(newface) == steinpt);
22691 for (k = i + 1; k < newtetlist->len() && !bdflag; k++) {
22692 neightet = * (triface *)(* newtetlist)[k];
22693 neightet.ver = 0;
22694 for (l = 0; l < 3; l++) {
22695 if ((org(neightet) == pa && dest(neightet) == pb) ||
22696 (org(neightet) == pb && dest(neightet) == pa)) {
22697 // Find the neighbor.
22698 fnextself(neightet);
22699 assert(apex(neightet) == steinpt);
22700 // Now neightet is a face same as newface, bond them.
22701 bond(newface, neightet);
22702 bdflag = true;
22703 break;
22704 }
22705 enextself(neightet);
22706 }
22707 }
22708 assert(bdflag);
22709 }
22710 enextself(newtet);
22711 }
22712 // Let the corners of newtet point to it for fast searching.
22713 pa = org(newtet);
22714 setpoint2tet(pa, encode(newtet));
22715 pa = dest(newtet);
22716 setpoint2tet(pa, encode(newtet));
22717 pa = apex(newtet);
22718 setpoint2tet(pa, encode(newtet));
22719 pa = oppo(newtet);
22720 setpoint2tet(pa, encode(newtet));
22721 }
22722
22723 if (flipque != (queue *) NULL) {
22724 // Recover locally Delaunay faces.
22725 flip(flipque, NULL);
22726 }
22727 }
22728
22729 ///////////////////////////////////////////////////////////////////////////////
22730 // //
22731 // findcollapseedge() Find collapseable edge to suppress an endpoint. //
22732 // //
22733 ///////////////////////////////////////////////////////////////////////////////
22734
22735 bool tetgenmesh::findcollapseedge(point suppt, point *conpt, list* oldtetlist,
22736 list* ptlist)
22737 {
22738 triface front;
22739 point pt, pa, pb, pc;
22740 REAL *lenarray, ltmp, ori;
22741 bool visflag;
22742 int *idxarray, itmp;
22743 int n, i, j;
22744
22745 if (b->verbose > 2) {
22746 printf(" Search an edge (in %d edges) for collapse %d.\n",
22747 ptlist->len(), pointmark(suppt));
22748 }
22749
22750 // Candidate edges are p to the points of B(p) (in 'ptlist').
22751 n = ptlist->len();
22752 lenarray = new REAL[n];
22753 idxarray = new int[n];
22754 // Sort the points of B(p) by distance to p.
22755 for (i = 0; i < n; i++) {
22756 pt = * (point *)(* ptlist)[i];
22757 lenarray[i] = distance(suppt, pt);
22758 idxarray[i] = i;
22759 }
22760 // Bubble sort.
22761 for (i = 0; i < n - 1; i++) {
22762 for (j = 0; j < n - 1 - i; j++) {
22763 if (lenarray[j + 1] < lenarray[j]) { // compare the two neighbors
22764 ltmp = lenarray[j]; // swap a[j] and a[j + 1]
22765 lenarray[j] = lenarray[j + 1];
22766 lenarray[j + 1] = ltmp;
22767 itmp = idxarray[j]; // swap a[j] and a[j + 1]
22768 idxarray[j] = idxarray[j + 1];
22769 idxarray[j + 1] = itmp;
22770 }
22771 }
22772 }
22773 // For each point q of B(p), test if the edge (p, q) can be collapseed.
22774 for (i = 0; i < n; i++) {
22775 pt = * (point *)(* ptlist)[idxarray[i]];
22776 // Is q visible by faces of B(p) not with q as a vertex.
22777 lenarray[i] = 0.0; // zero volume.
22778 visflag = true;
22779 for (j = 0; j < oldtetlist->len() && visflag; j++) {
22780 front = * (triface *)(* oldtetlist)[j];
22781 // Let f face to inside of B(p).
22782 adjustedgering(front, CCW);
22783 pa = org(front);
22784 pb = dest(front);
22785 pc = apex(front);
22786 // Is f contains q?
22787 if ((pa != pt) && (pb != pt) && (pc != pt)) {
22788 ori = orient3d(pa, pb, pc, pt);
22789 if (ori != 0.0) {
22790 if (iscoplanar(pa, pb, pc, pt, ori, b->epsilon * 1e+2)) ori = 0.0;
22791 }
22792 visflag = ori < 0.0;
22793 if (visflag) {
22794 // Visible, set the smallest volume.
22795 if (j == 0) {
22796 lenarray[i] = fabs(ori);
22797 } else {
22798 lenarray[i] = fabs(ori) < lenarray[i] ? fabs(ori) : lenarray[i];
22799 }
22800 } else {
22801 // Invisible. Do not collapse (p, q).
22802 lenarray[i] = 0.0;
22803 }
22804 }
22805 }
22806 if ((b->verbose > 2) && visflag) {
22807 printf(" Got candidate %d vol(%g).\n", pointmark(pt), lenarray[i]);
22808 }
22809 }
22810
22811 // Select the largest non-zero volume (result in ltmp).
22812 ltmp = lenarray[0];
22813 itmp = idxarray[0];
22814 for (i = 1; i < n; i++) {
22815 if (lenarray[i] != 0.0) {
22816 if (lenarray[i] > ltmp) {
22817 ltmp = lenarray[i];
22818 itmp = idxarray[i]; // The index to find the point.
22819 }
22820 }
22821 }
22822
22823 delete [] lenarray;
22824 delete [] idxarray;
22825
22826 if (ltmp == 0.0) {
22827 // No edge can be collapseed.
22828 *conpt = (point) NULL;
22829 return false;
22830 } else {
22831 pt = * (point *)(* ptlist)[itmp];
22832 *conpt = pt;
22833 return true;
22834 }
22835 }
22836
22837 ///////////////////////////////////////////////////////////////////////////////
22838 // //
22839 // collapseedge() Remove a point by edge collapse. //
22840 // //
22841 ///////////////////////////////////////////////////////////////////////////////
22842
22843 void tetgenmesh::collapseedge(point suppt, point conpt, list* oldtetlist,
22844 list* deadtetlist)
22845 {
22846 triface oldtet, deadtet;
22847 triface adjtet1, adjtet2;
22848 face adjsh;
22849 point pa, pb, pc;
22850 int i, j;
22851
22852 if (b->verbose > 2) {
22853 printf(" Collapse edge (%d,%d).\n", pointmark(suppt), pointmark(conpt));
22854 }
22855
22856 // Loop in B(p), replace p with np, queue dead tets, uninfect old tets.
22857 for (i = 0; i < oldtetlist->len(); i++) {
22858 oldtet = * (triface *)(* oldtetlist)[i];
22859 assert(!infected(oldtet));
22860 pa = org(oldtet);
22861 pb = dest(oldtet);
22862 pc = apex(oldtet);
22863 assert(oppo(oldtet) == suppt);
22864 setoppo(oldtet, conpt);
22865 if ((pa == conpt) || (pb == conpt) || (pc == conpt)) {
22866 deadtetlist->append(&oldtet); // a collpased tet.
22867 }
22868 }
22869 // Loop in deadtetlist, glue adjacent tets of dead tets.
22870 for (i = 0; i < deadtetlist->len(); i++) {
22871 deadtet = * (triface *)(* deadtetlist)[i];
22872 // Get the adjacent tet n1 (outside B(p)).
22873 sym(deadtet, adjtet1);
22874 tspivot(deadtet, adjsh);
22875 // Find the edge in deadtet opposite to conpt.
22876 adjustedgering(deadtet, CCW);
22877 for (j = 0; j < 3; j++) {
22878 if (apex(deadtet) == conpt) break;
22879 enextself(deadtet);
22880 }
22881 assert(j < 3);
22882 // Get another adjacent tet n2.
22883 fnext(deadtet, adjtet2);
22884 symself(adjtet2);
22885 assert(adjtet2.tet != dummytet); // n2 is inside B(p).
22886 if (adjtet1.tet != dummytet) {
22887 bond(adjtet1, adjtet2); // Bond n1 <--> n2.
22888 } else {
22889 dissolve(adjtet2); // Dissolve at n2.
22890 dummytet[0] = encode(adjtet2); // Let dummytet holds n2.
22891 }
22892 if (adjsh.sh != dummysh) {
22893 tsbond(adjtet2, adjsh); // Bond s <--> n2.
22894 }
22895 // Collapse deadtet.
22896 tetrahedrondealloc(deadtet.tet);
22897 }
22898 deadtetlist->clear();
22899 }
22900
22901 ///////////////////////////////////////////////////////////////////////////////
22902 // //
22903 // deallocfaketets() Deleted fake tets at fronts. //
22904 // //
22905 // This routine is only called when the findrelocatepoint() routine fails. //
22906 // In other cases, the fake tets are removed automatically in carvecavity() //
22907 // or relocatepoint(). //
22908 // //
22909 ///////////////////////////////////////////////////////////////////////////////
22910
22911 void tetgenmesh::deallocfaketets(list* frontlist)
22912 {
22913 triface front, neightet;
22914 face checksh;
22915 bool infectflag;
22916 int i;
22917
22918 for (i = 0; i < frontlist->len(); i++) {
22919 // Get a front f.
22920 front = * (triface *)(* frontlist)[i];
22921 // Let f face inside C. (f is a face of tet adjacent to C).
22922 adjustedgering(front, CW);
22923 sym(front, neightet);
22924 tspivot(front, checksh);
22925 if (oppo(front) == (point) NULL) {
22926 if (b->verbose > 2) {
22927 printf(" Get fake tet (%d, %d, %d).\n", pointmark(org(front)),
22928 pointmark(dest(front)), pointmark(apex(front)));
22929 }
22930 if (neightet.tet != dummytet) {
22931 // The neightet may be infected. After dissolve it, the infect flag
22932 // will be lost. Save the flag and restore it later.
22933 infectflag = infected(neightet);
22934 dissolve(neightet);
22935 if (infectflag) {
22936 infect(neightet);
22937 }
22938 }
22939 if (checksh.sh != dummysh) {
22940 infectflag = sinfected(checksh);
22941 stdissolve(checksh);
22942 if (infectflag) {
22943 sinfect(checksh);
22944 }
22945 }
22946 // Dealloc the 'fake' tet.
22947 tetrahedrondealloc(front.tet);
22948 // This side (neightet) is a boundary face, let 'dummytet' bond to it.
22949 dummytet[0] = encode(neightet);
22950 }
22951 }
22952 }
22953
22954 ///////////////////////////////////////////////////////////////////////////////
22955 // //
22956 // restorepolyhedron() Restore the tetrahedralization in a polyhedron. //
22957 // //
22958 // This routine is only called when the operation of suppressing a point is //
22959 // aborted (eg., findrelocatepoint() routine fails). The polyhedron has been //
22960 // remeshed by new tets. This routine restore the old tets in it. //
22961 // //
22962 // 'oldtetlist' contains the list of old tets. Each old tet t_o assumes that //
22963 // it still connects to a tet t_b of the mesh, however, t_b does not connect //
22964 // to t_o, this routine resets the connection such that t_b <--> t_o. //
22965 // //
22966 ///////////////////////////////////////////////////////////////////////////////
22967
22968 void tetgenmesh::restorepolyhedron(list* oldtetlist)
22969 {
22970 triface oldtet, neightet, neineitet;
22971 face checksh;
22972 int i;
22973
22974 for (i = 0; i < oldtetlist->len(); i++) {
22975 // Get an old tet t_o.
22976 oldtet = * (triface *)(* oldtetlist)[i];
22977 // Check the four sides of t_o.
22978 for (oldtet.loc = 0; oldtet.loc < 4; oldtet.loc++) {
22979 sym(oldtet, neightet);
22980 tspivot(oldtet, checksh);
22981 if (neightet.tet != dummytet) {
22982 sym(neightet, neineitet);
22983 if (neineitet.tet != oldtet.tet) {
22984 // This face of t_o is a boundary of P.
22985 bond(neightet, oldtet);
22986 if (checksh.sh != dummysh) {
22987 tsbond(oldtet, checksh);
22988 }
22989 }
22990 } else {
22991 // t_o has a hull face. It should be the boundary of P.
22992 #ifdef SELF_CHECK
22993 assert(checksh.sh != dummysh);
22994 stpivot(checksh, neineitet);
22995 assert(neineitet.tet != oldtet.tet);
22996 #endif
22997 tsbond(oldtet, checksh);
22998 // Let dummytet[0] points to it.
22999 dummytet[0] = encode(oldtet);
23000 }
23001 }
23002 }
23003 }
23004
23005 ///////////////////////////////////////////////////////////////////////////////
23006 // //
23007 // suppressfacetpoint() Suppress a point inside a facet. //
23008 // //
23009 // The point p inside a facet F will be suppressed from F by either being //
23010 // deleted from the mesh or being relocated into the volume. //
23011 // //
23012 // 'supsh' is a subface f of F, and p = sapex(f); the other parameters are //
23013 // working lists which are empty at the beginning and the end. //
23014 // //
23015 ///////////////////////////////////////////////////////////////////////////////
23016
23017 bool tetgenmesh::suppressfacetpoint(face* supsh, list* frontlist,
23018 list* misfrontlist, list* ptlist, list* conlist, memorypool* viri,
23019 queue* flipque)
23020 {
23021 list *oldtetlist[2], *newtetlist[2];
23022 list *oldshlist, *newshlist;
23023 triface oldtet, newtet;
23024 face oldsh, newsh;
23025 point suppt, newpt[2];
23026 point *cons;
23027 REAL norm[3];
23028 bool success;
23029 int shmark;
23030 int i, j;
23031
23032 suppt = sapex(*supsh);
23033 if (b->verbose > 1) {
23034 printf(" Suppress point %d in facet.\n", pointmark(suppt));
23035 }
23036
23037 // Initialize working lists, variables.
23038 for (i = 0; i < 2; i++) {
23039 oldtetlist[i] = (list *) NULL;
23040 newtetlist[i] = (list *) NULL;
23041 newpt[i] = (point) NULL;
23042 }
23043 oldshlist = new list(sizeof(face), NULL, 256);
23044 newshlist = new list(sizeof(face), NULL, 256);
23045 success = true; // Assume p can be suppressed.
23046
23047 // Find subs of C(p).
23048 oldshlist->append(supsh);
23049 formstarpolygon(suppt, oldshlist, ptlist);
23050 // Get the edges of C(p). They form a closed polygon.
23051 for (i = 0; i < oldshlist->len(); i++) {
23052 oldsh = * (face *)(* oldshlist)[i];
23053 cons = (point *) conlist->append(NULL);
23054 cons[0] = sorg(oldsh);
23055 cons[1] = sdest(oldsh);
23056 }
23057 // Re-triangulate the old C(p).
23058 shmark = shellmark(*supsh);
23059 triangulate(shmark, b->epsilon, ptlist, conlist, 0, NULL, viri, flipque);
23060 // Get new subs of C(p), remove protected segments.
23061 retrievenewsubs(newshlist, true);
23062 // Substitute the old C(p) with the new C(p)
23063 replacepolygonsubs(oldshlist, newshlist);
23064 // Clear work lists.
23065 ptlist->clear();
23066 conlist->clear();
23067 flipque->clear();
23068 viri->restart();
23069
23070 // B(p) (tets with p as a vertex) has been separated into two parts
23071 // (B_0(p) and B_1(p)) by F. Process them individually.
23072 for (i = 0; i < 2 && success; i++) {
23073 if (i == 1) sesymself(*supsh);
23074 // Get a tet containing p.
23075 stpivot(*supsh, oldtet);
23076 // Is this part empty?
23077 if (oldtet.tet == dummytet) continue;
23078 // Allocate spaces for storing (old and new) B_i(p).
23079 oldtetlist[i] = new list(sizeof(triface), NULL, 256);
23080 newtetlist[i] = new list(sizeof(triface), NULL, 256);
23081 // Form old B_i(p) in oldtetlist[i].
23082 assert(!isdead(&oldtet));
23083 oldtetlist[i]->append(&oldtet);
23084 formstarpolyhedron(suppt, oldtetlist[i], ptlist, false);
23085 // Infect the tets in old B_i(p) (they're going to be delete).
23086 for (j = 0; j < oldtetlist[i]->len(); j++) {
23087 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23088 infect(oldtet);
23089 }
23090 // Preparation for re-tetrahedralzing old B_i(p).
23091 orientnewsubs(newshlist, supsh, norm);
23092 // Tetrahedralize old B_i(p).
23093 if (!constrainedcavity(&oldtet, newshlist, oldtetlist[i], ptlist,
23094 frontlist, misfrontlist, newtetlist[i], flipque)) {
23095 // Unable to mesh old B_i(p), try to relocate p into it.
23096 makepoint(&(newpt[i]));
23097 success = findrelocatepoint(suppt, newpt[i], norm, frontlist,
23098 oldtetlist[i]);
23099 if (success) {
23100 // p is relocated by newpt[i]. Now insert it. Don't do flip since
23101 // the new tets may get deleted again.
23102 relocatepoint(newpt[i], &oldtet, frontlist, newtetlist[i], NULL);
23103 setpointtype(newpt[i], FREEVOLVERTEX);
23104 relverts++;
23105 } else {
23106 // Fail to relocate p. Clean fake tets and quit this option.
23107 deallocfaketets(frontlist);
23108 pointdealloc(newpt[i]);
23109 newpt[i] = (point) NULL;
23110 assert(newtetlist[i]->len() == 0);
23111 }
23112 }
23113 // Clear work lists.
23114 ptlist->clear();
23115 frontlist->clear();
23116 misfrontlist->clear();
23117 flipque->clear();
23118 }
23119
23120 if (success) {
23121 // p has been removed! (Still in the pool).
23122 setpointtype(suppt, UNUSEDVERTEX);
23123 unuverts++;
23124 // Delete old C(p).
23125 for (i = 0; i < oldshlist->len(); i++) {
23126 oldsh = * (face *)(* oldshlist)[i];
23127 if (i == 0) {
23128 // Update the 'hullsize' if C(p) is on the hull.
23129 stpivot(oldsh, oldtet);
23130 if (oldtet.tet != dummytet) {
23131 sesymself(oldsh);
23132 stpivot(oldsh, oldtet);
23133 }
23134 if (oldtet.tet == dummytet) {
23135 // A boundary face. Update the 'hullsize'.
23136 j = oldshlist->len() - newshlist->len();
23137 assert(j > 0);
23138 hullsize -= j;
23139 }
23140 }
23141 shellfacedealloc(subfaces, oldsh.sh);
23142 }
23143 // Delete old B_i(p).
23144 for (i = 0; i < 2; i++) {
23145 if (oldtetlist[i] != (list *) NULL) {
23146 // Delete tets of the old B_i(p).
23147 for (j = 0; j < oldtetlist[i]->len(); j++) {
23148 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23149 assert(!isdead(&oldtet));
23150 tetrahedrondealloc(oldtet.tet);
23151 }
23152 }
23153 }
23154 } else {
23155 // p is not suppressed. Recover the original state.
23156 unsupverts++;
23157 // Restore the old C(p).
23158 replacepolygonsubs(newshlist, oldshlist);
23159 // Delete subs of the new C(p)
23160 for (i = 0; i < newshlist->len(); i++) {
23161 newsh = * (face *)(* newshlist)[i];
23162 shellfacedealloc(subfaces, newsh.sh);
23163 }
23164 // Restore old B_i(p).
23165 for (i = 0; i < 2; i++) {
23166 if (oldtetlist[i] != (list *) NULL) {
23167 // Uninfect tets of old B_i(p).
23168 for (j = 0; j < oldtetlist[i]->len(); j++) {
23169 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23170 assert(infected(oldtet));
23171 uninfect(oldtet);
23172 }
23173 // Has it been re-meshed?
23174 if (newtetlist[i]->len() > 0) {
23175 // Restore the old B_i(p).
23176 restorepolyhedron(oldtetlist[i]);
23177 // Delete tets of the new B_i(p);
23178 for (j = 0; j < newtetlist[i]->len(); j++) {
23179 newtet = * (triface *)(* (newtetlist[i]))[j];
23180 // Some new tets may already be deleted (by carvecavity()).
23181 if (!isdead(&newtet)) {
23182 tetrahedrondealloc(newtet.tet);
23183 }
23184 }
23185 }
23186 // Dealloc newpt[i] if it exists.
23187 if (newpt[i] != (point) NULL) {
23188 pointdealloc(newpt[i]);
23189 relverts--;
23190 }
23191 }
23192 }
23193 }
23194
23195 // Delete work lists.
23196 delete oldshlist;
23197 delete newshlist;
23198 for (i = 0; i < 2; i++) {
23199 if (oldtetlist[i] != (list *) NULL) {
23200 delete oldtetlist[i];
23201 delete newtetlist[i];
23202 }
23203 }
23204
23205 return success;
23206 }
23207
23208 ///////////////////////////////////////////////////////////////////////////////
23209 // //
23210 // suppresssegpoint() Suppress a point on a segment. //
23211 // //
23212 // The point p on a segment S will be suppressed from S by either being //
23213 // deleted from the mesh or being relocated into the volume. //
23214 // //
23215 // 'supseg' is the segment S, and p = sdest(S); the other parameters are //
23216 // working lists which are empty at the beginning and the end. //
23217 // //
23218 ///////////////////////////////////////////////////////////////////////////////
23219
23220 bool tetgenmesh::suppresssegpoint(face* supseg, list* spinshlist,
23221 list* newsegshlist, list* frontlist, list* misfrontlist, list* ptlist,
23222 list* conlist, memorypool* viri, queue* flipque)
23223 {
23224 list **oldtetlist, **newtetlist;
23225 list **oldshlist, **newshlist;
23226 list *pnewshlist, *dnewshlist;
23227 triface oldtet, newtet;
23228 face oldsh, newsh;
23229 face startsh, spinsh, segsh1, segsh2;
23230 face nsupseg, newseg, prevseg, nextseg;
23231 point suppt, *newpt;
23232 point pa, pb, *cons;
23233 REAL norm[3], pnorm[2][3];
23234 bool success;
23235 int shmark;
23236 int n, i, j, k;
23237
23238 // Get the Steiner point p.
23239 assert(supseg->shver == 0);
23240 suppt = sdest(*supseg);
23241 // Find the segment ab split by p.
23242 senext(*supseg, nsupseg);
23243 spivotself(nsupseg);
23244 assert(nsupseg.sh != dummysh);
23245 nsupseg.shver = 0;
23246 assert(sorg(nsupseg) == suppt);
23247 pa = sorg(*supseg);
23248 pb = sdest(nsupseg);
23249 if (b->verbose > 1) {
23250 printf(" Remove point %d on segment (%d, %d).\n",
23251 pointmark(suppt), pointmark(pa), pointmark(pb));
23252 }
23253
23254 // Let startsh s containing p.
23255 spivot(*supseg, startsh);
23256 spinsh = startsh;
23257 do {
23258 // Save it in list.
23259 spinshlist->append(&spinsh);
23260 // Go to the next facet.
23261 spivotself(spinsh);
23262 } while (spinsh.sh != startsh.sh);
23263 if (spinshlist->len() == 1) {
23264 // This case has not handled yet.
23265 // printf("Unhandled case: segment only belongs to one facet.\n");
23266 spinshlist->clear();
23267 unsupverts++;
23268 return false;
23269 }
23270
23271 // Suppose ab is shared by n facets (n > 1), then there are n B(p) (tets
23272 // with p as a vertex). Some B(p) may be empty, eg, outside.
23273 n = spinshlist->len();
23274 oldtetlist = new list*[n];
23275 newtetlist = new list*[n];
23276 oldshlist = new list*[n];
23277 newshlist = new list*[n];
23278 newpt = new point[n];
23279 for (i = 0; i < n; i++) {
23280 oldtetlist[i] = (list *) NULL;
23281 newtetlist[i] = (list *) NULL;
23282 oldshlist[i] = (list *) NULL;
23283 newshlist[i] = (list *) NULL;
23284 newpt[i] = (point) NULL;
23285 }
23286
23287 // Create a new segment ab (result in newseg).
23288 makeshellface(subsegs, &newseg);
23289 setsorg(newseg, pa);
23290 setsdest(newseg, pb);
23291 // ab gets the same mark and segment type as ap.
23292 setshellmark(newseg, shellmark(*supseg));
23293 setshelltype(newseg, shelltype(*supseg));
23294 if (b->quality && varconstraint) {
23295 // Copy the areabound into the new subsegment.
23296 setareabound(newseg, areabound(*supseg));
23297 }
23298 // Save the old connection at a.
23299 senext2(*supseg, prevseg);
23300 spivotself(prevseg);
23301 if (prevseg.sh != dummysh) {
23302 prevseg.shver = 0;
23303 assert(sdest(prevseg) == pa);
23304 senextself(prevseg);
23305 senext2self(newseg);
23306 sbond(newseg, prevseg);
23307 newseg.shver = 0;
23308 }
23309 // Save the old connection at b.
23310 senext(nsupseg, nextseg);
23311 spivotself(nextseg);
23312 if (nextseg.sh != dummysh) {
23313 nextseg.shver = 0;
23314 assert(sorg(nextseg) == pb);
23315 senext2self(nextseg);
23316 senextself(newseg);
23317 sbond(newseg, nextseg);
23318 newseg.shver = 0;
23319 }
23320
23321 // Re-triangulate C(p) (subs with p as a vertex) to remove p.
23322 for (i = 0; i < spinshlist->len(); i++) {
23323 spinsh = * (face *)(* spinshlist)[i];
23324 // Allocate spaces for C_i(p).
23325 oldshlist[i] = new list(sizeof(face), NULL, 256);
23326 newshlist[i] = new list(sizeof(face), NULL, 256);
23327 // Get the subs of C_i(p).
23328 oldshlist[i]->append(&spinsh);
23329 formstarpolygon(suppt, oldshlist[i], ptlist);
23330 // Find the edges of C_i(p). It DOES NOT form a closed polygon.
23331 for (j = 0; j < oldshlist[i]->len(); j++) {
23332 oldsh = * (face *)(* (oldshlist[i]))[j];
23333 cons = (point *) conlist->append(NULL);
23334 cons[0] = sorg(oldsh);
23335 cons[1] = sdest(oldsh);
23336 }
23337 // The C_i(p) isn't closed without ab. Add it to it.
23338 cons = (point *) conlist->append(NULL);
23339 cons[0] = pa;
23340 cons[1] = pb;
23341 // Re-triangulate C_i(p).
23342 shmark = shellmark(spinsh);
23343 triangulate(shmark, b->epsilon, ptlist, conlist, 0, NULL, viri, flipque);
23344 // Get new subs of C_i(p), remove protected segments.
23345 retrievenewsubs(newshlist[i], true);
23346 // Substitute old C_i(p) with the new C_i(p). !IT IS NOT COMPLETE!
23347 replacepolygonsubs(oldshlist[i], newshlist[i]);
23348 // Find the new subface s having edge ab.
23349 for (j = 0; j < newshlist[i]->len(); j++) {
23350 segsh1 = * (face *)(* (newshlist[i]))[j];
23351 for (k = 0; k < 3; k++) {
23352 if (((sorg(segsh1) == pa) && (sdest(segsh1) == pb)) ||
23353 ((sorg(segsh1) == pb) && (sdest(segsh1) == pa))) break;
23354 senextself(segsh1);
23355 }
23356 if (k < 3) break; // Found.
23357 }
23358 assert(j < newshlist[i]->len()); // ab must exist.
23359 // Bond s and ab together. The C_i(p) is completedly substituted.
23360 ssbond(segsh1, newseg);
23361 // Save s for forming the face ring of ab.
23362 newsegshlist->append(&segsh1);
23363 // Clear work lists.
23364 ptlist->clear();
23365 conlist->clear();
23366 flipque->clear();
23367 viri->restart();
23368 }
23369 // Form the face ring of ab.
23370 for (i = 0; i < newsegshlist->len(); i++) {
23371 segsh1 = * (face *)(* newsegshlist)[i];
23372 if ((i + 1) == newsegshlist->len()) {
23373 segsh2 = * (face *)(* newsegshlist)[0];
23374 } else {
23375 segsh2 = * (face *)(* newsegshlist)[i + 1];
23376 }
23377 sbond1(segsh1, segsh2);
23378 }
23379
23380 // A work list for keeping subfaces from two facets.
23381 dnewshlist = new list(sizeof(face), NULL, 256);
23382 success = true; // Assume p is suppressable.
23383
23384 // Suppress p in all B(p). B_i(p) is looped wrt the right-hand rule of ab.
23385 for (i = 0; i < spinshlist->len() && success; i++) {
23386 // Get an old subface s (ap) of a facet.
23387 spinsh = * (face *)(* spinshlist)[i];
23388 // Let the edge direction of s be a->b. Hence all subfaces follow
23389 // the right-hand rule of ab.
23390 if (sorg(spinsh) != pa) sesymself(spinsh);
23391 // Get a tet t of B_i(p).
23392 stpivot(spinsh, oldtet);
23393 // Is B_i(p) empty?
23394 if (oldtet.tet == dummytet) continue;
23395 // Allocate spaces for B_i(p).
23396 oldtetlist[i] = new list(sizeof(triface), NULL, 256);
23397 newtetlist[i] = new list(sizeof(triface), NULL, 256);
23398 // Find all tets of old B_i(p).
23399 oldtetlist[i]->append(&oldtet);
23400 formstarpolyhedron(suppt, oldtetlist[i], ptlist, false);
23401 // Infect tets of old B_i(p) (they're going to be deleted).
23402 for (j = 0; j < oldtetlist[i]->len(); j++) {
23403 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23404 infect(oldtet);
23405 }
23406 // Collect new subfaces (of two facets) bounded B_i(p).
23407 for (k = 0; k < 2; k++) {
23408 if ((i + k) < spinshlist->len()) {
23409 pnewshlist = newshlist[i + k];
23410 segsh1 = * (face *)(* spinshlist)[i + k];
23411 } else {
23412 pnewshlist = newshlist[0];
23413 segsh1 = * (face *)(* spinshlist)[0];
23414 }
23415 // Adjust the orientation of segsh1 to face to the inside of C.
23416 if (k == 0) {
23417 if (sorg(segsh1) != pa) sesymself(segsh1);
23418 assert(sorg(segsh1) == pa);
23419 } else {
23420 if (sdest(segsh1) != pa) sesymself(segsh1);
23421 assert(sdest(segsh1) == pa);
23422 }
23423 // Preparation for re-tetrahedralzing old B_i(p).
23424 orientnewsubs(pnewshlist, &segsh1, pnorm[k]);
23425 for (j = 0; j < pnewshlist->len(); j++) {
23426 dnewshlist->append((face *)(* pnewshlist)[j]);
23427 }
23428 }
23429 // Tetrahedralize B_i(p).
23430 if (!constrainedcavity(&oldtet, dnewshlist, oldtetlist[i], ptlist,
23431 frontlist, misfrontlist, newtetlist[i], flipque)) {
23432 // C must be finished by re-locating the steiner point.
23433 makepoint(&(newpt[i]));
23434 for (j = 0; j < 3; j++) norm[j] = 0.5 * (pnorm[0][j] + pnorm[1][j]);
23435 success = findrelocatepoint(suppt, newpt[i], norm, frontlist,
23436 oldtetlist[i]);
23437 if (success) {
23438 // p is relocated by newpt[i]. Now insert it. Don't do flip since
23439 // the new tets may get deleted again.
23440 relocatepoint(newpt[i], &oldtet, frontlist, newtetlist[i], NULL);
23441 setpointtype(newpt[i], FREEVOLVERTEX);
23442 relverts++;
23443 } else {
23444 // Fail to relocate p. Clean fake tets and quit this option.
23445 deallocfaketets(frontlist);
23446 pointdealloc(newpt[i]);
23447 newpt[i] = (point) NULL;
23448 assert(newtetlist[i]->len() == 0);
23449 }
23450 }
23451 // Clear work lists.
23452 dnewshlist->clear();
23453 ptlist->clear();
23454 frontlist->clear();
23455 misfrontlist->clear();
23456 flipque->clear();
23457 }
23458
23459 if (success) {
23460 // p has been suppressed. (Still in the pool).
23461 setpointtype(suppt, UNUSEDVERTEX);
23462 unuverts++;
23463 // Delete old segments ap, pb.
23464 shellfacedealloc(subsegs, supseg->sh);
23465 shellfacedealloc(subsegs, nsupseg.sh);
23466 // Delete subs of old C_i(p).
23467 for (i = 0; i < spinshlist->len(); i++) {
23468 for (j = 0; j < oldshlist[i]->len(); j++) {
23469 oldsh = * (face *)(* (oldshlist[i]))[j];
23470 if (j == 0) {
23471 // Update 'hullsize' if C_i(p) is on the hull.
23472 stpivot(oldsh, oldtet);
23473 if (oldtet.tet != dummytet) {
23474 sesymself(oldsh);
23475 stpivot(oldsh, oldtet);
23476 }
23477 if (oldtet.tet == dummytet) {
23478 // Update 'hullsize'.
23479 k = oldshlist[i]->len() - newshlist[i]->len();
23480 assert(k > 0);
23481 hullsize -= k;
23482 }
23483 }
23484 shellfacedealloc(subfaces, oldsh.sh);
23485 }
23486 }
23487 // Delete tets old B_i(p).
23488 for (i = 0; i < spinshlist->len(); i++) {
23489 // Delete them if it is not empty.
23490 if (oldtetlist[i] != (list *) NULL) {
23491 for (j = 0; j < oldtetlist[i]->len(); j++) {
23492 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23493 assert(!isdead(&oldtet));
23494 tetrahedrondealloc(oldtet.tet);
23495 }
23496 }
23497 }
23498 } else {
23499 // p is not suppressed. Recover the original state.
23500 unsupverts++;
23501 // Restore old connection at a.
23502 senext2(*supseg, prevseg);
23503 spivotself(prevseg);
23504 if (prevseg.sh != dummysh) {
23505 prevseg.shver = 0;
23506 assert(sdest(prevseg) == pa);
23507 senextself(prevseg);
23508 senext2self(*supseg);
23509 sbond(*supseg, prevseg);
23510 supseg->shver = 0;
23511 }
23512 // Restore old connection at b.
23513 senext(nsupseg, nextseg);
23514 spivotself(nextseg);
23515 if (nextseg.sh != dummysh) {
23516 nextseg.shver = 0;
23517 assert(sorg(nextseg) == pb);
23518 senext2self(nextseg);
23519 senextself(nsupseg);
23520 sbond(nsupseg, nextseg);
23521 nsupseg.shver = 0;
23522 }
23523 // Delete the new segment ab.
23524 shellfacedealloc(subsegs, newseg.sh);
23525 // Restore old C_i(p).
23526 for (i = 0; i < spinshlist->len(); i++) {
23527 replacepolygonsubs(newshlist[i], oldshlist[i]);
23528 // Delete subs of the new C_i(p)
23529 for (j = 0; j < newshlist[i]->len(); j++) {
23530 newsh = * (face *)(* (newshlist[i]))[j];
23531 shellfacedealloc(subfaces, newsh.sh);
23532 }
23533 }
23534 // Restore old B_i(p).
23535 for (i = 0; i < spinshlist->len(); i++) {
23536 if (oldtetlist[i] != (list *) NULL) {
23537 // Uninfect tets of old B_i(p).
23538 for (j = 0; j < oldtetlist[i]->len(); j++) {
23539 oldtet = * (triface *)(* (oldtetlist[i]))[j];
23540 assert(infected(oldtet));
23541 uninfect(oldtet);
23542 }
23543 // Has it been re-meshed?
23544 if (newtetlist[i]->len() > 0) {
23545 // Restore the old B_i(p).
23546 restorepolyhedron(oldtetlist[i]);
23547 // Delete tets of the new B_i(p);
23548 for (j = 0; j < newtetlist[i]->len(); j++) {
23549 newtet = * (triface *)(* (newtetlist[i]))[j];
23550 // Some new tets may already be deleted (by carvecavity()).
23551 if (!isdead(&newtet)) {
23552 tetrahedrondealloc(newtet.tet);
23553 }
23554 }
23555 }
23556 // Dealloc newpt[i] if it exists.
23557 if (newpt[i] != (point) NULL) {
23558 pointdealloc(newpt[i]);
23559 relverts--;
23560 }
23561 }
23562 }
23563 }
23564
23565 // Delete work lists.
23566 delete dnewshlist;
23567 for (i = 0; i < spinshlist->len(); i++) {
23568 delete oldshlist[i];
23569 delete newshlist[i];
23570 }
23571 delete [] oldshlist;
23572 delete [] newshlist;
23573 for (i = 0; i < spinshlist->len(); i++) {
23574 if (oldtetlist[i] != (list *) NULL) {
23575 delete oldtetlist[i];
23576 delete newtetlist[i];
23577 }
23578 }
23579 delete [] oldtetlist;
23580 delete [] newtetlist;
23581 // Clear work lists.
23582 newsegshlist->clear();
23583 spinshlist->clear();
23584
23585 return success;
23586 }
23587
23588 ///////////////////////////////////////////////////////////////////////////////
23589 // //
23590 // suppressvolpoint() Suppress a point inside mesh. //
23591 // //
23592 // The point p inside the mesh will be suppressed by being deleted from the //
23593 // mesh. p may not be suppressed. //
23594 // //
23595 ///////////////////////////////////////////////////////////////////////////////
23596
23597 bool tetgenmesh::suppressvolpoint(point suppt, list* frontlist,
23598 list* misfrontlist, list* ptlist, queue* flipque)
23599 {
23600 list *oldtetlist, *newtetlist;
23601 list *newshlist; // a dummy list.
23602 tetrahedron tetptr;
23603 triface oldtet, newtet;
23604 bool success;
23605 int j;
23606
23607 if (b->verbose > 1) {
23608 printf(" Remove point %d in mesh.\n", pointmark(suppt));
23609 }
23610
23611 // Get a tet with p as a vertex.
23612 oldtet.tet = (tetrahedron *) NULL;
23613 tetptr = point2tet(suppt);
23614 if (tetptr != (tetrahedron) NULL) {
23615 decode(tetptr, oldtet);
23616 }
23617 // Make sure oldtet contains p.
23618 if (isdead(&oldtet) || !findorg(&oldtet, suppt)) {
23619 // The pointer is invalid. Recreate the map.
23620 makepoint2tetmap();
23621 tetptr = point2tet(suppt);
23622 decode(tetptr, oldtet);
23623 if (isdead(&oldtet)) {
23624 // There is no tet contain p, it is indeed an unused point.
23625 // expandsteinercavity() deleted all tets of p.
23626 setpointtype(suppt, UNUSEDVERTEX);
23627 unuverts++;
23628 return true;
23629 }
23630 }
23631
23632 // Allocate spaces for storing (old and new) B(p).
23633 oldtetlist = new list(sizeof(triface), NULL, 256);
23634 newtetlist = new list(sizeof(triface), NULL, 256);
23635 newshlist = new list(sizeof(face), NULL, 256);
23636 success = true; // Assume p can be suppressed.
23637
23638 // Form old B(p) in oldtetlist.
23639 oldtetlist->append(&oldtet);
23640 formstarpolyhedron(suppt, oldtetlist, ptlist, false);
23641 // Infect the tets in old B(p) (they're going to be delete).
23642 for (j = 0; j < oldtetlist->len(); j++) {
23643 oldtet = * (triface *)(* oldtetlist)[j];
23644 infect(oldtet);
23645 }
23646 // Tetrahedralize old B(p).
23647 if (!constrainedcavity(&oldtet, newshlist, oldtetlist, ptlist, frontlist,
23648 misfrontlist, newtetlist, flipque)) {
23649 // Unable to suppress p.
23650 success = false;
23651 // Clean fake tets and quit this option.
23652 deallocfaketets(frontlist);
23653 assert(newtetlist->len() == 0);
23654 }
23655 // Clear work lists.
23656 ptlist->clear();
23657 frontlist->clear();
23658 misfrontlist->clear();
23659 flipque->clear();
23660
23661 if (success) {
23662 // p has been removed! (Still in the pool).
23663 setpointtype(suppt, UNUSEDVERTEX);
23664 unuverts++;
23665 suprelverts++;
23666 // Delete old B(p).
23667 for (j = 0; j < oldtetlist->len(); j++) {
23668 oldtet = * (triface *)(* oldtetlist)[j];
23669 assert(!isdead(&oldtet));
23670 tetrahedrondealloc(oldtet.tet);
23671 }
23672 } else {
23673 // p is not suppressed. Recover the original state.
23674 // Uninfect tets of old B(p).
23675 for (j = 0; j < oldtetlist->len(); j++) {
23676 oldtet = * (triface *)(* oldtetlist)[j];
23677 assert(infected(oldtet));
23678 uninfect(oldtet);
23679 }
23680 }
23681
23682 delete oldtetlist;
23683 delete newtetlist;
23684 delete newshlist;
23685
23686 return success;
23687 }
23688
23689 ///////////////////////////////////////////////////////////////////////////////
23690 // //
23691 // collapseedgepoint() Delete a point by edge collapse. //
23692 // //
23693 ///////////////////////////////////////////////////////////////////////////////
23694
23695 bool tetgenmesh::collapseedgepoint(point colpt, list *oldtetlist,
23696 list* deadtetlist, list *ptlist)
23697 {
23698 tetrahedron tetptr;
23699 triface oldtet, newtet;
23700 point conpt;
23701 bool success;
23702
23703 if (b->verbose > 1) {
23704 printf(" Collapse point %d.\n", pointmark(colpt));
23705 }
23706
23707 // Get a tet with p as a vertex.
23708 oldtet.tet = (tetrahedron *) NULL;
23709 tetptr = point2tet(colpt);
23710 if (tetptr != (tetrahedron) NULL) {
23711 decode(tetptr, oldtet);
23712 }
23713 // Make sure oldtet contains p.
23714 if (isdead(&oldtet) || !findorg(&oldtet, colpt)) {
23715 // The pointer is invalid. Recreate the map.
23716 makepoint2tetmap();
23717 tetptr = point2tet(colpt);
23718 decode(tetptr, oldtet);
23719 if (isdead(&oldtet)) {
23720 // There is no tet contain p, it is indeed an unused point.
23721 // expandsteinercavity() deleted all tets of p.
23722 setpointtype(colpt, UNUSEDVERTEX);
23723 unuverts++;
23724 return true;
23725 }
23726 }
23727
23728 // Form old B(p) in oldtetlist.
23729 oldtetlist->append(&oldtet);
23730 formstarpolyhedron(colpt, oldtetlist, ptlist, false);
23731 // Try to collapse p.
23732 success = findcollapseedge(colpt, &conpt, oldtetlist, ptlist);
23733 if (success) {
23734 // Collapse p by edge contraction.
23735 collapseedge(colpt, conpt, oldtetlist, deadtetlist);
23736 collapverts++;
23737 // p has been removed! (Still in the pool).
23738 setpointtype(colpt, UNUSEDVERTEX);
23739 unuverts++;
23740 deadtetlist->clear();
23741 }
23742 oldtetlist->clear();
23743 ptlist->clear();
23744
23745 return success;
23746 }
23747
23748 ///////////////////////////////////////////////////////////////////////////////
23749 // //
23750 // removesteiners() Delete or relocate Steiner points on facets. //
23751 // //
23752 ///////////////////////////////////////////////////////////////////////////////
23753
23754 void tetgenmesh::removesteiners()
23755 {
23756 list *frontlist, *misfrontlist;
23757 list *spinshlist, *newsegshlist;
23758 list *ptlist, *conlist;
23759 memorypool *viri;
23760 queue *flipque;
23761 triface checktet;
23762 face shloop;
23763 face segloop, nextseg;
23764 point pa;
23765 bool remflag;
23766 int oldnum, rmstein;
23767 int i;
23768
23769 // Initiliaze work lists.
23770 frontlist = new list(sizeof(triface), NULL);
23771 misfrontlist = new list(sizeof(triface), NULL);
23772 spinshlist = new list(sizeof(face), NULL);
23773 newsegshlist = new list(sizeof(face), NULL);
23774 ptlist = new list(sizeof(point *), NULL);
23775 conlist = new list(sizeof(point *) * 2, NULL);
23776 flipque = new queue(sizeof(badface));
23777 viri = new memorypool(sizeof(shellface *), 1024, POINTER, 0);
23778 oldnum = unuverts;
23779 relverts = suprelverts = collapverts = unsupverts = 0;
23780 expcavcount = 0;
23781
23782 if (!b->quiet) {
23783 printf("Removing Steiner points.\n");
23784 }
23785
23786 // Suppress Steiner points inside facets.
23787 do {
23788 rmstein = unuverts;
23789 subfaces->traversalinit();
23790 shloop.sh = shellfacetraverse(subfaces);
23791 while (shloop.sh != (shellface *) NULL) {
23792 remflag = false;
23793 // Is s contains a Steiner point?
23794 shloop.shver = 0;
23795 for (i = 0; i < 3; i++) {
23796 pa = sapex(shloop);
23797 if (pointtype(pa) == FREESUBVERTEX) {
23798 // Find a Steiner point p.
23799 if (b->nobisect == 1) {
23800 // '-Y'. Remove p if s is a hull face.
23801 stpivot(shloop, checktet);
23802 if (checktet.tet != dummytet) {
23803 sesymself(shloop);
23804 stpivot(shloop, checktet);
23805 }
23806 remflag = (checktet.tet == dummytet);
23807 } else {
23808 // '-YY'. Remove p whatever s is a hull face or not.
23809 remflag = true;
23810 }
23811 break;
23812 }
23813 senextself(shloop);
23814 }
23815 if (remflag) {
23816 suppressfacetpoint(&shloop, frontlist, misfrontlist, ptlist, conlist,
23817 viri, flipque);
23818 }
23819 shloop.sh = shellfacetraverse(subfaces);
23820 }
23821 // Continue if any Steiner point has been removed.
23822 } while (unuverts > rmstein);
23823
23824 // Suppress Steiner points on segments.
23825 do {
23826 rmstein = unuverts;
23827 subsegs->traversalinit();
23828 segloop.sh = shellfacetraverse(subsegs);
23829 while (segloop.sh != (shellface *) NULL) {
23830 remflag = false;
23831 // Don't check the poinytype of pa, it may be a Steiner point but has
23832 // type NACUTEVERTEX due to splitting a type-3 segment.
23833 // if (pointtype(pa) == FREESEGVERTEX) {
23834 segloop.shver = 0;
23835 senext(segloop, nextseg);
23836 spivotself(nextseg);
23837 if (nextseg.sh != dummysh) {
23838 // Find a Steiner point p.
23839 pa = sdest(segloop); // For checking.
23840 nextseg.shver = 0;
23841 assert(sorg(nextseg) == pa);
23842 if (b->nobisect == 1) {
23843 // '-Y'. Remove p if it is on the hull.
23844 sstpivot(&segloop, &checktet);
23845 assert(checktet.tet != dummytet);
23846 pa = apex(checktet);
23847 do {
23848 if (!fnextself(checktet)) {
23849 // Meet a boundary face - p is on the hull.
23850 remflag = true; break;
23851 }
23852 } while (pa != apex(checktet));
23853 } else {
23854 // '-YY'. Remove p whatever it is on the hull or not.
23855 remflag = true;
23856 }
23857 }
23858 if (remflag) {
23859 suppresssegpoint(&segloop, spinshlist, newsegshlist, frontlist,
23860 misfrontlist, ptlist, conlist, viri, flipque);
23861 }
23862 segloop.sh = shellfacetraverse(subsegs);
23863 }
23864 // Continue if any Steiner point has been removed.
23865 } while (unuverts > rmstein);
23866
23867 if (relverts > 0) {
23868 // Suppress relocated points.
23869 do {
23870 rmstein = unuverts;
23871 points->traversalinit();
23872 pa = pointtraverse();
23873 while (pa != (point) NULL) {
23874 remflag = (pointtype(pa) == FREEVOLVERTEX);
23875 if (remflag) {
23876 suppressvolpoint(pa, frontlist, misfrontlist, ptlist, flipque);
23877 }
23878 pa = pointtraverse();
23879 }
23880 // Continue if any relocated point has been suppressed.
23881 } while (unuverts > rmstein);
23882 }
23883
23884 /* if ((relverts - suprelverts) > 0) {
23885 // Try to collapse relocated points.
23886 do {
23887 rmstein = unuverts;
23888 points->traversalinit();
23889 pa = pointtraverse();
23890 while (pa != (point) NULL) {
23891 remflag = (pointtype(pa) == FREEVOLVERTEX);
23892 if (remflag) {
23893 collapseedgepoint(pa, frontlist, misfrontlist, ptlist);
23894 }
23895 pa = pointtraverse();
23896 }
23897 // Continue if any relocated point has been suppressed.
23898 } while (unuverts > rmstein);
23899 } */
23900
23901 if (b->verbose > 0) {
23902 printf(" %d points removed from boundary.\n", unuverts - oldnum);
23903 if (relverts > 0) {
23904 printf(" %d points relocated into volume.\n", relverts);
23905 }
23906 if (suprelverts > 0) {
23907 printf(" %d relocated points are suppressed.\n", suprelverts);
23908 }
23909 if (collapverts > 0) {
23910 printf(" %d relocated points are collapsed.\n", collapverts);
23911 }
23912 if (unsupverts > 0) {
23913 printf(" %d points are unsuppressed.\n", unsupverts);
23914 }
23915 if (expcavcount > 0) {
23916 printf(" %d cavity corrections.\n", expcavcount);
23917 }
23918 }
23919
23920 // Delete work lists.
23921 delete frontlist;
23922 delete misfrontlist;
23923 delete spinshlist;
23924 delete newsegshlist;
23925 delete ptlist;
23926 delete conlist;
23927 delete flipque;
23928 delete viri;
23929 }
23930
23931 //
23932 // End of boundary Steiner points removing routines
23933 //
23934
23935 //
23936 // Begin of mesh reconstruction routines
23937 //
23938
23939 ///////////////////////////////////////////////////////////////////////////////
23940 // //
23941 // reconstructmesh() Reconstruct a tetrahedral mesh from a list of //
23942 // tetrahedra and possibly a list of boundary faces. //
23943 // //
23944 // The list of tetrahedra is stored in 'in->tetrahedronlist', the list of //
23945 // boundary faces is stored in 'in->trifacelist'. The tetrahedral mesh is //
23946 // reconstructed in memorypool 'tetrahedrons', its boundary faces (subfaces) //
23947 // are reconstructed in 'subfaces', its boundary edges (subsegments) are //
23948 // reconstructed in 'subsegs'. If the -a switch is used, this procedure will //
23949 // also read a list of REALs from 'in->tetrahedronvolumelist' and set a //
23950 // maximum volume constraint on each tetrahedron. //
23951 // //
23952 // If the user has provided the boundary faces in 'in->trifacelist', they //
23953 // will be inserted the mesh. Otherwise subfaces will be identified from the //
23954 // mesh. All hull faces (including faces of the internal holes) will be //
23955 // recognized as subfaces, internal faces between two tetrahedra which have //
23956 // different attributes will also be recognized as subfaces. //
23957 // //
23958 // Subsegments will be identified after subfaces are reconstructed. Edges at //
23959 // the intersections of non-coplanar subfaces are recognized as subsegments. //
23960 // Edges between two coplanar subfaces with different boundary markers are //
23961 // also recognized as subsegments. //
23962 // //
23963 // The facet index of each subface will be set automatically after we have //
23964 // recovered subfaces and subsegments. That is, the set of subfaces, which //
23965 // are coplanar and have the same boundary marker will be recognized as a //
23966 // facet and has a unique index, stored as the facet marker in each subface //
23967 // of the set, the real boundary marker of each subface will be found in //
23968 // 'in->facetmarkerlist' by the index. Facet index will be used in Delaunay //
23969 // refinement for detecting two incident facets. //
23970 // //
23971 // Points which are not corners of tetrahedra will be inserted into the mesh.//
23972 // Return the number of faces on the hull after the reconstruction. //
23973 // //
23974 ///////////////////////////////////////////////////////////////////////////////
23975
23976 long tetgenmesh::reconstructmesh()
23977 {
23978 tetrahedron **tetsperverlist;
23979 shellface **facesperverlist;
23980 triface tetloop, neightet, neineightet, spintet;
23981 face subloop, neighsh, neineighsh, subseg;
23982 face sface1, sface2;
23983 point *idx2verlist;
23984 point torg, tdest, tapex, toppo;
23985 point norg, ndest, napex;
23986 list *neighshlist, *markerlist;
23987 REAL sign, attrib, volume;
23988 REAL da1, da2;
23989 bool bondflag, insertsegflag;
23990 int *idx2tetlist;
23991 int *idx2facelist;
23992 int *worklist;
23993 int facetidx, marker;
23994 int iorg, idest, iapex, ioppo;
23995 int inorg, indest, inapex;
23996 int index, i, j;
23997
23998 if (!b->quiet) {
23999 printf("Reconstructing mesh.\n");
24000 }
24001
24002 // Create a map from index to points.
24003 makeindex2pointmap(idx2verlist);
24004
24005 // Create the tetrahedra.
24006 for (i = 0; i < in->numberoftetrahedra; i++) {
24007 // Create a new tetrahedron and set its four corners, make sure that
24008 // four corners form a positive orientation.
24009 maketetrahedron(&tetloop);
24010 index = i * in->numberofcorners;
24011 // Although there may be 10 nodes, we only read the first 4.
24012 iorg = in->tetrahedronlist[index] - in->firstnumber;
24013 idest = in->tetrahedronlist[index + 1] - in->firstnumber;
24014 iapex = in->tetrahedronlist[index + 2] - in->firstnumber;
24015 ioppo = in->tetrahedronlist[index + 3] - in->firstnumber;
24016 torg = idx2verlist[iorg];
24017 tdest = idx2verlist[idest];
24018 tapex = idx2verlist[iapex];
24019 toppo = idx2verlist[ioppo];
24020 sign = orient3d(torg, tdest, tapex, toppo);
24021 if (sign > 0.0) {
24022 norg = torg; torg = tdest; tdest = norg;
24023 } else if (sign == 0.0) {
24024 if (!b->quiet) {
24025 printf("Warning: Tet %d is degenerate.\n", i + in->firstnumber);
24026 }
24027 }
24028 setorg(tetloop, torg);
24029 setdest(tetloop, tdest);
24030 setapex(tetloop, tapex);
24031 setoppo(tetloop, toppo);
24032 // Temporarily set the vertices be type VOLVERTEX, to indicate that
24033 // they belong to the mesh. These types may be changed later.
24034 setpointtype(torg, VOLVERTEX);
24035 setpointtype(tdest, VOLVERTEX);
24036 setpointtype(tapex, VOLVERTEX);
24037 setpointtype(toppo, VOLVERTEX);
24038 // Set element attributes if they exist.
24039 for (j = 0; j < in->numberoftetrahedronattributes; j++) {
24040 index = i * in->numberoftetrahedronattributes;
24041 attrib = in->tetrahedronattributelist[index + j];
24042 setelemattribute(tetloop.tet, j, attrib);
24043 }
24044 // If -a switch is used (with no number follows) Set a volume
24045 // constraint if it exists.
24046 if (b->varvolume) {
24047 if (in->tetrahedronvolumelist != (REAL *) NULL) {
24048 volume = in->tetrahedronvolumelist[i];
24049 } else {
24050 volume = -1.0;
24051 }
24052 setvolumebound(tetloop.tet, volume);
24053 }
24054 }
24055
24056 // Set the connection between tetrahedra.
24057 hullsize = 0l;
24058 // Create a map from nodes to tetrahedra.
24059 maketetrahedronmap(idx2tetlist, tetsperverlist);
24060 // Initialize the worklist.
24061 worklist = new int[points->items];
24062 for (i = 0; i < points->items; i++) worklist[i] = 0;
24063
24064 // Loop all tetrahedra, bond two tetrahedra if they share a common face.
24065 tetrahedrons->traversalinit();
24066 tetloop.tet = tetrahedrontraverse();
24067 while (tetloop.tet != (tetrahedron *) NULL) {
24068 // Loop the four sides of the tetrahedron.
24069 for (tetloop.loc = 0; tetloop.loc < 4; tetloop.loc++) {
24070 sym(tetloop, neightet);
24071 if (neightet.tet != dummytet) continue; // This side has finished.
24072 torg = org(tetloop);
24073 tdest = dest(tetloop);
24074 tapex = apex(tetloop);
24075 iorg = pointmark(torg) - in->firstnumber;
24076 idest = pointmark(tdest) - in->firstnumber;
24077 iapex = pointmark(tapex) - in->firstnumber;
24078 worklist[iorg] = 1;
24079 worklist[idest] = 1;
24080 worklist[iapex] = 1;
24081 bondflag = false;
24082 // Search its neighbor in the adjacent tets of torg.
24083 for (j = idx2tetlist[iorg]; j < idx2tetlist[iorg + 1] && !bondflag;
24084 j++) {
24085 if (tetsperverlist[j] == tetloop.tet) continue; // Skip myself.
24086 neightet.tet = tetsperverlist[j];
24087 for (neightet.loc = 0; neightet.loc < 4; neightet.loc++) {
24088 sym(neightet, neineightet);
24089 if (neineightet.tet == dummytet) {
24090 norg = org(neightet);
24091 ndest = dest(neightet);
24092 napex = apex(neightet);
24093 inorg = pointmark(norg) - in->firstnumber;
24094 indest = pointmark(ndest) - in->firstnumber;
24095 inapex = pointmark(napex) - in->firstnumber;
24096 if ((worklist[inorg] + worklist[indest] + worklist[inapex]) == 3) {
24097 // Find! Bond them together and break the loop.
24098 bond(tetloop, neightet);
24099 bondflag = true;
24100 break;
24101 }
24102 }
24103 }
24104 }
24105 if (!bondflag) {
24106 hullsize++; // It's a hull face.
24107 // Bond this side to outer space.
24108 dummytet[0] = encode(tetloop);
24109 if (in->pointmarkerlist != (int *) NULL) {
24110 // Set its three corners's markers be boundary (hull) vertices.
24111 if (in->pointmarkerlist[iorg] == 0) {
24112 in->pointmarkerlist[iorg] = 1;
24113 }
24114 if (in->pointmarkerlist[idest] == 0) {
24115 in->pointmarkerlist[idest] = 1;
24116 }
24117 if (in->pointmarkerlist[iapex] == 0) {
24118 in->pointmarkerlist[iapex] = 1;
24119 }
24120 }
24121 }
24122 worklist[iorg] = 0;
24123 worklist[idest] = 0;
24124 worklist[iapex] = 0;
24125 }
24126 tetloop.tet = tetrahedrontraverse();
24127 }
24128
24129 // Subfaces will be inserted into the mesh. It has two phases:
24130 // (1) Insert subfaces provided by user (in->trifacelist);
24131 // (2) Create subfaces for hull faces (if they're not subface yet) and
24132 // interior faces which separate two different materials.
24133
24134 // Phase (1). Is there a list of user-provided subfaces?
24135 if (in->trifacelist != (int *) NULL) {
24136 // Recover subfaces from 'in->trifacelist'.
24137 for (i = 0; i < in->numberoftrifaces; i++) {
24138 index = i * 3;
24139 iorg = in->trifacelist[index] - in->firstnumber;
24140 idest = in->trifacelist[index + 1] - in->firstnumber;
24141 iapex = in->trifacelist[index + 2] - in->firstnumber;
24142 // Look for the location of this subface.
24143 worklist[iorg] = 1;
24144 worklist[idest] = 1;
24145 worklist[iapex] = 1;
24146 bondflag = false;
24147 // Search its neighbor in the adjacent tets of torg.
24148 for (j = idx2tetlist[iorg]; j < idx2tetlist[iorg + 1] && !bondflag;
24149 j++) {
24150 neightet.tet = tetsperverlist[j];
24151 for (neightet.loc = 0; neightet.loc < 4; neightet.loc++) {
24152 norg = org(neightet);
24153 ndest = dest(neightet);
24154 napex = apex(neightet);
24155 inorg = pointmark(norg) - in->firstnumber;
24156 indest = pointmark(ndest) - in->firstnumber;
24157 inapex = pointmark(napex) - in->firstnumber;
24158 if ((worklist[inorg] + worklist[indest] + worklist[inapex]) == 3) {
24159 bondflag = true; // Find!
24160 break;
24161 }
24162 }
24163 }
24164 if (bondflag) {
24165 // Create a new subface and insert it into the mesh.
24166 makeshellface(subfaces, &subloop);
24167 torg = idx2verlist[iorg];
24168 tdest = idx2verlist[idest];
24169 tapex = idx2verlist[iapex];
24170 setsorg(subloop, torg);
24171 setsdest(subloop, tdest);
24172 setsapex(subloop, tapex);
24173 // Set the vertices be FREESUBVERTEX to indicate they belong to a
24174 // facet of the domain. They may be changed later.
24175 setpointtype(torg, FREESUBVERTEX);
24176 setpointtype(tdest, FREESUBVERTEX);
24177 setpointtype(tapex, FREESUBVERTEX);
24178 if (in->trifacemarkerlist != (int *) NULL) {
24179 setshellmark(subloop, in->trifacemarkerlist[i]);
24180 }
24181 adjustedgering(neightet, CCW);
24182 findedge(&subloop, org(neightet), dest(neightet));
24183 tsbond(neightet, subloop);
24184 sym(neightet, neineightet);
24185 if (neineightet.tet != dummytet) {
24186 sesymself(subloop);
24187 tsbond(neineightet, subloop);
24188 }
24189 } else {
24190 if (!b->quiet) {
24191 printf("Warning: Subface %d is discarded.\n", i + in->firstnumber);
24192 }
24193 }
24194 worklist[iorg] = 0;
24195 worklist[idest] = 0;
24196 worklist[iapex] = 0;
24197 }
24198 }
24199
24200 // Phase (2). Indentify subfaces from the mesh.
24201 tetrahedrons->traversalinit();
24202 tetloop.tet = tetrahedrontraverse();
24203 while (tetloop.tet != (tetrahedron *) NULL) {
24204 // Loop the four sides of the tetrahedron.
24205 for (tetloop.loc = 0; tetloop.loc < 4; tetloop.loc++) {
24206 tspivot(tetloop, subloop);
24207 if (subloop.sh != dummysh) continue;
24208 bondflag = false;
24209 sym(tetloop, neightet);
24210 if (neightet.tet == dummytet) {
24211 // It's a hull face. Insert a subface at here.
24212 bondflag = true;
24213 } else {
24214 // It's an interior face. Insert a subface if two tetrahedra have
24215 // different attributes (i.e., they belong to two regions).
24216 if (in->numberoftetrahedronattributes > 0) {
24217 if (elemattribute(neightet.tet,
24218 in->numberoftetrahedronattributes - 1) !=
24219 elemattribute(tetloop.tet,
24220 in->numberoftetrahedronattributes - 1)) {
24221 bondflag = true;
24222 }
24223 }
24224 }
24225 if (bondflag) {
24226 adjustedgering(tetloop, CCW);
24227 makeshellface(subfaces, &subloop);
24228 torg = org(tetloop);
24229 tdest = dest(tetloop);
24230 tapex = apex(tetloop);
24231 setsorg(subloop, torg);
24232 setsdest(subloop, tdest);
24233 setsapex(subloop, tapex);
24234 // Set the vertices be FACETVERTEX to indicate they belong to a
24235 // facet of the domain. They may be changed later.
24236 setpointtype(torg, FACETVERTEX);
24237 setpointtype(tdest, FACETVERTEX);
24238 setpointtype(tapex, FACETVERTEX);
24239 tsbond(tetloop, subloop);
24240 if (neightet.tet != dummytet) {
24241 sesymself(subloop);
24242 tsbond(neightet, subloop);
24243 }
24244 }
24245 }
24246 tetloop.tet = tetrahedrontraverse();
24247 }
24248
24249 // Set the connection between subfaces. A subsegment may have more than
24250 // two subfaces sharing it, 'neighshlist' stores all subfaces sharing
24251 // one edge.
24252 neighshlist = new list(sizeof(face), NULL);
24253 // Create a map from nodes to subfaces.
24254 makesubfacemap(idx2facelist, facesperverlist);
24255
24256 // Loop over the set of subfaces, setup the connection between subfaces.
24257 subfaces->traversalinit();
24258 subloop.sh = shellfacetraverse(subfaces);
24259 while (subloop.sh != (shellface *) NULL) {
24260 for (i = 0; i < 3; i++) {
24261 spivot(subloop, neighsh);
24262 if (neighsh.sh == dummysh) {
24263 // This side is 'empty', operate on it.
24264 torg = sorg(subloop);
24265 tdest = sdest(subloop);
24266 tapex = sapex(subloop);
24267 neighshlist->append(&subloop);
24268 iorg = pointmark(torg) - in->firstnumber;
24269 // Search its neighbor in the adjacent list of torg.
24270 for (j = idx2facelist[iorg]; j < idx2facelist[iorg + 1]; j++) {
24271 neighsh.sh = facesperverlist[j];
24272 if (neighsh.sh == subloop.sh) continue;
24273 neighsh.shver = 0;
24274 if (isfacehasedge(&neighsh, torg, tdest)) {
24275 findedge(&neighsh, torg, tdest);
24276 // Insert 'neighsh' into 'neighshlist'.
24277 if (neighshlist->len() < 2) {
24278 neighshlist->append(&neighsh);
24279 } else {
24280 for (index = 0; index < neighshlist->len() - 1; index++) {
24281 sface1 = * (face *)(* neighshlist)[index];
24282 sface2 = * (face *)(* neighshlist)[index + 1];
24283 da1 = facedihedral(torg, tdest, sapex(sface1), sapex(neighsh));
24284 da2 = facedihedral(torg, tdest, sapex(sface1), sapex(sface2));
24285 if (da1 < da2) {
24286 break; // Insert it after index.
24287 }
24288 }
24289 neighshlist->insert(index + 1, &neighsh);
24290 }
24291 }
24292 }
24293 // Bond the subfaces in 'neighshlist'.
24294 if (neighshlist->len() > 1) {
24295 neighsh = * (face *)(* neighshlist)[0];
24296 for (j = 1; j <= neighshlist->len(); j++) {
24297 if (j < neighshlist->len()) {
24298 neineighsh = * (face *)(* neighshlist)[j];
24299 } else {
24300 neineighsh = * (face *)(* neighshlist)[0];
24301 }
24302 sbond1(neighsh, neineighsh);
24303 neighsh = neineighsh;
24304 }
24305 } else {
24306 // No neighbor subface be found, bond 'subloop' to itself.
24307 sbond(subloop, subloop);
24308 }
24309 neighshlist->clear();
24310 }
24311 senextself(subloop);
24312 }
24313 subloop.sh = shellfacetraverse(subfaces);
24314 }
24315
24316 // Segments will be introudced. Each segment has a unique marker (1-based).
24317 marker = 1;
24318 subfaces->traversalinit();
24319 subloop.sh = shellfacetraverse(subfaces);
24320 while (subloop.sh != (shellface *) NULL) {
24321 for (i = 0; i < 3; i++) {
24322 sspivot(subloop, subseg);
24323 if (subseg.sh == dummysh) {
24324 // This side has no subsegment bonded, check it.
24325 torg = sorg(subloop);
24326 tdest = sdest(subloop);
24327 tapex = sapex(subloop);
24328 spivot(subloop, neighsh);
24329 spivot(neighsh, neineighsh);
24330 insertsegflag = false;
24331 if (subloop.sh == neighsh.sh || subloop.sh != neineighsh.sh) {
24332 // This side is either self-bonded or more than two subfaces,
24333 // insert a subsegment at this side.
24334 insertsegflag = true;
24335 } else {
24336 // Only two subfaces case.
24337 #ifdef SELF_CHECK
24338 assert(subloop.sh != neighsh.sh);
24339 #endif
24340 napex = sapex(neighsh);
24341 sign = orient3d(torg, tdest, tapex, napex);
24342 if (iscoplanar(torg, tdest, tapex, napex, sign, b->epsilon)) {
24343 // Although they are coplanar, we still need to check if they
24344 // have the same boundary marker.
24345 insertsegflag = (shellmark(subloop) != shellmark(neighsh));
24346 } else {
24347 // Non-coplanar.
24348 insertsegflag = true;
24349 }
24350 }
24351 if (insertsegflag) {
24352 // Create a subsegment at this side.
24353 makeshellface(subsegs, &subseg);
24354 setsorg(subseg, torg);
24355 setsdest(subseg, tdest);
24356 // At the moment, all segment vertices have type FACETVERTEX.
24357 // They will be set to type ACUTEVERTEX or NACUTEVERTEX by
24358 // routine markacutevertices() later.
24359 // setpointtype(torg, SEGMENTVERTEX);
24360 // setpointtype(tdest, SEGMENTVERTEX);
24361 setshellmark(subseg, marker);
24362 marker++;
24363 // Bond all subfaces to this subsegment.
24364 neighsh = subloop;
24365 do {
24366 ssbond(neighsh, subseg);
24367 spivotself(neighsh);
24368 } while (neighsh.sh != subloop.sh);
24369 }
24370 }
24371 senextself(subloop);
24372 }
24373 subloop.sh = shellfacetraverse(subfaces);
24374 }
24375 // Remember the number of input segments.
24376 insegments = subsegs->items;
24377 // Find the acute vertices and set them be type ACUTEVERTEX.
24378
24379 // Indentify facets and set the facet marker (1-based) for subfaces.
24380 markerlist = new list("int");
24381
24382 subfaces->traversalinit();
24383 subloop.sh = shellfacetraverse(subfaces);
24384 while (subloop.sh != (shellface *) NULL) {
24385 // Only operate on uninfected subface, after operating, infect it.
24386 if (!sinfected(subloop)) {
24387 // A new facet is found.
24388 marker = shellmark(subloop);
24389 markerlist->append(&marker);
24390 facetidx = markerlist->len(); // 'facetidx' starts from 1.
24391 setshellmark(subloop, facetidx);
24392 sinfect(subloop);
24393 neighshlist->append(&subloop);
24394 // Find out all subfaces of this facet (bounded by subsegments).
24395 for (i = 0; i < neighshlist->len(); i++) {
24396 neighsh = * (face *) (* neighshlist)[i];
24397 for (j = 0; j < 3; j++) {
24398 sspivot(neighsh, subseg);
24399 if (subseg.sh == dummysh) {
24400 spivot(neighsh, neineighsh);
24401 if (!sinfected(neineighsh)) {
24402 // 'neineighsh' is in the same facet as 'subloop'.
24403 #ifdef SELF_CHECK
24404 assert(shellmark(neineighsh) == marker);
24405 #endif
24406 setshellmark(neineighsh, facetidx);
24407 sinfect(neineighsh);
24408 neighshlist->append(&neineighsh);
24409 }
24410 }
24411 senextself(neighsh);
24412 }
24413 }
24414 neighshlist->clear();
24415 }
24416 subloop.sh = shellfacetraverse(subfaces);
24417 }
24418 // Uninfect all subfaces.
24419 subfaces->traversalinit();
24420 subloop.sh = shellfacetraverse(subfaces);
24421 while (subloop.sh != (shellface *) NULL) {
24422 #ifdef SELF_CHECK
24423 assert(sinfected(subloop));
24424 #endif
24425 suninfect(subloop);
24426 subloop.sh = shellfacetraverse(subfaces);
24427 }
24428 // Save the facet markers in 'in->facetmarkerlist'.
24429 in->numberoffacets = markerlist->len();
24430 in->facetmarkerlist = new int[in->numberoffacets];
24431 for (i = 0; i < in->numberoffacets; i++) {
24432 marker = * (int *) (* markerlist)[i];
24433 in->facetmarkerlist[i] = marker;
24434 }
24435 // Initialize the 'facetabovepointlist'.
24436 facetabovepointarray = new point[in->numberoffacets + 1];
24437 for (i = 0; i < in->numberoffacets + 1; i++) {
24438 facetabovepointarray[i] = (point) NULL;
24439 }
24440
24441 // The mesh contains boundary now.
24442 checksubfaces = 1;
24443 // The mesh is nonconvex now.
24444 nonconvex = 1;
24445
24446 // Is there periodic boundary confitions?
24447 if (checkpbcs) {
24448 tetgenio::pbcgroup *pg;
24449 pbcdata *pd;
24450 // Initialize the global array 'subpbcgrouptable'.
24451 createsubpbcgrouptable();
24452 // Loop for each pbcgroup i.
24453 for (i = 0; i < in->numberofpbcgroups; i++) {
24454 pg = &(in->pbcgrouplist[i]);
24455 pd = &(subpbcgrouptable[i]);
24456 // Find all subfaces of pd, set each subface's group id be i.
24457 for (j = 0; j < 2; j++) {
24458 subfaces->traversalinit();
24459 subloop.sh = shellfacetraverse(subfaces);
24460 while (subloop.sh != (shellface *) NULL) {
24461 facetidx = shellmark(subloop);
24462 marker = in->facetmarkerlist[facetidx - 1];
24463 if (marker == pd->fmark[j]) {
24464 setshellpbcgroup(subloop, i);
24465 pd->ss[j] = subloop;
24466 }
24467 subloop.sh = shellfacetraverse(subfaces);
24468 }
24469 }
24470 if (pg->pointpairlist != (int *) NULL) {
24471 // Set the connections between pbc point pairs.
24472 for (j = 0; j < pg->numberofpointpairs; j++) {
24473 iorg = pg->pointpairlist[j * 2] - in->firstnumber;
24474 idest = pg->pointpairlist[j * 2 + 1] - in->firstnumber;
24475 torg = idx2verlist[iorg];
24476 tdest = idx2verlist[idest];
24477 setpoint2pbcpt(torg, tdest);
24478 setpoint2pbcpt(tdest, torg);
24479 }
24480 }
24481 }
24482 // Create the global array 'segpbcgrouptable'.
24483 createsegpbcgrouptable();
24484 }
24485
24486 // if (b->quality && varconstraint) {
24487 // // Assign constraints on facets, segments, and nodes.
24488 // assignvarconstraints(idx2verlist);
24489 // }
24490
24491 /*
24492 if (b->quality) {
24493 // Check and recover the Delaunay property.
24494 queue* flipqueue = new queue(sizeof(badface));
24495 checkdelaunay(0.0, flipqueue);
24496 if (!flipqueue->empty()) {
24497 // Call flip algorithm to recover Delaunayness.
24498 flip(flipqueue, NULL);
24499 }
24500 delete flipqueue;
24501 }
24502 */
24503
24504 delete markerlist;
24505 delete neighshlist;
24506 delete [] worklist;
24507 delete [] idx2tetlist;
24508 delete [] tetsperverlist;
24509 delete [] idx2facelist;
24510 delete [] facesperverlist;
24511 delete [] idx2verlist;
24512
24513 return hullsize;
24514 }
24515
24516 ///////////////////////////////////////////////////////////////////////////////
24517 // //
24518 // intettest() Test if a point is inside (or on) a tetrahedron. //
24519 // //
24520 // Return TRUE if the point p and the tet t has one of the relations: (1) p //
24521 // is inside t; (2) p is on a faces of t; (3) p is on an edge of t; (4) p is //
24522 // a vertex of t. Otherwise, return FALSE. //
24523 // //
24524 // An relative tolerance is used to determine coplanar case when a face of t //
24525 // is on the hull. To bring back a boundary point inside the mesh. //
24526 // //
24527 ///////////////////////////////////////////////////////////////////////////////
24528
24529 bool tetgenmesh::intettest(point testpt, triface* testtet, REAL eps)
24530 {
24531 triface checktet;
24532 point p1, p2, p3;
24533 REAL ori;
24534
24535 testtet->ver = 0;
24536 for (testtet->loc = 0; testtet->loc < 4; testtet->loc++) {
24537 // Get points of the side f.
24538 p1 = org(*testtet);
24539 p2 = dest(*testtet);
24540 p3 = apex(*testtet);
24541 ori = orient3d(p1, p2, p3, testpt);
24542 if (ori > 0.0) {
24543 if (eps > 0.0) {
24544 // Is f on the hull.
24545 sym(*testtet, checktet);
24546 if (checktet.tet == dummytet) {
24547 if (iscoplanar(p1, p2, p3, testpt, ori, eps)) continue;
24548 }
24549 }
24550 // p is below f. outside.
24551 return false;
24552 }
24553 }
24554 testtet->loc = 0;
24555
24556 return true;
24557 }
24558
24559 ///////////////////////////////////////////////////////////////////////////////
24560 // //
24561 // insertaddpoints() Insert additional points in 'in->addpointlist'. //
24562 // //
24563 ///////////////////////////////////////////////////////////////////////////////
24564
24565 void tetgenmesh::insertaddpoints()
24566 {
24567 queue *flipqueue;
24568 triface searchtet;
24569 face checksh, checkseg;
24570 point newpoint;
24571 enum locateresult loc;
24572 REAL *attr;
24573 int index;
24574 int i, j;
24575
24576 if (!b->quiet) {
24577 printf("Insert additional points into mesh.\n");
24578 }
24579 // Initialize 'flipqueue'.
24580 flipqueue = new queue(sizeof(badface));
24581 recenttet.tet = dummytet;
24582
24583 index = 0;
24584 for (i = 0; i < in->numberofaddpoints; i++) {
24585 // Create a newpoint.
24586 makepoint(&newpoint);
24587 newpoint[0] = in->addpointlist[index++];
24588 newpoint[1] = in->addpointlist[index++];
24589 newpoint[2] = in->addpointlist[index++];
24590 // Copy new attributes (if available).
24591 if(in->addpointattributelist != (REAL *) NULL) {
24592 attr = in->addpointattributelist + in->numberofpointattributes * i;
24593 for (j = 0; j < in->numberofpointattributes; j++)
24594 newpoint[3 + j] = attr[j];
24595 }
24596 // Find the location of the inserted point.
24597 searchtet = recenttet;
24598 loc = locate(newpoint, &searchtet);
24599 if (loc != OUTSIDE) {
24600 if (loc != ONVERTEX) {
24601 loc = adjustlocate(newpoint, &searchtet, loc, b->epsilon);
24602 }
24603 }
24604 if (loc == OUTSIDE) {
24605 // Perform a brute-force search.
24606 tetrahedrons->traversalinit();
24607 searchtet.tet = tetrahedrontraverse();
24608 while (searchtet.tet != (tetrahedron *) NULL) {
24609 if (intettest(newpoint, &searchtet, b->epsilon)) {
24610 loc = adjustlocate(newpoint, &searchtet, OUTSIDE, b->epsilon);
24611 assert(loc != OUTSIDE);
24612 break;
24613 }
24614 searchtet.tet = tetrahedrontraverse();
24615 }
24616 }
24617 // Insert the point if it not lies outside or on a vertex.
24618 switch (loc) {
24619 case INTETRAHEDRON:
24620 setpointtype(newpoint, VOLVERTEX);
24621 splittetrahedron(newpoint, &searchtet, flipqueue);
24622 break;
24623 case ONFACE:
24624 tspivot(searchtet, checksh);
24625 if (checksh.sh != dummysh) {
24626 setpointtype(newpoint, FREESUBVERTEX);
24627 } else {
24628 setpointtype(newpoint, FREEVOLVERTEX);
24629 }
24630 splittetface(newpoint, &searchtet, flipqueue);
24631 break;
24632 case ONEDGE:
24633 tsspivot(&searchtet, &checkseg);
24634 if (checkseg.sh != dummysh) {
24635 setpointtype(newpoint, FREESEGVERTEX);
24636 setpoint2sh(newpoint, sencode(checkseg));
24637 } else {
24638 tspivot(searchtet, checksh);
24639 if (checksh.sh != dummysh) {
24640 setpointtype(newpoint, FREESUBVERTEX);
24641 } else {
24642 setpointtype(newpoint, VOLVERTEX);
24643 }
24644 }
24645 splittetedge(newpoint, &searchtet, flipqueue);
24646 break;
24647 case ONVERTEX:
24648 if (!b->quiet) {
24649 printf("Warning: Point (%.17g, %.17g, %.17g) falls on a vertex.\n",
24650 newpoint[0], newpoint[1], newpoint[2]);
24651 }
24652 break;
24653 case OUTSIDE:
24654 if (!b->quiet) {
24655 printf("Warning: Point (%.17g, %.17g, %.17g) lies outside the mesh.\n",
24656 newpoint[0], newpoint[1], newpoint[2]);
24657 }
24658 break;
24659 }
24660 // Remember the tetrahedron for next point searching.
24661 recenttet = searchtet;
24662 if (loc == ONVERTEX || loc == OUTSIDE) {
24663 pointdealloc(newpoint);
24664 } else {
24665 flip(flipqueue, NULL);
24666 }
24667 }
24668
24669 delete flipqueue;
24670 }
24671
24672 //
24673 // End of mesh reconstruction routines
24674 //
24675
24676 //
24677 // Begin of background mesh routines
24678 //
24679
24680 ///////////////////////////////////////////////////////////////////////////////
24681 // //
24682 // interpolatepointsize() Set a point size by interpolating in bgmesh. //
24683 // //
24684 // This function first finds the tet t in background mesh contains 'pt, then //
24685 // set the size of 'pt' by interpolating the sizes of the corners of t. //
24686 // //
24687 // 'bgmtet' is a suggesting tet in background mesh for locating 'pt' in it. //
24688 // It returns the tet containing 'pt'. //
24689 // //
24690 ///////////////////////////////////////////////////////////////////////////////
24691
24692 bool tetgenmesh::interpolatepointsize(point pt, triface* bgmtet, long *scount)
24693 {
24694 point bgmpt[4];
24695 enum locateresult loc;
24696 REAL vol, volpt[4], weights[4];
24697 int i;
24698
24699 loc = bgm->preciselocate(pt, bgmtet, bgm->tetrahedrons->items);
24700 if (loc == OUTSIDE) {
24701 // Perform a brute-force search.
24702 if (scount) (*scount)++;
24703 bgm->tetrahedrons->traversalinit(); // in bgm
24704 bgmtet->tet = bgm->tetrahedrontraverse(); // in bgm
24705 while (bgmtet->tet != (tetrahedron *) NULL) {
24706 if (bgm->intettest(pt, bgmtet, b->epsilon)) {
24707 loc = bgm->adjustlocate(pt, bgmtet, OUTSIDE, b->epsilon);
24708 assert(loc != OUTSIDE);
24709 break;
24710 }
24711 bgmtet->tet = bgm->tetrahedrontraverse(); // in bgm
24712 }
24713 }
24714 if (loc != OUTSIDE) {
24715 // Let p remember t.
24716 setpoint2bgmtet(pt, encode(*bgmtet)); // in m
24717 // Interpolate the point size.
24718 // get the corners of t.
24719 for (i = 0; i < 4; i++) bgmpt[i] = (point) bgmtet->tet[4 + i];
24720 // Calculate the weighted coordinates of p in t.
24721 vol = orient3d(bgmpt[0], bgmpt[1], bgmpt[2], bgmpt[3]);
24722 volpt[0] = orient3d(pt, bgmpt[1], bgmpt[2], bgmpt[3]);
24723 volpt[1] = orient3d(bgmpt[0], pt, bgmpt[2], bgmpt[3]);
24724 volpt[2] = orient3d(bgmpt[0], bgmpt[1], pt, bgmpt[3]);
24725 volpt[3] = orient3d(bgmpt[0], bgmpt[1], bgmpt[2], pt);
24726 for (i = 0; i < 4; i++) weights[i] = fabs(volpt[i] / vol);
24727 // Interpolate the solution for p.
24728 for (i = 0; i < bgm->in->numberofpointattributes; i++) {
24729 pt[3 + i] = weights[0] * bgmpt[0][3 + i]
24730 + weights[1] * bgmpt[1][3 + i]
24731 + weights[2] * bgmpt[2][3 + i]
24732 + weights[3] * bgmpt[3][3 + i];
24733 }
24734 } else {
24735 setpoint2bgmtet(pt, (tetrahedron) NULL); // in m
24736 }
24737 return loc != OUTSIDE;
24738 }
24739
24740 ///////////////////////////////////////////////////////////////////////////////
24741 // //
24742 // searchpointrecursive() Search point in background mesh recursively. //
24743 // //
24744 ///////////////////////////////////////////////////////////////////////////////
24745
24746 void tetgenmesh::searchpointrecursive(triface *curtet, long *scount)
24747 {
24748 triface searchtet, bgmtet;
24749 point searchpt;
24750 int idx, i;
24751
24752 // Mark t as proceed.
24753 infect(*curtet);
24754 // Get the opposite point of t.
24755 searchpt = oppo(*curtet);
24756 // Has p already been processed?
24757 if (pointmark(searchpt) >= 0) {
24758 // Find the location of p.
24759 bgmtet = bgm->recenttet;
24760 if (interpolatepointsize(searchpt, &bgmtet, scount)) {
24761 bgm->recenttet = bgmtet; // in bgm
24762 }
24763 // Mark p as processed.
24764 idx = pointmark(searchpt);
24765 setpointmark(searchpt, -idx - 1);
24766 }
24767 // Recursively do the above searching.
24768 adjustedgering(*curtet, CCW);
24769 for (i = 0; i < 3; i++) {
24770 fnext(*curtet, searchtet);
24771 symself(searchtet);
24772 if ((searchtet.tet != dummytet) && (!infected(searchtet))) {
24773 searchpointrecursive(&searchtet, scount);
24774 }
24775 enextself(*curtet);
24776 }
24777 }
24778
24779 ///////////////////////////////////////////////////////////////////////////////
24780 // //
24781 // interpolatesizemap() Interpolate the point sizes in the given size map.//
24782 // //
24783 // The size map is specified on each node of the background mesh. The points //
24784 // of current mesh get their sizes by interpolating. //
24785 // //
24786 // This function operation on two meshes simultaneously, the current mesh m, //
24787 // and the background mesh bgm. After this function, each point p in m will //
24788 // have a pointer to a tet of bgm. //
24789 // //
24790 ///////////////////////////////////////////////////////////////////////////////
24791
24792 void tetgenmesh::interpolatesizemap()
24793 {
24794 triface tetloop, bgmtet;
24795 point searchpt;
24796 long scount;
24797 int idx, i;
24798
24799 if (b->verbose) {
24800 printf(" Interpolating size map.\n");
24801 }
24802 scount = 0l;
24803
24804 tetrahedrons->traversalinit();
24805 tetloop.tet = tetrahedrontraverse();
24806 while (tetloop.tet != (tetrahedron *) NULL) {
24807 if (!infected(tetloop)) {
24808 // Found an traversed tet t.
24809 tetloop.loc = 0;
24810 tetloop.ver = 0;
24811 // Locate the three vertices of current face of t.
24812 for (i = 0; i < 3; i++) {
24813 searchpt = org(tetloop);
24814 // Has p already been processed?
24815 if (pointmark(searchpt) >= 0) {
24816 // Interpolate p in background mesh.
24817 bgmtet = bgm->recenttet;
24818 if (interpolatepointsize(searchpt, &bgmtet, &scount)) {
24819 bgm->recenttet = bgmtet;
24820 }
24821 // Mark p as processed.
24822 idx = pointmark(searchpt);
24823 setpointmark(searchpt, -idx - 1);
24824 }
24825 enextself(tetloop);
24826 }
24827 // Recursively do the above searching in the neighbring tets of t.
24828 searchpointrecursive(&tetloop, &scount);
24829 }
24830 tetloop.tet = tetrahedrontraverse();
24831 }
24832
24833 // Have searched all points. Unmark tets.
24834 tetrahedrons->traversalinit();
24835 tetloop.tet = tetrahedrontraverse();
24836 while (tetloop.tet != (tetrahedron *) NULL) {
24837 assert(infected(tetloop));
24838 uninfect(tetloop);
24839 tetloop.tet = tetrahedrontraverse();
24840 }
24841 // Unmark points.
24842 points->traversalinit(); // in m
24843 searchpt = pointtraverse(); // in m
24844 while (searchpt != (point) NULL) {
24845 idx = pointmark(searchpt);
24846 assert(idx < 0);
24847 setpointmark(searchpt, -(idx + 1));
24848 searchpt = pointtraverse(); // in m
24849 }
24850
24851 #ifdef SELF_CHECK
24852 if (b->verbose) {
24853 printf(" %ld brute-force searches.\n", scount);
24854 }
24855 #endif
24856 }
24857
24858 //
24859 // End of of background mesh routines
24860 //
24861
24862 //
24863 // Begin of Delaunay refinement routines
24864 //
24865
24866 ///////////////////////////////////////////////////////////////////////////////
24867 // //
24868 // calclocalfeaturesizes() Calculate local feature sizes of all points. //
24869 // //
24870 // Given a PLC X, the local feature size, lfs_d(x), of any point x in X is //
24871 // defined as the distance from x to two features of X which are of dim no //
24872 // large than d. For example, lfs_0(x) is the distance from x to the second //
24873 // nearest point of X. Let lfs(x) = lfs_2(x). //
24874 // //
24875 ///////////////////////////////////////////////////////////////////////////////
24876
24877 void tetgenmesh::calclocalfeaturesizes()
24878 {
24879 list *tetlist, *verlist;
24880 tetrahedron tetptr;
24881 triface starttet;
24882 face checksh, checkseg;
24883 point ploop, ver[3];
24884 point ptlfslarge, ptlfssmall;
24885 enum locateresult loc;
24886 REAL prj[3], lfs[3], len;
24887 REAL lfslarge, lfssmall;
24888 int i, j;
24889
24890 if (b->verbose > 0) {
24891 printf(" Calculating local feature sizes.\n");
24892 }
24893
24894 // Construct a map from points to tetrahedra.
24895 makepoint2tetmap();
24896 // Initialize working lists.
24897 tetlist = new list(sizeof(triface), NULL, 256);
24898 verlist = new list(sizeof(point *), NULL, 256);
24899 // Initialize bookkeeping variables.
24900 ptlfslarge = ptlfssmall = (point) NULL;
24901 lfslarge = lfssmall = 0.0;
24902
24903 points->traversalinit();
24904 ploop = pointtraverse();
24905 while (ploop != (point) NULL) {
24906 tetptr = point2tet(ploop);
24907 // Only calculate lfs(p) if it is in the mesh.
24908 if (tetptr != (tetrahedron) NULL) {
24909 decode(tetptr, starttet);
24910 tetlist->append(&starttet);
24911 formstarpolyhedron(ploop, tetlist, verlist, true); // Form star(p).
24912 lfs[0] = lfs[1] = lfs[2] = longest;
24913 // Calculate lfs_0(p).
24914 for (i = 0; i < verlist->len(); i++) {
24915 ver[0] = * (point *)(* verlist)[i];
24916 len = distance(ploop, ver[0]);
24917 if (lfs[0] > len) lfs[0] = len;
24918 }
24919 // Claculate lfs_1(p).
24920 for (i = 0; i < tetlist->len(); i++) {
24921 starttet = * (triface *)(* tetlist)[i];
24922 starttet.ver = 0;
24923 for (j = 0; j < 3; j++) {
24924 tsspivot(&starttet, &checkseg);
24925 if (checkseg.sh != dummysh) {
24926 checkseg.shver = 0;
24927 ver[0] = sorg(checkseg);
24928 ver[1] = sdest(checkseg);
24929 projpt2edge(ploop, ver[0], ver[1], prj);
24930 loc = locateseg(prj, &checkseg);
24931 if (loc != OUTSIDE) {
24932 len = distance(ploop, prj);
24933 if (lfs[1] > len) lfs[1] = len;
24934 }
24935 }
24936 enextself(starttet);
24937 }
24938 }
24939 // Claculate lfs_2(p).
24940 for (i = 0; i < tetlist->len(); i++) {
24941 starttet = * (triface *)(* tetlist)[i];
24942 tspivot(starttet, checksh);
24943 if (checksh.sh != dummysh) {
24944 ver[0] = sorg(checksh);
24945 ver[1] = sdest(checksh);
24946 ver[2] = sapex(checksh);
24947 projpt2face(ploop, ver[0], ver[1], ver[2], prj);
24948 abovepoint = facetabovepointarray[shellmark(checksh)];
24949 if (abovepoint == (point) NULL) {
24950 getfacetabovepoint(&checksh);
24951 }
24952 loc = locatesub(prj, &checksh, 1, b->epsilon);
24953 if (loc != OUTSIDE) {
24954 len = distance(ploop, prj);
24955 if (lfs[2] > len) lfs[2] = len;
24956 }
24957 }
24958 }
24959 // Decide lfs(p).
24960 ploop[pointlfsindex] = lfs[0];
24961 if (ploop[pointlfsindex] > lfs[1]) ploop[pointlfsindex] = lfs[1];
24962 if (ploop[pointlfsindex] > lfs[2]) ploop[pointlfsindex] = lfs[2];
24963 // Update statistics.
24964 if (ptlfslarge == (point) NULL) {
24965 ptlfslarge = ptlfssmall = ploop;
24966 lfslarge = lfssmall = ploop[pointlfsindex];
24967 } else {
24968 if (lfslarge < ploop[pointlfsindex]) {
24969 lfslarge = ploop[pointlfsindex];
24970 ptlfslarge = ploop;
24971 }
24972 if (lfssmall > ploop[pointlfsindex]) {
24973 lfssmall = ploop[pointlfsindex];
24974 ptlfssmall = ploop;
24975 }
24976 }
24977 // Clear working lists.
24978 tetlist->clear();
24979 verlist->clear();
24980 }
24981 ploop = pointtraverse();
24982 }
24983
24984 if (b->verbose > 1) {
24985 printf(" smallest lfs = %g (%d).\n", lfssmall, pointmark(ptlfssmall));
24986 printf(" largest lfs = %g (%d).\n", lfslarge, pointmark(ptlfslarge));
24987 }
24988
24989 delete tetlist;
24990 delete verlist;
24991 }
24992
24993 ///////////////////////////////////////////////////////////////////////////////
24994 // //
24995 // marksharpsubsegs() Mark all sharp subsegments. //
24996 // //
24997 // A segment is sharp if it is between two facets that form a small dihedral //
24998 // angle (< 'dihedbound', given in degrees). It is marked as SHARP. //
24999 // //
25000 ///////////////////////////////////////////////////////////////////////////////
25001
25002 void tetgenmesh::marksharpsubsegs(REAL dihedbound)
25003 {
25004 list *spinshlist;
25005 triface adjtet;
25006 face startsh, spinsh, neighsh;
25007 face segloop, prevseg, nextseg;
25008 point eorg, edest;
25009 enum shestype stype;
25010 REAL angle, smallang;
25011 bool issharp;
25012 int scount;
25013 int i;
25014
25015 if (b->verbose > 0) {
25016 printf(" Marking sharp subsegments.\n");
25017 }
25018
25019 smallang = dihedbound * PI / 180.;
25020 scount = 0;
25021 eorg = edest = (point) NULL; // avoid compilation warnings.
25022 // Initial working list.
25023 spinshlist = new list(sizeof(face), NULL, 256);
25024
25025 // A segment s may be split into many subsegments. Operate the one which
25026 // contains the origin of s. Then mark the rest of subsegments.
25027 subsegs->traversalinit();
25028 segloop.sh = shellfacetraverse(subsegs);
25029 while (segloop.sh != (shellface *) NULL) {
25030 segloop.shver = 0;
25031 senext2(segloop, prevseg);
25032 spivotself(prevseg);
25033 if (prevseg.sh == dummysh) {
25034 // Operate on this seg.
25035 issharp = false;
25036 segloop.shver = 0;
25037 spivot(segloop, startsh);
25038 if (startsh.sh != dummysh) {
25039 spivot(startsh, spinsh);
25040 if (spinsh.sh != startsh.sh) {
25041 // This subface is not self-bonded.
25042 eorg = sorg(segloop);
25043 edest = sdest(segloop);
25044 // Get all incident subfaces around the seg.
25045 spinsh = startsh;
25046 do {
25047 if (sorg(spinsh) != eorg) {
25048 sesymself(spinsh);
25049 }
25050 spinshlist->append(&spinsh);
25051 spivotself(spinsh);
25052 } while (spinsh.sh != startsh.sh);
25053 }
25054 // Check the pair of adjacent subfaces for small angle.
25055 spinsh = * (face *)(* spinshlist)[0];
25056 for (i = 1; i <= spinshlist->len() && !issharp; i++) {
25057 if (i == spinshlist->len()) {
25058 neighsh = * (face *)(* spinshlist)[0];
25059 } else {
25060 neighsh = * (face *)(* spinshlist)[i];
25061 }
25062 // Only do test when the spinsh is faceing inward.
25063 stpivot(spinsh, adjtet);
25064 if (adjtet.tet != dummytet) {
25065 angle = facedihedral(eorg, edest, sapex(spinsh), sapex(neighsh));
25066 issharp = angle < smallang;
25067 }
25068 spinsh = neighsh;
25069 }
25070 spinshlist->clear();
25071 }
25072 // Set type for this segment (inclusing subsegments).
25073 stype = issharp ? SHARP : NSHARPNSKINNY;
25074 scount += issharp ? 1 : 0;
25075 setshelltype(segloop, stype);
25076 senext(segloop, nextseg);
25077 spivotself(nextseg);
25078 while (nextseg.sh != dummysh) {
25079 nextseg.shver = 0;
25080 setshelltype(nextseg, stype);
25081 senextself(nextseg);
25082 spivotself(nextseg);
25083 }
25084 }
25085 segloop.sh = shellfacetraverse(subsegs);
25086 }
25087
25088 if (b->verbose > 0) {
25089 printf(" %d sharp segments.\n", scount);
25090 }
25091 delete spinshlist;
25092 }
25093
25094 ///////////////////////////////////////////////////////////////////////////////
25095 // //
25096 // markskinnysubfaces() Mark all skinny subfaces. //
25097 // //
25098 // A subface is skinny if it has an angle smaller than 'anglebound' and the //
25099 // two edges form the angle are both segments. Such subface is not be able //
25100 // to refine. It will be marked as type SKINNY. //
25101 // //
25102 // This procedure operates in two phases. The first phase finds some skinny //
25103 // subfaces by checking the angles of subfaces. The second phase finds all //
25104 // skinny subfaces by a neighbor-first search. //
25105 // //
25106 ///////////////////////////////////////////////////////////////////////////////
25107
25108 void tetgenmesh::markskinnysubfaces(REAL anglebound)
25109 {
25110 list *skinnyshlist;
25111 face subloop, checksub;
25112 face startsh, neighsh;
25113 face seg1, seg2, checkseg;
25114 point pa, pb, pc;
25115 enum shestype shty;
25116 REAL smallang, angle;
25117 int i, j;
25118
25119 if (b->verbose > 0) {
25120 printf(" Marking skinny subfaces.\n");
25121 }
25122
25123 smallang = anglebound * PI / 180.;
25124 // Initial working list.
25125 skinnyshlist = new list(sizeof(face), NULL, subfaces->items);
25126
25127 // Loop the set of subfaces, collect some skinny ones.
25128 subfaces->traversalinit();
25129 subloop.sh = shellfacetraverse(subfaces);
25130 while (subloop.sh != (shellface *) NULL) {
25131 // Check the three angles of subloop;
25132 for (i = 0; i < 3; i++) {
25133 sspivot(subloop, seg1);
25134 if (seg1.sh != dummysh) {
25135 senext2(subloop, checksub);
25136 sspivot(checksub, seg2);
25137 if (seg2.sh != dummysh) {
25138 pa = sorg(subloop);
25139 pb = sdest(subloop);
25140 pc = sapex(subloop);
25141 angle = interiorangle(pa, pb, pc, NULL);
25142 if (angle < smallang) {
25143 // It is skinny!
25144 setshelltype(subloop, SKINNY);
25145 skinnyshlist->append(&subloop);
25146 break;
25147 }
25148 }
25149 }
25150 senextself(subloop);
25151 }
25152 subloop.sh = shellfacetraverse(subfaces);
25153 }
25154
25155 // Next finds all skinny subfaces.
25156 for (i = 0; i < skinnyshlist->len(); i++) {
25157 startsh = * (face *)(* skinnyshlist)[i];
25158 shty = shelltype(startsh);
25159 for (j = 0; j < 3; j++) {
25160 sspivot(startsh, checkseg);
25161 if (checkseg.sh == dummysh) {
25162 spivot(startsh, neighsh);
25163 if (shelltype(neighsh) != shty) {
25164 setshelltype(neighsh, shty);
25165 skinnyshlist->append(&neighsh);
25166 }
25167 }
25168 senextself(startsh);
25169 }
25170 }
25171
25172 if (b->verbose > 0) {
25173 printf(" %d skinny subfaces.\n", skinnyshlist->len());
25174 }
25175 delete skinnyshlist;
25176 }
25177
25178 ///////////////////////////////////////////////////////////////////////////////
25179 // //
25180 // enqueuebadtet() Add a tetrahedron into the queue. //
25181 // //
25182 ///////////////////////////////////////////////////////////////////////////////
25183
25184 void tetgenmesh::enqueuebadtet(triface* testtet, REAL ratio2, REAL* cent)
25185 {
25186 badface *newbadtet;
25187 int queuenumber;
25188 int i;
25189
25190 // Allocate space for the bad tetrahedron.
25191 newbadtet = (badface *) badtetrahedrons->alloc();
25192 newbadtet->tt = *testtet;
25193 newbadtet->key = ratio2;
25194 if (cent != NULL) {
25195 for (i = 0; i < 3; i++) newbadtet->cent[i] = cent[i];
25196 } else {
25197 for (i = 0; i < 3; i++) newbadtet->cent[i] = 0.0;
25198 }
25199 newbadtet->forg = org(*testtet);
25200 newbadtet->fdest = dest(*testtet);
25201 newbadtet->fapex = apex(*testtet);
25202 newbadtet->foppo = oppo(*testtet);
25203 newbadtet->nextitem = (badface *) NULL;
25204 // Determine the appropriate queue to put the bad tetrahedron into.
25205 if (ratio2 > b->goodratio) {
25206 queuenumber = (int) ((ratio2 - b->goodratio) / 0.5);
25207 // 'queuenumber' may overflow (negative) caused by a very large ratio.
25208 if ((queuenumber > 63) || (queuenumber < 0)) {
25209 queuenumber = 63;
25210 }
25211 } else {
25212 // It's not a bad ratio; put the tet in the lowest-priority queue.
25213 queuenumber = 0;
25214 }
25215 // Add the tetrahedron to the end of a queue.
25216 *tetquetail[queuenumber] = newbadtet;
25217 // Maintain a pointer to the NULL pointer at the end of the queue.
25218 tetquetail[queuenumber] = &newbadtet->nextitem;
25219 if (b->verbose > 2) {
25220 printf(" Queueing bad tet: (%d, %d, %d, %d), ratio %g, qnum %d.\n",
25221 pointmark(newbadtet->forg), pointmark(newbadtet->fdest),
25222 pointmark(newbadtet->fapex), pointmark(newbadtet->foppo),
25223 sqrt(ratio2), queuenumber);
25224 }
25225 }
25226
25227 ///////////////////////////////////////////////////////////////////////////////
25228 // //
25229 // enqueueencsub() Add an encroached subface into the queue. //
25230 // //
25231 ///////////////////////////////////////////////////////////////////////////////
25232
25233 void tetgenmesh::enqueueencsub(face* testsub, point encpt, int quenumber,
25234 REAL* cent)
25235 {
25236 badface *encsub;
25237 int i;
25238
25239 encsub = (badface *) badsubfaces->alloc();
25240 encsub->ss = *testsub;
25241 encsub->forg = sorg(*testsub);
25242 encsub->fdest = sdest(*testsub);
25243 encsub->fapex = sapex(*testsub);
25244 encsub->foppo = (point) encpt;
25245 if (quenumber == 2) {
25246 for (i = 0; i < 3; i++) encsub->cent[i] = 0.0;
25247 } else {
25248 for (i = 0; i < 3; i++) encsub->cent[i] = cent[i];
25249 }
25250 encsub->nextitem = (badface *) NULL;
25251 // Set the pointer of 'encsubseg' into 'testsub'. It has two purposes:
25252 // (1) We can regonize it is encroached; (2) It is uniquely queued.
25253 setshell2badface(encsub->ss, encsub);
25254 // Add the subface to the end of a queue (quenumber = 2, high priority).
25255 *subquetail[quenumber] = encsub;
25256 // Maintain a pointer to the NULL pointer at the end of the queue.
25257 subquetail[quenumber] = &encsub->nextitem;
25258 if (b->verbose > 2) {
25259 printf(" Queuing subface (%d, %d, %d) [%d].\n", pointmark(encsub->forg),
25260 pointmark(encsub->fdest), pointmark(encsub->fapex), quenumber);
25261 }
25262 }
25263
25264 ///////////////////////////////////////////////////////////////////////////////
25265 // //
25266 // dequeuebadtet() Remove a tetrahedron from the front of the queue. //
25267 // //
25268 ///////////////////////////////////////////////////////////////////////////////
25269
25270 tetgenmesh::badface* tetgenmesh::dequeuebadtet()
25271 {
25272 badface *result;
25273 int queuenumber;
25274
25275 // Look for a nonempty queue.
25276 for (queuenumber = 63; queuenumber >= 0; queuenumber--) {
25277 result = tetquefront[queuenumber];
25278 if (result != (badface *) NULL) {
25279 // Remove the tetrahedron from the queue.
25280 tetquefront[queuenumber] = result->nextitem;
25281 // Maintain a pointer to the NULL pointer at the end of the queue.
25282 if (tetquefront[queuenumber] == (badface *) NULL) {
25283 tetquetail[queuenumber] = &tetquefront[queuenumber];
25284 }
25285 return result;
25286 }
25287 }
25288 return (badface *) NULL;
25289 }
25290
25291 ///////////////////////////////////////////////////////////////////////////////
25292 // //
25293 // dequeueencsub() Remove an enc-subface from the front of the queue. //
25294 // //
25295 ///////////////////////////////////////////////////////////////////////////////
25296
25297 tetgenmesh::badface* tetgenmesh::dequeueencsub(int* pquenumber)
25298 {
25299 badface *result;
25300 int quenumber;
25301
25302 // Look for a nonempty queue.
25303 for (quenumber = 2; quenumber >= 0; quenumber--) {
25304 result = subquefront[quenumber];
25305 if (result != (badface *) NULL) {
25306 // Remove the badface from the queue.
25307 subquefront[quenumber] = result->nextitem;
25308 // Maintain a pointer to the NULL pointer at the end of the queue.
25309 if (subquefront[quenumber] == (badface *) NULL) {
25310 subquetail[quenumber] = &subquefront[quenumber];
25311 }
25312 *pquenumber = quenumber;
25313 return result;
25314 }
25315 }
25316 return (badface *) NULL;
25317 }
25318
25319 ///////////////////////////////////////////////////////////////////////////////
25320 // //
25321 // checkseg4encroach() Check a subsegment to see if it is encroached. //
25322 // //
25323 // A segment s is encroached if there is a vertex lies inside or on its dia- //
25324 // metral circumsphere, i.e., s faces an angle theta >= 90 degrees. //
25325 // //
25326 // If 'testpt' (p) != NULL, only test if 'testseg' (s) is encroached by it, //
25327 // else, check all apexes of faces around s. Return TRUE if s is encroached. //
25328 // If and 'enqflag' is TRUE, add it into 'badsubsegs' if s is encroached. //
25329 // //
25330 // If 'prefpt' != NULL, it returns the reference point (defined in my paper) //
25331 // if it exists. This point is will be used to split s. //
25332 // //
25333 ///////////////////////////////////////////////////////////////////////////////
25334
25335 bool tetgenmesh::checkseg4encroach(face* testseg, point testpt, point* prefpt,
25336 bool enqflag)
25337 {
25338 badface *encsubseg;
25339 triface starttet, spintet;
25340 point eorg, edest, eapex, encpt;
25341 REAL cent[3], radius, dist, diff;
25342 REAL maxradius;
25343 bool enq;
25344 int hitbdry;
25345
25346 eorg = sorg(*testseg);
25347 edest = sdest(*testseg);
25348 cent[0] = 0.5 * (eorg[0] + edest[0]);
25349 cent[1] = 0.5 * (eorg[1] + edest[1]);
25350 cent[2] = 0.5 * (eorg[2] + edest[2]);
25351 radius = distance(cent, eorg);
25352
25353 enq = false;
25354 maxradius = 0.0;
25355 if (testpt == (point) NULL) {
25356 // Check if it is encroached by traversing all faces containing it.
25357 sstpivot(testseg, &starttet);
25358 eapex = apex(starttet);
25359 spintet = starttet;
25360 hitbdry = 0;
25361 do {
25362 dist = distance(cent, apex(spintet));
25363 diff = dist - radius;
25364 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25365 if (diff <= 0.0) {
25366 // s is encroached.
25367 enq = true;
25368 if (prefpt != (point *) NULL) {
25369 // Find the reference point.
25370 encpt = apex(spintet);
25371 circumsphere(eorg, edest, encpt, NULL, NULL, &dist);
25372 if (dist > maxradius) {
25373 // Rememebr this point.
25374 *prefpt = encpt;
25375 maxradius = dist;
25376 }
25377 } else {
25378 break;
25379 }
25380 }
25381 if (!fnextself(spintet)) {
25382 hitbdry++;
25383 if (hitbdry < 2) {
25384 esym(starttet, spintet);
25385 if (!fnextself(spintet)) {
25386 hitbdry++;
25387 }
25388 }
25389 }
25390 } while (apex(spintet) != eapex && (hitbdry < 2));
25391 } else {
25392 // Only check if 'testseg' is encroached by 'testpt'.
25393 dist = distance(cent, testpt);
25394 diff = dist - radius;
25395 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25396 enq = (diff <= 0.0);
25397 }
25398
25399 if (enq && enqflag) {
25400 if (b->verbose > 2) {
25401 printf(" Queuing encroaching subsegment (%d, %d).\n",
25402 pointmark(eorg), pointmark(edest));
25403 }
25404 encsubseg = (badface *) badsubsegs->alloc();
25405 encsubseg->ss = *testseg;
25406 encsubseg->forg = eorg;
25407 encsubseg->fdest = edest;
25408 encsubseg->foppo = (point) NULL; // Not used.
25409 // Set the pointer of 'encsubseg' into 'testseg'. It has two purposes:
25410 // (1) We can regonize it is encroached; (2) It is uniquely queued.
25411 setshell2badface(encsubseg->ss, encsubseg);
25412 }
25413
25414 return enq;
25415 }
25416
25417 ///////////////////////////////////////////////////////////////////////////////
25418 // //
25419 // checksub4encroach() Check a subface to see if it is encroached. //
25420 // //
25421 // A subface f is encroached if there is a vertex inside or on its diametral //
25422 // circumsphere. //
25423 // //
25424 // If 'testpt (p) != NULL', test if 'testsub' (f) is encroached by it, else, //
25425 // test if f is encroached by one of the two opposites of the adjacent tets. //
25426 // Return TRUE if f is encroached and queue it if 'enqflag' is set. //
25427 // //
25428 ///////////////////////////////////////////////////////////////////////////////
25429
25430 bool tetgenmesh::checksub4encroach(face* testsub, point testpt, bool enqflag)
25431 {
25432 triface abuttet;
25433 point forg, fdest, fapex, encpt;
25434 REAL cent[3];
25435 REAL radius, dist, diff;
25436 bool enq, ncollinear;
25437 int quenumber;
25438
25439 forg = sorg(*testsub);
25440 fdest = sdest(*testsub);
25441 fapex = sapex(*testsub);
25442 ncollinear = circumsphere(forg, fdest, fapex, NULL, cent, &radius);
25443 if (!ncollinear) return false; // Not a valid subface.
25444
25445 enq = false;
25446 encpt = (point) NULL;
25447 if (testpt == (point) NULL) {
25448 stpivot(*testsub, abuttet);
25449 if (abuttet.tet != dummytet) {
25450 dist = distance(cent, oppo(abuttet));
25451 diff = dist - radius;
25452 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25453 enq = (diff <= 0.0);
25454 if (enq) encpt = oppo(abuttet);
25455 }
25456 if (!enq) {
25457 sesymself(*testsub);
25458 stpivot(*testsub, abuttet);
25459 if (abuttet.tet != dummytet) {
25460 dist = distance(cent, oppo(abuttet));
25461 diff = dist - radius;
25462 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25463 enq = (diff <= 0.0);
25464 if (enq) encpt = oppo(abuttet);
25465 }
25466 }
25467 } else {
25468 dist = distance(cent, testpt);
25469 diff = dist - radius;
25470 if (fabs(diff) / radius <= b->epsilon) diff = 0.0; // Rounding.
25471 enq = (diff <= 0.0);
25472 }
25473
25474 if (enq && enqflag) {
25475 /* REAL prj[3], ori1, ori2, ori3;
25476 bool inflag;
25477 // Test if encpt is inside the face.
25478 if (encpt) {
25479 projpt2face(encpt, forg, fdest, fapex, prj);
25480 } else {
25481 assert(testpt);
25482 projpt2face(testpt, forg, fdest, fapex, prj);
25483 }
25484 abovepoint = facetabovepointarray[shellmark(*testsub)];
25485 if (abovepoint == (point) NULL) {
25486 getfacetabovepoint(testsub);
25487 }
25488 ori1 = orient3d(forg, fdest, abovepoint, prj);
25489 ori2 = orient3d(fdest, fapex, abovepoint, prj);
25490 inflag = (ori1 * ori2 >= 0.0);
25491 if (inflag) {
25492 ori3 = orient3d(fapex, forg, abovepoint, prj);
25493 inflag = (ori2 * ori3 >= 0.0);
25494 }
25495 // Decide which queue (1 or 0) to put s (1 has higher priority).
25496 quenumber = (inflag ? 1 : 0); */
25497 quenumber = 0;
25498 enqueueencsub(testsub, encpt, quenumber, cent);
25499 }
25500
25501 return enq;
25502 }
25503
25504 ///////////////////////////////////////////////////////////////////////////////
25505 // //
25506 // checkseg4badqual() Check if a segment is longer than it is allowed. //
25507 // //
25508 ///////////////////////////////////////////////////////////////////////////////
25509
25510 bool tetgenmesh::checkseg4badqual(face* testseg, bool enqflag)
25511 {
25512 badface *encsubseg;
25513 point eorg, edest;
25514 REAL dist;
25515 bool enq;
25516
25517 eorg = sorg(*testseg);
25518 edest = sdest(*testseg);
25519 dist = distance(eorg, edest);
25520
25521 enq = dist > areabound(*testseg);
25522
25523 if (enq && enqflag) {
25524 if (b->verbose > 2) {
25525 printf(" Queuing badqual subsegment (%d, %d).\n",
25526 pointmark(eorg), pointmark(edest));
25527 }
25528 encsubseg = (badface *) badsubsegs->alloc();
25529 encsubseg->ss = *testseg;
25530 encsubseg->forg = eorg;
25531 encsubseg->fdest = edest;
25532 encsubseg->foppo = NULL;
25533 // Set the pointer of 'encsubseg' into 'testseg'. It has two purposes:
25534 // (1) We can regonize it is encroached; (2) It is uniquely queued.
25535 setshell2badface(encsubseg->ss, encsubseg);
25536 }
25537
25538 return enq;
25539 }
25540
25541 ///////////////////////////////////////////////////////////////////////////////
25542 // //
25543 // checksub4badqual() Test if the quality of a subface is bad. //
25544 // //
25545 // A subface has bad quality if: (1) its minimum internal angle is smaller //
25546 // than 20 degree; or (2) its area is larger than a maximum area condition. //
25547 // Return TRUE if it is bad. //
25548 // //
25549 ///////////////////////////////////////////////////////////////////////////////
25550
25551 bool tetgenmesh::checksub4badqual(face* testsub, bool enqflag)
25552 {
25553 face sametestsub;
25554 face subseg1, subseg2;
25555 point torg, tdest, tapex;
25556 point anglevertex;
25557 REAL dxod, dyod, dzod;
25558 REAL dxda, dyda, dzda;
25559 REAL dxao, dyao, dzao;
25560 REAL dxod2, dyod2, dzod2;
25561 REAL dxda2, dyda2, dzda2;
25562 REAL dxao2, dyao2, dzao2;
25563 REAL apexlen, orglen, destlen;
25564 REAL angle, area;
25565 bool enq;
25566
25567 enq = false;
25568 torg = sorg(*testsub);
25569 tdest = sdest(*testsub);
25570 tapex = sapex(*testsub);
25571 dxod = torg[0] - tdest[0];
25572 dyod = torg[1] - tdest[1];
25573 dzod = torg[2] - tdest[2];
25574 dxda = tdest[0] - tapex[0];
25575 dyda = tdest[1] - tapex[1];
25576 dzda = tdest[2] - tapex[2];
25577 dxao = tapex[0] - torg[0];
25578 dyao = tapex[1] - torg[1];
25579 dzao = tapex[2] - torg[2];
25580 dxod2 = dxod * dxod;
25581 dyod2 = dyod * dyod;
25582 dzod2 = dzod * dzod;
25583 dxda2 = dxda * dxda;
25584 dyda2 = dyda * dyda;
25585 dzda2 = dzda * dzda;
25586 dxao2 = dxao * dxao;
25587 dyao2 = dyao * dyao;
25588 dzao2 = dzao * dzao;
25589 // Find the lengths of the triangle's three edges.
25590 apexlen = dxod2 + dyod2 + dzod2;
25591 orglen = dxda2 + dyda2 + dzda2;
25592 destlen = dxao2 + dyao2 + dzao2;
25593 if ((apexlen < orglen) && (apexlen < destlen)) {
25594 // The edge opposite the apex is shortest.
25595 // Find the square of the cosine of the angle at the apex.
25596 angle = dxda * dxao + dyda * dyao + dzda * dzao;
25597 angle = angle * angle / (orglen * destlen);
25598 anglevertex = tapex;
25599 senext(*testsub, sametestsub);
25600 sspivot(sametestsub, subseg1);
25601 senext2(*testsub, sametestsub);
25602 sspivot(sametestsub, subseg2);
25603 } else if (orglen < destlen) {
25604 // The edge opposite the origin is shortest.
25605 // Find the square of the cosine of the angle at the origin.
25606 angle = dxod * dxao + dyod * dyao + dzod * dzao;
25607 angle = angle * angle / (apexlen * destlen);
25608 anglevertex = torg;
25609 sspivot(*testsub, subseg1);
25610 senext2(*testsub, sametestsub);
25611 sspivot(sametestsub, subseg2);
25612 } else {
25613 // The edge opposite the destination is shortest.
25614 // Find the square of the cosine of the angle at the destination.
25615 angle = dxod * dxda + dyod * dyda + dzod * dzda;
25616 angle = angle * angle / (apexlen * orglen);
25617 anglevertex = tdest;
25618 sspivot(*testsub, subseg1);
25619 senext(*testsub, sametestsub);
25620 sspivot(sametestsub, subseg2);
25621 }
25622
25623 // Check if both edges that form the angle are segments.
25624 // if ((subseg1.sh != dummysh) && (subseg2.sh != dummysh)) {
25625 if (shelltype(*testsub) == SKINNY) {
25626 // The angle is a segment intersection. Don't add this bad subface to
25627 // the list; there's nothing that can be done about a small angle
25628 // between two segments.
25629 angle = 0.0;
25630 }
25631
25632 // Check whether the angle is smaller than permitted.
25633 if (angle > b->goodangle) {
25634 enq = true;
25635 }
25636
25637 if (!enq && varconstraint && areabound(*testsub) > 0.0) {
25638 // Check whether the area is larger than desired. A variation form of
25639 // Heron's formula which only uses the squares of the edge lengthes
25640 // is used to calculated the area of a 3D triangle.
25641 area = apexlen + orglen - destlen;
25642 area = area * area;
25643 area = 4 * apexlen * orglen - area;
25644 area = 0.25 * sqrt(fabs(area));
25645 enq = area > areabound(*testsub);
25646 }
25647
25648 if (enq && enqflag) {
25649 enqueueencsub(testsub, NULL, 2, NULL);
25650 }
25651
25652 return enq;
25653 }
25654
25655 ///////////////////////////////////////////////////////////////////////////////
25656 // //
25657 // checktet4badqual() Test a tetrahedron for quality measures. //
25658 // //
25659 // Tests a tetrahedron to see if it satisfies the minimum ratio condition //
25660 // and the maximum volume condition. Tetrahedra that aren't upto spec are //
25661 // added to the bad tetrahedron queue. //
25662 // //
25663 ///////////////////////////////////////////////////////////////////////////////
25664
25665 bool tetgenmesh::checktet4badqual(triface* testtet, bool enqflag)
25666 {
25667 badface *newbadtet;
25668 point pa, pb, pc, pd, pe1, pe2;
25669 REAL vda[3], vdb[3], vdc[3];
25670 REAL vab[3], vbc[3], vca[3];
25671 REAL N[4][3], A[4][4], rhs[4], D;
25672 REAL elen[6], circumcent[3];
25673 REAL bicent[3], offcent[3];
25674 REAL volume, L, q, cosd;
25675 REAL radius2, smlen2, ratio2;
25676 REAL dist, sdist, split;
25677 bool enq;
25678 int indx[4];
25679 int queuenumber;
25680 int sidx, i, j;
25681
25682 pa = (point) testtet->tet[4];
25683 pb = (point) testtet->tet[5];
25684 pc = (point) testtet->tet[6];
25685 pd = (point) testtet->tet[7];
25686
25687 // Avoid compile warnings.
25688 pe1 = pe2 = (point) NULL;
25689 radius2 = 0.0;
25690
25691 // Get the edge vectors vda: d->a, vdb: d->b, vdc: d->c.
25692 // Set the matrix A = [vda, vdb, vdc]^T.
25693 for (i = 0; i < 3; i++) A[0][i] = vda[i] = pa[i] - pd[i];
25694 for (i = 0; i < 3; i++) A[1][i] = vdb[i] = pb[i] - pd[i];
25695 for (i = 0; i < 3; i++) A[2][i] = vdc[i] = pc[i] - pd[i];
25696 // Get the rest edge vectors
25697 for (i = 0; i < 3; i++) vab[i] = pb[i] - pa[i];
25698 for (i = 0; i < 3; i++) vbc[i] = pc[i] - pb[i];
25699 for (i = 0; i < 3; i++) vca[i] = pa[i] - pc[i];
25700
25701 // Lu-decompose the matrix A.
25702 lu_decmp(A, 3, indx, &D, 0);
25703 // Get the volume of abcd.
25704 volume = (A[indx[0]][0] * A[indx[1]][1] * A[indx[2]][2]) / 6.0;
25705 if (volume < 0.0) volume = -volume;
25706 // Compare the volume to average edge length of abcd.
25707 elen[0] = dot(vda, vda);
25708 elen[1] = dot(vdb, vdb);
25709 elen[2] = dot(vdc, vdc);
25710 elen[3] = dot(vab, vab);
25711 elen[4] = dot(vbc, vbc);
25712 elen[5] = dot(vca, vca);
25713
25714 enq = false;
25715 if (b->offcenter) {
25716 // Check if the tet is very flat.
25717 L = 0.0;
25718 for (i = 0; i < 6; i++) L += sqrt(elen[i]);
25719 L /= 6.0;
25720 q = volume / (L * L * L);
25721 enq = (q < b->epsilon * 1e+2);
25722 }
25723
25724 // Is abcd very flat?
25725 if (!enq) {
25726 rhs[0] = 0.5 * dot(vda, vda);
25727 rhs[1] = 0.5 * dot(vdb, vdb);
25728 rhs[2] = 0.5 * dot(vdc, vdc);
25729 lu_solve(A, 3, indx, rhs, 0);
25730 // Get the circumcenter.
25731 for (i = 0; i < 3; i++) circumcent[i] = pd[i] + rhs[i];
25732 // Get the square of the circumradius.
25733 radius2 = dot(rhs, rhs);
25734 // Find the square of the shortest edge length.
25735 smlen2 = elen[0]; sidx = 0;
25736 for (i = 1; i < 6; i++) {
25737 if (smlen2 > elen[i]) { smlen2 = elen[i]; sidx = i; }
25738 }
25739 // Calculate the square of radius-edge ratio.
25740 ratio2 = radius2 / smlen2;
25741 // Check whether the ratio is smaller than permitted.
25742 enq = ratio2 > b->goodratio;
25743 if (!enq) {
25744 // abcd has good ratio.
25745 if (b->offcenter) {
25746 // Test if it is a sliver.
25747 // Compute the 4 face normals (N[0], ..., N[3]).
25748 for (j = 0; j < 3; j++) {
25749 for (i = 0; i < 3; i++) rhs[i] = 0.0;
25750 rhs[j] = 1.0; // Positive means the inside direction
25751 lu_solve(A, 3, indx, rhs, 0);
25752 for (i = 0; i < 3; i++) N[j][i] = rhs[i];
25753 }
25754 // Get the fourth normal by summing up the first three.
25755 for (i = 0; i < 3; i++) N[3][i] = - N[0][i] - N[1][i] - N[2][i];
25756 // Normalized the normals.
25757 for (i = 0; i < 4; i++) {
25758 L = sqrt(dot(N[i], N[i]));
25759 if (L > 0.0) {
25760 for (j = 0; j < 3; j++) N[i][j] /= L;
25761 }
25762 }
25763 // N[0] is the normal of face bcd. Test the dihedral angles at edge
25764 // cd, bd, and bc to see if they are too small or too big.
25765 for (i = 1; i < 4 && !enq; i++) {
25766 cosd = -dot(N[0], N[i]); // Edge cd, bd, bc.
25767 enq = ((cosd > cosmindihed) || ((cosd < cosmaxdihed)));
25768 }
25769 if (enq) {
25770 // A sliver! Split it at the barycenter.
25771 for (i = 0; i < 3; i++) {
25772 circumcent[i] = 0.25 * (pa[i] + pb[i] + pc[i] + pd[i]);
25773 }
25774 ratio2 = 0.0;
25775 }
25776 }
25777 } else if (b->offcenter) {
25778 // abcd has bad-quality. Use off-center instead of circumcenter.
25779 switch (sidx) {
25780 case 0: // edge da.
25781 pe1 = pd; pe2 = pa; break;
25782 case 1: // edge db.
25783 pe1 = pd; pe2 = pb; break;
25784 case 2: // edge dc.
25785 pe1 = pd; pe2 = pc; break;
25786 case 3: // edge ab.
25787 pe1 = pa; pe2 = pb; break;
25788 case 4: // edge bc.
25789 pe1 = pb; pe2 = pc; break;
25790 case 5: // edge ca.
25791 pe1 = pc; pe2 = pa; break;
25792 default: break;
25793 }
25794 // The shortest edge is e1->e2.
25795 for (i = 0; i < 3; i++) bicent[i] = 0.5 * (pe1[i] + pe2[i]);
25796 dist = distance(bicent, circumcent);
25797 // sdist = sqrt(smlen2) * sin(PI / 3.0); // A icoso-triangle.
25798 // The following formulae is from
25799 sdist = b->alpha3 * (b->minratio + sqrt(b->goodratio - 0.25))
25800 * sqrt(smlen2);
25801 split = sdist / dist;
25802 if (split > 1.0) split = 1.0;
25803 // Get the off-center.
25804 for (i = 0; i < 3; i++) {
25805 offcent[i] = bicent[i] + split * (circumcent[i] - bicent[i]);
25806 }
25807 }
25808 } else {
25809 // A fat tet. Split it at the centroid.
25810 for (i = 0; i < 3; i++) {
25811 circumcent[i] = 0.25 * (pa[i] + pb[i] + pc[i] + pd[i]);
25812 }
25813 ratio2 = 0.0;
25814 }
25815
25816 if (!enq && (b->varvolume || b->fixedvolume)) {
25817 // The tet is in good shape.
25818 ratio2 = 0.0;
25819 enq = b->fixedvolume && (volume > b->maxvolume);
25820 if (!enq && b->varvolume) {
25821 enq = (volume > volumebound(testtet->tet)) &&
25822 (volumebound(testtet->tet) > 0.0);
25823 }
25824 }
25825 if (!enq) {
25826 // The tet is in good shape.
25827 ratio2 = 0.0;
25828 if (b->bgmesh && (b->alpha1 > 0.0)) {
25829 sdist = sqrt(radius2) / b->alpha1;
25830 // Check if the nodal size map is satisfied.
25831 for (i = 0; i < 4; i++) {
25832 pa = (point) testtet->tet[4 + i];
25833 // Get the indicated size of p.
25834 dist = pa[3]; // dist = b->alpha1 * pa[pointlfsindex];
25835 enq = ((dist < sdist) && (dist > 0.0));
25836 if (enq) break; // It is bad wrt. a node constraint.
25837 // *** Experiment ! Stop test if c is inside H(a).
25838 // if ((dist > 0.0) && (dist > sdist)) break;
25839 }
25840 // *** Experiment !
25841 // enq = (i == 4); // Does c lies outside all sparse-ball?
25842 }
25843 }
25844
25845 if (enq && enqflag) {
25846 // Allocate space for the bad tetrahedron.
25847 newbadtet = (badface *) badtetrahedrons->alloc();
25848 newbadtet->tt = *testtet;
25849 newbadtet->key = ratio2;
25850 if ((ratio2 != 0) && b->offcenter) {
25851 for (i = 0; i < 3; i++) newbadtet->cent[i] = offcent[i];
25852 } else {
25853 for (i = 0; i < 3; i++) newbadtet->cent[i] = circumcent[i];
25854 }
25855 newbadtet->forg = org(*testtet);
25856 newbadtet->fdest = dest(*testtet);
25857 newbadtet->fapex = apex(*testtet);
25858 newbadtet->foppo = oppo(*testtet);
25859 newbadtet->nextitem = (badface *) NULL;
25860 // Determine the appropriate queue to put the bad tetrahedron into.
25861 if (ratio2 > b->goodratio) {
25862 queuenumber = (int) ((ratio2 - b->goodratio) / 0.5);
25863 // 'queuenumber' may overflow (negative) caused by a very large ratio.
25864 if ((queuenumber > 63) || (queuenumber < 0)) {
25865 queuenumber = 63;
25866 }
25867 } else {
25868 // It's not a bad ratio; put the tet in the lowest-priority queue.
25869 queuenumber = 0;
25870 }
25871 // Add the tetrahedron to the end of a queue.
25872 *tetquetail[queuenumber] = newbadtet;
25873 // Maintain a pointer to the NULL pointer at the end of the queue.
25874 tetquetail[queuenumber] = &newbadtet->nextitem;
25875 if (b->verbose > 2) {
25876 printf(" Queueing bad tet: (%d, %d, %d, %d), ratio %g, qnum %d.\n",
25877 pointmark(pa), pointmark(pb), pointmark(pc), pointmark(pd),
25878 sqrt(ratio2), queuenumber);
25879 }
25880 }
25881
25882 return enq;
25883 }
25884
25885 ///////////////////////////////////////////////////////////////////////////////
25886 // //
25887 // acceptsegpt() Check if a segment point can be inserted or not. //
25888 // //
25889 // Segment(ab) is indicated to be split by a point p (\in ab). This routine //
25890 // decides whether p can be inserted or not. //
25891 // //
25892 // p can not be inserted either the '-Y' option is used and ab is a hull //
25893 // segment or '-YY' option is used. //
25894 // //
25895 // p can be inserted if it is in one of the following cases (L = |a - b|): //
25896 // (1) if ab is too long wrt the edge constraint (bad-quality); or //
25897 // (2) if a subface having ab has max. area constraint A, and L^2 > 2 * A, //
25898 // (3) if a tet having ab has maximal volume constraint V, and L^3 > 6 * V.//
25899 // (4) if |a - p| > \alpha_2 H(a) and |p - b| > \alpha_2 H(b). //
25900 // (5) if 'refpt' != NULL. //
25901 // //
25902 // The purpose of using L instead of area and volume is to avoid resulting //
25903 // too skinny triangles and tetrahedron. //
25904 // //
25905 ///////////////////////////////////////////////////////////////////////////////
25906
25907 bool tetgenmesh::acceptsegpt(point segpt, point refpt, face* splitseg)
25908 {
25909 triface spintet;
25910 face parentsh, spinsh;
25911 point pa, pb, pc;
25912 REAL ablen, palen, pblen;
25913 REAL V, A;
25914
25915 if (b->nobisect == 1) {
25916 // '-Y'. It can not be split if it is on the hull.
25917 sstpivot(splitseg, &spintet);
25918 assert(spintet.tet != dummytet);
25919 pc = apex(spintet);
25920 do {
25921 if (!fnextself(spintet)) {
25922 // Meet a boundary face - s is on the hull.
25923 return false;
25924 }
25925 } while (pc != apex(spintet));
25926 } else if (b->nobisect > 1) {
25927 // '-YY'. Do not split it.
25928 return false;
25929 }
25930
25931 pa = sorg(*splitseg);
25932 pb = sdest(*splitseg);
25933 ablen = distance(pa, pb);
25934 if (varconstraint) {
25935 A = areabound(*splitseg);
25936 if ((A > 0.0) && (ablen > A)) {
25937 return true; // case (1)
25938 }
25939 }
25940
25941 if (varconstraint && in->facetconstraintlist) {
25942 A = ablen * ablen / 2.0;
25943 spinsh = parentsh;
25944 do {
25945 if ((A > areabound(spinsh)) && (areabound(spinsh) > 0.0)) {
25946 return true; // case (2)
25947 }
25948 spivotself(spinsh);
25949 } while (spinsh.sh != parentsh.sh);
25950 }
25951
25952 if (b->varvolume || b->fixedvolume) {
25953 V = ablen * ablen * ablen / 6.0;
25954 if (b->fixedvolume && (V > b->maxvolume)) {
25955 return true; // case (3)
25956 }
25957 if (b->varvolume) {
25958 spivot(*splitseg, parentsh);
25959 if (sorg(parentsh) != pa) sesymself(parentsh);
25960 stpivot(parentsh, spintet);
25961 if (spintet.tet == dummytet) {
25962 sesymself(parentsh);
25963 stpivot(parentsh, spintet);
25964 }
25965 findedge(&spintet, pa, pb);
25966 pc = apex(spintet);
25967 while (true) {
25968 if (!fnextself(spintet)) {
25969 // Meet a boundary, walk through it.
25970 tspivot(spintet, spinsh);
25971 findedge(&spinsh, pa, pb);
25972 sfnextself(spinsh);
25973 stpivot(spinsh, spintet);
25974 findedge(&spintet, pa, pb);
25975 }
25976 if ((V > volumebound(spintet.tet)) &&
25977 (volumebound(spintet.tet) > 0.0)) {
25978 return true; // case (3)
25979 }
25980 if (apex(spintet) == pc) break;
25981 }
25982 }
25983 }
25984
25985 // If p is outside both protect balls of a and b.
25986 palen = distance(segpt, pa);
25987 pblen = distance(segpt, pb);
25988 if (!b->bgmesh) {
25989 if ((palen > (b->alpha2 * pa[pointlfsindex])) &&
25990 (pblen > (b->alpha2 * pb[pointlfsindex]))) {
25991 return true; // case (4)
25992 }
25993 } else {
25994 if ((palen > b->alpha2 * pa[3]) && (pblen > b->alpha2 * pb[3])) {
25995 return true; // case (4)
25996 }
25997 }
25998
25999 // If 'refpt' != NULL, force p to be inserted.
26000 if (refpt != (point) NULL) {
26001 cdtenforcesegpts++;
26002 return true;
26003 }
26004
26005 // Do not split it.
26006 rejsegpts++;
26007 return false;
26008 }
26009
26010 ///////////////////////////////////////////////////////////////////////////////
26011 // //
26012 // acceptfacpt() Check if a facet point can be inserted or not. //
26013 // //
26014 // 'subceillist' is CBC(p). 'verlist' (V) is empty on input, it returns the //
26015 // set of vertices of CBC(p). //
26016 // //
26017 // p can not be inserted either the '-Y' option is used and the facet is on //
26018 // the hull or '-YY' option is used. //
26019 // //
26020 // p can be inserted if it is in one of the following cases (f is a subface //
26021 // of CBC(p), L = max{|p - v|, v \in V}): //
26022 // (1) if f has maximal area constraints A, and L^2 > 2 * A. //
26023 // (2) if a tet having f has max. volume constraint V, and L^3 > 6 * V. //
26024 // (3) if |p - v| > \alpha_2 H(v), for all v \in V. //
26025 // //
26026 // The purpose of using L^3 is to avoid resulting too skinny tetrahedron. //
26027 // //
26028 ///////////////////////////////////////////////////////////////////////////////
26029
26030 bool tetgenmesh::acceptfacpt(point facpt, list* subceillist, list* verlist)
26031 {
26032 triface testtet;
26033 face *testsh;
26034 point p[3];
26035 REAL L, L2, L3, lfs;
26036 int idx, i, j;
26037
26038 if (b->nobisect == 1) {
26039 // '-Y'. p can not be inserted if CBC(p) is on the hull.
26040 testsh = (face *)(* subceillist)[0];
26041 stpivot(*testsh, testtet);
26042 if (testtet.tet != dummytet) {
26043 sesymself(*testsh);
26044 stpivot(*testsh, testtet);
26045 }
26046 if (testtet.tet == dummytet) return false;
26047 } else if (b->nobisect > 1) {
26048 // '-YY'. Do not split s.
26049 return false;
26050 }
26051
26052 // Collect the vertices of CBC(p), save them in V.
26053 for (i = 0; i < subceillist->len(); i++) {
26054 testsh = (face *)(* subceillist)[i];
26055 p[0] = sorg(*testsh);
26056 p[1] = sdest(*testsh);
26057 for (j = 0; j < 2; j++) {
26058 idx = pointmark(p[j]);
26059 if (idx >= 0) {
26060 setpointmark(p[j], -idx - 1);
26061 verlist->append(&(p[j]));
26062 }
26063 }
26064 }
26065 // Uninfect collected vertices.
26066 for (i = 0; i < verlist->len(); i++) {
26067 p[0] = * (point *)(* verlist)[i];
26068 idx = pointmark(p[0]);
26069 setpointmark(p[0], -(idx + 1));
26070 }
26071
26072 if (varconstraint && in->facetconstraintlist) {
26073 for (i = 0; i < subceillist->len(); i++) {
26074 testsh = (face *)(* subceillist)[i];
26075 if (areabound(*testsh) > 0.0) {
26076 // Get the longest edge length of testsh = L.
26077 for (j = 0; j < 3; j++) p[j] = (point) testsh->sh[j + 3];
26078 L = distance(p[0], p[1]);
26079 L2 = distance(p[1], p[2]);
26080 L = (L >= L2 ? L : L2);
26081 L2 = distance(p[2], p[0]);
26082 L = (L >= L2 ? L : L2);
26083 L2 = L * L / 2.0;
26084 if (L2 > areabound(*testsh)) {
26085 return true; // case (1)
26086 }
26087 }
26088 }
26089 }
26090
26091 // Check if it is in case (2).
26092 if (b->varvolume || b->fixedvolume) {
26093 for (i = 0; i < subceillist->len(); i++) {
26094 testsh = (face *)(* subceillist)[i];
26095 // Get the longest edge length of testsh = L.
26096 for (j = 0; j < 3; j++) p[j] = (point) testsh->sh[j + 3];
26097 L = distance(p[0], p[1]);
26098 L3 = distance(p[1], p[2]);
26099 L = (L >= L3 ? L : L3);
26100 L3 = distance(p[2], p[0]);
26101 L = (L >= L3 ? L : L3);
26102 L3 = L * L * L / 6.0;
26103 if (b->fixedvolume && (L3 > b->maxvolume)) {
26104 // This face is too large wrt. the maximum volume bound. Split it.
26105 return true; // case (2)
26106 }
26107 if (b->varvolume) {
26108 for (j = 0; j < 2; j ++) {
26109 stpivot(*testsh, testtet);
26110 if (testtet.tet != dummytet) {
26111 if ((L3 > volumebound(testtet.tet)) &&
26112 (volumebound(testtet.tet) > 0.0)) {
26113 // This face is too large wrt the maximum volume bound.
26114 return true; // case (2)
26115 }
26116 }
26117 sesymself(*testsh);
26118 }
26119 }
26120 }
26121 }
26122
26123 // Check if p is inside the protect balls of vertices of V.
26124 for (i = 0; i < verlist->len(); i++) {
26125 p[0] = * (point *)(* verlist)[i];
26126 if (!b->bgmesh) {
26127 lfs = b->alpha2 * p[0][pointlfsindex];
26128 } else {
26129 lfs = b->alpha2 * p[0][3];
26130 }
26131 L = distance(p[0], facpt);
26132 if (L < lfs) break; // p is inside ball.
26133 }
26134 if (i == verlist->len()) return true; // case (3).
26135
26136 rejsubpts++;
26137 return false;
26138 }
26139
26140 ///////////////////////////////////////////////////////////////////////////////
26141 // //
26142 // acceptvolpt() Check if a volume point can be inserted or not. //
26143 // //
26144 // 'ceillist' is B(p). 'verlist' (V) is empty on input, it returns the set //
26145 // of vertices of B(p). //
26146 // //
26147 // p can be split if it is in one of the following cases: //
26148 // (1) if the t \in B(p) has maximal volume constraint V, and vol(t) < V. //
26149 // (2) if |p - v| > \alpha_2 H(v), for all v \in V. //
26150 // //
26151 ///////////////////////////////////////////////////////////////////////////////
26152
26153 bool tetgenmesh::acceptvolpt(point volpt, list* ceillist, list* verlist)
26154 {
26155 triface* testtet;
26156 point p[4];
26157 REAL L, vol, lfs;
26158 int idx, i, j;
26159
26160 // Collect the vertices of CBC(p), save them in V.
26161 for (i = 0; i < ceillist->len(); i++) {
26162 testtet = (triface *)(* ceillist)[i];
26163 p[0] = org(*testtet);
26164 p[1] = dest(*testtet);
26165 p[2] = apex(*testtet);
26166 for (j = 0; j < 3; j++) {
26167 idx = pointmark(p[j]);
26168 if (idx >= 0) {
26169 setpointmark(p[j], -idx - 1);
26170 verlist->append(&(p[j]));
26171 }
26172 }
26173 }
26174 // Uninfect collected vertices.
26175 for (i = 0; i < verlist->len(); i++) {
26176 p[0] = * (point *)(* verlist)[i];
26177 idx = pointmark(p[0]);
26178 setpointmark(p[0], -(idx + 1));
26179 }
26180
26181 if (b->varvolume || b->fixedvolume) {
26182 for (i = 0; i < ceillist->len(); i++) {
26183 testtet = (triface *)(* ceillist)[i];
26184 for (j = 0; j < 4; j++) p[j] = (point) testtet->tet[4 + j];
26185 vol = orient3d(p[0], p[1], p[2], p[3]) / 6.0;
26186 if (vol < 0) vol = -vol;
26187 if (b->fixedvolume && (vol > b->maxvolume)) {
26188 // This tet is too large wrt. the maximum volume bound. Split it.
26189 return true; // case (1)
26190 }
26191 if (b->varvolume) {
26192 if ((vol > volumebound(testtet->tet)) &&
26193 (volumebound(testtet->tet) > 0.0)) {
26194 // This tet is too large wrt the maximum volume bound.
26195 return true; // case (1)
26196 }
26197 }
26198 }
26199 }
26200
26201 // Check if p is inside the protect balls of vertices of V.
26202 for (i = 0; i < verlist->len(); i++) {
26203 p[0] = * (point *)(* verlist)[i];
26204 if (!b->bgmesh) {
26205 lfs = b->alpha2 * p[0][pointlfsindex];
26206 } else {
26207 lfs = b->alpha2 * p[0][3];
26208 }
26209 L = distance(p[0], volpt);
26210 if (L < lfs) break; // p is inside ball.
26211 }
26212 if (i == verlist->len()) return true; // case (2).
26213
26214 rejtetpts++;
26215 return false;
26216 }
26217
26218 ///////////////////////////////////////////////////////////////////////////////
26219 // //
26220 // getsplitpoint() Get the inserting point in a segment. //
26221 // //
26222 ///////////////////////////////////////////////////////////////////////////////
26223
26224 void tetgenmesh::getsplitpoint(point e1, point e2, point refpt, point newpt)
26225 {
26226 point ei, ej;
26227 REAL split, L, d1, d2, ps, rs;
26228 bool acutea, acuteb;
26229 int i;
26230
26231 if (refpt != (point) NULL) {
26232 // Use the CDT rules to split the segment.
26233 acutea = (pointtype(e1) == ACUTEVERTEX);
26234 acuteb = (pointtype(e2) == ACUTEVERTEX);
26235 if (acutea ^ acuteb) {
26236 // Only one endpoint is acute. Use rule-2 or rule-3.
26237 ei = acutea ? e1 : e2;
26238 ej = acutea ? e2 : e1;
26239 L = distance(ei, ej);
26240 // Apply rule-2.
26241 d1 = distance(ei, refpt);
26242 split = d1 / L;
26243 for (i = 0; i < 3; i++) newpt[i] = ei[i] + split * (ej[i] - ei[i]);
26244 // Check if rule-3 is needed.
26245 d2 = distance(refpt, newpt);
26246 if (d2 > (L - d1)) {
26247 // Apply rule-3.
26248 if ((d1 - d2) > (0.5 * d1)) {
26249 split = (d1 - d2) / L;
26250 } else {
26251 split = 0.5 * d1 / L;
26252 }
26253 for (i = 0; i < 3; i++) newpt[i] = ei[i] + split * (ej[i] - ei[i]);
26254 if (b->verbose > 1) {
26255 printf(" Found by rule-3:");
26256 }
26257 r3count++;
26258 } else {
26259 if (b->verbose > 1) {
26260 printf(" Found by rule-2:");
26261 }
26262 r2count++;
26263 }
26264 if (b->verbose > 1) {
26265 printf(" center %d, split = %.12g.\n", pointmark(ei), split);
26266 }
26267 // Add a random perturbation on newpt.
26268 d1 = distance(ei, newpt);
26269 d2 = distance(newpt, refpt);
26270 ps = randgenerator(d2 * b->epsilon2);
26271 rs = ps / d1;
26272 // Perturb newpt away from ei.
26273 for (i = 0; i < 3; i++) newpt[i] = ei[i] + (1.0+rs) * (newpt[i] - ei[i]);
26274 } else {
26275 // Both endpoints are acute or not. Split it at the middle.
26276 for (i = 0; i < 3; i++) newpt[i] = 0.5 * (e1[i] + e2[i]);
26277 }
26278 } else {
26279 // Split the segment at its midpoint.
26280 for (i = 0; i < 3; i++) newpt[i] = 0.5 * (e1[i] + e2[i]);
26281 }
26282 }
26283
26284 ///////////////////////////////////////////////////////////////////////////////
26285 // //
26286 // shepardinterpolation() Interpolate the local size of a newpoint. //
26287 // //
26288 // The classical Shepard interoplation (inversed weighted distance) is used. //
26289 // (With the choice p = 2). //
26290 // //
26291 // 'verlist' contains a list vertices neighboring to 'newpt'. //
26292 // //
26293 ///////////////////////////////////////////////////////////////////////////////
26294
26295 void tetgenmesh::shepardinterpolate(point newpt, list *verlist)
26296 {
26297 point neipt;
26298 REAL *weights, sumweight;
26299 REAL vec[3];
26300 int i, j;
26301
26302 weights = new REAL[verlist->len()];
26303 sumweight = 0.0;
26304
26305 // Calculate the weight of each point.
26306 for (i = 0; i < verlist->len(); i++) {
26307 neipt = * (point *)(* verlist)[i];
26308 for (j = 0; j < 3; j++) vec[j] = neipt[j] - newpt[j];
26309 weights[i] = 1.0 / dot(vec, vec);
26310 sumweight += weights[i];
26311 }
26312 // Interpolate.
26313 newpt[pointlfsindex] = 0.0;
26314 for (i = 0; i < verlist->len(); i++) {
26315 neipt = * (point *)(* verlist)[i];
26316 newpt[pointlfsindex] += (weights[i] * neipt[pointlfsindex]) / sumweight;
26317 }
26318
26319 delete [] weights;
26320 }
26321
26322 ///////////////////////////////////////////////////////////////////////////////
26323 // //
26324 // setnewpointsize() Set the size for a new point. //
26325 // //
26326 // The size of the new point p is interpolated either from a background mesh //
26327 // (b->bgmesh) or from the sizes of the adjacent vertices of p. //
26328 // //
26329 ///////////////////////////////////////////////////////////////////////////////
26330
26331 void tetgenmesh::setnewpointsize(point newpt, list* verlist)
26332 {
26333 if (b->bgmesh) {
26334 triface bgmtet;
26335 point pa;
26336 // Get a tet in background mesh for locating p.
26337 pa = * (point *)(* verlist)[0];
26338 decode(point2bgmtet(pa), bgmtet);
26339 interpolatepointsize(newpt, &bgmtet, NULL);
26340 } else {
26341 // Interpolate a local size for p using Shepard interpolation.
26342 shepardinterpolate(newpt, verlist);
26343 }
26344 }
26345
26346 ///////////////////////////////////////////////////////////////////////////////
26347 // //
26348 // splitencseg() Split an enc-seg and recover the Delaunayness by flips. //
26349 // //
26350 ///////////////////////////////////////////////////////////////////////////////
26351
26352 void tetgenmesh::splitencseg(point newpt, face* splitseg, list* tetlist,
26353 list* sublist, list* verlist, queue* flipque, bool chkencsub, bool chkbadtet)
26354 {
26355 triface starttet;
26356 face startsh, spinsh, checksh;
26357 int i;
26358
26359 // Use the base orientation (important in this routine).
26360 splitseg->shver = 0;
26361 // Insert p, this should always success.
26362 sstpivot(splitseg, &starttet);
26363 splittetedge(newpt, &starttet, flipque);
26364 if (steinerleft > 0) steinerleft--;
26365 // Remove locally non-Delaunay faces by flipping.
26366 flip(flipque, NULL);
26367
26368 // Check the two new subsegs to see if they're encroached (not by p).
26369 for (i = 0; i < 2; i++) {
26370 if (!shell2badface(*splitseg)) {
26371 checkseg4encroach(splitseg, NULL, NULL, true);
26372 if (!shell2badface(*splitseg)) {
26373 if (varconstraint && (areabound(*splitseg) > 0.0)) {
26374 checkseg4badqual(splitseg, true);
26375 }
26376 }
26377 }
26378 if (i == 1) break; // Two new segs have been checked.
26379 senextself(*splitseg);
26380 spivotself(*splitseg);
26381 #ifdef SELF_CHECK
26382 assert(splitseg->sh != (shellface *) NULL);
26383 #endif
26384 splitseg->shver = 0;
26385 }
26386 // Check the new subfaces to see if they're encroached (not by p).
26387 if (chkencsub) {
26388 spivot(*splitseg, startsh);
26389 spinsh = startsh;
26390 do {
26391 sublist->append(&spinsh);
26392 formstarpolygon(newpt, sublist, verlist);
26393 for (i = 0; i < sublist->len(); i++) {
26394 checksh = * (face *)(* sublist)[i];
26395 if (!shell2badface(checksh)) {
26396 checksub4encroach(&checksh, NULL, true);
26397 if (!shell2badface(checksh)) {
26398 if (varconstraint && (areabound(checksh) > 0.0)) {
26399 checksub4badqual(&checksh, true);
26400 }
26401 }
26402 }
26403 }
26404 sublist->clear();
26405 verlist->clear();
26406 spivotself(spinsh);
26407 } while (spinsh.sh != startsh.sh);
26408 }
26409
26410 // Collect the new tets connecting at p.
26411 sstpivot(splitseg, &starttet);
26412 tetlist->append(&starttet);
26413 formstarpolyhedron(newpt, tetlist, verlist, true);
26414
26415 // Check if p encroaches adjacent segments.
26416 tallencsegs(newpt, 1, &tetlist);
26417 if (chkencsub) {
26418 // Check if p encroaches adjacent subfaces.
26419 tallencsubs(newpt, 1, &tetlist);
26420 }
26421 if (chkbadtet) {
26422 // Check if there are new bad quality tets at p.
26423 for (i = 0; i < tetlist->len(); i++) {
26424 starttet = * (triface *)(* tetlist)[i];
26425 checktet4badqual(&starttet, true);
26426 }
26427 }
26428 tetlist->clear();
26429 }
26430
26431 ///////////////////////////////////////////////////////////////////////////////
26432 // //
26433 // tallencsegs() Check for encroached segments and save them in list. //
26434 // //
26435 // If 'testpt' (p) != NULL, only check if segments are encroached by p, else,//
26436 // check all the nearby mesh vertices. //
26437 // //
26438 // If 'ceillists' (B_i(p)) != NULL, there are 'n' B_i(p)s, only check the //
26439 // segments which are on B_i(p)s, else, check the entire list of segments //
26440 // (in the pool 'this->subsegs'). //
26441 // //
26442 ///////////////////////////////////////////////////////////////////////////////
26443
26444 bool tetgenmesh::tallencsegs(point testpt, int n, list **ceillists)
26445 {
26446 list *ceillist;
26447 triface ceiltet;
26448 face checkseg;
26449 long oldencnum;
26450 int i, j, k;
26451
26452 // Remember the current number of encroached segments.
26453 oldencnum = badsubsegs->items;
26454
26455 if (ceillists != (list **) NULL) {
26456 for (k = 0; k < n; k++) {
26457 ceillist = ceillists[k];
26458 // Check the segments on B_i(p).
26459 for (i = 0; i < ceillist->len(); i++) {
26460 ceiltet = * (triface *)(* ceillist)[i];
26461 ceiltet.ver = 0;
26462 for (j = 0; j < 3; j++) {
26463 tsspivot(&ceiltet, &checkseg);
26464 if (checkseg.sh != dummysh) {
26465 // Found a segment. Test it if it isn't in enc-list.
26466 if (!shell2badface(checkseg)) {
26467 checkseg4encroach(&checkseg, testpt, NULL, true);
26468 if (!shell2badface(checkseg)) {
26469 if (varconstraint && (areabound(checkseg) > 0.0)) {
26470 checkseg4badqual(&checkseg, true);
26471 }
26472 }
26473 }
26474 }
26475 enextself(ceiltet);
26476 }
26477 }
26478 }
26479 } else {
26480 // Check the entire list of segments.
26481 subsegs->traversalinit();
26482 checkseg.sh = shellfacetraverse(subsegs);
26483 while (checkseg.sh != (shellface *) NULL) {
26484 // Test it if it isn't in enc-list.
26485 if (!shell2badface(checkseg)) {
26486 checkseg4encroach(&checkseg, testpt, NULL, true);
26487 if (!shell2badface(checkseg)) {
26488 if (varconstraint && (areabound(checkseg) > 0.0)) {
26489 checkseg4badqual(&checkseg, true);
26490 }
26491 }
26492 }
26493 checkseg.sh = shellfacetraverse(subsegs);
26494 }
26495 }
26496
26497 return (badsubsegs->items > oldencnum);
26498 }
26499
26500 ///////////////////////////////////////////////////////////////////////////////
26501 // //
26502 // tallencsubs() Find all encroached subfaces and save them in list. //
26503 // //
26504 // If 'testpt' (p) != NULL, only check if subfaces are encroached by p, else,//
26505 // check the adjacent vertices of subfaces. //
26506 // //
26507 // If 'ceillists' (B_i(p)) != NULL, there are 'n' B_i(p)s, only check the //
26508 // subfaces which are on B_i(p)s, else, check the entire list of subfaces //
26509 // (in the pool 'this->subfaces'). //
26510 // //
26511 ///////////////////////////////////////////////////////////////////////////////
26512
26513 bool tetgenmesh::tallencsubs(point testpt, int n, list** ceillists)
26514 {
26515 list *ceillist;
26516 triface ceiltet;
26517 face checksh;
26518 long oldencnum;
26519 int i, k;
26520
26521 // Remember the current number of encroached segments.
26522 oldencnum = badsubfaces->items;
26523
26524 if (ceillists != (list **) NULL) {
26525 for (k = 0; k < n; k++) {
26526 ceillist = ceillists[k];
26527 // Check the subfaces on B_i(p).
26528 for (i = 0; i < ceillist->len(); i++) {
26529 ceiltet = * (triface *)(* ceillist)[i];
26530 tspivot(ceiltet, checksh);
26531 if (checksh.sh != dummysh) {
26532 // Found a subface. Test it if it isn't in enc-list.
26533 if (!shell2badface(checksh)) {
26534 checksub4encroach(&checksh, testpt, true);
26535 if (!shell2badface(checksh)) {
26536 if (varconstraint && (areabound(checksh) > 0.0)) {
26537 checksub4badqual(&checksh, true);
26538 }
26539 }
26540 }
26541 }
26542 }
26543 }
26544 } else {
26545 // Check the entire list of subfaces.
26546 subfaces->traversalinit();
26547 checksh.sh = shellfacetraverse(subfaces);
26548 while (checksh.sh != (shellface *) NULL) {
26549 // Test it if it isn't in enc-list.
26550 if (!shell2badface(checksh)) {
26551 checksub4encroach(&checksh, testpt, true);
26552 if (!shell2badface(checksh)) {
26553 if (varconstraint && (areabound(checksh) > 0.0)) {
26554 checksub4badqual(&checksh, true);
26555 }
26556 }
26557 }
26558 checksh.sh = shellfacetraverse(subfaces);
26559 }
26560 }
26561
26562 return (badsubfaces->items > oldencnum);
26563 }
26564
26565 ///////////////////////////////////////////////////////////////////////////////
26566 // //
26567 // tallbadtetrahedrons() Queue all the bad-quality tetrahedra in the mesh.//
26568 // //
26569 ///////////////////////////////////////////////////////////////////////////////
26570
26571 void tetgenmesh::tallbadtetrahedrons()
26572 {
26573 triface tetloop;
26574
26575 tetrahedrons->traversalinit();
26576 tetloop.tet = tetrahedrontraverse();
26577 while (tetloop.tet != (tetrahedron *) NULL) {
26578 checktet4badqual(&tetloop, true);
26579 tetloop.tet = tetrahedrontraverse();
26580 }
26581 }
26582
26583 ///////////////////////////////////////////////////////////////////////////////
26584 // //
26585 // repairencsegs() Repair (split) all the encroached segments. //
26586 // //
26587 // Each encroached segment is repaired by splitting it - inserting a vertex //
26588 // at or near its midpoint. Newly inserted vertices may encroach upon other //
26589 // subsegments, these are also repaired. //
26590 // //
26591 // 'chkencsub' and 'chkbadtet' are two flags that specify whether one should //
26592 // take note of new encroaced subfaces and bad quality tets that result from //
26593 // inserting vertices to repair encroached subsegments. //
26594 // //
26595 ///////////////////////////////////////////////////////////////////////////////
26596
26597 void tetgenmesh::repairencsegs(bool chkencsub, bool chkbadtet)
26598 {
26599 list **tetlists, **ceillists;
26600 list **sublists, **subceillists;
26601 list *tetlist, *sublist, *verlist;
26602 queue *flipque;
26603 badface *encloop;
26604 face splitseg, symsplitseg;
26605 point newpt, sympt, refpt;
26606 enum locateresult symloc;
26607 int nmax, n, i, j;
26608
26609 n = 0;
26610 nmax = 128;
26611 tetlist = (list *) NULL;
26612 flipque = (queue *) NULL;
26613 if (!b->fliprepair) {
26614 tetlists = new list*[nmax];
26615 ceillists = new list*[nmax];
26616 sublists = new list*[nmax];
26617 subceillists = new list*[nmax];
26618 } else {
26619 tetlist = new list(sizeof(triface), NULL, 1024);
26620 sublist = new list(sizeof(face), NULL, 256);
26621 }
26622 verlist = new list(sizeof(point *), NULL, 256);
26623 if (b->fliprepair) {
26624 flipque = new queue(sizeof(badface));
26625 }
26626
26627 // Loop until the pool 'badsubsegs' is empty. Note that steinerleft == -1
26628 // if an unlimited number of Steiner points is allowed.
26629 while ((badsubsegs->items > 0) && (steinerleft != 0)) {
26630 badsubsegs->traversalinit();
26631 encloop = badfacetraverse(badsubsegs);
26632 while ((encloop != (badface *) NULL) && (steinerleft != 0)) {
26633 // Get an encroached subsegment s.
26634 splitseg = encloop->ss;
26635 // Clear the in-queue flag in s.
26636 setshell2badface(splitseg, NULL);
26637 if ((sorg(splitseg) == encloop->forg) &&
26638 (sdest(splitseg) == encloop->fdest)) {
26639 if (b->verbose > 1) {
26640 printf(" Get an enc-seg (%d, %d)\n", pointmark(encloop->forg),
26641 pointmark(encloop->fdest));
26642 }
26643 refpt = (point) NULL;
26644 if (b->conformdel) {
26645 // Look for a reference point.
26646 checkseg4encroach(&splitseg, NULL, &refpt, false);
26647 }
26648 // Create the new point p (at the middle of s).
26649 makepoint(&newpt);
26650 // for (i = 0; i < 3; i++) {
26651 // newpt[i] = 0.5 * (encloop->forg[i] + encloop->fdest[i]);
26652 // }
26653 getsplitpoint(encloop->forg, encloop->fdest, refpt, newpt);
26654 setpointtype(newpt, FREESEGVERTEX);
26655 setpoint2sh(newpt, sencode(splitseg));
26656 // Decide whether p can be inserted or not.
26657 if (acceptsegpt(newpt, refpt, &splitseg)) {
26658 // Is there periodic boundary condition?
26659 if (checkpbcs) {
26660 // Insert points on other segments of incident pbcgroups.
26661 i = shellmark(splitseg) - 1;
26662 for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++) {
26663 makepoint(&sympt);
26664 symloc = getsegpbcsympoint(newpt, &splitseg, sympt, &symsplitseg,
26665 segpglist[j]);
26666 if (symloc == ONEDGE) {
26667 if (symsplitseg.sh != splitseg.sh) {
26668 // Insert sympt.
26669 setpointtype(sympt, FREESEGVERTEX);
26670 setpoint2sh(sympt, sencode(symsplitseg));
26671 if (!b->fliprepair) {
26672 // Form BC(symp), B(symp), CBC(symp)s, C(symp)s.
26673 formbowatcavity(sympt, &symsplitseg, NULL, &n, &nmax,
26674 sublists, subceillists, tetlists, ceillists);
26675 // Validate BC(symp), B(symp), CBC(symp)s, C(symp)s.
26676 if (trimbowatcavity(sympt, &symsplitseg, n, sublists,
26677 subceillists, tetlists, ceillists, -1.0)) {
26678 bowatinsertsite(sympt, &symsplitseg, n, sublists,
26679 subceillists, tetlists, ceillists, verlist, flipque,
26680 true, chkencsub, chkbadtet);
26681 setnewpointsize(sympt, verlist);
26682 if (steinerleft > 0) steinerleft--;
26683 } else {
26684 // p did not insert for invalid BC(symp).
26685 pointdealloc(sympt);
26686 }
26687 // Free the memory allocated in formbowatcavity().
26688 releasebowatcavity(&symsplitseg, n, sublists, subceillists,
26689 tetlists, ceillists);
26690 } else {
26691 splitencseg(sympt, &symsplitseg, tetlist, sublist, verlist,
26692 flipque, chkencsub, chkbadtet);
26693 setnewpointsize(sympt, verlist);
26694 if (steinerleft > 0) steinerleft--;
26695 }
26696 verlist->clear();
26697 } else {
26698 // The sympt are on the same segment. It is possible when
26699 // splitseg is the symmetric rotating axes.
26700 pointdealloc(sympt);
26701 }
26702 } else if (symloc == ONVERTEX) {
26703 // The sympt already exists. It is possible when two pbc
26704 // groups are exactly the same. Omit this point.
26705 pointdealloc(sympt);
26706 } else {
26707 // Do not isnert symp for unknown cases: ONFACE, OUTSIDE.
26708 // assert(0);
26709 pointdealloc(sympt);
26710 }
26711 } // for (j = idx2segpglist[i]; j < idx2segpglist[i + 1]; j++)
26712 } // if (checkpbcs)
26713 if (!b->fliprepair) {
26714 // Form BC(p), B(p), CBC(p)s, and C(p)s.
26715 formbowatcavity(newpt, &splitseg, NULL, &n, &nmax, sublists,
26716 subceillists, tetlists, ceillists);
26717 // Validate/update BC(p), B(p), CBC(p)s, and C(p)s.
26718 if (trimbowatcavity(newpt, &splitseg, n, sublists, subceillists,
26719 tetlists, ceillists, -1.0)) {
26720 bowatinsertsite(newpt, &splitseg, n, sublists, subceillists,
26721 tetlists, ceillists, verlist, flipque, true,
26722 chkencsub, chkbadtet);
26723 setnewpointsize(newpt, verlist);
26724 if (steinerleft > 0) steinerleft--;
26725 } else {
26726 // p did not insert for invalid B(p).
26727 pointdealloc(newpt);
26728 }
26729 // Free the memory allocated in formbowatcavity().
26730 releasebowatcavity(&splitseg, n, sublists, subceillists, tetlists,
26731 ceillists);
26732 } else {
26733 splitencseg(newpt, &splitseg, tetlist, sublist, verlist, flipque,
26734 chkencsub, chkbadtet);
26735 setnewpointsize(newpt, verlist);
26736 if (steinerleft > 0) steinerleft--;
26737 }
26738 verlist->clear();
26739 } else {
26740 // p did not accept for insertion.
26741 pointdealloc(newpt);
26742 } // if (checkseg4splitting(newpt, &splitseg))
26743 } // if ((encloop->forg == pa) && (encloop->fdest == pb))
26744 badfacedealloc(badsubsegs, encloop); // Remove this entry from list.
26745 encloop = badfacetraverse(badsubsegs); // Get the next enc-segment.
26746 } // while ((encloop != (badface *) NULL) && (steinerleft != 0))
26747 } // while ((badsubsegs->items > 0) && (steinerleft != 0))
26748
26749 if (!b->fliprepair) {
26750 delete [] tetlists;
26751 delete [] ceillists;
26752 delete [] sublists;
26753 delete [] subceillists;
26754 } else {
26755 delete tetlist;
26756 delete sublist;
26757 }
26758 delete verlist;
26759 if (b->fliprepair) {
26760 delete flipque;
26761 }
26762 }
26763
26764 ///////////////////////////////////////////////////////////////////////////////
26765 // //
26766 // repairencsubs() Repair (split) all the encroached subfaces. //
26767 // //
26768 // Each encroached subface is repaired by splitting it - inserting a vertex //
26769 // at or near its circumcenter. Newly inserted vertices may encroach upon //
26770 // other subfaces, these are also repaired. //
26771 // //
26772 // 'chkbadtet' is a flag that specifies whether one should take note of new //
26773 // bad quality tets that result from inserted vertices. //
26774 // //
26775 ///////////////////////////////////////////////////////////////////////////////
26776
26777 void tetgenmesh::repairencsubs(bool chkbadtet)
26778 {
26779 list *tetlists[2], *ceillists[2];
26780 list *sublist, *subceillist;
26781 list *verlist;
26782 badface *encloop;
26783 face splitsub, symsplitsub;
26784 point newpt, sympt;
26785 enum locateresult loc, symloc;
26786 bool reject;
26787 long oldptnum;
26788 int quenumber, n, i;
26789
26790 n = 0;
26791 sublist = (list *) NULL;
26792 subceillist = (list *) NULL;
26793 verlist = new list(sizeof(point *), NULL, 256);
26794
26795 // Loop until the pool 'badsubfaces' is empty. Note that steinerleft == -1
26796 // if an unlimited number of Steiner points is allowed.
26797 while ((badsubfaces->items > 0) && (steinerleft != 0)) {
26798 // Get an encroached subface f.
26799 encloop = dequeueencsub(&quenumber);
26800 splitsub = encloop->ss;
26801 // Clear the in-queue flag of f.
26802 setshell2badface(splitsub, NULL);
26803 // f may not be the same one when it was determined to be encroached.
26804 if (!isdead(&splitsub) && (sorg(splitsub) == encloop->forg) &&
26805 (sdest(splitsub) == encloop->fdest) &&
26806 (sapex(splitsub) == encloop->fapex)) {
26807 if (b->verbose > 1) {
26808 printf(" Dequeuing ensub (%d, %d, %d) [%d].\n",
26809 pointmark(encloop->forg), pointmark(encloop->fdest),
26810 pointmark(encloop->fapex), quenumber);
26811 }
26812 // Create a new point p.
26813 makepoint(&newpt);
26814 // If f was added by checksub4badqual(), calculate its circumcenter.
26815 if (quenumber == 2) {
26816 circumsphere(encloop->forg, encloop->fdest, encloop->fapex, NULL,
26817 encloop->cent, NULL);
26818 }
26819 for (i = 0; i < 3; i++) newpt[i] = encloop->cent[i];
26820 setpointtype(newpt, FREESUBVERTEX);
26821 setpoint2sh(newpt, sencode(splitsub));
26822 // Set the abovepoint of f for point location.
26823 abovepoint = facetabovepointarray[shellmark(splitsub)];
26824 if (abovepoint == (point) NULL) {
26825 getfacetabovepoint(&splitsub);
26826 }
26827 // Locate p, start from f, stop at segment (1), use a tolerance to
26828 // detect ONVERTEX or OUTSIDE case. Update f on return.
26829 loc = locatesub(newpt, &splitsub, 1, b->epsilon * 1e+2);
26830 if ((loc != ONVERTEX) && (loc != OUTSIDE)) {
26831 // Form BC(p), B(p), CBC(p) and C(p).
26832 formbowatcavity(newpt, NULL, &splitsub, &n, NULL, &sublist,
26833 &subceillist, tetlists, ceillists);
26834 // Check for encroaching subsegments (on B(p)).
26835 reject = tallencsegs(newpt, 2, ceillists);
26836 if (!reject) {
26837 // Decide whether f is allowed to be split or not?
26838 reject = !acceptfacpt(newpt, subceillist, verlist);
26839 verlist->clear();
26840 }
26841 if (!reject) {
26842 // Validate/update cavity.
26843 reject = !trimbowatcavity(newpt, NULL, n, &sublist, &subceillist,
26844 tetlists, ceillists, -1.0);
26845 }
26846 if (!reject) {
26847 // CBC(p) should include s, so that s can be removed after CBC(p)
26848 // is remeshed. However, if there are locally non-Delaunay faces
26849 // and encroached subsegments, s may not be collected in CBC(p).
26850 // p should not be inserted in such case.
26851 reject = !sinfected(encloop->ss);
26852 }
26853 if (!reject) {
26854 if (checkpbcs) {
26855 if (shellpbcgroup(splitsub) >= 0) {
26856 // Check for splitting of the symmetric subface of f.
26857 makepoint(&sympt);
26858 symloc = getsubpbcsympoint(newpt,&splitsub,sympt,&symsplitsub);
26859 if (symloc != ONVERTEX) {
26860 // Release CBC(p) and BC(p) and free the memory..
26861 releasebowatcavity(NULL, 2, &sublist, &subceillist, tetlists,
26862 ceillists);
26863 // Form CBC(symp), C(symp), BC(sympt) and B(sympt).
26864 formbowatcavity(sympt, NULL, &symsplitsub, &n, NULL, &sublist,
26865 &subceillist, tetlists, ceillists);
26866 reject = tallencsegs(sympt, 2, ceillists);
26867 if (!reject) {
26868 reject = !acceptfacpt(sympt, subceillist, verlist);
26869 verlist->clear();
26870 }
26871 if (!reject) {
26872 reject = !trimbowatcavity(sympt,NULL,n,&sublist,&subceillist,
26873 tetlists, ceillists, -1.0);
26874 }
26875 if (!reject) {
26876 // Insert sympt.
26877 setpoint2pbcpt(newpt, sympt);
26878 setpoint2pbcpt(sympt, newpt);
26879 setpointtype(sympt, FREESUBVERTEX);
26880 setpoint2sh(sympt, sencode(symsplitsub));
26881 bowatinsertsite(sympt, NULL, n, &sublist, &subceillist,
26882 tetlists,ceillists,verlist,NULL,false,true,chkbadtet);
26883 setnewpointsize(sympt, verlist);
26884 verlist->clear();
26885 if (steinerleft > 0) steinerleft--;
26886 } else {
26887 // symp is rejected for one of the following reasons:
26888 // (1) BC(symp) is not valid; or
26889 // (2) symp encroaches upon some subsegments (queued); or
26890 // (3) symp is rejected by point accepting rule.
26891 pointdealloc(sympt);
26892 }
26893 // Release CBC(symp) and BC(symp) and free the memory..
26894 releasebowatcavity(NULL, n, &sublist, &subceillist, tetlists,
26895 ceillists);
26896 } else {
26897 // Do not insert sympt for invalid PBC data.
26898 pointdealloc(sympt);
26899 // p is rejected due to symp.
26900 reject = true;
26901 }
26902 }
26903 } // if (checkpbcs)
26904 }
26905 if (!reject) {
26906 // Insert p.
26907 if (checkpbcs) {
26908 if (shellpbcgroup(splitsub) >= 0) {
26909 // Form CBC(p), C(p), BC(p) and B(p).
26910 formbowatcavity(newpt, NULL, &splitsub, &n, NULL, &sublist,
26911 &subceillist, tetlists, ceillists);
26912 trimbowatcavity(newpt, NULL, n, &sublist, &subceillist, tetlists,
26913 ceillists, -1.0);
26914 }
26915 }
26916 bowatinsertsite(newpt, NULL, n, &sublist, &subceillist, tetlists,
26917 ceillists, verlist, NULL, true, true, chkbadtet);
26918 setnewpointsize(newpt, verlist);
26919 verlist->clear();
26920 if (steinerleft > 0) steinerleft--;
26921 } else {
26922 // p is rejected for the one of the following reasons:
26923 // (1) BC(p) is not valid.
26924 // (2) s does not in CBC(p).
26925 // (3) p encroaches upon some segments (queued); or
26926 // (4) p is rejected by point accepting rule, or
26927 // (5) due to the rejection of symp (the PBC).
26928 pointdealloc(newpt);
26929 } // if (!reject)
26930 // Release the cavity and free the memory.
26931 releasebowatcavity(NULL, n, &sublist, &subceillist, tetlists,
26932 ceillists);
26933 if (reject) {
26934 // Are there queued encroached subsegments.
26935 if (badsubsegs->items > 0) {
26936 // Repair enc-subsegments.
26937 oldptnum = points->items;
26938 repairencsegs(true, chkbadtet);
26939 if (points->items > oldptnum) {
26940 // Some enc-subsegments got split. Try to repair f later.
26941 splitsub = encloop->ss;
26942 if (!isdead(&splitsub)) {
26943 if (!shell2badface(splitsub)) {
26944 checksub4encroach(&splitsub, NULL, true);
26945 if (!shell2badface(splitsub)) {
26946 if (varconstraint && (areabound(splitsub) > 0.0)) {
26947 checksub4badqual(&splitsub, true);
26948 }
26949 }
26950 }
26951 }
26952 }
26953 }
26954 }
26955 } else {
26956 // Don't insert p for one of the following reasons:
26957 // (1) Locate on an existing vertex; or
26958 // (2) locate outside the domain.
26959 // Case (1) should not be possible. If such vertex v exists, it is
26960 // the circumcenter of f, ie., f is non-Delaunay. Either f was got
26961 // split before by v, but survived after v was inserted, or the
26962 // same for a f' which is nearly co-circular with f. Whatsoever,
26963 // there are encroached segs by v, but the routine tallencsegs()
26964 // did not find them out.
26965 if (loc == ONVERTEX) {
26966 printf("Internal error in repairencsubs():\n");
26967 printf(" During repairing encroached subface (%d, %d, %d)\n",
26968 pointmark(encloop->forg), pointmark(encloop->fdest),
26969 pointmark(encloop->fapex));
26970 printf(" New point %d is coincident with an existing vertex %d\n",
26971 pointmark(newpt), pointmark(sorg(splitsub)));
26972 internalerror();
26973 }
26974 // Case (2) can happen when thers is a segment s which is close to f
26975 // and is non-conforming Delaunay. The circumcenter of f encroaches
26976 // upon s, but the circumcenter of s is rejected for insertion.
26977 pointdealloc(newpt);
26978 } // if ((loc != ONVERTEX) && (loc != OUTSIDE))
26979 } else {
26980 if (!isdead(&splitsub)) {
26981 // The subface has been changed, re-check it.
26982 checksub4encroach(&splitsub, NULL, true);
26983 if (!shell2badface(splitsub)) {
26984 if (varconstraint && (areabound(splitsub) > 0.0)) {
26985 checksub4badqual(&splitsub, true);
26986 }
26987 }
26988 }
26989 } // if (!isdead(&splitsub) && (sorg(splitsub) == encloop->forg) &&
26990 // Remove this entry from list.
26991 badfacedealloc(badsubfaces, encloop);
26992 } // while ((badsubfaces->items > 0) && (steinerleft != 0))
26993
26994 delete verlist;
26995 }
26996
26997 ///////////////////////////////////////////////////////////////////////////////
26998 // //
26999 // repairbadtets() Repair all bad-quality tetrahedra. //
27000 // //
27001 // All bad-quality tets are stored in pool 'badtetrahedrons'. Each bad tet //
27002 // is repaired by inserting a point at or near its circumcenter. However, if //
27003 // this point encroaches any subsegment or subface, it is not inserted. Ins- //
27004 // tead the encroached segment and subface are split. Newly inserted points //
27005 // may create other bad-quality tets, these are also repaired. //
27006 // //
27007 ///////////////////////////////////////////////////////////////////////////////
27008
27009 void tetgenmesh::repairbadtets()
27010 {
27011 list *tetlist, *ceillist;
27012 list *verlist;
27013 badface *badtet;
27014 triface starttet;
27015 point newpt;
27016 enum locateresult loc;
27017 bool reject;
27018 long oldptnum;
27019 int i;
27020
27021 tetlist = new list(sizeof(triface), NULL, 1024);
27022 ceillist = new list(sizeof(triface), NULL, 1024);
27023 verlist = new list(sizeof(point *), NULL, 256);
27024
27025 // Loop until pool 'badtetrahedrons' is empty. Note that steinerleft == -1
27026 // if an unlimited number of Steiner points is allowed.
27027 while ((badtetrahedrons->items > 0) && (steinerleft != 0)) {
27028 // Get a bad-quality tet t.
27029 badtet = dequeuebadtet();
27030 // Make sure that the tet is still the same one when it was tested.
27031 // Subsequent transformations may have made it a different tet.
27032 if (!isdead(&badtet->tt) && org(badtet->tt) == badtet->forg &&
27033 dest(badtet->tt) == badtet->fdest &&
27034 apex(badtet->tt) == badtet->fapex &&
27035 oppo(badtet->tt) == badtet->foppo) {
27036 // Create the new point p.
27037 makepoint(&newpt);
27038 for (i = 0; i < 3; i++) newpt[i] = badtet->cent[i];
27039 setpointtype(newpt, FREEVOLVERTEX);
27040 // Locate p.
27041 starttet = badtet->tt;
27042 loc = preciselocate(newpt, &starttet, tetrahedrons->items);
27043 if ((loc != ONVERTEX) && (loc != OUTSIDE)) {
27044 // For BC(p) and B(p).
27045 infect(starttet);
27046 tetlist->append(&starttet);
27047 formbowatcavityquad(newpt, tetlist, ceillist);
27048 // Check for encroached subsegments.
27049 reject = tallencsegs(newpt, 1, &ceillist);
27050 if (!reject) {
27051 // Check for encroached subfaces.
27052 reject = tallencsubs(newpt, 1, &ceillist);
27053 }
27054 if (!reject) {
27055 // Does p allowed to be inseted?
27056 reject = !acceptvolpt(newpt, ceillist, verlist);
27057 }
27058 if (!reject) {
27059 reject = !trimbowatcavity(newpt, NULL, 1, NULL, NULL, &tetlist,
27060 &ceillist, -1.0);
27061 }
27062 if (!reject) {
27063 // BC(p) should include t, so that t can be removed after BC(p) is
27064 // remeshed. However, if there are locally non-Delaunay faces
27065 // and encroached subsegments/subfaces, t may not be collected
27066 // in BC(p). p should not be inserted in such case.
27067 reject = !infected(badtet->tt);
27068 if (reject) outbowatcircumcount++;
27069 }
27070 if (!reject) {
27071 // Insert p.
27072 bowatinsertsite(newpt, NULL, 1, NULL, NULL, &tetlist, &ceillist,
27073 NULL, NULL, false, false, true);
27074 setnewpointsize(newpt, verlist);
27075 if (steinerleft > 0) steinerleft--;
27076 } else {
27077 // p is rejected for one of the following reasons:
27078 // (1) BC(p) is not valid.
27079 // (2) t does not in BC(p).
27080 // (3) p encroaches upon some segments;
27081 // (4) p encroaches upon some subfaces;
27082 // (5) p is rejected by the point accepting rule.
27083 pointdealloc(newpt);
27084 // Uninfect tets of BC(p).
27085 for (i = 0; i < tetlist->len(); i++) {
27086 starttet = * (triface *)(* tetlist)[i];
27087 uninfect(starttet);
27088 }
27089 }
27090 tetlist->clear();
27091 ceillist->clear();
27092 verlist->clear();
27093 // Split encroached subsegments/subfaces if there are.
27094 if (reject) {
27095 oldptnum = points->items;
27096 if (badsubsegs->items > 0) {
27097 repairencsegs(true, true);
27098 }
27099 if (badsubfaces->items > 0) {
27100 repairencsubs(true);
27101 }
27102 if (points->items > oldptnum) {
27103 // Some encroaching subsegments/subfaces have been split.
27104 starttet = badtet->tt;
27105 if (!isdead(&starttet)) {
27106 checktet4badqual(&starttet, true);
27107 }
27108 }
27109 }
27110 } else {
27111 // Do not insert p. The reason may be one of:
27112 // (1) p is coincident (ONVERTEX) with an existing vertex; or
27113 // (2) p is outside (OUTSIDE) the mesh.
27114 // Case (1) should not be possible. If such vertex v exists, it is
27115 // the circumcenter of t, ie., t is non-Delaunay. Either t was got
27116 // split before by v, but survived after v was inserted, or the
27117 // same for a t' which is nearly co-spherical with t. Whatsoever,
27118 // there are encroached segments or subfaces by v but the routines
27119 // tallencsegs() or tallencsubs() did not find them out.
27120 if (loc == ONVERTEX) {
27121 printf("Internal error in repairbadtets():\n");
27122 printf(" During repairing bad tet (%d, %d, %d, %d)\n",
27123 pointmark(badtet->forg), pointmark(badtet->fdest),
27124 pointmark(badtet->fapex), pointmark(badtet->foppo));
27125 printf(" New point %d is coincident with an existing vertex %d\n",
27126 pointmark(newpt), pointmark(org(starttet)));
27127 internalerror();
27128 }
27129 // Case (2) can happen when there is a segment s (or subface f) which
27130 // is close to f and is non-conforming Delaunay. The circumcenter
27131 // of t encroaches upon s (or f), but the circumcenter of s (or f)
27132 // is rejected for insertion.
27133 pointdealloc(newpt);
27134 } // if ((loc != ONVERTEX) && (loc != OUTSIDE))
27135 } // if (!isdead(&badtet->tt) && org(badtet->tt) == badtet->forg &&
27136 // Remove the tet from the pool.
27137 badfacedealloc(badtetrahedrons, badtet);
27138 } // while ((badtetrahedrons->items > 0) && (steinerleft != 0))
27139
27140 delete tetlist;
27141 delete ceillist;
27142 delete verlist;
27143 }
27144
27145 ///////////////////////////////////////////////////////////////////////////////
27146 // //
27147 // enforcequality() Refine the mesh. //
27148 // //
27149 ///////////////////////////////////////////////////////////////////////////////
27150
27151 void tetgenmesh::enforcequality()
27152 {
27153 long total, vertcount;
27154 int i;
27155
27156 if (!b->quiet) {
27157 printf("Adding Steiner points to enforce quality.\n");
27158 }
27159
27160 total = vertcount = 0l;
27161 if (b->conformdel) {
27162 r2count = r3count = 0l;
27163 }
27164
27165 if (b->refine) {
27166 // Mark segment vertices (acute or not).
27167 markacutevertices(89.0);
27168 }
27169 if (!b->bgmesh) {
27170 // Calculate the node local feature sizes.
27171 calclocalfeaturesizes();
27172 }
27173 // Mark sharp subfaces (for termination).
27174 marksharpsubsegs(89.0);
27175 // Mark skinny subfaces (for reducing Steiner points).
27176 markskinnysubfaces(19.0);
27177
27178 // Initialize the pool of encroached subsegments.
27179 badsubsegs = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
27180 // Looking for encroached subsegments.
27181 tallencsegs(NULL, 0, NULL);
27182 if (b->verbose && badsubsegs->items > 0) {
27183 printf(" Splitting encroached subsegments.\n");
27184 }
27185 vertcount = points->items;
27186 // Fix encroached segments without noting any enc subfaces.
27187 repairencsegs(false, false);
27188 if (b->verbose > 0) {
27189 printf(" %ld split points.\n", points->items - vertcount);
27190 }
27191 total += points->items - vertcount;
27192
27193 // Initialize the pool of encroached subfaces.
27194 badsubfaces = new memorypool(sizeof(badface), SUBPERBLOCK, POINTER, 0);
27195 // Initialize the priority queues of badfaces.
27196 for (i = 0; i < 3; i++) subquefront[i] = (badface *) NULL;
27197 for (i = 0; i < 3; i++) subquetail[i] = &subquefront[i];
27198 // Looking for encroached subfaces.
27199 tallencsubs(NULL, 0, NULL);
27200 if (b->verbose && badsubfaces->items > 0) {
27201 printf(" Splitting encroached subfaces.\n");
27202 }
27203 vertcount = points->items;
27204 // Fix encroached subfaces without noting bad tetrahedra.
27205 repairencsubs(false);
27206 if (b->verbose > 0) {
27207 printf(" %ld split points.\n", points->items - vertcount);
27208 }
27209 total += points->items - vertcount;
27210 // At this point, the mesh should be conforming Delaunay if no input
27211 // angle is smaller than 90 degree.
27212
27213 // Next, fix bad quality tetrahedra.
27214 if ((b->minratio > 0.0) || b->varvolume || b->fixedvolume) {
27215 // Initialize the pool of bad tets
27216 badtetrahedrons = new memorypool(sizeof(badface), ELEPERBLOCK, POINTER, 0);
27217 // Initialize the priority queues of bad tets.
27218 for (i = 0; i < 64; i++) tetquefront[i] = (badface *) NULL;
27219 for (i = 0; i < 64; i++) tetquetail[i] = &tetquefront[i];
27220 // Looking for bad quality tets.
27221 tallbadtetrahedrons();
27222 if (b->verbose && badtetrahedrons->items > 0) {
27223 printf(" Splitting bad tetrahedra.\n");
27224 }
27225 vertcount = points->items;
27226 repairbadtets();
27227 if (b->verbose > 0) {
27228 printf(" %ld refinement points.\n", points->items - vertcount);
27229 }
27230 total += points->items - vertcount;
27231 delete badtetrahedrons;
27232 }
27233
27234 if (b->verbose > 0) {
27235 printf(" Totally added %ld points.\n", total);
27236 }
27237
27238 delete badsubfaces;
27239 delete badsubsegs;
27240 }
27241
27242 //
27243 // End of Delaunay refinement routines
27244 //
27245
27246 //
27247 // Begin of mesh smoothing routines
27248 //
27249
27250 ///////////////////////////////////////////////////////////////////////////////
27251 // //
27252 // checktet4ill() Check a tet to see if it is illegal. //
27253 // //
27254 // A tet is "illegal" if it spans on one input facet. Save the tet in queue //
27255 // if it is illegal and the flag 'enqflag' is set. //
27256 // //
27257 // Note: Such case can happen when the input facet has non-coplanar vertices //
27258 // and the Delaunay tetrahedralization of the vertices may creat such tets. //
27259 // //
27260 ///////////////////////////////////////////////////////////////////////////////
27261
27262 bool tetgenmesh::checktet4ill(triface* testtet, bool enqflag)
27263 {
27264 badface *newbadtet;
27265 triface checktet;
27266 face checksh1, checksh2;
27267 face checkseg;
27268 bool illflag;
27269 int i;
27270
27271 illflag = false;
27272 for (testtet->loc = 0; testtet->loc < 4; testtet->loc++) {
27273 tspivot(*testtet, checksh1);
27274 if (checksh1.sh != dummysh) {
27275 testtet->ver = 0;
27276 findedge(&checksh1, org(*testtet), dest(*testtet));
27277 for (i = 0; i < 3; i++) {
27278 fnext(*testtet, checktet);
27279 tspivot(checktet, checksh2);
27280 if (checksh2.sh != dummysh) {
27281 // Two subfaces share this edge. It should be a segment.
27282 sspivot(checksh1, checkseg);
27283 if (checkseg.sh == dummysh) {
27284 illflag = true; break;
27285 }
27286 }
27287 enextself(*testtet);
27288 senextself(checksh1);
27289 }
27290 }
27291 if (illflag) break;
27292 }
27293
27294 if (illflag && enqflag) {
27295 // Allocate space for the bad tetrahedron.
27296 newbadtet = (badface *) badtetrahedrons->alloc();
27297 newbadtet->tt = *testtet;
27298 newbadtet->key = 0.0;
27299 for (i = 0; i < 3; i++) newbadtet->cent[i] = 0.0;
27300 newbadtet->forg = org(*testtet);
27301 newbadtet->fdest = dest(*testtet);
27302 newbadtet->fapex = apex(*testtet);
27303 newbadtet->foppo = oppo(*testtet);
27304 newbadtet->nextitem = (badface *) NULL;
27305 if (b->verbose > 2) {
27306 printf(" Queueing illtet: (%d, %d, %d, %d).\n",
27307 pointmark(newbadtet->forg), pointmark(newbadtet->fdest),
27308 pointmark(newbadtet->fapex), pointmark(newbadtet->foppo));
27309 }
27310 }
27311
27312 return illflag;
27313 }
27314
27315 ///////////////////////////////////////////////////////////////////////////////
27316 // //
27317 // checktet4sliver() Check a tet to see if it is a sliver. //
27318 // //
27319 // A sliver is a tet has no small edges, but has a nearly zero volume. When //
27320 // the mesh quality is measured by radios-edge ratio, slivers can have rela- //
27321 // tively small value and are not classified as bad quality. //
27322 // //
27323 // This routine finds whether a tet is a sliver or not by checking the bigg- //
27324 // est dihedral angle of the tet. It is a sliver if the angle is larger than //
27325 // 'maxdihed' (default is 170 degree, can be adjusted by '-s' option). //
27326 // //
27327 // If the flag 'chkill' is set, only check the volume of tet. It is a sliver //
27328 // if it has a zero or negative volume. //
27329 // //
27330 ///////////////////////////////////////////////////////////////////////////////
27331
27332 bool tetgenmesh::checktet4sliver(triface* testtet, bool chkill, bool enqflag)
27333 {
27334 badface *newbadtet;
27335 point pa, pb, pc, pd;
27336 REAL N[4][3], volume, len;
27337 REAL cosd, smallcosd;
27338 bool enq;
27339 int edgeno, i, j;
27340
27341 enq = false;
27342
27343 pa = (point) testtet->tet[4];
27344 pb = (point) testtet->tet[5];
27345 pc = (point) testtet->tet[6];
27346 pd = (point) testtet->tet[7];
27347 // Compute the 4 face normals (N[0], ..., N[3]).
27348 tetallnormal(pa, pb, pc, pd, N, &volume);
27349 // Normalize the normals.
27350 for (i = 0; i < 4; i++) {
27351 len = sqrt(dot(N[i], N[i]));
27352 if (len != 0.0) {
27353 for (j = 0; j < 3; j++) N[i][j] /= len;
27354 }
27355 }
27356 // Find the largest dihedral and the edge.
27357 smallcosd = -dot(N[2], N[3]); // Edge ab.
27358 edgeno = 0;
27359 for (i = 1; i < 4; i++) {
27360 cosd = -dot(N[0], N[i]); // Edge cd, bd, bc.
27361 if (cosd < smallcosd) {
27362 smallcosd = cosd;
27363 edgeno = i;
27364 }
27365 }
27366 for (i = 2; i < 4; i++) {
27367 cosd = -dot(N[1], N[i]); // Edge ad, ac.
27368 if (cosd < smallcosd) {
27369 smallcosd = cosd;
27370 edgeno = i + 2;
27371 }
27372 }
27373 // Check if abcd is sliver.
27374 if (!chkill) {
27375 enq = ((smallcosd > cosmindihed) || ((smallcosd < cosmaxdihed)));
27376 } else {
27377 enq = (volume <= 0.0);
27378 }
27379
27380 if (enq && enqflag) {
27381 // Let t represent the edge having the biggest dihedral angle.
27382 testtet->loc = 0;
27383 testtet->ver = 0;
27384 switch (edgeno) {
27385 case 0: break; // edge ab
27386 case 1: // edge cd
27387 enextfnextself(*testtet);
27388 enextself(*testtet);
27389 break;
27390 case 2: // edge bd
27391 enextfnextself(*testtet);
27392 enext2self(*testtet);
27393 break;
27394 case 3: // edge bc
27395 enextself(*testtet);
27396 break;
27397 case 4: // edge ad
27398 enext2fnextself(*testtet);
27399 enextself(*testtet);
27400 break;
27401 case 5: // edge ac
27402 enext2self(*testtet);
27403 break;
27404 }
27405 // Allocate space for the bad tetrahedron.
27406 newbadtet = (badface *) badtetrahedrons->alloc();
27407 newbadtet->tt = *testtet;
27408 newbadtet->key = smallcosd;
27409 for (i = 0; i < 3; i++) newbadtet->cent[i] = 0.0;
27410 newbadtet->forg = org(*testtet);
27411 newbadtet->fdest = dest(*testtet);
27412 newbadtet->fapex = apex(*testtet);
27413 newbadtet->foppo = oppo(*testtet);
27414 newbadtet->nextitem = (badface *) NULL;
27415 if (b->verbose > 2) {
27416 printf(" Queueing sliver: (%d, %d, %d, %d), maxdihed %g (degree).\n",
27417 pointmark(newbadtet->forg), pointmark(newbadtet->fdest),
27418 pointmark(newbadtet->fapex), pointmark(newbadtet->foppo),
27419 acos(smallcosd) * 180.0 / PI);
27420 }
27421 }
27422
27423 return enq;
27424 }
27425
27426 ///////////////////////////////////////////////////////////////////////////////
27427 // //
27428 // removetetbystripoff() Remove a boundary tet by stripping it off. //
27429 // //
27430 // 'striptet' (abcd) is on boundary and can be removed by stripping it off. //
27431 // Let abc and bad are the external boundary faces. //
27432 // //
27433 // To strip 'abcd' from the mesh is to detach its two interal faces (dca and //
27434 // cdb) from their adjoining tets together with a 2-to-2 flip to transform //
27435 // two subfaces (abc and bad) into another two (dca and cdb). //
27436 // //
27437 ///////////////////////////////////////////////////////////////////////////////
27438
27439 void tetgenmesh::removetetbystripoff(triface *striptet)
27440 {
27441 triface abcd, badc;
27442 triface dcacasing, cdbcasing;
27443 face abc, bad;
27444
27445 if (b->verbose > 1) {
27446 printf(" by stripping it off.\n");
27447 }
27448
27449 striptetcount++;
27450
27451 abcd = *striptet;
27452 adjustedgering(abcd, CCW);
27453
27454 // Get the external subfaces abc, bad.
27455 fnext(abcd, badc);
27456 esymself(badc);
27457 tspivot(abcd, abc);
27458 tspivot(badc, bad);
27459 #ifdef SELF_CHECK
27460 assert((abc.sh != dummysh) && (bad.sh != dummysh));
27461 #endif
27462 findedge(&abc, org(abcd), dest(abcd));
27463 findedge(&bad, org(badc), dest(badc));
27464
27465 // Get the casing tets at the internal sides.
27466 enextfnext(abcd, cdbcasing);
27467 enext2fnext(abcd, dcacasing);
27468 symself(cdbcasing);
27469 symself(dcacasing);
27470 #ifdef SELF_CHECK
27471 assert(cdbcasing.tet != dummytet && dcacasing.tet != dummytet);
27472 #endif
27473
27474 // Do a 2-to-2 flip on abc and bad, transform abc->dca, bad->cdb.
27475 flip22sub(&abc, NULL);
27476 // Detach abcd from the two internal faces.
27477 dissolve(cdbcasing);
27478 dissolve(dcacasing);
27479 // The two internal faces become boundary faces.
27480 tsbond(cdbcasing, bad);
27481 tsbond(dcacasing, abc);
27482 // Delete abcd.
27483 tetrahedrondealloc(abcd.tet);
27484 }
27485
27486 ///////////////////////////////////////////////////////////////////////////////
27487 // //
27488 // removetetbyflip32() Remove a tet by a 3-to-2 flip. //
27489 // //
27490 // 'fliptet' (abcd) is going to be removed by a 3-to-2 flip. ab is the edge //
27491 // will be flipped away, i.e., abc, bad, and abe are three internal faces. //
27492 // //
27493 // Note: If abc and bad are subfaces(abe must not), a 2-to-2 flip is used to //
27494 // transform abc, bad into dca, cdb prior to the 3-to-2 flip. //
27495 // //
27496 // If 'enq' flag is set, check the two new tets after flip to see if they're //
27497 // slivers or illegal tets according to the 'chkill' flag. //
27498 // //
27499 ///////////////////////////////////////////////////////////////////////////////
27500
27501 void tetgenmesh::removetetbyflip32(triface *fliptet, bool enq, bool chkill)
27502 {
27503 triface abcd, badc;
27504 triface cdab, dcba;
27505 triface baccasing, abdcasing;
27506 triface dcacasing, cdbcasing;
27507 face abc, bad;
27508 REAL attrib, volume;
27509 int i;
27510
27511 if (b->verbose > 1) {
27512 printf(" by a 3-to-2 flip.\n");
27513 }
27514
27515 fliptetcount++;
27516
27517 abcd = *fliptet;
27518 adjustedgering(abcd, CCW);
27519 fnext(abcd, badc);
27520 esymself(badc);
27521 sym(abcd, baccasing);
27522 sym(badc, abdcasing);
27523 #ifdef SELF_CHECK
27524 assert((baccasing.tet != dummytet) && (abdcasing.tet != dummytet));
27525 assert(oppo(baccasing) == oppo(abdcasing));
27526 #endif
27527
27528 // Get subfaces abc, bad.
27529 tspivot(abcd, abc);
27530 tspivot(badc, bad);
27531 if (abc.sh != dummysh) {
27532 #ifdef SELF_CHECK
27533 // Because ab is not a subsegment.
27534 assert(bad.sh != dummysh);
27535 #endif
27536 // abc and bad are internal subfaces. tets baccasing and abdcasing must
27537 // have the same attributes (such as the region attribute if the -A
27538 // switch is in use). But abcd may not be at the same region. After
27539 // flip32, if abcd is not deleted, it will have the wrong attributes.
27540 // Set abcd be the same region attributes as baccasing and abdcasing.
27541 for (i = 0; i < in->numberoftetrahedronattributes; i++) {
27542 attrib = elemattribute(baccasing.tet, i);
27543 #ifdef SELF_CHECK
27544 REAL testattr = elemattribute(abdcasing.tet, i);
27545 assert(attrib == testattr);
27546 #endif
27547 setelemattribute(abcd.tet, i, attrib);
27548 }
27549 if (b->varvolume) {
27550 volume = volumebound(baccasing.tet);
27551 setvolumebound(abcd.tet, volume);
27552 }
27553 findedge(&abc, org(abcd), dest(abcd));
27554 findedge(&bad, org(badc), dest(badc));
27555 // Detach abc, bad from the four tets at both sides.
27556 stdissolve(abc);
27557 stdissolve(bad);
27558 sesymself(abc);
27559 sesymself(bad);
27560 stdissolve(abc);
27561 stdissolve(bad);
27562 sesymself(abc);
27563 sesymself(bad);
27564 // Detach the four tets which hold abc and bad.
27565 tsdissolve(abcd);
27566 tsdissolve(badc);
27567 tsdissolve(baccasing);
27568 tsdissolve(abdcasing);
27569 // Perform a 2-to-2 flip on abc, bad, transform abc->dca, bad->cdb.
27570 flip22sub(&abc, NULL);
27571 // Insert the flipped subfaces abc and bad into tets.
27572 enextfnext(abcd, dcba); // dcba = bcda
27573 esymself(dcba); // dcba = cbda
27574 enext2fnext(abcd, cdab); // cdab = cadb
27575 esymself(cdab); // cdab = acdb
27576 findedge(&abc, org(cdab), dest(cdab));
27577 tsbond(cdab, abc);
27578 findedge(&bad, org(dcba), dest(dcba));
27579 tsbond(dcba, bad);
27580 // Bond the other sides of cdab, dcba, they may outer space.
27581 sym(cdab, dcacasing);
27582 sym(dcba, cdbcasing);
27583 sesymself(abc);
27584 sesymself(bad);
27585 tsbond(dcacasing, abc);
27586 tsbond(cdbcasing, bad);
27587 }
27588 // Remove abcd by a 3-to-2 flip.
27589 flip32(&abcd, NULL);
27590 // After flip abc is the internal face.
27591
27592 if (enq) {
27593 // Get the adjtet of abcd (in badc).
27594 sym(abcd, badc);
27595 if (chkill) {
27596 // Test the two new tets to see if they are illegal.
27597 checktet4ill(&abcd, true);
27598 checktet4ill(&badc, true);
27599 } else {
27600 // Test the two new tets to see if they are sliver.
27601 checktet4sliver(&abcd, false, true);
27602 checktet4sliver(&badc, false, true);
27603 }
27604 }
27605 }
27606
27607 ///////////////////////////////////////////////////////////////////////////////
27608 // //
27609 // removetetbyrecon() Remove a tet by local reconnection. //
27610 // //
27611 // 'remtet' (abcd) is wanted to be removed from the mesh. ab is the primary //
27612 // edge (which is diagonal if a, b, c, and d form a convex quadrilateral). //
27613 // //
27614 // abcd is removable if it is not a segment, and either it can be stripped //
27615 // off or it can be flipped away. //
27616 // //
27617 // The return value indicates abcd is remveable or not. Note, although abcd //
27618 // is removeable but it may not be removed when 'chkill' is FALSE. //
27619 // //
27620 ///////////////////////////////////////////////////////////////////////////////
27621
27622 bool tetgenmesh::removetetbyrecon(badface* remtet, bool chkill)
27623 {
27624 triface abcd, badc; // Tet configuration at edge ab.
27625 triface baccasing, abdcasing;
27626 face abseg;
27627 point pa, pb, pc, pd, pe;
27628 REAL ori1, ori2;
27629 REAL cosmaxd1, cosmaxd2;
27630 bool remflag;
27631 int i;
27632
27633 remflag = false;
27634 // tet 'abcd' is indicated to remove.
27635 abcd = remtet->tt;
27636 // Check if abcd is removeable (at edge ab and cd).
27637 for (i = 0; i < 2; i++) {
27638 // If ab a segment, it is unremoveable.
27639 tsspivot(&abcd, &abseg);
27640 if (abseg.sh == dummysh) {
27641 adjustedgering(abcd, CCW);
27642 // Get the tet configuration at edge ab (or cd).
27643 fnext(abcd, badc);
27644 esymself(badc);
27645 sym(abcd, baccasing);
27646 sym(badc, abdcasing);
27647 // Can 'abcd' be stripped off?
27648 if ((baccasing.tet == dummytet) && (abdcasing.tet == dummytet)) {
27649 removetetbystripoff(&abcd);
27650 remflag = true;
27651 break; // abcd has been removed.
27652 } else if (oppo(baccasing) == oppo(abdcasing)) {
27653 // Can 'abcd' be flipped away?
27654 pa = org(abcd);
27655 pb = dest(abcd);
27656 pc = apex(abcd);
27657 pd = oppo(abcd);
27658 pe = oppo(baccasing);
27659 // Check if face cde is crossed by ab.
27660 ori1 = orient3d(pc, pd, pe, pa);
27661 ori2 = orient3d(pc, pd, pe, pb);
27662 if (ori1 * ori2 < 0.0) {
27663 // ab can be flipped away.
27664 if (!chkill) {
27665 // Do flip if the maximal dihedrals of the new tets are reduced?
27666 tetalldihedral(pd, pc, pe, pa, NULL, &cosmaxd1, NULL);
27667 tetalldihedral(pc, pd, pe, pb, NULL, &cosmaxd2, NULL);
27668 if ((remtet->key <= cosmaxd1) && (remtet->key <= cosmaxd2)) {
27669 removetetbyflip32(&abcd, true, chkill);
27670 remflag = true;
27671 break; // abcd has been removed.
27672 }
27673 } else {
27674 removetetbyflip32(&abcd, true, chkill);
27675 remflag = true;
27676 break; // abcd has been removed.
27677 }
27678 }
27679 }
27680 } // if (abseg.sh == dummysh)
27681 // 'abcd' is not removed (although it may be removeable).
27682 if (i == 1) break; // Stop if both ab and cd have been checked.
27683 // Go to edge cd, re-use handle abcd.
27684 enextfnextself(abcd);
27685 esymself(abcd);
27686 enext2self(abcd);
27687 } // for (i = 0; i < 2; i++)
27688
27689 return remflag;
27690 }
27691
27692 ///////////////////////////////////////////////////////////////////////////////
27693 // //
27694 // removetetbysplit() Remove a tet by inserting a point in it. //
27695 // //
27696 ///////////////////////////////////////////////////////////////////////////////
27697
27698 bool tetgenmesh::removetetbysplit(badface* remtet)
27699 {
27700 list **tetlists, **ceillists;
27701 list **sublists, **subceillists;
27702 list *tetlist, *ceillist, *verlist;
27703 triface abcd, starttet;
27704 face abseg, abcsh;
27705 point newpt, refpt;
27706 REAL maxcosd;
27707 int nmax, n;
27708 int i, j;
27709
27710 // tet 'abcd' is indicated to remove.
27711 abcd = remtet->tt;
27712 abseg.sh = dummysh;
27713 abcsh.sh = dummysh;
27714
27715 // Check if ab or cd is a segment.
27716 tsspivot(&abcd, &abseg);
27717 if (abseg.sh == dummysh) {
27718 adjustedgering(abcd, CCW);
27719 enextfnextself(abcd);
27720 enextself(abcd);
27721 tsspivot(&abcd, &abseg);
27722 }
27723 if (abseg.sh == dummysh) {
27724 abcd = remtet->tt;
27725 adjustedgering(abcd, CCW);
27726 // Check if abc is a subface.
27727 tspivot(abcd, abcsh);
27728 if (abcsh.sh == dummysh) {
27729 // Check if bad is a subface.
27730 fnextself(abcd);
27731 tspivot(abcd, abcsh);
27732 if (abcsh.sh == dummysh) {
27733 // Check if cda is a subface
27734 abcd = remtet->tt;
27735 adjustedgering(abcd, CCW);
27736 enext2fnextself(abcd);
27737 enext2self(abcd);
27738 esymself(abcd);
27739 tspivot(abcd, abcsh);
27740 if (abcsh.sh == dummysh) {
27741 // Check if cdb is a subface
27742 fnextself(abcd);
27743 tspivot(abcd, abcsh);
27744 }
27745 }
27746 }
27747 }
27748
27749 if (abseg.sh != dummysh) {
27750 if (checkpbcs) {
27751 // Do not split ab if it belongs to any pbcgroup.
27752 i = shellmark(abseg) - 1;
27753 if (idx2segpglist[i + 1] > idx2segpglist[i]) {
27754 return false; // There are pbc facets at ab.
27755 }
27756 }
27757 // Find if segment ab is encroached by an existing point.
27758 refpt = (point) NULL;
27759 checkseg4encroach(&abseg, NULL, &refpt, false);
27760 // Find a point in segment ab.
27761 makepoint(&newpt);
27762 getsplitpoint(sorg(abseg), sdest(abseg), refpt, newpt);
27763 setpointtype(newpt, FREESEGVERTEX);
27764 setpoint2sh(newpt, sencode(abseg));
27765 maxcosd = remtet->key;
27766 if (refpt != (point) NULL) {
27767 // ab is encroached. Force p to be inserted.
27768 maxcosd = -1.0; // 180 degree
27769 }
27770 n = 0;
27771 nmax = 128;
27772 tetlists = new list*[nmax];
27773 ceillists = new list*[nmax];
27774 sublists = new list*[nmax];
27775 subceillists = new list*[nmax];
27776 verlist = new list(sizeof(point *), NULL, 256);
27777 // Form BC(p).
27778 formbowatcavity(newpt, &abseg, NULL, &n, &nmax, sublists, subceillists,
27779 tetlists, ceillists);
27780 // Can local maximal dihedral be reduced by inserting p?
27781 if (trimbowatcavity(newpt, &abseg, n, sublists, subceillists, tetlists,
27782 ceillists, maxcosd)) {
27783 // Inserting p. Ignore any new enc-seg, enc-sub, and bad tets.
27784 bowatinsertsite(newpt, &abseg, n, sublists, subceillists, tetlists,
27785 ceillists, verlist, NULL, false, false, false);
27786 setnewpointsize(newpt, verlist);
27787 // Check if there are new slivers at p.
27788 for (j = 0; j < n; j++) {
27789 tetlist = ceillists[j];
27790 for (i = 0; i < tetlist->len(); i++) {
27791 starttet = * (triface *)(* tetlist)[i];
27792 checktet4sliver(&starttet, false, true);
27793 }
27794 }
27795 refpt != (point) NULL ? smoothcdtsegpt++ : smoothsegpt++;
27796 } else {
27797 // The local quality will not be improved. Do not insert p.
27798 pointdealloc(newpt);
27799 newpt = (point) NULL;
27800 refpt != (point) NULL ? unsmoothcdtsegpt++ : unsmoothsegpt++;
27801 }
27802 // Free the memory allocated in formbowatcavity().
27803 releasebowatcavity(&abseg, n, sublists, subceillists, tetlists, ceillists);
27804 delete [] tetlists;
27805 delete [] ceillists;
27806 delete [] sublists;
27807 delete [] subceillists;
27808 delete verlist;
27809 } else if (abcsh.sh != dummysh) {
27810 if (checkpbcs) {
27811 // Do not split abc if it belongs to a pbcgroup.
27812 if (shellpbcgroup(abcsh) >= 0) {
27813 return false; // It is on a pbc facet.
27814 }
27815 }
27816 // Insert the midpoint of ab which is on a facet.
27817 makepoint(&newpt);
27818 getsplitpoint(org(abcd), dest(abcd), NULL, newpt);
27819 setpointtype(newpt, FREESUBVERTEX);
27820 setpoint2sh(newpt, sencode(abcsh));
27821 n = 2;
27822 tetlists = new list*[2];
27823 ceillists = new list*[2];
27824 sublists = new list*[2];
27825 subceillists = new list*[2];
27826 verlist = new list(sizeof(point *), NULL, 256);
27827 // Form BC(p).
27828 formbowatcavity(newpt, NULL, &abcsh, &n, NULL, sublists, subceillists,
27829 tetlists, ceillists);
27830 // Can local maximal dihedral be reduced by inserting p?
27831 if (trimbowatcavity(newpt, NULL, n, sublists, subceillists, tetlists,
27832 ceillists, remtet->key)) {
27833 // Inserting p. Ignore any new enc-seg, enc-sub, and bad tets.
27834 bowatinsertsite(newpt, NULL, n, sublists, subceillists, tetlists,
27835 ceillists, verlist, NULL, false, false, false);
27836 setnewpointsize(newpt, verlist);
27837 // Check if there are new slivers at p.
27838 for (j = 0; j < n; j++) {
27839 tetlist = ceillists[j];
27840 for (i = 0; i < tetlist->len(); i++) {
27841 starttet = * (triface *)(* tetlist)[i];
27842 checktet4sliver(&starttet, false, true);
27843 }
27844 }
27845 smoothsubpt++;
27846 } else {
27847 // The local quality will not be improved. Do not insert p.
27848 pointdealloc(newpt);
27849 newpt = (point) NULL;
27850 unsmoothsubpt++;
27851 }
27852 // Free the memory allocated in formbowatcavity().
27853 releasebowatcavity(NULL, n, sublists, subceillists, tetlists, ceillists);
27854 delete [] tetlists;
27855 delete [] ceillists;
27856 delete [] sublists;
27857 delete [] subceillists;
27858 delete verlist;
27859 } else {
27860 // Insert the midpoint of the edge having largest dihedral angle.
27861 abcd = remtet->tt;
27862 makepoint(&newpt);
27863 getsplitpoint(org(abcd), dest(abcd), NULL, newpt);
27864 setpointtype(newpt, FREEVOLVERTEX);
27865 // Form BC(p).
27866 tetlist = new list(sizeof(triface), NULL, 1024);
27867 ceillist = new list(sizeof(triface), NULL, 1024);
27868 verlist = new list(sizeof(point *), NULL, 256);
27869 starttet = abcd;
27870 infect(starttet);
27871 tetlist->append(&starttet);
27872 formbowatcavityquad(newpt, tetlist, ceillist);
27873 // Can local maximal dihedral be reduced by inserting p?
27874 if (trimbowatcavity(newpt, NULL, 1, NULL, NULL, &tetlist, &ceillist,
27875 remtet->key)) {
27876 // Inserting p. Ignore any new enc-seg, enc-sub, and bad tets.
27877 bowatinsertsite(newpt, NULL, 1, NULL, NULL, &tetlist, &ceillist, verlist,
27878 NULL, false, false, false);
27879 setnewpointsize(newpt, verlist);
27880 // Check if there are new slivers at p.
27881 for (i = 0; i < ceillist->len(); i++) {
27882 starttet = * (triface *)(* ceillist)[i];
27883 checktet4sliver(&starttet, false, true);
27884 }
27885 smoothvolpt++;
27886 } else {
27887 // The local quality will not be improved. Do not insert p.
27888 pointdealloc(newpt);
27889 newpt = (point) NULL;
27890 // Uninfect tets of BC(p).
27891 for (i = 0; i < tetlist->len(); i++) {
27892 starttet = * (triface *)(* tetlist)[i];
27893 uninfect(starttet);
27894 }
27895 unsmoothvolpt++;
27896 }
27897 delete tetlist;
27898 delete ceillist;
27899 delete verlist;
27900 }
27901
27902 return newpt != (point) NULL;
27903 }
27904
27905 ///////////////////////////////////////////////////////////////////////////////
27906 // //
27907 // tallslivers() Queue all the slivers in the mesh. //
27908 // //
27909 ///////////////////////////////////////////////////////////////////////////////
27910
27911 void tetgenmesh::tallslivers(bool chkill)
27912 {
27913 triface tetloop;
27914
27915 tetrahedrons->traversalinit();
27916 tetloop.tet = tetrahedrontraverse();
27917 while (tetloop.tet != (tetrahedron *) NULL) {
27918 if (chkill) {
27919 if (!checktet4sliver(&tetloop, true, true)) {
27920 checktet4ill(&tetloop, true);
27921 }
27922 } else {
27923 checktet4sliver(&tetloop, false, true);
27924 }
27925 tetloop.tet = tetrahedrontraverse();
27926 }
27927 }
27928
27929 ///////////////////////////////////////////////////////////////////////////////
27930 // //
27931 // repairmesh() Remove illegal tets in the mesh. //
27932 // //
27933 ///////////////////////////////////////////////////////////////////////////////
27934
27935 void tetgenmesh::repairmesh()
27936 {
27937 badface *remtet, *lastunrementry;
27938
27939 if (!b->quiet) {
27940 printf("Repairing mesh.\n");
27941 }
27942
27943 // Initialize the pool of bad tets
27944 badtetrahedrons = new memorypool(sizeof(badface), ELEPERBLOCK, POINTER, 0);
27945 lastunrementry = (badface *) NULL;
27946 striptetcount = fliptetcount = unimprovecount = 0l;
27947
27948 // Looking for illegal tets.
27949 tallslivers(true);
27950
27951 // Loop until pool 'badtetrahedrons' is empty.
27952 while (badtetrahedrons->items > 0) {
27953 badtetrahedrons->traversalinit();
27954 remtet = badfacetraverse(badtetrahedrons);
27955 while (remtet != (badface *) NULL) {
27956 // Make sure that the tet is still the same one when it was tested.
27957 // Subsequent transformations may have made it a different tet.
27958 if (!isdead(&remtet->tt) && org(remtet->tt) == remtet->forg &&
27959 dest(remtet->tt) == remtet->fdest &&
27960 apex(remtet->tt) == remtet->fapex &&
27961 oppo(remtet->tt) == remtet->foppo) {
27962 if (b->verbose > 1) {
27963 printf(" Repair tet (%d, %d, %d, %d).\n", pointmark(remtet->forg),
27964 pointmark(remtet->fdest), pointmark(remtet->fapex),
27965 pointmark(remtet->foppo));
27966 }
27967 if (!removetetbyrecon(remtet, true)) {
27968 // An unremoveable tet. Check if it forms a loop.
27969 if (lastunrementry != (badface *) NULL) {
27970 if (remtet == lastunrementry) break;
27971 } else {
27972 // Remember this tet as a breakpoint.
27973 lastunrementry = remtet;
27974 }
27975 } else {
27976 // Clear the breakpoint.
27977 lastunrementry = (badface *) NULL;
27978 // Remove the entry from the queue.
27979 badfacedealloc(badtetrahedrons, remtet);
27980 }
27981 } else {
27982 // Remove the entry from the queue.
27983 badfacedealloc(badtetrahedrons, remtet);
27984 }
27985 remtet = badfacetraverse(badtetrahedrons);
27986 }
27987 // Stop if the above loop was out by force.
27988 if (remtet != (badface *) NULL) break;
27989 }
27990
27991 if (b->verbose) {
27992 if (striptetcount > 0l) {
27993 printf(" %ld tets are stripped off.\n", striptetcount);
27994 }
27995 if (fliptetcount > 0l) {
27996 printf(" %ld tets are flipped away.\n", fliptetcount);
27997 }
27998 if (badtetrahedrons->items > 0l) {
27999 printf(" %ld tets are unremoveable.\n", badtetrahedrons->items);
28000 }
28001 }
28002
28003 delete badtetrahedrons;
28004 badtetrahedrons = (memorypool *) NULL;
28005 }
28006
28007 ///////////////////////////////////////////////////////////////////////////////
28008 // //
28009 // smoothmesh() Smooth the mesh. //
28010 // //
28011 ///////////////////////////////////////////////////////////////////////////////
28012
28013 void tetgenmesh::smoothmesh()
28014 {
28015 badface *remtet, *lastunrementry;
28016
28017 if (!b->quiet) {
28018 printf("Smoothing mesh.\n");
28019 }
28020
28021 // Initialize the pool of bad tets
28022 badtetrahedrons = new memorypool(sizeof(badface), ELEPERBLOCK, POINTER, 0);
28023 cosmaxdihed = cos(b->maxdihedral * PI / 180.0);
28024 cosmindihed = 1.0;
28025 striptetcount = fliptetcount = unimprovecount = 0l;
28026 smoothcdtsegpt = smoothsegpt = smoothsubpt = smoothvolpt = 0l;
28027 unsmoothcdtsegpt = unsmoothsegpt = unsmoothsubpt = unsmoothvolpt = 0l;
28028
28029 // Looking for bad tets.
28030 tallslivers(false);
28031
28032 lastunrementry = (badface *) NULL;
28033 // Loop until pool 'badtetrahedrons' is empty.
28034 while (badtetrahedrons->items > 0) {
28035 badtetrahedrons->traversalinit();
28036 remtet = badfacetraverse(badtetrahedrons);
28037 while (remtet != (badface *) NULL) {
28038 // Make sure that the tet is still the same one when it was tested.
28039 // Subsequent transformations may have made it a different tet.
28040 if (!isdead(&remtet->tt) && org(remtet->tt) == remtet->forg &&
28041 dest(remtet->tt) == remtet->fdest &&
28042 apex(remtet->tt) == remtet->fapex &&
28043 oppo(remtet->tt) == remtet->foppo) {
28044 if (b->verbose > 1) {
28045 printf(" Repair tet (%d, %d, %d, %d).\n", pointmark(remtet->forg),
28046 pointmark(remtet->fdest), pointmark(remtet->fapex),
28047 pointmark(remtet->foppo));
28048 }
28049 if (!removetetbyrecon(remtet, false)) {
28050 // An unremoveable tet. Check if it forms a loop.
28051 if (lastunrementry != (badface *) NULL) {
28052 if (remtet == lastunrementry) break;
28053 } else {
28054 // Remember this tet as a breakpoint.
28055 lastunrementry = remtet;
28056 }
28057 } else {
28058 // Clear the breakpoint.
28059 lastunrementry = (badface *) NULL;
28060 // Remove the entry from the queue.
28061 badfacedealloc(badtetrahedrons, remtet);
28062 }
28063 } else {
28064 // Remove the entry from the queue.
28065 badfacedealloc(badtetrahedrons, remtet);
28066 }
28067 remtet = badfacetraverse(badtetrahedrons);
28068 }
28069 // Stop if the above loop was out by force.
28070 if (remtet != (badface *) NULL) break;
28071 }
28072
28073 if (b->verbose) {
28074 if (striptetcount > 0l) {
28075 printf(" %ld tets are stripped off.\n", striptetcount);
28076 }
28077 if (fliptetcount > 0l) {
28078 printf(" %ld tets are flipped away.\n", fliptetcount);
28079 }
28080 }
28081
28082 lastunrementry = (badface *) NULL;
28083 // Loop until pool 'badtetrahedrons' is empty.
28084 while (badtetrahedrons->items > 0) {
28085 badtetrahedrons->traversalinit();
28086 remtet = badfacetraverse(badtetrahedrons);
28087 while (remtet != (badface *) NULL) {
28088 // Make sure that the tet is still the same one when it was tested.
28089 // Subsequent transformations may have made it a different tet.
28090 if (!isdead(&remtet->tt) && org(remtet->tt) == remtet->forg &&
28091 dest(remtet->tt) == remtet->fdest &&
28092 apex(remtet->tt) == remtet->fapex &&
28093 oppo(remtet->tt) == remtet->foppo) {
28094 if (b->verbose > 1) {
28095 printf(" Repair tet (%d, %d, %d, %d).\n", pointmark(remtet->forg),
28096 pointmark(remtet->fdest), pointmark(remtet->fapex),
28097 pointmark(remtet->foppo));
28098 }
28099 if (!removetetbyrecon(remtet, false)) {
28100 // An unremoveable tet. Find if a segment which can be split.
28101 if (!removetetbysplit(remtet)) {
28102 // An unremoveable tet. Check if it forms a loop.
28103 if (lastunrementry != (badface *) NULL) {
28104 if (remtet == lastunrementry) break;
28105 } else {
28106 // Remember this tet as a breakpoint.
28107 lastunrementry = remtet;
28108 }
28109 } else {
28110 // Clear the breakpoint.
28111 lastunrementry = (badface *) NULL;
28112 // Remove the entry from the queue.
28113 badfacedealloc(badtetrahedrons, remtet);
28114 }
28115 } else {
28116 // Clear the breakpoint.
28117 lastunrementry = (badface *) NULL;
28118 // Remove the entry from the queue.
28119 badfacedealloc(badtetrahedrons, remtet);
28120 }
28121 } else {
28122 // Remove the entry from the queue.
28123 badfacedealloc(badtetrahedrons, remtet);
28124 }
28125 remtet = badfacetraverse(badtetrahedrons);
28126 }
28127 // Stop if the above loop was out by force.
28128 if (remtet != (badface *) NULL) break;
28129 }
28130
28131 if (b->verbose) {
28132 if ((smoothcdtsegpt + smoothsegpt + smoothsubpt + smoothvolpt) > 0l) {
28133 printf(" %ld smooth points.\n",
28134 smoothcdtsegpt + smoothsegpt + smoothsubpt + smoothvolpt);
28135 }
28136 if (badtetrahedrons->items > 0l) {
28137 printf(" %ld remaining tets.\n", badtetrahedrons->items);
28138 }
28139 }
28140
28141 delete badtetrahedrons;
28142 badtetrahedrons = (memorypool *) NULL;
28143 }
28144
28145 //
28146 // End of mesh smoothing routines
28147 //
28148
28149 //
28150 // Begin of I/O rouitnes
28151 //
28152
28153 ///////////////////////////////////////////////////////////////////////////////
28154 // //
28155 // transfernodes() Transfer nodes from 'io->pointlist' to 'this->points'. //
28156 // //
28157 // Initializing 'this->points'. Transferring all points from 'in->pointlist'//
28158 // into it. All points are indexed (start from in->firstnumber). Each point //
28159 // is initialized be UNUSEDVERTEX. The bounding box (xmin, xmax, ymin, ymax,//
28160 // zmin, zmax) and the diameter (longest) of the point set are calculated. //
28161 // //
28162 ///////////////////////////////////////////////////////////////////////////////
28163
28164 void tetgenmesh::transfernodes()
28165 {
28166 point pointloop;
28167 REAL x, y, z;
28168 int coordindex;
28169 int attribindex;
28170 int i, j;
28171
28172 // Read the points.
28173 coordindex = 0;
28174 attribindex = 0;
28175 for (i = 0; i < in->numberofpoints; i++) {
28176 makepoint(&pointloop);
28177 // Read the point coordinates.
28178 x = pointloop[0] = in->pointlist[coordindex++];
28179 y = pointloop[1] = in->pointlist[coordindex++];
28180 z = pointloop[2] = in->pointlist[coordindex++];
28181 // Read the point attributes.
28182 for (j = 0; j < in->numberofpointattributes; j++) {
28183 pointloop[3 + j] = in->pointattributelist[attribindex++];
28184 }
28185 // Determine the smallest and largests x, y and z coordinates.
28186 if (i == 0) {
28187 xmin = xmax = x;
28188 ymin = ymax = y;
28189 zmin = zmax = z;
28190 } else {
28191 xmin = (x < xmin) ? x : xmin;
28192 xmax = (x > xmax) ? x : xmax;
28193 ymin = (y < ymin) ? y : ymin;
28194 ymax = (y > ymax) ? y : ymax;
28195 zmin = (z < zmin) ? z : zmin;
28196 zmax = (z > zmax) ? z : zmax;
28197 }
28198 }
28199 // 'longest' is the largest possible edge length formed by input vertices.
28200 // It is used as the measure to distinguish two identical points.
28201 x = xmax - xmin;
28202 y = ymax - ymin;
28203 z = zmax - zmin;
28204 longest = sqrt(x * x + y * y + z * z);
28205 if (longest == 0.0) {
28206 printf("Error: The point set is trivial.\n");
28207 terminatetetgen(1);
28208 }
28209 lengthlimit = longest * b->epsilon * 1e+2;
28210 }
28211
28212 ///////////////////////////////////////////////////////////////////////////////
28213 // //
28214 // jettisonnodes() Jettison unused or duplicated vertices. //
28215 // //
28216 // Unused points are those input points which are outside the mesh domain or //
28217 // have no connection (isolated) to the mesh. Duplicated points exist for //
28218 // example if the input PLC is read from a .stl mesh file (marked during the //
28219 // Delaunay tetrahedralization step. This routine remove these points from //
28220 // points list. All existing points are reindexed. //
28221 // //
28222 ///////////////////////////////////////////////////////////////////////////////
28223
28224 void tetgenmesh::jettisonnodes()
28225 {
28226 point pointloop;
28227 bool jetflag;
28228 int oldidx, newidx;
28229 int remcount;
28230
28231 if (!b->quiet) {
28232 printf("Jettisoning redundants points.\n");
28233 }
28234
28235 points->traversalinit();
28236 pointloop = pointtraverse();
28237 oldidx = newidx = 0; // in->firstnumber;
28238 remcount = 0;
28239 while (pointloop != (point) NULL) {
28240 jetflag = (pointtype(pointloop) == DUPLICATEDVERTEX) ||
28241 (pointtype(pointloop) == UNUSEDVERTEX);
28242 if (jetflag) {
28243 // It is a duplicated point, delete it.
28244 pointdealloc(pointloop);
28245 remcount++;
28246 } else {
28247 // Re-index it.
28248 setpointmark(pointloop, newidx + in->firstnumber);
28249 if (in->pointmarkerlist != (int *) NULL) {
28250 if (oldidx < in->numberofpoints) {
28251 // Re-index the point marker as well.
28252 in->pointmarkerlist[newidx] = in->pointmarkerlist[oldidx];
28253 }
28254 }
28255 newidx++;
28256 }
28257 oldidx++;
28258 if (oldidx == in->numberofpoints) {
28259 // Update the numbe of input points (Because some were removed).
28260 in->numberofpoints -= remcount;
28261 // Remember this number for output original input nodes.
28262 jettisoninverts = remcount;
28263 }
28264 pointloop = pointtraverse();
28265 }
28266 if (b->verbose) {
28267 printf(" %d duplicated vertices have been removed.\n", dupverts);
28268 printf(" %d unused vertices have been removed.\n", unuverts);
28269 }
28270 dupverts = 0;
28271 unuverts = 0;
28272
28273 // The following line ensures that dead items in the pool of nodes cannot
28274 // be allocated for the new created nodes. This ensures that the input
28275 // nodes will occur earlier in the output files, and have lower indices.
28276 points->deaditemstack = (void *) NULL;
28277 }
28278
28279 ///////////////////////////////////////////////////////////////////////////////
28280 // //
28281 // highorder() Create extra nodes for quadratic subparametric elements. //
28282 // //
28283 // 'highordertable' is an array (size = numberoftetrahedra * 6) for storing //
28284 // high-order nodes of each tetrahedron. This routine is used only when -o2 //
28285 // switch is used. //
28286 // //
28287 ///////////////////////////////////////////////////////////////////////////////
28288
28289 void tetgenmesh::highorder()
28290 {
28291 triface tetloop, worktet;
28292 triface spintet, adjtet;
28293 point torg, tdest, tapex;
28294 point *extralist, *adjextralist;
28295 point newpoint;
28296 int hitbdry, ptmark;
28297 int i, j;
28298
28299 // The 'edgeindex' (from 0 to 5) is list as follows:
28300 // 0 - (v0, v1), 1 - (v1, v2), 2 - (v2, v0)
28301 // 3 - (v3, v0), 4 - (v3, v1), 5 - (v3, v2)
28302 // Define an edgeindex map: (loc, ver)->edgeindex.
28303 int edgeindexmap[4][6] = {{0, 0, 1, 1, 2, 2},
28304 {3, 3, 4, 4, 0, 0},
28305 {4, 4, 5, 5, 1, 1},
28306 {5, 5, 3, 3, 2, 2}};
28307
28308 if (!b->quiet) {
28309 printf("Adding vertices for second-order tetrahedra.\n");
28310 }
28311
28312 // Initialize the 'highordertable'.
28313 highordertable = new point[tetrahedrons->items * 6];
28314 if (highordertable == (point *) NULL) {
28315 printf("Error: Out of memory.\n");
28316 terminatetetgen(1);
28317 }
28318
28319 // The following line ensures that dead items in the pool of nodes cannot
28320 // be allocated for the extra nodes associated with high order elements.
28321 // This ensures that the primary nodes (at the corners of elements) will
28322 // occur earlier in the output files, and have lower indices, than the
28323 // extra nodes.
28324 points->deaditemstack = (void *) NULL;
28325
28326 // Assign an entry for each tetrahedron to find its extra nodes. At the
28327 // mean while, initialize all extra nodes be NULL.
28328 i = 0;
28329 tetrahedrons->traversalinit();
28330 tetloop.tet = tetrahedrontraverse();
28331 while (tetloop.tet != (tetrahedron *) NULL) {
28332 tetloop.tet[highorderindex] = (tetrahedron) &highordertable[i];
28333 for (j = 0; j < 6; j++) {
28334 highordertable[i + j] = (point) NULL;
28335 }
28336 i += 6;
28337 tetloop.tet = tetrahedrontraverse();
28338 }
28339
28340 // To create a unique node on each edge. Loop over all tetrahedra, and
28341 // look at the six edges of each tetrahedron. If the extra node in
28342 // the tetrahedron corresponding to this edge is NULL, create a node
28343 // for this edge, at the same time, set the new node into the extra
28344 // node lists of all other tetrahedra sharing this edge.
28345 tetrahedrons->traversalinit();
28346 tetloop.tet = tetrahedrontraverse();
28347 while (tetloop.tet != (tetrahedron *) NULL) {
28348 // Get the list of extra nodes.
28349 extralist = (point *) tetloop.tet[highorderindex];
28350 for (i = 0; i < 6; i++) {
28351 if (extralist[i] == (point) NULL) {
28352 // Operate on this edge.
28353 worktet = tetloop;
28354 worktet.loc = 0; worktet.ver = 0;
28355 // Get the correct edge in 'worktet'.
28356 switch(i) {
28357 case 0: // (v0, v1)
28358 break;
28359 case 1: // (v1, v2)
28360 enextself(worktet);
28361 break;
28362 case 2: // (v2, v0)
28363 enext2self(worktet);
28364 break;
28365 case 3: // (v3, v0)
28366 fnextself(worktet);
28367 enext2self(worktet);
28368 break;
28369 case 4: // (v3, v1)
28370 enextself(worktet);
28371 fnextself(worktet);
28372 enext2self(worktet);
28373 break;
28374 case 5: // (v3, v2)
28375 enext2self(worktet);
28376 fnextself(worktet);
28377 enext2self(worktet);
28378 }
28379 // Create a new node on this edge.
28380 torg = org(worktet);
28381 tdest = dest(worktet);
28382 // Create a new node in the middle of the edge.
28383 newpoint = (point) points->alloc();
28384 // Interpolate its attributes.
28385 // for (j = 0; j < 3 + in->numberofpointattributes; j++) {
28386 // newpoint[j] = 0.5 * (torg[j] + tdest[j]);
28387 // }
28388 ptmark = (int) points->items - (in->firstnumber == 1 ? 0 : 1);
28389 setpointmark(newpoint, ptmark);
28390 // Add this node to its extra node list.
28391 extralist[i] = newpoint;
28392 // Set 'newpoint' into extra node lists of other tetrahedra
28393 // sharing this edge.
28394 tapex = apex(worktet);
28395 spintet = worktet;
28396 hitbdry = 0;
28397 while (hitbdry < 2) {
28398 if (fnextself(spintet)) {
28399 // Get the extra node list of 'spintet'.
28400 adjextralist = (point *) spintet.tet[highorderindex];
28401 // Find the index of its extra node list.
28402 j = edgeindexmap[spintet.loc][spintet.ver];
28403 // Only set 'newpoint' into 'adjextralist' if it is a NULL.
28404 // Because two faces can belong to the same tetrahedron.
28405 if (adjextralist[j] == (point) NULL) {
28406 adjextralist[j] = newpoint;
28407 }
28408 if (apex(spintet) == tapex) {
28409 break;
28410 }
28411 } else {
28412 hitbdry++;
28413 if (hitbdry < 2) {
28414 esym(worktet, spintet);
28415 }
28416 }
28417 }
28418 }
28419 }
28420 tetloop.tet = tetrahedrontraverse();
28421 }
28422 }
28423
28424 ///////////////////////////////////////////////////////////////////////////////
28425 // //
28426 // outnodes() Output the points to a .node file or a tetgenio structure. //
28427 // //
28428 // Note: each point has already been numbered on input (the first index is //
28429 // 'in->firstnumber'). //
28430 // //
28431 ///////////////////////////////////////////////////////////////////////////////
28432
28433 void tetgenmesh::outnodes(tetgenio* out)
28434 {
28435 FILE *outfile;
28436 char outnodefilename[FILENAMESIZE];
28437 shellface subptr;
28438 triface adjtet;
28439 face subloop;
28440 point pointloop;
28441 point *extralist, ep[3];
28442 int nextras, bmark, shmark, marker;
28443 int coordindex, attribindex;
28444 int pointnumber, firstindex;
28445 int index, i;
28446
28447 if (out == (tetgenio *) NULL) {
28448 strcpy(outnodefilename, b->outfilename);
28449 strcat(outnodefilename, ".node");
28450 }
28451
28452 if (!b->quiet) {
28453 if (out == (tetgenio *) NULL) {
28454 printf("Writing %s.\n", outnodefilename);
28455 } else {
28456 printf("Writing nodes.\n");
28457 }
28458 }
28459
28460 // nextras = in->numberofpointattributes;
28461 nextras = 0; // After version 1.4.0, don't output point attributes.
28462 bmark = !b->nobound && in->pointmarkerlist;
28463
28464 // Avoid compile warnings.
28465 outfile = (FILE *) NULL;
28466 marker = coordindex = 0;
28467
28468 if (out == (tetgenio *) NULL) {
28469 outfile = fopen(outnodefilename, "w");
28470 if (outfile == (FILE *) NULL) {
28471 printf("File I/O Error: Cannot create file %s.\n", outnodefilename);
28472 terminatetetgen(1);
28473 }
28474 // Number of points, number of dimensions, number of point attributes,
28475 // and number of boundary markers (zero or one).
28476 fprintf(outfile, "%ld %d %d %d\n", points->items, 3, nextras, bmark);
28477 } else {
28478 // Allocate space for 'pointlist';
28479 out->pointlist = new REAL[points->items * 3];
28480 if (out->pointlist == (REAL *) NULL) {
28481 printf("Error: Out of memory.\n");
28482 terminatetetgen(1);
28483 }
28484 // Allocate space for 'pointattributelist' if necessary;
28485 if (nextras > 0) {
28486 out->pointattributelist = new REAL[points->items * nextras];
28487 if (out->pointattributelist == (REAL *) NULL) {
28488 printf("Error: Out of memory.\n");
28489 terminatetetgen(1);
28490 }
28491 }
28492 // Allocate space for 'pointmarkerlist' if necessary;
28493 if (bmark) {
28494 out->pointmarkerlist = new int[points->items];
28495 if (out->pointmarkerlist == (int *) NULL) {
28496 printf("Error: Out of memory.\n");
28497 terminatetetgen(1);
28498 }
28499 }
28500 out->numberofpoints = points->items;
28501 out->numberofpointattributes = nextras;
28502 coordindex = 0;
28503 attribindex = 0;
28504 }
28505
28506 if (bmark && (b->plc || b->refine)) {
28507 // Initialize the point2tet field of each point.
28508 points->traversalinit();
28509 pointloop = pointtraverse();
28510 while (pointloop != (point) NULL) {
28511 setpoint2tet(pointloop, (tetrahedron) NULL);
28512 pointloop = pointtraverse();
28513 }
28514 // Make a map point-to-subface. Hence a boundary point will get the
28515 // facet marker from that facet where it lies on.
28516 subfaces->traversalinit();
28517 subloop.sh = shellfacetraverse(subfaces);
28518 while (subloop.sh != (shellface *) NULL) {
28519 subloop.shver = 0;
28520 // Check all three points of the subface.
28521 for (i = 0; i < 3; i++) {
28522 pointloop = (point) subloop.sh[3 + i];
28523 setpoint2tet(pointloop, (tetrahedron) sencode(subloop));
28524 }
28525 if (b->order == 2) {
28526 // '-o2' switch. Set markers for quadratic nodes of this subface.
28527 stpivot(subloop, adjtet);
28528 if (adjtet.tet == dummytet) {
28529 sesymself(subloop);
28530 stpivot(subloop, adjtet);
28531 }
28532 assert(adjtet.tet != dummytet);
28533 extralist = (point *) adjtet.tet[highorderindex];
28534 switch (adjtet.loc) {
28535 case 0:
28536 ep[0] = extralist[0];
28537 ep[1] = extralist[1];
28538 ep[2] = extralist[2];
28539 break;
28540 case 1:
28541 ep[0] = extralist[0];
28542 ep[1] = extralist[4];
28543 ep[2] = extralist[3];
28544 break;
28545 case 2:
28546 ep[0] = extralist[1];
28547 ep[1] = extralist[5];
28548 ep[2] = extralist[4];
28549 break;
28550 case 3:
28551 ep[0] = extralist[2];
28552 ep[1] = extralist[3];
28553 ep[2] = extralist[5];
28554 break;
28555 default: break;
28556 }
28557 for (i = 0; i < 3; i++) {
28558 setpoint2tet(ep[i], (tetrahedron) sencode(subloop));
28559 }
28560 }
28561 subloop.sh = shellfacetraverse(subfaces);
28562 }
28563 }
28564
28565 // Determine the first index (0 or 1).
28566 firstindex = b->zeroindex ? 0 : in->firstnumber;
28567
28568 points->traversalinit();
28569 pointloop = pointtraverse();
28570 pointnumber = firstindex; // in->firstnumber;
28571 index = 0;
28572 while (pointloop != (point) NULL) {
28573 if (bmark) {
28574 // Default the vertex has a zero marker.
28575 marker = 0;
28576 // Is it an input vertex?
28577 if (index < in->numberofpoints) {
28578 // Input point's marker is directly copied to output.
28579 marker = in->pointmarkerlist[index];
28580 }
28581 // Is it a boundary vertex has marker zero?
28582 if ((marker == 0) && (b->plc || b->refine)) {
28583 subptr = (shellface) point2tet(pointloop);
28584 if (subptr != (shellface) NULL) {
28585 // Default a boundary vertex has marker 1.
28586 marker = 1;
28587 if (in->facetmarkerlist != (int *) NULL) {
28588 // The vertex gets the marker from the facet it lies on.
28589 sdecode(subptr, subloop);
28590 shmark = shellmark(subloop);
28591 marker = in->facetmarkerlist[shmark - 1];
28592 }
28593 }
28594 }
28595 }
28596 if (out == (tetgenio *) NULL) {
28597 // Point number, x, y and z coordinates.
28598 fprintf(outfile, "%4d %.17g %.17g %.17g", pointnumber,
28599 pointloop[0], pointloop[1], pointloop[2]);
28600 for (i = 0; i < nextras; i++) {
28601 // Write an attribute.
28602 fprintf(outfile, " %.17g", pointloop[3 + i]);
28603 }
28604 if (bmark) {
28605 // Write the boundary marker.
28606 fprintf(outfile, " %d", marker);
28607 }
28608 fprintf(outfile, "\n");
28609 } else {
28610 // X, y, and z coordinates.
28611 out->pointlist[coordindex++] = pointloop[0];
28612 out->pointlist[coordindex++] = pointloop[1];
28613 out->pointlist[coordindex++] = pointloop[2];
28614 // Point attributes.
28615 for (i = 0; i < nextras; i++) {
28616 // Output an attribute.
28617 out->pointattributelist[attribindex++] = pointloop[3 + i];
28618 }
28619 if (bmark) {
28620 // Output the boundary marker.
28621 out->pointmarkerlist[index] = marker;
28622 }
28623 }
28624 pointloop = pointtraverse();
28625 pointnumber++;
28626 index++;
28627 }
28628
28629 if (out == (tetgenio *) NULL) {
28630 fprintf(outfile, "# Generated by %s\n", b->commandline);
28631 fclose(outfile);
28632 }
28633 }
28634
28635 ///////////////////////////////////////////////////////////////////////////////
28636 // //
28637 // outmetrics() Output the metric to a file (*.mtr) or a tetgenio obj. //
28638 // //
28639 ///////////////////////////////////////////////////////////////////////////////
28640
28641 void tetgenmesh::outmetrics(tetgenio* out)
28642 {
28643 FILE *outfile;
28644 char outmtrfilename[FILENAMESIZE];
28645 point pointloop;
28646 int nextras, attribindex;
28647 int i;
28648
28649 if (out == (tetgenio *) NULL) {
28650 strcpy(outmtrfilename, b->outfilename);
28651 strcat(outmtrfilename, ".mtr");
28652 }
28653
28654 if (!b->quiet) {
28655 if (out == (tetgenio *) NULL) {
28656 printf("Writing %s.\n", outmtrfilename);
28657 } else {
28658 printf("Writing metrics.\n");
28659 }
28660 }
28661
28662 // Avoid compile warnings.
28663 outfile = (FILE *) NULL;
28664 attribindex = 0;
28665
28666 nextras = 0;
28667 if (b->bgmesh) {
28668 nextras = bgm->in->numberofpointattributes;
28669 } else if (b->quality) {
28670 nextras = 1;
28671 }
28672 if (out == (tetgenio *) NULL) {
28673 outfile = fopen(outmtrfilename, "w");
28674 if (outfile == (FILE *) NULL) {
28675 printf("File I/O Error: Cannot create file %s.\n", outmtrfilename);
28676 terminatetetgen(1);
28677 }
28678 // Number of points, number of point attributes,
28679 fprintf(outfile, "%ld %d\n", points->items, nextras);
28680 } else {
28681 // Allocate space for 'pointattributelist' if necessary;
28682 if (nextras > 0) {
28683 out->pointattributelist = new REAL[points->items * nextras];
28684 if (out->pointattributelist == (REAL *) NULL) {
28685 printf("Error: Out of memory.\n");
28686 terminatetetgen(1);
28687 }
28688 }
28689 out->numberofpointattributes = nextras;
28690 attribindex = 0;
28691 }
28692
28693 points->traversalinit();
28694 pointloop = pointtraverse();
28695 while (pointloop != (point) NULL) {
28696 if (out == (tetgenio *) NULL) {
28697 for (i = 0; i < nextras; i++) {
28698 // Write an attribute.
28699 fprintf(outfile, "%-22.17e ", pointloop[3 + i]);
28700 }
28701 fprintf(outfile, "\n");
28702 } else {
28703 for (i = 0; i < nextras; i++) {
28704 // Output an attribute.
28705 out->pointattributelist[attribindex++] = pointloop[3 + i];
28706 }
28707 }
28708 pointloop = pointtraverse();
28709 }
28710
28711 if (out == (tetgenio *) NULL) {
28712 fprintf(outfile, "# Generated by %s\n", b->commandline);
28713 fclose(outfile);
28714 }
28715 }
28716
28717 ///////////////////////////////////////////////////////////////////////////////
28718 // //
28719 // outelements() Output the tetrahedra to an .ele file or a tetgenio //
28720 // structure. //
28721 // //
28722 ///////////////////////////////////////////////////////////////////////////////
28723
28724 void tetgenmesh::outelements(tetgenio* out)
28725 {
28726 FILE *outfile;
28727 char outelefilename[FILENAMESIZE];
28728 tetrahedron* tptr;
28729 int *tlist;
28730 REAL *talist;
28731 int firstindex, shift;
28732 int pointindex;
28733 int attribindex;
28734 point p1, p2, p3, p4;
28735 point *extralist;
28736 int elementnumber;
28737 int eextras;
28738 int i;
28739
28740 if (out == (tetgenio *) NULL) {
28741 strcpy(outelefilename, b->outfilename);
28742 strcat(outelefilename, ".ele");
28743 }
28744
28745 if (!b->quiet) {
28746 if (out == (tetgenio *) NULL) {
28747 printf("Writing %s.\n", outelefilename);
28748 } else {
28749 printf("Writing elements.\n");
28750 }
28751 }
28752
28753 // Avoid compile warnings.
28754 outfile = (FILE *) NULL;
28755 tlist = (int *) NULL;
28756 talist = (double *) NULL;
28757 pointindex = attribindex = 0;
28758
28759 eextras = in->numberoftetrahedronattributes;
28760 if (out == (tetgenio *) NULL) {
28761 outfile = fopen(outelefilename, "w");
28762 if (outfile == (FILE *) NULL) {
28763 printf("File I/O Error: Cannot create file %s.\n", outelefilename);
28764 terminatetetgen(1);
28765 }
28766 // Number of tetras, points per tetra, attributes per tetra.
28767 fprintf(outfile, "%ld %d %d\n", tetrahedrons->items,
28768 b->order == 1 ? 4 : 10, eextras);
28769 } else {
28770 // Allocate memory for output tetrahedra.
28771 out->tetrahedronlist = new int[tetrahedrons->items *
28772 (b->order == 1 ? 4 : 10)];
28773 if (out->tetrahedronlist == (int *) NULL) {
28774 printf("Error: Out of memory.\n");
28775 terminatetetgen(1);
28776 }
28777 // Allocate memory for output tetrahedron attributes if necessary.
28778 if (eextras > 0) {
28779 out->tetrahedronattributelist = new REAL[tetrahedrons->items * eextras];
28780 if (out->tetrahedronattributelist == (REAL *) NULL) {
28781 printf("Error: Out of memory.\n");
28782 terminatetetgen(1);
28783 }
28784 }
28785 out->numberoftetrahedra = tetrahedrons->items;
28786 out->numberofcorners = b->order == 1 ? 4 : 10;
28787 out->numberoftetrahedronattributes = eextras;
28788 tlist = out->tetrahedronlist;
28789 talist = out->tetrahedronattributelist;
28790 pointindex = 0;
28791 attribindex = 0;
28792 }
28793
28794 // Determine the first index (0 or 1).
28795 firstindex = b->zeroindex ? 0 : in->firstnumber;
28796 shift = 0; // Default no shiftment.
28797 if ((in->firstnumber == 1) && (firstindex == 0)) {
28798 shift = 1; // Shift the output indices by 1.
28799 }
28800
28801 tetrahedrons->traversalinit();
28802 tptr = tetrahedrontraverse();
28803 elementnumber = firstindex; // in->firstnumber;
28804 while (tptr != (tetrahedron *) NULL) {
28805 p1 = (point) tptr[4];
28806 p2 = (point) tptr[5];
28807 p3 = (point) tptr[6];
28808 p4 = (point) tptr[7];
28809 if (out == (tetgenio *) NULL) {
28810 // Tetrahedron number, indices for four points.
28811 fprintf(outfile, "%5d %5d %5d %5d %5d", elementnumber,
28812 pointmark(p1) - shift, pointmark(p2) - shift,
28813 pointmark(p3) - shift, pointmark(p4) - shift);
28814 if (b->order == 2) {
28815 extralist = (point *) tptr[highorderindex];
28816 // Tetrahedron number, indices for four points plus six extra points.
28817 fprintf(outfile, " %5d %5d %5d %5d %5d %5d",
28818 pointmark(extralist[0]) - shift, pointmark(extralist[1]) - shift,
28819 pointmark(extralist[2]) - shift, pointmark(extralist[3]) - shift,
28820 pointmark(extralist[4]) - shift, pointmark(extralist[5]) - shift);
28821 }
28822 for (i = 0; i < eextras; i++) {
28823 fprintf(outfile, " %.17g", elemattribute(tptr, i));
28824 }
28825 fprintf(outfile, "\n");
28826 } else {
28827 tlist[pointindex++] = pointmark(p1) - shift;
28828 tlist[pointindex++] = pointmark(p2) - shift;
28829 tlist[pointindex++] = pointmark(p3) - shift;
28830 tlist[pointindex++] = pointmark(p4) - shift;
28831 if (b->order == 2) {
28832 extralist = (point *) tptr[highorderindex];
28833 tlist[pointindex++] = pointmark(extralist[0]) - shift;
28834 tlist[pointindex++] = pointmark(extralist[1]) - shift;
28835 tlist[pointindex++] = pointmark(extralist[2]) - shift;
28836 tlist[pointindex++] = pointmark(extralist[3]) - shift;
28837 tlist[pointindex++] = pointmark(extralist[4]) - shift;
28838 tlist[pointindex++] = pointmark(extralist[5]) - shift;
28839 }
28840 for (i = 0; i < eextras; i++) {
28841 talist[attribindex++] = elemattribute(tptr, i);
28842 }
28843 }
28844 if (b->neighout) {
28845 // Remember the index of this element.
28846 * (int *) (tptr + elemmarkerindex) = elementnumber;
28847 }
28848 tptr = tetrahedrontraverse();
28849 elementnumber++;
28850 }
28851 if (b->neighout) {
28852 // Set the outside element marker.
28853 * (int *) (dummytet + elemmarkerindex) = -1;
28854 }
28855
28856 if (out == (tetgenio *) NULL) {
28857 fprintf(outfile, "# Generated by %s\n", b->commandline);
28858 fclose(outfile);
28859 }
28860 }
28861
28862 ///////////////////////////////////////////////////////////////////////////////
28863 // //
28864 // outfaces() Output all faces to a .face file or a tetgenio structure. //
28865 // //
28866 // This routines outputs all triangular faces (including outer boundary //
28867 // faces and inner faces) of this mesh. //
28868 // //
28869 ///////////////////////////////////////////////////////////////////////////////
28870
28871 void tetgenmesh::outfaces(tetgenio* out)
28872 {
28873 FILE *outfile;
28874 char facefilename[FILENAMESIZE];
28875 int *elist;
28876 int *emlist;
28877 int index;
28878 triface tface, tsymface;
28879 face checkmark;
28880 point torg, tdest, tapex;
28881 long faces;
28882 int bmark, faceid, marker;
28883 int firstindex, shift;
28884 int facenumber;
28885
28886 if (out == (tetgenio *) NULL) {
28887 strcpy(facefilename, b->outfilename);
28888 strcat(facefilename, ".face");
28889 }
28890
28891 if (!b->quiet) {
28892 if (out == (tetgenio *) NULL) {
28893 printf("Writing %s.\n", facefilename);
28894 } else {
28895 printf("Writing faces.\n");
28896 }
28897 }
28898
28899 // Avoid compile warnings.
28900 outfile = (FILE *) NULL;
28901 elist = (int *) NULL;
28902 emlist = (int *) NULL;
28903 index = marker = 0;
28904
28905 faces = (4l * tetrahedrons->items + hullsize) / 2l;
28906 bmark = !b->nobound && in->facetmarkerlist;
28907
28908 if (out == (tetgenio *) NULL) {
28909 outfile = fopen(facefilename, "w");
28910 if (outfile == (FILE *) NULL) {
28911 printf("File I/O Error: Cannot create file %s.\n", facefilename);
28912 terminatetetgen(1);
28913 }
28914 fprintf(outfile, "%ld %d\n", faces, bmark);
28915 } else {
28916 // Allocate memory for 'trifacelist'.
28917 out->trifacelist = new int[faces * 3];
28918 if (out->trifacelist == (int *) NULL) {
28919 printf("Error: Out of memory.\n");
28920 terminatetetgen(1);
28921 }
28922 // Allocate memory for 'trifacemarkerlist' if necessary.
28923 if (bmark) {
28924 out->trifacemarkerlist = new int[faces];
28925 if (out->trifacemarkerlist == (int *) NULL) {
28926 printf("Error: Out of memory.\n");
28927 terminatetetgen(1);
28928 }
28929 }
28930 out->numberoftrifaces = faces;
28931 elist = out->trifacelist;
28932 emlist = out->trifacemarkerlist;
28933 index = 0;
28934 }
28935
28936 // Determine the first index (0 or 1).
28937 firstindex = b->zeroindex ? 0 : in->firstnumber;
28938 shift = 0; // Default no shiftment.
28939 if ((in->firstnumber == 1) && (firstindex == 0)) {
28940 shift = 1; // Shift the output indices by 1.
28941 }
28942
28943 tetrahedrons->traversalinit();
28944 tface.tet = tetrahedrontraverse();
28945 facenumber = firstindex; // in->firstnumber;
28946 // To loop over the set of faces, loop over all tetrahedra, and look at
28947 // the four faces of each one. If there isn't another tetrahedron
28948 // adjacent to this face, operate on the face. If there is another
28949 // adjacent tetrahedron, operate on the face only if the current
28950 // tetrahedron has a smaller pointer than its neighbor. This way, each
28951 // face is considered only once.
28952 while (tface.tet != (tetrahedron *) NULL) {
28953 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
28954 sym(tface, tsymface);
28955 if ((tsymface.tet == dummytet) || (tface.tet < tsymface.tet)) {
28956 torg = org(tface);
28957 tdest = dest(tface);
28958 tapex = apex(tface);
28959 if (bmark) {
28960 // Get the boundary marker of this face. If it is an inner face,
28961 // it has no boundary marker, set it be zero.
28962 if (b->useshelles) {
28963 // Shell face is used.
28964 tspivot(tface, checkmark);
28965 if (checkmark.sh == dummysh) {
28966 marker = 0; // It is an inner face.
28967 } else {
28968 faceid = shellmark(checkmark) - 1;
28969 marker = in->facetmarkerlist[faceid];
28970 }
28971 } else {
28972 // Shell face is not used, only distinguish outer and inner face.
28973 marker = tsymface.tet != dummytet ? 1 : 0;
28974 }
28975 }
28976 if (out == (tetgenio *) NULL) {
28977 // Face number, indices of three vertices.
28978 fprintf(outfile, "%5d %4d %4d %4d", facenumber,
28979 pointmark(torg) - shift, pointmark(tdest) - shift,
28980 pointmark(tapex) - shift);
28981 if (bmark) {
28982 // Output a boundary marker.
28983 fprintf(outfile, " %d", marker);
28984 }
28985 fprintf(outfile, "\n");
28986 } else {
28987 // Output indices of three vertices.
28988 elist[index++] = pointmark(torg) - shift;
28989 elist[index++] = pointmark(tdest) - shift;
28990 elist[index++] = pointmark(tapex) - shift;
28991 if (bmark) {
28992 emlist[facenumber - in->firstnumber] = marker;
28993 }
28994 }
28995 facenumber++;
28996 }
28997 }
28998 tface.tet = tetrahedrontraverse();
28999 }
29000
29001 if (out == (tetgenio *) NULL) {
29002 fprintf(outfile, "# Generated by %s\n", b->commandline);
29003 fclose(outfile);
29004 }
29005 }
29006
29007 ///////////////////////////////////////////////////////////////////////////////
29008 // //
29009 // outhullfaces() Output outer boundary faces to a .face file or a //
29010 // tetgenio structure. //
29011 // //
29012 // The normal of each face is arranged to point inside of the domain (use //
29013 // right-hand rule). This routines will outputs convex hull faces if the //
29014 // mesh is a Delaunay tetrahedralization. //
29015 // //
29016 ///////////////////////////////////////////////////////////////////////////////
29017
29018 void tetgenmesh::outhullfaces(tetgenio* out)
29019 {
29020 FILE *outfile;
29021 char facefilename[FILENAMESIZE];
29022 int *elist;
29023 int index;
29024 triface tface, tsymface;
29025 face checkmark;
29026 point torg, tdest, tapex;
29027 int firstindex, shift;
29028 int facenumber;
29029
29030 if (out == (tetgenio *) NULL) {
29031 strcpy(facefilename, b->outfilename);
29032 strcat(facefilename, ".face");
29033 }
29034
29035 if (!b->quiet) {
29036 if (out == (tetgenio *) NULL) {
29037 printf("Writing %s.\n", facefilename);
29038 } else {
29039 printf("Writing faces.\n");
29040 }
29041 }
29042
29043 // Avoid compile warnings.
29044 outfile = (FILE *) NULL;
29045 elist = (int *) NULL;
29046 index = 0;
29047
29048 if (out == (tetgenio *) NULL) {
29049 outfile = fopen(facefilename, "w");
29050 if (outfile == (FILE *) NULL) {
29051 printf("File I/O Error: Cannot create file %s.\n", facefilename);
29052 terminatetetgen(1);
29053 }
29054 fprintf(outfile, "%ld 0\n", hullsize);
29055 } else {
29056 // Allocate memory for 'trifacelist'.
29057 out->trifacelist = new int[hullsize * 3];
29058 if (out->trifacelist == (int *) NULL) {
29059 printf("Error: Out of memory.\n");
29060 terminatetetgen(1);
29061 }
29062 out->numberoftrifaces = hullsize;
29063 elist = out->trifacelist;
29064 index = 0;
29065 }
29066
29067 // Determine the first index (0 or 1).
29068 firstindex = b->zeroindex ? 0 : in->firstnumber;
29069 shift = 0; // Default no shiftment.
29070 if ((in->firstnumber == 1) && (firstindex == 0)) {
29071 shift = 1; // Shift the output indices by 1.
29072 }
29073
29074 tetrahedrons->traversalinit();
29075 tface.tet = tetrahedrontraverse();
29076 facenumber = firstindex; // in->firstnumber;
29077 // To loop over the set of hull faces, loop over all tetrahedra, and look
29078 // at the four faces of each one. If there isn't another tetrahedron
29079 // adjacent to this face, operate on the face.
29080 while (tface.tet != (tetrahedron *) NULL) {
29081 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
29082 sym(tface, tsymface);
29083 if (tsymface.tet == dummytet) {
29084 torg = org(tface);
29085 tdest = dest(tface);
29086 tapex = apex(tface);
29087 if (out == (tetgenio *) NULL) {
29088 // Face number, indices of three vertices.
29089 fprintf(outfile, "%5d %4d %4d %4d", facenumber,
29090 pointmark(torg) - shift, pointmark(tdest) - shift,
29091 pointmark(tapex) - shift);
29092 fprintf(outfile, "\n");
29093 } else {
29094 // Output indices of three vertices.
29095 elist[index++] = pointmark(torg) - shift;
29096 elist[index++] = pointmark(tdest) - shift;
29097 elist[index++] = pointmark(tapex) - shift;
29098 }
29099 facenumber++;
29100 }
29101 }
29102 tface.tet = tetrahedrontraverse();
29103 }
29104
29105 if (out == (tetgenio *) NULL) {
29106 fprintf(outfile, "# Generated by %s\n", b->commandline);
29107 fclose(outfile);
29108 }
29109 }
29110
29111 ///////////////////////////////////////////////////////////////////////////////
29112 // //
29113 // outsubfaces() Output subfaces (i.e. boundary faces) to a .face file or //
29114 // a tetgenio structure. //
29115 // //
29116 // The boundary faces are exist in 'subfaces'. For listing triangle vertices //
29117 // in the same sense for all triangles in the mesh, the direction determined //
29118 // by right-hand rule is pointer to the inside of the volume. //
29119 // //
29120 ///////////////////////////////////////////////////////////////////////////////
29121
29122 void tetgenmesh::outsubfaces(tetgenio* out)
29123 {
29124 FILE *outfile;
29125 char facefilename[FILENAMESIZE];
29126 int *elist;
29127 int *emlist;
29128 int index;
29129 triface abuttingtet;
29130 face faceloop;
29131 point torg, tdest, tapex;
29132 int bmark, faceid, marker;
29133 int firstindex, shift;
29134 int neigh1, neigh2;
29135 int facenumber;
29136
29137 if (out == (tetgenio *) NULL) {
29138 strcpy(facefilename, b->outfilename);
29139 strcat(facefilename, ".face");
29140 }
29141
29142 if (!b->quiet) {
29143 if (out == (tetgenio *) NULL) {
29144 printf("Writing %s.\n", facefilename);
29145 } else {
29146 printf("Writing faces.\n");
29147 }
29148 }
29149
29150 // Avoid compile warnings.
29151 outfile = (FILE *) NULL;
29152 elist = (int *) NULL;
29153 emlist = (int *) NULL;
29154 index = marker = 0;
29155 neigh1 = neigh2 = 0;
29156
29157 bmark = !b->nobound && in->facetmarkerlist;
29158
29159 if (out == (tetgenio *) NULL) {
29160 outfile = fopen(facefilename, "w");
29161 if (outfile == (FILE *) NULL) {
29162 printf("File I/O Error: Cannot create file %s.\n", facefilename);
29163 terminatetetgen(1);
29164 }
29165 // Number of subfaces.
29166 fprintf(outfile, "%ld %d\n", subfaces->items, bmark);
29167 } else {
29168 // Allocate memory for 'trifacelist'.
29169 out->trifacelist = new int[subfaces->items * 3];
29170 if (out->trifacelist == (int *) NULL) {
29171 printf("Error: Out of memory.\n");
29172 terminatetetgen(1);
29173 }
29174 if (bmark) {
29175 // Allocate memory for 'trifacemarkerlist'.
29176 out->trifacemarkerlist = new int[subfaces->items];
29177 if (out->trifacemarkerlist == (int *) NULL) {
29178 printf("Error: Out of memory.\n");
29179 terminatetetgen(1);
29180 }
29181 }
29182 if (b->neighout > 1) {
29183 // '-nn' switch.
29184 out->adjtetlist = new int[subfaces->items * 2];
29185 if (out->adjtetlist == (int *) NULL) {
29186 printf("Error: Out of memory.\n");
29187 terminatetetgen(1);
29188 }
29189 }
29190 out->numberoftrifaces = subfaces->items;
29191 elist = out->trifacelist;
29192 emlist = out->trifacemarkerlist;
29193 index = 0;
29194 }
29195
29196 // Determine the first index (0 or 1).
29197 firstindex = b->zeroindex ? 0 : in->firstnumber;
29198 shift = 0; // Default no shiftment.
29199 if ((in->firstnumber == 1) && (firstindex == 0)) {
29200 shift = 1; // Shift the output indices by 1.
29201 }
29202
29203 subfaces->traversalinit();
29204 faceloop.sh = shellfacetraverse(subfaces);
29205 facenumber = firstindex; // in->firstnumber;
29206 while (faceloop.sh != (shellface *) NULL) {
29207 stpivot(faceloop, abuttingtet);
29208 if (abuttingtet.tet == dummytet) {
29209 sesymself(faceloop);
29210 stpivot(faceloop, abuttingtet);
29211 }
29212 if (abuttingtet.tet != dummytet) {
29213 // If there is a tetrahedron containing this subface, orient it so
29214 // that the normal of this face points to inside of the volume by
29215 // right-hand rule.
29216 adjustedgering(abuttingtet, CCW);
29217 torg = org(abuttingtet);
29218 tdest = dest(abuttingtet);
29219 tapex = apex(abuttingtet);
29220 } else {
29221 // This may happen when only a surface mesh be generated.
29222 torg = sorg(faceloop);
29223 tdest = sdest(faceloop);
29224 tapex = sapex(faceloop);
29225 }
29226 if (bmark) {
29227 faceid = shellmark(faceloop) - 1;
29228 marker = in->facetmarkerlist[faceid];
29229 }
29230 if (b->neighout > 1) {
29231 // '-nn' switch. Output adjacent tets indices.
29232 neigh1 = -1;
29233 stpivot(faceloop, abuttingtet);
29234 if (abuttingtet.tet != dummytet) {
29235 neigh1 = * (int *)(abuttingtet.tet + elemmarkerindex);
29236 }
29237 neigh2 = -1;
29238 sesymself(faceloop);
29239 stpivot(faceloop, abuttingtet);
29240 if (abuttingtet.tet != dummytet) {
29241 neigh2 = * (int *)(abuttingtet.tet + elemmarkerindex);
29242 }
29243 }
29244 if (out == (tetgenio *) NULL) {
29245 fprintf(outfile, "%5d %4d %4d %4d", facenumber,
29246 pointmark(torg) - shift, pointmark(tdest) - shift,
29247 pointmark(tapex) - shift);
29248 if (bmark) {
29249 fprintf(outfile, " %d", marker);
29250 }
29251 if (b->neighout > 1) {
29252 fprintf(outfile, " %5d %5d", neigh1, neigh2);
29253 }
29254 fprintf(outfile, "\n");
29255 } else {
29256 // Output three vertices of this face;
29257 elist[index++] = pointmark(torg) - shift;
29258 elist[index++] = pointmark(tdest) - shift;
29259 elist[index++] = pointmark(tapex) - shift;
29260 if (bmark) {
29261 emlist[facenumber - in->firstnumber] = marker;
29262 }
29263 if (b->neighout > 1) {
29264 out->adjtetlist[(facenumber - in->firstnumber) * 2] = neigh1;
29265 out->adjtetlist[(facenumber - in->firstnumber) * 2 + 1] = neigh2;
29266 }
29267 }
29268 facenumber++;
29269 faceloop.sh = shellfacetraverse(subfaces);
29270 }
29271
29272 if (out == (tetgenio *) NULL) {
29273 fprintf(outfile, "# Generated by %s\n", b->commandline);
29274 fclose(outfile);
29275 }
29276 }
29277
29278 ///////////////////////////////////////////////////////////////////////////////
29279 // //
29280 // outsubsegments() Output segments to a .edge file or a structure. //
29281 // //
29282 ///////////////////////////////////////////////////////////////////////////////
29283
29284 void tetgenmesh::outsubsegments(tetgenio* out)
29285 {
29286 FILE *outfile;
29287 char edgefilename[FILENAMESIZE];
29288 int *elist;
29289 int index;
29290 face edgeloop;
29291 point torg, tdest;
29292 int firstindex, shift;
29293 int edgenumber;
29294
29295 if (out == (tetgenio *) NULL) {
29296 strcpy(edgefilename, b->outfilename);
29297 strcat(edgefilename, ".edge");
29298 }
29299
29300 if (!b->quiet) {
29301 if (out == (tetgenio *) NULL) {
29302 printf("Writing %s.\n", edgefilename);
29303 } else {
29304 printf("Writing faces.\n");
29305 }
29306 }
29307
29308 // Avoid compile warnings.
29309 outfile = (FILE *) NULL;
29310 elist = (int *) NULL;
29311 index = 0;
29312
29313 if (out == (tetgenio *) NULL) {
29314 outfile = fopen(edgefilename, "w");
29315 if (outfile == (FILE *) NULL) {
29316 printf("File I/O Error: Cannot create file %s.\n", edgefilename);
29317 terminatetetgen(1);
29318 }
29319 // Number of subsegments.
29320 fprintf(outfile, "%ld\n", subsegs->items);
29321 } else {
29322 // Allocate memory for 'edgelist'.
29323 out->edgelist = new int[subsegs->items * 2];
29324 if (out->edgelist == (int *) NULL) {
29325 printf("Error: Out of memory.\n");
29326 terminatetetgen(1);
29327 }
29328 out->numberofedges = subsegs->items;
29329 elist = out->edgelist;
29330 index = 0;
29331 }
29332
29333 // Determine the first index (0 or 1).
29334 firstindex = b->zeroindex ? 0 : in->firstnumber;
29335 shift = 0; // Default no shiftment.
29336 if ((in->firstnumber == 1) && (firstindex == 0)) {
29337 shift = 1; // Shift the output indices by 1.
29338 }
29339
29340 subsegs->traversalinit();
29341 edgeloop.sh = shellfacetraverse(subsegs);
29342 edgenumber = firstindex; // in->firstnumber;
29343 while (edgeloop.sh != (shellface *) NULL) {
29344 torg = sorg(edgeloop);
29345 tdest = sdest(edgeloop);
29346 if (out == (tetgenio *) NULL) {
29347 fprintf(outfile, "%5d %4d %4d\n", edgenumber,
29348 pointmark(torg) - shift, pointmark(tdest) - shift);
29349 } else {
29350 // Output three vertices of this face;
29351 elist[index++] = pointmark(torg) - shift;
29352 elist[index++] = pointmark(tdest) - shift;
29353 }
29354 edgenumber++;
29355 edgeloop.sh = shellfacetraverse(subsegs);
29356 }
29357
29358 if (out == (tetgenio *) NULL) {
29359 fprintf(outfile, "# Generated by %s\n", b->commandline);
29360 fclose(outfile);
29361 }
29362 }
29363
29364 ///////////////////////////////////////////////////////////////////////////////
29365 // //
29366 // outneighbors() Output tet neighbors to a .neigh file or a structure. //
29367 // //
29368 ///////////////////////////////////////////////////////////////////////////////
29369
29370 void tetgenmesh::outneighbors(tetgenio* out)
29371 {
29372 FILE *outfile;
29373 char neighborfilename[FILENAMESIZE];
29374 int *nlist;
29375 int index;
29376 triface tetloop, tetsym;
29377 int neighbor1, neighbor2, neighbor3, neighbor4;
29378 int firstindex;
29379 int elementnumber;
29380
29381 if (out == (tetgenio *) NULL) {
29382 strcpy(neighborfilename, b->outfilename);
29383 strcat(neighborfilename, ".neigh");
29384 }
29385
29386 if (!b->quiet) {
29387 if (out == (tetgenio *) NULL) {
29388 printf("Writing %s.\n", neighborfilename);
29389 } else {
29390 printf("Writing neighbors.\n");
29391 }
29392 }
29393
29394 // Avoid compile warnings.
29395 outfile = (FILE *) NULL;
29396 nlist = (int *) NULL;
29397 index = 0;
29398
29399 if (out == (tetgenio *) NULL) {
29400 outfile = fopen(neighborfilename, "w");
29401 if (outfile == (FILE *) NULL) {
29402 printf("File I/O Error: Cannot create file %s.\n", neighborfilename);
29403 terminatetetgen(1);
29404 }
29405 // Number of tetrahedra, four faces per tetrahedron.
29406 fprintf(outfile, "%ld %d\n", tetrahedrons->items, 4);
29407 } else {
29408 // Allocate memory for 'neighborlist'.
29409 out->neighborlist = new int[tetrahedrons->items * 4];
29410 if (out->neighborlist == (int *) NULL) {
29411 printf("Error: Out of memory.\n");
29412 terminatetetgen(1);
29413 }
29414 nlist = out->neighborlist;
29415 index = 0;
29416 }
29417
29418 // Determine the first index (0 or 1).
29419 firstindex = b->zeroindex ? 0 : in->firstnumber;
29420
29421 tetrahedrons->traversalinit();
29422 tetloop.tet = tetrahedrontraverse();
29423 elementnumber = firstindex; // in->firstnumber;
29424 while (tetloop.tet != (tetrahedron *) NULL) {
29425 tetloop.loc = 2;
29426 sym(tetloop, tetsym);
29427 neighbor1 = * (int *) (tetsym.tet + elemmarkerindex);
29428 tetloop.loc = 3;
29429 sym(tetloop, tetsym);
29430 neighbor2 = * (int *) (tetsym.tet + elemmarkerindex);
29431 tetloop.loc = 1;
29432 sym(tetloop, tetsym);
29433 neighbor3 = * (int *) (tetsym.tet + elemmarkerindex);
29434 tetloop.loc = 0;
29435 sym(tetloop, tetsym);
29436 neighbor4 = * (int *) (tetsym.tet + elemmarkerindex);
29437 if (out == (tetgenio *) NULL) {
29438 // Tetrahedra number, neighboring tetrahedron numbers.
29439 fprintf(outfile, "%4d %4d %4d %4d %4d\n", elementnumber,
29440 neighbor1, neighbor2, neighbor3, neighbor4);
29441 } else {
29442 nlist[index++] = neighbor1;
29443 nlist[index++] = neighbor2;
29444 nlist[index++] = neighbor3;
29445 nlist[index++] = neighbor4;
29446 }
29447 tetloop.tet = tetrahedrontraverse();
29448 elementnumber++;
29449 }
29450
29451 if (out == (tetgenio *) NULL) {
29452 fprintf(outfile, "# Generated by %s\n", b->commandline);
29453 fclose(outfile);
29454 }
29455 }
29456
29457 ///////////////////////////////////////////////////////////////////////////////
29458 // //
29459 // outpbcnodes() Output pbc node pairs to a .pbc file or a structure. //
29460 // //
29461 ///////////////////////////////////////////////////////////////////////////////
29462
29463 void tetgenmesh::outpbcnodes(tetgenio* out)
29464 {
29465 FILE *outfile;
29466 char pbcfilename[FILENAMESIZE];
29467 list *ptpairlist;
29468 tetgenio::pbcgroup *pgi, *pgo;
29469 pbcdata *pd;
29470 face faceloop;
29471 face checkseg, symseg;
29472 point *ptpair, pa, pb;
29473 enum locateresult loc;
29474 REAL sympt[3], d1, d2;
29475 int *worklist;
29476 int firstindex, shift;
29477 int index, idx;
29478 int i, j, k, l;
29479
29480 if (out == (tetgenio *) NULL) {
29481 strcpy(pbcfilename, b->outfilename);
29482 strcat(pbcfilename, ".pbc");
29483 }
29484
29485 if (!b->quiet) {
29486 if (out == (tetgenio *) NULL) {
29487 printf("Writing %s.\n", pbcfilename);
29488 } else {
29489 printf("Writing pbc nodes.\n");
29490 }
29491 }
29492
29493 // Avoid compilation warnings.
29494 outfile = (FILE *) NULL;
29495 pgo = (tetgenio::pbcgroup *) NULL;
29496 index = 0;
29497
29498 if (out == (tetgenio *) NULL) {
29499 outfile = fopen(pbcfilename, "w");
29500 if (outfile == (FILE *) NULL) {
29501 printf("File I/O Error: Cannot create file %s.\n", pbcfilename);
29502 terminatetetgen(1);
29503 }
29504 // Number of pbc groups.
29505 fprintf(outfile, "# number of PBCs.\n");
29506 fprintf(outfile, "%d\n\n", in->numberofpbcgroups);
29507 } else {
29508 out->numberofpbcgroups = in->numberofpbcgroups;
29509 // Allocate memory for 'out->pbcgrouplist'.
29510 out->pbcgrouplist = new tetgenio::pbcgroup[in->numberofpbcgroups];
29511 // (Next line was a bug, reported by Murry Nigel).
29512 if (out->pbcgrouplist == (tetgenio::pbcgroup *) NULL) {
29513 printf("Error: Out of memory.\n");
29514 terminatetetgen(1);
29515 }
29516 }
29517
29518 ptpairlist = new list(2 * sizeof(point *), NULL, 256);
29519 worklist = new int[points->items + 1];
29520 for (i = 0; i < points->items + 1; i++) worklist[i] = 0;
29521
29522 // Determine the first index (0 or 1).
29523 firstindex = b->zeroindex ? 0 : in->firstnumber;
29524 shift = 0; // Default no shiftment.
29525 if ((in->firstnumber == 1) && (firstindex == 0)) {
29526 shift = 1; // Shift the output indices by 1.
29527 }
29528
29529 for (i = 0; i < in->numberofpbcgroups; i++) {
29530 // Group i.
29531 pgi = &(in->pbcgrouplist[i]);
29532 if (out == (tetgenio *) NULL) {
29533 fprintf(outfile, "# PBC %d\n", in->firstnumber + i);
29534 // Output facet markers.
29535 fprintf(outfile, "%d %d\n", pgi->fmark1, pgi->fmark2);
29536 // Output transformation matrix.
29537 fprintf(outfile, "[\n");
29538 for (j = 0; j < 4; j++) {
29539 fprintf(outfile, " %.12g %.12g %.12g %.12g\n", pgi->transmat[j][0],
29540 pgi->transmat[j][1], pgi->transmat[j][2], pgi->transmat[j][3]);
29541 }
29542 fprintf(outfile, "]\n");
29543 } else {
29544 pgo = &(out->pbcgrouplist[i]);
29545 // Copy data from pgi to pgo.
29546 pgo->fmark1 = pgi->fmark1;
29547 pgo->fmark2 = pgi->fmark2;
29548 for (j = 0; j < 4; j++) {
29549 for (k = 0; k < 4; k++) pgo->transmat[j][k] = pgi->transmat[j][k];
29550 }
29551 }
29552
29553 // Find the point pairs of group i.
29554 subfaces->traversalinit();
29555 faceloop.sh = shellfacetraverse(subfaces);
29556 while (faceloop.sh != (shellface *) NULL) {
29557 if (shellpbcgroup(faceloop) == i) {
29558 // It is in group i. Operate on it if it has pgi->fmark1.
29559 idx = shellmark(faceloop) - 1;
29560 if (in->facetmarkerlist[idx] == pgi->fmark1) {
29561 // Loop three edges of the subface.
29562 for (j = 0; j < 3; j++) {
29563 sspivot(faceloop, checkseg);
29564 // Loop two vertices of the edge.
29565 for (k = 0; k < 2; k++) {
29566 if (k == 0) pa = sorg(faceloop);
29567 else pa = sdest(faceloop);
29568 if (worklist[pointmark(pa)] == 0) {
29569 pb = (point) NULL;
29570 if (checkseg.sh != dummysh) {
29571 // pa is on a segment. Find pb.
29572 // Find the incident pbcgroup of checkseg.
29573 idx = shellmark(checkseg) - 1;
29574 for (l = idx2segpglist[idx]; l < idx2segpglist[idx + 1];
29575 l++) {
29576 pd = (pbcdata *)(* segpbcgrouptable)[segpglist[l]];
29577 if (((pd->fmark[0] == pgi->fmark1) &&
29578 (pd->fmark[1] == pgi->fmark2)) ||
29579 ((pd->fmark[0] == pgi->fmark2) &&
29580 (pd->fmark[1] == pgi->fmark1))) break;
29581 }
29582 #ifdef SELF_CHECK
29583 assert(l < idx2segpglist[idx + 1]);
29584 #endif
29585 loc = getsegpbcsympoint(pa, &checkseg, sympt, &symseg,
29586 segpglist[l]);
29587 if (loc != ONVERTEX) {
29588 // Not found a match point! It may be caused by the
29589 // pair of input vertices don't have enough digits.
29590 // Choose a near vertex.
29591 d1 = distance(sympt, sorg(symseg));
29592 d2 = distance(sympt, sdest(symseg));
29593 if (d1 > d2) sesymself(symseg);
29594 }
29595 pb = sorg(symseg);
29596 } else {
29597 // Operate on pa if it is inside the facet.
29598 if (pointtype(pa) == FREESUBVERTEX) {
29599 pb = point2pbcpt(pa);
29600 }
29601 }
29602 if (pb != (point) NULL) {
29603 // Add the pair (pa, pb) into list.
29604 ptpair = (point *) ptpairlist->append(NULL);
29605 ptpair[0] = pa;
29606 ptpair[1] = pb;
29607 // Mark pa (avoid to operate on it later).
29608 worklist[pointmark(pa)] = 1;
29609 }
29610 }
29611 }
29612 // Get the next edge.
29613 senextself(faceloop);
29614 }
29615 }
29616 }
29617 faceloop.sh = shellfacetraverse(subfaces);
29618 }
29619
29620 // Output the list of pbc points.
29621 if (out == (tetgenio *) NULL) {
29622 fprintf(outfile, "%d\n", ptpairlist->len());
29623 } else {
29624 pgo->numberofpointpairs = ptpairlist->len();
29625 pgo->pointpairlist = new int[pgo->numberofpointpairs * 2];
29626 index = 0;
29627 }
29628 for (j = 0; j < ptpairlist->len(); j++) {
29629 ptpair = (point *)(* ptpairlist)[j];
29630 pa = ptpair[0];
29631 pb = ptpair[1];
29632 if (out == (tetgenio *) NULL) {
29633 fprintf(outfile, " %4d %4d\n", pointmark(pa) - shift,
29634 pointmark(pb) - shift);
29635 } else {
29636 pgo->pointpairlist[index++] = pointmark(pa) - shift;
29637 pgo->pointpairlist[index++] = pointmark(pb) - shift;
29638 }
29639 // Unmark pa.
29640 worklist[pointmark(pa)] = 0;
29641 }
29642 if (out == (tetgenio *) NULL) {
29643 fprintf(outfile, "\n");
29644 }
29645 ptpairlist->clear();
29646 }
29647
29648 delete [] worklist;
29649 delete ptpairlist;
29650
29651 if (out == (tetgenio *) NULL) {
29652 fprintf(outfile, "# Generated by %s\n", b->commandline);
29653 fclose(outfile);
29654 }
29655 }
29656
29657 ///////////////////////////////////////////////////////////////////////////////
29658 // //
29659 // outsmesh() Write surface mesh to a .smesh file, which can be read and //
29660 // tetrahedralized by TetGen. //
29661 // //
29662 // You can specify a filename (without suffix) in 'smfilename'. If you don't //
29663 // supply a filename (let smfilename be NULL), the default name stored in //
29664 // 'tetgenbehavior' will be used. //
29665 // //
29666 ///////////////////////////////////////////////////////////////////////////////
29667
29668 void tetgenmesh::outsmesh(char* smfilename)
29669 {
29670 FILE *outfile;
29671 char nodfilename[FILENAMESIZE];
29672 char smefilename[FILENAMESIZE];
29673 face faceloop;
29674 point p1, p2, p3;
29675 int firstindex, shift;
29676 int bmark;
29677 int faceid, marker;
29678 int i;
29679
29680 if (smfilename != (char *) NULL && smfilename[0] != '\0') {
29681 strcpy(smefilename, smfilename);
29682 } else if (b->outfilename[0] != '\0') {
29683 strcpy(smefilename, b->outfilename);
29684 } else {
29685 strcpy(smefilename, "unnamed");
29686 }
29687 strcpy(nodfilename, smefilename);
29688 strcat(smefilename, ".smesh");
29689 strcat(nodfilename, ".node");
29690
29691 if (!b->quiet) {
29692 printf("Writing %s.\n", smefilename);
29693 }
29694 outfile = fopen(smefilename, "w");
29695 if (outfile == (FILE *) NULL) {
29696 printf("File I/O Error: Cannot create file %s.\n", smefilename);
29697 return;
29698 }
29699
29700 // Determine the first index (0 or 1).
29701 firstindex = b->zeroindex ? 0 : in->firstnumber;
29702 shift = 0; // Default no shiftment.
29703 if ((in->firstnumber == 1) && (firstindex == 0)) {
29704 shift = 1; // Shift the output indices by 1.
29705 }
29706
29707 fprintf(outfile, "# %s. TetGen's input file.\n", smefilename);
29708 fprintf(outfile, "\n# part 1: node list.\n");
29709 fprintf(outfile, "0 3 0 0 # nodes are found in %s.\n", nodfilename);
29710
29711 marker = 0; // avoid compile warning.
29712 bmark = !b->nobound && in->facetmarkerlist;
29713
29714 fprintf(outfile, "\n# part 2: facet list.\n");
29715 // Number of facets, boundary marker.
29716 fprintf(outfile, "%ld %d\n", subfaces->items, bmark);
29717
29718 subfaces->traversalinit();
29719 faceloop.sh = shellfacetraverse(subfaces);
29720 while (faceloop.sh != (shellface *) NULL) {
29721 p1 = sorg(faceloop);
29722 p2 = sdest(faceloop);
29723 p3 = sapex(faceloop);
29724 if (bmark) {
29725 faceid = shellmark(faceloop) - 1;
29726 if (faceid >= 0) {
29727 marker = in->facetmarkerlist[faceid];
29728 } else {
29729 marker = 0; // This subface must be added manually later.
29730 }
29731 }
29732 fprintf(outfile, "3 %4d %4d %4d", pointmark(p1) - shift,
29733 pointmark(p2) - shift, pointmark(p3) - shift);
29734 if (bmark) {
29735 fprintf(outfile, " %d", marker);
29736 }
29737 fprintf(outfile, "\n");
29738 faceloop.sh = shellfacetraverse(subfaces);
29739 }
29740
29741 // Copy input holelist.
29742 fprintf(outfile, "\n# part 3: hole list.\n");
29743 fprintf(outfile, "%d\n", in->numberofholes);
29744 for (i = 0; i < in->numberofholes; i++) {
29745 fprintf(outfile, "%d %g %g %g\n", i + in->firstnumber,
29746 in->holelist[i * 3], in->holelist[i * 3 + 1],
29747 in->holelist[i * 3 + 2]);
29748 }
29749
29750 // Copy input regionlist.
29751 fprintf(outfile, "\n# part 4: region list.\n");
29752 fprintf(outfile, "%d\n", in->numberofregions);
29753 for (i = 0; i < in->numberofregions; i++) {
29754 fprintf(outfile, "%d %g %g %g %d %g\n", i + in->firstnumber,
29755 in->regionlist[i * 5], in->regionlist[i * 5 + 1],
29756 in->regionlist[i * 5 + 2], (int) in->regionlist[i * 5 + 3],
29757 in->regionlist[i * 5 + 4]);
29758 }
29759
29760 fprintf(outfile, "# Generated by %s\n", b->commandline);
29761 fclose(outfile);
29762 }
29763
29764 ///////////////////////////////////////////////////////////////////////////////
29765 // //
29766 // outmesh2medit() Write mesh to a .mesh file, which can be read and //
29767 // rendered by Medit (a free mesh viewer from INRIA). //
29768 // //
29769 // You can specify a filename (without suffix) in 'mfilename'. If you don't //
29770 // supply a filename (let mfilename be NULL), the default name stored in //
29771 // 'tetgenbehavior' will be used. The output file will have the suffix .mesh.//
29772 // //
29773 ///////////////////////////////////////////////////////////////////////////////
29774
29775 void tetgenmesh::outmesh2medit(char* mfilename)
29776 {
29777 FILE *outfile;
29778 char mefilename[FILENAMESIZE];
29779 tetrahedron* tetptr;
29780 triface tface, tsymface;
29781 face segloop, checkmark;
29782 point pointloop, p1, p2, p3, p4;
29783 long faces;
29784 int pointnumber;
29785 int i;
29786
29787 if (mfilename != (char *) NULL && mfilename[0] != '\0') {
29788 strcpy(mefilename, mfilename);
29789 } else if (b->outfilename[0] != '\0') {
29790 strcpy(mefilename, b->outfilename);
29791 } else {
29792 strcpy(mefilename, "unnamed");
29793 }
29794 strcat(mefilename, ".mesh");
29795
29796 if (!b->quiet) {
29797 printf("Writing %s.\n", mefilename);
29798 }
29799 outfile = fopen(mefilename, "w");
29800 if (outfile == (FILE *) NULL) {
29801 printf("File I/O Error: Cannot create file %s.\n", mefilename);
29802 return;
29803 }
29804
29805 fprintf(outfile, "MeshVersionFormatted 1\n");
29806 fprintf(outfile, "\n");
29807 fprintf(outfile, "Dimension\n");
29808 fprintf(outfile, "3\n");
29809 fprintf(outfile, "\n");
29810
29811 fprintf(outfile, "\n# Set of mesh vertices\n");
29812 fprintf(outfile, "Vertices\n");
29813 fprintf(outfile, "%ld\n", points->items);
29814
29815 points->traversalinit();
29816 pointloop = pointtraverse();
29817 pointnumber = 1; // Medit need start number form 1.
29818 while (pointloop != (point) NULL) {
29819 // Point coordinates.
29820 fprintf(outfile, "%.17g %.17g %.17g",
29821 pointloop[0], pointloop[1], pointloop[2]);
29822 if (in->numberofpointattributes > 0) {
29823 // Write an attribute, ignore others if more than one.
29824 fprintf(outfile, " %.17g\n", pointloop[3]);
29825 } else {
29826 fprintf(outfile, " 0\n");
29827 }
29828 setpointmark(pointloop, pointnumber);
29829 pointloop = pointtraverse();
29830 pointnumber++;
29831 }
29832
29833 // Compute the number of edges.
29834 faces = (4l * tetrahedrons->items + hullsize) / 2l;
29835
29836 fprintf(outfile, "\n# Set of Triangles\n");
29837 fprintf(outfile, "Triangles\n");
29838 fprintf(outfile, "%ld\n", faces);
29839
29840 tetrahedrons->traversalinit();
29841 tface.tet = tetrahedrontraverse();
29842 // To loop over the set of faces, loop over all tetrahedra, and look at
29843 // the four faces of each tetrahedron. If there isn't another tetrahedron
29844 // adjacent to the face, operate on the face. If there is another adj-
29845 // acent tetrahedron, operate on the face only if the current tetrahedron
29846 // has a smaller pointer than its neighbor. This way, each face is
29847 // considered only once.
29848 while (tface.tet != (tetrahedron *) NULL) {
29849 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
29850 sym(tface, tsymface);
29851 if (tface.tet < tsymface.tet || tsymface.tet == dummytet) {
29852 p1 = org (tface);
29853 p2 = dest(tface);
29854 p3 = apex(tface);
29855 fprintf(outfile, "%5d %5d %5d",
29856 pointmark(p1), pointmark(p2), pointmark(p3));
29857 fprintf(outfile, " 0\n");
29858 }
29859 }
29860 tface.tet = tetrahedrontraverse();
29861 }
29862
29863 fprintf(outfile, "\n# Set of Tetrahedra\n");
29864 fprintf(outfile, "Tetrahedra\n");
29865 fprintf(outfile, "%ld\n", tetrahedrons->items);
29866
29867 tetrahedrons->traversalinit();
29868 tetptr = tetrahedrontraverse();
29869 while (tetptr != (tetrahedron *) NULL) {
29870 p1 = (point) tetptr[4];
29871 p2 = (point) tetptr[5];
29872 p3 = (point) tetptr[6];
29873 p4 = (point) tetptr[7];
29874 fprintf(outfile, "%5d %5d %5d %5d",
29875 pointmark(p1), pointmark(p2), pointmark(p3), pointmark(p4));
29876 if (in->numberoftetrahedronattributes > 0) {
29877 fprintf(outfile, " %.17g", elemattribute(tetptr, 0));
29878 } else {
29879 fprintf(outfile, " 0");
29880 }
29881 fprintf(outfile, "\n");
29882 tetptr = tetrahedrontraverse();
29883 }
29884
29885 fprintf(outfile, "\nCorners\n");
29886 fprintf(outfile, "%d\n", in->numberofpoints);
29887
29888 for (i = 0; i < in->numberofpoints; i++) {
29889 fprintf(outfile, "%4d\n", i + 1);
29890 }
29891
29892 if (b->useshelles) {
29893 fprintf(outfile, "\nEdges\n");
29894 fprintf(outfile, "%ld\n", subsegs->items);
29895
29896 subsegs->traversalinit();
29897 segloop.sh = shellfacetraverse(subsegs);
29898 while (segloop.sh != (shellface *) NULL) {
29899 p1 = sorg(segloop);
29900 p2 = sdest(segloop);
29901 fprintf(outfile, "%5d %5d", pointmark(p1), pointmark(p2));
29902 fprintf(outfile, " 0\n");
29903 segloop.sh = shellfacetraverse(subsegs);
29904 }
29905 }
29906
29907 fprintf(outfile, "\nEnd\n");
29908 fclose(outfile);
29909 }
29910
29911 ///////////////////////////////////////////////////////////////////////////////
29912 // //
29913 // outmesh2gid() Write mesh to a .ele.msh file and a .face.msh file, //
29914 // which can be imported and rendered by Gid. //
29915 // //
29916 // You can specify a filename (without suffix) in 'gfilename'. If you don't //
29917 // supply a filename (let gfilename be NULL), the default name stored in //
29918 // 'tetgenbehavior' will be used. The suffixes (.ele.msh and .face.msh) will //
29919 // be automatically added. //
29920 // //
29921 ///////////////////////////////////////////////////////////////////////////////
29922
29923 void tetgenmesh::outmesh2gid(char* gfilename)
29924 {
29925 FILE *outfile;
29926 char gidfilename[FILENAMESIZE];
29927 tetrahedron* tetptr;
29928 triface tface, tsymface;
29929 face sface;
29930 point pointloop, p1, p2, p3, p4;
29931 int pointnumber;
29932 int elementnumber;
29933
29934 if (gfilename != (char *) NULL && gfilename[0] != '\0') {
29935 strcpy(gidfilename, gfilename);
29936 } else if (b->outfilename[0] != '\0') {
29937 strcpy(gidfilename, b->outfilename);
29938 } else {
29939 strcpy(gidfilename, "unnamed");
29940 }
29941 strcat(gidfilename, ".ele.msh");
29942
29943 if (!b->quiet) {
29944 printf("Writing %s.\n", gidfilename);
29945 }
29946 outfile = fopen(gidfilename, "w");
29947 if (outfile == (FILE *) NULL) {
29948 printf("File I/O Error: Cannot create file %s.\n", gidfilename);
29949 return;
29950 }
29951
29952 fprintf(outfile, "mesh dimension = 3 elemtype tetrahedron nnode = 4\n");
29953 fprintf(outfile, "coordinates\n");
29954
29955 points->traversalinit();
29956 pointloop = pointtraverse();
29957 pointnumber = 1; // Gid need start number form 1.
29958 while (pointloop != (point) NULL) {
29959 // Point coordinates.
29960 fprintf(outfile, "%4d %.17g %.17g %.17g", pointnumber,
29961 pointloop[0], pointloop[1], pointloop[2]);
29962 if (in->numberofpointattributes > 0) {
29963 // Write an attribute, ignore others if more than one.
29964 fprintf(outfile, " %.17g", pointloop[3]);
29965 }
29966 fprintf(outfile, "\n");
29967 setpointmark(pointloop, pointnumber);
29968 pointloop = pointtraverse();
29969 pointnumber++;
29970 }
29971
29972 fprintf(outfile, "end coordinates\n");
29973 fprintf(outfile, "elements\n");
29974
29975 tetrahedrons->traversalinit();
29976 tetptr = tetrahedrontraverse();
29977 elementnumber = 1;
29978 while (tetptr != (tetrahedron *) NULL) {
29979 p1 = (point) tetptr[4];
29980 p2 = (point) tetptr[5];
29981 p3 = (point) tetptr[6];
29982 p4 = (point) tetptr[7];
29983 fprintf(outfile, "%5d %5d %5d %5d %5d", elementnumber,
29984 pointmark(p1), pointmark(p2), pointmark(p3), pointmark(p4));
29985 if (in->numberoftetrahedronattributes > 0) {
29986 fprintf(outfile, " %.17g", elemattribute(tetptr, 0));
29987 }
29988 fprintf(outfile, "\n");
29989 tetptr = tetrahedrontraverse();
29990 elementnumber++;
29991 }
29992
29993 fprintf(outfile, "end elements\n");
29994 fclose(outfile);
29995
29996 if (gfilename != (char *) NULL && gfilename[0] != '\0') {
29997 strcpy(gidfilename, gfilename);
29998 } else if (b->outfilename[0] != '\0') {
29999 strcpy(gidfilename, b->outfilename);
30000 } else {
30001 strcpy(gidfilename, "unnamed");
30002 }
30003 strcat(gidfilename, ".face.msh");
30004
30005 if (!b->quiet) {
30006 printf("Writing %s.\n", gidfilename);
30007 }
30008 outfile = fopen(gidfilename, "w");
30009 if (outfile == (FILE *) NULL) {
30010 printf("File I/O Error: Cannot create file %s.\n", gidfilename);
30011 return;
30012 }
30013
30014 fprintf(outfile, "mesh dimension = 3 elemtype triangle nnode = 3\n");
30015 fprintf(outfile, "coordinates\n");
30016
30017 points->traversalinit();
30018 pointloop = pointtraverse();
30019 pointnumber = 1; // Gid need start number form 1.
30020 while (pointloop != (point) NULL) {
30021 // Point coordinates.
30022 fprintf(outfile, "%4d %.17g %.17g %.17g", pointnumber,
30023 pointloop[0], pointloop[1], pointloop[2]);
30024 if (in->numberofpointattributes > 0) {
30025 // Write an attribute, ignore others if more than one.
30026 fprintf(outfile, " %.17g", pointloop[3]);
30027 }
30028 fprintf(outfile, "\n");
30029 setpointmark(pointloop, pointnumber);
30030 pointloop = pointtraverse();
30031 pointnumber++;
30032 }
30033
30034 fprintf(outfile, "end coordinates\n");
30035 fprintf(outfile, "elements\n");
30036
30037 tetrahedrons->traversalinit();
30038 tface.tet = tetrahedrontraverse();
30039 elementnumber = 1;
30040 while (tface.tet != (tetrahedron *) NULL) {
30041 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
30042 sym(tface, tsymface);
30043 if ((tface.tet < tsymface.tet) || (tsymface.tet == dummytet)) {
30044 p1 = org(tface);
30045 p2 = dest(tface);
30046 p3 = apex(tface);
30047 if (tsymface.tet == dummytet) {
30048 // It's a hull face, output it.
30049 fprintf(outfile, "%5d %d %d %d\n", elementnumber,
30050 pointmark(p1), pointmark(p2), pointmark(p3));
30051 elementnumber++;
30052 } else if (b->useshelles) {
30053 // Only output it if it's a subface.
30054 tspivot(tface, sface);
30055 if (sface.sh != dummysh) {
30056 fprintf(outfile, "%5d %d %d %d\n", elementnumber,
30057 pointmark(p1), pointmark(p2), pointmark(p3));
30058 elementnumber++;
30059 }
30060 }
30061 }
30062 }
30063 tface.tet = tetrahedrontraverse();
30064 }
30065
30066 fprintf(outfile, "end elements\n");
30067 fclose(outfile);
30068 }
30069
30070 ///////////////////////////////////////////////////////////////////////////////
30071 // //
30072 // outmesh2off() Write the mesh to an .off file. //
30073 // //
30074 // .off, the Object File Format, is one of the popular file formats from the //
30075 // Geometry Center's Geomview package (http://www.geomview.org). //
30076 // //
30077 ///////////////////////////////////////////////////////////////////////////////
30078
30079 void tetgenmesh::outmesh2off(char* ofilename)
30080 {
30081 FILE *outfile;
30082 char offfilename[FILENAMESIZE];
30083 triface tface, tsymface;
30084 point pointloop, p1, p2, p3;
30085 long faces;
30086 int shift;
30087
30088 if (ofilename != (char *) NULL && ofilename[0] != '\0') {
30089 strcpy(offfilename, ofilename);
30090 } else if (b->outfilename[0] != '\0') {
30091 strcpy(offfilename, b->outfilename);
30092 } else {
30093 strcpy(offfilename, "unnamed");
30094 }
30095 strcat(offfilename, ".off");
30096
30097 if (!b->quiet) {
30098 printf("Writing %s.\n", offfilename);
30099 }
30100 outfile = fopen(offfilename, "w");
30101 if (outfile == (FILE *) NULL) {
30102 printf("File I/O Error: Cannot create file %s.\n", offfilename);
30103 return;
30104 }
30105
30106 // Calculate the number of triangular faces in the tetrahedral mesh.
30107 faces = (4l * tetrahedrons->items + hullsize) / 2l;
30108
30109 // Number of points, faces, and edges(not used, here show hullsize).
30110 fprintf(outfile, "OFF\n%ld %ld %ld\n", points->items, faces, hullsize);
30111
30112 // Write the points.
30113 points->traversalinit();
30114 pointloop = pointtraverse();
30115 while (pointloop != (point) NULL) {
30116 fprintf(outfile, " %.17g %.17g %.17g\n", pointloop[0], pointloop[1],
30117 pointloop[2]);
30118 pointloop = pointtraverse();
30119 }
30120
30121 // OFF always use zero as the first index.
30122 shift = in->firstnumber == 1 ? 1 : 0;
30123
30124 tetrahedrons->traversalinit();
30125 tface.tet = tetrahedrontraverse();
30126 // To loop over the set of faces, loop over all tetrahedra, and look at
30127 // the four faces of each tetrahedron. If there isn't another tetrahedron
30128 // adjacent to the face, operate on the face. If there is another adj-
30129 // acent tetrahedron, operate on the face only if the current tetrahedron
30130 // has a smaller pointer than its neighbor. This way, each face is
30131 // considered only once.
30132 while (tface.tet != (tetrahedron *) NULL) {
30133 for (tface.loc = 0; tface.loc < 4; tface.loc ++) {
30134 sym(tface, tsymface);
30135 if ((tface.tet < tsymface.tet) || (tsymface.tet == dummytet)) {
30136 p1 = org(tface);
30137 p2 = dest(tface);
30138 p3 = apex(tface);
30139 // Face number, indices of three vertexs.
30140 fprintf(outfile, "3 %4d %4d %4d\n", pointmark(p1) - shift,
30141 pointmark(p2) - shift, pointmark(p3) - shift);
30142 }
30143 }
30144 tface.tet = tetrahedrontraverse();
30145 }
30146
30147 fprintf(outfile, "# Generated by %s\n", b->commandline);
30148 fclose(outfile);
30149 }
30150
30151 //
30152 // End of I/O rouitnes
30153 //
30154
30155 //
30156 // Begin of user interaction routines
30157 //
30158
30159 ///////////////////////////////////////////////////////////////////////////////
30160 // //
30161 // internalerror() Ask the user to send me the defective product. Exit. //
30162 // //
30163 ///////////////////////////////////////////////////////////////////////////////
30164
30165 void tetgenmesh::internalerror()
30166 {
30167 printf(" Please report this bug to [email protected]. Include the\n");
30168 printf(" message above, your input data set, and the exact command\n");
30169 printf(" line you used to run this program, thank you.\n");
30170 terminatetetgen(2);
30171 }
30172
30173 ///////////////////////////////////////////////////////////////////////////////
30174 // //
30175 // checkmesh() Test the mesh for topological consistency. //
30176 // //
30177 ///////////////////////////////////////////////////////////////////////////////
30178
30179 void tetgenmesh::checkmesh()
30180 {
30181 triface tetraloop;
30182 triface oppotet, oppooppotet;
30183 point tetorg, tetdest, tetapex, tetoppo;
30184 REAL oritest;
30185 int horrors;
30186
30187 if (!b->quiet) {
30188 printf(" Checking consistency of mesh...\n");
30189 }
30190
30191 horrors = 0;
30192 // Run through the list of tetrahedra, checking each one.
30193 tetrahedrons->traversalinit();
30194 tetraloop.tet = tetrahedrontraverse();
30195 while (tetraloop.tet != (tetrahedron *) NULL) {
30196 // Check all four faces of the tetrahedron.
30197 for (tetraloop.loc = 0; tetraloop.loc < 4; tetraloop.loc++) {
30198 tetorg = org(tetraloop);
30199 tetdest = dest(tetraloop);
30200 tetapex = apex(tetraloop);
30201 tetoppo = oppo(tetraloop);
30202 if (tetraloop.loc == 0) { // Only test for inversion once.
30203 oritest = orient3d(tetorg, tetdest, tetapex, tetoppo);
30204 if (oritest >= 0.0) {
30205 printf(" !! !! %s ", oritest > 0.0 ? "Inverted" : "Degenerated");
30206 printtet(&tetraloop);
30207 printf(" orient3d = %.17g.\n", oritest);
30208 horrors++;
30209 }
30210 }
30211 // Find the neighboring tetrahedron on this face.
30212 sym(tetraloop, oppotet);
30213 if (oppotet.tet != dummytet) {
30214 // Check that the tetrahedron's neighbor knows it's a neighbor.
30215 sym(oppotet, oppooppotet);
30216 if ((tetraloop.tet != oppooppotet.tet)
30217 || (tetraloop.loc != oppooppotet.loc)) {
30218 printf(" !! !! Asymmetric tetra-tetra bond:\n");
30219 if (tetraloop.tet == oppooppotet.tet) {
30220 printf(" (Right tetrahedron, wrong orientation)\n");
30221 }
30222 printf(" First ");
30223 printtet(&tetraloop);
30224 printf(" Second (nonreciprocating) ");
30225 printtet(&oppotet);
30226 horrors++;
30227 }
30228 }
30229 }
30230 tetraloop.tet = tetrahedrontraverse();
30231 }
30232 if (horrors == 0) {
30233 if (!b->quiet) {
30234 printf(" In my studied opinion, the mesh appears to be consistent.\n");
30235 }
30236 } else if (horrors == 1) {
30237 printf(" !! !! !! !! Precisely one festering wound discovered.\n");
30238 } else {
30239 printf(" !! !! !! !! %d abominations witnessed.\n", horrors);
30240 }
30241 }
30242
30243 ///////////////////////////////////////////////////////////////////////////////
30244 // //
30245 // checkshells() Test the boundary mesh for topological consistency. //
30246 // //
30247 ///////////////////////////////////////////////////////////////////////////////
30248
30249 void tetgenmesh::checkshells()
30250 {
30251 triface oppotet, oppooppotet, testtet;
30252 face shloop, segloop, spin;
30253 face testsh, testseg, testshsh;
30254 point shorg, shdest, segorg, segdest;
30255 REAL checksign;
30256 bool same;
30257 int horrors;
30258 int i;
30259
30260 if (!b->quiet) {
30261 printf(" Checking consistency of the mesh boundary...\n");
30262 }
30263 horrors = 0;
30264
30265 // Run through the list of subfaces, checking each one.
30266 subfaces->traversalinit();
30267 shloop.sh = shellfacetraverse(subfaces);
30268 while (shloop.sh != (shellface *) NULL) {
30269 // Check two connected tetrahedra if they exist.
30270 shloop.shver = 0;
30271 stpivot(shloop, oppotet);
30272 if (oppotet.tet != dummytet) {
30273 tspivot(oppotet, testsh);
30274 if (testsh.sh != shloop.sh) {
30275 printf(" !! !! Wrong tetra-subface connection.\n");
30276 printf(" Tetra: ");
30277 printtet(&oppotet);
30278 printf(" Subface: ");
30279 printsh(&shloop);
30280 horrors++;
30281 }
30282 if (oppo(oppotet) != (point) NULL) {
30283 adjustedgering(oppotet, CCW);
30284 checksign = orient3d(sorg(shloop), sdest(shloop), sapex(shloop),
30285 oppo(oppotet));
30286 if (checksign >= 0.0) {
30287 printf(" !! !! Wrong subface orientation.\n");
30288 printf(" Subface: ");
30289 printsh(&shloop);
30290 horrors++;
30291 }
30292 }
30293 }
30294 sesymself(shloop);
30295 stpivot(shloop, oppooppotet);
30296 if (oppooppotet.tet != dummytet) {
30297 tspivot(oppooppotet, testsh);
30298 if (testsh.sh != shloop.sh) {
30299 printf(" !! !! Wrong tetra-subface connection.\n");
30300 printf(" Tetra: ");
30301 printtet(&oppooppotet);
30302 printf(" Subface: ");
30303 printsh(&shloop);
30304 horrors++;
30305 }
30306 if (oppotet.tet != dummytet) {
30307 sym(oppotet, testtet);
30308 if (testtet.tet != oppooppotet.tet) {
30309 printf(" !! !! Wrong tetra-subface-tetra connection.\n");
30310 printf(" Tetra 1: ");
30311 printtet(&oppotet);
30312 printf(" Subface: ");
30313 printsh(&shloop);
30314 printf(" Tetra 2: ");
30315 printtet(&oppooppotet);
30316 horrors++;
30317 }
30318 }
30319 if (oppo(oppooppotet) != (point) NULL) {
30320 adjustedgering(oppooppotet, CCW);
30321 checksign = orient3d(sorg(shloop), sdest(shloop), sapex(shloop),
30322 oppo(oppooppotet));
30323 if (checksign >= 0.0) {
30324 printf(" !! !! Wrong subface orientation.\n");
30325 printf(" Subface: ");
30326 printsh(&shloop);
30327 horrors++;
30328 }
30329 }
30330 }
30331 // Check connection between subfaces.
30332 shloop.shver = 0;
30333 for (i = 0; i < 3; i++) {
30334 shorg = sorg(shloop);
30335 shdest = sdest(shloop);
30336 sspivot(shloop, testseg);
30337 if (testseg.sh != dummysh) {
30338 segorg = sorg(testseg);
30339 segdest = sdest(testseg);
30340 same = ((shorg == segorg) && (shdest == segdest))
30341 || ((shorg == segdest) && (shdest == segorg));
30342 if (!same) {
30343 printf(" !! !! Wrong subface-subsegment connection.\n");
30344 printf(" Subface: ");
30345 printsh(&shloop);
30346 printf(" Subsegment: ");
30347 printsh(&testseg);
30348 horrors++;
30349 }
30350 }
30351 spivot(shloop, testsh);
30352 if (testsh.sh != dummysh) {
30353 segorg = sorg(testsh);
30354 segdest = sdest(testsh);
30355 same = ((shorg == segorg) && (shdest == segdest))
30356 || ((shorg == segdest) && (shdest == segorg));
30357 if (!same) {
30358 printf(" !! !! Wrong subface-subface connection.\n");
30359 printf(" Subface 1: ");
30360 printsh(&shloop);
30361 printf(" Subface 2: ");
30362 printsh(&testsh);
30363 horrors++;
30364 }
30365 spivot(testsh, testshsh);
30366 shorg = sorg(testshsh);
30367 shdest = sdest(testshsh);
30368 same = ((shorg == segorg) && (shdest == segdest))
30369 || ((shorg == segdest) && (shdest == segorg));
30370 if (!same) {
30371 printf(" !! !! Wrong subface-subface connection.\n");
30372 printf(" Subface 1: ");
30373 printsh(&testsh);
30374 printf(" Subface 2: ");
30375 printsh(&testshsh);
30376 horrors++;
30377 }
30378 if (testseg.sh == dummysh) {
30379 if (testshsh.sh != shloop.sh) {
30380 printf(" !! !! Wrong subface-subface connection.\n");
30381 printf(" Subface 1: ");
30382 printsh(&shloop);
30383 printf(" Subface 2: ");
30384 printsh(&testsh);
30385 horrors++;
30386 }
30387 }
30388 }
30389 senextself(shloop);
30390 }
30391 shloop.sh = shellfacetraverse(subfaces);
30392 }
30393
30394 // Run through the list of subsegs, checking each one.
30395 subsegs->traversalinit();
30396 segloop.sh = shellfacetraverse(subsegs);
30397 while (segloop.sh != (shellface *) NULL) {
30398 segorg = sorg(segloop);
30399 segdest = sdest(segloop);
30400 spivot(segloop, testsh);
30401 if (testsh.sh == dummysh) {
30402 printf(" !! !! Wrong subsegment-subface connection.\n");
30403 printf(" Subsegment: ");
30404 printsh(&segloop);
30405 horrors++;
30406 segloop.sh = shellfacetraverse(subsegs);
30407 continue;
30408 }
30409 shorg = sorg(testsh);
30410 shdest = sdest(testsh);
30411 same = ((shorg == segorg) && (shdest == segdest))
30412 || ((shorg == segdest) && (shdest == segorg));
30413 if (!same) {
30414 printf(" !! !! Wrong subsegment-subface connection.\n");
30415 printf(" Subsegment : ");
30416 printsh(&segloop);
30417 printf(" Subface : ");
30418 printsh(&testsh);
30419 horrors++;
30420 segloop.sh = shellfacetraverse(subsegs);
30421 continue;
30422 }
30423 // Check the connection of face loop around this subsegment.
30424 spin = testsh;
30425 i = 0;
30426 do {
30427 spivotself(spin);
30428 shorg = sorg(spin);
30429 shdest = sdest(spin);
30430 same = ((shorg == segorg) && (shdest == segdest))
30431 || ((shorg == segdest) && (shdest == segorg));
30432 if (!same) {
30433 printf(" !! !! Wrong subsegment-subface connection.\n");
30434 printf(" Subsegment : ");
30435 printsh(&segloop);
30436 printf(" Subface : ");
30437 printsh(&testsh);
30438 horrors++;
30439 break;
30440 }
30441 i++;
30442 } while (spin.sh != testsh.sh && i < 1000);
30443 if (i >= 1000) {
30444 printf(" !! !! Wrong subsegment-subface connection.\n");
30445 printf(" Subsegment : ");
30446 printsh(&segloop);
30447 horrors++;
30448 }
30449 segloop.sh = shellfacetraverse(subsegs);
30450 }
30451 if (horrors == 0) {
30452 if (!b->quiet) {
30453 printf(" Mesh boundaries connected correctly.\n");
30454 }
30455 } else {
30456 printf(" !! !! !! !! %d boundary connection viewed with horror.\n",
30457 horrors);
30458 return;
30459 }
30460 }
30461
30462 ///////////////////////////////////////////////////////////////////////////////
30463 // //
30464 // checkdelaunay() Ensure that the mesh is constrained Delaunay. //
30465 // //
30466 // If 'flipqueue' is not NULL, non-locally Delaunay faces are saved in it. //
30467 // //
30468 ///////////////////////////////////////////////////////////////////////////////
30469
30470 void tetgenmesh::checkdelaunay(REAL eps, queue* flipqueue)
30471 {
30472 triface tetraloop;
30473 triface oppotet;
30474 face opposhelle;
30475 point tetorg, tetdest, tetapex, tetoppo;
30476 point oppooppo;
30477 enum fliptype fc;
30478 REAL sign;
30479 int shouldbedelaunay;
30480 int horrors;
30481
30482 if (!b->quiet) {
30483 printf(" Checking Delaunay property of the mesh...\n");
30484 }
30485 horrors = 0;
30486 // Run through the list of triangles, checking each one.
30487 tetrahedrons->traversalinit();
30488 tetraloop.tet = tetrahedrontraverse();
30489 while (tetraloop.tet != (tetrahedron *) NULL) {
30490 // Check all four faces of the tetrahedron.
30491 for (tetraloop.loc = 0; tetraloop.loc < 4; tetraloop.loc++) {
30492 tetorg = org(tetraloop);
30493 tetdest = dest(tetraloop);
30494 tetapex = apex(tetraloop);
30495 tetoppo = oppo(tetraloop);
30496 sym(tetraloop, oppotet);
30497 oppooppo = oppo(oppotet);
30498 // Only do testif there is an adjoining tetrahedron whose pointer is
30499 // larger (to ensure that each pair isn't tested twice).
30500 shouldbedelaunay = (oppotet.tet != dummytet)
30501 && (tetoppo != (point) NULL)
30502 && (oppooppo != (point) NULL)
30503 && (tetraloop.tet < oppotet.tet);
30504 if (checksubfaces && shouldbedelaunay) {
30505 // If a shell face separates the tetrahedra, then the face is
30506 // constrained, so no local Delaunay test should be done.
30507 tspivot(tetraloop, opposhelle);
30508 if (opposhelle.sh != dummysh){
30509 shouldbedelaunay = 0;
30510 }
30511 }
30512 if (shouldbedelaunay) {
30513 sign = insphere(tetdest, tetorg, tetapex, tetoppo, oppooppo);
30514 if ((sign > 0.0) && (eps > 0.0)) {
30515 if (iscospheric(tetdest, tetorg, tetapex, tetoppo, oppooppo, sign,
30516 eps)) sign = 0.0;
30517 }
30518 if (sign > 0.0) {
30519 if (flipqueue) {
30520 enqueueflipface(tetraloop, flipqueue);
30521 } else {
30522 printf(" !! Non-locally Delaunay face (%d, %d, %d) ",
30523 pointmark(tetorg), pointmark(tetdest), pointmark(tetapex));
30524 fc = categorizeface(tetraloop);
30525 switch (fc) {
30526 case T23: printf("\"T23\""); break;
30527 case T32: printf("\"T32\""); break;
30528 case T22: printf("\"T22\""); break;
30529 case T44: printf("\"T44\""); break;
30530 case UNFLIPABLE: printf("\"UNFLIPABLE\""); break;
30531 case FORBIDDENFACE:printf("\"FORBIDDENFACE\""); break;
30532 case FORBIDDENEDGE:printf("\"FORBIDDENEDGE\""); break;
30533 case NONCONVEX:printf("\"NONCONVEX\""); break;
30534 }
30535 printf("\n");
30536 }
30537 horrors++;
30538 }
30539 }
30540 }
30541 tetraloop.tet = tetrahedrontraverse();
30542 }
30543 if (flipqueue == (queue *) NULL) {
30544 if (horrors == 0) {
30545 if (!b->quiet) {
30546 printf(" The mesh is %s.\n",
30547 checksubfaces ? "constrained Delaunay" : "Delaunay");
30548 }
30549 } else {
30550 printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors);
30551 }
30552 }
30553 }
30554
30555 ///////////////////////////////////////////////////////////////////////////////
30556 // //
30557 // checkdegeneracy() Check if the point set contains degeneracies. //
30558 // //
30559 // 'eps' is a relative error tolerance for testing approximatly degeneracies.//
30560 // Set it to zero if only exact test is desired. //
30561 // //
30562 ///////////////////////////////////////////////////////////////////////////////
30563
30564 void tetgenmesh::checkdegeneracy(REAL eps)
30565 {
30566 triface tetraloop;
30567 triface oppotet;
30568 point tetorg, tetdest, tetapex, tetoppo;
30569 point oppooppo;
30570 REAL sign;
30571 int horrors;
30572
30573 if (!b->quiet) {
30574 printf(" Checking degeneracies in the point set...\n");
30575 }
30576 horrors = 0;
30577 // Run through the list of triangles, checking each one.
30578 tetrahedrons->traversalinit();
30579 tetraloop.tet = tetrahedrontraverse();
30580 while (tetraloop.tet != (tetrahedron *) NULL) {
30581 // Check all four faces of the tetrahedron.
30582 for (tetraloop.loc = 0; tetraloop.loc < 4; tetraloop.loc++) {
30583 tetorg = org(tetraloop);
30584 tetdest = dest(tetraloop);
30585 tetapex = apex(tetraloop);
30586 tetoppo = oppo(tetraloop);
30587 sym(tetraloop, oppotet);
30588 oppooppo = oppo(oppotet);
30589 // Only do test if there is an adjoining tetrahedron whose pointer is
30590 // larger (to ensure that each pair isn't tested twice).
30591 if ((oppotet.tet != dummytet) && (tetoppo != (point) NULL) &&
30592 (oppooppo != (point) NULL) && (tetraloop.tet < oppotet.tet)) {
30593 sign = insphere(tetdest, tetorg, tetapex, tetoppo, oppooppo);
30594 if ((sign != 0.0) && (eps > 0.0)) {
30595 if (iscospheric(tetdest, tetorg, tetapex, tetoppo, oppooppo, sign,
30596 eps)) sign = 0.0;
30597 }
30598 if (sign == 0.0) {
30599 printf(" !! Degenerate set (%d, %d, %d, %d, %d).\n",
30600 pointmark(tetorg), pointmark(tetdest), pointmark(tetapex),
30601 pointmark(tetoppo), pointmark(oppooppo));
30602 horrors++;
30603 }
30604 }
30605 }
30606 tetraloop.tet = tetrahedrontraverse();
30607 }
30608
30609 if (horrors == 0) {
30610 if (!b->quiet) {
30611 printf(" The point set is non-degenerate.\n");
30612 }
30613 } else {
30614 printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors);
30615 }
30616 }
30617
30618 ///////////////////////////////////////////////////////////////////////////////
30619 // //
30620 // checkconforming() Ensure that the mesh is conforming Delaunay. //
30621 // //
30622 ///////////////////////////////////////////////////////////////////////////////
30623
30624 void tetgenmesh::checkconforming()
30625 {
30626 face segloop, shloop;
30627 int encsubsegs, encsubfaces;
30628
30629 if (!b->quiet) {
30630 printf(" Checking conforming Delaunay property of mesh...\n");
30631 }
30632 encsubsegs = encsubfaces = 0;
30633 // Run through the list of subsegments, check each one.
30634 subsegs->traversalinit();
30635 segloop.sh = shellfacetraverse(subsegs);
30636 while (segloop.sh != (shellface *) NULL) {
30637 if (checkseg4encroach(&segloop, NULL, NULL, false)) {
30638 printf(" !! !! Non-conforming subsegment: (%d, %d)\n",
30639 pointmark(sorg(segloop)), pointmark(sdest(segloop)));
30640 encsubsegs++;
30641 }
30642 segloop.sh = shellfacetraverse(subsegs);
30643 }
30644 // Run through the list of subfaces, check each one.
30645 subfaces->traversalinit();
30646 shloop.sh = shellfacetraverse(subfaces);
30647 while (shloop.sh != (shellface *) NULL) {
30648 if (checksub4encroach(&shloop, NULL, false)) {
30649 printf(" !! !! Non-conforming subface: (%d, %d, %d)\n",
30650 pointmark(sorg(shloop)), pointmark(sdest(shloop)),
30651 pointmark(sapex(shloop)));
30652 encsubfaces++;
30653 }
30654 shloop.sh = shellfacetraverse(subfaces);
30655 }
30656 if (encsubsegs == 0 && encsubfaces == 0) {
30657 if (!b->quiet) {
30658 printf(" The mesh is conforming Delaunay.\n");
30659 }
30660 } else {
30661 if (encsubsegs > 0) {
30662 printf(" !! !! %d subsegments are non-conforming.\n", encsubsegs);
30663 }
30664 if (encsubfaces > 0) {
30665 printf(" !! !! %d subfaces are non-conforming.\n", encsubfaces);
30666 }
30667 }
30668 }
30669
30670 ///////////////////////////////////////////////////////////////////////////////
30671 // //
30672 // algorithmicstatistics() Print statistics about the mesh algorithms. //
30673 // //
30674 ///////////////////////////////////////////////////////////////////////////////
30675
30676 void tetgenmesh::algorithmicstatistics()
30677 {
30678 printf("Algorithmic statistics:\n\n");
30679 if (b->plc || b->refine) {
30680 printf(" Number of facet above points calculations: %ld\n", abovecount);
30681 }
30682 if (b->plc) {
30683 printf(" Segment split rules: R1 %ld, R2 %ld, R3 %ld\n", r1count, r2count,
30684 r3count);
30685 }
30686 if (b->quality) {
30687 printf(" Bowyer-Watson counts (seg, sub, vol)\n");
30688 printf(" Insert vertices: %ld, %ld, %ld\n",
30689 bowatsegcount, bowatsubcount, bowatvolcount);
30690 printf(" Update cavities: %ld, %ld, %ld\n",
30691 updsegcount, updsubcount, updvolcount);
30692 printf(" Failed cavities: %ld, %ld, %ld\n",
30693 failsegcount, failsubcount, failvolcount);
30694 printf(" Number of repair flips: %ld.\n", repairflipcount);
30695 printf(" Number of circumcenters outside Bowat-cav.: %ld.\n",
30696 outbowatcircumcount);
30697 if (b->conformdel) {
30698 printf(" Segment split rules: R2 %ld, R3 %ld\n", r2count, r3count);
30699 printf(" Number of CDT enforcement points: %ld.\n", cdtenforcesegpts);
30700 }
30701 printf(" Reject vertices counts:\n");
30702 printf(" Rejected seg splits: %ld.\n", rejsegpts);
30703 printf(" Rejected sub splits: %ld.\n", rejsubpts);
30704 printf(" Rejected tet splits: %ld.\n", rejtetpts);
30705 if (b->smooth) {
30706 printf(" Mesh smooth counts:\n");
30707 printf(" %4ld cdt enforcement points.\n", smoothcdtsegpt);
30708 printf(" %4ld segment points.\n", smoothsegpt);
30709 printf(" %4ld facet points.\n", smoothsubpt);
30710 printf(" %4ld volume points.\n", smoothvolpt);
30711 printf(" %4ld failed cdt enforcement points.\n", unsmoothcdtsegpt);
30712 printf(" %4ld unimproved segment points.\n", unsmoothsegpt);
30713 printf(" %4ld unimproved facet points.\n", unsmoothsubpt);
30714 printf(" %4ld unimproved volume points.\n", unsmoothvolpt);
30715 }
30716 }
30717 printf("\n");
30718 }
30719
30720 ///////////////////////////////////////////////////////////////////////////////
30721 // //
30722 // qualitystatistics() Print statistics about the quality of the mesh. //
30723 // //
30724 ///////////////////////////////////////////////////////////////////////////////
30725
30726 void tetgenmesh::qualitystatistics()
30727 {
30728 triface tetloop;
30729 point p[4];
30730 char sbuf[128];
30731 REAL radiusratiotable[12];
30732 REAL aspectratiotable[12];
30733 REAL A[4][4], rhs[4], D;
30734 REAL V[6][3], N[4][3], H[4]; // edge-vectors, face-normals, face-heights.
30735 REAL edgelength[6], alldihed[6];
30736 REAL shortest, longest;
30737 REAL smallestvolume, biggestvolume;
30738 REAL smallestdiangle, biggestdiangle;
30739 REAL tetvol, minaltitude;
30740 REAL cirradius, minheightinv; // insradius;
30741 REAL shortlen, longlen;
30742 REAL tetaspect, tetradius;
30743 REAL smalldiangle, bigdiangle;
30744 int radiustable[12];
30745 int aspecttable[16];
30746 int dihedangletable[18];
30747 int indx[4];
30748 int radiusindex;
30749 int aspectindex;
30750 int tendegree;
30751 int i, j;
30752
30753 printf("Mesh quality statistics:\n\n");
30754
30755 // Avoid compile warnings.
30756 shortlen = longlen = 0.0;
30757 smalldiangle = bigdiangle = 0.0;
30758
30759 radiusratiotable[0] = 0.707; radiusratiotable[1] = 1.0;
30760 radiusratiotable[2] = 1.1; radiusratiotable[3] = 1.2;
30761 radiusratiotable[4] = 1.4; radiusratiotable[5] = 1.6;
30762 radiusratiotable[6] = 1.8; radiusratiotable[7] = 2.0;
30763 radiusratiotable[8] = 2.5; radiusratiotable[9] = 3.0;
30764 radiusratiotable[10] = 10.0; radiusratiotable[11] = 0.0;
30765
30766 aspectratiotable[0] = 1.5; aspectratiotable[1] = 2.0;
30767 aspectratiotable[2] = 2.5; aspectratiotable[3] = 3.0;
30768 aspectratiotable[4] = 4.0; aspectratiotable[5] = 6.0;
30769 aspectratiotable[6] = 10.0; aspectratiotable[7] = 15.0;
30770 aspectratiotable[8] = 25.0; aspectratiotable[9] = 50.0;
30771 aspectratiotable[10] = 100.0; aspectratiotable[11] = 0.0;
30772
30773 for (i = 0; i < 12; i++) radiustable[i] = 0;
30774 for (i = 0; i < 12; i++) aspecttable[i] = 0;
30775 for (i = 0; i < 18; i++) dihedangletable[i] = 0;
30776
30777 minaltitude = xmax - xmin + ymax - ymin + zmax - zmin;
30778 minaltitude = minaltitude * minaltitude;
30779 shortest = minaltitude;
30780 longest = 0.0;
30781 smallestvolume = minaltitude;
30782 biggestvolume = 0.0;
30783 smallestdiangle = 180.0;
30784 biggestdiangle = 0.0;
30785
30786 // Loop all elements, calculate quality parameters for each element.
30787 tetrahedrons->traversalinit();
30788 tetloop.tet = tetrahedrontraverse();
30789 while (tetloop.tet != (tetrahedron *) NULL) {
30790
30791 // Get four vertices: p0, p1, p2, p3.
30792 for (i = 0; i < 4; i++) p[i] = (point) tetloop.tet[4 + i];
30793 // Set the edge vectors: V[0], ..., V[5]
30794 for (i = 0; i < 3; i++) V[0][i] = p[0][i] - p[3][i]; // V[0]: p3->p0.
30795 for (i = 0; i < 3; i++) V[1][i] = p[1][i] - p[3][i]; // V[1]: p3->p1.
30796 for (i = 0; i < 3; i++) V[2][i] = p[2][i] - p[3][i]; // V[2]: p3->p2.
30797 for (i = 0; i < 3; i++) V[3][i] = p[1][i] - p[0][i]; // V[3]: p0->p1.
30798 for (i = 0; i < 3; i++) V[4][i] = p[2][i] - p[1][i]; // V[4]: p1->p2.
30799 for (i = 0; i < 3; i++) V[5][i] = p[0][i] - p[2][i]; // V[5]: p2->p0.
30800 // Set the matrix A = [V[0], V[1], V[2]]^T.
30801 for (j = 0; j < 3; j++) {
30802 for (i = 0; i < 3; i++) A[j][i] = V[j][i];
30803 }
30804 // Decompose A just once.
30805 lu_decmp(A, 3, indx, &D, 0);
30806 // Get the tet volume.
30807 tetvol = fabs(A[indx[0]][0] * A[indx[1]][1] * A[indx[2]][2]) / 6.0;
30808 // Get the three faces normals.
30809 for (j = 0; j < 3; j++) {
30810 for (i = 0; i < 3; i++) rhs[i] = 0.0;
30811 rhs[j] = 1.0; // Positive means the inside direction
30812 lu_solve(A, 3, indx, rhs, 0);
30813 for (i = 0; i < 3; i++) N[j][i] = rhs[i];
30814 }
30815 // Get the fourth face normal by summing up the first three.
30816 for (i = 0; i < 3; i++) N[3][i] = - N[0][i] - N[1][i] - N[2][i];
30817 // Get the radius of the circumsphere.
30818 for (i = 0; i < 3; i++) rhs[i] = 0.5 * dot(V[i], V[i]);
30819 lu_solve(A, 3, indx, rhs, 0);
30820 cirradius = sqrt(dot(rhs, rhs));
30821 // Normalize the face normals.
30822 for (i = 0; i < 4; i++) {
30823 // H[i] is the inverse of height of its corresponding face.
30824 H[i] = sqrt(dot(N[i], N[i]));
30825 for (j = 0; j < 3; j++) N[i][j] /= H[i];
30826 }
30827 // Get the radius of the inscribed sphere.
30828 // insradius = 1.0 / (H[0] + H[1] + H[2] + H[3]);
30829 // Get the biggest H[i] (corresponding to the smallest height).
30830 minheightinv = H[0];
30831 for (i = 1; i < 3; i++) {
30832 if (H[i] > minheightinv) minheightinv = H[i];
30833 }
30834 // Get the squares of the edge lengthes.
30835 for (i = 0; i < 6; i++) edgelength[i] = dot(V[i], V[i]);
30836 // Get the dihedrals (in degree) at each edges.
30837 j = 0;
30838 for (i = 1; i < 4; i++) {
30839 alldihed[j] = -dot(N[0], N[i]); // Edge cd, bd, bc.
30840 if (alldihed[j] < -1.0) alldihed[j] = -1; // Rounding.
30841 else if (alldihed[j] > 1.0) alldihed[j] = 1;
30842 alldihed[j] = acos(alldihed[j]) / PI * 180.0;
30843 j++;
30844 }
30845 for (i = 2; i < 4; i++) {
30846 alldihed[j] = -dot(N[1], N[i]); // Edge ad, ac.
30847 if (alldihed[j] < -1.0) alldihed[j] = -1; // Rounding.
30848 else if (alldihed[j] > 1.0) alldihed[j] = 1;
30849 alldihed[j] = acos(alldihed[j]) / PI * 180.0;
30850 j++;
30851 }
30852 alldihed[j] = -dot(N[2], N[3]); // Edge ab.
30853 if (alldihed[j] < -1.0) alldihed[j] = -1; // Rounding.
30854 else if (alldihed[j] > 1.0) alldihed[j] = 1;
30855 alldihed[j] = acos(alldihed[j]) / PI * 180.0;
30856
30857 // Calculate the longest and shortest edge length.
30858 for (i = 0; i < 6; i++) {
30859 if (i == 0) {
30860 shortlen = longlen = edgelength[i];
30861 } else {
30862 shortlen = edgelength[i] < shortlen ? edgelength[i] : shortlen;
30863 longlen = edgelength[i] > longlen ? edgelength[i] : longlen;
30864 }
30865 if (edgelength[i] > longest) {
30866 longest = edgelength[i];
30867 }
30868 if (edgelength[i] < shortest) {
30869 shortest = edgelength[i];
30870 }
30871 }
30872
30873 // Calculate the largest and smallest volume.
30874 if (tetvol < smallestvolume) {
30875 smallestvolume = tetvol;
30876 }
30877 if (tetvol > biggestvolume) {
30878 biggestvolume = tetvol;
30879 }
30880
30881 // Calculate the largest and smallest dihedral angles.
30882 for (i = 0; i < 6; i++) {
30883 if (i == 0) {
30884 smalldiangle = bigdiangle = alldihed[i];
30885 } else {
30886 smalldiangle = alldihed[i] < smalldiangle ? alldihed[i] : smalldiangle;
30887 bigdiangle = alldihed[i] > bigdiangle ? alldihed[i] : bigdiangle;
30888 }
30889 if (alldihed[i] < smallestdiangle) {
30890 smallestdiangle = alldihed[i];
30891 }
30892 if (alldihed[i] > biggestdiangle) {
30893 biggestdiangle = alldihed[i];
30894 }
30895 }
30896 // Accumulate the corresponding number in the dihedral angle histogram.
30897 if (smalldiangle < 5.0) {
30898 tendegree = 0;
30899 } else if (smalldiangle >= 5.0 && smalldiangle < 10.0) {
30900 tendegree = 1;
30901 } else if (smalldiangle >= 80.0 && smalldiangle < 110.0) {
30902 tendegree = 9; // Angles between 80 to 110 degree are in one entry.
30903 } else {
30904 tendegree = (int) (smalldiangle / 10.);
30905 if (smalldiangle < 80.0) {
30906 tendegree++; // In the left column.
30907 } else {
30908 tendegree--; // In the right column.
30909 }
30910 }
30911 dihedangletable[tendegree]++;
30912 if (bigdiangle >= 80.0 && bigdiangle < 110.0) {
30913 tendegree = 9; // Angles between 80 to 110 degree are in one entry.
30914 } else if (bigdiangle >= 170.0 && bigdiangle < 175.0) {
30915 tendegree = 16;
30916 } else if (bigdiangle >= 175.0) {
30917 tendegree = 17;
30918 } else {
30919 tendegree = (int) (bigdiangle / 10.);
30920 if (bigdiangle < 80.0) {
30921 tendegree++; // In the left column.
30922 } else {
30923 tendegree--; // In the right column.
30924 }
30925 }
30926 dihedangletable[tendegree]++;
30927
30928 // Calculate aspect ratio and radius-edge ratio for this element.
30929 tetradius = cirradius / sqrt(shortlen);
30930 // tetaspect = sqrt(longlen) / (2.0 * insradius);
30931 tetaspect = sqrt(longlen) * minheightinv;
30932 aspectindex = 0;
30933 while ((tetaspect > aspectratiotable[aspectindex]) && (aspectindex < 11)) {
30934 aspectindex++;
30935 }
30936 aspecttable[aspectindex]++;
30937 radiusindex = 0;
30938 while ((tetradius > radiusratiotable[radiusindex]) && (radiusindex < 11)) {
30939 radiusindex++;
30940 }
30941 radiustable[radiusindex]++;
30942
30943 tetloop.tet = tetrahedrontraverse();
30944 }
30945
30946 shortest = sqrt(shortest);
30947 longest = sqrt(longest);
30948 minaltitude = sqrt(minaltitude);
30949
30950 printf(" Smallest volume: %16.5g | Largest volume: %16.5g\n",
30951 smallestvolume, biggestvolume);
30952 printf(" Shortest edge: %16.5g | Longest edge: %16.5g\n",
30953 shortest, longest);
30954 sprintf(sbuf, "%.17g", biggestdiangle);
30955 if (strlen(sbuf) > 8) {
30956 sbuf[8] = '\0';
30957 }
30958 printf(" Smallest dihedral: %14.5g | Largest dihedral: %s\n\n",
30959 smallestdiangle, sbuf);
30960
30961 printf(" Radius-edge ratio histogram:\n");
30962 printf(" < %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30963 radiusratiotable[0], radiustable[0], radiusratiotable[5],
30964 radiusratiotable[6], radiustable[6]);
30965 for (i = 1; i < 5; i++) {
30966 printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30967 radiusratiotable[i - 1], radiusratiotable[i], radiustable[i],
30968 radiusratiotable[i + 5], radiusratiotable[i + 6],
30969 radiustable[i + 6]);
30970 }
30971 printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n",
30972 radiusratiotable[4], radiusratiotable[5], radiustable[5],
30973 radiusratiotable[10], radiustable[11]);
30974 printf(" (A tetrahedron's radius-edge ratio is its radius of ");
30975 printf("circumsphere divided\n");
30976 printf(" by its shortest edge length)\n\n");
30977
30978 printf(" Aspect ratio histogram:\n");
30979 printf(" < %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30980 aspectratiotable[0], aspecttable[0], aspectratiotable[5],
30981 aspectratiotable[6], aspecttable[6]);
30982 for (i = 1; i < 5; i++) {
30983 printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
30984 aspectratiotable[i - 1], aspectratiotable[i], aspecttable[i],
30985 aspectratiotable[i + 5], aspectratiotable[i + 6],
30986 aspecttable[i + 6]);
30987 }
30988 printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n",
30989 aspectratiotable[4], aspectratiotable[5], aspecttable[5],
30990 aspectratiotable[10], aspecttable[11]);
30991 printf(" (A tetrahedron's aspect ratio is its longest edge length");
30992 printf(" divided by its\n");
30993 printf(" smallest side height)\n\n");
30994
30995 printf(" Dihedral angle histogram:\n");
30996 // Print the three two rows:
30997 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
30998 0, 5, dihedangletable[0], 80, 110, dihedangletable[9]);
30999 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31000 5, 10, dihedangletable[1], 110, 120, dihedangletable[10]);
31001 // Print the third to seventh rows.
31002 for (i = 2; i < 7; i++) {
31003 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31004 (i - 1) * 10, (i - 1) * 10 + 10, dihedangletable[i],
31005 (i - 1) * 10 + 110, (i - 1) * 10 + 120, dihedangletable[i + 9]);
31006 }
31007 // Print the last two rows.
31008 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31009 60, 70, dihedangletable[7], 170, 175, dihedangletable[16]);
31010 printf(" %3d - %2d degrees: %8d | %3d - %3d degrees: %8d\n",
31011 70, 80, dihedangletable[8], 175, 180, dihedangletable[17]);
31012
31013 printf("\n");
31014 }
31015
31016 ///////////////////////////////////////////////////////////////////////////////
31017 // //
31018 // statistics() Print all sorts of cool facts. //
31019 // //
31020 ///////////////////////////////////////////////////////////////////////////////
31021
31022 void tetgenmesh::statistics()
31023 {
31024 printf("\nStatistics:\n\n");
31025 printf(" Input points: %d\n", in->numberofpoints + jettisoninverts);
31026 if (b->refine) {
31027 printf(" Input tetrahedra: %d\n", in->numberoftetrahedra);
31028 }
31029 if (b->plc) {
31030 printf(" Input facets: %d\n", in->numberoffacets);
31031 printf(" Input holes: %d\n", in->numberofholes);
31032 printf(" Input regions: %d\n", in->numberofregions);
31033 }
31034
31035 printf("\n Mesh points: %ld\n", points->items);
31036 printf(" Mesh tetrahedra: %ld\n", tetrahedrons->items);
31037 if (b->plc || b->refine) {
31038 printf(" Mesh faces: %ld\n", (4l * tetrahedrons->items + hullsize) / 2l);
31039 }
31040 if (b->plc || b->refine) {
31041 printf(" Mesh subfaces: %ld\n", subfaces->items);
31042 printf(" Mesh subsegments: %ld\n\n", subsegs->items);
31043 } else {
31044 printf(" Convex hull faces: %ld\n\n", hullsize);
31045 }
31046 if (b->verbose > 0) {
31047 #ifdef SELF_CHECK
31048 // algorithmicstatistics();
31049 #endif
31050 qualitystatistics();
31051 printf("\n");
31052 }
31053 }
31054
31055 //
31056 // End of user interaction routines
31057 //
31058
31059 //
31060 // Begin of constructor and destructor of tetgenmesh
31061 //
31062
31063 ///////////////////////////////////////////////////////////////////////////////
31064 // //
31065 // ~tetgenmesh() Deallocte memory occupied by a tetgenmesh object. //
31066 // //
31067 ///////////////////////////////////////////////////////////////////////////////
31068
31069 tetgenmesh::~tetgenmesh()
31070 {
31071 bgm = (tetgenmesh *) NULL;
31072 in = (tetgenio *) NULL;
31073 b = (tetgenbehavior *) NULL;
31074
31075 if (tetrahedrons != (memorypool *) NULL) {
31076 delete tetrahedrons;
31077 }
31078 if (subfaces != (memorypool *) NULL) {
31079 delete subfaces;
31080 }
31081 if (subsegs != (memorypool *) NULL) {
31082 delete subsegs;
31083 }
31084 if (points != (memorypool *) NULL) {
31085 delete points;
31086 }
31087 if (dummytetbase != (tetrahedron *) NULL) {
31088 delete [] dummytetbase;
31089 }
31090 if (dummyshbase != (shellface *) NULL) {
31091 delete [] dummyshbase;
31092 }
31093 if (facetabovepointarray != (point *) NULL) {
31094 delete [] facetabovepointarray;
31095 }
31096 if (highordertable != (point *) NULL) {
31097 delete [] highordertable;
31098 }
31099 if (subpbcgrouptable != (pbcdata *) NULL) {
31100 delete [] subpbcgrouptable;
31101 }
31102 if (segpbcgrouptable != (list *) NULL) {
31103 delete segpbcgrouptable;
31104 delete [] idx2segpglist;
31105 delete [] segpglist;
31106 }
31107 }
31108
31109 ///////////////////////////////////////////////////////////////////////////////
31110 // //
31111 // tetgenmesh() Initialize a tetgenmesh object. //
31112 // //
31113 ///////////////////////////////////////////////////////////////////////////////
31114
31115 tetgenmesh::tetgenmesh()
31116 {
31117 bgm = (tetgenmesh *) NULL;
31118 in = (tetgenio *) NULL;
31119 b = (tetgenbehavior *) NULL;
31120
31121 tetrahedrons = (memorypool *) NULL;
31122 subfaces = (memorypool *) NULL;
31123 subsegs = (memorypool *) NULL;
31124 points = (memorypool *) NULL;
31125 badsubsegs = (memorypool *) NULL;
31126 badsubfaces = (memorypool *) NULL;
31127 badtetrahedrons = (memorypool *) NULL;
31128 flipstackers = (memorypool *) NULL;
31129
31130 dummytet = (tetrahedron *) NULL;
31131 dummytetbase = (tetrahedron *) NULL;
31132 dummysh = (shellface *) NULL;
31133 dummyshbase = (shellface *) NULL;
31134
31135 facetabovepointarray = (point *) NULL;
31136 abovepoint = (point) NULL;
31137 highordertable = (point *) NULL;
31138 subpbcgrouptable = (pbcdata *) NULL;
31139 segpbcgrouptable = (list *) NULL;
31140 idx2segpglist = (int *) NULL;
31141 segpglist = (int *) NULL;
31142
31143 xmax = xmin = ymax = ymin = zmax = zmin = 0.0;
31144 longest = 0.0;
31145 hullsize = 0l;
31146 insegments = 0l;
31147 pointlfsindex = 0;
31148 pointmarkindex = 0;
31149 point2simindex = 0;
31150 point2pbcptindex = 0;
31151 highorderindex = 0;
31152 elemattribindex = 0;
31153 volumeboundindex = 0;
31154 shmarkindex = 0;
31155 areaboundindex = 0;
31156 checksubfaces = 0;
31157 checkpbcs = 0;
31158 varconstraint = 0;
31159 nonconvex = 0;
31160 dupverts = 0;
31161 unuverts = 0;
31162 relverts = 0;
31163 suprelverts = 0;
31164 collapverts = 0;
31165 unsupverts = 0;
31166 jettisoninverts = 0;
31167 symbolic = 0;
31168 samples = 0l;
31169 randomseed = 0l;
31170 macheps = 0.0;
31171 maxcavfaces = maxcavverts = 0;
31172 expcavcount = 0;
31173 abovecount = 0l;
31174 bowatvolcount = bowatsubcount = bowatsegcount = 0l;
31175 updvolcount = updsubcount = updsegcount = 0l;
31176 repairflipcount = 0l;
31177 outbowatcircumcount = 0l;
31178 failvolcount = failsubcount = failsegcount = 0l;
31179 r1count = r2count = r3count = r4count = 0l;
31180 cdtenforcesegpts = 0l;
31181 rejsegpts = rejsubpts = rejtetpts = 0l;
31182 flip23s = flip32s = flip22s = flip44s = 0l;
31183 }
31184
31185 //
31186 // End of constructor and destructor of tetgenmesh
31187 //
31188
31189 //
31190 // End of class 'tetgenmesh' implementation.
31191 //
31192
31193 ///////////////////////////////////////////////////////////////////////////////
31194 // //
31195 // tetrahedralize() The interface for users using TetGen library to //
31196 // generate tetrahedral meshes with all features. //
31197 // //
31198 // The sequence is roughly as follows. Many of these steps can be skipped, //
31199 // depending on the command line switches. //
31200 // //
31201 // - Initialize constants and parse the command line. //
31202 // - Read the vertices from a file and either //
31203 // - tetrahedralize them (no -r), or //
31204 // - read an old mesh from files and reconstruct it (-r). //
31205 // - Insert the PLC segments and facets (-p). //
31206 // - Read the holes (-p), regional attributes (-pA), and regional volume //
31207 // constraints (-pa). Carve the holes and concavities, and spread the //
31208 // regional attributes and volume constraints. //
31209 // - Enforce the constraints on minimum quality bound (-q) and maximum //
31210 // volume (-a). Also enforce the conforming Delaunay property (-q and -a). //
31211 // - Promote the mesh's linear tetrahedra to higher order elements (-o). //
31212 // - Write the output files and print the statistics. //
31213 // - Check the consistency and Delaunay property of the mesh (-C). //
31214 // //
31215 ///////////////////////////////////////////////////////////////////////////////
31216
31217 #include <time.h> // Defined type clock_t, constant CLOCKS_PER_SEC.
31218
31219 void tetrahedralize(tetgenbehavior *b, tetgenio *in, tetgenio *out,
31220 tetgenio *bgmesh)
31221 {
31222 tetgenmesh m;
31223 clock_t tv0, tv1, tv2, tv3, tv4, tv5, tv6, tv7, tv8, tv9, tv10, tv11;
31224
31225 tv0 = clock();
31226
31227 m.b = b;
31228 m.in = in;
31229 m.macheps = exactinit();
31230 m.steinerleft = b->steiner;
31231 if (b->bgmesh) {
31232 // '-m' switch
31233 m.bgm = new tetgenmesh();
31234 m.bgm->b = b;
31235 m.bgm->in = bgmesh;
31236 m.bgm->macheps = exactinit();
31237 }
31238 m.initializepools();
31239 m.transfernodes();
31240
31241 tv1 = clock();
31242
31243 if (b->refine) {
31244 m.reconstructmesh();
31245 } else {
31246 m.delaunizevertices();
31247 }
31248
31249 tv2 = clock();
31250 if (!b->quiet) {
31251 if (b->refine) {
31252 printf("Mesh reconstruction seconds: %g\n",
31253 (tv2 - tv1) / (REAL) CLOCKS_PER_SEC);
31254 } else {
31255 printf("Delaunay seconds: %g\n", (tv2 - tv1) / (REAL) CLOCKS_PER_SEC);
31256 }
31257 }
31258
31259 if (b->useshelles && !b->refine) {
31260 m.insegments = m.meshsurface();
31261 if (b->diagnose != 1) {
31262 m.incrperturbvertices(b->epsilon); // '-p' switch.
31263 m.delaunizesegments();
31264 m.constrainedfacets();
31265 } else {
31266 m.detectinterfaces(); // '-d' switch.
31267 }
31268 }
31269
31270 tv3 = clock();
31271 if (!b->quiet) {
31272 if (b->useshelles && !b->refine) {
31273 if (b->diagnose != 1) {
31274 printf("Segment and facet seconds: %g\n",
31275 (tv3 - tv2) / (REAL) CLOCKS_PER_SEC);
31276 } else {
31277 printf("Intersection seconds: %g\n",
31278 (tv3 - tv2) / (REAL) CLOCKS_PER_SEC);
31279 }
31280 }
31281 }
31282
31283 if (b->plc && !(b->diagnose == 1)) {
31284 m.carveholes();
31285 }
31286
31287 tv4 = clock();
31288 if (!b->quiet) {
31289 if (b->plc && !(b->diagnose == 1)) {
31290 printf("Hole seconds: %g\n", (tv4 - tv3) / (REAL) CLOCKS_PER_SEC);
31291 }
31292 }
31293
31294 if ((b->plc || b->refine) && !(b->diagnose == 1)) {
31295 m.repairmesh();
31296 }
31297
31298 tv5 = clock();
31299 if (!b->quiet) {
31300 if ((b->plc || b->refine) && !(b->diagnose == 1)) {
31301 printf("Repair seconds: %g\n", (tv5 - tv4) / (REAL) CLOCKS_PER_SEC);
31302 }
31303 }
31304
31305 if ((b->plc && b->nobisect) && !(b->diagnose == 1)) {
31306 m.removesteiners();
31307 }
31308
31309 tv6 = clock();
31310 if (!b->quiet) {
31311 if ((b->plc && b->nobisect) && !(b->diagnose == 1)) {
31312 printf("Steiner removal seconds: %g\n",
31313 (tv6 - tv5) / (REAL) CLOCKS_PER_SEC);
31314 }
31315 }
31316
31317 if (b->insertaddpoints) {
31318 if (in->numberofaddpoints == 0) {
31319 in->load_addnodes(b->infilename);
31320 }
31321 if (in->numberofaddpoints > 0) {
31322 m.insertaddpoints();
31323 }
31324 }
31325
31326 tv7 = clock();
31327 if (!b->quiet) {
31328 if ((b->plc || b->refine) && (in->numberofaddpoints > 0)) {
31329 printf("Add points seconds: %g\n", (tv7 - tv6) / (REAL) CLOCKS_PER_SEC);
31330 }
31331 }
31332
31333 if (b->bgmesh) {
31334 // '-b' switch
31335 m.bgm->initializepools();
31336 m.bgm->transfernodes();
31337 m.bgm->reconstructmesh();
31338 m.interpolatesizemap();
31339 }
31340
31341 tv8 = clock();
31342 if (!b->quiet) {
31343 if (b->bgmesh) {
31344 printf("Background mesh reconstruct seconds: %g\n",
31345 (tv8 - tv7) / (REAL) CLOCKS_PER_SEC);
31346 }
31347 }
31348
31349 if (b->quality) {
31350 m.enforcequality();
31351 }
31352
31353 tv9 = clock();
31354 if (!b->quiet) {
31355 if (b->quality) {
31356 printf("Quality seconds: %g\n", (tv9 - tv8) / (REAL) CLOCKS_PER_SEC);
31357 }
31358 }
31359
31360 if (b->quality && b->smooth) {
31361 m.smoothmesh();
31362 }
31363
31364 tv10 = clock();
31365 if (!b->quiet) {
31366 if (b->quality && b->smooth) {
31367 printf("Smooth seconds: %g\n", (tv10 - tv9) / (REAL) CLOCKS_PER_SEC);
31368 }
31369 }
31370
31371 if (!b->nojettison && ((m.dupverts > 0) || (m.unuverts > 0)
31372 || (b->refine && (in->numberofcorners == 10)))) {
31373 m.jettisonnodes();
31374 }
31375
31376 if (b->order > 1) {
31377 m.highorder();
31378 }
31379
31380 if (!b->quiet) {
31381 printf("\n");
31382 }
31383
31384 if (out != (tetgenio *) NULL) {
31385 out->firstnumber = in->firstnumber;
31386 out->mesh_dim = in->mesh_dim;
31387 }
31388
31389 if (b->nonodewritten || b->noiterationnum) {
31390 if (!b->quiet) {
31391 printf("NOT writing a .node file.\n");
31392 }
31393 } else {
31394 if (b->diagnose == 1) {
31395 if (m.subfaces->items > 0l) {
31396 // Only output when there are intersecting faces.
31397 m.outnodes(out);
31398 }
31399 } else {
31400 m.outnodes(out);
31401 if (b->metric) {
31402 m.outmetrics(out);
31403 }
31404 }
31405 }
31406
31407 if (b->noelewritten) {
31408 if (!b->quiet) {
31409 printf("NOT writing an .ele file.\n");
31410 }
31411 } else {
31412 if (!(b->diagnose == 1)) {
31413 if (m.tetrahedrons->items > 0l) {
31414 m.outelements(out);
31415 }
31416 }
31417 }
31418
31419 if (b->nofacewritten) {
31420 if (!b->quiet) {
31421 printf("NOT writing an .face file.\n");
31422 }
31423 } else {
31424 if (b->facesout) {
31425 if (m.tetrahedrons->items > 0l) {
31426 // Output all faces.
31427 m.outfaces(out);
31428 }
31429 } else {
31430 if (b->diagnose == 1) {
31431 if (m.subfaces->items > 0l) {
31432 // Only output when there are intersecting faces.
31433 m.outsubfaces(out);
31434 }
31435 } else if (b->plc || b->refine) {
31436 if (m.subfaces->items > 0l) {
31437 // Output boundary faces.
31438 m.outsubfaces(out);
31439 }
31440 } else {
31441 if (m.tetrahedrons->items > 0l) {
31442 // Output convex hull faces.
31443 m.outhullfaces(out);
31444 }
31445 }
31446 }
31447 }
31448
31449 if (m.checkpbcs) {
31450 m.outpbcnodes(out);
31451 }
31452
31453 if (b->edgesout && b->plc) {
31454 if (m.subsegs->items > 0l) {
31455 m.outsubsegments(out);
31456 }
31457 }
31458
31459 if (!out && b->plc &&
31460 ((b->object == tetgenbehavior::OFF) ||
31461 (b->object == tetgenbehavior::PLY) ||
31462 (b->object == tetgenbehavior::STL))) {
31463 m.outsmesh(b->outfilename);
31464 }
31465
31466 if (!out && b->meditview) {
31467 m.outmesh2medit(b->outfilename);
31468 }
31469
31470 if (!out && b->gidview) {
31471 m.outmesh2gid(b->outfilename);
31472 }
31473
31474 if (!out && b->geomview) {
31475 m.outmesh2off(b->outfilename);
31476 }
31477
31478 if (b->neighout) {
31479 m.outneighbors(out);
31480 }
31481
31482 tv11 = clock();
31483 if (!b->quiet) {
31484 printf("\nOutput seconds: %g\n", (tv11 - tv10) / (REAL) CLOCKS_PER_SEC);
31485 printf("Total running seconds: %g\n",
31486 (tv11 - tv0) / (REAL) CLOCKS_PER_SEC);
31487 }
31488
31489 if (b->docheck) {
31490 m.checkmesh();
31491 if (m.checksubfaces) {
31492 m.checkshells();
31493 }
31494 if (b->docheck > 1) {
31495 m.checkdelaunay(0.0, NULL);
31496 if (b->docheck > 2) {
31497 if (b->quality || b->refine) {
31498 m.checkconforming();
31499 }
31500 }
31501 }
31502 }
31503
31504 if (!b->quiet) {
31505 m.statistics();
31506 }
31507
31508 if (bgmesh) {
31509 delete m.bgm;
31510 }
31511 }
31512
31513 #ifndef TETLIBRARY
31514
31515 ///////////////////////////////////////////////////////////////////////////////
31516 // //
31517 // main() The entrance for running TetGen from command line. //
31518 // //
31519 ///////////////////////////////////////////////////////////////////////////////
31520
31521 int main(int argc, char *argv[])
31522
31523 #else // with TETLIBRARY
31524
31525 ///////////////////////////////////////////////////////////////////////////////
31526 // //
31527 // tetrahedralize() The entrance for calling TetGen from another program. //
31528 // //
31529 ///////////////////////////////////////////////////////////////////////////////
31530
31531 void tetrahedralize(char *switches, tetgenio *in, tetgenio *out,
31532 tetgenio *bgmesh)
31533
31534 #endif // not TETLIBRARY
31535
31536 {
31537 tetgenbehavior b;
31538
31539 #ifndef TETLIBRARY
31540
31541 tetgenio in, bgmesh;
31542
31543 if (!b.parse_commandline(argc, argv)) {
31544 terminatetetgen(1);
31545 }
31546 if (b.refine) {
31547 if (!in.load_tetmesh(b.infilename)) {
31548 terminatetetgen(1);
31549 }
31550 } else {
31551 if (!in.load_plc(b.infilename, (int) b.object)) {
31552 terminatetetgen(1);
31553 }
31554 }
31555 if (b.bgmesh) {
31556 if (!bgmesh.load_tetmesh(b.bgmeshfilename)) {
31557 bgmesh.numberoftetrahedra = 0l;
31558 }
31559 }
31560
31561 if (bgmesh.numberoftetrahedra > 0l) {
31562 tetrahedralize(&b, &in, NULL, &bgmesh);
31563 } else {
31564 tetrahedralize(&b, &in, NULL, NULL);
31565 }
31566
31567 return 0;
31568
31569 #else // with TETLIBRARY
31570
31571 if (!b.parse_commandline(switches)) {
31572 terminatetetgen(1);
31573 }
31574 tetrahedralize(&b, in, out, bgmesh);
31575
31576 #endif // not TETLIBRARY
31577 }