source: src/tesselation.cpp@ 791138

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

Fixes and naming of final Tecplot output file is now molecule name.

  • FIXES to builder.cpp:
    • case 'p' would not dissect the molecule into connected subgraphs
    • if done so, the BondGraph was not yet initialised
    • if done so, we need to check whether BondGraphFileName has been set
    • BondGraphFileName.empty() could not be used as a check, as was set to "" instead of "\n"
    • if (finally) done so, we have to remove the empty molecule that we parsed in
    • ... and then pick the newly added molecule for mol to point at
    • SaveConfig() did not set the merged molecule name correctly.
    • if empty config is given, the empty molecule now receives the ConfigFileName as name
  • FIXES to config.cpp
    • Load() did not set the name of the molecule
  • changes to tesselationhelper.cpp and tesselation.cpp
  • changes to PointCloud and molecule
    • new virtual function PointCloud::GetName() returns "unknown"
    • new function molecule::GetName() returns pointer to name of molecule
    • IsEmpty() and IsEnd() now return true by default
  • all .dat files in the "Tesselations" tests were changed accordingly (i.e. have now the name in the second line)
  • benzene was added as a new test for an absolutely flat molecule. So far, it fails horribly.
  • 13 of 17 tests run fine

Signed-off-by: Frederik Heber <heber@…>

  • Property mode set to 100644
File size: 164.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 "log.hpp"
13#include "tesselation.hpp"
14#include "tesselationhelpers.hpp"
15#include "vector.hpp"
16#include "verbose.hpp"
17
18class molecule;
19
20// ======================================== Points on Boundary =================================
21
22/** Constructor of BoundaryPointSet.
23 */
24BoundaryPointSet::BoundaryPointSet()
25{
26 LinesCount = 0;
27 Nr = -1;
28 value = 0.;
29};
30
31/** Constructor of BoundaryPointSet with Tesselpoint.
32 * \param *Walker TesselPoint this boundary point represents
33 */
34BoundaryPointSet::BoundaryPointSet(TesselPoint * Walker)
35{
36 node = Walker;
37 LinesCount = 0;
38 Nr = Walker->nr;
39 value = 0.;
40};
41
42/** Destructor of BoundaryPointSet.
43 * Sets node to NULL to avoid removing the original, represented TesselPoint.
44 * \note When removing point from a class Tesselation, use RemoveTesselationPoint()
45 */
46BoundaryPointSet::~BoundaryPointSet()
47{
48 //Log() << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
49 if (!lines.empty())
50 eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some lines." << endl;
51 node = NULL;
52};
53
54/** Add a line to the LineMap of this point.
55 * \param *line line to add
56 */
57void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
58{
59 Log() << Verbose(6) << "Adding " << *this << " to line " << *line << "."
60 << endl;
61 if (line->endpoints[0] == this)
62 {
63 lines.insert(LinePair(line->endpoints[1]->Nr, line));
64 }
65 else
66 {
67 lines.insert(LinePair(line->endpoints[0]->Nr, line));
68 }
69 LinesCount++;
70};
71
72/** output operator for BoundaryPointSet.
73 * \param &ost output stream
74 * \param &a boundary point
75 */
76ostream & operator <<(ostream &ost, const BoundaryPointSet &a)
77{
78 ost << "[" << a.Nr << "|" << a.node->Name << " at " << *a.node->node << "]";
79 return ost;
80}
81;
82
83// ======================================== Lines on Boundary =================================
84
85/** Constructor of BoundaryLineSet.
86 */
87BoundaryLineSet::BoundaryLineSet()
88{
89 for (int i = 0; i < 2; i++)
90 endpoints[i] = NULL;
91 Nr = -1;
92};
93
94/** Constructor of BoundaryLineSet with two endpoints.
95 * Adds line automatically to each endpoints' LineMap
96 * \param *Point[2] array of two boundary points
97 * \param number number of the list
98 */
99BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], const int number)
100{
101 // set number
102 Nr = number;
103 // set endpoints in ascending order
104 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
105 // add this line to the hash maps of both endpoints
106 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
107 Point[1]->AddLine(this); //
108 // clear triangles list
109 Log() << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
110};
111
112/** Destructor for BoundaryLineSet.
113 * Removes itself from each endpoints' LineMap, calling RemoveTrianglePoint() when point not connected anymore.
114 * \note When removing lines from a class Tesselation, use RemoveTesselationLine()
115 */
116BoundaryLineSet::~BoundaryLineSet()
117{
118 int Numbers[2];
119
120 // get other endpoint number of finding copies of same line
121 if (endpoints[1] != NULL)
122 Numbers[0] = endpoints[1]->Nr;
123 else
124 Numbers[0] = -1;
125 if (endpoints[0] != NULL)
126 Numbers[1] = endpoints[0]->Nr;
127 else
128 Numbers[1] = -1;
129
130 for (int i = 0; i < 2; i++) {
131 if (endpoints[i] != NULL) {
132 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
133 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
134 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
135 if ((*Runner).second == this) {
136 //Log() << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
137 endpoints[i]->lines.erase(Runner);
138 break;
139 }
140 } else { // there's just a single line left
141 if (endpoints[i]->lines.erase(Nr)) {
142 //Log() << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
143 }
144 }
145 if (endpoints[i]->lines.empty()) {
146 //Log() << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
147 if (endpoints[i] != NULL) {
148 delete(endpoints[i]);
149 endpoints[i] = NULL;
150 }
151 }
152 }
153 }
154 if (!triangles.empty())
155 eLog() << Verbose(2) << "Memory Leak! I " << *this << " am still connected to some triangles." << endl;
156};
157
158/** Add triangle to TriangleMap of this boundary line.
159 * \param *triangle to add
160 */
161void BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
162{
163 Log() << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "." << endl;
164 triangles.insert(TrianglePair(triangle->Nr, triangle));
165};
166
167/** Checks whether we have a common endpoint with given \a *line.
168 * \param *line other line to test
169 * \return true - common endpoint present, false - not connected
170 */
171bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
172{
173 if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
174 return true;
175 else
176 return false;
177};
178
179/** Checks whether the adjacent triangles of a baseline are convex or not.
180 * We sum the two angles of each height vector with respect to the center of the baseline.
181 * If greater/equal M_PI than we are convex.
182 * \param *out output stream for debugging
183 * \return true - triangles are convex, false - concave or less than two triangles connected
184 */
185bool BoundaryLineSet::CheckConvexityCriterion()
186{
187 Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2], NormalCheck;
188 // get the two triangles
189 if (triangles.size() != 2) {
190 eLog() << Verbose(1) << "Baseline " << *this << " is connected to less than two triangles, Tesselation incomplete!" << endl;
191 return true;
192 }
193 // check normal vectors
194 // have a normal vector on the base line pointing outwards
195 //Log() << Verbose(3) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
196 BaseLineCenter.CopyVector(endpoints[0]->node->node);
197 BaseLineCenter.AddVector(endpoints[1]->node->node);
198 BaseLineCenter.Scale(1./2.);
199 BaseLine.CopyVector(endpoints[0]->node->node);
200 BaseLine.SubtractVector(endpoints[1]->node->node);
201 //Log() << Verbose(3) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
202
203 BaseLineNormal.Zero();
204 NormalCheck.Zero();
205 double sign = -1.;
206 int i=0;
207 class BoundaryPointSet *node = NULL;
208 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
209 //Log() << Verbose(3) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
210 NormalCheck.AddVector(&runner->second->NormalVector);
211 NormalCheck.Scale(sign);
212 sign = -sign;
213 if (runner->second->NormalVector.NormSquared() > MYEPSILON)
214 BaseLineNormal.CopyVector(&runner->second->NormalVector); // yes, copy second on top of first
215 else {
216 Log() << Verbose(1) << "CRITICAL: Triangle " << *runner->second << " has zero normal vector!" << endl;
217 exit(255);
218 }
219 node = runner->second->GetThirdEndpoint(this);
220 if (node != NULL) {
221 //Log() << Verbose(3) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
222 helper[i].CopyVector(node->node->node);
223 helper[i].SubtractVector(&BaseLineCenter);
224 helper[i].MakeNormalVector(&BaseLine); // we want to compare the triangle's heights' angles!
225 //Log() << Verbose(4) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
226 i++;
227 } else {
228 //eLog() << Verbose(1) << "I cannot find third node in triangle, something's wrong." << endl;
229 return true;
230 }
231 }
232 //Log() << Verbose(3) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
233 if (NormalCheck.NormSquared() < MYEPSILON) {
234 Log() << Verbose(3) << "ACCEPT: Normalvectors of both triangles are the same: convex." << endl;
235 return true;
236 }
237 BaseLineNormal.Scale(-1.);
238 double angle = GetAngle(helper[0], helper[1], BaseLineNormal);
239 if ((angle - M_PI) > -MYEPSILON) {
240 Log() << Verbose(3) << "ACCEPT: Angle is greater than pi: convex." << endl;
241 return true;
242 } else {
243 Log() << Verbose(3) << "REJECT: Angle is less than pi: concave." << endl;
244 return false;
245 }
246}
247
248/** Checks whether point is any of the two endpoints this line contains.
249 * \param *point point to test
250 * \return true - point is of the line, false - is not
251 */
252bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
253{
254 for(int i=0;i<2;i++)
255 if (point == endpoints[i])
256 return true;
257 return false;
258};
259
260/** Returns other endpoint of the line.
261 * \param *point other endpoint
262 * \return NULL - if endpoint not contained in BoundaryLineSet, or pointer to BoundaryPointSet otherwise
263 */
264class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(class BoundaryPointSet *point)
265{
266 if (endpoints[0] == point)
267 return endpoints[1];
268 else if (endpoints[1] == point)
269 return endpoints[0];
270 else
271 return NULL;
272};
273
274/** output operator for BoundaryLineSet.
275 * \param &ost output stream
276 * \param &a boundary line
277 */
278ostream & operator <<(ostream &ost, const BoundaryLineSet &a)
279{
280 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 << "]";
281 return ost;
282};
283
284// ======================================== Triangles on Boundary =================================
285
286/** Constructor for BoundaryTriangleSet.
287 */
288BoundaryTriangleSet::BoundaryTriangleSet()
289{
290 for (int i = 0; i < 3; i++)
291 {
292 endpoints[i] = NULL;
293 lines[i] = NULL;
294 }
295 Nr = -1;
296};
297
298/** Constructor for BoundaryTriangleSet with three lines.
299 * \param *line[3] lines that make up the triangle
300 * \param number number of triangle
301 */
302BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
303{
304 // set number
305 Nr = number;
306 // set lines
307 Log() << Verbose(5) << "New triangle " << Nr << ":" << endl;
308 for (int i = 0; i < 3; i++)
309 {
310 lines[i] = line[i];
311 lines[i]->AddTriangle(this);
312 }
313 // get ascending order of endpoints
314 map<int, class BoundaryPointSet *> OrderMap;
315 for (int i = 0; i < 3; i++)
316 // for all three lines
317 for (int j = 0; j < 2; j++)
318 { // for both endpoints
319 OrderMap.insert(pair<int, class BoundaryPointSet *> (
320 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
321 // and we don't care whether insertion fails
322 }
323 // set endpoints
324 int Counter = 0;
325 Log() << Verbose(6) << " with end points ";
326 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
327 != OrderMap.end(); runner++)
328 {
329 endpoints[Counter] = runner->second;
330 Log() << Verbose(0) << " " << *endpoints[Counter];
331 Counter++;
332 }
333 if (Counter < 3)
334 {
335 eLog() << Verbose(0) << "ERROR! We have a triangle with only two distinct endpoints!" << endl;
336 performCriticalExit();
337 }
338 Log() << Verbose(0) << "." << 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 //Log() << Verbose(5) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
351 }
352 if (lines[i]->triangles.empty()) {
353 //Log() << 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 //Log() << 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(Vector *MolCenter, Vector *x, Vector *Intersection)
389{
390 Vector CrossPoint;
391 Vector helper;
392
393 if (!Intersection->GetIntersectionWithPlane(&NormalVector, endpoints[0]->node->node, MolCenter, x)) {
394 Log() << 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(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 eLog() << Verbose(1) << "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 Log() << 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 eLog() << Verbose(1) << "The triangle " << runner->first << " has already been free'd." << endl;
636 }
637 Log() << Verbose(1) << "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()
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 // Log() << Verbose(1) << "Listing DistanceMMap:";
765 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
766 // Log() << Verbose(0) << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
767 // }
768 // Log() << Verbose(0) << 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 Log() << Verbose(2) << "Plane vector of candidate triangle is ";
781 PlaneVector.Output();
782 Log() << Verbose(0) << 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 Log() << 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 Log() << 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 Log() << 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 Log() << Verbose(0) << "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 Log() << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
879 }
880 else
881 {
882 Log() << 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(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();
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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 //Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
1042 } else
1043 Log() << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
1044 } else
1045 Log() << 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 Log() << 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 Log() << 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 Log() << 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(const PointCloud *cloud, const LinkedCell *LC)
1100{
1101 Vector Intersection, Normal;
1102 TesselPoint *Walker = NULL;
1103 Vector *Center = cloud->GetCenter();
1104 list<BoundaryTriangleSet*> *triangles = NULL;
1105 bool AddFlag = false;
1106 LinkedCell *BoundaryPoints = NULL;
1107
1108 Log() << 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 Log() << Verbose(2) << "Current point is " << *Walker << "." << endl;
1120 // get the next triangle
1121 triangles = FindClosestTrianglesToPoint(Walker->node, BoundaryPoints);
1122 BTS = triangles->front();
1123 if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
1124 Log() << Verbose(2) << "No triangles found, probably a tesselation point itself." << endl;
1125 cloud->GoToNext();
1126 continue;
1127 } else {
1128 }
1129 Log() << Verbose(2) << "Closest triangle is " << *BTS << "." << endl;
1130 // get the intersection point
1131 if (BTS->GetIntersectionInsideTriangle(Center, Walker->node, &Intersection)) {
1132 Log() << 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 Log() << Verbose(2) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
1137 } else {
1138 // outside!
1139 Log() << 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 Log() << 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 Log() << 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 Log() << 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 Log() << Verbose(1) << 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 Log() << 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 eLog() << Verbose(1) << "The closest triangle did not produce an intersection!" << endl;
1193 return false;
1194 }
1195 cloud->GoToNext();
1196 }
1197
1198 // exit
1199 delete(Center);
1200 Log() << 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 Log() << Verbose(4) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1240 TPS[n] = (InsertUnique.first)->second;
1241 }
1242}
1243;
1244
1245/** Sets point to a present Tesselation::PointsOnBoundary.
1246 * Tesselation::TPS is set to the existing one or NULL if not found.
1247 * @param Candidate point to set to
1248 * @param n index for this point in Tesselation::TPS array
1249 */
1250void Tesselation::SetTesselationPoint(TesselPoint* Candidate, const int n) const
1251{
1252 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidate->nr);
1253 if (FindPoint != PointsOnBoundary.end())
1254 TPS[n] = FindPoint->second;
1255 else
1256 TPS[n] = NULL;
1257};
1258
1259/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1260 * If successful it raises the line count and inserts the new line into the BLS,
1261 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1262 * @param *a first endpoint
1263 * @param *b second endpoint
1264 * @param n index of Tesselation::BLS giving the line with both endpoints
1265 */
1266void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n) {
1267 bool insertNewLine = true;
1268
1269 if (a->lines.find(b->node->nr) != a->lines.end()) {
1270 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1271 pair<LineMap::iterator,LineMap::iterator> FindPair;
1272 FindPair = a->lines.equal_range(b->node->nr);
1273 Log() << Verbose(5) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1274
1275 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1276 // If there is a line with less than two attached triangles, we don't need a new line.
1277 if (FindLine->second->triangles.size() < 2) {
1278 insertNewLine = false;
1279 Log() << Verbose(4) << "Using existing line " << *FindLine->second << endl;
1280
1281 BPS[0] = FindLine->second->endpoints[0];
1282 BPS[1] = FindLine->second->endpoints[1];
1283 BLS[n] = FindLine->second;
1284
1285 break;
1286 }
1287 }
1288 }
1289
1290 if (insertNewLine) {
1291 AlwaysAddTesselationTriangleLine(a, b, n);
1292 }
1293}
1294;
1295
1296/**
1297 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1298 * Raises the line count and inserts the new line into the BLS.
1299 *
1300 * @param *a first endpoint
1301 * @param *b second endpoint
1302 * @param n index of Tesselation::BLS giving the line with both endpoints
1303 */
1304void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
1305{
1306 Log() << Verbose(4) << "Adding line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1307 BPS[0] = a;
1308 BPS[1] = b;
1309 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1310 // add line to global map
1311 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1312 // increase counter
1313 LinesOnBoundaryCount++;
1314};
1315
1316/** Function adds triangle to global list.
1317 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1318 */
1319void Tesselation::AddTesselationTriangle()
1320{
1321 Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1322
1323 // add triangle to global map
1324 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1325 TrianglesOnBoundaryCount++;
1326
1327 // set as last new triangle
1328 LastTriangle = BTS;
1329
1330 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1331};
1332
1333/** Function adds triangle to global list.
1334 * Furthermore, the triangle number is set to \a nr.
1335 * \param nr triangle number
1336 */
1337void Tesselation::AddTesselationTriangle(const int nr)
1338{
1339 Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1340
1341 // add triangle to global map
1342 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1343
1344 // set as last new triangle
1345 LastTriangle = BTS;
1346
1347 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1348};
1349
1350/** Removes a triangle from the tesselation.
1351 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1352 * Removes itself from memory.
1353 * \param *triangle to remove
1354 */
1355void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1356{
1357 if (triangle == NULL)
1358 return;
1359 for (int i = 0; i < 3; i++) {
1360 if (triangle->lines[i] != NULL) {
1361 Log() << Verbose(5) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1362 triangle->lines[i]->triangles.erase(triangle->Nr);
1363 if (triangle->lines[i]->triangles.empty()) {
1364 Log() << Verbose(5) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1365 RemoveTesselationLine(triangle->lines[i]);
1366 } else {
1367 Log() << Verbose(5) << *triangle->lines[i] << " is still attached to another triangle: ";
1368 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1369 Log() << Verbose(0) << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1370 Log() << Verbose(0) << endl;
1371// for (int j=0;j<2;j++) {
1372// Log() << Verbose(5) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1373// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1374// Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1375// Log() << Verbose(0) << endl;
1376// }
1377 }
1378 triangle->lines[i] = NULL; // free'd or not: disconnect
1379 } else
1380 eLog() << Verbose(1) << "This line " << i << " has already been free'd." << endl;
1381 }
1382
1383 if (TrianglesOnBoundary.erase(triangle->Nr))
1384 Log() << Verbose(5) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1385 delete(triangle);
1386};
1387
1388/** Removes a line from the tesselation.
1389 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1390 * \param *line line to remove
1391 */
1392void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1393{
1394 int Numbers[2];
1395
1396 if (line == NULL)
1397 return;
1398 // get other endpoint number for finding copies of same line
1399 if (line->endpoints[1] != NULL)
1400 Numbers[0] = line->endpoints[1]->Nr;
1401 else
1402 Numbers[0] = -1;
1403 if (line->endpoints[0] != NULL)
1404 Numbers[1] = line->endpoints[0]->Nr;
1405 else
1406 Numbers[1] = -1;
1407
1408 for (int i = 0; i < 2; i++) {
1409 if (line->endpoints[i] != NULL) {
1410 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
1411 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
1412 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
1413 if ((*Runner).second == line) {
1414 Log() << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1415 line->endpoints[i]->lines.erase(Runner);
1416 break;
1417 }
1418 } else { // there's just a single line left
1419 if (line->endpoints[i]->lines.erase(line->Nr))
1420 Log() << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1421 }
1422 if (line->endpoints[i]->lines.empty()) {
1423 Log() << Verbose(5) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
1424 RemoveTesselationPoint(line->endpoints[i]);
1425 } else {
1426 Log() << Verbose(5) << *line->endpoints[i] << " has still lines it's attached to: ";
1427 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
1428 Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1429 Log() << Verbose(0) << endl;
1430 }
1431 line->endpoints[i] = NULL; // free'd or not: disconnect
1432 } else
1433 eLog() << Verbose(1) << "Endpoint " << i << " has already been free'd." << endl;
1434 }
1435 if (!line->triangles.empty())
1436 eLog() << Verbose(2) << "Memory Leak! I " << *line << " am still connected to some triangles." << endl;
1437
1438 if (LinesOnBoundary.erase(line->Nr))
1439 Log() << Verbose(5) << "Removing line Nr. " << line->Nr << "." << endl;
1440 delete(line);
1441};
1442
1443/** Removes a point from the tesselation.
1444 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
1445 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
1446 * \param *point point to remove
1447 */
1448void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
1449{
1450 if (point == NULL)
1451 return;
1452 if (PointsOnBoundary.erase(point->Nr))
1453 Log() << Verbose(5) << "Removing point Nr. " << point->Nr << "." << endl;
1454 delete(point);
1455};
1456
1457/** Checks whether the triangle consisting of the three points is already present.
1458 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1459 * lines. If any of the three edges already has two triangles attached, false is
1460 * returned.
1461 * \param *out output stream for debugging
1462 * \param *Candidates endpoints of the triangle candidate
1463 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1464 * triangles exist which is the maximum for three points
1465 */
1466int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) const
1467{
1468 int adjacentTriangleCount = 0;
1469 class BoundaryPointSet *Points[3];
1470
1471 Log() << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1472 // builds a triangle point set (Points) of the end points
1473 for (int i = 0; i < 3; i++) {
1474 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1475 if (FindPoint != PointsOnBoundary.end()) {
1476 Points[i] = FindPoint->second;
1477 } else {
1478 Points[i] = NULL;
1479 }
1480 }
1481
1482 // checks lines between the points in the Points for their adjacent triangles
1483 for (int i = 0; i < 3; i++) {
1484 if (Points[i] != NULL) {
1485 for (int j = i; j < 3; j++) {
1486 if (Points[j] != NULL) {
1487 LineMap::const_iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1488 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1489 TriangleMap *triangles = &FindLine->second->triangles;
1490 Log() << Verbose(3) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1491 for (TriangleMap::const_iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1492 if (FindTriangle->second->IsPresentTupel(Points)) {
1493 adjacentTriangleCount++;
1494 }
1495 }
1496 Log() << Verbose(3) << "end." << endl;
1497 }
1498 // Only one of the triangle lines must be considered for the triangle count.
1499 //Log() << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1500 //return adjacentTriangleCount;
1501 }
1502 }
1503 }
1504 }
1505
1506 Log() << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1507 Log() << Verbose(2) << "End of CheckPresenceOfTriangle" << endl;
1508 return adjacentTriangleCount;
1509};
1510
1511/** Checks whether the triangle consisting of the three points is already present.
1512 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1513 * lines. If any of the three edges already has two triangles attached, false is
1514 * returned.
1515 * \param *out output stream for debugging
1516 * \param *Candidates endpoints of the triangle candidate
1517 * \return NULL - none found or pointer to triangle
1518 */
1519class BoundaryTriangleSet * Tesselation::GetPresentTriangle(TesselPoint *Candidates[3])
1520{
1521 class BoundaryTriangleSet *triangle = NULL;
1522 class BoundaryPointSet *Points[3];
1523
1524 // builds a triangle point set (Points) of the end points
1525 for (int i = 0; i < 3; i++) {
1526 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1527 if (FindPoint != PointsOnBoundary.end()) {
1528 Points[i] = FindPoint->second;
1529 } else {
1530 Points[i] = NULL;
1531 }
1532 }
1533
1534 // checks lines between the points in the Points for their adjacent triangles
1535 for (int i = 0; i < 3; i++) {
1536 if (Points[i] != NULL) {
1537 for (int j = i; j < 3; j++) {
1538 if (Points[j] != NULL) {
1539 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1540 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1541 TriangleMap *triangles = &FindLine->second->triangles;
1542 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1543 if (FindTriangle->second->IsPresentTupel(Points)) {
1544 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
1545 triangle = FindTriangle->second;
1546 }
1547 }
1548 }
1549 // Only one of the triangle lines must be considered for the triangle count.
1550 //Log() << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1551 //return adjacentTriangleCount;
1552 }
1553 }
1554 }
1555 }
1556
1557 return triangle;
1558};
1559
1560
1561/** Finds the starting triangle for FindNonConvexBorder().
1562 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
1563 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
1564 * point are called.
1565 * \param *out output stream for debugging
1566 * \param RADIUS radius of virtual rolling sphere
1567 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1568 */
1569void Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
1570{
1571 Log() << Verbose(1) << "Begin of FindStartingTriangle\n";
1572 int i = 0;
1573 TesselPoint* FirstPoint = NULL;
1574 TesselPoint* SecondPoint = NULL;
1575 TesselPoint* MaxPoint[NDIM];
1576 double maxCoordinate[NDIM];
1577 Vector Oben;
1578 Vector helper;
1579 Vector Chord;
1580 Vector SearchDirection;
1581
1582 Oben.Zero();
1583
1584 for (i = 0; i < 3; i++) {
1585 MaxPoint[i] = NULL;
1586 maxCoordinate[i] = -1;
1587 }
1588
1589 // 1. searching topmost point with respect to each axis
1590 for (int i=0;i<NDIM;i++) { // each axis
1591 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1592 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1593 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1594 const LinkedNodes *List = LC->GetCurrentCell();
1595 //Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1596 if (List != NULL) {
1597 for (LinkedNodes::const_iterator Runner = List->begin();Runner != List->end();Runner++) {
1598 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
1599 Log() << Verbose(2) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1600 maxCoordinate[i] = (*Runner)->node->x[i];
1601 MaxPoint[i] = (*Runner);
1602 }
1603 }
1604 } else {
1605 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1606 }
1607 }
1608 }
1609
1610 Log() << Verbose(2) << "Found maximum coordinates: ";
1611 for (int i=0;i<NDIM;i++)
1612 Log() << Verbose(0) << i << ": " << *MaxPoint[i] << "\t";
1613 Log() << Verbose(0) << endl;
1614
1615 BTS = NULL;
1616 CandidateList *OptCandidates = new CandidateList();
1617 for (int k=0;k<NDIM;k++) {
1618 Oben.Zero();
1619 Oben.x[k] = 1.;
1620 FirstPoint = MaxPoint[k];
1621 Log() << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1622
1623 double ShortestAngle;
1624 TesselPoint* OptCandidate = NULL;
1625 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.
1626
1627 FindSecondPointForTesselation(FirstPoint, Oben, OptCandidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1628 SecondPoint = OptCandidate;
1629 if (SecondPoint == NULL) // have we found a second point?
1630 continue;
1631
1632 helper.CopyVector(FirstPoint->node);
1633 helper.SubtractVector(SecondPoint->node);
1634 helper.Normalize();
1635 Oben.ProjectOntoPlane(&helper);
1636 Oben.Normalize();
1637 helper.VectorProduct(&Oben);
1638 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1639
1640 Chord.CopyVector(FirstPoint->node); // bring into calling function
1641 Chord.SubtractVector(SecondPoint->node);
1642 double radius = Chord.ScalarProduct(&Chord);
1643 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1644 helper.CopyVector(&Oben);
1645 helper.Scale(CircleRadius);
1646 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
1647
1648 // look in one direction of baseline for initial candidate
1649 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
1650
1651 // adding point 1 and point 2 and add the line between them
1652 Log() << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1653 AddTesselationPoint(FirstPoint, 0);
1654 Log() << Verbose(1) << "Found second point is at " << *SecondPoint->node << ".\n";
1655 AddTesselationPoint(SecondPoint, 1);
1656 AddTesselationLine(TPS[0], TPS[1], 0);
1657
1658 //Log() << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
1659 FindThirdPointForTesselation(Oben, SearchDirection, helper, BLS[0], NULL, *&OptCandidates, &ShortestAngle, RADIUS, LC);
1660 Log() << Verbose(1) << "List of third Points is ";
1661 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1662 Log() << Verbose(0) << " " << *(*it)->point;
1663 }
1664 Log() << Verbose(0) << endl;
1665
1666 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1667 // add third triangle point
1668 AddTesselationPoint((*it)->point, 2);
1669 // add the second and third line
1670 AddTesselationLine(TPS[1], TPS[2], 1);
1671 AddTesselationLine(TPS[0], TPS[2], 2);
1672 // ... and triangles to the Maps of the Tesselation class
1673 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1674 AddTesselationTriangle();
1675 // ... and calculate its normal vector (with correct orientation)
1676 (*it)->OptCenter.Scale(-1.);
1677 Log() << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
1678 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
1679 Log() << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
1680 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
1681
1682 // if we do not reach the end with the next step of iteration, we need to setup a new first line
1683 if (it != OptCandidates->end()--) {
1684 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
1685 SecondPoint = (*it)->point;
1686 // adding point 1 and point 2 and the line between them
1687 AddTesselationPoint(FirstPoint, 0);
1688 AddTesselationPoint(SecondPoint, 1);
1689 AddTesselationLine(TPS[0], TPS[1], 0);
1690 }
1691 Log() << Verbose(2) << "Projection is " << BTS->NormalVector.ScalarProduct(&Oben) << "." << endl;
1692 }
1693 if (BTS != NULL) // we have created one starting triangle
1694 break;
1695 else {
1696 // remove all candidates from the list and then the list itself
1697 class CandidateForTesselation *remover = NULL;
1698 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1699 remover = *it;
1700 delete(remover);
1701 }
1702 OptCandidates->clear();
1703 }
1704 }
1705
1706 // remove all candidates from the list and then the list itself
1707 class CandidateForTesselation *remover = NULL;
1708 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1709 remover = *it;
1710 delete(remover);
1711 }
1712 delete(OptCandidates);
1713 Log() << Verbose(1) << "End of FindStartingTriangle\n";
1714};
1715
1716/** Checks for a given baseline and a third point candidate whether baselines of the found triangle don't have even better candidates.
1717 * This is supposed to prevent early closing of the tesselation.
1718 * \param *BaseRay baseline, i.e. not \a *OptCandidate
1719 * \param *ThirdNode third point in triangle, not in BoundaryLineSet::endpoints
1720 * \param ShortestAngle path length on this circle band for the current \a *ThirdNode
1721 * \param RADIUS radius of sphere
1722 * \param *LC LinkedCell structure
1723 * \return true - there is a better candidate (smaller angle than \a ShortestAngle), false - no better TesselPoint candidate found
1724 */
1725bool Tesselation::HasOtherBaselineBetterCandidate(const BoundaryLineSet * const BaseRay, const TesselPoint * const ThirdNode, double ShortestAngle, double RADIUS, const LinkedCell * const LC) const
1726{
1727 bool result = false;
1728 Vector CircleCenter;
1729 Vector CirclePlaneNormal;
1730 Vector OldSphereCenter;
1731 Vector SearchDirection;
1732 Vector helper;
1733 TesselPoint *OtherOptCandidate = NULL;
1734 double OtherShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1735 double radius, CircleRadius;
1736 BoundaryLineSet *Line = NULL;
1737 BoundaryTriangleSet *T = NULL;
1738
1739 Log() << Verbose(1) << "Begin of HasOtherBaselineBetterCandidate" << endl;
1740
1741 // check both other lines
1742 PointMap::const_iterator FindPoint = PointsOnBoundary.find(ThirdNode->nr);
1743 if (FindPoint != PointsOnBoundary.end()) {
1744 for (int i=0;i<2;i++) {
1745 LineMap::const_iterator FindLine = (FindPoint->second)->lines.find(BaseRay->endpoints[0]->node->nr);
1746 if (FindLine != (FindPoint->second)->lines.end()) {
1747 Line = FindLine->second;
1748 Log() << Verbose(1) << "Found line " << *Line << "." << endl;
1749 if (Line->triangles.size() == 1) {
1750 T = Line->triangles.begin()->second;
1751 // construct center of circle
1752 CircleCenter.CopyVector(Line->endpoints[0]->node->node);
1753 CircleCenter.AddVector(Line->endpoints[1]->node->node);
1754 CircleCenter.Scale(0.5);
1755
1756 // construct normal vector of circle
1757 CirclePlaneNormal.CopyVector(Line->endpoints[0]->node->node);
1758 CirclePlaneNormal.SubtractVector(Line->endpoints[1]->node->node);
1759
1760 // calculate squared radius of circle
1761 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1762 if (radius/4. < RADIUS*RADIUS) {
1763 CircleRadius = RADIUS*RADIUS - radius/4.;
1764 CirclePlaneNormal.Normalize();
1765 //Log() << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1766
1767 // construct old center
1768 GetCenterofCircumcircle(&OldSphereCenter, *T->endpoints[0]->node->node, *T->endpoints[1]->node->node, *T->endpoints[2]->node->node);
1769 helper.CopyVector(&T->NormalVector); // normal vector ensures that this is correct center of the two possible ones
1770 radius = Line->endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
1771 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1772 OldSphereCenter.AddVector(&helper);
1773 OldSphereCenter.SubtractVector(&CircleCenter);
1774 //Log() << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
1775
1776 // construct SearchDirection
1777 SearchDirection.MakeNormalVector(&T->NormalVector, &CirclePlaneNormal);
1778 helper.CopyVector(Line->endpoints[0]->node->node);
1779 helper.SubtractVector(ThirdNode->node);
1780 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
1781 SearchDirection.Scale(-1.);
1782 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
1783 SearchDirection.Normalize();
1784 Log() << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1785 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
1786 // rotated the wrong way!
1787 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
1788 }
1789
1790 // add third point
1791 CandidateList *OptCandidates = new CandidateList();
1792 FindThirdPointForTesselation(T->NormalVector, SearchDirection, OldSphereCenter, Line, ThirdNode, OptCandidates, &OtherShortestAngle, RADIUS, LC);
1793 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1794 if (((*it)->point == BaseRay->endpoints[0]->node) || ((*it)->point == BaseRay->endpoints[1]->node)) // skip if it's the same triangle than suggested
1795 continue;
1796 Log() << Verbose(1) << " Third point candidate is " << *(*it)->point
1797 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
1798 Log() << Verbose(1) << " Baseline is " << *BaseRay << endl;
1799
1800 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
1801 TesselPoint *PointCandidates[3];
1802 PointCandidates[0] = (*it)->point;
1803 PointCandidates[1] = BaseRay->endpoints[0]->node;
1804 PointCandidates[2] = BaseRay->endpoints[1]->node;
1805 bool check=false;
1806 int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
1807 // If there is no triangle, add it regularly.
1808 if (existentTrianglesCount == 0) {
1809 SetTesselationPoint((*it)->point, 0);
1810 SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
1811 SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
1812
1813 if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
1814 OtherOptCandidate = (*it)->point;
1815 check = true;
1816 }
1817 } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
1818 SetTesselationPoint((*it)->point, 0);
1819 SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
1820 SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
1821
1822 // 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)
1823 // i.e. at least one of the three lines must be present with TriangleCount <= 1
1824 if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS)) {
1825 OtherOptCandidate = (*it)->point;
1826 check = true;
1827 }
1828 }
1829
1830 if (check) {
1831 if (ShortestAngle > OtherShortestAngle) {
1832 Log() << Verbose(1) << "There is a better candidate than " << *ThirdNode << " with " << ShortestAngle << " from baseline " << *Line << ": " << *OtherOptCandidate << " with " << OtherShortestAngle << "." << endl;
1833 result = true;
1834 break;
1835 }
1836 }
1837 }
1838 delete(OptCandidates);
1839 if (result)
1840 break;
1841 } else {
1842 Log() << Verbose(1) << "Circumcircle for base line " << *Line << " and base triangle " << T << " is too big!" << endl;
1843 }
1844 } else {
1845 eLog() << Verbose(2) << "Baseline is connected to two triangles already?" << endl;
1846 }
1847 } else {
1848 Log() << Verbose(2) << "No present baseline between " << BaseRay->endpoints[0] << " and candidate " << *ThirdNode << "." << endl;
1849 }
1850 }
1851 } else {
1852 eLog() << Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl;
1853 }
1854
1855 Log() << Verbose(1) << "End of HasOtherBaselineBetterCandidate" << endl;
1856
1857 return result;
1858};
1859
1860/** This function finds a triangle to a line, adjacent to an existing one.
1861 * @param out output stream for debugging
1862 * @param Line current baseline to search from
1863 * @param T current triangle which \a Line is edge of
1864 * @param RADIUS radius of the rolling ball
1865 * @param N number of found triangles
1866 * @param *LC LinkedCell structure with neighbouring points
1867 */
1868bool Tesselation::FindNextSuitableTriangle(BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
1869{
1870 Log() << Verbose(0) << "Begin of FindNextSuitableTriangle\n";
1871 bool result = true;
1872 CandidateList *OptCandidates = new CandidateList();
1873
1874 Vector CircleCenter;
1875 Vector CirclePlaneNormal;
1876 Vector OldSphereCenter;
1877 Vector SearchDirection;
1878 Vector helper;
1879 TesselPoint *ThirdNode = NULL;
1880 LineMap::iterator testline;
1881 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1882 double radius, CircleRadius;
1883
1884 Log() << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
1885 for (int i=0;i<3;i++)
1886 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
1887 ThirdNode = T.endpoints[i]->node;
1888
1889 // construct center of circle
1890 CircleCenter.CopyVector(Line.endpoints[0]->node->node);
1891 CircleCenter.AddVector(Line.endpoints[1]->node->node);
1892 CircleCenter.Scale(0.5);
1893
1894 // construct normal vector of circle
1895 CirclePlaneNormal.CopyVector(Line.endpoints[0]->node->node);
1896 CirclePlaneNormal.SubtractVector(Line.endpoints[1]->node->node);
1897
1898 // calculate squared radius of circle
1899 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1900 if (radius/4. < RADIUS*RADIUS) {
1901 CircleRadius = RADIUS*RADIUS - radius/4.;
1902 CirclePlaneNormal.Normalize();
1903 //Log() << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1904
1905 // construct old center
1906 GetCenterofCircumcircle(&OldSphereCenter, *T.endpoints[0]->node->node, *T.endpoints[1]->node->node, *T.endpoints[2]->node->node);
1907 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
1908 radius = Line.endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
1909 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1910 OldSphereCenter.AddVector(&helper);
1911 OldSphereCenter.SubtractVector(&CircleCenter);
1912 //Log() << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
1913
1914 // construct SearchDirection
1915 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
1916 helper.CopyVector(Line.endpoints[0]->node->node);
1917 helper.SubtractVector(ThirdNode->node);
1918 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
1919 SearchDirection.Scale(-1.);
1920 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
1921 SearchDirection.Normalize();
1922 Log() << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1923 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
1924 // rotated the wrong way!
1925 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
1926 }
1927
1928 // add third point
1929 FindThirdPointForTesselation(T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, OptCandidates, &ShortestAngle, RADIUS, LC);
1930
1931 } else {
1932 Log() << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
1933 }
1934
1935 if (OptCandidates->begin() == OptCandidates->end()) {
1936 eLog() << Verbose(2) << "Could not find a suitable candidate." << endl;
1937 return false;
1938 }
1939 Log() << Verbose(1) << "Third Points are ";
1940 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1941 Log() << Verbose(1) << " " << *(*it)->point << endl;
1942 }
1943
1944 BoundaryLineSet *BaseRay = &Line;
1945 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1946 Log() << Verbose(1) << " Third point candidate is " << *(*it)->point
1947 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
1948 Log() << Verbose(1) << " Baseline is " << *BaseRay << endl;
1949
1950 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
1951 TesselPoint *PointCandidates[3];
1952 PointCandidates[0] = (*it)->point;
1953 PointCandidates[1] = BaseRay->endpoints[0]->node;
1954 PointCandidates[2] = BaseRay->endpoints[1]->node;
1955 int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
1956
1957 BTS = NULL;
1958 // check for present edges and whether we reach better candidates from them
1959 //if (HasOtherBaselineBetterCandidate(BaseRay, (*it)->point, ShortestAngle, RADIUS, LC) ) {
1960 if (0) {
1961 result = false;
1962 break;
1963 } else {
1964 // If there is no triangle, add it regularly.
1965 if (existentTrianglesCount == 0) {
1966 AddTesselationPoint((*it)->point, 0);
1967 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1968 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1969
1970 if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
1971 AddTesselationLine(TPS[0], TPS[1], 0);
1972 AddTesselationLine(TPS[0], TPS[2], 1);
1973 AddTesselationLine(TPS[1], TPS[2], 2);
1974
1975 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1976 AddTesselationTriangle();
1977 (*it)->OptCenter.Scale(-1.);
1978 BTS->GetNormalVector((*it)->OptCenter);
1979 (*it)->OptCenter.Scale(-1.);
1980
1981 Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1982 << " for this triangle ... " << endl;
1983 //Log() << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
1984 } else {
1985 eLog() << Verbose(2) << "This triangle consisting of ";
1986 Log() << Verbose(0) << *(*it)->point << ", ";
1987 Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
1988 Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
1989 Log() << Verbose(0) << "exists and is not added, as it does not seem helpful!" << endl;
1990 result = false;
1991 }
1992 } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
1993 AddTesselationPoint((*it)->point, 0);
1994 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1995 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1996
1997 // 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)
1998 // i.e. at least one of the three lines must be present with TriangleCount <= 1
1999 if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS)) {
2000 AddTesselationLine(TPS[0], TPS[1], 0);
2001 AddTesselationLine(TPS[0], TPS[2], 1);
2002 AddTesselationLine(TPS[1], TPS[2], 2);
2003
2004 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2005 AddTesselationTriangle(); // add to global map
2006
2007 (*it)->OtherOptCenter.Scale(-1.);
2008 BTS->GetNormalVector((*it)->OtherOptCenter);
2009 (*it)->OtherOptCenter.Scale(-1.);
2010
2011 eLog() << Verbose(2) << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector << " for this triangle ... " << endl;
2012 Log() << Verbose(1) << "We have "<< BaseRay->triangles.size() << " for line " << BaseRay << "." << endl;
2013 } else {
2014 eLog() << Verbose(2) << "This triangle consisting of " << *(*it)->point << ", " << *BaseRay->endpoints[0]->node << " and " << *BaseRay->endpoints[1]->node << " " << "exists and is not added, as it does not seem helpful!" << endl;
2015 result = false;
2016 }
2017 } else {
2018 Log() << Verbose(1) << "This triangle consisting of ";
2019 Log() << Verbose(0) << *(*it)->point << ", ";
2020 Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2021 Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2022 Log() << Verbose(0) << "is invalid!" << endl;
2023 result = false;
2024 }
2025 }
2026
2027 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
2028 BaseRay = BLS[0];
2029 if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
2030 eLog() << Verbose(1) << "Triangle " << *BTS << " has zero normal vector!" << endl;
2031 exit(255);
2032 }
2033
2034 }
2035
2036 // remove all candidates from the list and then the list itself
2037 class CandidateForTesselation *remover = NULL;
2038 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2039 remover = *it;
2040 delete(remover);
2041 }
2042 delete(OptCandidates);
2043 Log() << Verbose(0) << "End of FindNextSuitableTriangle\n";
2044 return result;
2045};
2046
2047/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
2048 * We look whether the closest point on \a *Base with respect to the other baseline is outside
2049 * of the segment formed by both endpoints (concave) or not (convex).
2050 * \param *out output stream for debugging
2051 * \param *Base line to be flipped
2052 * \return NULL - convex, otherwise endpoint that makes it concave
2053 */
2054class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
2055{
2056 class BoundaryPointSet *Spot = NULL;
2057 class BoundaryLineSet *OtherBase;
2058 Vector *ClosestPoint;
2059
2060 int m=0;
2061 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2062 for (int j=0;j<3;j++) // all of their endpoints and baselines
2063 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2064 BPS[m++] = runner->second->endpoints[j];
2065 OtherBase = new class BoundaryLineSet(BPS,-1);
2066
2067 Log() << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
2068 Log() << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
2069
2070 // get the closest point on each line to the other line
2071 ClosestPoint = GetClosestPointBetweenLine(Base, OtherBase);
2072
2073 // delete the temporary other base line
2074 delete(OtherBase);
2075
2076 // get the distance vector from Base line to OtherBase line
2077 Vector DistanceToIntersection[2], BaseLine;
2078 double distance[2];
2079 BaseLine.CopyVector(Base->endpoints[1]->node->node);
2080 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
2081 for (int i=0;i<2;i++) {
2082 DistanceToIntersection[i].CopyVector(ClosestPoint);
2083 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
2084 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
2085 }
2086 delete(ClosestPoint);
2087 if ((distance[0] * distance[1]) > 0) { // have same sign?
2088 Log() << Verbose(3) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
2089 if (distance[0] < distance[1]) {
2090 Spot = Base->endpoints[0];
2091 } else {
2092 Spot = Base->endpoints[1];
2093 }
2094 return Spot;
2095 } else { // different sign, i.e. we are in between
2096 Log() << Verbose(3) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
2097 return NULL;
2098 }
2099
2100};
2101
2102void Tesselation::PrintAllBoundaryPoints(ofstream *out) const
2103{
2104 // print all lines
2105 Log() << Verbose(1) << "Printing all boundary points for debugging:" << endl;
2106 for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
2107 Log() << Verbose(2) << *(PointRunner->second) << endl;
2108};
2109
2110void Tesselation::PrintAllBoundaryLines(ofstream *out) const
2111{
2112 // print all lines
2113 Log() << Verbose(1) << "Printing all boundary lines for debugging:" << endl;
2114 for (LineMap::const_iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
2115 Log() << Verbose(2) << *(LineRunner->second) << endl;
2116};
2117
2118void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
2119{
2120 // print all triangles
2121 Log() << Verbose(1) << "Printing all boundary triangles for debugging:" << endl;
2122 for (TriangleMap::const_iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
2123 Log() << Verbose(2) << *(TriangleRunner->second) << endl;
2124};
2125
2126/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
2127 * \param *out output stream for debugging
2128 * \param *Base line to be flipped
2129 * \return volume change due to flipping (0 - then no flipped occured)
2130 */
2131double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
2132{
2133 class BoundaryLineSet *OtherBase;
2134 Vector *ClosestPoint[2];
2135 double volume;
2136
2137 int m=0;
2138 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2139 for (int j=0;j<3;j++) // all of their endpoints and baselines
2140 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2141 BPS[m++] = runner->second->endpoints[j];
2142 OtherBase = new class BoundaryLineSet(BPS,-1);
2143
2144 Log() << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
2145 Log() << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
2146
2147 // get the closest point on each line to the other line
2148 ClosestPoint[0] = GetClosestPointBetweenLine(Base, OtherBase);
2149 ClosestPoint[1] = GetClosestPointBetweenLine(OtherBase, Base);
2150
2151 // get the distance vector from Base line to OtherBase line
2152 Vector Distance;
2153 Distance.CopyVector(ClosestPoint[1]);
2154 Distance.SubtractVector(ClosestPoint[0]);
2155
2156 // calculate volume
2157 volume = CalculateVolumeofGeneralTetraeder(*Base->endpoints[1]->node->node, *OtherBase->endpoints[0]->node->node, *OtherBase->endpoints[1]->node->node, *Base->endpoints[0]->node->node);
2158
2159 // delete the temporary other base line and the closest points
2160 delete(ClosestPoint[0]);
2161 delete(ClosestPoint[1]);
2162 delete(OtherBase);
2163
2164 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2165 Log() << Verbose(3) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2166 return false;
2167 } else { // check for sign against BaseLineNormal
2168 Vector BaseLineNormal;
2169 BaseLineNormal.Zero();
2170 if (Base->triangles.size() < 2) {
2171 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2172 return 0.;
2173 }
2174 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2175 Log() << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2176 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2177 }
2178 BaseLineNormal.Scale(1./2.);
2179
2180 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2181 Log() << Verbose(2) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2182 // calculate volume summand as a general tetraeder
2183 return volume;
2184 } else { // Base higher than OtherBase -> do nothing
2185 Log() << Verbose(2) << "REJECT: Base line is higher: Nothing to do." << endl;
2186 return 0.;
2187 }
2188 }
2189};
2190
2191/** For a given baseline and its two connected triangles, flips the baseline.
2192 * I.e. we create the new baseline between the other two endpoints of these four
2193 * endpoints and reconstruct the two triangles accordingly.
2194 * \param *out output stream for debugging
2195 * \param *Base line to be flipped
2196 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2197 */
2198class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
2199{
2200 class BoundaryLineSet *OldLines[4], *NewLine;
2201 class BoundaryPointSet *OldPoints[2];
2202 Vector BaseLineNormal;
2203 int OldTriangleNrs[2], OldBaseLineNr;
2204 int i,m;
2205
2206 Log() << Verbose(1) << "Begin of FlipBaseline" << endl;
2207
2208 // calculate NormalVector for later use
2209 BaseLineNormal.Zero();
2210 if (Base->triangles.size() < 2) {
2211 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2212 return NULL;
2213 }
2214 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2215 Log() << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2216 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2217 }
2218 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2219
2220 // get the two triangles
2221 // gather four endpoints and four lines
2222 for (int j=0;j<4;j++)
2223 OldLines[j] = NULL;
2224 for (int j=0;j<2;j++)
2225 OldPoints[j] = NULL;
2226 i=0;
2227 m=0;
2228 Log() << Verbose(3) << "The four old lines are: ";
2229 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2230 for (int j=0;j<3;j++) // all of their endpoints and baselines
2231 if (runner->second->lines[j] != Base) { // pick not the central baseline
2232 OldLines[i++] = runner->second->lines[j];
2233 Log() << Verbose(0) << *runner->second->lines[j] << "\t";
2234 }
2235 Log() << Verbose(0) << endl;
2236 Log() << Verbose(3) << "The two old points are: ";
2237 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2238 for (int j=0;j<3;j++) // all of their endpoints and baselines
2239 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2240 OldPoints[m++] = runner->second->endpoints[j];
2241 Log() << Verbose(0) << *runner->second->endpoints[j] << "\t";
2242 }
2243 Log() << Verbose(0) << endl;
2244
2245 // check whether everything is in place to create new lines and triangles
2246 if (i<4) {
2247 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2248 return NULL;
2249 }
2250 for (int j=0;j<4;j++)
2251 if (OldLines[j] == NULL) {
2252 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2253 return NULL;
2254 }
2255 for (int j=0;j<2;j++)
2256 if (OldPoints[j] == NULL) {
2257 eLog() << Verbose(1) << "We have not gathered enough endpoints!" << endl;
2258 return NULL;
2259 }
2260
2261 // remove triangles and baseline removes itself
2262 Log() << Verbose(3) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2263 OldBaseLineNr = Base->Nr;
2264 m=0;
2265 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2266 Log() << Verbose(3) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
2267 OldTriangleNrs[m++] = runner->second->Nr;
2268 RemoveTesselationTriangle(runner->second);
2269 }
2270
2271 // construct new baseline (with same number as old one)
2272 BPS[0] = OldPoints[0];
2273 BPS[1] = OldPoints[1];
2274 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2275 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2276 Log() << Verbose(3) << "INFO: Created new baseline " << *NewLine << "." << endl;
2277
2278 // construct new triangles with flipped baseline
2279 i=-1;
2280 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2281 i=2;
2282 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2283 i=3;
2284 if (i!=-1) {
2285 BLS[0] = OldLines[0];
2286 BLS[1] = OldLines[i];
2287 BLS[2] = NewLine;
2288 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2289 BTS->GetNormalVector(BaseLineNormal);
2290 AddTesselationTriangle(OldTriangleNrs[0]);
2291 Log() << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2292
2293 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
2294 BLS[1] = OldLines[1];
2295 BLS[2] = NewLine;
2296 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2297 BTS->GetNormalVector(BaseLineNormal);
2298 AddTesselationTriangle(OldTriangleNrs[1]);
2299 Log() << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2300 } else {
2301 Log() << Verbose(1) << "The four old lines do not connect, something's utterly wrong here!" << endl;
2302 return NULL;
2303 }
2304
2305 Log() << Verbose(1) << "End of FlipBaseline" << endl;
2306 return NewLine;
2307};
2308
2309
2310/** Finds the second point of starting triangle.
2311 * \param *a first node
2312 * \param Oben vector indicating the outside
2313 * \param OptCandidate reference to recommended candidate on return
2314 * \param Storage[3] array storing angles and other candidate information
2315 * \param RADIUS radius of virtual sphere
2316 * \param *LC LinkedCell structure with neighbouring points
2317 */
2318void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC)
2319{
2320 Log() << Verbose(2) << "Begin of FindSecondPointForTesselation" << endl;
2321 Vector AngleCheck;
2322 class TesselPoint* Candidate = NULL;
2323 double norm = -1.;
2324 double angle = 0.;
2325 int N[NDIM];
2326 int Nlower[NDIM];
2327 int Nupper[NDIM];
2328
2329 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2330 for(int i=0;i<NDIM;i++) // store indices of this cell
2331 N[i] = LC->n[i];
2332 } else {
2333 eLog() << Verbose(1) << "Point " << *a << " is not found in cell " << LC->index << "." << endl;
2334 return;
2335 }
2336 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2337 for (int i=0;i<NDIM;i++) {
2338 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2339 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2340 }
2341 Log() << Verbose(3) << "LC Intervals from [" << N[0] << "<->" << LC->N[0] << ", " << N[1] << "<->" << LC->N[1] << ", " << N[2] << "<->" << LC->N[2] << "] :"
2342 << " [" << Nlower[0] << "," << Nupper[0] << "], " << " [" << Nlower[1] << "," << Nupper[1] << "], " << " [" << Nlower[2] << "," << Nupper[2] << "], " << endl;
2343
2344 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2345 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2346 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2347 const LinkedNodes *List = LC->GetCurrentCell();
2348 //Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2349 if (List != NULL) {
2350 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2351 Candidate = (*Runner);
2352 // check if we only have one unique point yet ...
2353 if (a != Candidate) {
2354 // Calculate center of the circle with radius RADIUS through points a and Candidate
2355 Vector OrthogonalizedOben, aCandidate, Center;
2356 double distance, scaleFactor;
2357
2358 OrthogonalizedOben.CopyVector(&Oben);
2359 aCandidate.CopyVector(a->node);
2360 aCandidate.SubtractVector(Candidate->node);
2361 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
2362 OrthogonalizedOben.Normalize();
2363 distance = 0.5 * aCandidate.Norm();
2364 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2365 OrthogonalizedOben.Scale(scaleFactor);
2366
2367 Center.CopyVector(Candidate->node);
2368 Center.AddVector(a->node);
2369 Center.Scale(0.5);
2370 Center.AddVector(&OrthogonalizedOben);
2371
2372 AngleCheck.CopyVector(&Center);
2373 AngleCheck.SubtractVector(a->node);
2374 norm = aCandidate.Norm();
2375 // second point shall have smallest angle with respect to Oben vector
2376 if (norm < RADIUS*2.) {
2377 angle = AngleCheck.Angle(&Oben);
2378 if (angle < Storage[0]) {
2379 //Log() << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2380 Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2381 OptCandidate = Candidate;
2382 Storage[0] = angle;
2383 //Log() << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2384 } else {
2385 //Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
2386 }
2387 } else {
2388 //Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2389 }
2390 } else {
2391 //Log() << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2392 }
2393 }
2394 } else {
2395 Log() << Verbose(3) << "Linked cell list is empty." << endl;
2396 }
2397 }
2398 Log() << Verbose(2) << "End of FindSecondPointForTesselation" << endl;
2399};
2400
2401
2402/** This recursive function finds a third point, to form a triangle with two given ones.
2403 * Note that this function is for the starting triangle.
2404 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2405 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2406 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2407 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2408 * us the "null" on this circle, the new center of the candidate point will be some way along this
2409 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2410 * by the normal vector of the base triangle that always points outwards by construction.
2411 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2412 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2413 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2414 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2415 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2416 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2417 * both.
2418 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2419 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2420 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2421 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2422 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2423 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2424 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2425 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2426 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2427 * @param BaseLine BoundaryLineSet with the current base line
2428 * @param ThirdNode third point to avoid in search
2429 * @param candidates list of equally good candidates to return
2430 * @param ShortestAngle the current path length on this circle band for the current OptCandidate
2431 * @param RADIUS radius of sphere
2432 * @param *LC LinkedCell structure with neighbouring points
2433 */
2434void Tesselation::FindThirdPointForTesselation(Vector &NormalVector, Vector &SearchDirection, Vector &OldSphereCenter, class BoundaryLineSet *BaseLine, const class TesselPoint * const ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, const LinkedCell *LC) const
2435{
2436 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2437 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2438 Vector SphereCenter;
2439 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2440 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2441 Vector NewNormalVector; // normal vector of the Candidate's triangle
2442 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2443 double CircleRadius; // radius of this circle
2444 double radius;
2445 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2446 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2447 TesselPoint *Candidate = NULL;
2448 CandidateForTesselation *optCandidate = NULL;
2449
2450 Log() << Verbose(1) << "Begin of FindThirdPointForTesselation" << endl;
2451
2452 Log() << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
2453
2454 // construct center of circle
2455 CircleCenter.CopyVector(BaseLine->endpoints[0]->node->node);
2456 CircleCenter.AddVector(BaseLine->endpoints[1]->node->node);
2457 CircleCenter.Scale(0.5);
2458
2459 // construct normal vector of circle
2460 CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
2461 CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
2462
2463 // calculate squared radius TesselPoint *ThirdNode,f circle
2464 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2465 if (radius/4. < RADIUS*RADIUS) {
2466 CircleRadius = RADIUS*RADIUS - radius/4.;
2467 CirclePlaneNormal.Normalize();
2468 //Log() << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2469
2470 // test whether old center is on the band's plane
2471 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
2472 eLog() << Verbose(1) << "Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
2473 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
2474 }
2475 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
2476 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2477 //Log() << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2478
2479 // check SearchDirection
2480 //Log() << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2481 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2482 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
2483 }
2484
2485 // get cell for the starting point
2486 if (LC->SetIndexToVector(&CircleCenter)) {
2487 for(int i=0;i<NDIM;i++) // store indices of this cell
2488 N[i] = LC->n[i];
2489 //Log() << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2490 } else {
2491 eLog() << Verbose(1) << "Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
2492 return;
2493 }
2494 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2495 //Log() << Verbose(2) << "LC Intervals:";
2496 for (int i=0;i<NDIM;i++) {
2497 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2498 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2499 //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2500 }
2501 //Log() << Verbose(0) << endl;
2502 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2503 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2504 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2505 const LinkedNodes *List = LC->GetCurrentCell();
2506 //Log() << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2507 if (List != NULL) {
2508 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2509 Candidate = (*Runner);
2510
2511 // check for three unique points
2512 //Log() << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->node << "." << endl;
2513 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
2514
2515 // construct both new centers
2516 GetCenterofCircumcircle(&NewSphereCenter, *BaseLine->endpoints[0]->node->node, *BaseLine->endpoints[1]->node->node, *Candidate->node);
2517 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
2518
2519 if ((NewNormalVector.MakeNormalVector(BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node))
2520 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
2521 ) {
2522 helper.CopyVector(&NewNormalVector);
2523 //Log() << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2524 radius = BaseLine->endpoints[0]->node->node->DistanceSquared(&NewSphereCenter);
2525 if (radius < RADIUS*RADIUS) {
2526 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2527 //Log() << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
2528 NewSphereCenter.AddVector(&helper);
2529 NewSphereCenter.SubtractVector(&CircleCenter);
2530 //Log() << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
2531
2532 // OtherNewSphereCenter is created by the same vector just in the other direction
2533 helper.Scale(-1.);
2534 OtherNewSphereCenter.AddVector(&helper);
2535 OtherNewSphereCenter.SubtractVector(&CircleCenter);
2536 //Log() << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2537
2538 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2539 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2540 alpha = min(alpha, Otheralpha);
2541 // if there is a better candidate, drop the current list and add the new candidate
2542 // otherwise ignore the new candidate and keep the list
2543 if (*ShortestAngle > (alpha - HULLEPSILON)) {
2544 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
2545 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2546 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
2547 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2548 } else {
2549 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
2550 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
2551 }
2552 // if there is an equal candidate, add it to the list without clearing the list
2553 if ((*ShortestAngle - HULLEPSILON) < alpha) {
2554 candidates->push_back(optCandidate);
2555 Log() << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
2556 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2557 } else {
2558 // remove all candidates from the list and then the list itself
2559 class CandidateForTesselation *remover = NULL;
2560 for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
2561 remover = *it;
2562 delete(remover);
2563 }
2564 candidates->clear();
2565 candidates->push_back(optCandidate);
2566 Log() << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
2567 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2568 }
2569 *ShortestAngle = alpha;
2570 //Log() << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
2571 } else {
2572 if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
2573 //Log() << Verbose(2) << "REJECT: Old candidate " << *(optCandidate->point) << " with " << *ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
2574 } else {
2575 //Log() << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2576 }
2577 }
2578
2579 } else {
2580 //Log() << Verbose(2) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
2581 }
2582 } else {
2583 //Log() << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2584 }
2585 } else {
2586 if (ThirdNode != NULL) {
2587 //Log() << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2588 } else {
2589 //Log() << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
2590 }
2591 }
2592 }
2593 }
2594 }
2595 } else {
2596 eLog() << Verbose(1) << "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2597 }
2598 } else {
2599 if (ThirdNode != NULL)
2600 Log() << Verbose(2) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2601 else
2602 Log() << Verbose(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
2603 }
2604
2605 //Log() << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
2606 if (candidates->size() > 1) {
2607 candidates->unique();
2608 candidates->sort(SortCandidates);
2609 }
2610
2611 Log() << Verbose(1) << "End of FindThirdPointForTesselation" << endl;
2612};
2613
2614/** Finds the endpoint two lines are sharing.
2615 * \param *line1 first line
2616 * \param *line2 second line
2617 * \return point which is shared or NULL if none
2618 */
2619class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
2620{
2621 const BoundaryLineSet * lines[2] = { line1, line2 };
2622 class BoundaryPointSet *node = NULL;
2623 map<int, class BoundaryPointSet *> OrderMap;
2624 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
2625 for (int i = 0; i < 2; i++)
2626 // for both lines
2627 for (int j = 0; j < 2; j++)
2628 { // for both endpoints
2629 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
2630 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
2631 if (!OrderTest.second)
2632 { // if insertion fails, we have common endpoint
2633 node = OrderTest.first->second;
2634 Log() << Verbose(5) << "Common endpoint of lines " << *line1
2635 << " and " << *line2 << " is: " << *node << "." << endl;
2636 j = 2;
2637 i = 2;
2638 break;
2639 }
2640 }
2641 return node;
2642};
2643
2644/** Finds the triangle that is closest to a given Vector \a *x.
2645 * \param *out output stream for debugging
2646 * \param *x Vector to look from
2647 * \return list of BoundaryTriangleSet of nearest triangles or NULL in degenerate case.
2648 */
2649list<BoundaryTriangleSet*> * Tesselation::FindClosestTrianglesToPoint(const Vector *x, const LinkedCell* LC) const
2650{
2651 TesselPoint *trianglePoints[3];
2652 TesselPoint *SecondPoint = NULL;
2653 list<BoundaryTriangleSet*> *triangles = NULL;
2654
2655 if (LinesOnBoundary.empty()) {
2656 Log() << Verbose(0) << "Error: There is no tesselation structure to compare the point with, please create one first.";
2657 return NULL;
2658 }
2659 Log() << Verbose(1) << "Finding closest Tesselpoint to " << *x << " ... " << endl;
2660 trianglePoints[0] = FindClosestPoint(x, SecondPoint, LC);
2661
2662 // check whether closest point is "too close" :), then it's inside
2663 if (trianglePoints[0] == NULL) {
2664 Log() << Verbose(2) << "Is the only point, no one else is closeby." << endl;
2665 return NULL;
2666 }
2667 if (trianglePoints[0]->node->DistanceSquared(x) < MYEPSILON) {
2668 Log() << Verbose(3) << "Point is right on a tesselation point, no nearest triangle." << endl;
2669 PointMap::const_iterator PointRunner = PointsOnBoundary.find(trianglePoints[0]->nr);
2670 triangles = new list<BoundaryTriangleSet*>;
2671 if (PointRunner != PointsOnBoundary.end()) {
2672 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2673 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2674 triangles->push_back(TriangleRunner->second);
2675 triangles->sort();
2676 triangles->unique();
2677 } else {
2678 PointRunner = PointsOnBoundary.find(SecondPoint->nr);
2679 trianglePoints[0] = SecondPoint;
2680 if (PointRunner != PointsOnBoundary.end()) {
2681 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2682 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2683 triangles->push_back(TriangleRunner->second);
2684 triangles->sort();
2685 triangles->unique();
2686 } else {
2687 eLog() << Verbose(1) << "I cannot find a boundary point to the tessel point " << *trianglePoints[0] << "." << endl;
2688 return NULL;
2689 }
2690 }
2691 } else {
2692 list<TesselPoint*> *connectedClosestPoints = GetCircleOfConnectedPoints(trianglePoints[0], x);
2693 if (connectedClosestPoints != NULL) {
2694 trianglePoints[1] = connectedClosestPoints->front();
2695 trianglePoints[2] = connectedClosestPoints->back();
2696 for (int i=0;i<3;i++) {
2697 if (trianglePoints[i] == NULL) {
2698 eLog() << Verbose(1) << "IsInnerPoint encounters serious error, point " << i << " not found." << endl;
2699 }
2700 //Log() << Verbose(2) << "List of triangle points:" << endl;
2701 //Log() << Verbose(3) << *trianglePoints[i] << endl;
2702 }
2703
2704 triangles = FindTriangles(trianglePoints);
2705 Log() << Verbose(2) << "List of possible triangles:" << endl;
2706 for(list<BoundaryTriangleSet*>::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
2707 Log() << Verbose(3) << **Runner << endl;
2708
2709 delete(connectedClosestPoints);
2710 } else {
2711 triangles = NULL;
2712 Log() << Verbose(1) << "There is no circle of connected points!" << endl;
2713 }
2714 }
2715
2716 if ((triangles == NULL) || (triangles->empty())) {
2717 eLog() << Verbose(1) << "There is no nearest triangle. Please check the tesselation structure.";
2718 delete(triangles);
2719 return NULL;
2720 } else
2721 return triangles;
2722};
2723
2724/** Finds closest triangle to a point.
2725 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
2726 * \param *out output stream for debugging
2727 * \param *x Vector to look from
2728 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
2729 */
2730class BoundaryTriangleSet * Tesselation::FindClosestTriangleToPoint(const Vector *x, const LinkedCell* LC) const
2731{
2732 class BoundaryTriangleSet *result = NULL;
2733 list<BoundaryTriangleSet*> *triangles = FindClosestTrianglesToPoint(x, LC);
2734 Vector Center;
2735
2736 if (triangles == NULL)
2737 return NULL;
2738
2739 if (triangles->size() == 1) { // there is no degenerate case
2740 result = triangles->front();
2741 Log() << Verbose(2) << "Normal Vector of this triangle is " << result->NormalVector << "." << endl;
2742 } else {
2743 result = triangles->front();
2744 result->GetCenter(&Center);
2745 Center.SubtractVector(x);
2746 Log() << Verbose(2) << "Normal Vector of this front side is " << result->NormalVector << "." << endl;
2747 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2748 result = triangles->back();
2749 Log() << Verbose(2) << "Normal Vector of this back side is " << result->NormalVector << "." << endl;
2750 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2751 eLog() << Verbose(1) << "Front and back side yield NormalVector in wrong direction!" << endl;
2752 }
2753 }
2754 }
2755 delete(triangles);
2756 return result;
2757};
2758
2759/** Checks whether the provided Vector is within the tesselation structure.
2760 *
2761 * @param point of which to check the position
2762 * @param *LC LinkedCell structure
2763 *
2764 * @return true if the point is inside the tesselation structure, false otherwise
2765 */
2766bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const
2767{
2768 class BoundaryTriangleSet *result = FindClosestTriangleToPoint(&Point, LC);
2769 Vector Center;
2770
2771 if (result == NULL) {// is boundary point or only point in point cloud?
2772 Log() << Verbose(1) << Point << " is the only point in vicinity." << endl;
2773 return false;
2774 }
2775
2776 result->GetCenter(&Center);
2777 Log() << Verbose(3) << "INFO: Central point of the triangle is " << Center << "." << endl;
2778 Center.SubtractVector(&Point);
2779 Log() << Verbose(3) << "INFO: Vector from center to point to test is " << Center << "." << endl;
2780 if (Center.ScalarProduct(&result->NormalVector) > -MYEPSILON) {
2781 Log() << Verbose(1) << Point << " is an inner point." << endl;
2782 return true;
2783 } else {
2784 Log() << Verbose(1) << Point << " is NOT an inner point." << endl;
2785 return false;
2786 }
2787}
2788
2789/** Checks whether the provided TesselPoint is within the tesselation structure.
2790 *
2791 * @param *Point of which to check the position
2792 * @param *LC Linked Cell structure
2793 *
2794 * @return true if the point is inside the tesselation structure, false otherwise
2795 */
2796bool Tesselation::IsInnerPoint(const TesselPoint * const Point, const LinkedCell* const LC) const
2797{
2798 return IsInnerPoint(*(Point->node), LC);
2799}
2800
2801/** Gets all points connected to the provided point by triangulation lines.
2802 *
2803 * @param *Point of which get all connected points
2804 *
2805 * @return set of the all points linked to the provided one
2806 */
2807set<TesselPoint*> * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
2808{
2809 set<TesselPoint*> *connectedPoints = new set<TesselPoint*>;
2810 class BoundaryPointSet *ReferencePoint = NULL;
2811 TesselPoint* current;
2812 bool takePoint = false;
2813
2814 Log() << Verbose(3) << "Begin of GetAllConnectedPoints" << endl;
2815
2816 // find the respective boundary point
2817 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
2818 if (PointRunner != PointsOnBoundary.end()) {
2819 ReferencePoint = PointRunner->second;
2820 } else {
2821 Log() << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2822 ReferencePoint = NULL;
2823 }
2824
2825 // little trick so that we look just through lines connect to the BoundaryPoint
2826 // OR fall-back to look through all lines if there is no such BoundaryPoint
2827 const LineMap *Lines;;
2828 if (ReferencePoint != NULL)
2829 Lines = &(ReferencePoint->lines);
2830 else
2831 Lines = &LinesOnBoundary;
2832 LineMap::const_iterator findLines = Lines->begin();
2833 while (findLines != Lines->end()) {
2834 takePoint = false;
2835
2836 if (findLines->second->endpoints[0]->Nr == Point->nr) {
2837 takePoint = true;
2838 current = findLines->second->endpoints[1]->node;
2839 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
2840 takePoint = true;
2841 current = findLines->second->endpoints[0]->node;
2842 }
2843
2844 if (takePoint) {
2845 Log() << Verbose(5) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
2846 connectedPoints->insert(current);
2847 }
2848
2849 findLines++;
2850 }
2851
2852 if (connectedPoints->size() == 0) { // if have not found any points
2853 eLog() << Verbose(1) << "We have not found any connected points to " << *Point<< "." << endl;
2854 return NULL;
2855 }
2856
2857 Log() << Verbose(3) << "End of GetAllConnectedPoints" << endl;
2858 return connectedPoints;
2859};
2860
2861
2862/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2863 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2864 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2865 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2866 * triangle we are looking for.
2867 *
2868 * @param *out output stream for debugging
2869 * @param *Point of which get all connected points
2870 * @param *Reference Reference vector for zero angle or NULL for no preference
2871 * @return list of the all points linked to the provided one
2872 */
2873list<TesselPoint*> * Tesselation::GetCircleOfConnectedPoints(const TesselPoint* const Point, const Vector * const Reference) const
2874{
2875 map<double, TesselPoint*> anglesOfPoints;
2876 set<TesselPoint*> *connectedPoints = GetAllConnectedPoints(Point);
2877 list<TesselPoint*> *connectedCircle = new list<TesselPoint*>;
2878 Vector center;
2879 Vector PlaneNormal;
2880 Vector AngleZero;
2881 Vector OrthogonalVector;
2882 Vector helper;
2883
2884 if (connectedPoints == NULL) {
2885 Log() << Verbose(2) << "Could not find any connected points!" << endl;
2886 delete(connectedCircle);
2887 return NULL;
2888 }
2889 Log() << Verbose(2) << "Begin of GetCircleOfConnectedPoints" << endl;
2890
2891 // calculate central point
2892 for (set<TesselPoint*>::const_iterator TesselRunner = connectedPoints->begin(); TesselRunner != connectedPoints->end(); TesselRunner++)
2893 center.AddVector((*TesselRunner)->node);
2894 //Log() << Verbose(0) << "Summed vectors " << center << "; number of points " << connectedPoints.size()
2895 // << "; scale factor " << 1.0/connectedPoints.size();
2896 center.Scale(1.0/connectedPoints->size());
2897 Log() << Verbose(4) << "INFO: Calculated center of all circle points is " << center << "." << endl;
2898
2899 // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
2900 PlaneNormal.CopyVector(Point->node);
2901 PlaneNormal.SubtractVector(&center);
2902 PlaneNormal.Normalize();
2903 Log() << Verbose(4) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
2904
2905 // construct one orthogonal vector
2906 if (Reference != NULL) {
2907 AngleZero.CopyVector(Reference);
2908 AngleZero.SubtractVector(Point->node);
2909 AngleZero.ProjectOntoPlane(&PlaneNormal);
2910 }
2911 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
2912 Log() << Verbose(4) << "Using alternatively " << *(*connectedPoints->begin())->node << " as angle 0 referencer." << endl;
2913 AngleZero.CopyVector((*connectedPoints->begin())->node);
2914 AngleZero.SubtractVector(Point->node);
2915 AngleZero.ProjectOntoPlane(&PlaneNormal);
2916 if (AngleZero.NormSquared() < MYEPSILON) {
2917 eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
2918 performCriticalExit();
2919 }
2920 }
2921 Log() << Verbose(4) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
2922 if (AngleZero.NormSquared() > MYEPSILON)
2923 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
2924 else
2925 OrthogonalVector.MakeNormalVector(&PlaneNormal);
2926 Log() << Verbose(4) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
2927
2928 // go through all connected points and calculate angle
2929 for (set<TesselPoint*>::iterator listRunner = connectedPoints->begin(); listRunner != connectedPoints->end(); listRunner++) {
2930 helper.CopyVector((*listRunner)->node);
2931 helper.SubtractVector(Point->node);
2932 helper.ProjectOntoPlane(&PlaneNormal);
2933 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
2934 Log() << Verbose(3) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
2935 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
2936 }
2937
2938 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
2939 connectedCircle->push_back(AngleRunner->second);
2940 }
2941
2942 delete(connectedPoints);
2943
2944 Log() << Verbose(2) << "End of GetCircleOfConnectedPoints" << endl;
2945
2946 return connectedCircle;
2947}
2948
2949/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
2950 *
2951 * @param *out output stream for debugging
2952 * @param *Point of which get all connected points
2953 * @return list of the all points linked to the provided one
2954 */
2955list<list<TesselPoint*> *> * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
2956{
2957 map<double, TesselPoint*> anglesOfPoints;
2958 list<list<TesselPoint*> *> *ListOfPaths = new list<list<TesselPoint*> *>;
2959 list<TesselPoint*> *connectedPath = NULL;
2960 Vector center;
2961 Vector PlaneNormal;
2962 Vector AngleZero;
2963 Vector OrthogonalVector;
2964 Vector helper;
2965 class BoundaryPointSet *ReferencePoint = NULL;
2966 class BoundaryPointSet *CurrentPoint = NULL;
2967 class BoundaryTriangleSet *triangle = NULL;
2968 class BoundaryLineSet *CurrentLine = NULL;
2969 class BoundaryLineSet *StartLine = NULL;
2970
2971 // find the respective boundary point
2972 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
2973 if (PointRunner != PointsOnBoundary.end()) {
2974 ReferencePoint = PointRunner->second;
2975 } else {
2976 eLog() << Verbose(1) << "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2977 return NULL;
2978 }
2979
2980 map <class BoundaryLineSet *, bool> TouchedLine;
2981 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
2982 map <class BoundaryLineSet *, bool>::iterator LineRunner;
2983 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
2984 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
2985 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
2986 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
2987 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
2988 }
2989 if (!ReferencePoint->lines.empty()) {
2990 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
2991 LineRunner = TouchedLine.find(runner->second);
2992 if (LineRunner == TouchedLine.end()) {
2993 eLog() << Verbose(1) << "I could not find " << *runner->second << " in the touched list." << endl;
2994 } else if (!LineRunner->second) {
2995 LineRunner->second = true;
2996 connectedPath = new list<TesselPoint*>;
2997 triangle = NULL;
2998 CurrentLine = runner->second;
2999 StartLine = CurrentLine;
3000 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3001 Log() << Verbose(3)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
3002 do {
3003 // push current one
3004 Log() << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3005 connectedPath->push_back(CurrentPoint->node);
3006
3007 // find next triangle
3008 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
3009 Log() << Verbose(3) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
3010 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
3011 triangle = Runner->second;
3012 TriangleRunner = TouchedTriangle.find(triangle);
3013 if (TriangleRunner != TouchedTriangle.end()) {
3014 if (!TriangleRunner->second) {
3015 TriangleRunner->second = true;
3016 Log() << Verbose(3) << "INFO: Connecting triangle is " << *triangle << "." << endl;
3017 break;
3018 } else {
3019 Log() << Verbose(3) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
3020 triangle = NULL;
3021 }
3022 } else {
3023 eLog() << Verbose(1) << "I could not find " << *triangle << " in the touched list." << endl;
3024 triangle = NULL;
3025 }
3026 }
3027 }
3028 if (triangle == NULL)
3029 break;
3030 // find next line
3031 for (int i=0;i<3;i++) {
3032 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
3033 CurrentLine = triangle->lines[i];
3034 Log() << Verbose(3) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
3035 break;
3036 }
3037 }
3038 LineRunner = TouchedLine.find(CurrentLine);
3039 if (LineRunner == TouchedLine.end())
3040 eLog() << Verbose(1) << "I could not find " << *CurrentLine << " in the touched list." << endl;
3041 else
3042 LineRunner->second = true;
3043 // find next point
3044 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3045
3046 } while (CurrentLine != StartLine);
3047 // last point is missing, as it's on start line
3048 Log() << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3049 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
3050 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
3051
3052 ListOfPaths->push_back(connectedPath);
3053 } else {
3054 Log() << Verbose(3) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
3055 }
3056 }
3057 } else {
3058 eLog() << Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl;
3059 }
3060
3061 return ListOfPaths;
3062}
3063
3064/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
3065 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
3066 * @param *out output stream for debugging
3067 * @param *Point of which get all connected points
3068 * @return list of the closed paths
3069 */
3070list<list<TesselPoint*> *> * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
3071{
3072 list<list<TesselPoint*> *> *ListofPaths = GetPathsOfConnectedPoints(Point);
3073 list<list<TesselPoint*> *> *ListofClosedPaths = new list<list<TesselPoint*> *>;
3074 list<TesselPoint*> *connectedPath = NULL;
3075 list<TesselPoint*> *newPath = NULL;
3076 int count = 0;
3077
3078
3079 list<TesselPoint*>::iterator CircleRunner;
3080 list<TesselPoint*>::iterator CircleStart;
3081
3082 for(list<list<TesselPoint*> *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
3083 connectedPath = *ListRunner;
3084
3085 Log() << Verbose(2) << "INFO: Current path is " << connectedPath << "." << endl;
3086
3087 // go through list, look for reappearance of starting Point and count
3088 CircleStart = connectedPath->begin();
3089
3090 // go through list, look for reappearance of starting Point and create list
3091 list<TesselPoint*>::iterator Marker = CircleStart;
3092 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
3093 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
3094 // we have a closed circle from Marker to new Marker
3095 Log() << Verbose(3) << count+1 << ". closed path consists of: ";
3096 newPath = new list<TesselPoint*>;
3097 list<TesselPoint*>::iterator CircleSprinter = Marker;
3098 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
3099 newPath->push_back(*CircleSprinter);
3100 Log() << Verbose(0) << (**CircleSprinter) << " <-> ";
3101 }
3102 Log() << Verbose(0) << ".." << endl;
3103 count++;
3104 Marker = CircleRunner;
3105
3106 // add to list
3107 ListofClosedPaths->push_back(newPath);
3108 }
3109 }
3110 }
3111 Log() << Verbose(3) << "INFO: " << count << " closed additional path(s) have been created." << endl;
3112
3113 // delete list of paths
3114 while (!ListofPaths->empty()) {
3115 connectedPath = *(ListofPaths->begin());
3116 ListofPaths->remove(connectedPath);
3117 delete(connectedPath);
3118 }
3119 delete(ListofPaths);
3120
3121 // exit
3122 return ListofClosedPaths;
3123};
3124
3125
3126/** Gets all belonging triangles for a given BoundaryPointSet.
3127 * \param *out output stream for debugging
3128 * \param *Point BoundaryPoint
3129 * \return pointer to allocated list of triangles
3130 */
3131set<BoundaryTriangleSet*> *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
3132{
3133 set<BoundaryTriangleSet*> *connectedTriangles = new set<BoundaryTriangleSet*>;
3134
3135 if (Point == NULL) {
3136 eLog() << Verbose(1) << "Point given is NULL." << endl;
3137 } else {
3138 // go through its lines and insert all triangles
3139 for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
3140 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
3141 connectedTriangles->insert(TriangleRunner->second);
3142 }
3143 }
3144
3145 return connectedTriangles;
3146};
3147
3148
3149/** Removes a boundary point from the envelope while keeping it closed.
3150 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
3151 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
3152 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
3153 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
3154 * -# the surface is closed, when the path is empty
3155 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
3156 * \param *out output stream for debugging
3157 * \param *point point to be removed
3158 * \return volume added to the volume inside the tesselated surface by the removal
3159 */
3160double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point) {
3161 class BoundaryLineSet *line = NULL;
3162 class BoundaryTriangleSet *triangle = NULL;
3163 Vector OldPoint, NormalVector;
3164 double volume = 0;
3165 int count = 0;
3166
3167 if (point == NULL) {
3168 eLog() << Verbose(1) << "Cannot remove the point " << point << ", it's NULL!" << endl;
3169 return 0.;
3170 } else
3171 Log() << Verbose(2) << "Removing point " << *point << " from tesselated boundary ..." << endl;
3172
3173 // copy old location for the volume
3174 OldPoint.CopyVector(point->node->node);
3175
3176 // get list of connected points
3177 if (point->lines.empty()) {
3178 eLog() << Verbose(1) << "Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
3179 return 0.;
3180 }
3181
3182 list<list<TesselPoint*> *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
3183 list<TesselPoint*> *connectedPath = NULL;
3184
3185 // gather all triangles
3186 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3187 count+=LineRunner->second->triangles.size();
3188 map<class BoundaryTriangleSet *, int> Candidates;
3189 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3190 line = LineRunner->second;
3191 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3192 triangle = TriangleRunner->second;
3193 Candidates.insert( pair<class BoundaryTriangleSet *, int> (triangle, triangle->Nr) );
3194 }
3195 }
3196
3197 // remove all triangles
3198 count=0;
3199 NormalVector.Zero();
3200 for (map<class BoundaryTriangleSet *, int>::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3201 Log() << Verbose(3) << "INFO: Removing triangle " << *(Runner->first) << "." << endl;
3202 NormalVector.SubtractVector(&Runner->first->NormalVector); // has to point inward
3203 RemoveTesselationTriangle(Runner->first);
3204 count++;
3205 }
3206 Log() << Verbose(1) << count << " triangles were removed." << endl;
3207
3208 list<list<TesselPoint*> *>::iterator ListAdvance = ListOfClosedPaths->begin();
3209 list<list<TesselPoint*> *>::iterator ListRunner = ListAdvance;
3210 map<class BoundaryTriangleSet *, int>::iterator NumberRunner = Candidates.begin();
3211 list<TesselPoint*>::iterator StartNode, MiddleNode, EndNode;
3212 double angle;
3213 double smallestangle;
3214 Vector Point, Reference, OrthogonalVector;
3215 if (count > 2) { // less than three triangles, then nothing will be created
3216 class TesselPoint *TriangleCandidates[3];
3217 count = 0;
3218 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3219 if (ListAdvance != ListOfClosedPaths->end())
3220 ListAdvance++;
3221
3222 connectedPath = *ListRunner;
3223
3224 // re-create all triangles by going through connected points list
3225 list<class BoundaryLineSet *> NewLines;
3226 for (;!connectedPath->empty();) {
3227 // search middle node with widest angle to next neighbours
3228 EndNode = connectedPath->end();
3229 smallestangle = 0.;
3230 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3231 Log() << Verbose(3) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3232 // construct vectors to next and previous neighbour
3233 StartNode = MiddleNode;
3234 if (StartNode == connectedPath->begin())
3235 StartNode = connectedPath->end();
3236 StartNode--;
3237 //Log() << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
3238 Point.CopyVector((*StartNode)->node);
3239 Point.SubtractVector((*MiddleNode)->node);
3240 StartNode = MiddleNode;
3241 StartNode++;
3242 if (StartNode == connectedPath->end())
3243 StartNode = connectedPath->begin();
3244 //Log() << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
3245 Reference.CopyVector((*StartNode)->node);
3246 Reference.SubtractVector((*MiddleNode)->node);
3247 OrthogonalVector.CopyVector((*MiddleNode)->node);
3248 OrthogonalVector.SubtractVector(&OldPoint);
3249 OrthogonalVector.MakeNormalVector(&Reference);
3250 angle = GetAngle(Point, Reference, OrthogonalVector);
3251 //if (angle < M_PI) // no wrong-sided triangles, please?
3252 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3253 smallestangle = angle;
3254 EndNode = MiddleNode;
3255 }
3256 }
3257 MiddleNode = EndNode;
3258 if (MiddleNode == connectedPath->end()) {
3259 Log() << Verbose(1) << "CRITICAL: Could not find a smallest angle!" << endl;
3260 exit(255);
3261 }
3262 StartNode = MiddleNode;
3263 if (StartNode == connectedPath->begin())
3264 StartNode = connectedPath->end();
3265 StartNode--;
3266 EndNode++;
3267 if (EndNode == connectedPath->end())
3268 EndNode = connectedPath->begin();
3269 Log() << Verbose(4) << "INFO: StartNode is " << **StartNode << "." << endl;
3270 Log() << Verbose(4) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3271 Log() << Verbose(4) << "INFO: EndNode is " << **EndNode << "." << endl;
3272 Log() << Verbose(3) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
3273 TriangleCandidates[0] = *StartNode;
3274 TriangleCandidates[1] = *MiddleNode;
3275 TriangleCandidates[2] = *EndNode;
3276 triangle = GetPresentTriangle(TriangleCandidates);
3277 if (triangle != NULL) {
3278 eLog() << Verbose(2) << "New triangle already present, skipping!" << endl;
3279 StartNode++;
3280 MiddleNode++;
3281 EndNode++;
3282 if (StartNode == connectedPath->end())
3283 StartNode = connectedPath->begin();
3284 if (MiddleNode == connectedPath->end())
3285 MiddleNode = connectedPath->begin();
3286 if (EndNode == connectedPath->end())
3287 EndNode = connectedPath->begin();
3288 continue;
3289 }
3290 Log() << Verbose(5) << "Adding new triangle points."<< endl;
3291 AddTesselationPoint(*StartNode, 0);
3292 AddTesselationPoint(*MiddleNode, 1);
3293 AddTesselationPoint(*EndNode, 2);
3294 Log() << Verbose(5) << "Adding new triangle lines."<< endl;
3295 AddTesselationLine(TPS[0], TPS[1], 0);
3296 AddTesselationLine(TPS[0], TPS[2], 1);
3297 NewLines.push_back(BLS[1]);
3298 AddTesselationLine(TPS[1], TPS[2], 2);
3299 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3300 BTS->GetNormalVector(NormalVector);
3301 AddTesselationTriangle();
3302 // calculate volume summand as a general tetraeder
3303 volume += CalculateVolumeofGeneralTetraeder(*TPS[0]->node->node, *TPS[1]->node->node, *TPS[2]->node->node, OldPoint);
3304 // advance number
3305 count++;
3306
3307 // prepare nodes for next triangle
3308 StartNode = EndNode;
3309 Log() << Verbose(4) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
3310 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3311 if (connectedPath->size() == 2) { // we are done
3312 connectedPath->remove(*StartNode); // remove the start node
3313 connectedPath->remove(*EndNode); // remove the end node
3314 break;
3315 } else if (connectedPath->size() < 2) { // something's gone wrong!
3316 Log() << Verbose(1) << "CRITICAL: There are only two endpoints left!" << endl;
3317 exit(255);
3318 } else {
3319 MiddleNode = StartNode;
3320 MiddleNode++;
3321 if (MiddleNode == connectedPath->end())
3322 MiddleNode = connectedPath->begin();
3323 EndNode = MiddleNode;
3324 EndNode++;
3325 if (EndNode == connectedPath->end())
3326 EndNode = connectedPath->begin();
3327 }
3328 }
3329 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
3330 if (NewLines.size() > 1) {
3331 list<class BoundaryLineSet *>::iterator Candidate;
3332 class BoundaryLineSet *OtherBase = NULL;
3333 double tmp, maxgain;
3334 do {
3335 maxgain = 0;
3336 for(list<class BoundaryLineSet *>::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
3337 tmp = PickFarthestofTwoBaselines(*Runner);
3338 if (maxgain < tmp) {
3339 maxgain = tmp;
3340 Candidate = Runner;
3341 }
3342 }
3343 if (maxgain != 0) {
3344 volume += maxgain;
3345 Log() << Verbose(3) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
3346 OtherBase = FlipBaseline(*Candidate);
3347 NewLines.erase(Candidate);
3348 NewLines.push_back(OtherBase);
3349 }
3350 } while (maxgain != 0.);
3351 }
3352
3353 ListOfClosedPaths->remove(connectedPath);
3354 delete(connectedPath);
3355 }
3356 Log() << Verbose(1) << count << " triangles were created." << endl;
3357 } else {
3358 while (!ListOfClosedPaths->empty()) {
3359 ListRunner = ListOfClosedPaths->begin();
3360 connectedPath = *ListRunner;
3361 ListOfClosedPaths->remove(connectedPath);
3362 delete(connectedPath);
3363 }
3364 Log() << Verbose(1) << "No need to create any triangles." << endl;
3365 }
3366 delete(ListOfClosedPaths);
3367
3368 Log() << Verbose(1) << "Removed volume is " << volume << "." << endl;
3369
3370 return volume;
3371};
3372
3373
3374
3375/**
3376 * Finds triangles belonging to the three provided points.
3377 *
3378 * @param *Points[3] list, is expected to contain three points
3379 *
3380 * @return triangles which belong to the provided points, will be empty if there are none,
3381 * will usually be one, in case of degeneration, there will be two
3382 */
3383list<BoundaryTriangleSet*> *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
3384{
3385 list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
3386 LineMap::const_iterator FindLine;
3387 TriangleMap::const_iterator FindTriangle;
3388 class BoundaryPointSet *TrianglePoints[3];
3389
3390 for (int i = 0; i < 3; i++) {
3391 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->nr);
3392 if (FindPoint != PointsOnBoundary.end()) {
3393 TrianglePoints[i] = FindPoint->second;
3394 } else {
3395 TrianglePoints[i] = NULL;
3396 }
3397 }
3398
3399 // checks lines between the points in the Points for their adjacent triangles
3400 for (int i = 0; i < 3; i++) {
3401 if (TrianglePoints[i] != NULL) {
3402 for (int j = i+1; j < 3; j++) {
3403 if (TrianglePoints[j] != NULL) {
3404 for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr); // is a multimap!
3405 (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->nr);
3406 FindLine++) {
3407 for (FindTriangle = FindLine->second->triangles.begin();
3408 FindTriangle != FindLine->second->triangles.end();
3409 FindTriangle++) {
3410 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3411 result->push_back(FindTriangle->second);
3412 }
3413 }
3414 }
3415 // Is it sufficient to consider one of the triangle lines for this.
3416 return result;
3417 }
3418 }
3419 }
3420 }
3421
3422 return result;
3423}
3424
3425/**
3426 * Finds all degenerated lines within the tesselation structure.
3427 *
3428 * @return map of keys of degenerated line pairs, each line occurs twice
3429 * in the list, once as key and once as value
3430 */
3431map<int, int> * Tesselation::FindAllDegeneratedLines()
3432{
3433 map<int, class BoundaryLineSet *> AllLines;
3434 map<int, int> * DegeneratedLines = new map<int, int>;
3435
3436 // sanity check
3437 if (LinesOnBoundary.empty()) {
3438 Log() << Verbose(1) << "Warning: FindAllDegeneratedTriangles() was called without any tesselation structure.";
3439 return DegeneratedLines;
3440 }
3441
3442 LineMap::iterator LineRunner1;
3443 pair<LineMap::iterator, bool> tester;
3444 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
3445 tester = AllLines.insert( pair<int,BoundaryLineSet *> (LineRunner1->second->endpoints[0]->Nr, LineRunner1->second) );
3446 if ((!tester.second) && (tester.first->second->endpoints[1]->Nr == LineRunner1->second->endpoints[1]->Nr)) { // found degenerated line
3447 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, tester.first->second->Nr) );
3448 DegeneratedLines->insert ( pair<int, int> (tester.first->second->Nr, LineRunner1->second->Nr) );
3449 }
3450 }
3451
3452 AllLines.clear();
3453
3454 Log() << Verbose(1) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
3455 map<int,int>::iterator it;
3456 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++)
3457 Log() << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3458
3459 return DegeneratedLines;
3460}
3461
3462/**
3463 * Finds all degenerated triangles within the tesselation structure.
3464 *
3465 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
3466 * in the list, once as key and once as value
3467 */
3468map<int, int> * Tesselation::FindAllDegeneratedTriangles()
3469{
3470 map<int, int> * DegeneratedLines = FindAllDegeneratedLines();
3471 map<int, int> * DegeneratedTriangles = new map<int, int>;
3472
3473 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
3474 LineMap::iterator Liner;
3475 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
3476
3477 for (map<int, int>::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
3478 // run over both lines' triangles
3479 Liner = LinesOnBoundary.find(LineRunner->first);
3480 if (Liner != LinesOnBoundary.end())
3481 line1 = Liner->second;
3482 Liner = LinesOnBoundary.find(LineRunner->second);
3483 if (Liner != LinesOnBoundary.end())
3484 line2 = Liner->second;
3485 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
3486 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
3487 if ((TriangleRunner1->second != TriangleRunner2->second)
3488 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
3489 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
3490 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
3491 }
3492 }
3493 }
3494 }
3495 delete(DegeneratedLines);
3496
3497 Log() << Verbose(1) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
3498 map<int,int>::iterator it;
3499 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
3500 Log() << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3501
3502 return DegeneratedTriangles;
3503}
3504
3505/**
3506 * Purges degenerated triangles from the tesselation structure if they are not
3507 * necessary to keep a single point within the structure.
3508 */
3509void Tesselation::RemoveDegeneratedTriangles()
3510{
3511 map<int, int> * DegeneratedTriangles = FindAllDegeneratedTriangles();
3512 TriangleMap::iterator finder;
3513 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
3514 int count = 0;
3515
3516 Log() << Verbose(1) << "Begin of RemoveDegeneratedTriangles" << endl;
3517
3518 for (map<int, int>::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
3519 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
3520 ) {
3521 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
3522 if (finder != TrianglesOnBoundary.end())
3523 triangle = finder->second;
3524 else
3525 break;
3526 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
3527 if (finder != TrianglesOnBoundary.end())
3528 partnerTriangle = finder->second;
3529 else
3530 break;
3531
3532 bool trianglesShareLine = false;
3533 for (int i = 0; i < 3; ++i)
3534 for (int j = 0; j < 3; ++j)
3535 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
3536
3537 if (trianglesShareLine
3538 && (triangle->endpoints[1]->LinesCount > 2)
3539 && (triangle->endpoints[2]->LinesCount > 2)
3540 && (triangle->endpoints[0]->LinesCount > 2)
3541 ) {
3542 // check whether we have to fix lines
3543 BoundaryTriangleSet *Othertriangle = NULL;
3544 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
3545 TriangleMap::iterator TriangleRunner;
3546 for (int i = 0; i < 3; ++i)
3547 for (int j = 0; j < 3; ++j)
3548 if (triangle->lines[i] != partnerTriangle->lines[j]) {
3549 // get the other two triangles
3550 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
3551 if (TriangleRunner->second != triangle) {
3552 Othertriangle = TriangleRunner->second;
3553 }
3554 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
3555 if (TriangleRunner->second != partnerTriangle) {
3556 OtherpartnerTriangle = TriangleRunner->second;
3557 }
3558 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
3559 // the line of triangle receives the degenerated ones
3560 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
3561 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
3562 for (int k=0;k<3;k++)
3563 if (triangle->lines[i] == Othertriangle->lines[k]) {
3564 Othertriangle->lines[k] = partnerTriangle->lines[j];
3565 break;
3566 }
3567 // the line of partnerTriangle receives the non-degenerated ones
3568 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
3569 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
3570 partnerTriangle->lines[j] = triangle->lines[i];
3571 }
3572
3573 // erase the pair
3574 count += (int) DegeneratedTriangles->erase(triangle->Nr);
3575 Log() << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
3576 RemoveTesselationTriangle(triangle);
3577 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
3578 Log() << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
3579 RemoveTesselationTriangle(partnerTriangle);
3580 } else {
3581 Log() << Verbose(1) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
3582 << " and its partner " << *partnerTriangle << " because it is essential for at"
3583 << " least one of the endpoints to be kept in the tesselation structure." << endl;
3584 }
3585 }
3586 delete(DegeneratedTriangles);
3587 if (count > 0)
3588 LastTriangle = NULL;
3589
3590 Log() << Verbose(1) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
3591 Log() << Verbose(1) << "End of RemoveDegeneratedTriangles" << endl;
3592}
3593
3594/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
3595 * We look for the closest point on the boundary, we look through its connected boundary lines and
3596 * seek the one with the minimum angle between its center point and the new point and this base line.
3597 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
3598 * \param *out output stream for debugging
3599 * \param *point point to add
3600 * \param *LC Linked Cell structure to find nearest point
3601 */
3602void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC)
3603{
3604 Log() << Verbose(2) << "Begin of AddBoundaryPointByDegeneratedTriangle" << endl;
3605
3606 // find nearest boundary point
3607 class TesselPoint *BackupPoint = NULL;
3608 class TesselPoint *NearestPoint = FindClosestPoint(point->node, BackupPoint, LC);
3609 class BoundaryPointSet *NearestBoundaryPoint = NULL;
3610 PointMap::iterator PointRunner;
3611
3612 if (NearestPoint == point)
3613 NearestPoint = BackupPoint;
3614 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
3615 if (PointRunner != PointsOnBoundary.end()) {
3616 NearestBoundaryPoint = PointRunner->second;
3617 } else {
3618 eLog() << Verbose(1) << "I cannot find the boundary point." << endl;
3619 return;
3620 }
3621 Log() << Verbose(2) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
3622
3623 // go through its lines and find the best one to split
3624 Vector CenterToPoint;
3625 Vector BaseLine;
3626 double angle, BestAngle = 0.;
3627 class BoundaryLineSet *BestLine = NULL;
3628 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
3629 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
3630 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
3631 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
3632 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
3633 CenterToPoint.Scale(0.5);
3634 CenterToPoint.SubtractVector(point->node);
3635 angle = CenterToPoint.Angle(&BaseLine);
3636 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
3637 BestAngle = angle;
3638 BestLine = Runner->second;
3639 }
3640 }
3641
3642 // remove one triangle from the chosen line
3643 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
3644 BestLine->triangles.erase(TempTriangle->Nr);
3645 int nr = -1;
3646 for (int i=0;i<3; i++) {
3647 if (TempTriangle->lines[i] == BestLine) {
3648 nr = i;
3649 break;
3650 }
3651 }
3652
3653 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
3654 Log() << Verbose(5) << "Adding new triangle points."<< endl;
3655 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3656 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3657 AddTesselationPoint(point, 2);
3658 Log() << Verbose(5) << "Adding new triangle lines."<< endl;
3659 AddTesselationLine(TPS[0], TPS[1], 0);
3660 AddTesselationLine(TPS[0], TPS[2], 1);
3661 AddTesselationLine(TPS[1], TPS[2], 2);
3662 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3663 BTS->GetNormalVector(TempTriangle->NormalVector);
3664 BTS->NormalVector.Scale(-1.);
3665 Log() << Verbose(3) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
3666 AddTesselationTriangle();
3667
3668 // create other side of this triangle and close both new sides of the first created triangle
3669 Log() << Verbose(5) << "Adding new triangle points."<< endl;
3670 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3671 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3672 AddTesselationPoint(point, 2);
3673 Log() << Verbose(5) << "Adding new triangle lines."<< endl;
3674 AddTesselationLine(TPS[0], TPS[1], 0);
3675 AddTesselationLine(TPS[0], TPS[2], 1);
3676 AddTesselationLine(TPS[1], TPS[2], 2);
3677 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3678 BTS->GetNormalVector(TempTriangle->NormalVector);
3679 Log() << Verbose(3) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
3680 AddTesselationTriangle();
3681
3682 // add removed triangle to the last open line of the second triangle
3683 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
3684 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
3685 if (BestLine == BTS->lines[i]){
3686 Log() << Verbose(1) << "CRITICAL: BestLine is same as found line, something's wrong here!" << endl;
3687 exit(255);
3688 }
3689 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
3690 TempTriangle->lines[nr] = BTS->lines[i];
3691 break;
3692 }
3693 }
3694
3695 // exit
3696 Log() << Verbose(2) << "End of AddBoundaryPointByDegeneratedTriangle" << endl;
3697};
3698
3699/** Writes the envelope to file.
3700 * \param *out otuput stream for debugging
3701 * \param *filename basename of output file
3702 * \param *cloud PointCloud structure with all nodes
3703 */
3704void Tesselation::Output(const char *filename, const PointCloud * const cloud)
3705{
3706 ofstream *tempstream = NULL;
3707 string NameofTempFile;
3708 char NumberName[255];
3709
3710 if (LastTriangle != NULL) {
3711 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
3712 if (DoTecplotOutput) {
3713 string NameofTempFile(filename);
3714 NameofTempFile.append(NumberName);
3715 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3716 NameofTempFile.erase(npos, 1);
3717 NameofTempFile.append(TecplotSuffix);
3718 Log() << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3719 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3720 WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
3721 tempstream->close();
3722 tempstream->flush();
3723 delete(tempstream);
3724 }
3725
3726 if (DoRaster3DOutput) {
3727 string NameofTempFile(filename);
3728 NameofTempFile.append(NumberName);
3729 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3730 NameofTempFile.erase(npos, 1);
3731 NameofTempFile.append(Raster3DSuffix);
3732 Log() << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3733 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3734 WriteRaster3dFile(tempstream, this, cloud);
3735 IncludeSphereinRaster3D(tempstream, this, cloud);
3736 tempstream->close();
3737 tempstream->flush();
3738 delete(tempstream);
3739 }
3740 }
3741 if (DoTecplotOutput || DoRaster3DOutput)
3742 TriangleFilesWritten++;
3743};
Note: See TracBrowser for help on using the repository browser.