source: src/tesselation.cpp@ 4fc93f

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 4fc93f was 27bd2f, checked in by Frederik Heber <heber@…>, 16 years ago

BUGFIX: testcase heptan was not correctly tesselated, as edges of a (degenerated) polygon were not correctly created.

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