source: src/tesselation.cpp@ ebb50e

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

Renamed AddCandidateTriangle() -> AddCandidatePolygon()

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