source: src/tesselation.cpp@ 99593f

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

Extension to the periodic boundary case for analysis_correlation.cpp

other stuff:

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