source: src/tesselation.cpp@ bc84ffc

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

Memory leak fixes and code cleanup after tesselation rewrite.

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