source: src/tesselation.cpp@ 4455f4

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 4455f4 was 4455f4, checked in by Frederik Heber <heber@…>, 16 years ago

Huge Refactoring: class atom split up into several inherited classes.

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