source: src/tesselation.cpp@ 58ed4a

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 58ed4a was 58ed4a, checked in by Frederik Heber <heber@…>, 15 years ago

Log() and eLog() are prepended by a DoLog()/DoeLog() construct.

  • Most of the run time (95%) is spent on verbosity that it is discarded anyway due to a low verbosity setting. However, the operator << is evaluated from the right-hand side, hence the whole message is constructed and then thrown away.
  • DoLog() and DoeLog() are new functions that check the verbosity beforehand and are used as follows: DoLog(2) && (Log() << verbose(2) << "message" << endl);

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

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