source: src/tesselation.cpp@ a33931

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since a33931 was a33931, checked in by Frederik Heber <heber@…>, 16 years ago

Merge branch 'ConcaveHull' into ConvexHull

Conflicts:

.gitignore
molecuilder/src/Makefile.am
molecuilder/src/atom.cpp
molecuilder/src/tesselation.cpp

no serious overlaps, just a free Frees that were not present in ConcaveHull were MemoryAllocator class was added.

  • Property mode set to 100644
File size: 153.9 KB
Line 
1/*
2 * tesselation.cpp
3 *
4 * Created on: Aug 3, 2009
5 * Author: heber
6 */
7
8#include "helpers.hpp"
9#include "linkedcell.hpp"
10#include "memoryallocator.hpp"
11#include "tesselation.hpp"
12#include "tesselationhelpers.hpp"
13#include "vector.hpp"
14
15class molecule;
16
17// ======================================== Points on Boundary =================================
18
19/** Constructor of BoundaryPointSet.
20 */
21BoundaryPointSet::BoundaryPointSet()
22{
23 LinesCount = 0;
24 Nr = -1;
25 value = 0.;
26};
27
28/** Constructor of BoundaryPointSet with Tesselpoint.
29 * \param *Walker TesselPoint this boundary point represents
30 */
31BoundaryPointSet::BoundaryPointSet(TesselPoint *Walker)
32{
33 node = Walker;
34 LinesCount = 0;
35 Nr = Walker->nr;
36 value = 0.;
37};
38
39/** Destructor of BoundaryPointSet.
40 * Sets node to NULL to avoid removing the original, represented TesselPoint.
41 * \note When removing point from a class Tesselation, use RemoveTesselationPoint()
42 */
43BoundaryPointSet::~BoundaryPointSet()
44{
45 //cout << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
46 if (!lines.empty())
47 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some lines." << endl;
48 node = NULL;
49};
50
51/** Add a line to the LineMap of this point.
52 * \param *line line to add
53 */
54void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
55{
56 cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
57 << endl;
58 if (line->endpoints[0] == this)
59 {
60 lines.insert(LinePair(line->endpoints[1]->Nr, line));
61 }
62 else
63 {
64 lines.insert(LinePair(line->endpoints[0]->Nr, line));
65 }
66 LinesCount++;
67};
68
69/** output operator for BoundaryPointSet.
70 * \param &ost output stream
71 * \param &a boundary point
72 */
73ostream & operator <<(ostream &ost, BoundaryPointSet &a)
74{
75 ost << "[" << a.Nr << "|" << a.node->Name << " at " << *a.node->node << "]";
76 return ost;
77}
78;
79
80// ======================================== Lines on Boundary =================================
81
82/** Constructor of BoundaryLineSet.
83 */
84BoundaryLineSet::BoundaryLineSet()
85{
86 for (int i = 0; i < 2; i++)
87 endpoints[i] = NULL;
88 Nr = -1;
89};
90
91/** Constructor of BoundaryLineSet with two endpoints.
92 * Adds line automatically to each endpoints' LineMap
93 * \param *Point[2] array of two boundary points
94 * \param number number of the list
95 */
96BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], int number)
97{
98 // set number
99 Nr = number;
100 // set endpoints in ascending order
101 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
102 // add this line to the hash maps of both endpoints
103 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
104 Point[1]->AddLine(this); //
105 // clear triangles list
106 cout << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
107};
108
109/** Destructor for BoundaryLineSet.
110 * Removes itself from each endpoints' LineMap, calling RemoveTrianglePoint() when point not connected anymore.
111 * \note When removing lines from a class Tesselation, use RemoveTesselationLine()
112 */
113BoundaryLineSet::~BoundaryLineSet()
114{
115 int Numbers[2];
116
117 // get other endpoint number of finding copies of same line
118 if (endpoints[1] != NULL)
119 Numbers[0] = endpoints[1]->Nr;
120 else
121 Numbers[0] = -1;
122 if (endpoints[0] != NULL)
123 Numbers[1] = endpoints[0]->Nr;
124 else
125 Numbers[1] = -1;
126
127 for (int i = 0; i < 2; i++) {
128 if (endpoints[i] != NULL) {
129 if (Numbers[i] != -1) { // as there may be multiple lines with same endpoints, we have to go through each and find in the endpoint's line list this line set
130 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
131 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
132 if ((*Runner).second == this) {
133 //cout << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
134 endpoints[i]->lines.erase(Runner);
135 break;
136 }
137 } else { // there's just a single line left
138 if (endpoints[i]->lines.erase(Nr)) {
139 //cout << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
140 }
141 }
142 if (endpoints[i]->lines.empty()) {
143 //cout << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
144 if (endpoints[i] != NULL) {
145 delete(endpoints[i]);
146 endpoints[i] = NULL;
147 }
148 }
149 }
150 }
151 if (!triangles.empty())
152 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some triangles." << endl;
153};
154
155/** Add triangle to TriangleMap of this boundary line.
156 * \param *triangle to add
157 */
158void BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
159{
160 cout << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "." << endl;
161 triangles.insert(TrianglePair(triangle->Nr, triangle));
162};
163
164/** Checks whether we have a common endpoint with given \a *line.
165 * \param *line other line to test
166 * \return true - common endpoint present, false - not connected
167 */
168bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
169{
170 if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
171 return true;
172 else
173 return false;
174};
175
176/** Checks whether the adjacent triangles of a baseline are convex or not.
177 * We sum the two angles of each height vector with respect to the center of the baseline.
178 * If greater/equal M_PI than we are convex.
179 * \param *out output stream for debugging
180 * \return true - triangles are convex, false - concave or less than two triangles connected
181 */
182bool BoundaryLineSet::CheckConvexityCriterion(ofstream *out)
183{
184 Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2], NormalCheck;
185 // get the two triangles
186 if (triangles.size() != 2) {
187 *out << Verbose(1) << "ERROR: Baseline " << *this << " is connected to less than two triangles, Tesselation incomplete!" << endl;
188 return true;
189 }
190 // check normal vectors
191 // have a normal vector on the base line pointing outwards
192 //*out << Verbose(3) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
193 BaseLineCenter.CopyVector(endpoints[0]->node->node);
194 BaseLineCenter.AddVector(endpoints[1]->node->node);
195 BaseLineCenter.Scale(1./2.);
196 BaseLine.CopyVector(endpoints[0]->node->node);
197 BaseLine.SubtractVector(endpoints[1]->node->node);
198 //*out << Verbose(3) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
199
200 BaseLineNormal.Zero();
201 NormalCheck.Zero();
202 double sign = -1.;
203 int i=0;
204 class BoundaryPointSet *node = NULL;
205 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
206 //*out << Verbose(3) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
207 NormalCheck.AddVector(&runner->second->NormalVector);
208 NormalCheck.Scale(sign);
209 sign = -sign;
210 if (runner->second->NormalVector.NormSquared() > MYEPSILON)
211 BaseLineNormal.CopyVector(&runner->second->NormalVector); // yes, copy second on top of first
212 else {
213 *out << Verbose(1) << "CRITICAL: Triangle " << *runner->second << " has zero normal vector!" << endl;
214 exit(255);
215 }
216 node = runner->second->GetThirdEndpoint(this);
217 if (node != NULL) {
218 //*out << Verbose(3) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
219 helper[i].CopyVector(node->node->node);
220 helper[i].SubtractVector(&BaseLineCenter);
221 helper[i].MakeNormalVector(&BaseLine); // we want to compare the triangle's heights' angles!
222 //*out << Verbose(4) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
223 i++;
224 } else {
225 //*out << Verbose(2) << "ERROR: I cannot find third node in triangle, something's wrong." << endl;
226 return true;
227 }
228 }
229 //*out << Verbose(3) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
230 if (NormalCheck.NormSquared() < MYEPSILON) {
231 *out << Verbose(3) << "ACCEPT: Normalvectors of both triangles are the same: convex." << endl;
232 return true;
233 }
234 BaseLineNormal.Scale(-1.);
235 double angle = GetAngle(helper[0], helper[1], BaseLineNormal);
236 if ((angle - M_PI) > -MYEPSILON) {
237 *out << Verbose(3) << "ACCEPT: Angle is greater than pi: convex." << endl;
238 return true;
239 } else {
240 *out << Verbose(3) << "REJECT: Angle is less than pi: concave." << endl;
241 return false;
242 }
243}
244
245/** Checks whether point is any of the two endpoints this line contains.
246 * \param *point point to test
247 * \return true - point is of the line, false - is not
248 */
249bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
250{
251 for(int i=0;i<2;i++)
252 if (point == endpoints[i])
253 return true;
254 return false;
255};
256
257/** Returns other endpoint of the line.
258 * \param *point other endpoint
259 * \return NULL - if endpoint not contained in BoundaryLineSet, or pointer to BoundaryPointSet otherwise
260 */
261class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(class BoundaryPointSet *point)
262{
263 if (endpoints[0] == point)
264 return endpoints[1];
265 else if (endpoints[1] == point)
266 return endpoints[0];
267 else
268 return NULL;
269};
270
271/** output operator for BoundaryLineSet.
272 * \param &ost output stream
273 * \param &a boundary line
274 */
275ostream & operator <<(ostream &ost, BoundaryLineSet &a)
276{
277 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << "," << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "]";
278 return ost;
279};
280
281// ======================================== Triangles on Boundary =================================
282
283/** Constructor for BoundaryTriangleSet.
284 */
285BoundaryTriangleSet::BoundaryTriangleSet()
286{
287 for (int i = 0; i < 3; i++)
288 {
289 endpoints[i] = NULL;
290 lines[i] = NULL;
291 }
292 Nr = -1;
293};
294
295/** Constructor for BoundaryTriangleSet with three lines.
296 * \param *line[3] lines that make up the triangle
297 * \param number number of triangle
298 */
299BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
300{
301 // set number
302 Nr = number;
303 // set lines
304 cout << Verbose(5) << "New triangle " << Nr << ":" << endl;
305 for (int i = 0; i < 3; i++)
306 {
307 lines[i] = line[i];
308 lines[i]->AddTriangle(this);
309 }
310 // get ascending order of endpoints
311 map<int, class BoundaryPointSet *> OrderMap;
312 for (int i = 0; i < 3; i++)
313 // for all three lines
314 for (int j = 0; j < 2; j++)
315 { // for both endpoints
316 OrderMap.insert(pair<int, class BoundaryPointSet *> (
317 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
318 // and we don't care whether insertion fails
319 }
320 // set endpoints
321 int Counter = 0;
322 cout << Verbose(6) << " with end points ";
323 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
324 != OrderMap.end(); runner++)
325 {
326 endpoints[Counter] = runner->second;
327 cout << " " << *endpoints[Counter];
328 Counter++;
329 }
330 if (Counter < 3)
331 {
332 cerr << "ERROR! We have a triangle with only two distinct endpoints!"
333 << endl;
334 //exit(1);
335 }
336 cout << "." << endl;
337};
338
339/** Destructor of BoundaryTriangleSet.
340 * Removes itself from each of its lines' LineMap and removes them if necessary.
341 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
342 */
343BoundaryTriangleSet::~BoundaryTriangleSet()
344{
345 for (int i = 0; i < 3; i++) {
346 if (lines[i] != NULL) {
347 if (lines[i]->triangles.erase(Nr)) {
348 //cout << Verbose(5) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
349 }
350 if (lines[i]->triangles.empty()) {
351 //cout << Verbose(5) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
352 delete (lines[i]);
353 lines[i] = NULL;
354 }
355 }
356 }
357 //cout << Verbose(5) << "Erasing triangle Nr." << Nr << " itself." << endl;
358};
359
360/** Calculates the normal vector for this triangle.
361 * Is made unique by comparison with \a OtherVector to point in the other direction.
362 * \param &OtherVector direction vector to make normal vector unique.
363 */
364void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
365{
366 // get normal vector
367 NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
368
369 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
370 if (NormalVector.ScalarProduct(&OtherVector) > 0.)
371 NormalVector.Scale(-1.);
372};
373
374/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
375 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
376 * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
377 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
378 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
379 * the first two basepoints) or not.
380 * \param *out output stream for debugging
381 * \param *MolCenter offset vector of line
382 * \param *x second endpoint of line, minus \a *MolCenter is directional vector of line
383 * \param *Intersection intersection on plane on return
384 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
385 */
386bool BoundaryTriangleSet::GetIntersectionInsideTriangle(ofstream *out, Vector *MolCenter, Vector *x, Vector *Intersection)
387{
388 Vector CrossPoint;
389 Vector helper;
390
391 if (!Intersection->GetIntersectionWithPlane(out, &NormalVector, endpoints[0]->node->node, MolCenter, x)) {
392 *out << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl;
393 return false;
394 }
395
396 // Calculate cross point between one baseline and the line from the third endpoint to intersection
397 int i=0;
398 do {
399 if (CrossPoint.GetIntersectionOfTwoLinesOnPlane(out, endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection, &NormalVector)) {
400 helper.CopyVector(endpoints[(i+1)%3]->node->node);
401 helper.SubtractVector(endpoints[i%3]->node->node);
402 } else
403 i++;
404 if (i>2)
405 break;
406 } while (CrossPoint.NormSquared() < MYEPSILON);
407 if (i==3) {
408 *out << Verbose(1) << "ERROR: Could not find any cross points, something's utterly wrong here!" << endl;
409 exit(255);
410 }
411 CrossPoint.SubtractVector(endpoints[i%3]->node->node); // cross point was returned as absolute vector
412
413 // check whether intersection is inside or not by comparing length of intersection and length of cross point
414 if ((CrossPoint.NormSquared() - helper.NormSquared()) < MYEPSILON) { // inside
415 return true;
416 } else { // outside!
417 Intersection->Zero();
418 return false;
419 }
420};
421
422/** Checks whether lines is any of the three boundary lines this triangle contains.
423 * \param *line line to test
424 * \return true - line is of the triangle, false - is not
425 */
426bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
427{
428 for(int i=0;i<3;i++)
429 if (line == lines[i])
430 return true;
431 return false;
432};
433
434/** Checks whether point is any of the three endpoints this triangle contains.
435 * \param *point point to test
436 * \return true - point is of the triangle, false - is not
437 */
438bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
439{
440 for(int i=0;i<3;i++)
441 if (point == endpoints[i])
442 return true;
443 return false;
444};
445
446/** Checks whether point is any of the three endpoints this triangle contains.
447 * \param *point TesselPoint to test
448 * \return true - point is of the triangle, false - is not
449 */
450bool BoundaryTriangleSet::ContainsBoundaryPoint(class TesselPoint *point)
451{
452 for(int i=0;i<3;i++)
453 if (point == endpoints[i]->node)
454 return true;
455 return false;
456};
457
458/** Checks whether three given \a *Points coincide with triangle's endpoints.
459 * \param *Points[3] pointer to BoundaryPointSet
460 * \return true - is the very triangle, false - is not
461 */
462bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
463{
464 return (((endpoints[0] == Points[0])
465 || (endpoints[0] == Points[1])
466 || (endpoints[0] == Points[2])
467 ) && (
468 (endpoints[1] == Points[0])
469 || (endpoints[1] == Points[1])
470 || (endpoints[1] == Points[2])
471 ) && (
472 (endpoints[2] == Points[0])
473 || (endpoints[2] == Points[1])
474 || (endpoints[2] == Points[2])
475
476 ));
477};
478
479/** Checks whether three given \a *Points coincide with triangle's endpoints.
480 * \param *Points[3] pointer to BoundaryPointSet
481 * \return true - is the very triangle, false - is not
482 */
483bool BoundaryTriangleSet::IsPresentTupel(class BoundaryTriangleSet *T)
484{
485 return (((endpoints[0] == T->endpoints[0])
486 || (endpoints[0] == T->endpoints[1])
487 || (endpoints[0] == T->endpoints[2])
488 ) && (
489 (endpoints[1] == T->endpoints[0])
490 || (endpoints[1] == T->endpoints[1])
491 || (endpoints[1] == T->endpoints[2])
492 ) && (
493 (endpoints[2] == T->endpoints[0])
494 || (endpoints[2] == T->endpoints[1])
495 || (endpoints[2] == T->endpoints[2])
496
497 ));
498};
499
500/** Returns the endpoint which is not contained in the given \a *line.
501 * \param *line baseline defining two endpoints
502 * \return pointer third endpoint or NULL if line does not belong to triangle.
503 */
504class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(class BoundaryLineSet *line)
505{
506 // sanity check
507 if (!ContainsBoundaryLine(line))
508 return NULL;
509 for(int i=0;i<3;i++)
510 if (!line->ContainsBoundaryPoint(endpoints[i]))
511 return endpoints[i];
512 // actually, that' impossible :)
513 return NULL;
514};
515
516/** Calculates the center point of the triangle.
517 * Is third of the sum of all endpoints.
518 * \param *center central point on return.
519 */
520void BoundaryTriangleSet::GetCenter(Vector *center)
521{
522 center->Zero();
523 for(int i=0;i<3;i++)
524 center->AddVector(endpoints[i]->node->node);
525 center->Scale(1./3.);
526}
527
528/** output operator for BoundaryTriangleSet.
529 * \param &ost output stream
530 * \param &a boundary triangle
531 */
532ostream &operator <<(ostream &ost, BoundaryTriangleSet &a)
533{
534 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
535 << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
536 return ost;
537};
538
539// =========================================================== class TESSELPOINT ===========================================
540
541/** Constructor of class TesselPoint.
542 */
543TesselPoint::TesselPoint()
544{
545 node = NULL;
546 nr = -1;
547 Name = NULL;
548};
549
550/** Destructor for class TesselPoint.
551 */
552TesselPoint::~TesselPoint()
553{
554 Free<char *>(&Name, "~TesselPoint - *Name");
555};
556
557/** Prints LCNode to screen.
558 */
559ostream & operator << (ostream &ost, const TesselPoint &a)
560{
561 ost << "[" << (a.Name) << "|" << a.Name << " at " << *a.node << "]";
562 return ost;
563};
564
565/** Prints LCNode to screen.
566 */
567ostream & TesselPoint::operator << (ostream &ost)
568{
569 ost << "[" << (Name) << "|" << this << "]";
570 return ost;
571};
572
573
574// =========================================================== class POINTCLOUD ============================================
575
576/** Constructor of class PointCloud.
577 */
578PointCloud::PointCloud()
579{
580
581};
582
583/** Destructor for class PointCloud.
584 */
585PointCloud::~PointCloud()
586{
587
588};
589
590// ============================ CandidateForTesselation =============================
591
592/** Constructor of class CandidateForTesselation.
593 */
594CandidateForTesselation::CandidateForTesselation(TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) {
595 point = candidate;
596 BaseLine = line;
597 OptCenter.CopyVector(&OptCandidateCenter);
598 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
599};
600
601/** Destructor for class CandidateForTesselation.
602 */
603CandidateForTesselation::~CandidateForTesselation() {
604 point = NULL;
605 BaseLine = NULL;
606};
607
608// =========================================================== class TESSELATION ===========================================
609
610/** Constructor of class Tesselation.
611 */
612Tesselation::Tesselation()
613{
614 PointsOnBoundaryCount = 0;
615 LinesOnBoundaryCount = 0;
616 TrianglesOnBoundaryCount = 0;
617 InternalPointer = PointsOnBoundary.begin();
618 LastTriangle = NULL;
619 TriangleFilesWritten = 0;
620}
621;
622
623/** Destructor of class Tesselation.
624 * We have to free all points, lines and triangles.
625 */
626Tesselation::~Tesselation()
627{
628 cout << Verbose(1) << "Free'ing TesselStruct ... " << endl;
629 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
630 if (runner->second != NULL) {
631 delete (runner->second);
632 runner->second = NULL;
633 } else
634 cerr << "ERROR: The triangle " << runner->first << " has already been free'd." << endl;
635 }
636 cout << "This envelope was written to file " << TriangleFilesWritten << " times(s)." << endl;
637}
638;
639
640/** PointCloud implementation of GetCenter
641 * Uses PointsOnBoundary and STL stuff.
642 */
643Vector * Tesselation::GetCenter(ofstream *out)
644{
645 Vector *Center = new Vector(0.,0.,0.);
646 int num=0;
647 for (GoToFirst(); (!IsEnd()); GoToNext()) {
648 Center->AddVector(GetPoint()->node);
649 num++;
650 }
651 Center->Scale(1./num);
652 return Center;
653};
654
655/** PointCloud implementation of GoPoint
656 * Uses PointsOnBoundary and STL stuff.
657 */
658TesselPoint * Tesselation::GetPoint()
659{
660 return (InternalPointer->second->node);
661};
662
663/** PointCloud implementation of GetTerminalPoint.
664 * Uses PointsOnBoundary and STL stuff.
665 */
666TesselPoint * Tesselation::GetTerminalPoint()
667{
668 PointMap::iterator Runner = PointsOnBoundary.end();
669 Runner--;
670 return (Runner->second->node);
671};
672
673/** PointCloud implementation of GoToNext.
674 * Uses PointsOnBoundary and STL stuff.
675 */
676void Tesselation::GoToNext()
677{
678 if (InternalPointer != PointsOnBoundary.end())
679 InternalPointer++;
680};
681
682/** PointCloud implementation of GoToPrevious.
683 * Uses PointsOnBoundary and STL stuff.
684 */
685void Tesselation::GoToPrevious()
686{
687 if (InternalPointer != PointsOnBoundary.begin())
688 InternalPointer--;
689};
690
691/** PointCloud implementation of GoToFirst.
692 * Uses PointsOnBoundary and STL stuff.
693 */
694void Tesselation::GoToFirst()
695{
696 InternalPointer = PointsOnBoundary.begin();
697};
698
699/** PointCloud implementation of GoToLast.
700 * Uses PointsOnBoundary and STL stuff.
701 */
702void Tesselation::GoToLast()
703{
704 InternalPointer = PointsOnBoundary.end();
705 InternalPointer--;
706};
707
708/** PointCloud implementation of IsEmpty.
709 * Uses PointsOnBoundary and STL stuff.
710 */
711bool Tesselation::IsEmpty()
712{
713 return (PointsOnBoundary.empty());
714};
715
716/** PointCloud implementation of IsLast.
717 * Uses PointsOnBoundary and STL stuff.
718 */
719bool Tesselation::IsEnd()
720{
721 return (InternalPointer == PointsOnBoundary.end());
722};
723
724
725/** Gueses first starting triangle of the convex envelope.
726 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
727 * \param *out output stream for debugging
728 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
729 */
730void
731Tesselation::GuessStartingTriangle(ofstream *out)
732{
733 // 4b. create a starting triangle
734 // 4b1. create all distances
735 DistanceMultiMap DistanceMMap;
736 double distance, tmp;
737 Vector PlaneVector, TrialVector;
738 PointMap::iterator A, B, C; // three nodes of the first triangle
739 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
740
741 // with A chosen, take each pair B,C and sort
742 if (A != PointsOnBoundary.end())
743 {
744 B = A;
745 B++;
746 for (; B != PointsOnBoundary.end(); B++)
747 {
748 C = B;
749 C++;
750 for (; C != PointsOnBoundary.end(); C++)
751 {
752 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
753 distance = tmp * tmp;
754 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
755 distance += tmp * tmp;
756 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
757 distance += tmp * tmp;
758 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
759 }
760 }
761 }
762 // // listing distances
763 // *out << Verbose(1) << "Listing DistanceMMap:";
764 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
765 // *out << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
766 // }
767 // *out << endl;
768 // 4b2. pick three baselines forming a triangle
769 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
770 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
771 for (; baseline != DistanceMMap.end(); baseline++)
772 {
773 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
774 // 2. next, we have to check whether all points reside on only one side of the triangle
775 // 3. construct plane vector
776 PlaneVector.MakeNormalVector(A->second->node->node,
777 baseline->second.first->second->node->node,
778 baseline->second.second->second->node->node);
779 *out << Verbose(2) << "Plane vector of candidate triangle is ";
780 PlaneVector.Output(out);
781 *out << endl;
782 // 4. loop over all points
783 double sign = 0.;
784 PointMap::iterator checker = PointsOnBoundary.begin();
785 for (; checker != PointsOnBoundary.end(); checker++)
786 {
787 // (neglecting A,B,C)
788 if ((checker == A) || (checker == baseline->second.first) || (checker
789 == baseline->second.second))
790 continue;
791 // 4a. project onto plane vector
792 TrialVector.CopyVector(checker->second->node->node);
793 TrialVector.SubtractVector(A->second->node->node);
794 distance = TrialVector.ScalarProduct(&PlaneVector);
795 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
796 continue;
797 *out << Verbose(3) << "Projection of " << checker->second->node->Name
798 << " yields distance of " << distance << "." << endl;
799 tmp = distance / fabs(distance);
800 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
801 if ((sign != 0) && (tmp != sign))
802 {
803 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
804 *out << Verbose(2) << "Current candidates: "
805 << A->second->node->Name << ","
806 << baseline->second.first->second->node->Name << ","
807 << baseline->second.second->second->node->Name << " leaves "
808 << checker->second->node->Name << " outside the convex hull."
809 << endl;
810 break;
811 }
812 else
813 { // note the sign for later
814 *out << Verbose(2) << "Current candidates: "
815 << A->second->node->Name << ","
816 << baseline->second.first->second->node->Name << ","
817 << baseline->second.second->second->node->Name << " leave "
818 << checker->second->node->Name << " inside the convex hull."
819 << endl;
820 sign = tmp;
821 }
822 // 4d. Check whether the point is inside the triangle (check distance to each node
823 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
824 int innerpoint = 0;
825 if ((tmp < A->second->node->node->DistanceSquared(
826 baseline->second.first->second->node->node)) && (tmp
827 < A->second->node->node->DistanceSquared(
828 baseline->second.second->second->node->node)))
829 innerpoint++;
830 tmp = checker->second->node->node->DistanceSquared(
831 baseline->second.first->second->node->node);
832 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
833 A->second->node->node)) && (tmp
834 < baseline->second.first->second->node->node->DistanceSquared(
835 baseline->second.second->second->node->node)))
836 innerpoint++;
837 tmp = checker->second->node->node->DistanceSquared(
838 baseline->second.second->second->node->node);
839 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
840 baseline->second.first->second->node->node)) && (tmp
841 < baseline->second.second->second->node->node->DistanceSquared(
842 A->second->node->node)))
843 innerpoint++;
844 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
845 if (innerpoint == 3)
846 break;
847 }
848 // 5. come this far, all on same side? Then break 1. loop and construct triangle
849 if (checker == PointsOnBoundary.end())
850 {
851 *out << "Looks like we have a candidate!" << endl;
852 break;
853 }
854 }
855 if (baseline != DistanceMMap.end())
856 {
857 BPS[0] = baseline->second.first->second;
858 BPS[1] = baseline->second.second->second;
859 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
860 BPS[0] = A->second;
861 BPS[1] = baseline->second.second->second;
862 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
863 BPS[0] = baseline->second.first->second;
864 BPS[1] = A->second;
865 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
866
867 // 4b3. insert created triangle
868 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
869 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
870 TrianglesOnBoundaryCount++;
871 for (int i = 0; i < NDIM; i++)
872 {
873 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
874 LinesOnBoundaryCount++;
875 }
876
877 *out << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
878 }
879 else
880 {
881 *out << Verbose(1) << "No starting triangle found." << endl;
882 exit(255);
883 }
884}
885;
886
887/** Tesselates the convex envelope of a cluster from a single starting triangle.
888 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
889 * 2 triangles. Hence, we go through all current lines:
890 * -# if the lines contains to only one triangle
891 * -# We search all points in the boundary
892 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
893 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
894 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
895 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
896 * \param *out output stream for debugging
897 * \param *configuration for IsAngstroem
898 * \param *cloud cluster of points
899 */
900void Tesselation::TesselateOnBoundary(ofstream *out, PointCloud *cloud)
901{
902 bool flag;
903 PointMap::iterator winner;
904 class BoundaryPointSet *peak = NULL;
905 double SmallestAngle, TempAngle;
906 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
907 LineMap::iterator LineChecker[2];
908
909 Center = cloud->GetCenter(out);
910 // create a first tesselation with the given BoundaryPoints
911 do {
912 flag = false;
913 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
914 if (baseline->second->triangles.size() == 1) {
915 // 5a. go through each boundary point if not _both_ edges between either endpoint of the current line and this point exist (and belong to 2 triangles)
916 SmallestAngle = M_PI;
917
918 // get peak point with respect to this base line's only triangle
919 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
920 *out << Verbose(2) << "Current baseline is between " << *(baseline->second) << "." << endl;
921 for (int i = 0; i < 3; i++)
922 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
923 peak = BTS->endpoints[i];
924 *out << Verbose(3) << " and has peak " << *peak << "." << endl;
925
926 // prepare some auxiliary vectors
927 Vector BaseLineCenter, BaseLine;
928 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
929 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
930 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
931 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
932 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
933
934 // offset to center of triangle
935 CenterVector.Zero();
936 for (int i = 0; i < 3; i++)
937 CenterVector.AddVector(BTS->endpoints[i]->node->node);
938 CenterVector.Scale(1. / 3.);
939 *out << Verbose(4) << "CenterVector of base triangle is " << CenterVector << endl;
940
941 // normal vector of triangle
942 NormalVector.CopyVector(Center);
943 NormalVector.SubtractVector(&CenterVector);
944 BTS->GetNormalVector(NormalVector);
945 NormalVector.CopyVector(&BTS->NormalVector);
946 *out << Verbose(4) << "NormalVector of base triangle is " << NormalVector << endl;
947
948 // vector in propagation direction (out of triangle)
949 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
950 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
951 TempVector.CopyVector(&CenterVector);
952 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
953 //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
954 if (PropagationVector.ScalarProduct(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
955 PropagationVector.Scale(-1.);
956 *out << Verbose(4) << "PropagationVector of base triangle is " << PropagationVector << endl;
957 winner = PointsOnBoundary.end();
958
959 // loop over all points and calculate angle between normal vector of new and present triangle
960 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
961 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
962 *out << Verbose(3) << "Target point is " << *(target->second) << ":" << endl;
963
964 // first check direction, so that triangles don't intersect
965 VirtualNormalVector.CopyVector(target->second->node->node);
966 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
967 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
968 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
969 *out << Verbose(4) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
970 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
971 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
972 continue;
973 } else
974 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
975
976 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
977 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
978 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
979 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->triangles.size() == 2))) {
980 *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->triangles.size() << " triangles." << endl;
981 continue;
982 }
983 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->triangles.size() == 2))) {
984 *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->triangles.size() << " triangles." << endl;
985 continue;
986 }
987
988 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
989 if ((((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (GetCommonEndpoint(LineChecker[0]->second, LineChecker[1]->second) == peak)))) {
990 *out << Verbose(4) << "Current target is peak!" << endl;
991 continue;
992 }
993
994 // check for linear dependence
995 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
996 TempVector.SubtractVector(target->second->node->node);
997 helper.CopyVector(baseline->second->endpoints[1]->node->node);
998 helper.SubtractVector(target->second->node->node);
999 helper.ProjectOntoPlane(&TempVector);
1000 if (fabs(helper.NormSquared()) < MYEPSILON) {
1001 *out << Verbose(4) << "Chosen set of vectors is linear dependent." << endl;
1002 continue;
1003 }
1004
1005 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
1006 flag = true;
1007 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
1008 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1009 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
1010 TempVector.AddVector(target->second->node->node);
1011 TempVector.Scale(1./3.);
1012 TempVector.SubtractVector(Center);
1013 // make it always point outward
1014 if (VirtualNormalVector.ScalarProduct(&TempVector) < 0)
1015 VirtualNormalVector.Scale(-1.);
1016 // calculate angle
1017 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1018 *out << Verbose(4) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
1019 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
1020 SmallestAngle = TempAngle;
1021 winner = target;
1022 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1023 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
1024 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
1025 helper.CopyVector(target->second->node->node);
1026 helper.SubtractVector(&BaseLineCenter);
1027 helper.ProjectOntoPlane(&BaseLine);
1028 // ...the one with the smaller angle is the better candidate
1029 TempVector.CopyVector(target->second->node->node);
1030 TempVector.SubtractVector(&BaseLineCenter);
1031 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1032 TempAngle = TempVector.Angle(&helper);
1033 TempVector.CopyVector(winner->second->node->node);
1034 TempVector.SubtractVector(&BaseLineCenter);
1035 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1036 if (TempAngle < TempVector.Angle(&helper)) {
1037 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1038 SmallestAngle = TempAngle;
1039 winner = target;
1040 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
1041 } else
1042 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
1043 } else
1044 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1045 }
1046 } // end of loop over all boundary points
1047
1048 // 5b. The point of the above whose triangle has the greatest angle with the triangle the current line belongs to (it only belongs to one, remember!): New triangle
1049 if (winner != PointsOnBoundary.end()) {
1050 *out << Verbose(2) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
1051 // create the lins of not yet present
1052 BLS[0] = baseline->second;
1053 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1054 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
1055 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
1056 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
1057 BPS[0] = baseline->second->endpoints[0];
1058 BPS[1] = winner->second;
1059 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1060 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
1061 LinesOnBoundaryCount++;
1062 } else
1063 BLS[1] = LineChecker[0]->second;
1064 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
1065 BPS[0] = baseline->second->endpoints[1];
1066 BPS[1] = winner->second;
1067 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1068 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
1069 LinesOnBoundaryCount++;
1070 } else
1071 BLS[2] = LineChecker[1]->second;
1072 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1073 BTS->GetCenter(&helper);
1074 helper.SubtractVector(Center);
1075 helper.Scale(-1);
1076 BTS->GetNormalVector(helper);
1077 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1078 TrianglesOnBoundaryCount++;
1079 } else {
1080 *out << Verbose(1) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
1081 }
1082
1083 // 5d. If the set of lines is not yet empty, go to 5. and continue
1084 } else
1085 *out << Verbose(2) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl;
1086 } while (flag);
1087
1088 // exit
1089 delete(Center);
1090};
1091
1092/** Inserts all points outside of the tesselated surface into it by adding new triangles.
1093 * \param *out output stream for debugging
1094 * \param *cloud cluster of points
1095 * \param *LC LinkedCell structure to find nearest point quickly
1096 * \return true - all straddling points insert, false - something went wrong
1097 */
1098bool Tesselation::InsertStraddlingPoints(ofstream *out, PointCloud *cloud, LinkedCell *LC)
1099{
1100 Vector Intersection, Normal;
1101 TesselPoint *Walker = NULL;
1102 Vector *Center = cloud->GetCenter(out);
1103 list<BoundaryTriangleSet*> *triangles = NULL;
1104 bool AddFlag = false;
1105 LinkedCell *BoundaryPoints = NULL;
1106
1107 *out << Verbose(1) << "Begin of InsertStraddlingPoints" << endl;
1108
1109 cloud->GoToFirst();
1110 BoundaryPoints = new LinkedCell(this, 5.);
1111 while (!cloud->IsEnd()) { // we only have to go once through all points, as boundary can become only bigger
1112 if (AddFlag) {
1113 delete(BoundaryPoints);
1114 BoundaryPoints = new LinkedCell(this, 5.);
1115 AddFlag = false;
1116 }
1117 Walker = cloud->GetPoint();
1118 *out << Verbose(2) << "Current point is " << *Walker << "." << endl;
1119 // get the next triangle
1120 triangles = FindClosestTrianglesToPoint(out, Walker->node, BoundaryPoints);
1121 BTS = triangles->front();
1122 if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
1123 *out << Verbose(2) << "No triangles found, probably a tesselation point itself." << endl;
1124 cloud->GoToNext();
1125 continue;
1126 } else {
1127 }
1128 *out << Verbose(2) << "Closest triangle is " << *BTS << "." << endl;
1129 // get the intersection point
1130 if (BTS->GetIntersectionInsideTriangle(out, Center, Walker->node, &Intersection)) {
1131 *out << Verbose(2) << "We have an intersection at " << Intersection << "." << endl;
1132 // we have the intersection, check whether in- or outside of boundary
1133 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
1134 // inside, next!
1135 *out << Verbose(2) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
1136 } else {
1137 // outside!
1138 *out << Verbose(2) << *Walker << " is outside wrt triangle " << *BTS << "." << endl;
1139 class BoundaryLineSet *OldLines[3], *NewLines[3];
1140 class BoundaryPointSet *OldPoints[3], *NewPoint;
1141 // store the three old lines and old points
1142 for (int i=0;i<3;i++) {
1143 OldLines[i] = BTS->lines[i];
1144 OldPoints[i] = BTS->endpoints[i];
1145 }
1146 Normal.CopyVector(&BTS->NormalVector);
1147 // add Walker to boundary points
1148 *out << Verbose(2) << "Adding " << *Walker << " to BoundaryPoints." << endl;
1149 AddFlag = true;
1150 if (AddBoundaryPoint(Walker,0))
1151 NewPoint = BPS[0];
1152 else
1153 continue;
1154 // remove triangle
1155 *out << Verbose(2) << "Erasing triangle " << *BTS << "." << endl;
1156 TrianglesOnBoundary.erase(BTS->Nr);
1157 delete(BTS);
1158 // create three new boundary lines
1159 for (int i=0;i<3;i++) {
1160 BPS[0] = NewPoint;
1161 BPS[1] = OldPoints[i];
1162 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1163 *out << Verbose(3) << "Creating new line " << *NewLines[i] << "." << endl;
1164 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
1165 LinesOnBoundaryCount++;
1166 }
1167 // create three new triangle with new point
1168 for (int i=0;i<3;i++) { // find all baselines
1169 BLS[0] = OldLines[i];
1170 int n = 1;
1171 for (int j=0;j<3;j++) {
1172 if (NewLines[j]->IsConnectedTo(BLS[0])) {
1173 if (n>2) {
1174 *out << Verbose(1) << "ERROR: " << BLS[0] << " connects to all of the new lines?!" << endl;
1175 return false;
1176 } else
1177 BLS[n++] = NewLines[j];
1178 }
1179 }
1180 // create the triangle
1181 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1182 Normal.Scale(-1.);
1183 BTS->GetNormalVector(Normal);
1184 Normal.Scale(-1.);
1185 *out << Verbose(2) << "Created new triangle " << *BTS << "." << endl;
1186 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1187 TrianglesOnBoundaryCount++;
1188 }
1189 }
1190 } else { // something is wrong with FindClosestTriangleToPoint!
1191 *out << Verbose(1) << "ERROR: The closest triangle did not produce an intersection!" << endl;
1192 return false;
1193 }
1194 cloud->GoToNext();
1195 }
1196
1197 // exit
1198 delete(Center);
1199 *out << Verbose(1) << "End of InsertStraddlingPoints" << endl;
1200 return true;
1201};
1202
1203/** Adds a point to the tesselation::PointsOnBoundary list.
1204 * \param *Walker point to add
1205 * \param n TesselStruct::BPS index to put pointer into
1206 * \return true - new point was added, false - point already present
1207 */
1208bool
1209Tesselation::AddBoundaryPoint(TesselPoint *Walker, int n)
1210{
1211 PointTestPair InsertUnique;
1212 BPS[n] = new class BoundaryPointSet(Walker);
1213 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[n]));
1214 if (InsertUnique.second) { // if new point was not present before, increase counter
1215 PointsOnBoundaryCount++;
1216 return true;
1217 } else {
1218 delete(BPS[n]);
1219 BPS[n] = InsertUnique.first->second;
1220 return false;
1221 }
1222}
1223;
1224
1225/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1226 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1227 * @param Candidate point to add
1228 * @param n index for this point in Tesselation::TPS array
1229 */
1230void
1231Tesselation::AddTesselationPoint(TesselPoint* Candidate, int n)
1232{
1233 PointTestPair InsertUnique;
1234 TPS[n] = new class BoundaryPointSet(Candidate);
1235 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1236 if (InsertUnique.second) { // if new point was not present before, increase counter
1237 PointsOnBoundaryCount++;
1238 } else {
1239 delete TPS[n];
1240 cout << Verbose(4) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1241 TPS[n] = (InsertUnique.first)->second;
1242 }
1243}
1244;
1245
1246/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1247 * If successful it raises the line count and inserts the new line into the BLS,
1248 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1249 * @param *a first endpoint
1250 * @param *b second endpoint
1251 * @param n index of Tesselation::BLS giving the line with both endpoints
1252 */
1253void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n) {
1254 bool insertNewLine = true;
1255
1256 if (a->lines.find(b->node->nr) != a->lines.end()) {
1257 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1258 pair<LineMap::iterator,LineMap::iterator> FindPair;
1259 FindPair = a->lines.equal_range(b->node->nr);
1260 cout << Verbose(5) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1261
1262 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1263 // If there is a line with less than two attached triangles, we don't need a new line.
1264 if (FindLine->second->triangles.size() < 2) {
1265 insertNewLine = false;
1266 cout << Verbose(4) << "Using existing line " << *FindLine->second << endl;
1267
1268 BPS[0] = FindLine->second->endpoints[0];
1269 BPS[1] = FindLine->second->endpoints[1];
1270 BLS[n] = FindLine->second;
1271
1272 break;
1273 }
1274 }
1275 }
1276
1277 if (insertNewLine) {
1278 AlwaysAddTesselationTriangleLine(a, b, n);
1279 }
1280}
1281;
1282
1283/**
1284 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1285 * Raises the line count and inserts the new line into the BLS.
1286 *
1287 * @param *a first endpoint
1288 * @param *b second endpoint
1289 * @param n index of Tesselation::BLS giving the line with both endpoints
1290 */
1291void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n)
1292{
1293 cout << Verbose(4) << "Adding line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1294 BPS[0] = a;
1295 BPS[1] = b;
1296 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1297 // add line to global map
1298 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1299 // increase counter
1300 LinesOnBoundaryCount++;
1301};
1302
1303/** Function adds triangle to global list.
1304 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1305 */
1306void Tesselation::AddTesselationTriangle()
1307{
1308 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1309
1310 // add triangle to global map
1311 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1312 TrianglesOnBoundaryCount++;
1313
1314 // set as last new triangle
1315 LastTriangle = BTS;
1316
1317 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1318};
1319
1320/** Function adds triangle to global list.
1321 * Furthermore, the triangle number is set to \a nr.
1322 * \param nr triangle number
1323 */
1324void Tesselation::AddTesselationTriangle(int nr)
1325{
1326 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1327
1328 // add triangle to global map
1329 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1330
1331 // set as last new triangle
1332 LastTriangle = BTS;
1333
1334 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1335};
1336
1337/** Removes a triangle from the tesselation.
1338 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1339 * Removes itself from memory.
1340 * \param *triangle to remove
1341 */
1342void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1343{
1344 if (triangle == NULL)
1345 return;
1346 for (int i = 0; i < 3; i++) {
1347 if (triangle->lines[i] != NULL) {
1348 cout << Verbose(5) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1349 triangle->lines[i]->triangles.erase(triangle->Nr);
1350 if (triangle->lines[i]->triangles.empty()) {
1351 cout << Verbose(5) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1352 RemoveTesselationLine(triangle->lines[i]);
1353 } else {
1354 cout << Verbose(5) << *triangle->lines[i] << " is still attached to another triangle: ";
1355 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1356 cout << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1357 cout << endl;
1358// for (int j=0;j<2;j++) {
1359// cout << Verbose(5) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1360// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1361// cout << "[" << *(LineRunner->second) << "] \t";
1362// cout << endl;
1363// }
1364 }
1365 triangle->lines[i] = NULL; // free'd or not: disconnect
1366 } else
1367 cerr << "ERROR: This line " << i << " has already been free'd." << endl;
1368 }
1369
1370 if (TrianglesOnBoundary.erase(triangle->Nr))
1371 cout << Verbose(5) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1372 delete(triangle);
1373};
1374
1375/** Removes a line from the tesselation.
1376 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1377 * \param *line line to remove
1378 */
1379void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1380{
1381 int Numbers[2];
1382
1383 if (line == NULL)
1384 return;
1385 // get other endpoint number for finding copies of same line
1386 if (line->endpoints[1] != NULL)
1387 Numbers[0] = line->endpoints[1]->Nr;
1388 else
1389 Numbers[0] = -1;
1390 if (line->endpoints[0] != NULL)
1391 Numbers[1] = line->endpoints[0]->Nr;
1392 else
1393 Numbers[1] = -1;
1394
1395 for (int i = 0; i < 2; i++) {
1396 if (line->endpoints[i] != NULL) {
1397 if (Numbers[i] != -1) { // as there may be multiple lines with same endpoints, we have to go through each and find in the endpoint's line list this line set
1398 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
1399 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
1400 if ((*Runner).second == line) {
1401 cout << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1402 line->endpoints[i]->lines.erase(Runner);
1403 break;
1404 }
1405 } else { // there's just a single line left
1406 if (line->endpoints[i]->lines.erase(line->Nr))
1407 cout << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1408 }
1409 if (line->endpoints[i]->lines.empty()) {
1410 cout << Verbose(5) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
1411 RemoveTesselationPoint(line->endpoints[i]);
1412 } else {
1413 cout << Verbose(5) << *line->endpoints[i] << " has still lines it's attached to: ";
1414 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
1415 cout << "[" << *(LineRunner->second) << "] \t";
1416 cout << endl;
1417 }
1418 line->endpoints[i] = NULL; // free'd or not: disconnect
1419 } else
1420 cerr << "ERROR: Endpoint " << i << " has already been free'd." << endl;
1421 }
1422 if (!line->triangles.empty())
1423 cerr << "WARNING: Memory Leak! I " << *line << " am still connected to some triangles." << endl;
1424
1425 if (LinesOnBoundary.erase(line->Nr))
1426 cout << Verbose(5) << "Removing line Nr. " << line->Nr << "." << endl;
1427 delete(line);
1428};
1429
1430/** Removes a point from the tesselation.
1431 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
1432 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
1433 * \param *point point to remove
1434 */
1435void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
1436{
1437 if (point == NULL)
1438 return;
1439 if (PointsOnBoundary.erase(point->Nr))
1440 cout << Verbose(5) << "Removing point Nr. " << point->Nr << "." << endl;
1441 delete(point);
1442};
1443
1444/** Checks whether the triangle consisting of the three points is already present.
1445 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1446 * lines. If any of the three edges already has two triangles attached, false is
1447 * returned.
1448 * \param *out output stream for debugging
1449 * \param *Candidates endpoints of the triangle candidate
1450 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1451 * triangles exist which is the maximum for three points
1452 */
1453int Tesselation::CheckPresenceOfTriangle(ofstream *out, TesselPoint *Candidates[3]) {
1454 int adjacentTriangleCount = 0;
1455 class BoundaryPointSet *Points[3];
1456
1457 *out << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1458 // builds a triangle point set (Points) of the end points
1459 for (int i = 0; i < 3; i++) {
1460 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1461 if (FindPoint != PointsOnBoundary.end()) {
1462 Points[i] = FindPoint->second;
1463 } else {
1464 Points[i] = NULL;
1465 }
1466 }
1467
1468 // checks lines between the points in the Points for their adjacent triangles
1469 for (int i = 0; i < 3; i++) {
1470 if (Points[i] != NULL) {
1471 for (int j = i; j < 3; j++) {
1472 if (Points[j] != NULL) {
1473 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1474 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1475 TriangleMap *triangles = &FindLine->second->triangles;
1476 *out << Verbose(3) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1477 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1478 if (FindTriangle->second->IsPresentTupel(Points)) {
1479 adjacentTriangleCount++;
1480 }
1481 }
1482 *out << Verbose(3) << "end." << endl;
1483 }
1484 // Only one of the triangle lines must be considered for the triangle count.
1485 //*out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1486 //return adjacentTriangleCount;
1487 }
1488 }
1489 }
1490 }
1491
1492 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1493 *out << Verbose(2) << "End of CheckPresenceOfTriangle" << endl;
1494 return adjacentTriangleCount;
1495};
1496
1497/** Checks whether the triangle consisting of the three points is already present.
1498 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1499 * lines. If any of the three edges already has two triangles attached, false is
1500 * returned.
1501 * \param *out output stream for debugging
1502 * \param *Candidates endpoints of the triangle candidate
1503 * \return NULL - none found or pointer to triangle
1504 */
1505class BoundaryTriangleSet * Tesselation::GetPresentTriangle(ofstream *out, TesselPoint *Candidates[3])
1506{
1507 class BoundaryTriangleSet *triangle = NULL;
1508 class BoundaryPointSet *Points[3];
1509
1510 // builds a triangle point set (Points) of the end points
1511 for (int i = 0; i < 3; i++) {
1512 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1513 if (FindPoint != PointsOnBoundary.end()) {
1514 Points[i] = FindPoint->second;
1515 } else {
1516 Points[i] = NULL;
1517 }
1518 }
1519
1520 // checks lines between the points in the Points for their adjacent triangles
1521 for (int i = 0; i < 3; i++) {
1522 if (Points[i] != NULL) {
1523 for (int j = i; j < 3; j++) {
1524 if (Points[j] != NULL) {
1525 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1526 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1527 TriangleMap *triangles = &FindLine->second->triangles;
1528 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1529 if (FindTriangle->second->IsPresentTupel(Points)) {
1530 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
1531 triangle = FindTriangle->second;
1532 }
1533 }
1534 }
1535 // Only one of the triangle lines must be considered for the triangle count.
1536 //*out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1537 //return adjacentTriangleCount;
1538 }
1539 }
1540 }
1541 }
1542
1543 return triangle;
1544};
1545
1546
1547/** Finds the starting triangle for FindNonConvexBorder().
1548 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
1549 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
1550 * point are called.
1551 * \param *out output stream for debugging
1552 * \param RADIUS radius of virtual rolling sphere
1553 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1554 */
1555void Tesselation::FindStartingTriangle(ofstream *out, const double RADIUS, LinkedCell *LC)
1556{
1557 cout << Verbose(1) << "Begin of FindStartingTriangle\n";
1558 int i = 0;
1559 LinkedNodes *List = NULL;
1560 TesselPoint* FirstPoint = NULL;
1561 TesselPoint* SecondPoint = NULL;
1562 TesselPoint* MaxPoint[NDIM];
1563 double maxCoordinate[NDIM];
1564 Vector Oben;
1565 Vector helper;
1566 Vector Chord;
1567 Vector SearchDirection;
1568
1569 Oben.Zero();
1570
1571 for (i = 0; i < 3; i++) {
1572 MaxPoint[i] = NULL;
1573 maxCoordinate[i] = -1;
1574 }
1575
1576 // 1. searching topmost point with respect to each axis
1577 for (int i=0;i<NDIM;i++) { // each axis
1578 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1579 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1580 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1581 List = LC->GetCurrentCell();
1582 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1583 if (List != NULL) {
1584 for (LinkedNodes::iterator Runner = List->begin();Runner != List->end();Runner++) {
1585 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
1586 cout << Verbose(2) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1587 maxCoordinate[i] = (*Runner)->node->x[i];
1588 MaxPoint[i] = (*Runner);
1589 }
1590 }
1591 } else {
1592 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1593 }
1594 }
1595 }
1596
1597 cout << Verbose(2) << "Found maximum coordinates: ";
1598 for (int i=0;i<NDIM;i++)
1599 cout << i << ": " << *MaxPoint[i] << "\t";
1600 cout << endl;
1601
1602 BTS = NULL;
1603 CandidateList *OptCandidates = new CandidateList();
1604 for (int k=0;k<NDIM;k++) {
1605 Oben.Zero();
1606 Oben.x[k] = 1.;
1607 FirstPoint = MaxPoint[k];
1608 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1609
1610 double ShortestAngle;
1611 TesselPoint* OptCandidate = NULL;
1612 ShortestAngle = 999999.; // This will contain the angle, which will be always positive (when looking for second point), when looking for third point this will be the quadrant.
1613
1614 FindSecondPointForTesselation(FirstPoint, Oben, OptCandidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1615 SecondPoint = OptCandidate;
1616 if (SecondPoint == NULL) // have we found a second point?
1617 continue;
1618
1619 helper.CopyVector(FirstPoint->node);
1620 helper.SubtractVector(SecondPoint->node);
1621 helper.Normalize();
1622 Oben.ProjectOntoPlane(&helper);
1623 Oben.Normalize();
1624 helper.VectorProduct(&Oben);
1625 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1626
1627 Chord.CopyVector(FirstPoint->node); // bring into calling function
1628 Chord.SubtractVector(SecondPoint->node);
1629 double radius = Chord.ScalarProduct(&Chord);
1630 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1631 helper.CopyVector(&Oben);
1632 helper.Scale(CircleRadius);
1633 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
1634
1635 // look in one direction of baseline for initial candidate
1636 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
1637
1638 // adding point 1 and point 2 and add the line between them
1639 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1640 AddTesselationPoint(FirstPoint, 0);
1641 cout << Verbose(1) << "Found second point is at " << *SecondPoint->node << ".\n";
1642 AddTesselationPoint(SecondPoint, 1);
1643 AddTesselationLine(TPS[0], TPS[1], 0);
1644
1645 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
1646 FindThirdPointForTesselation(
1647 Oben, SearchDirection, helper, BLS[0], NULL, *&OptCandidates, &ShortestAngle, RADIUS, LC
1648 );
1649 cout << Verbose(1) << "List of third Points is ";
1650 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1651 cout << " " << *(*it)->point;
1652 }
1653 cout << endl;
1654
1655 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1656 // add third triangle point
1657 AddTesselationPoint((*it)->point, 2);
1658 // add the second and third line
1659 AddTesselationLine(TPS[1], TPS[2], 1);
1660 AddTesselationLine(TPS[0], TPS[2], 2);
1661 // ... and triangles to the Maps of the Tesselation class
1662 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1663 AddTesselationTriangle();
1664 // ... and calculate its normal vector (with correct orientation)
1665 (*it)->OptCenter.Scale(-1.);
1666 cout << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
1667 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
1668 cout << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
1669 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
1670
1671 // if we do not reach the end with the next step of iteration, we need to setup a new first line
1672 if (it != OptCandidates->end()--) {
1673 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
1674 SecondPoint = (*it)->point;
1675 // adding point 1 and point 2 and the line between them
1676 AddTesselationPoint(FirstPoint, 0);
1677 AddTesselationPoint(SecondPoint, 1);
1678 AddTesselationLine(TPS[0], TPS[1], 0);
1679 }
1680 cout << Verbose(2) << "Projection is " << BTS->NormalVector.ScalarProduct(&Oben) << "." << endl;
1681 }
1682 if (BTS != NULL) // we have created one starting triangle
1683 break;
1684 else {
1685 // remove all candidates from the list and then the list itself
1686 class CandidateForTesselation *remover = NULL;
1687 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1688 remover = *it;
1689 delete(remover);
1690 }
1691 OptCandidates->clear();
1692 }
1693 }
1694
1695 // remove all candidates from the list and then the list itself
1696 class CandidateForTesselation *remover = NULL;
1697 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1698 remover = *it;
1699 delete(remover);
1700 }
1701 delete(OptCandidates);
1702 cout << Verbose(1) << "End of FindStartingTriangle\n";
1703};
1704
1705
1706/** This function finds a triangle to a line, adjacent to an existing one.
1707 * @param out output stream for debugging
1708 * @param Line current baseline to search from
1709 * @param T current triangle which \a Line is edge of
1710 * @param RADIUS radius of the rolling ball
1711 * @param N number of found triangles
1712 * @param *LC LinkedCell structure with neighbouring points
1713 */
1714bool Tesselation::FindNextSuitableTriangle(ofstream *out, BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, LinkedCell *LC)
1715{
1716 cout << Verbose(0) << "Begin of FindNextSuitableTriangle\n";
1717 bool result = true;
1718 CandidateList *OptCandidates = new CandidateList();
1719
1720 Vector CircleCenter;
1721 Vector CirclePlaneNormal;
1722 Vector OldSphereCenter;
1723 Vector SearchDirection;
1724 Vector helper;
1725 TesselPoint *ThirdNode = NULL;
1726 LineMap::iterator testline;
1727 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1728 double radius, CircleRadius;
1729
1730 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
1731 for (int i=0;i<3;i++)
1732 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
1733 ThirdNode = T.endpoints[i]->node;
1734
1735 // construct center of circle
1736 CircleCenter.CopyVector(Line.endpoints[0]->node->node);
1737 CircleCenter.AddVector(Line.endpoints[1]->node->node);
1738 CircleCenter.Scale(0.5);
1739
1740 // construct normal vector of circle
1741 CirclePlaneNormal.CopyVector(Line.endpoints[0]->node->node);
1742 CirclePlaneNormal.SubtractVector(Line.endpoints[1]->node->node);
1743
1744 // calculate squared radius of circle
1745 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1746 if (radius/4. < RADIUS*RADIUS) {
1747 CircleRadius = RADIUS*RADIUS - radius/4.;
1748 CirclePlaneNormal.Normalize();
1749 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1750
1751 // construct old center
1752 GetCenterofCircumcircle(&OldSphereCenter, T.endpoints[0]->node->node, T.endpoints[1]->node->node, T.endpoints[2]->node->node);
1753 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
1754 radius = Line.endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
1755 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1756 OldSphereCenter.AddVector(&helper);
1757 OldSphereCenter.SubtractVector(&CircleCenter);
1758 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
1759
1760 // construct SearchDirection
1761 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
1762 helper.CopyVector(Line.endpoints[0]->node->node);
1763 helper.SubtractVector(ThirdNode->node);
1764 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
1765 SearchDirection.Scale(-1.);
1766 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
1767 SearchDirection.Normalize();
1768 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1769 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
1770 // rotated the wrong way!
1771 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
1772 }
1773
1774 // add third point
1775 FindThirdPointForTesselation(
1776 T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, OptCandidates,
1777 &ShortestAngle, RADIUS, LC
1778 );
1779
1780 } else {
1781 cout << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
1782 }
1783
1784 if (OptCandidates->begin() == OptCandidates->end()) {
1785 cerr << "WARNING: Could not find a suitable candidate." << endl;
1786 return false;
1787 }
1788 cout << Verbose(1) << "Third Points are ";
1789 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1790 cout << " " << *(*it)->point;
1791 }
1792 cout << endl;
1793
1794 BoundaryLineSet *BaseRay = &Line;
1795 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1796 cout << Verbose(1) << " Third point candidate is " << *(*it)->point
1797 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
1798 cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
1799
1800 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
1801 TesselPoint *PointCandidates[3];
1802 PointCandidates[0] = (*it)->point;
1803 PointCandidates[1] = BaseRay->endpoints[0]->node;
1804 PointCandidates[2] = BaseRay->endpoints[1]->node;
1805 int existentTrianglesCount = CheckPresenceOfTriangle(out, PointCandidates);
1806
1807 BTS = NULL;
1808 // If there is no triangle, add it regularly.
1809 if (existentTrianglesCount == 0) {
1810 AddTesselationPoint((*it)->point, 0);
1811 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1812 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1813
1814 if (CheckLineCriteriaForDegeneratedTriangle(TPS)) {
1815 AddTesselationLine(TPS[0], TPS[1], 0);
1816 AddTesselationLine(TPS[0], TPS[2], 1);
1817 AddTesselationLine(TPS[1], TPS[2], 2);
1818
1819 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1820 AddTesselationTriangle();
1821 (*it)->OptCenter.Scale(-1.);
1822 BTS->GetNormalVector((*it)->OptCenter);
1823 (*it)->OptCenter.Scale(-1.);
1824
1825 cout << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1826 << " for this triangle ... " << endl;
1827 //cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
1828 } else {
1829 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1830 cout << *(*it)->point << ", ";
1831 cout << *BaseRay->endpoints[0]->node << " and ";
1832 cout << *BaseRay->endpoints[1]->node << " ";
1833 cout << "exists and is not added, as it does not seem helpful!" << endl;
1834 result = false;
1835 }
1836 } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
1837 AddTesselationPoint((*it)->point, 0);
1838 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1839 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1840
1841 // We demand that at most one new degenerate line is created and that this line also already exists (which has to be the case due to existentTrianglesCount == 1)
1842 // i.e. at least one of the three lines must be present with TriangleCount <= 1
1843 if (CheckLineCriteriaForDegeneratedTriangle(TPS)) {
1844 AddTesselationLine(TPS[0], TPS[1], 0);
1845 AddTesselationLine(TPS[0], TPS[2], 1);
1846 AddTesselationLine(TPS[1], TPS[2], 2);
1847
1848 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1849 AddTesselationTriangle(); // add to global map
1850
1851 (*it)->OtherOptCenter.Scale(-1.);
1852 BTS->GetNormalVector((*it)->OtherOptCenter);
1853 (*it)->OtherOptCenter.Scale(-1.);
1854
1855 cout << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1856 << " for this triangle ... " << endl;
1857 cout << Verbose(1) << "We have "<< BaseRay->triangles.size() << " for line " << BaseRay << "." << endl;
1858 } else {
1859 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1860 cout << *(*it)->point << ", ";
1861 cout << *BaseRay->endpoints[0]->node << " and ";
1862 cout << *BaseRay->endpoints[1]->node << " ";
1863 cout << "exists and is not added, as it does not seem helpful!" << endl;
1864 result = false;
1865 }
1866 } else {
1867 cout << Verbose(1) << "This triangle consisting of ";
1868 cout << *(*it)->point << ", ";
1869 cout << *BaseRay->endpoints[0]->node << " and ";
1870 cout << *BaseRay->endpoints[1]->node << " ";
1871 cout << "is invalid!" << endl;
1872 result = false;
1873 }
1874
1875 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
1876 BaseRay = BLS[0];
1877 if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
1878 *out << Verbose(1) << "CRITICAL: Triangle " << *BTS << " has zero normal vector!" << endl;
1879 exit(255);
1880 }
1881
1882 }
1883
1884 // remove all candidates from the list and then the list itself
1885 class CandidateForTesselation *remover = NULL;
1886 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1887 remover = *it;
1888 delete(remover);
1889 }
1890 delete(OptCandidates);
1891 cout << Verbose(0) << "End of FindNextSuitableTriangle\n";
1892 return result;
1893};
1894
1895/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
1896 * We look whether the closest point on \a *Base with respect to the other baseline is outside
1897 * of the segment formed by both endpoints (concave) or not (convex).
1898 * \param *out output stream for debugging
1899 * \param *Base line to be flipped
1900 * \return NULL - convex, otherwise endpoint that makes it concave
1901 */
1902class BoundaryPointSet *Tesselation::IsConvexRectangle(ofstream *out, class BoundaryLineSet *Base)
1903{
1904 class BoundaryPointSet *Spot = NULL;
1905 class BoundaryLineSet *OtherBase;
1906 Vector *ClosestPoint;
1907
1908 int m=0;
1909 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1910 for (int j=0;j<3;j++) // all of their endpoints and baselines
1911 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1912 BPS[m++] = runner->second->endpoints[j];
1913 OtherBase = new class BoundaryLineSet(BPS,-1);
1914
1915 *out << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
1916 *out << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
1917
1918 // get the closest point on each line to the other line
1919 ClosestPoint = GetClosestPointBetweenLine(out, Base, OtherBase);
1920
1921 // delete the temporary other base line
1922 delete(OtherBase);
1923
1924 // get the distance vector from Base line to OtherBase line
1925 Vector DistanceToIntersection[2], BaseLine;
1926 double distance[2];
1927 BaseLine.CopyVector(Base->endpoints[1]->node->node);
1928 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
1929 for (int i=0;i<2;i++) {
1930 DistanceToIntersection[i].CopyVector(ClosestPoint);
1931 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
1932 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
1933 }
1934 delete(ClosestPoint);
1935 if ((distance[0] * distance[1]) > 0) { // have same sign?
1936 *out << Verbose(3) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
1937 if (distance[0] < distance[1]) {
1938 Spot = Base->endpoints[0];
1939 } else {
1940 Spot = Base->endpoints[1];
1941 }
1942 return Spot;
1943 } else { // different sign, i.e. we are in between
1944 *out << Verbose(3) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
1945 return NULL;
1946 }
1947
1948};
1949
1950void Tesselation::PrintAllBoundaryPoints(ofstream *out)
1951{
1952 // print all lines
1953 *out << Verbose(1) << "Printing all boundary points for debugging:" << endl;
1954 for (PointMap::iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
1955 *out << Verbose(2) << *(PointRunner->second) << endl;
1956};
1957
1958void Tesselation::PrintAllBoundaryLines(ofstream *out)
1959{
1960 // print all lines
1961 *out << Verbose(1) << "Printing all boundary lines for debugging:" << endl;
1962 for (LineMap::iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
1963 *out << Verbose(2) << *(LineRunner->second) << endl;
1964};
1965
1966void Tesselation::PrintAllBoundaryTriangles(ofstream *out)
1967{
1968 // print all triangles
1969 *out << Verbose(1) << "Printing all boundary triangles for debugging:" << endl;
1970 for (TriangleMap::iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
1971 *out << Verbose(2) << *(TriangleRunner->second) << endl;
1972};
1973
1974/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
1975 * \param *out output stream for debugging
1976 * \param *Base line to be flipped
1977 * \return volume change due to flipping (0 - then no flipped occured)
1978 */
1979double Tesselation::PickFarthestofTwoBaselines(ofstream *out, class BoundaryLineSet *Base)
1980{
1981 class BoundaryLineSet *OtherBase;
1982 Vector *ClosestPoint[2];
1983 double volume;
1984
1985 int m=0;
1986 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1987 for (int j=0;j<3;j++) // all of their endpoints and baselines
1988 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1989 BPS[m++] = runner->second->endpoints[j];
1990 OtherBase = new class BoundaryLineSet(BPS,-1);
1991
1992 *out << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
1993 *out << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
1994
1995 // get the closest point on each line to the other line
1996 ClosestPoint[0] = GetClosestPointBetweenLine(out, Base, OtherBase);
1997 ClosestPoint[1] = GetClosestPointBetweenLine(out, OtherBase, Base);
1998
1999 // get the distance vector from Base line to OtherBase line
2000 Vector Distance;
2001 Distance.CopyVector(ClosestPoint[1]);
2002 Distance.SubtractVector(ClosestPoint[0]);
2003
2004 // calculate volume
2005 volume = CalculateVolumeofGeneralTetraeder(Base->endpoints[1]->node->node, OtherBase->endpoints[0]->node->node, OtherBase->endpoints[1]->node->node, Base->endpoints[0]->node->node);
2006
2007 // delete the temporary other base line and the closest points
2008 delete(ClosestPoint[0]);
2009 delete(ClosestPoint[1]);
2010 delete(OtherBase);
2011
2012 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2013 *out << Verbose(3) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2014 return false;
2015 } else { // check for sign against BaseLineNormal
2016 Vector BaseLineNormal;
2017 BaseLineNormal.Zero();
2018 if (Base->triangles.size() < 2) {
2019 *out << Verbose(2) << "ERROR: Less than two triangles are attached to this baseline!" << endl;
2020 return 0.;
2021 }
2022 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2023 *out << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2024 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2025 }
2026 BaseLineNormal.Scale(1./2.);
2027
2028 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2029 *out << Verbose(2) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2030 // calculate volume summand as a general tetraeder
2031 return volume;
2032 } else { // Base higher than OtherBase -> do nothing
2033 *out << Verbose(2) << "REJECT: Base line is higher: Nothing to do." << endl;
2034 return 0.;
2035 }
2036 }
2037};
2038
2039/** For a given baseline and its two connected triangles, flips the baseline.
2040 * I.e. we create the new baseline between the other two endpoints of these four
2041 * endpoints and reconstruct the two triangles accordingly.
2042 * \param *out output stream for debugging
2043 * \param *Base line to be flipped
2044 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2045 */
2046class BoundaryLineSet * Tesselation::FlipBaseline(ofstream *out, class BoundaryLineSet *Base)
2047{
2048 class BoundaryLineSet *OldLines[4], *NewLine;
2049 class BoundaryPointSet *OldPoints[2];
2050 Vector BaseLineNormal;
2051 int OldTriangleNrs[2], OldBaseLineNr;
2052 int i,m;
2053
2054 *out << Verbose(1) << "Begin of FlipBaseline" << endl;
2055
2056 // calculate NormalVector for later use
2057 BaseLineNormal.Zero();
2058 if (Base->triangles.size() < 2) {
2059 *out << Verbose(2) << "ERROR: Less than two triangles are attached to this baseline!" << endl;
2060 return NULL;
2061 }
2062 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2063 *out << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2064 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2065 }
2066 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2067
2068 // get the two triangles
2069 // gather four endpoints and four lines
2070 for (int j=0;j<4;j++)
2071 OldLines[j] = NULL;
2072 for (int j=0;j<2;j++)
2073 OldPoints[j] = NULL;
2074 i=0;
2075 m=0;
2076 *out << Verbose(3) << "The four old lines are: ";
2077 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2078 for (int j=0;j<3;j++) // all of their endpoints and baselines
2079 if (runner->second->lines[j] != Base) { // pick not the central baseline
2080 OldLines[i++] = runner->second->lines[j];
2081 *out << *runner->second->lines[j] << "\t";
2082 }
2083 *out << endl;
2084 *out << Verbose(3) << "The two old points are: ";
2085 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2086 for (int j=0;j<3;j++) // all of their endpoints and baselines
2087 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2088 OldPoints[m++] = runner->second->endpoints[j];
2089 *out << *runner->second->endpoints[j] << "\t";
2090 }
2091 *out << endl;
2092
2093 // check whether everything is in place to create new lines and triangles
2094 if (i<4) {
2095 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
2096 return NULL;
2097 }
2098 for (int j=0;j<4;j++)
2099 if (OldLines[j] == NULL) {
2100 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
2101 return NULL;
2102 }
2103 for (int j=0;j<2;j++)
2104 if (OldPoints[j] == NULL) {
2105 *out << Verbose(1) << "ERROR: We have not gathered enough endpoints!" << endl;
2106 return NULL;
2107 }
2108
2109 // remove triangles and baseline removes itself
2110 *out << Verbose(3) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2111 OldBaseLineNr = Base->Nr;
2112 m=0;
2113 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2114 *out << Verbose(3) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
2115 OldTriangleNrs[m++] = runner->second->Nr;
2116 RemoveTesselationTriangle(runner->second);
2117 }
2118
2119 // construct new baseline (with same number as old one)
2120 BPS[0] = OldPoints[0];
2121 BPS[1] = OldPoints[1];
2122 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2123 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2124 *out << Verbose(3) << "INFO: Created new baseline " << *NewLine << "." << endl;
2125
2126 // construct new triangles with flipped baseline
2127 i=-1;
2128 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2129 i=2;
2130 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2131 i=3;
2132 if (i!=-1) {
2133 BLS[0] = OldLines[0];
2134 BLS[1] = OldLines[i];
2135 BLS[2] = NewLine;
2136 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2137 BTS->GetNormalVector(BaseLineNormal);
2138 AddTesselationTriangle(OldTriangleNrs[0]);
2139 *out << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2140
2141 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
2142 BLS[1] = OldLines[1];
2143 BLS[2] = NewLine;
2144 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2145 BTS->GetNormalVector(BaseLineNormal);
2146 AddTesselationTriangle(OldTriangleNrs[1]);
2147 *out << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2148 } else {
2149 *out << Verbose(1) << "The four old lines do not connect, something's utterly wrong here!" << endl;
2150 return NULL;
2151 }
2152
2153 *out << Verbose(1) << "End of FlipBaseline" << endl;
2154 return NewLine;
2155};
2156
2157
2158/** Finds the second point of starting triangle.
2159 * \param *a first node
2160 * \param Oben vector indicating the outside
2161 * \param OptCandidate reference to recommended candidate on return
2162 * \param Storage[3] array storing angles and other candidate information
2163 * \param RADIUS radius of virtual sphere
2164 * \param *LC LinkedCell structure with neighbouring points
2165 */
2166void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, LinkedCell *LC)
2167{
2168 cout << Verbose(2) << "Begin of FindSecondPointForTesselation" << endl;
2169 Vector AngleCheck;
2170 class TesselPoint* Candidate = NULL;
2171 double norm = -1., angle;
2172 LinkedNodes *List = NULL;
2173 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2174
2175 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2176 for(int i=0;i<NDIM;i++) // store indices of this cell
2177 N[i] = LC->n[i];
2178 } else {
2179 cerr << "ERROR: Point " << *a << " is not found in cell " << LC->index << "." << endl;
2180 return;
2181 }
2182 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2183 cout << Verbose(3) << "LC Intervals from [";
2184 for (int i=0;i<NDIM;i++) {
2185 cout << " " << N[i] << "<->" << LC->N[i];
2186 }
2187 cout << "] :";
2188 for (int i=0;i<NDIM;i++) {
2189 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2190 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2191 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2192 }
2193 cout << endl;
2194
2195
2196 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2197 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2198 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2199 List = LC->GetCurrentCell();
2200 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2201 if (List != NULL) {
2202 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2203 Candidate = (*Runner);
2204 // check if we only have one unique point yet ...
2205 if (a != Candidate) {
2206 // Calculate center of the circle with radius RADIUS through points a and Candidate
2207 Vector OrthogonalizedOben, aCandidate, Center;
2208 double distance, scaleFactor;
2209
2210 OrthogonalizedOben.CopyVector(&Oben);
2211 aCandidate.CopyVector(a->node);
2212 aCandidate.SubtractVector(Candidate->node);
2213 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
2214 OrthogonalizedOben.Normalize();
2215 distance = 0.5 * aCandidate.Norm();
2216 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2217 OrthogonalizedOben.Scale(scaleFactor);
2218
2219 Center.CopyVector(Candidate->node);
2220 Center.AddVector(a->node);
2221 Center.Scale(0.5);
2222 Center.AddVector(&OrthogonalizedOben);
2223
2224 AngleCheck.CopyVector(&Center);
2225 AngleCheck.SubtractVector(a->node);
2226 norm = aCandidate.Norm();
2227 // second point shall have smallest angle with respect to Oben vector
2228 if (norm < RADIUS*2.) {
2229 angle = AngleCheck.Angle(&Oben);
2230 if (angle < Storage[0]) {
2231 //cout << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2232 cout << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2233 OptCandidate = Candidate;
2234 Storage[0] = angle;
2235 //cout << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2236 } else {
2237 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
2238 }
2239 } else {
2240 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2241 }
2242 } else {
2243 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2244 }
2245 }
2246 } else {
2247 cout << Verbose(3) << "Linked cell list is empty." << endl;
2248 }
2249 }
2250 cout << Verbose(2) << "End of FindSecondPointForTesselation" << endl;
2251};
2252
2253
2254/** This recursive function finds a third point, to form a triangle with two given ones.
2255 * Note that this function is for the starting triangle.
2256 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2257 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2258 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2259 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2260 * us the "null" on this circle, the new center of the candidate point will be some way along this
2261 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2262 * by the normal vector of the base triangle that always points outwards by construction.
2263 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2264 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2265 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2266 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2267 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2268 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2269 * both.
2270 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2271 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2272 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2273 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2274 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2275 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2276 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2277 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2278 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2279 * @param BaseLine BoundaryLineSet with the current base line
2280 * @param ThirdNode third point to avoid in search
2281 * @param candidates list of equally good candidates to return
2282 * @param ShortestAngle the current path length on this circle band for the current OptCandidate
2283 * @param RADIUS radius of sphere
2284 * @param *LC LinkedCell structure with neighbouring points
2285 */
2286void Tesselation::FindThirdPointForTesselation(Vector NormalVector, Vector SearchDirection, Vector OldSphereCenter, class BoundaryLineSet *BaseLine, class TesselPoint *ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, LinkedCell *LC)
2287{
2288 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2289 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2290 Vector SphereCenter;
2291 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2292 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2293 Vector NewNormalVector; // normal vector of the Candidate's triangle
2294 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2295 LinkedNodes *List = NULL;
2296 double CircleRadius; // radius of this circle
2297 double radius;
2298 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2299 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2300 TesselPoint *Candidate = NULL;
2301 CandidateForTesselation *optCandidate = NULL;
2302
2303 cout << Verbose(1) << "Begin of FindThirdPointForTesselation" << endl;
2304
2305 cout << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
2306
2307 // construct center of circle
2308 CircleCenter.CopyVector(BaseLine->endpoints[0]->node->node);
2309 CircleCenter.AddVector(BaseLine->endpoints[1]->node->node);
2310 CircleCenter.Scale(0.5);
2311
2312 // construct normal vector of circle
2313 CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
2314 CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
2315
2316 // calculate squared radius TesselPoint *ThirdNode,f circle
2317 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2318 if (radius/4. < RADIUS*RADIUS) {
2319 CircleRadius = RADIUS*RADIUS - radius/4.;
2320 CirclePlaneNormal.Normalize();
2321 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2322
2323 // test whether old center is on the band's plane
2324 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
2325 cerr << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
2326 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
2327 }
2328 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
2329 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2330 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2331
2332 // check SearchDirection
2333 //cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2334 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2335 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
2336 }
2337
2338 // get cell for the starting point
2339 if (LC->SetIndexToVector(&CircleCenter)) {
2340 for(int i=0;i<NDIM;i++) // store indices of this cell
2341 N[i] = LC->n[i];
2342 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2343 } else {
2344 cerr << "ERROR: Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
2345 return;
2346 }
2347 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2348 //cout << Verbose(2) << "LC Intervals:";
2349 for (int i=0;i<NDIM;i++) {
2350 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2351 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2352 //cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2353 }
2354 //cout << endl;
2355 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2356 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2357 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2358 List = LC->GetCurrentCell();
2359 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2360 if (List != NULL) {
2361 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2362 Candidate = (*Runner);
2363
2364 // check for three unique points
2365 //cout << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->node << "." << endl;
2366 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
2367
2368 // construct both new centers
2369 GetCenterofCircumcircle(&NewSphereCenter, BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node);
2370 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
2371
2372 if ((NewNormalVector.MakeNormalVector(BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node))
2373 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
2374 ) {
2375 helper.CopyVector(&NewNormalVector);
2376 //cout << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2377 radius = BaseLine->endpoints[0]->node->node->DistanceSquared(&NewSphereCenter);
2378 if (radius < RADIUS*RADIUS) {
2379 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2380 //cout << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
2381 NewSphereCenter.AddVector(&helper);
2382 NewSphereCenter.SubtractVector(&CircleCenter);
2383 //cout << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
2384
2385 // OtherNewSphereCenter is created by the same vector just in the other direction
2386 helper.Scale(-1.);
2387 OtherNewSphereCenter.AddVector(&helper);
2388 OtherNewSphereCenter.SubtractVector(&CircleCenter);
2389 //cout << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2390
2391 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2392 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2393 alpha = min(alpha, Otheralpha);
2394 // if there is a better candidate, drop the current list and add the new candidate
2395 // otherwise ignore the new candidate and keep the list
2396 if (*ShortestAngle > (alpha - HULLEPSILON)) {
2397 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
2398 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2399 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
2400 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2401 } else {
2402 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
2403 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
2404 }
2405 // if there is an equal candidate, add it to the list without clearing the list
2406 if ((*ShortestAngle - HULLEPSILON) < alpha) {
2407 candidates->push_back(optCandidate);
2408 cout << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
2409 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2410 } else {
2411 // remove all candidates from the list and then the list itself
2412 class CandidateForTesselation *remover = NULL;
2413 for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
2414 remover = *it;
2415 delete(remover);
2416 }
2417 candidates->clear();
2418 candidates->push_back(optCandidate);
2419 cout << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
2420 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2421 }
2422 *ShortestAngle = alpha;
2423 //cout << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
2424 } else {
2425 if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
2426 //cout << Verbose(2) << "REJECT: Old candidate " << *(optCandidate->point) << " with " << *ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
2427 } else {
2428 //cout << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2429 }
2430 }
2431
2432 } else {
2433 //cout << Verbose(2) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
2434 }
2435 } else {
2436 //cout << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2437 }
2438 } else {
2439 if (ThirdNode != NULL) {
2440 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2441 } else {
2442 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
2443 }
2444 }
2445 }
2446 }
2447 }
2448 } else {
2449 cerr << Verbose(2) << "ERROR: The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2450 }
2451 } else {
2452 if (ThirdNode != NULL)
2453 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2454 else
2455 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
2456 }
2457
2458 //cout << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
2459 if (candidates->size() > 1) {
2460 candidates->unique();
2461 candidates->sort(SortCandidates);
2462 }
2463
2464 cout << Verbose(1) << "End of FindThirdPointForTesselation" << endl;
2465};
2466
2467/** Finds the endpoint two lines are sharing.
2468 * \param *line1 first line
2469 * \param *line2 second line
2470 * \return point which is shared or NULL if none
2471 */
2472class BoundaryPointSet *Tesselation::GetCommonEndpoint(class BoundaryLineSet * line1, class BoundaryLineSet * line2)
2473{
2474 class BoundaryLineSet * lines[2] =
2475 { line1, line2 };
2476 class BoundaryPointSet *node = NULL;
2477 map<int, class BoundaryPointSet *> OrderMap;
2478 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
2479 for (int i = 0; i < 2; i++)
2480 // for both lines
2481 for (int j = 0; j < 2; j++)
2482 { // for both endpoints
2483 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
2484 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
2485 if (!OrderTest.second)
2486 { // if insertion fails, we have common endpoint
2487 node = OrderTest.first->second;
2488 cout << Verbose(5) << "Common endpoint of lines " << *line1
2489 << " and " << *line2 << " is: " << *node << "." << endl;
2490 j = 2;
2491 i = 2;
2492 break;
2493 }
2494 }
2495 return node;
2496};
2497
2498/** Finds the triangle that is closest to a given Vector \a *x.
2499 * \param *out output stream for debugging
2500 * \param *x Vector to look from
2501 * \return list of BoundaryTriangleSet of nearest triangles or NULL in degenerate case.
2502 */
2503list<BoundaryTriangleSet*> * Tesselation::FindClosestTrianglesToPoint(ofstream *out, Vector *x, LinkedCell* LC)
2504{
2505 TesselPoint *trianglePoints[3];
2506 TesselPoint *SecondPoint = NULL;
2507 list<BoundaryTriangleSet*> *triangles = NULL;
2508
2509 if (LinesOnBoundary.empty()) {
2510 *out << Verbose(0) << "Error: There is no tesselation structure to compare the point with, please create one first.";
2511 return NULL;
2512 }
2513
2514 trianglePoints[0] = FindClosestPoint(x, SecondPoint, LC);
2515
2516 // check whether closest point is "too close" :), then it's inside
2517 if (trianglePoints[0] == NULL) {
2518 *out << Verbose(2) << "Is the only point, no one else is closeby." << endl;
2519 return NULL;
2520 }
2521 if (trianglePoints[0]->node->DistanceSquared(x) < MYEPSILON) {
2522 *out << Verbose(3) << "Point is right on a tesselation point, no nearest triangle." << endl;
2523 PointMap::iterator PointRunner = PointsOnBoundary.find(trianglePoints[0]->nr);
2524 triangles = new list<BoundaryTriangleSet*>;
2525 if (PointRunner != PointsOnBoundary.end()) {
2526 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2527 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2528 triangles->push_back(TriangleRunner->second);
2529 triangles->sort();
2530 triangles->unique();
2531 } else {
2532 PointRunner = PointsOnBoundary.find(SecondPoint->nr);
2533 trianglePoints[0] = SecondPoint;
2534 if (PointRunner != PointsOnBoundary.end()) {
2535 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2536 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2537 triangles->push_back(TriangleRunner->second);
2538 triangles->sort();
2539 triangles->unique();
2540 } else {
2541 *out << Verbose(1) << "ERROR: I cannot find a boundary point to the tessel point " << *trianglePoints[0] << "." << endl;
2542 return NULL;
2543 }
2544 }
2545 } else {
2546 list<TesselPoint*> *connectedClosestPoints = GetCircleOfConnectedPoints(out, trianglePoints[0], x);
2547 trianglePoints[1] = connectedClosestPoints->front();
2548 trianglePoints[2] = connectedClosestPoints->back();
2549 for (int i=0;i<3;i++) {
2550 if (trianglePoints[i] == NULL) {
2551 *out << Verbose(1) << "ERROR: IsInnerPoint encounters serious error, point " << i << " not found." << endl;
2552 }
2553 //*out << Verbose(2) << "List of triangle points:" << endl;
2554 //*out << Verbose(3) << *trianglePoints[i] << endl;
2555 }
2556
2557 triangles = FindTriangles(trianglePoints);
2558 *out << Verbose(2) << "List of possible triangles:" << endl;
2559 for(list<BoundaryTriangleSet*>::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
2560 *out << Verbose(3) << **Runner << endl;
2561
2562 delete(connectedClosestPoints);
2563 }
2564
2565 if (triangles->empty()) {
2566 *out << Verbose(0) << "ERROR: There is no nearest triangle. Please check the tesselation structure.";
2567 delete(triangles);
2568 return NULL;
2569 } else
2570 return triangles;
2571};
2572
2573/** Finds closest triangle to a point.
2574 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
2575 * \param *out output stream for debugging
2576 * \param *x Vector to look from
2577 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
2578 */
2579class BoundaryTriangleSet * Tesselation::FindClosestTriangleToPoint(ofstream *out, Vector *x, LinkedCell* LC)
2580{
2581 class BoundaryTriangleSet *result = NULL;
2582 list<BoundaryTriangleSet*> *triangles = FindClosestTrianglesToPoint(out, x, LC);
2583 Vector Center;
2584
2585 if (triangles == NULL)
2586 return NULL;
2587
2588 if (triangles->size() == 1) { // there is no degenerate case
2589 result = triangles->front();
2590 *out << Verbose(2) << "Normal Vector of this triangle is " << result->NormalVector << "." << endl;
2591 } else {
2592 result = triangles->front();
2593 result->GetCenter(&Center);
2594 Center.SubtractVector(x);
2595 *out << Verbose(2) << "Normal Vector of this front side is " << result->NormalVector << "." << endl;
2596 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2597 result = triangles->back();
2598 *out << Verbose(2) << "Normal Vector of this back side is " << result->NormalVector << "." << endl;
2599 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2600 *out << Verbose(1) << "ERROR: Front and back side yield NormalVector in wrong direction!" << endl;
2601 }
2602 }
2603 }
2604 delete(triangles);
2605 return result;
2606};
2607
2608/** Checks whether the provided Vector is within the tesselation structure.
2609 *
2610 * @param point of which to check the position
2611 * @param *LC LinkedCell structure
2612 *
2613 * @return true if the point is inside the tesselation structure, false otherwise
2614 */
2615bool Tesselation::IsInnerPoint(ofstream *out, Vector Point, LinkedCell* LC)
2616{
2617 class BoundaryTriangleSet *result = FindClosestTriangleToPoint(out, &Point, LC);
2618 Vector Center;
2619
2620 if (result == NULL) {// is boundary point or only point in point cloud?
2621 *out << Verbose(1) << Point << " is the only point in vicinity." << endl;
2622 return false;
2623 }
2624
2625 result->GetCenter(&Center);
2626 *out << Verbose(3) << "INFO: Central point of the triangle is " << Center << "." << endl;
2627 Center.SubtractVector(&Point);
2628 *out << Verbose(3) << "INFO: Vector from center to point to test is " << Center << "." << endl;
2629 if (Center.ScalarProduct(&result->NormalVector) > -MYEPSILON) {
2630 *out << Verbose(1) << Point << " is an inner point." << endl;
2631 return true;
2632 } else {
2633 *out << Verbose(1) << Point << " is NOT an inner point." << endl;
2634 return false;
2635 }
2636}
2637
2638/** Checks whether the provided TesselPoint is within the tesselation structure.
2639 *
2640 * @param *Point of which to check the position
2641 * @param *LC Linked Cell structure
2642 *
2643 * @return true if the point is inside the tesselation structure, false otherwise
2644 */
2645bool Tesselation::IsInnerPoint(ofstream *out, TesselPoint *Point, LinkedCell* LC)
2646{
2647 return IsInnerPoint(out, *(Point->node), LC);
2648}
2649
2650/** Gets all points connected to the provided point by triangulation lines.
2651 *
2652 * @param *Point of which get all connected points
2653 *
2654 * @return set of the all points linked to the provided one
2655 */
2656set<TesselPoint*> * Tesselation::GetAllConnectedPoints(ofstream *out, TesselPoint* Point)
2657{
2658 set<TesselPoint*> *connectedPoints = new set<TesselPoint*>;
2659 class BoundaryPointSet *ReferencePoint = NULL;
2660 TesselPoint* current;
2661 bool takePoint = false;
2662
2663 // find the respective boundary point
2664 PointMap::iterator PointRunner = PointsOnBoundary.find(Point->nr);
2665 if (PointRunner != PointsOnBoundary.end()) {
2666 ReferencePoint = PointRunner->second;
2667 } else {
2668 *out << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2669 ReferencePoint = NULL;
2670 }
2671
2672 // little trick so that we look just through lines connect to the BoundaryPoint
2673 // OR fall-back to look through all lines if there is no such BoundaryPoint
2674 LineMap *Lines = &LinesOnBoundary;
2675 if (ReferencePoint != NULL)
2676 Lines = &(ReferencePoint->lines);
2677 LineMap::iterator findLines = Lines->begin();
2678 while (findLines != Lines->end()) {
2679 takePoint = false;
2680
2681 if (findLines->second->endpoints[0]->Nr == Point->nr) {
2682 takePoint = true;
2683 current = findLines->second->endpoints[1]->node;
2684 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
2685 takePoint = true;
2686 current = findLines->second->endpoints[0]->node;
2687 }
2688
2689 if (takePoint) {
2690 *out << Verbose(5) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
2691 connectedPoints->insert(current);
2692 }
2693
2694 findLines++;
2695 }
2696
2697 if (connectedPoints->size() == 0) { // if have not found any points
2698 *out << Verbose(1) << "ERROR: We have not found any connected points to " << *Point<< "." << endl;
2699 return NULL;
2700 }
2701
2702 return connectedPoints;
2703};
2704
2705
2706/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2707 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2708 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2709 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2710 * triangle we are looking for.
2711 *
2712 * @param *out output stream for debugging
2713 * @param *Point of which get all connected points
2714 * @param *Reference Reference vector for zero angle or NULL for no preference
2715 * @return list of the all points linked to the provided one
2716 */
2717list<TesselPoint*> * Tesselation::GetCircleOfConnectedPoints(ofstream *out, TesselPoint* Point, Vector *Reference)
2718{
2719 map<double, TesselPoint*> anglesOfPoints;
2720 set<TesselPoint*> *connectedPoints = GetAllConnectedPoints(out, Point);
2721 list<TesselPoint*> *connectedCircle = new list<TesselPoint*>;
2722 Vector center;
2723 Vector PlaneNormal;
2724 Vector AngleZero;
2725 Vector OrthogonalVector;
2726 Vector helper;
2727
2728 // calculate central point
2729 for (set<TesselPoint*>::iterator TesselRunner = connectedPoints->begin(); TesselRunner != connectedPoints->end(); TesselRunner++)
2730 center.AddVector((*TesselRunner)->node);
2731 //*out << "Summed vectors " << center << "; number of points " << connectedPoints.size()
2732 // << "; scale factor " << 1.0/connectedPoints.size();
2733 center.Scale(1.0/connectedPoints->size());
2734 *out << Verbose(4) << "INFO: Calculated center of all circle points is " << center << "." << endl;
2735
2736 // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
2737 PlaneNormal.CopyVector(Point->node);
2738 PlaneNormal.SubtractVector(&center);
2739 PlaneNormal.Normalize();
2740 *out << Verbose(4) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
2741
2742 // construct one orthogonal vector
2743 if (Reference != NULL)
2744 AngleZero.CopyVector(Reference);
2745 else
2746 AngleZero.CopyVector((*connectedPoints->begin())->node);
2747 AngleZero.SubtractVector(Point->node);
2748 AngleZero.ProjectOntoPlane(&PlaneNormal);
2749 *out << Verbose(4) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
2750 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
2751 *out << Verbose(4) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
2752
2753 // go through all connected points and calculate angle
2754 for (set<TesselPoint*>::iterator listRunner = connectedPoints->begin(); listRunner != connectedPoints->end(); listRunner++) {
2755 helper.CopyVector((*listRunner)->node);
2756 helper.SubtractVector(Point->node);
2757 helper.ProjectOntoPlane(&PlaneNormal);
2758 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
2759 *out << Verbose(3) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
2760 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
2761 }
2762
2763 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
2764 connectedCircle->push_back(AngleRunner->second);
2765 }
2766
2767 delete(connectedPoints);
2768 return connectedCircle;
2769}
2770
2771/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
2772 *
2773 * @param *out output stream for debugging
2774 * @param *Point of which get all connected points
2775 * @return list of the all points linked to the provided one
2776 */
2777list<list<TesselPoint*> *> * Tesselation::GetPathsOfConnectedPoints(ofstream *out, TesselPoint* Point)
2778{
2779 map<double, TesselPoint*> anglesOfPoints;
2780 list<list<TesselPoint*> *> *ListOfPaths = new list<list<TesselPoint*> *>;
2781 list<TesselPoint*> *connectedPath = NULL;
2782 Vector center;
2783 Vector PlaneNormal;
2784 Vector AngleZero;
2785 Vector OrthogonalVector;
2786 Vector helper;
2787 class BoundaryPointSet *ReferencePoint = NULL;
2788 class BoundaryPointSet *CurrentPoint = NULL;
2789 class BoundaryTriangleSet *triangle = NULL;
2790 class BoundaryLineSet *CurrentLine = NULL;
2791 class BoundaryLineSet *StartLine = NULL;
2792
2793 // find the respective boundary point
2794 PointMap::iterator PointRunner = PointsOnBoundary.find(Point->nr);
2795 if (PointRunner != PointsOnBoundary.end()) {
2796 ReferencePoint = PointRunner->second;
2797 } else {
2798 *out << Verbose(2) << "ERROR: GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2799 return NULL;
2800 }
2801
2802 map <class BoundaryLineSet *, bool> TouchedLine;
2803 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
2804 map <class BoundaryLineSet *, bool>::iterator LineRunner;
2805 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
2806 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
2807 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
2808 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
2809 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
2810 }
2811 if (!ReferencePoint->lines.empty()) {
2812 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
2813 LineRunner = TouchedLine.find(runner->second);
2814 if (LineRunner == TouchedLine.end()) {
2815 *out << Verbose(2) << "ERROR: I could not find " << *runner->second << " in the touched list." << endl;
2816 } else if (!LineRunner->second) {
2817 LineRunner->second = true;
2818 connectedPath = new list<TesselPoint*>;
2819 triangle = NULL;
2820 CurrentLine = runner->second;
2821 StartLine = CurrentLine;
2822 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
2823 *out << Verbose(3)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
2824 do {
2825 // push current one
2826 *out << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
2827 connectedPath->push_back(CurrentPoint->node);
2828
2829 // find next triangle
2830 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
2831 *out << Verbose(3) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
2832 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
2833 triangle = Runner->second;
2834 TriangleRunner = TouchedTriangle.find(triangle);
2835 if (TriangleRunner != TouchedTriangle.end()) {
2836 if (!TriangleRunner->second) {
2837 TriangleRunner->second = true;
2838 *out << Verbose(3) << "INFO: Connecting triangle is " << *triangle << "." << endl;
2839 break;
2840 } else {
2841 *out << Verbose(3) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
2842 triangle = NULL;
2843 }
2844 } else {
2845 *out << Verbose(2) << "ERROR: I could not find " << *triangle << " in the touched list." << endl;
2846 triangle = NULL;
2847 }
2848 }
2849 }
2850 if (triangle == NULL)
2851 break;
2852 // find next line
2853 for (int i=0;i<3;i++) {
2854 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
2855 CurrentLine = triangle->lines[i];
2856 *out << Verbose(3) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
2857 break;
2858 }
2859 }
2860 LineRunner = TouchedLine.find(CurrentLine);
2861 if (LineRunner == TouchedLine.end())
2862 *out << Verbose(2) << "ERROR: I could not find " << *CurrentLine << " in the touched list." << endl;
2863 else
2864 LineRunner->second = true;
2865 // find next point
2866 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
2867
2868 } while (CurrentLine != StartLine);
2869 // last point is missing, as it's on start line
2870 *out << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
2871 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
2872 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
2873
2874 ListOfPaths->push_back(connectedPath);
2875 } else {
2876 *out << Verbose(3) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
2877 }
2878 }
2879 } else {
2880 *out << Verbose(1) << "ERROR: There are no lines attached to " << *ReferencePoint << "." << endl;
2881 }
2882
2883 return ListOfPaths;
2884}
2885
2886/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
2887 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
2888 * @param *out output stream for debugging
2889 * @param *Point of which get all connected points
2890 * @return list of the closed paths
2891 */
2892list<list<TesselPoint*> *> * Tesselation::GetClosedPathsOfConnectedPoints(ofstream *out, TesselPoint* Point)
2893{
2894 list<list<TesselPoint*> *> *ListofPaths = GetPathsOfConnectedPoints(out, Point);
2895 list<list<TesselPoint*> *> *ListofClosedPaths = new list<list<TesselPoint*> *>;
2896 list<TesselPoint*> *connectedPath = NULL;
2897 list<TesselPoint*> *newPath = NULL;
2898 int count = 0;
2899
2900
2901 list<TesselPoint*>::iterator CircleRunner;
2902 list<TesselPoint*>::iterator CircleStart;
2903
2904 for(list<list<TesselPoint*> *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
2905 connectedPath = *ListRunner;
2906
2907 *out << Verbose(2) << "INFO: Current path is " << connectedPath << "." << endl;
2908
2909 // go through list, look for reappearance of starting Point and count
2910 CircleStart = connectedPath->begin();
2911
2912 // go through list, look for reappearance of starting Point and create list
2913 list<TesselPoint*>::iterator Marker = CircleStart;
2914 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
2915 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
2916 // we have a closed circle from Marker to new Marker
2917 *out << Verbose(3) << count+1 << ". closed path consists of: ";
2918 newPath = new list<TesselPoint*>;
2919 list<TesselPoint*>::iterator CircleSprinter = Marker;
2920 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
2921 newPath->push_back(*CircleSprinter);
2922 *out << (**CircleSprinter) << " <-> ";
2923 }
2924 *out << ".." << endl;
2925 count++;
2926 Marker = CircleRunner;
2927
2928 // add to list
2929 ListofClosedPaths->push_back(newPath);
2930 }
2931 }
2932 }
2933 *out << Verbose(3) << "INFO: " << count << " closed additional path(s) have been created." << endl;
2934
2935 // delete list of paths
2936 while (!ListofPaths->empty()) {
2937 connectedPath = *(ListofPaths->begin());
2938 ListofPaths->remove(connectedPath);
2939 delete(connectedPath);
2940 }
2941 delete(ListofPaths);
2942
2943 // exit
2944 return ListofClosedPaths;
2945};
2946
2947
2948/** Gets all belonging triangles for a given BoundaryPointSet.
2949 * \param *out output stream for debugging
2950 * \param *Point BoundaryPoint
2951 * \return pointer to allocated list of triangles
2952 */
2953set<BoundaryTriangleSet*> *Tesselation::GetAllTriangles(ofstream *out, class BoundaryPointSet *Point)
2954{
2955 set<BoundaryTriangleSet*> *connectedTriangles = new set<BoundaryTriangleSet*>;
2956
2957 if (Point == NULL) {
2958 *out << Verbose(1) << "ERROR: Point given is NULL." << endl;
2959 } else {
2960 // go through its lines and insert all triangles
2961 for (LineMap::iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
2962 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
2963 connectedTriangles->insert(TriangleRunner->second);
2964 }
2965 }
2966
2967 return connectedTriangles;
2968};
2969
2970
2971/** Removes a boundary point from the envelope while keeping it closed.
2972 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
2973 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
2974 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
2975 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
2976 * -# the surface is closed, when the path is empty
2977 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
2978 * \param *out output stream for debugging
2979 * \param *point point to be removed
2980 * \return volume added to the volume inside the tesselated surface by the removal
2981 */
2982double Tesselation::RemovePointFromTesselatedSurface(ofstream *out, class BoundaryPointSet *point) {
2983 class BoundaryLineSet *line = NULL;
2984 class BoundaryTriangleSet *triangle = NULL;
2985 Vector OldPoint, NormalVector;
2986 double volume = 0;
2987 int count = 0;
2988
2989 if (point == NULL) {
2990 *out << Verbose(1) << "ERROR: Cannot remove the point " << point << ", it's NULL!" << endl;
2991 return 0.;
2992 } else
2993 *out << Verbose(2) << "Removing point " << *point << " from tesselated boundary ..." << endl;
2994
2995 // copy old location for the volume
2996 OldPoint.CopyVector(point->node->node);
2997
2998 // get list of connected points
2999 if (point->lines.empty()) {
3000 *out << Verbose(1) << "ERROR: Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
3001 return 0.;
3002 }
3003
3004 list<list<TesselPoint*> *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(out, point->node);
3005 list<TesselPoint*> *connectedPath = NULL;
3006
3007 // gather all triangles
3008 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3009 count+=LineRunner->second->triangles.size();
3010 map<class BoundaryTriangleSet *, int> Candidates;
3011 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3012 line = LineRunner->second;
3013 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3014 triangle = TriangleRunner->second;
3015 Candidates.insert( pair<class BoundaryTriangleSet *, int> (triangle, triangle->Nr) );
3016 }
3017 }
3018
3019 // remove all triangles
3020 count=0;
3021 NormalVector.Zero();
3022 for (map<class BoundaryTriangleSet *, int>::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3023 *out << Verbose(3) << "INFO: Removing triangle " << *(Runner->first) << "." << endl;
3024 NormalVector.SubtractVector(&Runner->first->NormalVector); // has to point inward
3025 RemoveTesselationTriangle(Runner->first);
3026 count++;
3027 }
3028 *out << Verbose(1) << count << " triangles were removed." << endl;
3029
3030 list<list<TesselPoint*> *>::iterator ListAdvance = ListOfClosedPaths->begin();
3031 list<list<TesselPoint*> *>::iterator ListRunner = ListAdvance;
3032 map<class BoundaryTriangleSet *, int>::iterator NumberRunner = Candidates.begin();
3033 list<TesselPoint*>::iterator StartNode, MiddleNode, EndNode;
3034 double angle;
3035 double smallestangle;
3036 Vector Point, Reference, OrthogonalVector;
3037 if (count > 2) { // less than three triangles, then nothing will be created
3038 class TesselPoint *TriangleCandidates[3];
3039 count = 0;
3040 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3041 if (ListAdvance != ListOfClosedPaths->end())
3042 ListAdvance++;
3043
3044 connectedPath = *ListRunner;
3045
3046 // re-create all triangles by going through connected points list
3047 list<class BoundaryLineSet *> NewLines;
3048 for (;!connectedPath->empty();) {
3049 // search middle node with widest angle to next neighbours
3050 EndNode = connectedPath->end();
3051 smallestangle = 0.;
3052 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3053 cout << Verbose(3) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3054 // construct vectors to next and previous neighbour
3055 StartNode = MiddleNode;
3056 if (StartNode == connectedPath->begin())
3057 StartNode = connectedPath->end();
3058 StartNode--;
3059 //cout << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
3060 Point.CopyVector((*StartNode)->node);
3061 Point.SubtractVector((*MiddleNode)->node);
3062 StartNode = MiddleNode;
3063 StartNode++;
3064 if (StartNode == connectedPath->end())
3065 StartNode = connectedPath->begin();
3066 //cout << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
3067 Reference.CopyVector((*StartNode)->node);
3068 Reference.SubtractVector((*MiddleNode)->node);
3069 OrthogonalVector.CopyVector((*MiddleNode)->node);
3070 OrthogonalVector.SubtractVector(&OldPoint);
3071 OrthogonalVector.MakeNormalVector(&Reference);
3072 angle = GetAngle(Point, Reference, OrthogonalVector);
3073 //if (angle < M_PI) // no wrong-sided triangles, please?
3074 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3075 smallestangle = angle;
3076 EndNode = MiddleNode;
3077 }
3078 }
3079 MiddleNode = EndNode;
3080 if (MiddleNode == connectedPath->end()) {
3081 cout << Verbose(1) << "CRITICAL: Could not find a smallest angle!" << endl;
3082 exit(255);
3083 }
3084 StartNode = MiddleNode;
3085 if (StartNode == connectedPath->begin())
3086 StartNode = connectedPath->end();
3087 StartNode--;
3088 EndNode++;
3089 if (EndNode == connectedPath->end())
3090 EndNode = connectedPath->begin();
3091 cout << Verbose(4) << "INFO: StartNode is " << **StartNode << "." << endl;
3092 cout << Verbose(4) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3093 cout << Verbose(4) << "INFO: EndNode is " << **EndNode << "." << endl;
3094 *out << Verbose(3) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
3095 TriangleCandidates[0] = *StartNode;
3096 TriangleCandidates[1] = *MiddleNode;
3097 TriangleCandidates[2] = *EndNode;
3098 triangle = GetPresentTriangle(out, TriangleCandidates);
3099 if (triangle != NULL) {
3100 cout << Verbose(1) << "WARNING: New triangle already present, skipping!" << endl;
3101 StartNode++;
3102 MiddleNode++;
3103 EndNode++;
3104 if (StartNode == connectedPath->end())
3105 StartNode = connectedPath->begin();
3106 if (MiddleNode == connectedPath->end())
3107 MiddleNode = connectedPath->begin();
3108 if (EndNode == connectedPath->end())
3109 EndNode = connectedPath->begin();
3110 continue;
3111 }
3112 *out << Verbose(5) << "Adding new triangle points."<< endl;
3113 AddTesselationPoint(*StartNode, 0);
3114 AddTesselationPoint(*MiddleNode, 1);
3115 AddTesselationPoint(*EndNode, 2);
3116 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3117 AddTesselationLine(TPS[0], TPS[1], 0);
3118 AddTesselationLine(TPS[0], TPS[2], 1);
3119 NewLines.push_back(BLS[1]);
3120 AddTesselationLine(TPS[1], TPS[2], 2);
3121 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3122 BTS->GetNormalVector(NormalVector);
3123 AddTesselationTriangle();
3124 // calculate volume summand as a general tetraeder
3125 volume += CalculateVolumeofGeneralTetraeder(TPS[0]->node->node, TPS[1]->node->node, TPS[2]->node->node, &OldPoint);
3126 // advance number
3127 count++;
3128
3129 // prepare nodes for next triangle
3130 StartNode = EndNode;
3131 cout << Verbose(4) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
3132 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3133 if (connectedPath->size() == 2) { // we are done
3134 connectedPath->remove(*StartNode); // remove the start node
3135 connectedPath->remove(*EndNode); // remove the end node
3136 break;
3137 } else if (connectedPath->size() < 2) { // something's gone wrong!
3138 cout << Verbose(1) << "CRITICAL: There are only two endpoints left!" << endl;
3139 exit(255);
3140 } else {
3141 MiddleNode = StartNode;
3142 MiddleNode++;
3143 if (MiddleNode == connectedPath->end())
3144 MiddleNode = connectedPath->begin();
3145 EndNode = MiddleNode;
3146 EndNode++;
3147 if (EndNode == connectedPath->end())
3148 EndNode = connectedPath->begin();
3149 }
3150 }
3151 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
3152 if (NewLines.size() > 1) {
3153 list<class BoundaryLineSet *>::iterator Candidate;
3154 class BoundaryLineSet *OtherBase = NULL;
3155 double tmp, maxgain;
3156 do {
3157 maxgain = 0;
3158 for(list<class BoundaryLineSet *>::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
3159 tmp = PickFarthestofTwoBaselines(out, *Runner);
3160 if (maxgain < tmp) {
3161 maxgain = tmp;
3162 Candidate = Runner;
3163 }
3164 }
3165 if (maxgain != 0) {
3166 volume += maxgain;
3167 cout << Verbose(3) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
3168 OtherBase = FlipBaseline(out, *Candidate);
3169 NewLines.erase(Candidate);
3170 NewLines.push_back(OtherBase);
3171 }
3172 } while (maxgain != 0.);
3173 }
3174
3175 ListOfClosedPaths->remove(connectedPath);
3176 delete(connectedPath);
3177 }
3178 *out << Verbose(1) << count << " triangles were created." << endl;
3179 } else {
3180 while (!ListOfClosedPaths->empty()) {
3181 ListRunner = ListOfClosedPaths->begin();
3182 connectedPath = *ListRunner;
3183 ListOfClosedPaths->remove(connectedPath);
3184 delete(connectedPath);
3185 }
3186 *out << Verbose(1) << "No need to create any triangles." << endl;
3187 }
3188 delete(ListOfClosedPaths);
3189
3190 *out << Verbose(1) << "Removed volume is " << volume << "." << endl;
3191
3192 return volume;
3193};
3194
3195
3196
3197/**
3198 * Finds triangles belonging to the three provided points.
3199 *
3200 * @param *Points[3] list, is expected to contain three points
3201 *
3202 * @return triangles which belong to the provided points, will be empty if there are none,
3203 * will usually be one, in case of degeneration, there will be two
3204 */
3205list<BoundaryTriangleSet*> *Tesselation::FindTriangles(TesselPoint* Points[3])
3206{
3207 list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
3208 LineMap::iterator FindLine;
3209 PointMap::iterator FindPoint;
3210 TriangleMap::iterator FindTriangle;
3211 class BoundaryPointSet *TrianglePoints[3];
3212
3213 for (int i = 0; i < 3; i++) {
3214 FindPoint = PointsOnBoundary.find(Points[i]->nr);
3215 if (FindPoint != PointsOnBoundary.end()) {
3216 TrianglePoints[i] = FindPoint->second;
3217 } else {
3218 TrianglePoints[i] = NULL;
3219 }
3220 }
3221
3222 // checks lines between the points in the Points for their adjacent triangles
3223 for (int i = 0; i < 3; i++) {
3224 if (TrianglePoints[i] != NULL) {
3225 for (int j = i; j < 3; j++) {
3226 if (TrianglePoints[j] != NULL) {
3227 FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr);
3228 if (FindLine != TrianglePoints[i]->lines.end()) {
3229 for (; FindLine->first == TrianglePoints[j]->node->nr; FindLine++) {
3230 FindTriangle = FindLine->second->triangles.begin();
3231 for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
3232 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3233 result->push_back(FindTriangle->second);
3234 }
3235 }
3236 }
3237 // Is it sufficient to consider one of the triangle lines for this.
3238 return result;
3239
3240 }
3241 }
3242 }
3243 }
3244 }
3245
3246 return result;
3247}
3248
3249/**
3250 * Finds all degenerated lines within the tesselation structure.
3251 *
3252 * @return map of keys of degenerated line pairs, each line occurs twice
3253 * in the list, once as key and once as value
3254 */
3255map<int, int> * Tesselation::FindAllDegeneratedLines()
3256{
3257 map<int, class BoundaryLineSet *> AllLines;
3258 map<int, int> * DegeneratedLines = new map<int, int>;
3259
3260 // sanity check
3261 if (LinesOnBoundary.empty()) {
3262 cout << Verbose(1) << "Warning: FindAllDegeneratedTriangles() was called without any tesselation structure.";
3263 return DegeneratedLines;
3264 }
3265
3266 LineMap::iterator LineRunner1;
3267 pair<LineMap::iterator, bool> tester;
3268 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
3269 tester = AllLines.insert( pair<int,BoundaryLineSet *> (LineRunner1->second->endpoints[0]->Nr, LineRunner1->second) );
3270 if ((!tester.second) && (tester.first->second->endpoints[1]->Nr == LineRunner1->second->endpoints[1]->Nr)) { // found degenerated line
3271 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, tester.first->second->Nr) );
3272 DegeneratedLines->insert ( pair<int, int> (tester.first->second->Nr, LineRunner1->second->Nr) );
3273 }
3274 }
3275
3276 AllLines.clear();
3277
3278 cout << Verbose(1) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
3279 map<int,int>::iterator it;
3280 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++)
3281 cout << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3282
3283 return DegeneratedLines;
3284}
3285
3286/**
3287 * Finds all degenerated triangles within the tesselation structure.
3288 *
3289 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
3290 * in the list, once as key and once as value
3291 */
3292map<int, int> * Tesselation::FindAllDegeneratedTriangles()
3293{
3294 map<int, int> * DegeneratedLines = FindAllDegeneratedLines();
3295 map<int, int> * DegeneratedTriangles = new map<int, int>;
3296
3297 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
3298 LineMap::iterator Liner;
3299 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
3300
3301 for (map<int, int>::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
3302 // run over both lines' triangles
3303 Liner = LinesOnBoundary.find(LineRunner->first);
3304 if (Liner != LinesOnBoundary.end())
3305 line1 = Liner->second;
3306 Liner = LinesOnBoundary.find(LineRunner->second);
3307 if (Liner != LinesOnBoundary.end())
3308 line2 = Liner->second;
3309 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
3310 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
3311 if ((TriangleRunner1->second != TriangleRunner2->second)
3312 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
3313 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
3314 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
3315 }
3316 }
3317 }
3318 }
3319 delete(DegeneratedLines);
3320
3321 cout << Verbose(1) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
3322 map<int,int>::iterator it;
3323 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
3324 cout << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3325
3326 return DegeneratedTriangles;
3327}
3328
3329/**
3330 * Purges degenerated triangles from the tesselation structure if they are not
3331 * necessary to keep a single point within the structure.
3332 */
3333void Tesselation::RemoveDegeneratedTriangles()
3334{
3335 map<int, int> * DegeneratedTriangles = FindAllDegeneratedTriangles();
3336 TriangleMap::iterator finder;
3337 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
3338 int count = 0;
3339
3340 cout << Verbose(1) << "Begin of RemoveDegeneratedTriangles" << endl;
3341
3342 for (map<int, int>::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
3343 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
3344 ) {
3345 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
3346 if (finder != TrianglesOnBoundary.end())
3347 triangle = finder->second;
3348 else
3349 break;
3350 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
3351 if (finder != TrianglesOnBoundary.end())
3352 partnerTriangle = finder->second;
3353 else
3354 break;
3355
3356 bool trianglesShareLine = false;
3357 for (int i = 0; i < 3; ++i)
3358 for (int j = 0; j < 3; ++j)
3359 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
3360
3361 if (trianglesShareLine
3362 && (triangle->endpoints[1]->LinesCount > 2)
3363 && (triangle->endpoints[2]->LinesCount > 2)
3364 && (triangle->endpoints[0]->LinesCount > 2)
3365 ) {
3366 // check whether we have to fix lines
3367 BoundaryTriangleSet *Othertriangle = NULL;
3368 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
3369 TriangleMap::iterator TriangleRunner;
3370 for (int i = 0; i < 3; ++i)
3371 for (int j = 0; j < 3; ++j)
3372 if (triangle->lines[i] != partnerTriangle->lines[j]) {
3373 // get the other two triangles
3374 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
3375 if (TriangleRunner->second != triangle) {
3376 Othertriangle = TriangleRunner->second;
3377 }
3378 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
3379 if (TriangleRunner->second != partnerTriangle) {
3380 OtherpartnerTriangle = TriangleRunner->second;
3381 }
3382 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
3383 // the line of triangle receives the degenerated ones
3384 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
3385 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
3386 for (int k=0;k<3;k++)
3387 if (triangle->lines[i] == Othertriangle->lines[k]) {
3388 Othertriangle->lines[k] = partnerTriangle->lines[j];
3389 break;
3390 }
3391 // the line of partnerTriangle receives the non-degenerated ones
3392 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
3393 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
3394 partnerTriangle->lines[j] = triangle->lines[i];
3395 }
3396
3397 // erase the pair
3398 count += (int) DegeneratedTriangles->erase(triangle->Nr);
3399 cout << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
3400 RemoveTesselationTriangle(triangle);
3401 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
3402 cout << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
3403 RemoveTesselationTriangle(partnerTriangle);
3404 } else {
3405 cout << Verbose(1) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
3406 << " and its partner " << *partnerTriangle << " because it is essential for at"
3407 << " least one of the endpoints to be kept in the tesselation structure." << endl;
3408 }
3409 }
3410 delete(DegeneratedTriangles);
3411
3412 cout << Verbose(1) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
3413 cout << Verbose(1) << "End of RemoveDegeneratedTriangles" << endl;
3414}
3415
3416/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
3417 * We look for the closest point on the boundary, we look through its connected boundary lines and
3418 * seek the one with the minimum angle between its center point and the new point and this base line.
3419 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
3420 * \param *out output stream for debugging
3421 * \param *point point to add
3422 * \param *LC Linked Cell structure to find nearest point
3423 */
3424void Tesselation::AddBoundaryPointByDegeneratedTriangle(ofstream *out, class TesselPoint *point, LinkedCell *LC)
3425{
3426 *out << Verbose(2) << "Begin of AddBoundaryPointByDegeneratedTriangle" << endl;
3427
3428 // find nearest boundary point
3429 class TesselPoint *BackupPoint = NULL;
3430 class TesselPoint *NearestPoint = FindClosestPoint(point->node, BackupPoint, LC);
3431 class BoundaryPointSet *NearestBoundaryPoint = NULL;
3432 PointMap::iterator PointRunner;
3433
3434 if (NearestPoint == point)
3435 NearestPoint = BackupPoint;
3436 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
3437 if (PointRunner != PointsOnBoundary.end()) {
3438 NearestBoundaryPoint = PointRunner->second;
3439 } else {
3440 *out << Verbose(1) << "ERROR: I cannot find the boundary point." << endl;
3441 return;
3442 }
3443 *out << Verbose(2) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
3444
3445 // go through its lines and find the best one to split
3446 Vector CenterToPoint;
3447 Vector BaseLine;
3448 double angle, BestAngle = 0.;
3449 class BoundaryLineSet *BestLine = NULL;
3450 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
3451 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
3452 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
3453 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
3454 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
3455 CenterToPoint.Scale(0.5);
3456 CenterToPoint.SubtractVector(point->node);
3457 angle = CenterToPoint.Angle(&BaseLine);
3458 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
3459 BestAngle = angle;
3460 BestLine = Runner->second;
3461 }
3462 }
3463
3464 // remove one triangle from the chosen line
3465 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
3466 BestLine->triangles.erase(TempTriangle->Nr);
3467 int nr = -1;
3468 for (int i=0;i<3; i++) {
3469 if (TempTriangle->lines[i] == BestLine) {
3470 nr = i;
3471 break;
3472 }
3473 }
3474
3475 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
3476 *out << Verbose(5) << "Adding new triangle points."<< endl;
3477 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3478 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3479 AddTesselationPoint(point, 2);
3480 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3481 AddTesselationLine(TPS[0], TPS[1], 0);
3482 AddTesselationLine(TPS[0], TPS[2], 1);
3483 AddTesselationLine(TPS[1], TPS[2], 2);
3484 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3485 BTS->GetNormalVector(TempTriangle->NormalVector);
3486 BTS->NormalVector.Scale(-1.);
3487 *out << Verbose(3) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
3488 AddTesselationTriangle();
3489
3490 // create other side of this triangle and close both new sides of the first created triangle
3491 *out << Verbose(5) << "Adding new triangle points."<< endl;
3492 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3493 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3494 AddTesselationPoint(point, 2);
3495 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3496 AddTesselationLine(TPS[0], TPS[1], 0);
3497 AddTesselationLine(TPS[0], TPS[2], 1);
3498 AddTesselationLine(TPS[1], TPS[2], 2);
3499 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3500 BTS->GetNormalVector(TempTriangle->NormalVector);
3501 *out << Verbose(3) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
3502 AddTesselationTriangle();
3503
3504 // add removed triangle to the last open line of the second triangle
3505 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
3506 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
3507 if (BestLine == BTS->lines[i]){
3508 *out << Verbose(1) << "CRITICAL: BestLine is same as found line, something's wrong here!" << endl;
3509 exit(255);
3510 }
3511 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
3512 TempTriangle->lines[nr] = BTS->lines[i];
3513 break;
3514 }
3515 }
3516
3517 // exit
3518 *out << Verbose(2) << "End of AddBoundaryPointByDegeneratedTriangle" << endl;
3519};
3520
3521/** Writes the envelope to file.
3522 * \param *out otuput stream for debugging
3523 * \param *filename basename of output file
3524 * \param *cloud PointCloud structure with all nodes
3525 */
3526void Tesselation::Output(ofstream *out, const char *filename, PointCloud *cloud)
3527{
3528 ofstream *tempstream = NULL;
3529 string NameofTempFile;
3530 char NumberName[255];
3531
3532 if (LastTriangle != NULL) {
3533 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
3534 if (DoTecplotOutput) {
3535 string NameofTempFile(filename);
3536 NameofTempFile.append(NumberName);
3537 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3538 NameofTempFile.erase(npos, 1);
3539 NameofTempFile.append(TecplotSuffix);
3540 *out << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3541 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3542 WriteTecplotFile(out, tempstream, this, cloud, TriangleFilesWritten);
3543 tempstream->close();
3544 tempstream->flush();
3545 delete(tempstream);
3546 }
3547
3548 if (DoRaster3DOutput) {
3549 string NameofTempFile(filename);
3550 NameofTempFile.append(NumberName);
3551 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3552 NameofTempFile.erase(npos, 1);
3553 NameofTempFile.append(Raster3DSuffix);
3554 *out << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3555 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3556 WriteRaster3dFile(out, tempstream, this, cloud);
3557 IncludeSphereinRaster3D(out, tempstream, this, cloud);
3558 tempstream->close();
3559 tempstream->flush();
3560 delete(tempstream);
3561 }
3562 }
3563 if (DoTecplotOutput || DoRaster3DOutput)
3564 TriangleFilesWritten++;
3565};
Note: See TracBrowser for help on using the repository browser.