source: src/tesselation.cpp@ c39cc4

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

Merge branch 'StructureRefactoring' of jupiter:espack into StructureRefactoring

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