source: src/tesselation.cpp@ a3696f

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 a3696f was 734816, checked in by heber <heber@…>, 15 years ago

LinkedNodes is now declared inside LinkedCell and some new functions.

  • as prepraratory measure we placed LinkedNodes as typedef into LinkedCell class. This caused same namespace changes elsewhere where LinkedNodes is used.
  • new function GetallNeighbours() which performs going through linked cells.
  • new function GetPointsInsideaSphere() which performs going through linked cells and returns all neighbours up to a given distance to a given center.

Note: New functions are not yet used elsewhere. Unit test has to be written beforehand.

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

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