source: src/tesselation.cpp@ 36166d

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 36166d was 36166d, checked in by Tillmann Crueger <crueger@…>, 15 years ago

Removed left over parts from old memory-tracker

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