source: src/tesselation.cpp@ 474961

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

New approach to degenerated triangles: Recognize on creation and add both sides at once.

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