source: src/tesselation.cpp@ f67b6e

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

Multi-Candidate-Add included and incorporated class Info into boundary.cpp, tesselation.cpp and tesselationhelpers.cpp

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