source: src/tesselation.cpp@ fcad4b

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 Candidate_v1.7.0 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 fcad4b was fcad4b, checked in by Frederik Heber <heber@…>, 16 years ago

InsideOutside unit test of tesselation is working correctly.

  • FIX: BoundaryTriangleSet::GetIntersectionInsideTriangle() - don't need helper, just check whether CrossPoint is returned (and true) for all of the three sides.
  • FIX: Tesselation::IsInnerPoint() - projection onto plane and stuff was nonsense, just take the Point ans Intersection which is on the plane anyway.
  • FIX: Vector::GetIntersectionOfTwoLinesOnPlane() - coefficient MUST be zero (then vectors are coplanar), but parallelity check was missing. Also, we have to check whether s is in [0,1] in order to see whether we are inside the triangle side or outside.

Signed-off-by: Frederik Heber <heber@tabletINS.(none)>

  • Property mode set to 100644
File size: 202.0 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 through which the line defined by \a *MolCenter and \a *x crosses.
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 Log() << Verbose(1) << "INFO: Triangle is " << *this << "." << endl;
414 Log() << Verbose(1) << "INFO: Line is from " << *MolCenter << " to " << *x << "." << endl;
415 Log() << Verbose(1) << "INFO: Intersection is " << *Intersection << "." << endl;
416
417 // Calculate cross point between one baseline and the line from the third endpoint to intersection
418 int i=0;
419 do {
420 if (CrossPoint.GetIntersectionOfTwoLinesOnPlane(endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection, &NormalVector)) {
421 CrossPoint.SubtractVector(endpoints[i%3]->node->node); // cross point was returned as absolute vector
422 i++;
423 } else
424 break;
425 } while (i<3);
426 if (i==3) {
427 Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " inside of triangle." << endl;
428 return true;
429 } else {
430 Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " outside of triangle." << endl;
431 return false;
432 }
433};
434
435/** Checks whether lines is any of the three boundary lines this triangle contains.
436 * \param *line line to test
437 * \return true - line is of the triangle, false - is not
438 */
439bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
440{
441 Info FunctionInfo(__func__);
442 for(int i=0;i<3;i++)
443 if (line == lines[i])
444 return true;
445 return false;
446};
447
448/** Checks whether point is any of the three endpoints this triangle contains.
449 * \param *point point to test
450 * \return true - point is of the triangle, false - is not
451 */
452bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
453{
454 Info FunctionInfo(__func__);
455 for(int i=0;i<3;i++)
456 if (point == endpoints[i])
457 return true;
458 return false;
459};
460
461/** Checks whether point is any of the three endpoints this triangle contains.
462 * \param *point TesselPoint to test
463 * \return true - point is of the triangle, false - is not
464 */
465bool BoundaryTriangleSet::ContainsBoundaryPoint(class TesselPoint *point)
466{
467 Info FunctionInfo(__func__);
468 for(int i=0;i<3;i++)
469 if (point == endpoints[i]->node)
470 return true;
471 return false;
472};
473
474/** Checks whether three given \a *Points coincide with triangle's endpoints.
475 * \param *Points[3] pointer to BoundaryPointSet
476 * \return true - is the very triangle, false - is not
477 */
478bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
479{
480 Info FunctionInfo(__func__);
481 Log() << Verbose(1) << "INFO: Checking " << Points[0] << "," << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << "." << endl;
482 return (((endpoints[0] == Points[0])
483 || (endpoints[0] == Points[1])
484 || (endpoints[0] == Points[2])
485 ) && (
486 (endpoints[1] == Points[0])
487 || (endpoints[1] == Points[1])
488 || (endpoints[1] == Points[2])
489 ) && (
490 (endpoints[2] == Points[0])
491 || (endpoints[2] == Points[1])
492 || (endpoints[2] == Points[2])
493
494 ));
495};
496
497/** Checks whether three given \a *Points coincide with triangle's endpoints.
498 * \param *Points[3] pointer to BoundaryPointSet
499 * \return true - is the very triangle, false - is not
500 */
501bool BoundaryTriangleSet::IsPresentTupel(class BoundaryTriangleSet *T)
502{
503 Info FunctionInfo(__func__);
504 return (((endpoints[0] == T->endpoints[0])
505 || (endpoints[0] == T->endpoints[1])
506 || (endpoints[0] == T->endpoints[2])
507 ) && (
508 (endpoints[1] == T->endpoints[0])
509 || (endpoints[1] == T->endpoints[1])
510 || (endpoints[1] == T->endpoints[2])
511 ) && (
512 (endpoints[2] == T->endpoints[0])
513 || (endpoints[2] == T->endpoints[1])
514 || (endpoints[2] == T->endpoints[2])
515
516 ));
517};
518
519/** Returns the endpoint which is not contained in the given \a *line.
520 * \param *line baseline defining two endpoints
521 * \return pointer third endpoint or NULL if line does not belong to triangle.
522 */
523class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(class BoundaryLineSet *line)
524{
525 Info FunctionInfo(__func__);
526 // sanity check
527 if (!ContainsBoundaryLine(line))
528 return NULL;
529 for(int i=0;i<3;i++)
530 if (!line->ContainsBoundaryPoint(endpoints[i]))
531 return endpoints[i];
532 // actually, that' impossible :)
533 return NULL;
534};
535
536/** Calculates the center point of the triangle.
537 * Is third of the sum of all endpoints.
538 * \param *center central point on return.
539 */
540void BoundaryTriangleSet::GetCenter(Vector *center)
541{
542 Info FunctionInfo(__func__);
543 center->Zero();
544 for(int i=0;i<3;i++)
545 center->AddVector(endpoints[i]->node->node);
546 center->Scale(1./3.);
547}
548
549/** output operator for BoundaryTriangleSet.
550 * \param &ost output stream
551 * \param &a boundary triangle
552 */
553ostream &operator <<(ostream &ost, const BoundaryTriangleSet &a)
554{
555 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << "," << a.endpoints[1]->node->Name << "," << a.endpoints[2]->node->Name << "]";
556// ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
557// << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
558 return ost;
559};
560
561// ======================================== Polygons on Boundary =================================
562
563/** Constructor for BoundaryPolygonSet.
564 */
565BoundaryPolygonSet::BoundaryPolygonSet() :
566 Nr(-1)
567{
568 Info FunctionInfo(__func__);
569};
570
571/** Destructor of BoundaryPolygonSet.
572 * Just clears endpoints.
573 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
574 */
575BoundaryPolygonSet::~BoundaryPolygonSet()
576{
577 Info FunctionInfo(__func__);
578 endpoints.clear();
579 Log() << Verbose(1) << "Erasing polygon Nr." << Nr << " itself." << endl;
580};
581
582/** Calculates the normal vector for this triangle.
583 * Is made unique by comparison with \a OtherVector to point in the other direction.
584 * \param &OtherVector direction vector to make normal vector unique.
585 * \return allocated vector in normal direction
586 */
587Vector * BoundaryPolygonSet::GetNormalVector(const Vector &OtherVector) const
588{
589 Info FunctionInfo(__func__);
590 // get normal vector
591 Vector TemporaryNormal;
592 Vector *TotalNormal = new Vector;
593 PointSet::const_iterator Runner[3];
594 for (int i=0;i<3; i++) {
595 Runner[i] = endpoints.begin();
596 for (int j = 0; j<i; j++) { // go as much further
597 Runner[i]++;
598 if (Runner[i] == endpoints.end()) {
599 eLog() << Verbose(0) << "There are less than three endpoints in the polygon!" << endl;
600 performCriticalExit();
601 }
602 }
603 }
604 TotalNormal->Zero();
605 int counter=0;
606 for (; Runner[2] != endpoints.end(); ) {
607 TemporaryNormal.MakeNormalVector((*Runner[0])->node->node, (*Runner[1])->node->node, (*Runner[2])->node->node);
608 for (int i=0;i<3;i++) // increase each of them
609 Runner[i]++;
610 TotalNormal->AddVector(&TemporaryNormal);
611 }
612 TotalNormal->Scale(1./(double)counter);
613
614 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
615 if (TotalNormal->ScalarProduct(&OtherVector) > 0.)
616 TotalNormal->Scale(-1.);
617 Log() << Verbose(1) << "Normal Vector is " << *TotalNormal << "." << endl;
618
619 return TotalNormal;
620};
621
622/** Calculates the center point of the triangle.
623 * Is third of the sum of all endpoints.
624 * \param *center central point on return.
625 */
626void BoundaryPolygonSet::GetCenter(Vector * const center) const
627{
628 Info FunctionInfo(__func__);
629 center->Zero();
630 int counter = 0;
631 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
632 center->AddVector((*Runner)->node->node);
633 counter++;
634 }
635 center->Scale(1./(double)counter);
636 Log() << Verbose(1) << "Center is at " << *center << "." << endl;
637}
638
639/** Checks whether the polygons contains all three endpoints of the triangle.
640 * \param *triangle triangle to test
641 * \return true - triangle is contained polygon, false - is not
642 */
643bool BoundaryPolygonSet::ContainsBoundaryTriangle(const BoundaryTriangleSet * const triangle) const
644{
645 Info FunctionInfo(__func__);
646 return ContainsPresentTupel(triangle->endpoints, 3);
647};
648
649/** Checks whether the polygons contains both endpoints of the line.
650 * \param *line line to test
651 * \return true - line is of the triangle, false - is not
652 */
653bool BoundaryPolygonSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
654{
655 Info FunctionInfo(__func__);
656 return ContainsPresentTupel(line->endpoints, 2);
657};
658
659/** Checks whether point is any of the three endpoints this triangle contains.
660 * \param *point point to test
661 * \return true - point is of the triangle, false - is not
662 */
663bool BoundaryPolygonSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
664{
665 Info FunctionInfo(__func__);
666 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
667 Log() << Verbose(0) << "Checking against " << **Runner << endl;
668 if (point == (*Runner)) {
669 Log() << Verbose(0) << " Contained." << endl;
670 return true;
671 }
672 }
673 Log() << Verbose(0) << " Not contained." << endl;
674 return false;
675};
676
677/** Checks whether point is any of the three endpoints this triangle contains.
678 * \param *point TesselPoint to test
679 * \return true - point is of the triangle, false - is not
680 */
681bool BoundaryPolygonSet::ContainsBoundaryPoint(const TesselPoint * const point) const
682{
683 Info FunctionInfo(__func__);
684 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
685 if (point == (*Runner)->node) {
686 Log() << Verbose(0) << " Contained." << endl;
687 return true;
688 }
689 Log() << Verbose(0) << " Not contained." << endl;
690 return false;
691};
692
693/** Checks whether given array of \a *Points coincide with polygons's endpoints.
694 * \param **Points pointer to an array of BoundaryPointSet
695 * \param dim dimension of array
696 * \return true - set of points is contained in polygon, false - is not
697 */
698bool BoundaryPolygonSet::ContainsPresentTupel(const BoundaryPointSet * const * Points, const int dim) const
699{
700 Info FunctionInfo(__func__);
701 int counter = 0;
702 Log() << Verbose(1) << "Polygon is " << *this << endl;
703 for(int i=0;i<dim;i++) {
704 Log() << Verbose(1) << " Testing endpoint " << *Points[i] << endl;
705 if (ContainsBoundaryPoint(Points[i])) {
706 counter++;
707 }
708 }
709
710 if (counter == dim)
711 return true;
712 else
713 return false;
714};
715
716/** Checks whether given PointList coincide with polygons's endpoints.
717 * \param &endpoints PointList
718 * \return true - set of points is contained in polygon, false - is not
719 */
720bool BoundaryPolygonSet::ContainsPresentTupel(const PointSet &endpoints) const
721{
722 Info FunctionInfo(__func__);
723 size_t counter = 0;
724 Log() << Verbose(1) << "Polygon is " << *this << endl;
725 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++) {
726 Log() << Verbose(1) << " Testing endpoint " << **Runner << endl;
727 if (ContainsBoundaryPoint(*Runner))
728 counter++;
729 }
730
731 if (counter == endpoints.size())
732 return true;
733 else
734 return false;
735};
736
737/** Checks whether given set of \a *Points coincide with polygons's endpoints.
738 * \param *P pointer to BoundaryPolygonSet
739 * \return true - is the very triangle, false - is not
740 */
741bool BoundaryPolygonSet::ContainsPresentTupel(const BoundaryPolygonSet * const P) const
742{
743 return ContainsPresentTupel((const PointSet)P->endpoints);
744};
745
746/** Gathers all the endpoints' triangles in a unique set.
747 * \return set of all triangles
748 */
749TriangleSet * BoundaryPolygonSet::GetAllContainedTrianglesFromEndpoints() const
750{
751 Info FunctionInfo(__func__);
752 pair <TriangleSet::iterator, bool> Tester;
753 TriangleSet *triangles = new TriangleSet;
754
755 for(PointSet::const_iterator Runner = endpoints.begin(); Runner != endpoints.end(); Runner++)
756 for(LineMap::const_iterator Walker = (*Runner)->lines.begin(); Walker != (*Runner)->lines.end(); Walker++)
757 for(TriangleMap::const_iterator Sprinter = (Walker->second)->triangles.begin(); Sprinter != (Walker->second)->triangles.end(); Sprinter++) {
758 //Log() << Verbose(0) << " Testing triangle " << *(Sprinter->second) << endl;
759 if (ContainsBoundaryTriangle(Sprinter->second)) {
760 Tester = triangles->insert(Sprinter->second);
761 if (Tester.second)
762 Log() << Verbose(0) << "Adding triangle " << *(Sprinter->second) << endl;
763 }
764 }
765
766 Log() << Verbose(1) << "The Polygon of " << endpoints.size() << " endpoints has " << triangles->size() << " unique triangles in total." << endl;
767 return triangles;
768};
769
770/** Fills the endpoints of this polygon from the triangles attached to \a *line.
771 * \param *line lines with triangles attached
772 * \return true - polygon contains endpoints, false - line was NULL
773 */
774bool BoundaryPolygonSet::FillPolygonFromTrianglesOfLine(const BoundaryLineSet * const line)
775{
776 Info FunctionInfo(__func__);
777 pair <PointSet::iterator, bool> Tester;
778 if (line == NULL)
779 return false;
780 Log() << Verbose(1) << "Filling polygon from line " << *line << endl;
781 for(TriangleMap::const_iterator Runner = line->triangles.begin(); Runner != line->triangles.end(); Runner++) {
782 for (int i=0;i<3;i++) {
783 Tester = endpoints.insert((Runner->second)->endpoints[i]);
784 if (Tester.second)
785 Log() << Verbose(1) << " Inserting endpoint " << *((Runner->second)->endpoints[i]) << endl;
786 }
787 }
788
789 return true;
790};
791
792/** output operator for BoundaryPolygonSet.
793 * \param &ost output stream
794 * \param &a boundary polygon
795 */
796ostream &operator <<(ostream &ost, const BoundaryPolygonSet &a)
797{
798 ost << "[" << a.Nr << "|";
799 for(PointSet::const_iterator Runner = a.endpoints.begin(); Runner != a.endpoints.end();) {
800 ost << (*Runner)->node->Name;
801 Runner++;
802 if (Runner != a.endpoints.end())
803 ost << ",";
804 }
805 ost<< "]";
806 return ost;
807};
808
809// =========================================================== class TESSELPOINT ===========================================
810
811/** Constructor of class TesselPoint.
812 */
813TesselPoint::TesselPoint()
814{
815 Info FunctionInfo(__func__);
816 node = NULL;
817 nr = -1;
818 Name = NULL;
819};
820
821/** Destructor for class TesselPoint.
822 */
823TesselPoint::~TesselPoint()
824{
825 Info FunctionInfo(__func__);
826};
827
828/** Prints LCNode to screen.
829 */
830ostream & operator << (ostream &ost, const TesselPoint &a)
831{
832 ost << "[" << (a.Name) << "|" << a.Name << " at " << *a.node << "]";
833 return ost;
834};
835
836/** Prints LCNode to screen.
837 */
838ostream & TesselPoint::operator << (ostream &ost)
839{
840 Info FunctionInfo(__func__);
841 ost << "[" << (nr) << "|" << this << "]";
842 return ost;
843};
844
845
846// =========================================================== class POINTCLOUD ============================================
847
848/** Constructor of class PointCloud.
849 */
850PointCloud::PointCloud()
851{
852 Info FunctionInfo(__func__);
853};
854
855/** Destructor for class PointCloud.
856 */
857PointCloud::~PointCloud()
858{
859 Info FunctionInfo(__func__);
860};
861
862// ============================ CandidateForTesselation =============================
863
864/** Constructor of class CandidateForTesselation.
865 */
866CandidateForTesselation::CandidateForTesselation (BoundaryLineSet* line) :
867 BaseLine(line),
868 ShortestAngle(2.*M_PI),
869 OtherShortestAngle(2.*M_PI)
870{
871 Info FunctionInfo(__func__);
872};
873
874
875/** Constructor of class CandidateForTesselation.
876 */
877CandidateForTesselation::CandidateForTesselation (TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) :
878 BaseLine(line),
879 ShortestAngle(2.*M_PI),
880 OtherShortestAngle(2.*M_PI)
881{
882 Info FunctionInfo(__func__);
883 OptCenter.CopyVector(&OptCandidateCenter);
884 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
885};
886
887/** Destructor for class CandidateForTesselation.
888 */
889CandidateForTesselation::~CandidateForTesselation() {
890 BaseLine = NULL;
891};
892
893/** output operator for CandidateForTesselation.
894 * \param &ost output stream
895 * \param &a boundary line
896 */
897ostream & operator <<(ostream &ost, const CandidateForTesselation &a)
898{
899 ost << "[" << a.BaseLine->Nr << "|" << a.BaseLine->endpoints[0]->node->Name << "," << a.BaseLine->endpoints[1]->node->Name << "] with ";
900 if (a.pointlist.empty())
901 ost << "no candidate.";
902 else {
903 ost << "candidate";
904 if (a.pointlist.size() != 1)
905 ost << "s ";
906 else
907 ost << " ";
908 for (TesselPointList::const_iterator Runner = a.pointlist.begin(); Runner != a.pointlist.end(); Runner++)
909 ost << *(*Runner) << " ";
910 ost << " at angle " << (a.ShortestAngle)<< ".";
911 }
912
913 return ost;
914};
915
916
917// =========================================================== class TESSELATION ===========================================
918
919/** Constructor of class Tesselation.
920 */
921Tesselation::Tesselation() :
922 PointsOnBoundaryCount(0),
923 LinesOnBoundaryCount(0),
924 TrianglesOnBoundaryCount(0),
925 LastTriangle(NULL),
926 TriangleFilesWritten(0),
927 InternalPointer(PointsOnBoundary.begin())
928{
929 Info FunctionInfo(__func__);
930}
931;
932
933/** Destructor of class Tesselation.
934 * We have to free all points, lines and triangles.
935 */
936Tesselation::~Tesselation()
937{
938 Info FunctionInfo(__func__);
939 Log() << Verbose(0) << "Free'ing TesselStruct ... " << endl;
940 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
941 if (runner->second != NULL) {
942 delete (runner->second);
943 runner->second = NULL;
944 } else
945 eLog() << Verbose(1) << "The triangle " << runner->first << " has already been free'd." << endl;
946 }
947 Log() << Verbose(0) << "This envelope was written to file " << TriangleFilesWritten << " times(s)." << endl;
948}
949;
950
951/** PointCloud implementation of GetCenter
952 * Uses PointsOnBoundary and STL stuff.
953 */
954Vector * Tesselation::GetCenter(ofstream *out) const
955{
956 Info FunctionInfo(__func__);
957 Vector *Center = new Vector(0.,0.,0.);
958 int num=0;
959 for (GoToFirst(); (!IsEnd()); GoToNext()) {
960 Center->AddVector(GetPoint()->node);
961 num++;
962 }
963 Center->Scale(1./num);
964 return Center;
965};
966
967/** PointCloud implementation of GoPoint
968 * Uses PointsOnBoundary and STL stuff.
969 */
970TesselPoint * Tesselation::GetPoint() const
971{
972 Info FunctionInfo(__func__);
973 return (InternalPointer->second->node);
974};
975
976/** PointCloud implementation of GetTerminalPoint.
977 * Uses PointsOnBoundary and STL stuff.
978 */
979TesselPoint * Tesselation::GetTerminalPoint() const
980{
981 Info FunctionInfo(__func__);
982 PointMap::const_iterator Runner = PointsOnBoundary.end();
983 Runner--;
984 return (Runner->second->node);
985};
986
987/** PointCloud implementation of GoToNext.
988 * Uses PointsOnBoundary and STL stuff.
989 */
990void Tesselation::GoToNext() const
991{
992 Info FunctionInfo(__func__);
993 if (InternalPointer != PointsOnBoundary.end())
994 InternalPointer++;
995};
996
997/** PointCloud implementation of GoToPrevious.
998 * Uses PointsOnBoundary and STL stuff.
999 */
1000void Tesselation::GoToPrevious() const
1001{
1002 Info FunctionInfo(__func__);
1003 if (InternalPointer != PointsOnBoundary.begin())
1004 InternalPointer--;
1005};
1006
1007/** PointCloud implementation of GoToFirst.
1008 * Uses PointsOnBoundary and STL stuff.
1009 */
1010void Tesselation::GoToFirst() const
1011{
1012 Info FunctionInfo(__func__);
1013 InternalPointer = PointsOnBoundary.begin();
1014};
1015
1016/** PointCloud implementation of GoToLast.
1017 * Uses PointsOnBoundary and STL stuff.
1018 */
1019void Tesselation::GoToLast() const
1020{
1021 Info FunctionInfo(__func__);
1022 InternalPointer = PointsOnBoundary.end();
1023 InternalPointer--;
1024};
1025
1026/** PointCloud implementation of IsEmpty.
1027 * Uses PointsOnBoundary and STL stuff.
1028 */
1029bool Tesselation::IsEmpty() const
1030{
1031 Info FunctionInfo(__func__);
1032 return (PointsOnBoundary.empty());
1033};
1034
1035/** PointCloud implementation of IsLast.
1036 * Uses PointsOnBoundary and STL stuff.
1037 */
1038bool Tesselation::IsEnd() const
1039{
1040 Info FunctionInfo(__func__);
1041 return (InternalPointer == PointsOnBoundary.end());
1042};
1043
1044
1045/** Gueses first starting triangle of the convex envelope.
1046 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
1047 * \param *out output stream for debugging
1048 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
1049 */
1050void
1051Tesselation::GuessStartingTriangle()
1052{
1053 Info FunctionInfo(__func__);
1054 // 4b. create a starting triangle
1055 // 4b1. create all distances
1056 DistanceMultiMap DistanceMMap;
1057 double distance, tmp;
1058 Vector PlaneVector, TrialVector;
1059 PointMap::iterator A, B, C; // three nodes of the first triangle
1060 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
1061
1062 // with A chosen, take each pair B,C and sort
1063 if (A != PointsOnBoundary.end())
1064 {
1065 B = A;
1066 B++;
1067 for (; B != PointsOnBoundary.end(); B++)
1068 {
1069 C = B;
1070 C++;
1071 for (; C != PointsOnBoundary.end(); C++)
1072 {
1073 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
1074 distance = tmp * tmp;
1075 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
1076 distance += tmp * tmp;
1077 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
1078 distance += tmp * tmp;
1079 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
1080 }
1081 }
1082 }
1083 // // listing distances
1084 // Log() << Verbose(1) << "Listing DistanceMMap:";
1085 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
1086 // Log() << Verbose(0) << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
1087 // }
1088 // Log() << Verbose(0) << endl;
1089 // 4b2. pick three baselines forming a triangle
1090 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1091 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
1092 for (; baseline != DistanceMMap.end(); baseline++)
1093 {
1094 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
1095 // 2. next, we have to check whether all points reside on only one side of the triangle
1096 // 3. construct plane vector
1097 PlaneVector.MakeNormalVector(A->second->node->node,
1098 baseline->second.first->second->node->node,
1099 baseline->second.second->second->node->node);
1100 Log() << Verbose(2) << "Plane vector of candidate triangle is " << PlaneVector << endl;
1101 // 4. loop over all points
1102 double sign = 0.;
1103 PointMap::iterator checker = PointsOnBoundary.begin();
1104 for (; checker != PointsOnBoundary.end(); checker++)
1105 {
1106 // (neglecting A,B,C)
1107 if ((checker == A) || (checker == baseline->second.first) || (checker
1108 == baseline->second.second))
1109 continue;
1110 // 4a. project onto plane vector
1111 TrialVector.CopyVector(checker->second->node->node);
1112 TrialVector.SubtractVector(A->second->node->node);
1113 distance = TrialVector.ScalarProduct(&PlaneVector);
1114 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
1115 continue;
1116 Log() << Verbose(2) << "Projection of " << checker->second->node->Name << " yields distance of " << distance << "." << endl;
1117 tmp = distance / fabs(distance);
1118 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
1119 if ((sign != 0) && (tmp != sign))
1120 {
1121 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
1122 Log() << Verbose(2) << "Current candidates: "
1123 << A->second->node->Name << ","
1124 << baseline->second.first->second->node->Name << ","
1125 << baseline->second.second->second->node->Name << " leaves "
1126 << checker->second->node->Name << " outside the convex hull."
1127 << endl;
1128 break;
1129 }
1130 else
1131 { // note the sign for later
1132 Log() << Verbose(2) << "Current candidates: "
1133 << A->second->node->Name << ","
1134 << baseline->second.first->second->node->Name << ","
1135 << baseline->second.second->second->node->Name << " leave "
1136 << checker->second->node->Name << " inside the convex hull."
1137 << endl;
1138 sign = tmp;
1139 }
1140 // 4d. Check whether the point is inside the triangle (check distance to each node
1141 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
1142 int innerpoint = 0;
1143 if ((tmp < A->second->node->node->DistanceSquared(
1144 baseline->second.first->second->node->node)) && (tmp
1145 < A->second->node->node->DistanceSquared(
1146 baseline->second.second->second->node->node)))
1147 innerpoint++;
1148 tmp = checker->second->node->node->DistanceSquared(
1149 baseline->second.first->second->node->node);
1150 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
1151 A->second->node->node)) && (tmp
1152 < baseline->second.first->second->node->node->DistanceSquared(
1153 baseline->second.second->second->node->node)))
1154 innerpoint++;
1155 tmp = checker->second->node->node->DistanceSquared(
1156 baseline->second.second->second->node->node);
1157 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
1158 baseline->second.first->second->node->node)) && (tmp
1159 < baseline->second.second->second->node->node->DistanceSquared(
1160 A->second->node->node)))
1161 innerpoint++;
1162 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
1163 if (innerpoint == 3)
1164 break;
1165 }
1166 // 5. come this far, all on same side? Then break 1. loop and construct triangle
1167 if (checker == PointsOnBoundary.end())
1168 {
1169 Log() << Verbose(2) << "Looks like we have a candidate!" << endl;
1170 break;
1171 }
1172 }
1173 if (baseline != DistanceMMap.end())
1174 {
1175 BPS[0] = baseline->second.first->second;
1176 BPS[1] = baseline->second.second->second;
1177 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1178 BPS[0] = A->second;
1179 BPS[1] = baseline->second.second->second;
1180 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1181 BPS[0] = baseline->second.first->second;
1182 BPS[1] = A->second;
1183 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1184
1185 // 4b3. insert created triangle
1186 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1187 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1188 TrianglesOnBoundaryCount++;
1189 for (int i = 0; i < NDIM; i++)
1190 {
1191 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
1192 LinesOnBoundaryCount++;
1193 }
1194
1195 Log() << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
1196 }
1197 else
1198 {
1199 eLog() << Verbose(0) << "No starting triangle found." << endl;
1200 }
1201}
1202;
1203
1204/** Tesselates the convex envelope of a cluster from a single starting triangle.
1205 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
1206 * 2 triangles. Hence, we go through all current lines:
1207 * -# if the lines contains to only one triangle
1208 * -# We search all points in the boundary
1209 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
1210 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
1211 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
1212 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
1213 * \param *out output stream for debugging
1214 * \param *configuration for IsAngstroem
1215 * \param *cloud cluster of points
1216 */
1217void Tesselation::TesselateOnBoundary(const PointCloud * const cloud)
1218{
1219 Info FunctionInfo(__func__);
1220 bool flag;
1221 PointMap::iterator winner;
1222 class BoundaryPointSet *peak = NULL;
1223 double SmallestAngle, TempAngle;
1224 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
1225 LineMap::iterator LineChecker[2];
1226
1227 Center = cloud->GetCenter();
1228 // create a first tesselation with the given BoundaryPoints
1229 do {
1230 flag = false;
1231 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
1232 if (baseline->second->triangles.size() == 1) {
1233 // 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)
1234 SmallestAngle = M_PI;
1235
1236 // get peak point with respect to this base line's only triangle
1237 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
1238 Log() << Verbose(0) << "Current baseline is between " << *(baseline->second) << "." << endl;
1239 for (int i = 0; i < 3; i++)
1240 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
1241 peak = BTS->endpoints[i];
1242 Log() << Verbose(1) << " and has peak " << *peak << "." << endl;
1243
1244 // prepare some auxiliary vectors
1245 Vector BaseLineCenter, BaseLine;
1246 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
1247 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
1248 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
1249 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
1250 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
1251
1252 // offset to center of triangle
1253 CenterVector.Zero();
1254 for (int i = 0; i < 3; i++)
1255 CenterVector.AddVector(BTS->endpoints[i]->node->node);
1256 CenterVector.Scale(1. / 3.);
1257 Log() << Verbose(2) << "CenterVector of base triangle is " << CenterVector << endl;
1258
1259 // normal vector of triangle
1260 NormalVector.CopyVector(Center);
1261 NormalVector.SubtractVector(&CenterVector);
1262 BTS->GetNormalVector(NormalVector);
1263 NormalVector.CopyVector(&BTS->NormalVector);
1264 Log() << Verbose(2) << "NormalVector of base triangle is " << NormalVector << endl;
1265
1266 // vector in propagation direction (out of triangle)
1267 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
1268 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
1269 TempVector.CopyVector(&CenterVector);
1270 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
1271 //Log() << Verbose(0) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
1272 if (PropagationVector.ScalarProduct(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
1273 PropagationVector.Scale(-1.);
1274 Log() << Verbose(2) << "PropagationVector of base triangle is " << PropagationVector << endl;
1275 winner = PointsOnBoundary.end();
1276
1277 // loop over all points and calculate angle between normal vector of new and present triangle
1278 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
1279 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
1280 Log() << Verbose(1) << "Target point is " << *(target->second) << ":" << endl;
1281
1282 // first check direction, so that triangles don't intersect
1283 VirtualNormalVector.CopyVector(target->second->node->node);
1284 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
1285 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
1286 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
1287 Log() << Verbose(2) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
1288 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
1289 Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
1290 continue;
1291 } else
1292 Log() << Verbose(2) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
1293
1294 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
1295 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
1296 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
1297 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->triangles.size() == 2))) {
1298 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;
1299 continue;
1300 }
1301 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->triangles.size() == 2))) {
1302 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;
1303 continue;
1304 }
1305
1306 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
1307 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)))) {
1308 Log() << Verbose(4) << "Current target is peak!" << endl;
1309 continue;
1310 }
1311
1312 // check for linear dependence
1313 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1314 TempVector.SubtractVector(target->second->node->node);
1315 helper.CopyVector(baseline->second->endpoints[1]->node->node);
1316 helper.SubtractVector(target->second->node->node);
1317 helper.ProjectOntoPlane(&TempVector);
1318 if (fabs(helper.NormSquared()) < MYEPSILON) {
1319 Log() << Verbose(2) << "Chosen set of vectors is linear dependent." << endl;
1320 continue;
1321 }
1322
1323 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
1324 flag = true;
1325 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
1326 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1327 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
1328 TempVector.AddVector(target->second->node->node);
1329 TempVector.Scale(1./3.);
1330 TempVector.SubtractVector(Center);
1331 // make it always point outward
1332 if (VirtualNormalVector.ScalarProduct(&TempVector) < 0)
1333 VirtualNormalVector.Scale(-1.);
1334 // calculate angle
1335 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1336 Log() << Verbose(2) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
1337 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
1338 SmallestAngle = TempAngle;
1339 winner = target;
1340 Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1341 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
1342 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
1343 helper.CopyVector(target->second->node->node);
1344 helper.SubtractVector(&BaseLineCenter);
1345 helper.ProjectOntoPlane(&BaseLine);
1346 // ...the one with the smaller angle is the better candidate
1347 TempVector.CopyVector(target->second->node->node);
1348 TempVector.SubtractVector(&BaseLineCenter);
1349 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1350 TempAngle = TempVector.Angle(&helper);
1351 TempVector.CopyVector(winner->second->node->node);
1352 TempVector.SubtractVector(&BaseLineCenter);
1353 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1354 if (TempAngle < TempVector.Angle(&helper)) {
1355 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1356 SmallestAngle = TempAngle;
1357 winner = target;
1358 Log() << Verbose(2) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
1359 } else
1360 Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
1361 } else
1362 Log() << Verbose(2) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1363 }
1364 } // end of loop over all boundary points
1365
1366 // 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
1367 if (winner != PointsOnBoundary.end()) {
1368 Log() << Verbose(0) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
1369 // create the lins of not yet present
1370 BLS[0] = baseline->second;
1371 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1372 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
1373 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
1374 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
1375 BPS[0] = baseline->second->endpoints[0];
1376 BPS[1] = winner->second;
1377 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1378 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
1379 LinesOnBoundaryCount++;
1380 } else
1381 BLS[1] = LineChecker[0]->second;
1382 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
1383 BPS[0] = baseline->second->endpoints[1];
1384 BPS[1] = winner->second;
1385 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1386 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
1387 LinesOnBoundaryCount++;
1388 } else
1389 BLS[2] = LineChecker[1]->second;
1390 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1391 BTS->GetCenter(&helper);
1392 helper.SubtractVector(Center);
1393 helper.Scale(-1);
1394 BTS->GetNormalVector(helper);
1395 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1396 TrianglesOnBoundaryCount++;
1397 } else {
1398 eLog() << Verbose(2) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
1399 }
1400
1401 // 5d. If the set of lines is not yet empty, go to 5. and continue
1402 } else
1403 Log() << Verbose(0) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl;
1404 } while (flag);
1405
1406 // exit
1407 delete(Center);
1408};
1409
1410/** Inserts all points outside of the tesselated surface into it by adding new triangles.
1411 * \param *out output stream for debugging
1412 * \param *cloud cluster of points
1413 * \param *LC LinkedCell structure to find nearest point quickly
1414 * \return true - all straddling points insert, false - something went wrong
1415 */
1416bool Tesselation::InsertStraddlingPoints(const PointCloud *cloud, const LinkedCell *LC)
1417{
1418 Info FunctionInfo(__func__);
1419 Vector Intersection, Normal;
1420 TesselPoint *Walker = NULL;
1421 Vector *Center = cloud->GetCenter();
1422 TriangleList *triangles = NULL;
1423 bool AddFlag = false;
1424 LinkedCell *BoundaryPoints = NULL;
1425
1426 cloud->GoToFirst();
1427 BoundaryPoints = new LinkedCell(this, 5.);
1428 while (!cloud->IsEnd()) { // we only have to go once through all points, as boundary can become only bigger
1429 if (AddFlag) {
1430 delete(BoundaryPoints);
1431 BoundaryPoints = new LinkedCell(this, 5.);
1432 AddFlag = false;
1433 }
1434 Walker = cloud->GetPoint();
1435 Log() << Verbose(0) << "Current point is " << *Walker << "." << endl;
1436 // get the next triangle
1437 triangles = FindClosestTrianglesToVector(Walker->node, BoundaryPoints);
1438 BTS = triangles->front();
1439 if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
1440 Log() << Verbose(0) << "No triangles found, probably a tesselation point itself." << endl;
1441 cloud->GoToNext();
1442 continue;
1443 } else {
1444 }
1445 Log() << Verbose(0) << "Closest triangle is " << *BTS << "." << endl;
1446 // get the intersection point
1447 if (BTS->GetIntersectionInsideTriangle(Center, Walker->node, &Intersection)) {
1448 Log() << Verbose(0) << "We have an intersection at " << Intersection << "." << endl;
1449 // we have the intersection, check whether in- or outside of boundary
1450 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
1451 // inside, next!
1452 Log() << Verbose(0) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
1453 } else {
1454 // outside!
1455 Log() << Verbose(0) << *Walker << " is outside wrt triangle " << *BTS << "." << endl;
1456 class BoundaryLineSet *OldLines[3], *NewLines[3];
1457 class BoundaryPointSet *OldPoints[3], *NewPoint;
1458 // store the three old lines and old points
1459 for (int i=0;i<3;i++) {
1460 OldLines[i] = BTS->lines[i];
1461 OldPoints[i] = BTS->endpoints[i];
1462 }
1463 Normal.CopyVector(&BTS->NormalVector);
1464 // add Walker to boundary points
1465 Log() << Verbose(0) << "Adding " << *Walker << " to BoundaryPoints." << endl;
1466 AddFlag = true;
1467 if (AddBoundaryPoint(Walker,0))
1468 NewPoint = BPS[0];
1469 else
1470 continue;
1471 // remove triangle
1472 Log() << Verbose(0) << "Erasing triangle " << *BTS << "." << endl;
1473 TrianglesOnBoundary.erase(BTS->Nr);
1474 delete(BTS);
1475 // create three new boundary lines
1476 for (int i=0;i<3;i++) {
1477 BPS[0] = NewPoint;
1478 BPS[1] = OldPoints[i];
1479 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1480 Log() << Verbose(1) << "Creating new line " << *NewLines[i] << "." << endl;
1481 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
1482 LinesOnBoundaryCount++;
1483 }
1484 // create three new triangle with new point
1485 for (int i=0;i<3;i++) { // find all baselines
1486 BLS[0] = OldLines[i];
1487 int n = 1;
1488 for (int j=0;j<3;j++) {
1489 if (NewLines[j]->IsConnectedTo(BLS[0])) {
1490 if (n>2) {
1491 eLog() << Verbose(2) << BLS[0] << " connects to all of the new lines?!" << endl;
1492 return false;
1493 } else
1494 BLS[n++] = NewLines[j];
1495 }
1496 }
1497 // create the triangle
1498 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1499 Normal.Scale(-1.);
1500 BTS->GetNormalVector(Normal);
1501 Normal.Scale(-1.);
1502 Log() << Verbose(0) << "Created new triangle " << *BTS << "." << endl;
1503 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1504 TrianglesOnBoundaryCount++;
1505 }
1506 }
1507 } else { // something is wrong with FindClosestTriangleToPoint!
1508 eLog() << Verbose(1) << "The closest triangle did not produce an intersection!" << endl;
1509 return false;
1510 }
1511 cloud->GoToNext();
1512 }
1513
1514 // exit
1515 delete(Center);
1516 return true;
1517};
1518
1519/** Adds a point to the tesselation::PointsOnBoundary list.
1520 * \param *Walker point to add
1521 * \param n TesselStruct::BPS index to put pointer into
1522 * \return true - new point was added, false - point already present
1523 */
1524bool Tesselation::AddBoundaryPoint(TesselPoint * Walker, const int n)
1525{
1526 Info FunctionInfo(__func__);
1527 PointTestPair InsertUnique;
1528 BPS[n] = new class BoundaryPointSet(Walker);
1529 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[n]));
1530 if (InsertUnique.second) { // if new point was not present before, increase counter
1531 PointsOnBoundaryCount++;
1532 return true;
1533 } else {
1534 delete(BPS[n]);
1535 BPS[n] = InsertUnique.first->second;
1536 return false;
1537 }
1538}
1539;
1540
1541/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1542 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1543 * @param Candidate point to add
1544 * @param n index for this point in Tesselation::TPS array
1545 */
1546void Tesselation::AddTesselationPoint(TesselPoint* Candidate, const int n)
1547{
1548 Info FunctionInfo(__func__);
1549 PointTestPair InsertUnique;
1550 TPS[n] = new class BoundaryPointSet(Candidate);
1551 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1552 if (InsertUnique.second) { // if new point was not present before, increase counter
1553 PointsOnBoundaryCount++;
1554 } else {
1555 delete TPS[n];
1556 Log() << Verbose(0) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1557 TPS[n] = (InsertUnique.first)->second;
1558 }
1559}
1560;
1561
1562/** Sets point to a present Tesselation::PointsOnBoundary.
1563 * Tesselation::TPS is set to the existing one or NULL if not found.
1564 * @param Candidate point to set to
1565 * @param n index for this point in Tesselation::TPS array
1566 */
1567void Tesselation::SetTesselationPoint(TesselPoint* Candidate, const int n) const
1568{
1569 Info FunctionInfo(__func__);
1570 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidate->nr);
1571 if (FindPoint != PointsOnBoundary.end())
1572 TPS[n] = FindPoint->second;
1573 else
1574 TPS[n] = NULL;
1575};
1576
1577/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1578 * If successful it raises the line count and inserts the new line into the BLS,
1579 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1580 * @param *a first endpoint
1581 * @param *b second endpoint
1582 * @param n index of Tesselation::BLS giving the line with both endpoints
1583 */
1584void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n) {
1585 bool insertNewLine = true;
1586
1587 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1588 if (FindLine != a->lines.end()) {
1589 Log() << Verbose(1) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1590
1591 pair<LineMap::iterator,LineMap::iterator> FindPair;
1592 FindPair = a->lines.equal_range(b->node->nr);
1593
1594 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1595 // If there is a line with less than two attached triangles, we don't need a new line.
1596 if (FindLine->second->triangles.size() < 2) {
1597 insertNewLine = false;
1598 Log() << Verbose(0) << "Using existing line " << *FindLine->second << endl;
1599
1600 BPS[0] = FindLine->second->endpoints[0];
1601 BPS[1] = FindLine->second->endpoints[1];
1602 BLS[n] = FindLine->second;
1603
1604 // remove existing line from OpenLines
1605 CandidateMap::iterator CandidateLine = OpenLines.find(BLS[n]);
1606 if (CandidateLine != OpenLines.end()) {
1607 Log() << Verbose(1) << " Removing line from OpenLines." << endl;
1608 delete(CandidateLine->second);
1609 OpenLines.erase(CandidateLine);
1610 } else {
1611 eLog() << Verbose(1) << "Line exists and is attached to less than two triangles, but not in OpenLines!" << endl;
1612 }
1613
1614 break;
1615 }
1616 }
1617 }
1618
1619 if (insertNewLine) {
1620 AlwaysAddTesselationTriangleLine(a, b, n);
1621 }
1622}
1623;
1624
1625/**
1626 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1627 * Raises the line count and inserts the new line into the BLS.
1628 *
1629 * @param *a first endpoint
1630 * @param *b second endpoint
1631 * @param n index of Tesselation::BLS giving the line with both endpoints
1632 */
1633void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
1634{
1635 Info FunctionInfo(__func__);
1636 Log() << Verbose(0) << "Adding open line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1637 BPS[0] = a;
1638 BPS[1] = b;
1639 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1640 // add line to global map
1641 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1642 // increase counter
1643 LinesOnBoundaryCount++;
1644 // also add to open lines
1645 CandidateForTesselation *CFT = new CandidateForTesselation(BLS[n]);
1646 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (BLS[n], CFT));
1647};
1648
1649/** Function adds triangle to global list.
1650 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1651 */
1652void Tesselation::AddTesselationTriangle()
1653{
1654 Info FunctionInfo(__func__);
1655 Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1656
1657 // add triangle to global map
1658 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1659 TrianglesOnBoundaryCount++;
1660
1661 // set as last new triangle
1662 LastTriangle = BTS;
1663
1664 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1665};
1666
1667/** Function adds triangle to global list.
1668 * Furthermore, the triangle number is set to \a nr.
1669 * \param nr triangle number
1670 */
1671void Tesselation::AddTesselationTriangle(const int nr)
1672{
1673 Info FunctionInfo(__func__);
1674 Log() << Verbose(0) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1675
1676 // add triangle to global map
1677 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1678
1679 // set as last new triangle
1680 LastTriangle = BTS;
1681
1682 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1683};
1684
1685/** Removes a triangle from the tesselation.
1686 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1687 * Removes itself from memory.
1688 * \param *triangle to remove
1689 */
1690void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1691{
1692 Info FunctionInfo(__func__);
1693 if (triangle == NULL)
1694 return;
1695 for (int i = 0; i < 3; i++) {
1696 if (triangle->lines[i] != NULL) {
1697 Log() << Verbose(0) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1698 triangle->lines[i]->triangles.erase(triangle->Nr);
1699 if (triangle->lines[i]->triangles.empty()) {
1700 Log() << Verbose(0) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1701 RemoveTesselationLine(triangle->lines[i]);
1702 } else {
1703 Log() << Verbose(0) << *triangle->lines[i] << " is still attached to another triangle: ";
1704 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (triangle->lines[i], NULL));
1705 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1706 Log() << Verbose(0) << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1707 Log() << Verbose(0) << endl;
1708// for (int j=0;j<2;j++) {
1709// Log() << Verbose(0) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1710// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1711// Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1712// Log() << Verbose(0) << endl;
1713// }
1714 }
1715 triangle->lines[i] = NULL; // free'd or not: disconnect
1716 } else
1717 eLog() << Verbose(1) << "This line " << i << " has already been free'd." << endl;
1718 }
1719
1720 if (TrianglesOnBoundary.erase(triangle->Nr))
1721 Log() << Verbose(0) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1722 delete(triangle);
1723};
1724
1725/** Removes a line from the tesselation.
1726 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1727 * \param *line line to remove
1728 */
1729void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1730{
1731 Info FunctionInfo(__func__);
1732 int Numbers[2];
1733
1734 if (line == NULL)
1735 return;
1736 // get other endpoint number for finding copies of same line
1737 if (line->endpoints[1] != NULL)
1738 Numbers[0] = line->endpoints[1]->Nr;
1739 else
1740 Numbers[0] = -1;
1741 if (line->endpoints[0] != NULL)
1742 Numbers[1] = line->endpoints[0]->Nr;
1743 else
1744 Numbers[1] = -1;
1745
1746 for (int i = 0; i < 2; i++) {
1747 if (line->endpoints[i] != NULL) {
1748 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
1749 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
1750 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
1751 if ((*Runner).second == line) {
1752 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1753 line->endpoints[i]->lines.erase(Runner);
1754 break;
1755 }
1756 } else { // there's just a single line left
1757 if (line->endpoints[i]->lines.erase(line->Nr))
1758 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1759 }
1760 if (line->endpoints[i]->lines.empty()) {
1761 Log() << Verbose(0) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
1762 RemoveTesselationPoint(line->endpoints[i]);
1763 } else {
1764 Log() << Verbose(0) << *line->endpoints[i] << " has still lines it's attached to: ";
1765 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
1766 Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1767 Log() << Verbose(0) << endl;
1768 }
1769 line->endpoints[i] = NULL; // free'd or not: disconnect
1770 } else
1771 eLog() << Verbose(1) << "Endpoint " << i << " has already been free'd." << endl;
1772 }
1773 if (!line->triangles.empty())
1774 eLog() << Verbose(2) << "Memory Leak! I " << *line << " am still connected to some triangles." << endl;
1775
1776 if (LinesOnBoundary.erase(line->Nr))
1777 Log() << Verbose(0) << "Removing line Nr. " << line->Nr << "." << endl;
1778 delete(line);
1779};
1780
1781/** Removes a point from the tesselation.
1782 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
1783 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
1784 * \param *point point to remove
1785 */
1786void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
1787{
1788 Info FunctionInfo(__func__);
1789 if (point == NULL)
1790 return;
1791 if (PointsOnBoundary.erase(point->Nr))
1792 Log() << Verbose(0) << "Removing point Nr. " << point->Nr << "." << endl;
1793 delete(point);
1794};
1795
1796/** Checks whether the triangle consisting of the three points is already present.
1797 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1798 * lines. If any of the three edges already has two triangles attached, false is
1799 * returned.
1800 * \param *out output stream for debugging
1801 * \param *Candidates endpoints of the triangle candidate
1802 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1803 * triangles exist which is the maximum for three points
1804 */
1805int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) const
1806{
1807 Info FunctionInfo(__func__);
1808 int adjacentTriangleCount = 0;
1809 class BoundaryPointSet *Points[3];
1810
1811 // builds a triangle point set (Points) of the end points
1812 for (int i = 0; i < 3; i++) {
1813 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1814 if (FindPoint != PointsOnBoundary.end()) {
1815 Points[i] = FindPoint->second;
1816 } else {
1817 Points[i] = NULL;
1818 }
1819 }
1820
1821 // checks lines between the points in the Points for their adjacent triangles
1822 for (int i = 0; i < 3; i++) {
1823 if (Points[i] != NULL) {
1824 for (int j = i; j < 3; j++) {
1825 if (Points[j] != NULL) {
1826 LineMap::const_iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1827 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1828 TriangleMap *triangles = &FindLine->second->triangles;
1829 Log() << Verbose(1) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1830 for (TriangleMap::const_iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1831 if (FindTriangle->second->IsPresentTupel(Points)) {
1832 adjacentTriangleCount++;
1833 }
1834 }
1835 Log() << Verbose(1) << "end." << endl;
1836 }
1837 // Only one of the triangle lines must be considered for the triangle count.
1838 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1839 //return adjacentTriangleCount;
1840 }
1841 }
1842 }
1843 }
1844
1845 Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1846 return adjacentTriangleCount;
1847};
1848
1849/** Checks whether the triangle consisting of the three points is already present.
1850 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1851 * lines. If any of the three edges already has two triangles attached, false is
1852 * returned.
1853 * \param *out output stream for debugging
1854 * \param *Candidates endpoints of the triangle candidate
1855 * \return NULL - none found or pointer to triangle
1856 */
1857class BoundaryTriangleSet * Tesselation::GetPresentTriangle(TesselPoint *Candidates[3])
1858{
1859 Info FunctionInfo(__func__);
1860 class BoundaryTriangleSet *triangle = NULL;
1861 class BoundaryPointSet *Points[3];
1862
1863 // builds a triangle point set (Points) of the end points
1864 for (int i = 0; i < 3; i++) {
1865 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1866 if (FindPoint != PointsOnBoundary.end()) {
1867 Points[i] = FindPoint->second;
1868 } else {
1869 Points[i] = NULL;
1870 }
1871 }
1872
1873 // checks lines between the points in the Points for their adjacent triangles
1874 for (int i = 0; i < 3; i++) {
1875 if (Points[i] != NULL) {
1876 for (int j = i; j < 3; j++) {
1877 if (Points[j] != NULL) {
1878 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1879 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1880 TriangleMap *triangles = &FindLine->second->triangles;
1881 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1882 if (FindTriangle->second->IsPresentTupel(Points)) {
1883 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
1884 triangle = FindTriangle->second;
1885 }
1886 }
1887 }
1888 // Only one of the triangle lines must be considered for the triangle count.
1889 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1890 //return adjacentTriangleCount;
1891 }
1892 }
1893 }
1894 }
1895
1896 return triangle;
1897};
1898
1899
1900/** Finds the starting triangle for FindNonConvexBorder().
1901 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
1902 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
1903 * point are called.
1904 * \param *out output stream for debugging
1905 * \param RADIUS radius of virtual rolling sphere
1906 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1907 */
1908void Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
1909{
1910 Info FunctionInfo(__func__);
1911 int i = 0;
1912 TesselPoint* MaxPoint[NDIM];
1913 TesselPoint* Temporary;
1914 double maxCoordinate[NDIM];
1915 BoundaryLineSet BaseLine;
1916 Vector helper;
1917 Vector Chord;
1918 Vector SearchDirection;
1919 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
1920 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
1921 Vector SphereCenter;
1922 Vector NormalVector;
1923
1924 NormalVector.Zero();
1925
1926 for (i = 0; i < 3; i++) {
1927 MaxPoint[i] = NULL;
1928 maxCoordinate[i] = -1;
1929 }
1930
1931 // 1. searching topmost point with respect to each axis
1932 for (int i=0;i<NDIM;i++) { // each axis
1933 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1934 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1935 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1936 const LinkedNodes *List = LC->GetCurrentCell();
1937 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1938 if (List != NULL) {
1939 for (LinkedNodes::const_iterator Runner = List->begin();Runner != List->end();Runner++) {
1940 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
1941 Log() << Verbose(1) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1942 maxCoordinate[i] = (*Runner)->node->x[i];
1943 MaxPoint[i] = (*Runner);
1944 }
1945 }
1946 } else {
1947 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1948 }
1949 }
1950 }
1951
1952 Log() << Verbose(1) << "Found maximum coordinates: ";
1953 for (int i=0;i<NDIM;i++)
1954 Log() << Verbose(0) << i << ": " << *MaxPoint[i] << "\t";
1955 Log() << Verbose(0) << endl;
1956
1957 BTS = NULL;
1958 for (int k=0;k<NDIM;k++) {
1959 NormalVector.Zero();
1960 NormalVector.x[k] = 1.;
1961 BaseLine.endpoints[0] = new BoundaryPointSet(MaxPoint[k]);
1962 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
1963
1964 double ShortestAngle;
1965 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.
1966
1967 FindSecondPointForTesselation(BaseLine.endpoints[0]->node, NormalVector, Temporary, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1968 if (Temporary == NULL) // have we found a second point?
1969 continue;
1970 BaseLine.endpoints[1] = new BoundaryPointSet(Temporary);
1971
1972 // construct center of circle
1973 CircleCenter.CopyVector(BaseLine.endpoints[0]->node->node);
1974 CircleCenter.AddVector(BaseLine.endpoints[1]->node->node);
1975 CircleCenter.Scale(0.5);
1976
1977 // construct normal vector of circle
1978 CirclePlaneNormal.CopyVector(BaseLine.endpoints[0]->node->node);
1979 CirclePlaneNormal.SubtractVector(BaseLine.endpoints[1]->node->node);
1980
1981 double radius = CirclePlaneNormal.NormSquared();
1982 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1983
1984 NormalVector.ProjectOntoPlane(&CirclePlaneNormal);
1985 NormalVector.Normalize();
1986 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1987
1988 SphereCenter.CopyVector(&NormalVector);
1989 SphereCenter.Scale(CircleRadius);
1990 SphereCenter.AddVector(&CircleCenter);
1991 // Now, NormalVector and SphereCenter are two orthonormalized vectors in the plane defined by CirclePlaneNormal (not normalized)
1992
1993 // look in one direction of baseline for initial candidate
1994 SearchDirection.MakeNormalVector(&CirclePlaneNormal, &NormalVector); // whether we look "left" first or "right" first is not important ...
1995
1996 // adding point 1 and point 2 and add the line between them
1997 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
1998 Log() << Verbose(0) << "Found second point is at " << *BaseLine.endpoints[1]->node << ".\n";
1999
2000 //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << helper << ".\n";
2001 CandidateForTesselation OptCandidates(&BaseLine);
2002 FindThirdPointForTesselation(NormalVector, SearchDirection, SphereCenter, OptCandidates, NULL, RADIUS, LC);
2003 Log() << Verbose(0) << "List of third Points is:" << endl;
2004 for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); it++) {
2005 Log() << Verbose(0) << " " << *(*it) << endl;
2006 }
2007
2008 BTS = NULL;
2009 AddCandidateTriangle(OptCandidates);
2010// delete(BaseLine.endpoints[0]);
2011// delete(BaseLine.endpoints[1]);
2012
2013 if (BTS != NULL) // we have created one starting triangle
2014 break;
2015 else {
2016 // remove all candidates from the list and then the list itself
2017 OptCandidates.pointlist.clear();
2018 }
2019 }
2020};
2021
2022/** Checks for a given baseline and a third point candidate whether baselines of the found triangle don't have even better candidates.
2023 * This is supposed to prevent early closing of the tesselation.
2024 * \param CandidateLine CandidateForTesselation with baseline and shortestangle , i.e. not \a *OptCandidate
2025 * \param *ThirdNode third point in triangle, not in BoundaryLineSet::endpoints
2026 * \param RADIUS radius of sphere
2027 * \param *LC LinkedCell structure
2028 * \return true - there is a better candidate (smaller angle than \a ShortestAngle), false - no better TesselPoint candidate found
2029 */
2030//bool Tesselation::HasOtherBaselineBetterCandidate(CandidateForTesselation &CandidateLine, const TesselPoint * const ThirdNode, double RADIUS, const LinkedCell * const LC) const
2031//{
2032// Info FunctionInfo(__func__);
2033// bool result = false;
2034// Vector CircleCenter;
2035// Vector CirclePlaneNormal;
2036// Vector OldSphereCenter;
2037// Vector SearchDirection;
2038// Vector helper;
2039// TesselPoint *OtherOptCandidate = NULL;
2040// double OtherShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2041// double radius, CircleRadius;
2042// BoundaryLineSet *Line = NULL;
2043// BoundaryTriangleSet *T = NULL;
2044//
2045// // check both other lines
2046// PointMap::const_iterator FindPoint = PointsOnBoundary.find(ThirdNode->nr);
2047// if (FindPoint != PointsOnBoundary.end()) {
2048// for (int i=0;i<2;i++) {
2049// LineMap::const_iterator FindLine = (FindPoint->second)->lines.find(BaseRay->endpoints[0]->node->nr);
2050// if (FindLine != (FindPoint->second)->lines.end()) {
2051// Line = FindLine->second;
2052// Log() << Verbose(0) << "Found line " << *Line << "." << endl;
2053// if (Line->triangles.size() == 1) {
2054// T = Line->triangles.begin()->second;
2055// // construct center of circle
2056// CircleCenter.CopyVector(Line->endpoints[0]->node->node);
2057// CircleCenter.AddVector(Line->endpoints[1]->node->node);
2058// CircleCenter.Scale(0.5);
2059//
2060// // construct normal vector of circle
2061// CirclePlaneNormal.CopyVector(Line->endpoints[0]->node->node);
2062// CirclePlaneNormal.SubtractVector(Line->endpoints[1]->node->node);
2063//
2064// // calculate squared radius of circle
2065// radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2066// if (radius/4. < RADIUS*RADIUS) {
2067// CircleRadius = RADIUS*RADIUS - radius/4.;
2068// CirclePlaneNormal.Normalize();
2069// //Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2070//
2071// // construct old center
2072// GetCenterofCircumcircle(&OldSphereCenter, *T->endpoints[0]->node->node, *T->endpoints[1]->node->node, *T->endpoints[2]->node->node);
2073// helper.CopyVector(&T->NormalVector); // normal vector ensures that this is correct center of the two possible ones
2074// radius = Line->endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
2075// helper.Scale(sqrt(RADIUS*RADIUS - radius));
2076// OldSphereCenter.AddVector(&helper);
2077// OldSphereCenter.SubtractVector(&CircleCenter);
2078// //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2079//
2080// // construct SearchDirection
2081// SearchDirection.MakeNormalVector(&T->NormalVector, &CirclePlaneNormal);
2082// helper.CopyVector(Line->endpoints[0]->node->node);
2083// helper.SubtractVector(ThirdNode->node);
2084// if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2085// SearchDirection.Scale(-1.);
2086// SearchDirection.ProjectOntoPlane(&OldSphereCenter);
2087// SearchDirection.Normalize();
2088// Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2089// if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2090// // rotated the wrong way!
2091// eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2092// }
2093//
2094// // add third point
2095// FindThirdPointForTesselation(T->NormalVector, SearchDirection, OldSphereCenter, OptCandidates, ThirdNode, RADIUS, LC);
2096// for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); ++it) {
2097// if (((*it) == BaseRay->endpoints[0]->node) || ((*it) == BaseRay->endpoints[1]->node)) // skip if it's the same triangle than suggested
2098// continue;
2099// Log() << Verbose(0) << " Third point candidate is " << (*it)
2100// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2101// Log() << Verbose(0) << " Baseline is " << *BaseRay << endl;
2102//
2103// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2104// TesselPoint *PointCandidates[3];
2105// PointCandidates[0] = (*it);
2106// PointCandidates[1] = BaseRay->endpoints[0]->node;
2107// PointCandidates[2] = BaseRay->endpoints[1]->node;
2108// bool check=false;
2109// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2110// // If there is no triangle, add it regularly.
2111// if (existentTrianglesCount == 0) {
2112// SetTesselationPoint((*it), 0);
2113// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2114// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2115//
2116// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2117// OtherOptCandidate = (*it);
2118// check = true;
2119// }
2120// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2121// SetTesselationPoint((*it), 0);
2122// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2123// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2124//
2125// // 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)
2126// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2127// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS)) {
2128// OtherOptCandidate = (*it);
2129// check = true;
2130// }
2131// }
2132//
2133// if (check) {
2134// if (ShortestAngle > OtherShortestAngle) {
2135// Log() << Verbose(0) << "There is a better candidate than " << *ThirdNode << " with " << ShortestAngle << " from baseline " << *Line << ": " << *OtherOptCandidate << " with " << OtherShortestAngle << "." << endl;
2136// result = true;
2137// break;
2138// }
2139// }
2140// }
2141// delete(OptCandidates);
2142// if (result)
2143// break;
2144// } else {
2145// Log() << Verbose(0) << "Circumcircle for base line " << *Line << " and base triangle " << T << " is too big!" << endl;
2146// }
2147// } else {
2148// eLog() << Verbose(2) << "Baseline is connected to two triangles already?" << endl;
2149// }
2150// } else {
2151// Log() << Verbose(1) << "No present baseline between " << BaseRay->endpoints[0] << " and candidate " << *ThirdNode << "." << endl;
2152// }
2153// }
2154// } else {
2155// eLog() << Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl;
2156// }
2157//
2158// return result;
2159//};
2160
2161/** This function finds a triangle to a line, adjacent to an existing one.
2162 * @param out output stream for debugging
2163 * @param CandidateLine current cadndiate baseline to search from
2164 * @param T current triangle which \a Line is edge of
2165 * @param RADIUS radius of the rolling ball
2166 * @param N number of found triangles
2167 * @param *LC LinkedCell structure with neighbouring points
2168 */
2169bool Tesselation::FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
2170{
2171 Info FunctionInfo(__func__);
2172 bool result = true;
2173
2174 Vector CircleCenter;
2175 Vector CirclePlaneNormal;
2176 Vector RelativeSphereCenter;
2177 Vector SearchDirection;
2178 Vector helper;
2179 TesselPoint *ThirdNode = NULL;
2180 LineMap::iterator testline;
2181 double radius, CircleRadius;
2182
2183 for (int i=0;i<3;i++)
2184 if ((T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[0]->node) && (T.endpoints[i]->node != CandidateLine.BaseLine->endpoints[1]->node)) {
2185 ThirdNode = T.endpoints[i]->node;
2186 break;
2187 }
2188 Log() << Verbose(0) << "Current baseline is " << *CandidateLine.BaseLine << " with ThirdNode " << *ThirdNode << " of triangle " << T << "." << endl;
2189
2190 // construct center of circle
2191 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2192 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2193 CircleCenter.Scale(0.5);
2194
2195 // construct normal vector of circle
2196 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2197 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2198
2199 // calculate squared radius of circle
2200 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2201 if (radius/4. < RADIUS*RADIUS) {
2202 // construct relative sphere center with now known CircleCenter
2203 RelativeSphereCenter.CopyVector(&T.SphereCenter);
2204 RelativeSphereCenter.SubtractVector(&CircleCenter);
2205
2206 CircleRadius = RADIUS*RADIUS - radius/4.;
2207 CirclePlaneNormal.Normalize();
2208 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2209
2210 Log() << Verbose(1) << "INFO: OldSphereCenter is at " << T.SphereCenter << "." << endl;
2211
2212 // construct SearchDirection and an "outward pointer"
2213 SearchDirection.MakeNormalVector(&RelativeSphereCenter, &CirclePlaneNormal);
2214 helper.CopyVector(&CircleCenter);
2215 helper.SubtractVector(ThirdNode->node);
2216 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2217 SearchDirection.Scale(-1.);
2218 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2219 if (fabs(RelativeSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2220 // rotated the wrong way!
2221 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
2222 }
2223
2224 // add third point
2225 FindThirdPointForTesselation(T.NormalVector, SearchDirection, T.SphereCenter, CandidateLine, ThirdNode, RADIUS, LC);
2226
2227 } else {
2228 Log() << Verbose(0) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and base triangle " << T << " is too big!" << endl;
2229 }
2230
2231 if (CandidateLine.pointlist.empty()) {
2232 eLog() << Verbose(2) << "Could not find a suitable candidate." << endl;
2233 return false;
2234 }
2235 Log() << Verbose(0) << "Third Points are: " << endl;
2236 for (TesselPointList::iterator it = CandidateLine.pointlist.begin(); it != CandidateLine.pointlist.end(); ++it) {
2237 Log() << Verbose(0) << " " << *(*it) << endl;
2238 }
2239
2240 return true;
2241
2242// BoundaryLineSet *BaseRay = CandidateLine.BaseLine;
2243// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2244// Log() << Verbose(0) << "Third point candidate is " << *(*it)->point
2245// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2246// Log() << Verbose(0) << "Baseline is " << *BaseRay << endl;
2247//
2248// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2249// TesselPoint *PointCandidates[3];
2250// PointCandidates[0] = (*it)->point;
2251// PointCandidates[1] = BaseRay->endpoints[0]->node;
2252// PointCandidates[2] = BaseRay->endpoints[1]->node;
2253// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2254//
2255// BTS = NULL;
2256// // check for present edges and whether we reach better candidates from them
2257// //if (HasOtherBaselineBetterCandidate(BaseRay, (*it)->point, ShortestAngle, RADIUS, LC) ) {
2258// if (0) {
2259// result = false;
2260// break;
2261// } else {
2262// // If there is no triangle, add it regularly.
2263// if (existentTrianglesCount == 0) {
2264// AddTesselationPoint((*it)->point, 0);
2265// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2266// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2267//
2268// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2269// CandidateLine.point = (*it)->point;
2270// CandidateLine.OptCenter.CopyVector(&((*it)->OptCenter));
2271// CandidateLine.OtherOptCenter.CopyVector(&((*it)->OtherOptCenter));
2272// CandidateLine.ShortestAngle = ShortestAngle;
2273// } else {
2274//// eLog() << Verbose(1) << "This triangle consisting of ";
2275//// Log() << Verbose(0) << *(*it)->point << ", ";
2276//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2277//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2278//// Log() << Verbose(0) << "exists and is not added, as it 0x80000000006fc150(does not seem helpful!" << endl;
2279// result = false;
2280// }
2281// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2282// AddTesselationPoint((*it)->point, 0);
2283// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2284// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2285//
2286// // 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)
2287// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2288// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS) || CandidateLine.BaseLine->skipped) {
2289// CandidateLine.point = (*it)->point;
2290// CandidateLine.OptCenter.CopyVector(&(*it)->OptCenter);
2291// CandidateLine.OtherOptCenter.CopyVector(&(*it)->OtherOptCenter);
2292// CandidateLine.ShortestAngle = ShortestAngle+2.*M_PI;
2293//
2294// } else {
2295//// 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;
2296// result = false;
2297// }
2298// } else {
2299//// Log() << Verbose(1) << "This triangle consisting of ";
2300//// Log() << Verbose(0) << *(*it)->point << ", ";
2301//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2302//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2303//// Log() << Verbose(0) << "is invalid!" << endl;
2304// result = false;
2305// }
2306// }
2307//
2308// // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
2309// BaseRay = BLS[0];
2310// if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
2311// eLog() << Verbose(1) << "Triangle " << *BTS << " has zero normal vector!" << endl;
2312// exit(255);
2313// }
2314//
2315// }
2316//
2317// // remove all candidates from the list and then the list itself
2318// class CandidateForTesselation *remover = NULL;
2319// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2320// remover = *it;
2321// delete(remover);
2322// }
2323// delete(OptCandidates);
2324 return result;
2325};
2326
2327/** Adds the present line and candidate point from \a &CandidateLine to the Tesselation.
2328 * \param CandidateLine triangle to add
2329 * \NOTE we need the copy operator here as the original CandidateForTesselation is removed in AddTesselationLine()
2330 */
2331void Tesselation::AddCandidateTriangle(CandidateForTesselation CandidateLine)
2332{
2333 Info FunctionInfo(__func__);
2334 Vector Center;
2335 TesselPoint * const TurningPoint = CandidateLine.BaseLine->endpoints[0]->node;
2336
2337 // fill the set of neighbours
2338 TesselPointSet SetOfNeighbours;
2339 SetOfNeighbours.insert(CandidateLine.BaseLine->endpoints[1]->node);
2340 for (TesselPointList::iterator Runner = CandidateLine.pointlist.begin(); Runner != CandidateLine.pointlist.end(); Runner++)
2341 SetOfNeighbours.insert(*Runner);
2342 TesselPointList *connectedClosestPoints = GetCircleOfSetOfPoints(&SetOfNeighbours, TurningPoint, CandidateLine.BaseLine->endpoints[1]->node->node);
2343
2344 // go through all angle-sorted candidates (in degenerate n-nodes case we may have to add multiple triangles)
2345 Log() << Verbose(0) << "List of Candidates for Turning Point: " << *TurningPoint << "." << endl;
2346 for (TesselPointList::iterator TesselRunner = connectedClosestPoints->begin(); TesselRunner != connectedClosestPoints->end(); ++TesselRunner)
2347 Log() << Verbose(0) << **TesselRunner << endl;
2348 TesselPointList::iterator Runner = connectedClosestPoints->begin();
2349 TesselPointList::iterator Sprinter = Runner;
2350 Sprinter++;
2351 while(Sprinter != connectedClosestPoints->end()) {
2352 // add the points
2353 AddTesselationPoint(TurningPoint, 0);
2354 AddTesselationPoint((*Runner), 1);
2355 AddTesselationPoint((*Sprinter), 2);
2356
2357 // add the lines
2358 AddTesselationLine(TPS[0], TPS[1], 0);
2359 AddTesselationLine(TPS[0], TPS[2], 1);
2360 AddTesselationLine(TPS[1], TPS[2], 2);
2361
2362 // add the triangles
2363 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2364 AddTesselationTriangle();
2365 BTS->GetCenter(&Center);
2366 Center.SubtractVector(&CandidateLine.OptCenter);
2367 BTS->SphereCenter.CopyVector(&CandidateLine.OptCenter);
2368 BTS->GetNormalVector(Center);
2369
2370 Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector << "." << endl;
2371 Runner = Sprinter;
2372 Sprinter++;
2373 Log() << Verbose(0) << "Current Runner is " << **Runner << "." << endl;
2374 if (Sprinter != connectedClosestPoints->end())
2375 Log() << Verbose(0) << " There are still more triangles to add." << endl;
2376 }
2377 delete(connectedClosestPoints);
2378};
2379
2380/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
2381 * We look whether the closest point on \a *Base with respect to the other baseline is outside
2382 * of the segment formed by both endpoints (concave) or not (convex).
2383 * \param *out output stream for debugging
2384 * \param *Base line to be flipped
2385 * \return NULL - convex, otherwise endpoint that makes it concave
2386 */
2387class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
2388{
2389 Info FunctionInfo(__func__);
2390 class BoundaryPointSet *Spot = NULL;
2391 class BoundaryLineSet *OtherBase;
2392 Vector *ClosestPoint;
2393
2394 int m=0;
2395 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2396 for (int j=0;j<3;j++) // all of their endpoints and baselines
2397 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2398 BPS[m++] = runner->second->endpoints[j];
2399 OtherBase = new class BoundaryLineSet(BPS,-1);
2400
2401 Log() << Verbose(1) << "INFO: Current base line is " << *Base << "." << endl;
2402 Log() << Verbose(1) << "INFO: Other base line is " << *OtherBase << "." << endl;
2403
2404 // get the closest point on each line to the other line
2405 ClosestPoint = GetClosestPointBetweenLine(Base, OtherBase);
2406
2407 // delete the temporary other base line
2408 delete(OtherBase);
2409
2410 // get the distance vector from Base line to OtherBase line
2411 Vector DistanceToIntersection[2], BaseLine;
2412 double distance[2];
2413 BaseLine.CopyVector(Base->endpoints[1]->node->node);
2414 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
2415 for (int i=0;i<2;i++) {
2416 DistanceToIntersection[i].CopyVector(ClosestPoint);
2417 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
2418 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
2419 }
2420 delete(ClosestPoint);
2421 if ((distance[0] * distance[1]) > 0) { // have same sign?
2422 Log() << Verbose(1) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
2423 if (distance[0] < distance[1]) {
2424 Spot = Base->endpoints[0];
2425 } else {
2426 Spot = Base->endpoints[1];
2427 }
2428 return Spot;
2429 } else { // different sign, i.e. we are in between
2430 Log() << Verbose(0) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
2431 return NULL;
2432 }
2433
2434};
2435
2436void Tesselation::PrintAllBoundaryPoints(ofstream *out) const
2437{
2438 Info FunctionInfo(__func__);
2439 // print all lines
2440 Log() << Verbose(0) << "Printing all boundary points for debugging:" << endl;
2441 for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
2442 Log() << Verbose(0) << *(PointRunner->second) << endl;
2443};
2444
2445void Tesselation::PrintAllBoundaryLines(ofstream *out) const
2446{
2447 Info FunctionInfo(__func__);
2448 // print all lines
2449 Log() << Verbose(0) << "Printing all boundary lines for debugging:" << endl;
2450 for (LineMap::const_iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
2451 Log() << Verbose(0) << *(LineRunner->second) << endl;
2452};
2453
2454void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
2455{
2456 Info FunctionInfo(__func__);
2457 // print all triangles
2458 Log() << Verbose(0) << "Printing all boundary triangles for debugging:" << endl;
2459 for (TriangleMap::const_iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
2460 Log() << Verbose(0) << *(TriangleRunner->second) << endl;
2461};
2462
2463/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
2464 * \param *out output stream for debugging
2465 * \param *Base line to be flipped
2466 * \return volume change due to flipping (0 - then no flipped occured)
2467 */
2468double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
2469{
2470 Info FunctionInfo(__func__);
2471 class BoundaryLineSet *OtherBase;
2472 Vector *ClosestPoint[2];
2473 double volume;
2474
2475 int m=0;
2476 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2477 for (int j=0;j<3;j++) // all of their endpoints and baselines
2478 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2479 BPS[m++] = runner->second->endpoints[j];
2480 OtherBase = new class BoundaryLineSet(BPS,-1);
2481
2482 Log() << Verbose(0) << "INFO: Current base line is " << *Base << "." << endl;
2483 Log() << Verbose(0) << "INFO: Other base line is " << *OtherBase << "." << endl;
2484
2485 // get the closest point on each line to the other line
2486 ClosestPoint[0] = GetClosestPointBetweenLine(Base, OtherBase);
2487 ClosestPoint[1] = GetClosestPointBetweenLine(OtherBase, Base);
2488
2489 // get the distance vector from Base line to OtherBase line
2490 Vector Distance;
2491 Distance.CopyVector(ClosestPoint[1]);
2492 Distance.SubtractVector(ClosestPoint[0]);
2493
2494 // calculate volume
2495 volume = CalculateVolumeofGeneralTetraeder(*Base->endpoints[1]->node->node, *OtherBase->endpoints[0]->node->node, *OtherBase->endpoints[1]->node->node, *Base->endpoints[0]->node->node);
2496
2497 // delete the temporary other base line and the closest points
2498 delete(ClosestPoint[0]);
2499 delete(ClosestPoint[1]);
2500 delete(OtherBase);
2501
2502 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2503 Log() << Verbose(0) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2504 return false;
2505 } else { // check for sign against BaseLineNormal
2506 Vector BaseLineNormal;
2507 BaseLineNormal.Zero();
2508 if (Base->triangles.size() < 2) {
2509 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2510 return 0.;
2511 }
2512 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2513 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2514 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2515 }
2516 BaseLineNormal.Scale(1./2.);
2517
2518 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2519 Log() << Verbose(0) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2520 // calculate volume summand as a general tetraeder
2521 return volume;
2522 } else { // Base higher than OtherBase -> do nothing
2523 Log() << Verbose(0) << "REJECT: Base line is higher: Nothing to do." << endl;
2524 return 0.;
2525 }
2526 }
2527};
2528
2529/** For a given baseline and its two connected triangles, flips the baseline.
2530 * I.e. we create the new baseline between the other two endpoints of these four
2531 * endpoints and reconstruct the two triangles accordingly.
2532 * \param *out output stream for debugging
2533 * \param *Base line to be flipped
2534 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2535 */
2536class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
2537{
2538 Info FunctionInfo(__func__);
2539 class BoundaryLineSet *OldLines[4], *NewLine;
2540 class BoundaryPointSet *OldPoints[2];
2541 Vector BaseLineNormal;
2542 int OldTriangleNrs[2], OldBaseLineNr;
2543 int i,m;
2544
2545 // calculate NormalVector for later use
2546 BaseLineNormal.Zero();
2547 if (Base->triangles.size() < 2) {
2548 eLog() << Verbose(1) << "Less than two triangles are attached to this baseline!" << endl;
2549 return NULL;
2550 }
2551 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2552 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2553 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2554 }
2555 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2556
2557 // get the two triangles
2558 // gather four endpoints and four lines
2559 for (int j=0;j<4;j++)
2560 OldLines[j] = NULL;
2561 for (int j=0;j<2;j++)
2562 OldPoints[j] = NULL;
2563 i=0;
2564 m=0;
2565 Log() << Verbose(0) << "The four old lines are: ";
2566 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2567 for (int j=0;j<3;j++) // all of their endpoints and baselines
2568 if (runner->second->lines[j] != Base) { // pick not the central baseline
2569 OldLines[i++] = runner->second->lines[j];
2570 Log() << Verbose(0) << *runner->second->lines[j] << "\t";
2571 }
2572 Log() << Verbose(0) << endl;
2573 Log() << Verbose(0) << "The two old points are: ";
2574 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2575 for (int j=0;j<3;j++) // all of their endpoints and baselines
2576 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2577 OldPoints[m++] = runner->second->endpoints[j];
2578 Log() << Verbose(0) << *runner->second->endpoints[j] << "\t";
2579 }
2580 Log() << Verbose(0) << endl;
2581
2582 // check whether everything is in place to create new lines and triangles
2583 if (i<4) {
2584 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2585 return NULL;
2586 }
2587 for (int j=0;j<4;j++)
2588 if (OldLines[j] == NULL) {
2589 eLog() << Verbose(1) << "We have not gathered enough baselines!" << endl;
2590 return NULL;
2591 }
2592 for (int j=0;j<2;j++)
2593 if (OldPoints[j] == NULL) {
2594 eLog() << Verbose(1) << "We have not gathered enough endpoints!" << endl;
2595 return NULL;
2596 }
2597
2598 // remove triangles and baseline removes itself
2599 Log() << Verbose(0) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2600 OldBaseLineNr = Base->Nr;
2601 m=0;
2602 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2603 Log() << Verbose(0) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
2604 OldTriangleNrs[m++] = runner->second->Nr;
2605 RemoveTesselationTriangle(runner->second);
2606 }
2607
2608 // construct new baseline (with same number as old one)
2609 BPS[0] = OldPoints[0];
2610 BPS[1] = OldPoints[1];
2611 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2612 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2613 Log() << Verbose(0) << "INFO: Created new baseline " << *NewLine << "." << endl;
2614
2615 // construct new triangles with flipped baseline
2616 i=-1;
2617 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2618 i=2;
2619 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2620 i=3;
2621 if (i!=-1) {
2622 BLS[0] = OldLines[0];
2623 BLS[1] = OldLines[i];
2624 BLS[2] = NewLine;
2625 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2626 BTS->GetNormalVector(BaseLineNormal);
2627 AddTesselationTriangle(OldTriangleNrs[0]);
2628 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
2629
2630 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
2631 BLS[1] = OldLines[1];
2632 BLS[2] = NewLine;
2633 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2634 BTS->GetNormalVector(BaseLineNormal);
2635 AddTesselationTriangle(OldTriangleNrs[1]);
2636 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
2637 } else {
2638 eLog() << Verbose(0) << "The four old lines do not connect, something's utterly wrong here!" << endl;
2639 return NULL;
2640 }
2641
2642 return NewLine;
2643};
2644
2645
2646/** Finds the second point of starting triangle.
2647 * \param *a first node
2648 * \param Oben vector indicating the outside
2649 * \param OptCandidate reference to recommended candidate on return
2650 * \param Storage[3] array storing angles and other candidate information
2651 * \param RADIUS radius of virtual sphere
2652 * \param *LC LinkedCell structure with neighbouring points
2653 */
2654void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC)
2655{
2656 Info FunctionInfo(__func__);
2657 Vector AngleCheck;
2658 class TesselPoint* Candidate = NULL;
2659 double norm = -1.;
2660 double angle = 0.;
2661 int N[NDIM];
2662 int Nlower[NDIM];
2663 int Nupper[NDIM];
2664
2665 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2666 for(int i=0;i<NDIM;i++) // store indices of this cell
2667 N[i] = LC->n[i];
2668 } else {
2669 eLog() << Verbose(1) << "Point " << *a << " is not found in cell " << LC->index << "." << endl;
2670 return;
2671 }
2672 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2673 for (int i=0;i<NDIM;i++) {
2674 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2675 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2676 }
2677 Log() << Verbose(0) << "LC Intervals from [" << N[0] << "<->" << LC->N[0] << ", " << N[1] << "<->" << LC->N[1] << ", " << N[2] << "<->" << LC->N[2] << "] :"
2678 << " [" << Nlower[0] << "," << Nupper[0] << "], " << " [" << Nlower[1] << "," << Nupper[1] << "], " << " [" << Nlower[2] << "," << Nupper[2] << "], " << endl;
2679
2680 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2681 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2682 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2683 const LinkedNodes *List = LC->GetCurrentCell();
2684 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2685 if (List != NULL) {
2686 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2687 Candidate = (*Runner);
2688 // check if we only have one unique point yet ...
2689 if (a != Candidate) {
2690 // Calculate center of the circle with radius RADIUS through points a and Candidate
2691 Vector OrthogonalizedOben, aCandidate, Center;
2692 double distance, scaleFactor;
2693
2694 OrthogonalizedOben.CopyVector(&Oben);
2695 aCandidate.CopyVector(a->node);
2696 aCandidate.SubtractVector(Candidate->node);
2697 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
2698 OrthogonalizedOben.Normalize();
2699 distance = 0.5 * aCandidate.Norm();
2700 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2701 OrthogonalizedOben.Scale(scaleFactor);
2702
2703 Center.CopyVector(Candidate->node);
2704 Center.AddVector(a->node);
2705 Center.Scale(0.5);
2706 Center.AddVector(&OrthogonalizedOben);
2707
2708 AngleCheck.CopyVector(&Center);
2709 AngleCheck.SubtractVector(a->node);
2710 norm = aCandidate.Norm();
2711 // second point shall have smallest angle with respect to Oben vector
2712 if (norm < RADIUS*2.) {
2713 angle = AngleCheck.Angle(&Oben);
2714 if (angle < Storage[0]) {
2715 //Log() << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2716 Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2717 OptCandidate = Candidate;
2718 Storage[0] = angle;
2719 //Log() << Verbose(1) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2720 } else {
2721 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
2722 }
2723 } else {
2724 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2725 }
2726 } else {
2727 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2728 }
2729 }
2730 } else {
2731 Log() << Verbose(0) << "Linked cell list is empty." << endl;
2732 }
2733 }
2734};
2735
2736
2737/** This recursive function finds a third point, to form a triangle with two given ones.
2738 * Note that this function is for the starting triangle.
2739 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2740 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2741 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2742 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2743 * us the "null" on this circle, the new center of the candidate point will be some way along this
2744 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2745 * by the normal vector of the base triangle that always points outwards by construction.
2746 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2747 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2748 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2749 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2750 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2751 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2752 * both.
2753 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2754 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2755 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2756 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2757 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2758 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2759 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2760 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2761 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2762 * @param CandidateLine CandidateForTesselation with the current base line and list of candidates and ShortestAngle
2763 * @param ThirdNode third point to avoid in search
2764 * @param RADIUS radius of sphere
2765 * @param *LC LinkedCell structure with neighbouring points
2766 */
2767void Tesselation::FindThirdPointForTesselation(Vector &NormalVector, Vector &SearchDirection, Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class TesselPoint * const ThirdNode, const double RADIUS, const LinkedCell *LC) const
2768{
2769 Info FunctionInfo(__func__);
2770 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2771 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2772 Vector SphereCenter;
2773 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2774 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2775 Vector NewNormalVector; // normal vector of the Candidate's triangle
2776 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2777 Vector RelativeOldSphereCenter;
2778 Vector NewPlaneCenter;
2779 double CircleRadius; // radius of this circle
2780 double radius;
2781 double otherradius;
2782 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2783 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2784 TesselPoint *Candidate = NULL;
2785
2786 Log() << Verbose(1) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
2787
2788 // construct center of circle
2789 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2790 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2791 CircleCenter.Scale(0.5);
2792
2793 // construct normal vector of circle
2794 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2795 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2796
2797 RelativeOldSphereCenter.CopyVector(&OldSphereCenter);
2798 RelativeOldSphereCenter.SubtractVector(&CircleCenter);
2799
2800 // calculate squared radius TesselPoint *ThirdNode,f circle
2801 radius = CirclePlaneNormal.NormSquared()/4.;
2802 if (radius < RADIUS*RADIUS) {
2803 CircleRadius = RADIUS*RADIUS - radius;
2804 CirclePlaneNormal.Normalize();
2805 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2806
2807 // test whether old center is on the band's plane
2808 if (fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
2809 eLog() << Verbose(1) << "Something's very wrong here: RelativeOldSphereCenter is not on the band's plane as desired by " << fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
2810 RelativeOldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
2811 }
2812 radius = RelativeOldSphereCenter.NormSquared();
2813 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2814 Log() << Verbose(1) << "INFO: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << "." << endl;
2815
2816 // check SearchDirection
2817 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2818 if (fabs(RelativeOldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2819 eLog() << Verbose(1) << "SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
2820 }
2821
2822 // get cell for the starting point
2823 if (LC->SetIndexToVector(&CircleCenter)) {
2824 for(int i=0;i<NDIM;i++) // store indices of this cell
2825 N[i] = LC->n[i];
2826 //Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2827 } else {
2828 eLog() << Verbose(1) << "Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
2829 return;
2830 }
2831 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2832 //Log() << Verbose(1) << "LC Intervals:";
2833 for (int i=0;i<NDIM;i++) {
2834 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2835 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2836 //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2837 }
2838 //Log() << Verbose(0) << endl;
2839 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2840 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2841 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2842 const LinkedNodes *List = LC->GetCurrentCell();
2843 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2844 if (List != NULL) {
2845 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2846 Candidate = (*Runner);
2847
2848 // check for three unique points
2849 Log() << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " for BaseLine " << *CandidateLine.BaseLine << " with OldSphereCenter " << OldSphereCenter << "." << endl;
2850 if ((Candidate != CandidateLine.BaseLine->endpoints[0]->node) && (Candidate != CandidateLine.BaseLine->endpoints[1]->node) ){
2851
2852 // find center on the plane
2853 GetCenterofCircumcircle(&NewPlaneCenter, *CandidateLine.BaseLine->endpoints[0]->node->node, *CandidateLine.BaseLine->endpoints[1]->node->node, *Candidate->node);
2854 Log() << Verbose(1) << "INFO: NewPlaneCenter is " << NewPlaneCenter << "." << endl;
2855
2856 if (NewNormalVector.MakeNormalVector(CandidateLine.BaseLine->endpoints[0]->node->node, CandidateLine.BaseLine->endpoints[1]->node->node, Candidate->node)
2857 && (fabs(NewNormalVector.NormSquared()) > HULLEPSILON)
2858 ) {
2859 Log() << Verbose(1) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2860 radius = CandidateLine.BaseLine->endpoints[0]->node->node->DistanceSquared(&NewPlaneCenter);
2861 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2862 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2863 Log() << Verbose(1) << "INFO: Radius of CircumCenterCircle is " << radius << "." << endl;
2864 if (radius < RADIUS*RADIUS) {
2865 otherradius = CandidateLine.BaseLine->endpoints[1]->node->node->DistanceSquared(&NewPlaneCenter);
2866 if (fabs(radius - otherradius) > HULLEPSILON) {
2867 eLog() << Verbose(1) << "Distance to center of circumcircle is not the same from each corner of the triangle: " << fabs(radius-otherradius) << endl;
2868 }
2869 // construct both new centers
2870 NewSphereCenter.CopyVector(&NewPlaneCenter);
2871 OtherNewSphereCenter.CopyVector(&NewPlaneCenter);
2872 helper.CopyVector(&NewNormalVector);
2873 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2874 Log() << Verbose(2) << "INFO: Distance of NewPlaneCenter " << NewPlaneCenter << " to either NewSphereCenter is " << helper.Norm() << " of vector " << helper << " with sphere radius " << RADIUS << "." << endl;
2875 NewSphereCenter.AddVector(&helper);
2876 Log() << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
2877 // OtherNewSphereCenter is created by the same vector just in the other direction
2878 helper.Scale(-1.);
2879 OtherNewSphereCenter.AddVector(&helper);
2880 Log() << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2881
2882 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2883 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2884 alpha = min(alpha, Otheralpha);
2885
2886 // if there is a better candidate, drop the current list and add the new candidate
2887 // otherwise ignore the new candidate and keep the list
2888 if (CandidateLine.ShortestAngle > (alpha - HULLEPSILON)) {
2889 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2890 CandidateLine.OptCenter.CopyVector(&NewSphereCenter);
2891 CandidateLine.OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2892 } else {
2893 CandidateLine.OptCenter.CopyVector(&OtherNewSphereCenter);
2894 CandidateLine.OtherOptCenter.CopyVector(&NewSphereCenter);
2895 }
2896 // if there is an equal candidate, add it to the list without clearing the list
2897 if ((CandidateLine.ShortestAngle - HULLEPSILON) < alpha) {
2898 CandidateLine.pointlist.push_back(Candidate);
2899 Log() << Verbose(0) << "ACCEPT: We have found an equally good candidate: " << *(Candidate) << " with "
2900 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
2901 } else {
2902 // remove all candidates from the list and then the list itself
2903 CandidateLine.pointlist.clear();
2904 CandidateLine.pointlist.push_back(Candidate);
2905 Log() << Verbose(0) << "ACCEPT: We have found a better candidate: " << *(Candidate) << " with "
2906 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
2907 }
2908 CandidateLine.ShortestAngle = alpha;
2909 Log() << Verbose(0) << "INFO: There are " << CandidateLine.pointlist.size() << " candidates in the list now." << endl;
2910 } else {
2911 if ((Candidate != NULL) && (CandidateLine.pointlist.begin() != CandidateLine.pointlist.end())) {
2912 Log() << Verbose(1) << "REJECT: Old candidate " << *(Candidate) << " with " << CandidateLine.ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
2913 } else {
2914 Log() << Verbose(1) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2915 }
2916 }
2917 } else {
2918 Log() << Verbose(1) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
2919 }
2920 } else {
2921 Log() << Verbose(1) << "REJECT: Three points from " << *CandidateLine.BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2922 }
2923 } else {
2924 if (ThirdNode != NULL) {
2925 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2926 } else {
2927 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << "." << endl;
2928 }
2929 }
2930 }
2931 }
2932 }
2933 } else {
2934 eLog() << Verbose(1) << "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2935 }
2936 } else {
2937 if (ThirdNode != NULL)
2938 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2939 else
2940 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " is too big!" << endl;
2941 }
2942
2943 Log() << Verbose(1) << "INFO: Sorting candidate list ..." << endl;
2944 if (CandidateLine.pointlist.size() > 1) {
2945 CandidateLine.pointlist.unique();
2946 CandidateLine.pointlist.sort(); //SortCandidates);
2947 }
2948};
2949
2950/** Finds the endpoint two lines are sharing.
2951 * \param *line1 first line
2952 * \param *line2 second line
2953 * \return point which is shared or NULL if none
2954 */
2955class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
2956{
2957 Info FunctionInfo(__func__);
2958 const BoundaryLineSet * lines[2] = { line1, line2 };
2959 class BoundaryPointSet *node = NULL;
2960 PointMap OrderMap;
2961 PointTestPair OrderTest;
2962 for (int i = 0; i < 2; i++)
2963 // for both lines
2964 for (int j = 0; j < 2; j++)
2965 { // for both endpoints
2966 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
2967 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
2968 if (!OrderTest.second)
2969 { // if insertion fails, we have common endpoint
2970 node = OrderTest.first->second;
2971 Log() << Verbose(1) << "Common endpoint of lines " << *line1
2972 << " and " << *line2 << " is: " << *node << "." << endl;
2973 j = 2;
2974 i = 2;
2975 break;
2976 }
2977 }
2978 return node;
2979};
2980
2981/** Finds the boundary points that are closest to a given Vector \a *x.
2982 * \param *out output stream for debugging
2983 * \param *x Vector to look from
2984 * \return map of BoundaryPointSet of closest points sorted by squared distance or NULL.
2985 */
2986DistanceToPointMap * Tesselation::FindClosestBoundaryPointsToVector(const Vector *x, const LinkedCell* LC) const
2987{
2988 Info FunctionInfo(__func__);
2989 PointMap::const_iterator FindPoint;
2990 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2991
2992 if (LinesOnBoundary.empty()) {
2993 eLog() << Verbose(1) << "There is no tesselation structure to compare the point with, please create one first." << endl;
2994 return NULL;
2995 }
2996
2997 // gather all points close to the desired one
2998 LC->SetIndexToVector(x); // ignore status as we calculate bounds below sensibly
2999 for(int i=0;i<NDIM;i++) // store indices of this cell
3000 N[i] = LC->n[i];
3001 Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
3002
3003 DistanceToPointMap * points = new DistanceToPointMap;
3004 LC->GetNeighbourBounds(Nlower, Nupper);
3005 //Log() << Verbose(1) << endl;
3006 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
3007 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
3008 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
3009 const LinkedNodes *List = LC->GetCurrentCell();
3010 //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
3011 if (List != NULL) {
3012 for (LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
3013 FindPoint = PointsOnBoundary.find((*Runner)->nr);
3014 if (FindPoint != PointsOnBoundary.end()) {
3015 points->insert(DistanceToPointPair (FindPoint->second->node->node->DistanceSquared(x), FindPoint->second) );
3016 Log() << Verbose(1) << "INFO: Putting " << *FindPoint->second << " into the list." << endl;
3017 }
3018 }
3019 } else {
3020 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
3021 }
3022 }
3023
3024 // check whether we found some points
3025 if (points->empty()) {
3026 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3027 delete(points);
3028 return NULL;
3029 }
3030 return points;
3031};
3032
3033/** Finds the boundary line that is closest to a given Vector \a *x.
3034 * \param *out output stream for debugging
3035 * \param *x Vector to look from
3036 * \return closest BoundaryLineSet or NULL in degenerate case.
3037 */
3038BoundaryLineSet * Tesselation::FindClosestBoundaryLineToVector(const Vector *x, const LinkedCell* LC) const
3039{
3040 Info FunctionInfo(__func__);
3041
3042 // get closest points
3043 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
3044 if (points == NULL) {
3045 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3046 return NULL;
3047 }
3048
3049 // for each point, check its lines, remember closest
3050 Log() << Verbose(1) << "Finding closest BoundaryLine to " << *x << " ... " << endl;
3051 BoundaryLineSet *ClosestLine = NULL;
3052 double MinDistance = -1.;
3053 Vector helper;
3054 Vector Center;
3055 Vector BaseLine;
3056 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3057 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3058 // calculate closest point on line to desired point
3059 helper.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3060 helper.AddVector((LineRunner->second)->endpoints[1]->node->node);
3061 helper.Scale(0.5);
3062 Center.CopyVector(x);
3063 Center.SubtractVector(&helper);
3064 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3065 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3066 Center.ProjectOntoPlane(&BaseLine);
3067 const double distance = Center.NormSquared();
3068 if ((ClosestLine == NULL) || (distance < MinDistance)) {
3069 // additionally calculate intersection on line (whether it's on the line section or not)
3070 helper.CopyVector(x);
3071 helper.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3072 helper.SubtractVector(&Center);
3073 const double lengthA = helper.ScalarProduct(&BaseLine);
3074 helper.CopyVector(x);
3075 helper.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3076 helper.SubtractVector(&Center);
3077 const double lengthB = helper.ScalarProduct(&BaseLine);
3078 if (lengthB*lengthA < 0) { // if have different sign
3079 ClosestLine = LineRunner->second;
3080 MinDistance = distance;
3081 Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl;
3082 } else {
3083 Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl;
3084 }
3085 } else {
3086 Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl;
3087 }
3088 }
3089 }
3090 delete(points);
3091 // check whether closest line is "too close" :), then it's inside
3092 if (ClosestLine == NULL) {
3093 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3094 return NULL;
3095 }
3096 return ClosestLine;
3097};
3098
3099
3100/** Finds the triangle that is closest to a given Vector \a *x.
3101 * \param *out output stream for debugging
3102 * \param *x Vector to look from
3103 * \return BoundaryTriangleSet of nearest triangle or NULL.
3104 */
3105TriangleList * Tesselation::FindClosestTrianglesToVector(const Vector *x, const LinkedCell* LC) const
3106{
3107 Info FunctionInfo(__func__);
3108
3109 // get closest points
3110 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
3111 if (points == NULL) {
3112 eLog() << Verbose(1) << "There is no nearest point: too far away from the surface." << endl;
3113 return NULL;
3114 }
3115
3116 // for each point, check its lines, remember closest
3117 Log() << Verbose(1) << "Finding closest BoundaryTriangle to " << *x << " ... " << endl;
3118 BoundaryLineSet *ClosestLine = NULL;
3119 double MinDistance = 1e+16;
3120 Vector BaseLineIntersection;
3121 Vector Center;
3122 Vector BaseLine;
3123 Vector BaseLineCenter;
3124 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3125 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3126
3127 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3128 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3129 const double lengthBase = BaseLine.NormSquared();
3130
3131 BaseLineIntersection.CopyVector(x);
3132 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3133 const double lengthEndA = BaseLineIntersection.NormSquared();
3134
3135 BaseLineIntersection.CopyVector(x);
3136 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3137 const double lengthEndB = BaseLineIntersection.NormSquared();
3138
3139 if ((lengthEndA > lengthBase) || (lengthEndB > lengthBase) || ((lengthEndA < MYEPSILON) || (lengthEndB < MYEPSILON))) { // intersection would be outside, take closer endpoint
3140 if ((lengthEndA < MinDistance) && (lengthEndA < lengthEndB)) {
3141 ClosestLine = LineRunner->second;
3142 MinDistance = lengthEndA;
3143 Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[0]->node << " is closer with " << lengthEndA << "." << endl;
3144 } else if (lengthEndB < MinDistance) {
3145 ClosestLine = LineRunner->second;
3146 MinDistance = lengthEndB;
3147 Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[1]->node << " is closer with " << lengthEndB << "." << endl;
3148 } else {
3149 Log() << Verbose(1) << "REJECT: Line " << *LineRunner->second << " to either endpoints is further away than present closest line candidate: " << lengthEndA << ", " << lengthEndB << ", and distance is longer than baseline:" << lengthBase << "." << endl;
3150 }
3151 } else { // intersection is closer, calculate
3152 // calculate closest point on line to desired point
3153 BaseLineIntersection.CopyVector(x);
3154 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3155 Center.CopyVector(&BaseLineIntersection);
3156 Center.ProjectOntoPlane(&BaseLine);
3157 BaseLineIntersection.SubtractVector(&Center);
3158 const double distance = BaseLineIntersection.NormSquared();
3159 if (Center.NormSquared() > BaseLine.NormSquared()) {
3160 eLog() << Verbose(0) << "Algorithmic error: In second case we have intersection outside of baseline!" << endl;
3161 }
3162 if ((ClosestLine == NULL) || (distance < MinDistance)) {
3163 ClosestLine = LineRunner->second;
3164 MinDistance = distance;
3165 Log() << Verbose(1) << "ACCEPT: Intersection in between endpoints, new closest line " << *LineRunner->second << " is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl;
3166 } else {
3167 Log() << Verbose(2) << "REJECT: Point is further away from line " << *LineRunner->second << " than present closest line: " << distance << " >> " << MinDistance << "." << endl;
3168 }
3169 }
3170 }
3171 }
3172 delete(points);
3173
3174 // check whether closest line is "too close" :), then it's inside
3175 if (ClosestLine == NULL) {
3176 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3177 return NULL;
3178 }
3179 TriangleList * candidates = new TriangleList;
3180 for (TriangleMap::iterator Runner = ClosestLine->triangles.begin(); Runner != ClosestLine->triangles.end(); Runner++) {
3181 candidates->push_back(Runner->second);
3182 }
3183 return candidates;
3184};
3185
3186/** Finds closest triangle to a point.
3187 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
3188 * \param *out output stream for debugging
3189 * \param *x Vector to look from
3190 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
3191 */
3192class BoundaryTriangleSet * Tesselation::FindClosestTriangleToVector(const Vector *x, const LinkedCell* LC) const
3193{
3194 Info FunctionInfo(__func__);
3195 class BoundaryTriangleSet *result = NULL;
3196 TriangleList *triangles = FindClosestTrianglesToVector(x, LC);
3197 TriangleList candidates;
3198 Vector Center;
3199 Vector helper;
3200
3201 if ((triangles == NULL) || (triangles->empty()))
3202 return NULL;
3203
3204 // go through all and pick the one with the best alignment to x
3205 double MinAlignment = 2.*M_PI;
3206 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++) {
3207 (*Runner)->GetCenter(&Center);
3208 helper.CopyVector(x);
3209 helper.SubtractVector(&Center);
3210 const double Alignment = helper.Angle(&(*Runner)->NormalVector);
3211 if (Alignment < MinAlignment) {
3212 result = *Runner;
3213 MinAlignment = Alignment;
3214 Log() << Verbose(1) << "ACCEPT: Triangle " << *result << " is better aligned with " << MinAlignment << "." << endl;
3215 } else {
3216 Log() << Verbose(1) << "REJECT: Triangle " << *result << " is worse aligned with " << MinAlignment << "." << endl;
3217 }
3218 }
3219 delete(triangles);
3220
3221 return result;
3222};
3223
3224/** Checks whether the provided Vector is within the tesselation structure.
3225 * Calls FindClosestTriangleToVector() and checks whether the resulting triangle's BoundaryTriangleSet#NormalVector points
3226 * towards or away from the given \a &Point.
3227 *
3228 * @param point of which to check the position
3229 * @param *LC LinkedCell structure
3230 * @param epsilon Distance of \a &Point to Center of triangle (of point outwards) is tested less against this value (standard: -MYEPSILON)
3231 *
3232 * @return true if the point is inside the tesselation structure, false otherwise
3233 */
3234bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC, const double epsilon) const
3235{
3236 Info FunctionInfo(__func__);
3237 class BoundaryTriangleSet *result = FindClosestTriangleToVector(&Point, LC);
3238 Vector Center;
3239 Vector helper;
3240 Vector DistanceToCenter;
3241 Vector Intersection;
3242
3243 if (result == NULL) {// is boundary point or only point in point cloud?
3244 Log() << Verbose(1) << Point << " is the only point in vicinity." << endl;
3245 return false;
3246 } else {
3247 Log() << Verbose(1) << "INFO: Closest triangle found is " << *result << " with normal vector " << result->NormalVector << "." << endl;
3248 }
3249
3250 result->GetCenter(&Center);
3251 Log() << Verbose(2) << "INFO: Central point of the triangle is " << Center << "." << endl;
3252 DistanceToCenter.CopyVector(&Center);
3253 DistanceToCenter.SubtractVector(&Point);
3254 Log() << Verbose(2) << "INFO: Vector from point to test to center is " << DistanceToCenter << "." << endl;
3255
3256 // check whether we are on boundary
3257 if (fabs(DistanceToCenter.ScalarProduct(&result->NormalVector)) < MYEPSILON) {
3258 // calculate whether inside of triangle
3259 DistanceToCenter.CopyVector(&Point);
3260 Center.CopyVector(&Point);
3261 Center.SubtractVector(&result->NormalVector); // points towards MolCenter
3262 DistanceToCenter.AddVector(&result->NormalVector); // points outside
3263 Log() << Verbose(1) << "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << "." << endl;
3264 if (result->GetIntersectionInsideTriangle(&Center, &DistanceToCenter, &Intersection)) {
3265 Log() << Verbose(1) << Point << " is inner point: sufficiently close to boundary, " << Intersection << "." << endl;
3266 return true;
3267 } else {
3268 Log() << Verbose(1) << Point << " is NOT an inner point: on triangle plane but outside of triangle bounds." << endl;
3269 return false;
3270 }
3271 }
3272
3273 // then check direction to boundary
3274 if (DistanceToCenter.ScalarProduct(&result->NormalVector) > MYEPSILON) {
3275 Log() << Verbose(1) << Point << " is an inner point." << endl;
3276 return true;
3277 } else {
3278 Log() << Verbose(1) << Point << " is NOT an inner point." << endl;
3279 return false;
3280 }
3281}
3282
3283/** Gets all points connected to the provided point by triangulation lines.
3284 *
3285 * @param *Point of which get all connected points
3286 *
3287 * @return set of the all points linked to the provided one
3288 */
3289TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
3290{
3291 Info FunctionInfo(__func__);
3292 TesselPointSet *connectedPoints = new TesselPointSet;
3293 class BoundaryPointSet *ReferencePoint = NULL;
3294 TesselPoint* current;
3295 bool takePoint = false;
3296
3297 // find the respective boundary point
3298 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
3299 if (PointRunner != PointsOnBoundary.end()) {
3300 ReferencePoint = PointRunner->second;
3301 } else {
3302 eLog() << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
3303 ReferencePoint = NULL;
3304 }
3305
3306 // little trick so that we look just through lines connect to the BoundaryPoint
3307 // OR fall-back to look through all lines if there is no such BoundaryPoint
3308 const LineMap *Lines;;
3309 if (ReferencePoint != NULL)
3310 Lines = &(ReferencePoint->lines);
3311 else
3312 Lines = &LinesOnBoundary;
3313 LineMap::const_iterator findLines = Lines->begin();
3314 while (findLines != Lines->end()) {
3315 takePoint = false;
3316
3317 if (findLines->second->endpoints[0]->Nr == Point->nr) {
3318 takePoint = true;
3319 current = findLines->second->endpoints[1]->node;
3320 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
3321 takePoint = true;
3322 current = findLines->second->endpoints[0]->node;
3323 }
3324
3325 if (takePoint) {
3326 Log() << Verbose(1) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
3327 connectedPoints->insert(current);
3328 }
3329
3330 findLines++;
3331 }
3332
3333 if (connectedPoints->empty()) { // if have not found any points
3334 eLog() << Verbose(1) << "We have not found any connected points to " << *Point<< "." << endl;
3335 return NULL;
3336 }
3337
3338 return connectedPoints;
3339};
3340
3341
3342/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3343 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3344 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3345 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3346 * triangle we are looking for.
3347 *
3348 * @param *out output stream for debugging
3349 * @param *SetOfNeighbours all points for which the angle should be calculated
3350 * @param *Point of which get all connected points
3351 * @param *Reference Reference vector for zero angle or NULL for no preference
3352 * @return list of the all points linked to the provided one
3353 */
3354TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3355{
3356 Info FunctionInfo(__func__);
3357 map<double, TesselPoint*> anglesOfPoints;
3358 TesselPointList *connectedCircle = new TesselPointList;
3359 Vector PlaneNormal;
3360 Vector AngleZero;
3361 Vector OrthogonalVector;
3362 Vector helper;
3363 const TesselPoint * const TrianglePoints[3] = {Point, NULL, NULL};
3364 TriangleList *triangles = NULL;
3365
3366 if (SetOfNeighbours == NULL) {
3367 eLog() << Verbose(2) << "Could not find any connected points!" << endl;
3368 delete(connectedCircle);
3369 return NULL;
3370 }
3371
3372 // calculate central point
3373 triangles = FindTriangles(TrianglePoints);
3374 if ((triangles != NULL) && (!triangles->empty())) {
3375 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
3376 PlaneNormal.AddVector(&(*Runner)->NormalVector);
3377 } else {
3378 eLog() << Verbose(0) << "Could not find any triangles for point " << *Point << "." << endl;
3379 performCriticalExit();
3380 }
3381 PlaneNormal.Scale(1.0/triangles->size());
3382 Log() << Verbose(1) << "INFO: Calculated PlaneNormal of all circle points is " << PlaneNormal << "." << endl;
3383 PlaneNormal.Normalize();
3384
3385 // construct one orthogonal vector
3386 if (Reference != NULL) {
3387 AngleZero.CopyVector(Reference);
3388 AngleZero.SubtractVector(Point->node);
3389 AngleZero.ProjectOntoPlane(&PlaneNormal);
3390 }
3391 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3392 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3393 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3394 AngleZero.SubtractVector(Point->node);
3395 AngleZero.ProjectOntoPlane(&PlaneNormal);
3396 if (AngleZero.NormSquared() < MYEPSILON) {
3397 eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
3398 performCriticalExit();
3399 }
3400 }
3401 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3402 if (AngleZero.NormSquared() > MYEPSILON)
3403 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3404 else
3405 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3406 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3407
3408 // go through all connected points and calculate angle
3409 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3410 helper.CopyVector((*listRunner)->node);
3411 helper.SubtractVector(Point->node);
3412 helper.ProjectOntoPlane(&PlaneNormal);
3413 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3414 Log() << Verbose(0) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
3415 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3416 }
3417
3418 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3419 connectedCircle->push_back(AngleRunner->second);
3420 }
3421
3422 return connectedCircle;
3423}
3424
3425/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3426 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3427 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3428 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3429 * triangle we are looking for.
3430 *
3431 * @param *SetOfNeighbours all points for which the angle should be calculated
3432 * @param *Point of which get all connected points
3433 * @param *Reference Reference vector for zero angle or NULL for no preference
3434 * @return list of the all points linked to the provided one
3435 */
3436TesselPointList * Tesselation::GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3437{
3438 Info FunctionInfo(__func__);
3439 map<double, TesselPoint*> anglesOfPoints;
3440 TesselPointList *connectedCircle = new TesselPointList;
3441 Vector center;
3442 Vector PlaneNormal;
3443 Vector AngleZero;
3444 Vector OrthogonalVector;
3445 Vector helper;
3446
3447 if (SetOfNeighbours == NULL) {
3448 eLog() << Verbose(2) << "Could not find any connected points!" << endl;
3449 delete(connectedCircle);
3450 return NULL;
3451 }
3452
3453 // check whether there's something to do
3454 if (SetOfNeighbours->size() < 3) {
3455 for (TesselPointSet::iterator TesselRunner = SetOfNeighbours->begin(); TesselRunner != SetOfNeighbours->end(); TesselRunner++)
3456 connectedCircle->push_back(*TesselRunner);
3457 return connectedCircle;
3458 }
3459
3460 Log() << Verbose(1) << "INFO: Point is " << *Point << " and Reference is " << *Reference << "." << endl;
3461 // calculate central point
3462
3463 TesselPointSet::const_iterator TesselA = SetOfNeighbours->begin();
3464 TesselPointSet::const_iterator TesselB = SetOfNeighbours->begin();
3465 TesselPointSet::const_iterator TesselC = SetOfNeighbours->begin();
3466 TesselB++;
3467 TesselC++;
3468 TesselC++;
3469 int counter = 0;
3470 while (TesselC != SetOfNeighbours->end()) {
3471 helper.MakeNormalVector((*TesselA)->node, (*TesselB)->node, (*TesselC)->node);
3472 Log() << Verbose(0) << "Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper << endl;
3473 counter++;
3474 TesselA++;
3475 TesselB++;
3476 TesselC++;
3477 PlaneNormal.AddVector(&helper);
3478 }
3479 //Log() << Verbose(0) << "Summed vectors " << center << "; number of points " << connectedPoints.size()
3480 // << "; scale factor " << counter;
3481 PlaneNormal.Scale(1.0/(double)counter);
3482// Log() << Verbose(1) << "INFO: Calculated center of all circle points is " << center << "." << endl;
3483//
3484// // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
3485// PlaneNormal.CopyVector(Point->node);
3486// PlaneNormal.SubtractVector(&center);
3487// PlaneNormal.Normalize();
3488 Log() << Verbose(1) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
3489
3490 // construct one orthogonal vector
3491 if (Reference != NULL) {
3492 AngleZero.CopyVector(Reference);
3493 AngleZero.SubtractVector(Point->node);
3494 AngleZero.ProjectOntoPlane(&PlaneNormal);
3495 }
3496 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3497 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3498 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3499 AngleZero.SubtractVector(Point->node);
3500 AngleZero.ProjectOntoPlane(&PlaneNormal);
3501 if (AngleZero.NormSquared() < MYEPSILON) {
3502 eLog() << Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl;
3503 performCriticalExit();
3504 }
3505 }
3506 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3507 if (AngleZero.NormSquared() > MYEPSILON)
3508 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3509 else
3510 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3511 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3512
3513 // go through all connected points and calculate angle
3514 pair <map<double, TesselPoint*>::iterator, bool > InserterTest;
3515 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3516 helper.CopyVector((*listRunner)->node);
3517 helper.SubtractVector(Point->node);
3518 helper.ProjectOntoPlane(&PlaneNormal);
3519 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3520 if (angle > M_PI) // the correction is of no use here (and not desired)
3521 angle = 2.*M_PI - angle;
3522 Log() << Verbose(0) << "INFO: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << "." << endl;
3523 InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3524 if (!InserterTest.second) {
3525 eLog() << Verbose(0) << "GetCircleOfSetOfPoints() got two atoms with same angle: " << *((InserterTest.first)->second) << " and " << (*listRunner) << endl;
3526 performCriticalExit();
3527 }
3528 }
3529
3530 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3531 connectedCircle->push_back(AngleRunner->second);
3532 }
3533
3534 return connectedCircle;
3535}
3536
3537/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
3538 *
3539 * @param *out output stream for debugging
3540 * @param *Point of which get all connected points
3541 * @return list of the all points linked to the provided one
3542 */
3543list< TesselPointList *> * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
3544{
3545 Info FunctionInfo(__func__);
3546 map<double, TesselPoint*> anglesOfPoints;
3547 list< TesselPointList *> *ListOfPaths = new list< TesselPointList *>;
3548 TesselPointList *connectedPath = NULL;
3549 Vector center;
3550 Vector PlaneNormal;
3551 Vector AngleZero;
3552 Vector OrthogonalVector;
3553 Vector helper;
3554 class BoundaryPointSet *ReferencePoint = NULL;
3555 class BoundaryPointSet *CurrentPoint = NULL;
3556 class BoundaryTriangleSet *triangle = NULL;
3557 class BoundaryLineSet *CurrentLine = NULL;
3558 class BoundaryLineSet *StartLine = NULL;
3559
3560 // find the respective boundary point
3561 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
3562 if (PointRunner != PointsOnBoundary.end()) {
3563 ReferencePoint = PointRunner->second;
3564 } else {
3565 eLog() << Verbose(1) << "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
3566 return NULL;
3567 }
3568
3569 map <class BoundaryLineSet *, bool> TouchedLine;
3570 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
3571 map <class BoundaryLineSet *, bool>::iterator LineRunner;
3572 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
3573 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
3574 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
3575 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
3576 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
3577 }
3578 if (!ReferencePoint->lines.empty()) {
3579 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
3580 LineRunner = TouchedLine.find(runner->second);
3581 if (LineRunner == TouchedLine.end()) {
3582 eLog() << Verbose(1) << "I could not find " << *runner->second << " in the touched list." << endl;
3583 } else if (!LineRunner->second) {
3584 LineRunner->second = true;
3585 connectedPath = new TesselPointList;
3586 triangle = NULL;
3587 CurrentLine = runner->second;
3588 StartLine = CurrentLine;
3589 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3590 Log() << Verbose(1)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
3591 do {
3592 // push current one
3593 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3594 connectedPath->push_back(CurrentPoint->node);
3595
3596 // find next triangle
3597 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
3598 Log() << Verbose(1) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
3599 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
3600 triangle = Runner->second;
3601 TriangleRunner = TouchedTriangle.find(triangle);
3602 if (TriangleRunner != TouchedTriangle.end()) {
3603 if (!TriangleRunner->second) {
3604 TriangleRunner->second = true;
3605 Log() << Verbose(1) << "INFO: Connecting triangle is " << *triangle << "." << endl;
3606 break;
3607 } else {
3608 Log() << Verbose(1) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
3609 triangle = NULL;
3610 }
3611 } else {
3612 eLog() << Verbose(1) << "I could not find " << *triangle << " in the touched list." << endl;
3613 triangle = NULL;
3614 }
3615 }
3616 }
3617 if (triangle == NULL)
3618 break;
3619 // find next line
3620 for (int i=0;i<3;i++) {
3621 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
3622 CurrentLine = triangle->lines[i];
3623 Log() << Verbose(1) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
3624 break;
3625 }
3626 }
3627 LineRunner = TouchedLine.find(CurrentLine);
3628 if (LineRunner == TouchedLine.end())
3629 eLog() << Verbose(1) << "I could not find " << *CurrentLine << " in the touched list." << endl;
3630 else
3631 LineRunner->second = true;
3632 // find next point
3633 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3634
3635 } while (CurrentLine != StartLine);
3636 // last point is missing, as it's on start line
3637 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
3638 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
3639 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
3640
3641 ListOfPaths->push_back(connectedPath);
3642 } else {
3643 Log() << Verbose(1) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
3644 }
3645 }
3646 } else {
3647 eLog() << Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl;
3648 }
3649
3650 return ListOfPaths;
3651}
3652
3653/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
3654 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
3655 * @param *out output stream for debugging
3656 * @param *Point of which get all connected points
3657 * @return list of the closed paths
3658 */
3659list<TesselPointList *> * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
3660{
3661 Info FunctionInfo(__func__);
3662 list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
3663 list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *>;
3664 TesselPointList *connectedPath = NULL;
3665 TesselPointList *newPath = NULL;
3666 int count = 0;
3667
3668
3669 TesselPointList::iterator CircleRunner;
3670 TesselPointList::iterator CircleStart;
3671
3672 for(list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
3673 connectedPath = *ListRunner;
3674
3675 Log() << Verbose(1) << "INFO: Current path is " << connectedPath << "." << endl;
3676
3677 // go through list, look for reappearance of starting Point and count
3678 CircleStart = connectedPath->begin();
3679
3680 // go through list, look for reappearance of starting Point and create list
3681 TesselPointList::iterator Marker = CircleStart;
3682 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
3683 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
3684 // we have a closed circle from Marker to new Marker
3685 Log() << Verbose(1) << count+1 << ". closed path consists of: ";
3686 newPath = new TesselPointList;
3687 TesselPointList::iterator CircleSprinter = Marker;
3688 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
3689 newPath->push_back(*CircleSprinter);
3690 Log() << Verbose(0) << (**CircleSprinter) << " <-> ";
3691 }
3692 Log() << Verbose(0) << ".." << endl;
3693 count++;
3694 Marker = CircleRunner;
3695
3696 // add to list
3697 ListofClosedPaths->push_back(newPath);
3698 }
3699 }
3700 }
3701 Log() << Verbose(1) << "INFO: " << count << " closed additional path(s) have been created." << endl;
3702
3703 // delete list of paths
3704 while (!ListofPaths->empty()) {
3705 connectedPath = *(ListofPaths->begin());
3706 ListofPaths->remove(connectedPath);
3707 delete(connectedPath);
3708 }
3709 delete(ListofPaths);
3710
3711 // exit
3712 return ListofClosedPaths;
3713};
3714
3715
3716/** Gets all belonging triangles for a given BoundaryPointSet.
3717 * \param *out output stream for debugging
3718 * \param *Point BoundaryPoint
3719 * \return pointer to allocated list of triangles
3720 */
3721TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
3722{
3723 Info FunctionInfo(__func__);
3724 TriangleSet *connectedTriangles = new TriangleSet;
3725
3726 if (Point == NULL) {
3727 eLog() << Verbose(1) << "Point given is NULL." << endl;
3728 } else {
3729 // go through its lines and insert all triangles
3730 for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
3731 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
3732 connectedTriangles->insert(TriangleRunner->second);
3733 }
3734 }
3735
3736 return connectedTriangles;
3737};
3738
3739
3740/** Removes a boundary point from the envelope while keeping it closed.
3741 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
3742 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
3743 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
3744 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
3745 * -# the surface is closed, when the path is empty
3746 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
3747 * \param *out output stream for debugging
3748 * \param *point point to be removed
3749 * \return volume added to the volume inside the tesselated surface by the removal
3750 */
3751double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point) {
3752 class BoundaryLineSet *line = NULL;
3753 class BoundaryTriangleSet *triangle = NULL;
3754 Vector OldPoint, NormalVector;
3755 double volume = 0;
3756 int count = 0;
3757
3758 if (point == NULL) {
3759 eLog() << Verbose(1) << "Cannot remove the point " << point << ", it's NULL!" << endl;
3760 return 0.;
3761 } else
3762 Log() << Verbose(0) << "Removing point " << *point << " from tesselated boundary ..." << endl;
3763
3764 // copy old location for the volume
3765 OldPoint.CopyVector(point->node->node);
3766
3767 // get list of connected points
3768 if (point->lines.empty()) {
3769 eLog() << Verbose(1) << "Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
3770 return 0.;
3771 }
3772
3773 list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
3774 TesselPointList *connectedPath = NULL;
3775
3776 // gather all triangles
3777 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3778 count+=LineRunner->second->triangles.size();
3779 TriangleMap Candidates;
3780 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3781 line = LineRunner->second;
3782 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3783 triangle = TriangleRunner->second;
3784 Candidates.insert( TrianglePair (triangle->Nr, triangle) );
3785 }
3786 }
3787
3788 // remove all triangles
3789 count=0;
3790 NormalVector.Zero();
3791 for (TriangleMap::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3792 Log() << Verbose(1) << "INFO: Removing triangle " << *(Runner->second) << "." << endl;
3793 NormalVector.SubtractVector(&Runner->second->NormalVector); // has to point inward
3794 RemoveTesselationTriangle(Runner->second);
3795 count++;
3796 }
3797 Log() << Verbose(1) << count << " triangles were removed." << endl;
3798
3799 list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
3800 list<TesselPointList *>::iterator ListRunner = ListAdvance;
3801 TriangleMap::iterator NumberRunner = Candidates.begin();
3802 TesselPointList::iterator StartNode, MiddleNode, EndNode;
3803 double angle;
3804 double smallestangle;
3805 Vector Point, Reference, OrthogonalVector;
3806 if (count > 2) { // less than three triangles, then nothing will be created
3807 class TesselPoint *TriangleCandidates[3];
3808 count = 0;
3809 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3810 if (ListAdvance != ListOfClosedPaths->end())
3811 ListAdvance++;
3812
3813 connectedPath = *ListRunner;
3814
3815 // re-create all triangles by going through connected points list
3816 LineList NewLines;
3817 for (;!connectedPath->empty();) {
3818 // search middle node with widest angle to next neighbours
3819 EndNode = connectedPath->end();
3820 smallestangle = 0.;
3821 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3822 Log() << Verbose(1) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3823 // construct vectors to next and previous neighbour
3824 StartNode = MiddleNode;
3825 if (StartNode == connectedPath->begin())
3826 StartNode = connectedPath->end();
3827 StartNode--;
3828 //Log() << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
3829 Point.CopyVector((*StartNode)->node);
3830 Point.SubtractVector((*MiddleNode)->node);
3831 StartNode = MiddleNode;
3832 StartNode++;
3833 if (StartNode == connectedPath->end())
3834 StartNode = connectedPath->begin();
3835 //Log() << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
3836 Reference.CopyVector((*StartNode)->node);
3837 Reference.SubtractVector((*MiddleNode)->node);
3838 OrthogonalVector.CopyVector((*MiddleNode)->node);
3839 OrthogonalVector.SubtractVector(&OldPoint);
3840 OrthogonalVector.MakeNormalVector(&Reference);
3841 angle = GetAngle(Point, Reference, OrthogonalVector);
3842 //if (angle < M_PI) // no wrong-sided triangles, please?
3843 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3844 smallestangle = angle;
3845 EndNode = MiddleNode;
3846 }
3847 }
3848 MiddleNode = EndNode;
3849 if (MiddleNode == connectedPath->end()) {
3850 eLog() << Verbose(0) << "CRITICAL: Could not find a smallest angle!" << endl;
3851 performCriticalExit();
3852 }
3853 StartNode = MiddleNode;
3854 if (StartNode == connectedPath->begin())
3855 StartNode = connectedPath->end();
3856 StartNode--;
3857 EndNode++;
3858 if (EndNode == connectedPath->end())
3859 EndNode = connectedPath->begin();
3860 Log() << Verbose(2) << "INFO: StartNode is " << **StartNode << "." << endl;
3861 Log() << Verbose(2) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3862 Log() << Verbose(2) << "INFO: EndNode is " << **EndNode << "." << endl;
3863 Log() << Verbose(1) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
3864 TriangleCandidates[0] = *StartNode;
3865 TriangleCandidates[1] = *MiddleNode;
3866 TriangleCandidates[2] = *EndNode;
3867 triangle = GetPresentTriangle(TriangleCandidates);
3868 if (triangle != NULL) {
3869 eLog() << Verbose(0) << "New triangle already present, skipping!" << endl;
3870 StartNode++;
3871 MiddleNode++;
3872 EndNode++;
3873 if (StartNode == connectedPath->end())
3874 StartNode = connectedPath->begin();
3875 if (MiddleNode == connectedPath->end())
3876 MiddleNode = connectedPath->begin();
3877 if (EndNode == connectedPath->end())
3878 EndNode = connectedPath->begin();
3879 continue;
3880 }
3881 Log() << Verbose(3) << "Adding new triangle points."<< endl;
3882 AddTesselationPoint(*StartNode, 0);
3883 AddTesselationPoint(*MiddleNode, 1);
3884 AddTesselationPoint(*EndNode, 2);
3885 Log() << Verbose(3) << "Adding new triangle lines."<< endl;
3886 AddTesselationLine(TPS[0], TPS[1], 0);
3887 AddTesselationLine(TPS[0], TPS[2], 1);
3888 NewLines.push_back(BLS[1]);
3889 AddTesselationLine(TPS[1], TPS[2], 2);
3890 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3891 BTS->GetNormalVector(NormalVector);
3892 AddTesselationTriangle();
3893 // calculate volume summand as a general tetraeder
3894 volume += CalculateVolumeofGeneralTetraeder(*TPS[0]->node->node, *TPS[1]->node->node, *TPS[2]->node->node, OldPoint);
3895 // advance number
3896 count++;
3897
3898 // prepare nodes for next triangle
3899 StartNode = EndNode;
3900 Log() << Verbose(2) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
3901 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3902 if (connectedPath->size() == 2) { // we are done
3903 connectedPath->remove(*StartNode); // remove the start node
3904 connectedPath->remove(*EndNode); // remove the end node
3905 break;
3906 } else if (connectedPath->size() < 2) { // something's gone wrong!
3907 eLog() << Verbose(0) << "CRITICAL: There are only two endpoints left!" << endl;
3908 performCriticalExit();
3909 } else {
3910 MiddleNode = StartNode;
3911 MiddleNode++;
3912 if (MiddleNode == connectedPath->end())
3913 MiddleNode = connectedPath->begin();
3914 EndNode = MiddleNode;
3915 EndNode++;
3916 if (EndNode == connectedPath->end())
3917 EndNode = connectedPath->begin();
3918 }
3919 }
3920 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
3921 if (NewLines.size() > 1) {
3922 LineList::iterator Candidate;
3923 class BoundaryLineSet *OtherBase = NULL;
3924 double tmp, maxgain;
3925 do {
3926 maxgain = 0;
3927 for(LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
3928 tmp = PickFarthestofTwoBaselines(*Runner);
3929 if (maxgain < tmp) {
3930 maxgain = tmp;
3931 Candidate = Runner;
3932 }
3933 }
3934 if (maxgain != 0) {
3935 volume += maxgain;
3936 Log() << Verbose(1) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
3937 OtherBase = FlipBaseline(*Candidate);
3938 NewLines.erase(Candidate);
3939 NewLines.push_back(OtherBase);
3940 }
3941 } while (maxgain != 0.);
3942 }
3943
3944 ListOfClosedPaths->remove(connectedPath);
3945 delete(connectedPath);
3946 }
3947 Log() << Verbose(0) << count << " triangles were created." << endl;
3948 } else {
3949 while (!ListOfClosedPaths->empty()) {
3950 ListRunner = ListOfClosedPaths->begin();
3951 connectedPath = *ListRunner;
3952 ListOfClosedPaths->remove(connectedPath);
3953 delete(connectedPath);
3954 }
3955 Log() << Verbose(0) << "No need to create any triangles." << endl;
3956 }
3957 delete(ListOfClosedPaths);
3958
3959 Log() << Verbose(0) << "Removed volume is " << volume << "." << endl;
3960
3961 return volume;
3962};
3963
3964
3965
3966/**
3967 * Finds triangles belonging to the three provided points.
3968 *
3969 * @param *Points[3] list, is expected to contain three points (NULL means wildcard)
3970 *
3971 * @return triangles which belong to the provided points, will be empty if there are none,
3972 * will usually be one, in case of degeneration, there will be two
3973 */
3974TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
3975{
3976 Info FunctionInfo(__func__);
3977 TriangleList *result = new TriangleList;
3978 LineMap::const_iterator FindLine;
3979 TriangleMap::const_iterator FindTriangle;
3980 class BoundaryPointSet *TrianglePoints[3];
3981 size_t NoOfWildcards = 0;
3982
3983 for (int i = 0; i < 3; i++) {
3984 if (Points[i] == NULL) {
3985 NoOfWildcards++;
3986 TrianglePoints[i] = NULL;
3987 } else {
3988 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->nr);
3989 if (FindPoint != PointsOnBoundary.end()) {
3990 TrianglePoints[i] = FindPoint->second;
3991 } else {
3992 TrianglePoints[i] = NULL;
3993 }
3994 }
3995 }
3996
3997 switch (NoOfWildcards) {
3998 case 0: // checks lines between the points in the Points for their adjacent triangles
3999 for (int i = 0; i < 3; i++) {
4000 if (TrianglePoints[i] != NULL) {
4001 for (int j = i+1; j < 3; j++) {
4002 if (TrianglePoints[j] != NULL) {
4003 for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr); // is a multimap!
4004 (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->nr);
4005 FindLine++) {
4006 for (FindTriangle = FindLine->second->triangles.begin();
4007 FindTriangle != FindLine->second->triangles.end();
4008 FindTriangle++) {
4009 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
4010 result->push_back(FindTriangle->second);
4011 }
4012 }
4013 }
4014 // Is it sufficient to consider one of the triangle lines for this.
4015 return result;
4016 }
4017 }
4018 }
4019 }
4020 break;
4021 case 1: // copy all triangles of the respective line
4022 {
4023 int i=0;
4024 for (; i < 3; i++)
4025 if (TrianglePoints[i] == NULL)
4026 break;
4027 for (FindLine = TrianglePoints[(i+1)%3]->lines.find(TrianglePoints[(i+2)%3]->node->nr); // is a multimap!
4028 (FindLine != TrianglePoints[(i+1)%3]->lines.end()) && (FindLine->first == TrianglePoints[(i+2)%3]->node->nr);
4029 FindLine++) {
4030 for (FindTriangle = FindLine->second->triangles.begin();
4031 FindTriangle != FindLine->second->triangles.end();
4032 FindTriangle++) {
4033 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
4034 result->push_back(FindTriangle->second);
4035 }
4036 }
4037 }
4038 break;
4039 }
4040 case 2: // copy all triangles of the respective point
4041 {
4042 int i=0;
4043 for (; i < 3; i++)
4044 if (TrianglePoints[i] != NULL)
4045 break;
4046 for (LineMap::const_iterator line = TrianglePoints[i]->lines.begin(); line != TrianglePoints[i]->lines.end(); line++)
4047 for (TriangleMap::const_iterator triangle = line->second->triangles.begin(); triangle != line->second->triangles.end(); triangle++)
4048 result->push_back(triangle->second);
4049 result->sort();
4050 result->unique();
4051 break;
4052 }
4053 case 3: // copy all triangles
4054 {
4055 for (TriangleMap::const_iterator triangle = TrianglesOnBoundary.begin(); triangle != TrianglesOnBoundary.end(); triangle++)
4056 result->push_back(triangle->second);
4057 break;
4058 }
4059 default:
4060 eLog() << Verbose(0) << "Number of wildcards is greater than 3, cannot happen!" << endl;
4061 performCriticalExit();
4062 break;
4063 }
4064
4065 return result;
4066}
4067
4068struct BoundaryLineSetCompare {
4069 bool operator() (const BoundaryLineSet * const a, const BoundaryLineSet * const b) {
4070 int lowerNra = -1;
4071 int lowerNrb = -1;
4072
4073 if (a->endpoints[0] < a->endpoints[1])
4074 lowerNra = 0;
4075 else
4076 lowerNra = 1;
4077
4078 if (b->endpoints[0] < b->endpoints[1])
4079 lowerNrb = 0;
4080 else
4081 lowerNrb = 1;
4082
4083 if (a->endpoints[lowerNra] < b->endpoints[lowerNrb])
4084 return true;
4085 else if (a->endpoints[lowerNra] > b->endpoints[lowerNrb])
4086 return false;
4087 else { // both lower-numbered endpoints are the same ...
4088 if (a->endpoints[(lowerNra+1)%2] < b->endpoints[(lowerNrb+1)%2])
4089 return true;
4090 else if (a->endpoints[(lowerNra+1)%2] > b->endpoints[(lowerNrb+1)%2])
4091 return false;
4092 }
4093 return false;
4094 };
4095};
4096
4097#define UniqueLines set < class BoundaryLineSet *, BoundaryLineSetCompare>
4098
4099/**
4100 * Finds all degenerated lines within the tesselation structure.
4101 *
4102 * @return map of keys of degenerated line pairs, each line occurs twice
4103 * in the list, once as key and once as value
4104 */
4105IndexToIndex * Tesselation::FindAllDegeneratedLines()
4106{
4107 Info FunctionInfo(__func__);
4108 UniqueLines AllLines;
4109 IndexToIndex * DegeneratedLines = new IndexToIndex;
4110
4111 // sanity check
4112 if (LinesOnBoundary.empty()) {
4113 eLog() << Verbose(2) << "FindAllDegeneratedTriangles() was called without any tesselation structure.";
4114 return DegeneratedLines;
4115 }
4116
4117 LineMap::iterator LineRunner1;
4118 pair< UniqueLines::iterator, bool> tester;
4119 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
4120 tester = AllLines.insert( LineRunner1->second );
4121 if (!tester.second) { // found degenerated line
4122 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr) );
4123 DegeneratedLines->insert ( pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr) );
4124 }
4125 }
4126
4127 AllLines.clear();
4128
4129 Log() << Verbose(0) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
4130 IndexToIndex::iterator it;
4131 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
4132 const LineMap::const_iterator Line1 = LinesOnBoundary.find((*it).first);
4133 const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
4134 if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
4135 Log() << Verbose(0) << *Line1->second << " => " << *Line2->second << endl;
4136 else
4137 eLog() << Verbose(1) << "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!" << endl;
4138 }
4139
4140 return DegeneratedLines;
4141}
4142
4143/**
4144 * Finds all degenerated triangles within the tesselation structure.
4145 *
4146 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
4147 * in the list, once as key and once as value
4148 */
4149IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
4150{
4151 Info FunctionInfo(__func__);
4152 IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
4153 IndexToIndex * DegeneratedTriangles = new IndexToIndex;
4154
4155 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
4156 LineMap::iterator Liner;
4157 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
4158
4159 for (IndexToIndex::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
4160 // run over both lines' triangles
4161 Liner = LinesOnBoundary.find(LineRunner->first);
4162 if (Liner != LinesOnBoundary.end())
4163 line1 = Liner->second;
4164 Liner = LinesOnBoundary.find(LineRunner->second);
4165 if (Liner != LinesOnBoundary.end())
4166 line2 = Liner->second;
4167 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
4168 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
4169 if ((TriangleRunner1->second != TriangleRunner2->second)
4170 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
4171 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
4172 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
4173 }
4174 }
4175 }
4176 }
4177 delete(DegeneratedLines);
4178
4179 Log() << Verbose(0) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
4180 IndexToIndex::iterator it;
4181 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
4182 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
4183
4184 return DegeneratedTriangles;
4185}
4186
4187/**
4188 * Purges degenerated triangles from the tesselation structure if they are not
4189 * necessary to keep a single point within the structure.
4190 */
4191void Tesselation::RemoveDegeneratedTriangles()
4192{
4193 Info FunctionInfo(__func__);
4194 IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
4195 TriangleMap::iterator finder;
4196 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
4197 int count = 0;
4198
4199 for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
4200 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
4201 ) {
4202 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
4203 if (finder != TrianglesOnBoundary.end())
4204 triangle = finder->second;
4205 else
4206 break;
4207 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
4208 if (finder != TrianglesOnBoundary.end())
4209 partnerTriangle = finder->second;
4210 else
4211 break;
4212
4213 bool trianglesShareLine = false;
4214 for (int i = 0; i < 3; ++i)
4215 for (int j = 0; j < 3; ++j)
4216 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
4217
4218 if (trianglesShareLine
4219 && (triangle->endpoints[1]->LinesCount > 2)
4220 && (triangle->endpoints[2]->LinesCount > 2)
4221 && (triangle->endpoints[0]->LinesCount > 2)
4222 ) {
4223 // check whether we have to fix lines
4224 BoundaryTriangleSet *Othertriangle = NULL;
4225 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
4226 TriangleMap::iterator TriangleRunner;
4227 for (int i = 0; i < 3; ++i)
4228 for (int j = 0; j < 3; ++j)
4229 if (triangle->lines[i] != partnerTriangle->lines[j]) {
4230 // get the other two triangles
4231 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
4232 if (TriangleRunner->second != triangle) {
4233 Othertriangle = TriangleRunner->second;
4234 }
4235 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
4236 if (TriangleRunner->second != partnerTriangle) {
4237 OtherpartnerTriangle = TriangleRunner->second;
4238 }
4239 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
4240 // the line of triangle receives the degenerated ones
4241 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
4242 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
4243 for (int k=0;k<3;k++)
4244 if (triangle->lines[i] == Othertriangle->lines[k]) {
4245 Othertriangle->lines[k] = partnerTriangle->lines[j];
4246 break;
4247 }
4248 // the line of partnerTriangle receives the non-degenerated ones
4249 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
4250 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
4251 partnerTriangle->lines[j] = triangle->lines[i];
4252 }
4253
4254 // erase the pair
4255 count += (int) DegeneratedTriangles->erase(triangle->Nr);
4256 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
4257 RemoveTesselationTriangle(triangle);
4258 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
4259 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
4260 RemoveTesselationTriangle(partnerTriangle);
4261 } else {
4262 Log() << Verbose(0) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
4263 << " and its partner " << *partnerTriangle << " because it is essential for at"
4264 << " least one of the endpoints to be kept in the tesselation structure." << endl;
4265 }
4266 }
4267 delete(DegeneratedTriangles);
4268 if (count > 0)
4269 LastTriangle = NULL;
4270
4271 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
4272}
4273
4274/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
4275 * We look for the closest point on the boundary, we look through its connected boundary lines and
4276 * seek the one with the minimum angle between its center point and the new point and this base line.
4277 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
4278 * \param *out output stream for debugging
4279 * \param *point point to add
4280 * \param *LC Linked Cell structure to find nearest point
4281 */
4282void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC)
4283{
4284 Info FunctionInfo(__func__);
4285 // find nearest boundary point
4286 class TesselPoint *BackupPoint = NULL;
4287 class TesselPoint *NearestPoint = FindClosestTesselPoint(point->node, BackupPoint, LC);
4288 class BoundaryPointSet *NearestBoundaryPoint = NULL;
4289 PointMap::iterator PointRunner;
4290
4291 if (NearestPoint == point)
4292 NearestPoint = BackupPoint;
4293 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
4294 if (PointRunner != PointsOnBoundary.end()) {
4295 NearestBoundaryPoint = PointRunner->second;
4296 } else {
4297 eLog() << Verbose(1) << "I cannot find the boundary point." << endl;
4298 return;
4299 }
4300 Log() << Verbose(0) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
4301
4302 // go through its lines and find the best one to split
4303 Vector CenterToPoint;
4304 Vector BaseLine;
4305 double angle, BestAngle = 0.;
4306 class BoundaryLineSet *BestLine = NULL;
4307 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
4308 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
4309 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
4310 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
4311 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
4312 CenterToPoint.Scale(0.5);
4313 CenterToPoint.SubtractVector(point->node);
4314 angle = CenterToPoint.Angle(&BaseLine);
4315 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
4316 BestAngle = angle;
4317 BestLine = Runner->second;
4318 }
4319 }
4320
4321 // remove one triangle from the chosen line
4322 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
4323 BestLine->triangles.erase(TempTriangle->Nr);
4324 int nr = -1;
4325 for (int i=0;i<3; i++) {
4326 if (TempTriangle->lines[i] == BestLine) {
4327 nr = i;
4328 break;
4329 }
4330 }
4331
4332 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
4333 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4334 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4335 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4336 AddTesselationPoint(point, 2);
4337 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4338 AddTesselationLine(TPS[0], TPS[1], 0);
4339 AddTesselationLine(TPS[0], TPS[2], 1);
4340 AddTesselationLine(TPS[1], TPS[2], 2);
4341 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4342 BTS->GetNormalVector(TempTriangle->NormalVector);
4343 BTS->NormalVector.Scale(-1.);
4344 Log() << Verbose(1) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
4345 AddTesselationTriangle();
4346
4347 // create other side of this triangle and close both new sides of the first created triangle
4348 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4349 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4350 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4351 AddTesselationPoint(point, 2);
4352 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4353 AddTesselationLine(TPS[0], TPS[1], 0);
4354 AddTesselationLine(TPS[0], TPS[2], 1);
4355 AddTesselationLine(TPS[1], TPS[2], 2);
4356 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4357 BTS->GetNormalVector(TempTriangle->NormalVector);
4358 Log() << Verbose(1) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
4359 AddTesselationTriangle();
4360
4361 // add removed triangle to the last open line of the second triangle
4362 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
4363 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
4364 if (BestLine == BTS->lines[i]){
4365 eLog() << Verbose(0) << "BestLine is same as found line, something's wrong here!" << endl;
4366 performCriticalExit();
4367 }
4368 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
4369 TempTriangle->lines[nr] = BTS->lines[i];
4370 break;
4371 }
4372 }
4373};
4374
4375/** Writes the envelope to file.
4376 * \param *out otuput stream for debugging
4377 * \param *filename basename of output file
4378 * \param *cloud PointCloud structure with all nodes
4379 */
4380void Tesselation::Output(const char *filename, const PointCloud * const cloud)
4381{
4382 Info FunctionInfo(__func__);
4383 ofstream *tempstream = NULL;
4384 string NameofTempFile;
4385 char NumberName[255];
4386
4387 if (LastTriangle != NULL) {
4388 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
4389 if (DoTecplotOutput) {
4390 string NameofTempFile(filename);
4391 NameofTempFile.append(NumberName);
4392 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4393 NameofTempFile.erase(npos, 1);
4394 NameofTempFile.append(TecplotSuffix);
4395 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4396 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4397 WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
4398 tempstream->close();
4399 tempstream->flush();
4400 delete(tempstream);
4401 }
4402
4403 if (DoRaster3DOutput) {
4404 string NameofTempFile(filename);
4405 NameofTempFile.append(NumberName);
4406 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4407 NameofTempFile.erase(npos, 1);
4408 NameofTempFile.append(Raster3DSuffix);
4409 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4410 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4411 WriteRaster3dFile(tempstream, this, cloud);
4412 IncludeSphereinRaster3D(tempstream, this, cloud);
4413 tempstream->close();
4414 tempstream->flush();
4415 delete(tempstream);
4416 }
4417 }
4418 if (DoTecplotOutput || DoRaster3DOutput)
4419 TriangleFilesWritten++;
4420};
4421
4422struct BoundaryPolygonSetCompare {
4423 bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const {
4424 if (s1->endpoints.size() < s2->endpoints.size())
4425 return true;
4426 else if (s1->endpoints.size() > s2->endpoints.size())
4427 return false;
4428 else { // equality of number of endpoints
4429 PointSet::const_iterator Walker1 = s1->endpoints.begin();
4430 PointSet::const_iterator Walker2 = s2->endpoints.begin();
4431 while ((Walker1 != s1->endpoints.end()) || (Walker2 != s2->endpoints.end())) {
4432 if ((*Walker1)->Nr < (*Walker2)->Nr)
4433 return true;
4434 else if ((*Walker1)->Nr > (*Walker2)->Nr)
4435 return false;
4436 Walker1++;
4437 Walker2++;
4438 }
4439 return false;
4440 }
4441 }
4442};
4443
4444#define UniquePolygonSet set < BoundaryPolygonSet *, BoundaryPolygonSetCompare>
4445
4446/** Finds all degenerated polygons and calls ReTesselateDegeneratedPolygon()/
4447 * \return number of polygons found
4448 */
4449int Tesselation::CorrectAllDegeneratedPolygons()
4450{
4451 Info FunctionInfo(__func__);
4452
4453 /// 2. Go through all BoundaryPointSet's, check their triangles' NormalVector
4454 IndexToIndex *DegeneratedTriangles = FindAllDegeneratedTriangles();
4455 set < BoundaryPointSet *> EndpointCandidateList;
4456 pair < set < BoundaryPointSet *>::iterator, bool > InsertionTester;
4457 pair < map < int, Vector *>::iterator, bool > TriangleInsertionTester;
4458 for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
4459 Log() << Verbose(0) << "Current point is " << *Runner->second << "." << endl;
4460 map < int, Vector *> TriangleVectors;
4461 // gather all NormalVectors
4462 Log() << Verbose(1) << "Gathering triangles ..." << endl;
4463 for (LineMap::const_iterator LineRunner = (Runner->second)->lines.begin(); LineRunner != (Runner->second)->lines.end(); LineRunner++)
4464 for (TriangleMap::const_iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
4465 if (DegeneratedTriangles->find(TriangleRunner->second->Nr) == DegeneratedTriangles->end()) {
4466 TriangleInsertionTester = TriangleVectors.insert( pair< int, Vector *> ((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)) );
4467 if (TriangleInsertionTester.second)
4468 Log() << Verbose(1) << " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list." << endl;
4469 } else {
4470 Log() << Verbose(1) << " NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one." << endl;
4471 }
4472 }
4473 // check whether there are two that are parallel
4474 Log() << Verbose(1) << "Finding two parallel triangles ..." << endl;
4475 for (map < int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
4476 for (map < int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
4477 if (VectorWalker != VectorRunner) { // skip equals
4478 const double SCP = VectorWalker->second->ScalarProduct(VectorRunner->second); // ScalarProduct should result in -1. for degenerated triangles
4479 Log() << Verbose(1) << "Checking " << *VectorWalker->second<< " against " << *VectorRunner->second << ": " << SCP << endl;
4480 if (fabs(SCP + 1.) < ParallelEpsilon) {
4481 InsertionTester = EndpointCandidateList.insert((Runner->second));
4482 if (InsertionTester.second)
4483 Log() << Verbose(0) << " Adding " << *Runner->second << " to endpoint candidate list." << endl;
4484 // and break out of both loops
4485 VectorWalker = TriangleVectors.end();
4486 VectorRunner = TriangleVectors.end();
4487 break;
4488 }
4489 }
4490 }
4491
4492 /// 3. Find connected endpoint candidates and put them into a polygon
4493 UniquePolygonSet ListofDegeneratedPolygons;
4494 BoundaryPointSet *Walker = NULL;
4495 BoundaryPointSet *OtherWalker = NULL;
4496 BoundaryPolygonSet *Current = NULL;
4497 stack <BoundaryPointSet*> ToCheckConnecteds;
4498 while (!EndpointCandidateList.empty()) {
4499 Walker = *(EndpointCandidateList.begin());
4500 if (Current == NULL) { // create a new polygon with current candidate
4501 Log() << Verbose(0) << "Starting new polygon set at point " << *Walker << endl;
4502 Current = new BoundaryPolygonSet;
4503 Current->endpoints.insert(Walker);
4504 EndpointCandidateList.erase(Walker);
4505 ToCheckConnecteds.push(Walker);
4506 }
4507
4508 // go through to-check stack
4509 while (!ToCheckConnecteds.empty()) {
4510 Walker = ToCheckConnecteds.top(); // fetch ...
4511 ToCheckConnecteds.pop(); // ... and remove
4512 for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
4513 OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
4514 Log() << Verbose(1) << "Checking " << *OtherWalker << endl;
4515 set < BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
4516 if (Finder != EndpointCandidateList.end()) { // found a connected partner
4517 Log() << Verbose(1) << " Adding to polygon." << endl;
4518 Current->endpoints.insert(OtherWalker);
4519 EndpointCandidateList.erase(Finder); // remove from candidates
4520 ToCheckConnecteds.push(OtherWalker); // but check its partners too
4521 } else {
4522 Log() << Verbose(1) << " is not connected to " << *Walker << endl;
4523 }
4524 }
4525 }
4526
4527 Log() << Verbose(0) << "Final polygon is " << *Current << endl;
4528 ListofDegeneratedPolygons.insert(Current);
4529 Current = NULL;
4530 }
4531
4532 const int counter = ListofDegeneratedPolygons.size();
4533
4534 Log() << Verbose(0) << "The following " << counter << " degenerated polygons have been found: " << endl;
4535 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
4536 Log() << Verbose(0) << " " << **PolygonRunner << endl;
4537
4538 /// 4. Go through all these degenerated polygons
4539 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++) {
4540 stack <int> TriangleNrs;
4541 Vector NormalVector;
4542 /// 4a. Gather all triangles of this polygon
4543 TriangleSet *T = (*PolygonRunner)->GetAllContainedTrianglesFromEndpoints();
4544
4545 // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
4546 if (T->size() == 2) {
4547 Log() << Verbose(1) << " Skipping degenerated polygon, is just a (already simply degenerated) triangle." << endl;
4548 delete(T);
4549 continue;
4550 }
4551
4552 // check whether number is even
4553 // If this case occurs, we have to think about it!
4554 // The Problem is probably due to two degenerated polygons being connected by a bridging, non-degenerated polygon, as somehow one node has
4555 // connections to either polygon ...
4556 if (T->size() % 2 != 0) {
4557 eLog() << Verbose(0) << " degenerated polygon contains an odd number of triangles, probably contains bridging non-degenerated ones, too!" << endl;
4558 performCriticalExit();
4559 }
4560
4561 TriangleSet::iterator TriangleWalker = T->begin(); // is the inner iterator
4562 /// 4a. Get NormalVector for one side (this is "front")
4563 NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
4564 Log() << Verbose(1) << "\"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector << endl;
4565 TriangleWalker++;
4566 TriangleSet::iterator TriangleSprinter = TriangleWalker; // is the inner advanced iterator
4567 /// 4b. Remove all triangles whose NormalVector is in opposite direction (i.e. "back")
4568 BoundaryTriangleSet *triangle = NULL;
4569 while (TriangleSprinter != T->end()) {
4570 TriangleWalker = TriangleSprinter;
4571 triangle = *TriangleWalker;
4572 TriangleSprinter++;
4573 Log() << Verbose(1) << "Current triangle to test for removal: " << *triangle << endl;
4574 if (triangle->NormalVector.ScalarProduct(&NormalVector) < 0) { // if from other side, then delete and remove from list
4575 Log() << Verbose(1) << " Removing ... " << endl;
4576 TriangleNrs.push(triangle->Nr);
4577 T->erase(TriangleWalker);
4578 RemoveTesselationTriangle(triangle);
4579 } else
4580 Log() << Verbose(1) << " Keeping ... " << endl;
4581 }
4582 /// 4c. Copy all "front" triangles but with inverse NormalVector
4583 TriangleWalker = T->begin();
4584 while (TriangleWalker != T->end()) { // go through all front triangles
4585 Log() << Verbose(1) << " Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector << endl;
4586 for (int i = 0; i < 3; i++)
4587 AddTesselationPoint((*TriangleWalker)->endpoints[i]->node, i);
4588 AddTesselationLine(TPS[0], TPS[1], 0);
4589 AddTesselationLine(TPS[0], TPS[2], 1);
4590 AddTesselationLine(TPS[1], TPS[2], 2);
4591 if (TriangleNrs.empty())
4592 eLog() << Verbose(0) << "No more free triangle numbers!" << endl;
4593 BTS = new BoundaryTriangleSet(BLS, TriangleNrs.top()); // copy triangle ...
4594 AddTesselationTriangle(); // ... and add
4595 TriangleNrs.pop();
4596 BTS->NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
4597 BTS->NormalVector.Scale(-1.);
4598 TriangleWalker++;
4599 }
4600 if (!TriangleNrs.empty()) {
4601 eLog() << Verbose(0) << "There have been less triangles created than removed!" << endl;
4602 }
4603 delete(T); // remove the triangleset
4604 }
4605
4606 IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
4607 Log() << Verbose(0) << "Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:" << endl;
4608 IndexToIndex::iterator it;
4609 for (it = SimplyDegeneratedTriangles->begin(); it != SimplyDegeneratedTriangles->end(); it++)
4610 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
4611 delete(SimplyDegeneratedTriangles);
4612
4613 /// 5. exit
4614 UniquePolygonSet::iterator PolygonRunner;
4615 while (!ListofDegeneratedPolygons.empty()) {
4616 PolygonRunner = ListofDegeneratedPolygons.begin();
4617 delete(*PolygonRunner);
4618 ListofDegeneratedPolygons.erase(PolygonRunner);
4619 }
4620
4621 return counter;
4622};
Note: See TracBrowser for help on using the repository browser.