source: src/tesselation.cpp@ ba9f5b

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

MEMFIXES: Tesselation routines were leaking memory.

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

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