source: src/tesselation.cpp@ 061b06

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

FIX: If multiple open lines can be chosen in AddTesselationLine(), then pick the one for which candidate matches first.

  • Property mode set to 100644
File size: 226.0 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 *candidate third point of the triangle to be, for checking between multiple open line candidates
1830 * @param *a first endpoint
1831 * @param *b second endpoint
1832 * @param n index of Tesselation::BLS giving the line with both endpoints
1833 */
1834void Tesselation::AddTesselationLine(const BoundaryPointSet * const candidate, class BoundaryPointSet *a, class BoundaryPointSet *b, const int n) {
1835 bool insertNewLine = true;
1836
1837 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1838 BoundaryLineSet *WinningLine = NULL;
1839 if (FindLine != a->lines.end()) {
1840 Log() << Verbose(1) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1841
1842 pair<LineMap::iterator,LineMap::iterator> FindPair;
1843 FindPair = a->lines.equal_range(b->node->nr);
1844
1845 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1846 Log() << Verbose(1) << "INFO: Checking line " << *(FindLine->second) << " ..." << endl;
1847 // If there is a line with less than two attached triangles, we don't need a new line.
1848 if (FindLine->second->triangles.size() == 1) {
1849 // get open line
1850 CandidateMap::iterator Finder = OpenLines.find(FindLine->second);
1851 insertNewLine = false;
1852 WinningLine = FindLine->second;
1853 if ((!Finder->second->pointlist.empty()) && (*(Finder->second->pointlist.begin()) == candidate->node)) { // stop searching if candidate matches
1854 break;
1855 }
1856 }
1857 }
1858 }
1859
1860 if (insertNewLine) {
1861 AddNewTesselationTriangleLine(a, b, n);
1862 } else {
1863 AddExistingTesselationTriangleLine(WinningLine, n);
1864 }
1865}
1866;
1867
1868/**
1869 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1870 * Raises the line count and inserts the new line into the BLS.
1871 *
1872 * @param *a first endpoint
1873 * @param *b second endpoint
1874 * @param n index of Tesselation::BLS giving the line with both endpoints
1875 */
1876void Tesselation::AddNewTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, const int n)
1877{
1878 Info FunctionInfo(__func__);
1879 Log() << Verbose(0) << "Adding open line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1880 BPS[0] = a;
1881 BPS[1] = b;
1882 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1883 // add line to global map
1884 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1885 // increase counter
1886 LinesOnBoundaryCount++;
1887 // also add to open lines
1888 CandidateForTesselation *CFT = new CandidateForTesselation(BLS[n]);
1889 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (BLS[n], CFT));
1890};
1891
1892/** Uses an existing line for a new triangle.
1893 * Sets Tesselation::BLS[\a n] and removes the lines from Tesselation::OpenLines.
1894 * \param *FindLine the line to add
1895 * \param n index of the line to set in Tesselation::BLS
1896 */
1897void Tesselation::AddExistingTesselationTriangleLine(class BoundaryLineSet *Line, int n)
1898{
1899 Info FunctionInfo(__func__);
1900 Log() << Verbose(0) << "Using existing line " << *Line << endl;
1901
1902 // set endpoints and line
1903 BPS[0] = Line->endpoints[0];
1904 BPS[1] = Line->endpoints[1];
1905 BLS[n] = Line;
1906
1907 // remove existing line from OpenLines
1908 CandidateMap::iterator CandidateLine = OpenLines.find(BLS[n]);
1909 if (CandidateLine != OpenLines.end()) {
1910 Log() << Verbose(1) << " Removing line from OpenLines." << endl;
1911 delete(CandidateLine->second);
1912 OpenLines.erase(CandidateLine);
1913 } else {
1914 DoeLog(1) && (eLog()<< Verbose(1) << "Line exists and is attached to less than two triangles, but not in OpenLines!" << endl);
1915 }
1916};
1917
1918/** Function adds triangle to global list.
1919 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1920 */
1921void Tesselation::AddTesselationTriangle()
1922{
1923 Info FunctionInfo(__func__);
1924 Log() << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1925
1926 // add triangle to global map
1927 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1928 TrianglesOnBoundaryCount++;
1929
1930 // set as last new triangle
1931 LastTriangle = BTS;
1932
1933 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1934};
1935
1936/** Function adds triangle to global list.
1937 * Furthermore, the triangle number is set to \a nr.
1938 * \param nr triangle number
1939 */
1940void Tesselation::AddTesselationTriangle(const int nr)
1941{
1942 Info FunctionInfo(__func__);
1943 Log() << Verbose(0) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1944
1945 // add triangle to global map
1946 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1947
1948 // set as last new triangle
1949 LastTriangle = BTS;
1950
1951 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1952};
1953
1954/** Removes a triangle from the tesselation.
1955 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1956 * Removes itself from memory.
1957 * \param *triangle to remove
1958 */
1959void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1960{
1961 Info FunctionInfo(__func__);
1962 if (triangle == NULL)
1963 return;
1964 for (int i = 0; i < 3; i++) {
1965 if (triangle->lines[i] != NULL) {
1966 Log() << Verbose(0) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1967 triangle->lines[i]->triangles.erase(triangle->Nr);
1968 if (triangle->lines[i]->triangles.empty()) {
1969 Log() << Verbose(0) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1970 RemoveTesselationLine(triangle->lines[i]);
1971 } else {
1972 Log() << Verbose(0) << *triangle->lines[i] << " is still attached to another triangle: ";
1973 OpenLines.insert(pair< BoundaryLineSet *, CandidateForTesselation *> (triangle->lines[i], NULL));
1974 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1975 Log() << Verbose(0) << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1976 Log() << Verbose(0) << endl;
1977// for (int j=0;j<2;j++) {
1978// Log() << Verbose(0) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1979// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1980// Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
1981// Log() << Verbose(0) << endl;
1982// }
1983 }
1984 triangle->lines[i] = NULL; // free'd or not: disconnect
1985 } else
1986 DoeLog(1) && (eLog()<< Verbose(1) << "This line " << i << " has already been free'd." << endl);
1987 }
1988
1989 if (TrianglesOnBoundary.erase(triangle->Nr))
1990 Log() << Verbose(0) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1991 delete(triangle);
1992};
1993
1994/** Removes a line from the tesselation.
1995 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1996 * \param *line line to remove
1997 */
1998void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1999{
2000 Info FunctionInfo(__func__);
2001 int Numbers[2];
2002
2003 if (line == NULL)
2004 return;
2005 // get other endpoint number for finding copies of same line
2006 if (line->endpoints[1] != NULL)
2007 Numbers[0] = line->endpoints[1]->Nr;
2008 else
2009 Numbers[0] = -1;
2010 if (line->endpoints[0] != NULL)
2011 Numbers[1] = line->endpoints[0]->Nr;
2012 else
2013 Numbers[1] = -1;
2014
2015 for (int i = 0; i < 2; i++) {
2016 if (line->endpoints[i] != NULL) {
2017 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
2018 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
2019 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
2020 if ((*Runner).second == line) {
2021 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
2022 line->endpoints[i]->lines.erase(Runner);
2023 break;
2024 }
2025 } else { // there's just a single line left
2026 if (line->endpoints[i]->lines.erase(line->Nr))
2027 Log() << Verbose(0) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
2028 }
2029 if (line->endpoints[i]->lines.empty()) {
2030 Log() << Verbose(0) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
2031 RemoveTesselationPoint(line->endpoints[i]);
2032 } else {
2033 Log() << Verbose(0) << *line->endpoints[i] << " has still lines it's attached to: ";
2034 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
2035 Log() << Verbose(0) << "[" << *(LineRunner->second) << "] \t";
2036 Log() << Verbose(0) << endl;
2037 }
2038 line->endpoints[i] = NULL; // free'd or not: disconnect
2039 } else
2040 DoeLog(1) && (eLog()<< Verbose(1) << "Endpoint " << i << " has already been free'd." << endl);
2041 }
2042 if (!line->triangles.empty())
2043 DoeLog(2) && (eLog()<< Verbose(2) << "Memory Leak! I " << *line << " am still connected to some triangles." << endl);
2044
2045 if (LinesOnBoundary.erase(line->Nr))
2046 Log() << Verbose(0) << "Removing line Nr. " << line->Nr << "." << endl;
2047 delete(line);
2048};
2049
2050/** Removes a point from the tesselation.
2051 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
2052 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
2053 * \param *point point to remove
2054 */
2055void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
2056{
2057 Info FunctionInfo(__func__);
2058 if (point == NULL)
2059 return;
2060 if (PointsOnBoundary.erase(point->Nr))
2061 Log() << Verbose(0) << "Removing point Nr. " << point->Nr << "." << endl;
2062 delete(point);
2063};
2064
2065/** Checks whether the triangle consisting of the three points is already present.
2066 * Searches for the points in Tesselation::PointsOnBoundary and checks their
2067 * lines. If any of the three edges already has two triangles attached, false is
2068 * returned.
2069 * \param *out output stream for debugging
2070 * \param *Candidates endpoints of the triangle candidate
2071 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
2072 * triangles exist which is the maximum for three points
2073 */
2074int Tesselation::CheckPresenceOfTriangle(TesselPoint *Candidates[3]) const
2075{
2076 Info FunctionInfo(__func__);
2077 int adjacentTriangleCount = 0;
2078 class BoundaryPointSet *Points[3];
2079
2080 // builds a triangle point set (Points) of the end points
2081 for (int i = 0; i < 3; i++) {
2082 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
2083 if (FindPoint != PointsOnBoundary.end()) {
2084 Points[i] = FindPoint->second;
2085 } else {
2086 Points[i] = NULL;
2087 }
2088 }
2089
2090 // checks lines between the points in the Points for their adjacent triangles
2091 for (int i = 0; i < 3; i++) {
2092 if (Points[i] != NULL) {
2093 for (int j = i; j < 3; j++) {
2094 if (Points[j] != NULL) {
2095 LineMap::const_iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
2096 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
2097 TriangleMap *triangles = &FindLine->second->triangles;
2098 Log() << Verbose(1) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
2099 for (TriangleMap::const_iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
2100 if (FindTriangle->second->IsPresentTupel(Points)) {
2101 adjacentTriangleCount++;
2102 }
2103 }
2104 Log() << Verbose(1) << "end." << endl;
2105 }
2106 // Only one of the triangle lines must be considered for the triangle count.
2107 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
2108 //return adjacentTriangleCount;
2109 }
2110 }
2111 }
2112 }
2113
2114 Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
2115 return adjacentTriangleCount;
2116};
2117
2118/** Checks whether the triangle consisting of the three points is already present.
2119 * Searches for the points in Tesselation::PointsOnBoundary and checks their
2120 * lines. If any of the three edges already has two triangles attached, false is
2121 * returned.
2122 * \param *out output stream for debugging
2123 * \param *Candidates endpoints of the triangle candidate
2124 * \return NULL - none found or pointer to triangle
2125 */
2126class BoundaryTriangleSet * Tesselation::GetPresentTriangle(TesselPoint *Candidates[3])
2127{
2128 Info FunctionInfo(__func__);
2129 class BoundaryTriangleSet *triangle = NULL;
2130 class BoundaryPointSet *Points[3];
2131
2132 // builds a triangle point set (Points) of the end points
2133 for (int i = 0; i < 3; i++) {
2134 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
2135 if (FindPoint != PointsOnBoundary.end()) {
2136 Points[i] = FindPoint->second;
2137 } else {
2138 Points[i] = NULL;
2139 }
2140 }
2141
2142 // checks lines between the points in the Points for their adjacent triangles
2143 for (int i = 0; i < 3; i++) {
2144 if (Points[i] != NULL) {
2145 for (int j = i; j < 3; j++) {
2146 if (Points[j] != NULL) {
2147 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
2148 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
2149 TriangleMap *triangles = &FindLine->second->triangles;
2150 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
2151 if (FindTriangle->second->IsPresentTupel(Points)) {
2152 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
2153 triangle = FindTriangle->second;
2154 }
2155 }
2156 }
2157 // Only one of the triangle lines must be considered for the triangle count.
2158 //Log() << Verbose(0) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
2159 //return adjacentTriangleCount;
2160 }
2161 }
2162 }
2163 }
2164
2165 return triangle;
2166};
2167
2168
2169/** Finds the starting triangle for FindNonConvexBorder().
2170 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
2171 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
2172 * point are called.
2173 * \param *out output stream for debugging
2174 * \param RADIUS radius of virtual rolling sphere
2175 * \param *LC LinkedCell structure with neighbouring TesselPoint's
2176 */
2177void Tesselation::FindStartingTriangle(const double RADIUS, const LinkedCell *LC)
2178{
2179 Info FunctionInfo(__func__);
2180 int i = 0;
2181 TesselPoint* MaxPoint[NDIM];
2182 TesselPoint* Temporary;
2183 double maxCoordinate[NDIM];
2184 BoundaryLineSet BaseLine;
2185 Vector helper;
2186 Vector Chord;
2187 Vector SearchDirection;
2188 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2189 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2190 Vector SphereCenter;
2191 Vector NormalVector;
2192
2193 NormalVector.Zero();
2194
2195 for (i = 0; i < 3; i++) {
2196 MaxPoint[i] = NULL;
2197 maxCoordinate[i] = -1;
2198 }
2199
2200 // 1. searching topmost point with respect to each axis
2201 for (int i=0;i<NDIM;i++) { // each axis
2202 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
2203 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
2204 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
2205 const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
2206 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2207 if (List != NULL) {
2208 for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin();Runner != List->end();Runner++) {
2209 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
2210 Log() << Verbose(1) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
2211 maxCoordinate[i] = (*Runner)->node->x[i];
2212 MaxPoint[i] = (*Runner);
2213 }
2214 }
2215 } else {
2216 DoeLog(1) && (eLog()<< Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl);
2217 }
2218 }
2219 }
2220
2221 Log() << Verbose(1) << "Found maximum coordinates: ";
2222 for (int i=0;i<NDIM;i++)
2223 Log() << Verbose(0) << i << ": " << *MaxPoint[i] << "\t";
2224 Log() << Verbose(0) << endl;
2225
2226 BTS = NULL;
2227 for (int k=0;k<NDIM;k++) {
2228 NormalVector.Zero();
2229 NormalVector.x[k] = 1.;
2230 BaseLine.endpoints[0] = new BoundaryPointSet(MaxPoint[k]);
2231 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
2232
2233 double ShortestAngle;
2234 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.
2235
2236 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_...
2237 if (Temporary == NULL) // have we found a second point?
2238 continue;
2239 BaseLine.endpoints[1] = new BoundaryPointSet(Temporary);
2240
2241 // construct center of circle
2242 CircleCenter.CopyVector(BaseLine.endpoints[0]->node->node);
2243 CircleCenter.AddVector(BaseLine.endpoints[1]->node->node);
2244 CircleCenter.Scale(0.5);
2245
2246 // construct normal vector of circle
2247 CirclePlaneNormal.CopyVector(BaseLine.endpoints[0]->node->node);
2248 CirclePlaneNormal.SubtractVector(BaseLine.endpoints[1]->node->node);
2249
2250 double radius = CirclePlaneNormal.NormSquared();
2251 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
2252
2253 NormalVector.ProjectOntoPlane(&CirclePlaneNormal);
2254 NormalVector.Normalize();
2255 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2256
2257 SphereCenter.CopyVector(&NormalVector);
2258 SphereCenter.Scale(CircleRadius);
2259 SphereCenter.AddVector(&CircleCenter);
2260 // Now, NormalVector and SphereCenter are two orthonormalized vectors in the plane defined by CirclePlaneNormal (not normalized)
2261
2262 // look in one direction of baseline for initial candidate
2263 SearchDirection.MakeNormalVector(&CirclePlaneNormal, &NormalVector); // whether we look "left" first or "right" first is not important ...
2264
2265 // adding point 1 and point 2 and add the line between them
2266 Log() << Verbose(0) << "Coordinates of start node at " << *BaseLine.endpoints[0]->node << "." << endl;
2267 Log() << Verbose(0) << "Found second point is at " << *BaseLine.endpoints[1]->node << ".\n";
2268
2269 //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << helper << ".\n";
2270 CandidateForTesselation OptCandidates(&BaseLine);
2271 FindThirdPointForTesselation(NormalVector, SearchDirection, SphereCenter, OptCandidates, NULL, RADIUS, LC);
2272 Log() << Verbose(0) << "List of third Points is:" << endl;
2273 for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); it++) {
2274 Log() << Verbose(0) << " " << *(*it) << endl;
2275 }
2276
2277 BTS = NULL;
2278 AddCandidatePolygon(OptCandidates, RADIUS, LC);
2279// delete(BaseLine.endpoints[0]);
2280// delete(BaseLine.endpoints[1]);
2281
2282 if (BTS != NULL) // we have created one starting triangle
2283 break;
2284 else {
2285 // remove all candidates from the list and then the list itself
2286 OptCandidates.pointlist.clear();
2287 }
2288 }
2289};
2290
2291/** Checks for a given baseline and a third point candidate whether baselines of the found triangle don't have even better candidates.
2292 * This is supposed to prevent early closing of the tesselation.
2293 * \param CandidateLine CandidateForTesselation with baseline and shortestangle , i.e. not \a *OptCandidate
2294 * \param *ThirdNode third point in triangle, not in BoundaryLineSet::endpoints
2295 * \param RADIUS radius of sphere
2296 * \param *LC LinkedCell structure
2297 * \return true - there is a better candidate (smaller angle than \a ShortestAngle), false - no better TesselPoint candidate found
2298 */
2299//bool Tesselation::HasOtherBaselineBetterCandidate(CandidateForTesselation &CandidateLine, const TesselPoint * const ThirdNode, double RADIUS, const LinkedCell * const LC) const
2300//{
2301// Info FunctionInfo(__func__);
2302// bool result = false;
2303// Vector CircleCenter;
2304// Vector CirclePlaneNormal;
2305// Vector OldSphereCenter;
2306// Vector SearchDirection;
2307// Vector helper;
2308// TesselPoint *OtherOptCandidate = NULL;
2309// double OtherShortestAngle = 2.*M_PI; // This will indicate the quadrant.
2310// double radius, CircleRadius;
2311// BoundaryLineSet *Line = NULL;
2312// BoundaryTriangleSet *T = NULL;
2313//
2314// // check both other lines
2315// PointMap::const_iterator FindPoint = PointsOnBoundary.find(ThirdNode->nr);
2316// if (FindPoint != PointsOnBoundary.end()) {
2317// for (int i=0;i<2;i++) {
2318// LineMap::const_iterator FindLine = (FindPoint->second)->lines.find(BaseRay->endpoints[0]->node->nr);
2319// if (FindLine != (FindPoint->second)->lines.end()) {
2320// Line = FindLine->second;
2321// Log() << Verbose(0) << "Found line " << *Line << "." << endl;
2322// if (Line->triangles.size() == 1) {
2323// T = Line->triangles.begin()->second;
2324// // construct center of circle
2325// CircleCenter.CopyVector(Line->endpoints[0]->node->node);
2326// CircleCenter.AddVector(Line->endpoints[1]->node->node);
2327// CircleCenter.Scale(0.5);
2328//
2329// // construct normal vector of circle
2330// CirclePlaneNormal.CopyVector(Line->endpoints[0]->node->node);
2331// CirclePlaneNormal.SubtractVector(Line->endpoints[1]->node->node);
2332//
2333// // calculate squared radius of circle
2334// radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2335// if (radius/4. < RADIUS*RADIUS) {
2336// CircleRadius = RADIUS*RADIUS - radius/4.;
2337// CirclePlaneNormal.Normalize();
2338// //Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2339//
2340// // construct old center
2341// GetCenterofCircumcircle(&OldSphereCenter, *T->endpoints[0]->node->node, *T->endpoints[1]->node->node, *T->endpoints[2]->node->node);
2342// helper.CopyVector(&T->NormalVector); // normal vector ensures that this is correct center of the two possible ones
2343// radius = Line->endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
2344// helper.Scale(sqrt(RADIUS*RADIUS - radius));
2345// OldSphereCenter.AddVector(&helper);
2346// OldSphereCenter.SubtractVector(&CircleCenter);
2347// //Log() << Verbose(1) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2348//
2349// // construct SearchDirection
2350// SearchDirection.MakeNormalVector(&T->NormalVector, &CirclePlaneNormal);
2351// helper.CopyVector(Line->endpoints[0]->node->node);
2352// helper.SubtractVector(ThirdNode->node);
2353// if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2354// SearchDirection.Scale(-1.);
2355// SearchDirection.ProjectOntoPlane(&OldSphereCenter);
2356// SearchDirection.Normalize();
2357// Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2358// if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2359// // rotated the wrong way!
2360// DoeLog(1) && (eLog()<< Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl);
2361// }
2362//
2363// // add third point
2364// FindThirdPointForTesselation(T->NormalVector, SearchDirection, OldSphereCenter, OptCandidates, ThirdNode, RADIUS, LC);
2365// for (TesselPointList::iterator it = OptCandidates.pointlist.begin(); it != OptCandidates.pointlist.end(); ++it) {
2366// if (((*it) == BaseRay->endpoints[0]->node) || ((*it) == BaseRay->endpoints[1]->node)) // skip if it's the same triangle than suggested
2367// continue;
2368// Log() << Verbose(0) << " Third point candidate is " << (*it)
2369// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2370// Log() << Verbose(0) << " Baseline is " << *BaseRay << endl;
2371//
2372// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2373// TesselPoint *PointCandidates[3];
2374// PointCandidates[0] = (*it);
2375// PointCandidates[1] = BaseRay->endpoints[0]->node;
2376// PointCandidates[2] = BaseRay->endpoints[1]->node;
2377// bool check=false;
2378// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2379// // If there is no triangle, add it regularly.
2380// if (existentTrianglesCount == 0) {
2381// SetTesselationPoint((*it), 0);
2382// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2383// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2384//
2385// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2386// OtherOptCandidate = (*it);
2387// check = true;
2388// }
2389// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2390// SetTesselationPoint((*it), 0);
2391// SetTesselationPoint(BaseRay->endpoints[0]->node, 1);
2392// SetTesselationPoint(BaseRay->endpoints[1]->node, 2);
2393//
2394// // 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)
2395// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2396// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS)) {
2397// OtherOptCandidate = (*it);
2398// check = true;
2399// }
2400// }
2401//
2402// if (check) {
2403// if (ShortestAngle > OtherShortestAngle) {
2404// Log() << Verbose(0) << "There is a better candidate than " << *ThirdNode << " with " << ShortestAngle << " from baseline " << *Line << ": " << *OtherOptCandidate << " with " << OtherShortestAngle << "." << endl;
2405// result = true;
2406// break;
2407// }
2408// }
2409// }
2410// delete(OptCandidates);
2411// if (result)
2412// break;
2413// } else {
2414// Log() << Verbose(0) << "Circumcircle for base line " << *Line << " and base triangle " << T << " is too big!" << endl;
2415// }
2416// } else {
2417// DoeLog(2) && (eLog()<< Verbose(2) << "Baseline is connected to two triangles already?" << endl);
2418// }
2419// } else {
2420// Log() << Verbose(1) << "No present baseline between " << BaseRay->endpoints[0] << " and candidate " << *ThirdNode << "." << endl;
2421// }
2422// }
2423// } else {
2424// DoeLog(1) && (eLog()<< Verbose(1) << "Could not find the TesselPoint " << *ThirdNode << "." << endl);
2425// }
2426//
2427// return result;
2428//};
2429
2430/** This function finds a triangle to a line, adjacent to an existing one.
2431 * @param out output stream for debugging
2432 * @param CandidateLine current cadndiate baseline to search from
2433 * @param T current triangle which \a Line is edge of
2434 * @param RADIUS radius of the rolling ball
2435 * @param N number of found triangles
2436 * @param *LC LinkedCell structure with neighbouring points
2437 */
2438bool Tesselation::FindNextSuitableTriangle(CandidateForTesselation &CandidateLine, BoundaryTriangleSet &T, const double& RADIUS, const LinkedCell *LC)
2439{
2440 Info FunctionInfo(__func__);
2441 bool result = true;
2442
2443 Vector CircleCenter;
2444 Vector CirclePlaneNormal;
2445 Vector RelativeSphereCenter;
2446 Vector SearchDirection;
2447 Vector helper;
2448 BoundaryPointSet *ThirdPoint = NULL;
2449 LineMap::iterator testline;
2450 double radius, CircleRadius;
2451
2452 for (int i=0;i<3;i++)
2453 if ((T.endpoints[i] != CandidateLine.BaseLine->endpoints[0]) && (T.endpoints[i] != CandidateLine.BaseLine->endpoints[1])) {
2454 ThirdPoint = T.endpoints[i];
2455 break;
2456 }
2457 Log() << Verbose(0) << "Current baseline is " << *CandidateLine.BaseLine << " with ThirdPoint " << *ThirdPoint << " of triangle " << T << "." << endl;
2458
2459 CandidateLine.T = &T;
2460
2461 // construct center of circle
2462 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2463 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2464 CircleCenter.Scale(0.5);
2465
2466 // construct normal vector of circle
2467 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
2468 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
2469
2470 // calculate squared radius of circle
2471 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2472 if (radius/4. < RADIUS*RADIUS) {
2473 // construct relative sphere center with now known CircleCenter
2474 RelativeSphereCenter.CopyVector(&T.SphereCenter);
2475 RelativeSphereCenter.SubtractVector(&CircleCenter);
2476
2477 CircleRadius = RADIUS*RADIUS - radius/4.;
2478 CirclePlaneNormal.Normalize();
2479 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2480
2481 Log() << Verbose(1) << "INFO: OldSphereCenter is at " << T.SphereCenter << "." << endl;
2482
2483 // construct SearchDirection and an "outward pointer"
2484 SearchDirection.MakeNormalVector(&RelativeSphereCenter, &CirclePlaneNormal);
2485 helper.CopyVector(&CircleCenter);
2486 helper.SubtractVector(ThirdPoint->node->node);
2487 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
2488 SearchDirection.Scale(-1.);
2489 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2490 if (fabs(RelativeSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
2491 // rotated the wrong way!
2492 DoeLog(1) && (eLog()<< Verbose(1) << "SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl);
2493 }
2494
2495 // add third point
2496 FindThirdPointForTesselation(T.NormalVector, SearchDirection, T.SphereCenter, CandidateLine, ThirdPoint, RADIUS, LC);
2497
2498 } else {
2499 Log() << Verbose(0) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and base triangle " << T << " is too big!" << endl;
2500 }
2501
2502 if (CandidateLine.pointlist.empty()) {
2503 DoeLog(2) && (eLog()<< Verbose(2) << "Could not find a suitable candidate." << endl);
2504 return false;
2505 }
2506 Log() << Verbose(0) << "Third Points are: " << endl;
2507 for (TesselPointList::iterator it = CandidateLine.pointlist.begin(); it != CandidateLine.pointlist.end(); ++it) {
2508 Log() << Verbose(0) << " " << *(*it) << endl;
2509 }
2510
2511 return true;
2512
2513// BoundaryLineSet *BaseRay = CandidateLine.BaseLine;
2514// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2515// Log() << Verbose(0) << "Third point candidate is " << *(*it)->point
2516// << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
2517// Log() << Verbose(0) << "Baseline is " << *BaseRay << endl;
2518//
2519// // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
2520// TesselPoint *PointCandidates[3];
2521// PointCandidates[0] = (*it)->point;
2522// PointCandidates[1] = BaseRay->endpoints[0]->node;
2523// PointCandidates[2] = BaseRay->endpoints[1]->node;
2524// int existentTrianglesCount = CheckPresenceOfTriangle(PointCandidates);
2525//
2526// BTS = NULL;
2527// // check for present edges and whether we reach better candidates from them
2528// //if (HasOtherBaselineBetterCandidate(BaseRay, (*it)->point, ShortestAngle, RADIUS, LC) ) {
2529// if (0) {
2530// result = false;
2531// break;
2532// } else {
2533// // If there is no triangle, add it regularly.
2534// if (existentTrianglesCount == 0) {
2535// AddTesselationPoint((*it)->point, 0);
2536// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2537// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2538//
2539// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const )TPS)) {
2540// CandidateLine.point = (*it)->point;
2541// CandidateLine.OptCenter.CopyVector(&((*it)->OptCenter));
2542// CandidateLine.OtherOptCenter.CopyVector(&((*it)->OtherOptCenter));
2543// CandidateLine.ShortestAngle = ShortestAngle;
2544// } else {
2545//// DoeLog(1) && (eLog()<< Verbose(1) << "This triangle consisting of ");
2546//// Log() << Verbose(0) << *(*it)->point << ", ";
2547//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2548//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2549//// Log() << Verbose(0) << "exists and is not added, as it 0x80000000006fc150(does not seem helpful!" << endl;
2550// result = false;
2551// }
2552// } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
2553// AddTesselationPoint((*it)->point, 0);
2554// AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
2555// AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
2556//
2557// // 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)
2558// // i.e. at least one of the three lines must be present with TriangleCount <= 1
2559// if (CheckLineCriteriaForDegeneratedTriangle((const BoundaryPointSet ** const)TPS) || CandidateLine.BaseLine->skipped) {
2560// CandidateLine.point = (*it)->point;
2561// CandidateLine.OptCenter.CopyVector(&(*it)->OptCenter);
2562// CandidateLine.OtherOptCenter.CopyVector(&(*it)->OtherOptCenter);
2563// CandidateLine.ShortestAngle = ShortestAngle+2.*M_PI;
2564//
2565// } else {
2566//// 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);
2567// result = false;
2568// }
2569// } else {
2570//// Log() << Verbose(1) << "This triangle consisting of ";
2571//// Log() << Verbose(0) << *(*it)->point << ", ";
2572//// Log() << Verbose(0) << *BaseRay->endpoints[0]->node << " and ";
2573//// Log() << Verbose(0) << *BaseRay->endpoints[1]->node << " ";
2574//// Log() << Verbose(0) << "is invalid!" << endl;
2575// result = false;
2576// }
2577// }
2578//
2579// // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
2580// BaseRay = BLS[0];
2581// if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
2582// DoeLog(1) && (eLog()<< Verbose(1) << "Triangle " << *BTS << " has zero normal vector!" << endl);
2583// exit(255);
2584// }
2585//
2586// }
2587//
2588// // remove all candidates from the list and then the list itself
2589// class CandidateForTesselation *remover = NULL;
2590// for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
2591// remover = *it;
2592// delete(remover);
2593// }
2594// delete(OptCandidates);
2595 return result;
2596};
2597
2598/** Adds the present line and candidate point from \a &CandidateLine to the Tesselation.
2599 * \param CandidateLine triangle to add
2600 * \param RADIUS Radius of sphere
2601 * \param *LC LinkedCell structure
2602 * \NOTE we need the copy operator here as the original CandidateForTesselation is removed in
2603 * AddTesselationLine() in AddCandidateTriangle()
2604 */
2605void Tesselation::AddCandidatePolygon(CandidateForTesselation CandidateLine, const double RADIUS, const LinkedCell *LC)
2606{
2607 Info FunctionInfo(__func__);
2608 Vector Center;
2609 TesselPoint * const TurningPoint = CandidateLine.BaseLine->endpoints[0]->node;
2610 TesselPointList::iterator Runner;
2611 TesselPointList::iterator Sprinter;
2612
2613 // fill the set of neighbours
2614 TesselPointSet SetOfNeighbours;
2615 SetOfNeighbours.insert(CandidateLine.BaseLine->endpoints[1]->node);
2616 for (TesselPointList::iterator Runner = CandidateLine.pointlist.begin(); Runner != CandidateLine.pointlist.end(); Runner++)
2617 SetOfNeighbours.insert(*Runner);
2618 TesselPointList *connectedClosestPoints = GetCircleOfSetOfPoints(&SetOfNeighbours, TurningPoint, CandidateLine.BaseLine->endpoints[1]->node->node);
2619
2620 Log() << Verbose(0) << "List of Candidates for Turning Point " << *TurningPoint << ":" << endl;
2621 for (TesselPointList::iterator TesselRunner = connectedClosestPoints->begin(); TesselRunner != connectedClosestPoints->end(); ++TesselRunner)
2622 Log() << Verbose(0) << " " << **TesselRunner << endl;
2623
2624 // go through all angle-sorted candidates (in degenerate n-nodes case we may have to add multiple triangles)
2625 Runner = connectedClosestPoints->begin();
2626 Sprinter = Runner;
2627 Sprinter++;
2628 while(Sprinter != connectedClosestPoints->end()) {
2629 // add this triangle
2630 AddCandidateTriangle(TurningPoint, *Runner, *Sprinter);
2631
2632 // store values from tesselation procedure therein
2633 BTS->SetTopNode(CandidateLine.T);
2634 if (CandidateLine.T != NULL) // start triangle has angle from top of -1
2635 BTS->AngleFromTop = CandidateLine.ShortestAngle;
2636 else
2637 BTS->AngleFromTop = -1.;
2638
2639 // create normal vector
2640 BTS->GetCenter(&Center);
2641 Center.SubtractVector(&CandidateLine.OptCenter);
2642 BTS->SphereCenter.CopyVector(&CandidateLine.OptCenter);
2643 BTS->GetNormalVector(Center);
2644
2645 // give some verbose output about the whole procedure
2646 if (CandidateLine.T != NULL)
2647 Log() << Verbose(0) << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector << ", from " << *CandidateLine.T << " and angle " << CandidateLine.ShortestAngle << "." << endl;
2648 else
2649 Log() << Verbose(0) << "--> New starting triangle with " << *BTS << " and normal vector " << BTS->NormalVector << " and no top triangle." << endl;
2650
2651 // check whether its degenerate and if so, add the other side triangle as well
2652 if (BTS->CheckDegeneracy(&CandidateLine.OtherOptCenter, RADIUS, LC)) {
2653 Log() << Verbose(1) << "Triangle " << *BTS << " is degenerated, adding other side." << endl;
2654 BoundaryTriangleSet * const triangle = BTS;
2655 AddDegeneratedTriangle(BTS, &CandidateLine.OtherOptCenter, RADIUS, LC);
2656 // check whether other side triangle has been created
2657 if (BTS != NULL) {
2658 BTS->SetTopNode(CandidateLine.T);
2659 if (CandidateLine.T != NULL) // start triangle has angle from top of -1
2660 BTS->AngleFromTop = CandidateLine.ShortestAngle;
2661 else
2662 BTS->AngleFromTop = -1.;
2663 BTS->SphereCenter.CopyVector(&CandidateLine.OtherOptCenter);
2664 // normal vector points other way round
2665 BTS->NormalVector.CopyVector(&triangle->NormalVector);
2666 BTS->NormalVector.Scale(-1.);
2667
2668 // give some verbose output about the whole procedure
2669 if (CandidateLine.T != NULL)
2670 Log() << Verbose(0) << "--> New degenerate triangle with " << *BTS << " and normal vector " << BTS->NormalVector << ", from " << *CandidateLine.T << " and angle " << CandidateLine.ShortestAngle << "." << endl;
2671 else
2672 Log() << Verbose(0) << "--> New degenerate starting triangle with " << *BTS << " and normal vector " << BTS->NormalVector << " and no top triangle." << endl;
2673 }
2674 }
2675
2676 Runner = Sprinter;
2677 Sprinter++;
2678 Log() << Verbose(0) << "Current Runner is " << **Runner << "." << endl;
2679 if (Sprinter != connectedClosestPoints->end())
2680 Log() << Verbose(0) << " There are still more triangles to add." << endl;
2681 }
2682 delete(connectedClosestPoints);
2683};
2684
2685/** If a given \a *triangle is degenerated, this adds the "other side".
2686 * i.e. the triangle with same BoundaryPointSet's but NormalVector in opposite direction.
2687 * \param *triangle degenerated triangle
2688 * \param *OtherOptCenter center of the sphere for the other triangle
2689 * \param RADIUS radius of sphere
2690 * \param *LC pointer to LinkedCell structure
2691 * \return pointer to created other triangle
2692 */
2693void Tesselation::AddDegeneratedTriangle(BoundaryTriangleSet *&triangle, Vector *OtherOptCenter, const double RADIUS, const LinkedCell *LC)
2694{
2695 Info FunctionInfo(__func__);
2696 TesselPoint *ThirdNode = NULL;
2697 BoundaryTriangleSet *otherTriangle = NULL;
2698 /// 1. For each of the open sides of \a *triangle find best candidate
2699 for (int i=0;i<3;i++) {
2700 BLS[i] = NULL;
2701 // go through all possible lines (also degenerate ones) and find ones to be used
2702 pair<LineMap::iterator,LineMap::iterator> FindPair = triangle->lines[i]->endpoints[0]->lines.equal_range(triangle->lines[i]->endpoints[1]->Nr);
2703 for (LineMap::iterator FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
2704 if ((*FindLine).second->triangles.size() == 1) {
2705 Log() << Verbose(1) << "Found line " << *(*FindLine).second << " from triangle " << *((*FindLine).second->triangles.begin()->second) << "." << endl;
2706 // check whether best Candidate for this line from the degenerate triangle is the third endpoint
2707 CandidateForTesselation CandidateLine((*FindLine).second);
2708 otherTriangle = ((*FindLine).second->triangles.begin())->second; // this is unique and present, above we check that there is exactly one
2709 ThirdNode = otherTriangle->GetThirdEndpoint((*FindLine).second)->node;
2710 FindNextSuitableTriangle(CandidateLine, *triangle, RADIUS, LC);
2711
2712 /// 2. If best candidate is third endpoint,
2713 for (TesselPointList::const_iterator Runner = CandidateLine.pointlist.begin(); Runner != CandidateLine.pointlist.end(); ++Runner) {
2714 Log() << Verbose(1) << "Found candidate " << *(*Runner) << endl;
2715 if ((*Runner) == ThirdNode) { // seems like we found a line to connect to
2716 /// sets Tesselation::BLS[i] accordingly and removes the line from Tesselation::OpenLines
2717 AddExistingTesselationTriangleLine((*FindLine).second,i);
2718 break;
2719 }
2720 }
2721 }
2722 }
2723 /// otherwise we create a new BoundaryLineSet for this Tesselation::BLS[i] and add it to OpenLines
2724 }
2725 if ((BLS[0] == NULL) && (BLS[1] == NULL) && (BLS[2] == NULL)) {
2726 Log() << Verbose(0) << "This degenerate triangle would not share any line with its other side, rejecting." << endl;
2727 BTS = NULL;
2728 } else {
2729 // created new lines for the other egdes of the other side triangle
2730 for (int i=0;i<3;i++) {
2731 if (BLS[i] == NULL) {
2732 AddNewTesselationTriangleLine(triangle->lines[i]->endpoints[0],triangle->lines[i]->endpoints[1],i);
2733 }
2734 }
2735 /// 3. Create the triangle
2736 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2737 AddTesselationTriangle();
2738
2739 // add triangle to the CandidateForTesselation of its open lines
2740 CandidateMap::iterator Finder = OpenLines.end();
2741 for (int i=0;i<3;i++) {
2742 Finder = OpenLines.find(BTS->lines[i]);
2743 if (Finder != OpenLines.end()) {
2744 Log() << Verbose(1) << "INFO: Found open line of this triangle " << *(Finder->first) << endl;
2745 if (Finder->second->T == NULL) {
2746 Finder->second->T = BTS;
2747 Log() << Verbose(1) << "ACCEPT: Setting source triangle of open line " << *(Finder->first) << " to the newly created one." << endl;
2748 }
2749 } else
2750 Log() << Verbose(1) << "REJECT: line " << *BTS->lines[i] << " of this triangle is not found to be open." << endl;
2751 }
2752 }
2753};
2754
2755/** Adds a triangle to the Tesselation structure from three given TesselPoint's.
2756 * \param *first first TesselPoint
2757 * \param *second second TesselPoint
2758 * \param *third third TesselPoint
2759 */
2760void Tesselation::AddCandidateTriangle(TesselPoint *first, TesselPoint *second, TesselPoint *third)
2761{
2762 Info FunctionInfo(__func__);
2763 // add the points
2764 AddTesselationPoint(first, 0);
2765 AddTesselationPoint(second, 1);
2766 AddTesselationPoint(third, 2);
2767
2768 // add the lines
2769 AddTesselationLine(TPS[2], TPS[0], TPS[1], 0);
2770 AddTesselationLine(TPS[1], TPS[0], TPS[2], 1);
2771 AddTesselationLine(TPS[0], TPS[1], TPS[2], 2);
2772
2773 // add the triangles
2774 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
2775 AddTesselationTriangle();
2776};
2777
2778/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
2779 * We look whether the closest point on \a *Base with respect to the other baseline is outside
2780 * of the segment formed by both endpoints (concave) or not (convex).
2781 * \param *out output stream for debugging
2782 * \param *Base line to be flipped
2783 * \return NULL - convex, otherwise endpoint that makes it concave
2784 */
2785class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
2786{
2787 Info FunctionInfo(__func__);
2788 class BoundaryPointSet *Spot = NULL;
2789 class BoundaryLineSet *OtherBase;
2790 Vector *ClosestPoint;
2791
2792 int m=0;
2793 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2794 for (int j=0;j<3;j++) // all of their endpoints and baselines
2795 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2796 BPS[m++] = runner->second->endpoints[j];
2797 OtherBase = new class BoundaryLineSet(BPS,-1);
2798
2799 Log() << Verbose(1) << "INFO: Current base line is " << *Base << "." << endl;
2800 Log() << Verbose(1) << "INFO: Other base line is " << *OtherBase << "." << endl;
2801
2802 // get the closest point on each line to the other line
2803 ClosestPoint = GetClosestPointBetweenLine(Base, OtherBase);
2804
2805 // delete the temporary other base line
2806 delete(OtherBase);
2807
2808 // get the distance vector from Base line to OtherBase line
2809 Vector DistanceToIntersection[2], BaseLine;
2810 double distance[2];
2811 BaseLine.CopyVector(Base->endpoints[1]->node->node);
2812 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
2813 for (int i=0;i<2;i++) {
2814 DistanceToIntersection[i].CopyVector(ClosestPoint);
2815 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
2816 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
2817 }
2818 delete(ClosestPoint);
2819 if ((distance[0] * distance[1]) > 0) { // have same sign?
2820 Log() << Verbose(1) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
2821 if (distance[0] < distance[1]) {
2822 Spot = Base->endpoints[0];
2823 } else {
2824 Spot = Base->endpoints[1];
2825 }
2826 return Spot;
2827 } else { // different sign, i.e. we are in between
2828 Log() << Verbose(0) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
2829 return NULL;
2830 }
2831
2832};
2833
2834void Tesselation::PrintAllBoundaryPoints(ofstream *out) const
2835{
2836 Info FunctionInfo(__func__);
2837 // print all lines
2838 Log() << Verbose(0) << "Printing all boundary points for debugging:" << endl;
2839 for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
2840 Log() << Verbose(0) << *(PointRunner->second) << endl;
2841};
2842
2843void Tesselation::PrintAllBoundaryLines(ofstream *out) const
2844{
2845 Info FunctionInfo(__func__);
2846 // print all lines
2847 Log() << Verbose(0) << "Printing all boundary lines for debugging:" << endl;
2848 for (LineMap::const_iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
2849 Log() << Verbose(0) << *(LineRunner->second) << endl;
2850};
2851
2852void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
2853{
2854 Info FunctionInfo(__func__);
2855 // print all triangles
2856 Log() << Verbose(0) << "Printing all boundary triangles for debugging:" << endl;
2857 for (TriangleMap::const_iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
2858 Log() << Verbose(0) << *(TriangleRunner->second) << endl;
2859};
2860
2861/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
2862 * \param *out output stream for debugging
2863 * \param *Base line to be flipped
2864 * \return volume change due to flipping (0 - then no flipped occured)
2865 */
2866double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
2867{
2868 Info FunctionInfo(__func__);
2869 class BoundaryLineSet *OtherBase;
2870 Vector *ClosestPoint[2];
2871 double volume;
2872
2873 int m=0;
2874 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2875 for (int j=0;j<3;j++) // all of their endpoints and baselines
2876 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
2877 BPS[m++] = runner->second->endpoints[j];
2878 OtherBase = new class BoundaryLineSet(BPS,-1);
2879
2880 Log() << Verbose(0) << "INFO: Current base line is " << *Base << "." << endl;
2881 Log() << Verbose(0) << "INFO: Other base line is " << *OtherBase << "." << endl;
2882
2883 // get the closest point on each line to the other line
2884 ClosestPoint[0] = GetClosestPointBetweenLine(Base, OtherBase);
2885 ClosestPoint[1] = GetClosestPointBetweenLine(OtherBase, Base);
2886
2887 // get the distance vector from Base line to OtherBase line
2888 Vector Distance;
2889 Distance.CopyVector(ClosestPoint[1]);
2890 Distance.SubtractVector(ClosestPoint[0]);
2891
2892 // calculate volume
2893 volume = CalculateVolumeofGeneralTetraeder(*Base->endpoints[1]->node->node, *OtherBase->endpoints[0]->node->node, *OtherBase->endpoints[1]->node->node, *Base->endpoints[0]->node->node);
2894
2895 // delete the temporary other base line and the closest points
2896 delete(ClosestPoint[0]);
2897 delete(ClosestPoint[1]);
2898 delete(OtherBase);
2899
2900 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2901 Log() << Verbose(0) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2902 return false;
2903 } else { // check for sign against BaseLineNormal
2904 Vector BaseLineNormal;
2905 BaseLineNormal.Zero();
2906 if (Base->triangles.size() < 2) {
2907 DoeLog(1) && (eLog()<< Verbose(1) << "Less than two triangles are attached to this baseline!" << endl);
2908 return 0.;
2909 }
2910 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2911 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2912 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2913 }
2914 BaseLineNormal.Scale(1./2.);
2915
2916 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2917 Log() << Verbose(0) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2918 // calculate volume summand as a general tetraeder
2919 return volume;
2920 } else { // Base higher than OtherBase -> do nothing
2921 Log() << Verbose(0) << "REJECT: Base line is higher: Nothing to do." << endl;
2922 return 0.;
2923 }
2924 }
2925};
2926
2927/** For a given baseline and its two connected triangles, flips the baseline.
2928 * I.e. we create the new baseline between the other two endpoints of these four
2929 * endpoints and reconstruct the two triangles accordingly.
2930 * \param *out output stream for debugging
2931 * \param *Base line to be flipped
2932 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2933 */
2934class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
2935{
2936 Info FunctionInfo(__func__);
2937 class BoundaryLineSet *OldLines[4], *NewLine;
2938 class BoundaryPointSet *OldPoints[2];
2939 Vector BaseLineNormal;
2940 int OldTriangleNrs[2], OldBaseLineNr;
2941 int i,m;
2942
2943 // calculate NormalVector for later use
2944 BaseLineNormal.Zero();
2945 if (Base->triangles.size() < 2) {
2946 DoeLog(1) && (eLog()<< Verbose(1) << "Less than two triangles are attached to this baseline!" << endl);
2947 return NULL;
2948 }
2949 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2950 Log() << Verbose(1) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2951 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2952 }
2953 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2954
2955 // get the two triangles
2956 // gather four endpoints and four lines
2957 for (int j=0;j<4;j++)
2958 OldLines[j] = NULL;
2959 for (int j=0;j<2;j++)
2960 OldPoints[j] = NULL;
2961 i=0;
2962 m=0;
2963 Log() << Verbose(0) << "The four old lines are: ";
2964 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2965 for (int j=0;j<3;j++) // all of their endpoints and baselines
2966 if (runner->second->lines[j] != Base) { // pick not the central baseline
2967 OldLines[i++] = runner->second->lines[j];
2968 Log() << Verbose(0) << *runner->second->lines[j] << "\t";
2969 }
2970 Log() << Verbose(0) << endl;
2971 Log() << Verbose(0) << "The two old points are: ";
2972 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2973 for (int j=0;j<3;j++) // all of their endpoints and baselines
2974 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2975 OldPoints[m++] = runner->second->endpoints[j];
2976 Log() << Verbose(0) << *runner->second->endpoints[j] << "\t";
2977 }
2978 Log() << Verbose(0) << endl;
2979
2980 // check whether everything is in place to create new lines and triangles
2981 if (i<4) {
2982 DoeLog(1) && (eLog()<< Verbose(1) << "We have not gathered enough baselines!" << endl);
2983 return NULL;
2984 }
2985 for (int j=0;j<4;j++)
2986 if (OldLines[j] == NULL) {
2987 DoeLog(1) && (eLog()<< Verbose(1) << "We have not gathered enough baselines!" << endl);
2988 return NULL;
2989 }
2990 for (int j=0;j<2;j++)
2991 if (OldPoints[j] == NULL) {
2992 DoeLog(1) && (eLog()<< Verbose(1) << "We have not gathered enough endpoints!" << endl);
2993 return NULL;
2994 }
2995
2996 // remove triangles and baseline removes itself
2997 Log() << Verbose(0) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2998 OldBaseLineNr = Base->Nr;
2999 m=0;
3000 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
3001 Log() << Verbose(0) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
3002 OldTriangleNrs[m++] = runner->second->Nr;
3003 RemoveTesselationTriangle(runner->second);
3004 }
3005
3006 // construct new baseline (with same number as old one)
3007 BPS[0] = OldPoints[0];
3008 BPS[1] = OldPoints[1];
3009 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
3010 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
3011 Log() << Verbose(0) << "INFO: Created new baseline " << *NewLine << "." << endl;
3012
3013 // construct new triangles with flipped baseline
3014 i=-1;
3015 if (OldLines[0]->IsConnectedTo(OldLines[2]))
3016 i=2;
3017 if (OldLines[0]->IsConnectedTo(OldLines[3]))
3018 i=3;
3019 if (i!=-1) {
3020 BLS[0] = OldLines[0];
3021 BLS[1] = OldLines[i];
3022 BLS[2] = NewLine;
3023 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
3024 BTS->GetNormalVector(BaseLineNormal);
3025 AddTesselationTriangle(OldTriangleNrs[0]);
3026 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
3027
3028 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
3029 BLS[1] = OldLines[1];
3030 BLS[2] = NewLine;
3031 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
3032 BTS->GetNormalVector(BaseLineNormal);
3033 AddTesselationTriangle(OldTriangleNrs[1]);
3034 Log() << Verbose(0) << "INFO: Created new triangle " << *BTS << "." << endl;
3035 } else {
3036 DoeLog(0) && (eLog()<< Verbose(0) << "The four old lines do not connect, something's utterly wrong here!" << endl);
3037 return NULL;
3038 }
3039
3040 return NewLine;
3041};
3042
3043
3044/** Finds the second point of starting triangle.
3045 * \param *a first node
3046 * \param Oben vector indicating the outside
3047 * \param OptCandidate reference to recommended candidate on return
3048 * \param Storage[3] array storing angles and other candidate information
3049 * \param RADIUS radius of virtual sphere
3050 * \param *LC LinkedCell structure with neighbouring points
3051 */
3052void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell *LC)
3053{
3054 Info FunctionInfo(__func__);
3055 Vector AngleCheck;
3056 class TesselPoint* Candidate = NULL;
3057 double norm = -1.;
3058 double angle = 0.;
3059 int N[NDIM];
3060 int Nlower[NDIM];
3061 int Nupper[NDIM];
3062
3063 if (LC->SetIndexToNode(a)) { // get cell for the starting point
3064 for(int i=0;i<NDIM;i++) // store indices of this cell
3065 N[i] = LC->n[i];
3066 } else {
3067 DoeLog(1) && (eLog()<< Verbose(1) << "Point " << *a << " is not found in cell " << LC->index << "." << endl);
3068 return;
3069 }
3070 // then go through the current and all neighbouring cells and check the contained points for possible candidates
3071 for (int i=0;i<NDIM;i++) {
3072 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
3073 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
3074 }
3075 Log() << Verbose(0) << "LC Intervals from [" << N[0] << "<->" << LC->N[0] << ", " << N[1] << "<->" << LC->N[1] << ", " << N[2] << "<->" << LC->N[2] << "] :"
3076 << " [" << Nlower[0] << "," << Nupper[0] << "], " << " [" << Nlower[1] << "," << Nupper[1] << "], " << " [" << Nlower[2] << "," << Nupper[2] << "], " << endl;
3077
3078 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
3079 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
3080 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
3081 const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
3082 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
3083 if (List != NULL) {
3084 for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
3085 Candidate = (*Runner);
3086 // check if we only have one unique point yet ...
3087 if (a != Candidate) {
3088 // Calculate center of the circle with radius RADIUS through points a and Candidate
3089 Vector OrthogonalizedOben, aCandidate, Center;
3090 double distance, scaleFactor;
3091
3092 OrthogonalizedOben.CopyVector(&Oben);
3093 aCandidate.CopyVector(a->node);
3094 aCandidate.SubtractVector(Candidate->node);
3095 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
3096 OrthogonalizedOben.Normalize();
3097 distance = 0.5 * aCandidate.Norm();
3098 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
3099 OrthogonalizedOben.Scale(scaleFactor);
3100
3101 Center.CopyVector(Candidate->node);
3102 Center.AddVector(a->node);
3103 Center.Scale(0.5);
3104 Center.AddVector(&OrthogonalizedOben);
3105
3106 AngleCheck.CopyVector(&Center);
3107 AngleCheck.SubtractVector(a->node);
3108 norm = aCandidate.Norm();
3109 // second point shall have smallest angle with respect to Oben vector
3110 if (norm < RADIUS*2.) {
3111 angle = AngleCheck.Angle(&Oben);
3112 if (angle < Storage[0]) {
3113 //Log() << Verbose(1) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
3114 Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
3115 OptCandidate = Candidate;
3116 Storage[0] = angle;
3117 //Log() << Verbose(1) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
3118 } else {
3119 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
3120 }
3121 } else {
3122 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
3123 }
3124 } else {
3125 //Log() << Verbose(1) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
3126 }
3127 }
3128 } else {
3129 Log() << Verbose(0) << "Linked cell list is empty." << endl;
3130 }
3131 }
3132};
3133
3134
3135/** This recursive function finds a third point, to form a triangle with two given ones.
3136 * Note that this function is for the starting triangle.
3137 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
3138 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
3139 * the center of the sphere is still fixed up to a single parameter. The band of possible values
3140 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
3141 * us the "null" on this circle, the new center of the candidate point will be some way along this
3142 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
3143 * by the normal vector of the base triangle that always points outwards by construction.
3144 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
3145 * We construct the normal vector that defines the plane this circle lies in, it is just in the
3146 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
3147 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
3148 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
3149 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
3150 * both.
3151 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
3152 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
3153 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
3154 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
3155 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
3156 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
3157 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
3158 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
3159 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
3160 * @param CandidateLine CandidateForTesselation with the current base line and list of candidates and ShortestAngle
3161 * @param ThirdPoint third point to avoid in search
3162 * @param RADIUS radius of sphere
3163 * @param *LC LinkedCell structure with neighbouring points
3164 */
3165void Tesselation::FindThirdPointForTesselation(Vector &NormalVector, Vector &SearchDirection, Vector &OldSphereCenter, CandidateForTesselation &CandidateLine, const class BoundaryPointSet * const ThirdPoint, const double RADIUS, const LinkedCell *LC) const
3166{
3167 Info FunctionInfo(__func__);
3168 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
3169 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
3170 Vector SphereCenter;
3171 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
3172 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
3173 Vector NewNormalVector; // normal vector of the Candidate's triangle
3174 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
3175 Vector RelativeOldSphereCenter;
3176 Vector NewPlaneCenter;
3177 double CircleRadius; // radius of this circle
3178 double radius;
3179 double otherradius;
3180 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
3181 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
3182 TesselPoint *Candidate = NULL;
3183
3184 Log() << Verbose(1) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
3185
3186 // copy old center
3187 CandidateLine.OldCenter.CopyVector(&OldSphereCenter);
3188 CandidateLine.ThirdPoint = ThirdPoint;
3189 CandidateLine.pointlist.clear();
3190
3191 // construct center of circle
3192 CircleCenter.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
3193 CircleCenter.AddVector(CandidateLine.BaseLine->endpoints[1]->node->node);
3194 CircleCenter.Scale(0.5);
3195
3196 // construct normal vector of circle
3197 CirclePlaneNormal.CopyVector(CandidateLine.BaseLine->endpoints[0]->node->node);
3198 CirclePlaneNormal.SubtractVector(CandidateLine.BaseLine->endpoints[1]->node->node);
3199
3200 RelativeOldSphereCenter.CopyVector(&OldSphereCenter);
3201 RelativeOldSphereCenter.SubtractVector(&CircleCenter);
3202
3203 // calculate squared radius TesselPoint *ThirdPoint,f circle
3204 radius = CirclePlaneNormal.NormSquared()/4.;
3205 if (radius < RADIUS*RADIUS) {
3206 CircleRadius = RADIUS*RADIUS - radius;
3207 CirclePlaneNormal.Normalize();
3208 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
3209
3210 // test whether old center is on the band's plane
3211 if (fabs(RelativeOldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
3212 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);
3213 RelativeOldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
3214 }
3215 radius = RelativeOldSphereCenter.NormSquared();
3216 if (fabs(radius - CircleRadius) < HULLEPSILON) {
3217 Log() << Verbose(1) << "INFO: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << "." << endl;
3218
3219 // check SearchDirection
3220 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
3221 if (fabs(RelativeOldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
3222 DoeLog(1) && (eLog()<< Verbose(1) << "SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl);
3223 }
3224
3225 // get cell for the starting point
3226 if (LC->SetIndexToVector(&CircleCenter)) {
3227 for(int i=0;i<NDIM;i++) // store indices of this cell
3228 N[i] = LC->n[i];
3229 //Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
3230 } else {
3231 DoeLog(1) && (eLog()<< Verbose(1) << "Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl);
3232 return;
3233 }
3234 // then go through the current and all neighbouring cells and check the contained points for possible candidates
3235 //Log() << Verbose(1) << "LC Intervals:";
3236 for (int i=0;i<NDIM;i++) {
3237 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
3238 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
3239 //Log() << Verbose(0) << " [" << Nlower[i] << "," << Nupper[i] << "] ";
3240 }
3241 //Log() << Verbose(0) << endl;
3242 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
3243 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
3244 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
3245 const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
3246 //Log() << Verbose(1) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
3247 if (List != NULL) {
3248 for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
3249 Candidate = (*Runner);
3250
3251 // check for three unique points
3252 Log() << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " for BaseLine " << *CandidateLine.BaseLine << " with OldSphereCenter " << OldSphereCenter << "." << endl;
3253 if ((Candidate != CandidateLine.BaseLine->endpoints[0]->node) && (Candidate != CandidateLine.BaseLine->endpoints[1]->node) ){
3254
3255 // find center on the plane
3256 GetCenterofCircumcircle(&NewPlaneCenter, *CandidateLine.BaseLine->endpoints[0]->node->node, *CandidateLine.BaseLine->endpoints[1]->node->node, *Candidate->node);
3257 Log() << Verbose(1) << "INFO: NewPlaneCenter is " << NewPlaneCenter << "." << endl;
3258
3259 if (NewNormalVector.MakeNormalVector(CandidateLine.BaseLine->endpoints[0]->node->node, CandidateLine.BaseLine->endpoints[1]->node->node, Candidate->node)
3260 && (fabs(NewNormalVector.NormSquared()) > HULLEPSILON)
3261 ) {
3262 Log() << Verbose(1) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
3263 radius = CandidateLine.BaseLine->endpoints[0]->node->node->DistanceSquared(&NewPlaneCenter);
3264 Log() << Verbose(1) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
3265 Log() << Verbose(1) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
3266 Log() << Verbose(1) << "INFO: Radius of CircumCenterCircle is " << radius << "." << endl;
3267 if (radius < RADIUS*RADIUS) {
3268 otherradius = CandidateLine.BaseLine->endpoints[1]->node->node->DistanceSquared(&NewPlaneCenter);
3269 if (fabs(radius - otherradius) > HULLEPSILON) {
3270 DoeLog(1) && (eLog()<< Verbose(1) << "Distance to center of circumcircle is not the same from each corner of the triangle: " << fabs(radius-otherradius) << endl);
3271 }
3272 // construct both new centers
3273 NewSphereCenter.CopyVector(&NewPlaneCenter);
3274 OtherNewSphereCenter.CopyVector(&NewPlaneCenter);
3275 helper.CopyVector(&NewNormalVector);
3276 helper.Scale(sqrt(RADIUS*RADIUS - radius));
3277 Log() << Verbose(2) << "INFO: Distance of NewPlaneCenter " << NewPlaneCenter << " to either NewSphereCenter is " << helper.Norm() << " of vector " << helper << " with sphere radius " << RADIUS << "." << endl;
3278 NewSphereCenter.AddVector(&helper);
3279 Log() << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
3280 // OtherNewSphereCenter is created by the same vector just in the other direction
3281 helper.Scale(-1.);
3282 OtherNewSphereCenter.AddVector(&helper);
3283 Log() << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
3284
3285 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
3286 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
3287 alpha = min(alpha, Otheralpha);
3288
3289 // if there is a better candidate, drop the current list and add the new candidate
3290 // otherwise ignore the new candidate and keep the list
3291 if (CandidateLine.ShortestAngle > (alpha - HULLEPSILON)) {
3292 if (fabs(alpha - Otheralpha) > MYEPSILON) {
3293 CandidateLine.OptCenter.CopyVector(&NewSphereCenter);
3294 CandidateLine.OtherOptCenter.CopyVector(&OtherNewSphereCenter);
3295 } else {
3296 CandidateLine.OptCenter.CopyVector(&OtherNewSphereCenter);
3297 CandidateLine.OtherOptCenter.CopyVector(&NewSphereCenter);
3298 }
3299 // if there is an equal candidate, add it to the list without clearing the list
3300 if ((CandidateLine.ShortestAngle - HULLEPSILON) < alpha) {
3301 CandidateLine.pointlist.push_back(Candidate);
3302 Log() << Verbose(0) << "ACCEPT: We have found an equally good candidate: " << *(Candidate) << " with "
3303 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
3304 } else {
3305 // remove all candidates from the list and then the list itself
3306 CandidateLine.pointlist.clear();
3307 CandidateLine.pointlist.push_back(Candidate);
3308 Log() << Verbose(0) << "ACCEPT: We have found a better candidate: " << *(Candidate) << " with "
3309 << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << "." << endl;
3310 }
3311 CandidateLine.ShortestAngle = alpha;
3312 Log() << Verbose(0) << "INFO: There are " << CandidateLine.pointlist.size() << " candidates in the list now." << endl;
3313 } else {
3314 if ((Candidate != NULL) && (CandidateLine.pointlist.begin() != CandidateLine.pointlist.end())) {
3315 Log() << Verbose(1) << "REJECT: Old candidate " << *(*CandidateLine.pointlist.begin()) << " with " << CandidateLine.ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
3316 } else {
3317 Log() << Verbose(1) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
3318 }
3319 }
3320 } else {
3321 Log() << Verbose(1) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
3322 }
3323 } else {
3324 Log() << Verbose(1) << "REJECT: Three points from " << *CandidateLine.BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
3325 }
3326 } else {
3327 if (ThirdPoint != NULL) {
3328 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " and " << *ThirdPoint << " contains Candidate " << *Candidate << "." << endl;
3329 } else {
3330 Log() << Verbose(1) << "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << "." << endl;
3331 }
3332 }
3333 }
3334 }
3335 }
3336 } else {
3337 DoeLog(1) && (eLog()<< Verbose(1) << "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl);
3338 }
3339 } else {
3340 if (ThirdPoint != NULL)
3341 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " and third node " << *ThirdPoint << " is too big!" << endl;
3342 else
3343 Log() << Verbose(1) << "Circumcircle for base line " << *CandidateLine.BaseLine << " is too big!" << endl;
3344 }
3345
3346 if (!CandidateLine.CheckValidity(RADIUS, LC)) {
3347 DoeLog(0) && (eLog() << Verbose(0) << "There were other points contained in the rolling sphere as well!" << endl);
3348 performCriticalExit();
3349 }
3350
3351 DoLog(1) && (Log() << Verbose(1) << "INFO: Sorting candidate list ..." << endl);
3352 if (CandidateLine.pointlist.size() > 1) {
3353 CandidateLine.pointlist.unique();
3354 CandidateLine.pointlist.sort(); //SortCandidates);
3355 }
3356};
3357
3358/** Finds the endpoint two lines are sharing.
3359 * \param *line1 first line
3360 * \param *line2 second line
3361 * \return point which is shared or NULL if none
3362 */
3363class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
3364{
3365 Info FunctionInfo(__func__);
3366 const BoundaryLineSet * lines[2] = { line1, line2 };
3367 class BoundaryPointSet *node = NULL;
3368 PointMap OrderMap;
3369 PointTestPair OrderTest;
3370 for (int i = 0; i < 2; i++)
3371 // for both lines
3372 for (int j = 0; j < 2; j++)
3373 { // for both endpoints
3374 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
3375 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
3376 if (!OrderTest.second)
3377 { // if insertion fails, we have common endpoint
3378 node = OrderTest.first->second;
3379 Log() << Verbose(1) << "Common endpoint of lines " << *line1
3380 << " and " << *line2 << " is: " << *node << "." << endl;
3381 j = 2;
3382 i = 2;
3383 break;
3384 }
3385 }
3386 return node;
3387};
3388
3389/** Finds the boundary points that are closest to a given Vector \a *x.
3390 * \param *out output stream for debugging
3391 * \param *x Vector to look from
3392 * \return map of BoundaryPointSet of closest points sorted by squared distance or NULL.
3393 */
3394DistanceToPointMap * Tesselation::FindClosestBoundaryPointsToVector(const Vector *x, const LinkedCell* LC) const
3395{
3396 Info FunctionInfo(__func__);
3397 PointMap::const_iterator FindPoint;
3398 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
3399
3400 if (LinesOnBoundary.empty()) {
3401 DoeLog(1) && (eLog()<< Verbose(1) << "There is no tesselation structure to compare the point with, please create one first." << endl);
3402 return NULL;
3403 }
3404
3405 // gather all points close to the desired one
3406 LC->SetIndexToVector(x); // ignore status as we calculate bounds below sensibly
3407 for(int i=0;i<NDIM;i++) // store indices of this cell
3408 N[i] = LC->n[i];
3409 Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
3410
3411 DistanceToPointMap * points = new DistanceToPointMap;
3412 LC->GetNeighbourBounds(Nlower, Nupper);
3413 //Log() << Verbose(1) << endl;
3414 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
3415 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
3416 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
3417 const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
3418 //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
3419 if (List != NULL) {
3420 for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
3421 FindPoint = PointsOnBoundary.find((*Runner)->nr);
3422 if (FindPoint != PointsOnBoundary.end()) {
3423 points->insert(DistanceToPointPair (FindPoint->second->node->node->DistanceSquared(x), FindPoint->second) );
3424 Log() << Verbose(1) << "INFO: Putting " << *FindPoint->second << " into the list." << endl;
3425 }
3426 }
3427 } else {
3428 DoeLog(1) && (eLog()<< Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl);
3429 }
3430 }
3431
3432 // check whether we found some points
3433 if (points->empty()) {
3434 DoeLog(1) && (eLog()<< Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
3435 delete(points);
3436 return NULL;
3437 }
3438 return points;
3439};
3440
3441/** Finds the boundary line that is closest to a given Vector \a *x.
3442 * \param *out output stream for debugging
3443 * \param *x Vector to look from
3444 * \return closest BoundaryLineSet or NULL in degenerate case.
3445 */
3446BoundaryLineSet * Tesselation::FindClosestBoundaryLineToVector(const Vector *x, const LinkedCell* LC) const
3447{
3448 Info FunctionInfo(__func__);
3449
3450 // get closest points
3451 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
3452 if (points == NULL) {
3453 DoeLog(1) && (eLog()<< Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
3454 return NULL;
3455 }
3456
3457 // for each point, check its lines, remember closest
3458 Log() << Verbose(1) << "Finding closest BoundaryLine to " << *x << " ... " << endl;
3459 BoundaryLineSet *ClosestLine = NULL;
3460 double MinDistance = -1.;
3461 Vector helper;
3462 Vector Center;
3463 Vector BaseLine;
3464 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3465 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3466 // calculate closest point on line to desired point
3467 helper.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3468 helper.AddVector((LineRunner->second)->endpoints[1]->node->node);
3469 helper.Scale(0.5);
3470 Center.CopyVector(x);
3471 Center.SubtractVector(&helper);
3472 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3473 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3474 Center.ProjectOntoPlane(&BaseLine);
3475 const double distance = Center.NormSquared();
3476 if ((ClosestLine == NULL) || (distance < MinDistance)) {
3477 // additionally calculate intersection on line (whether it's on the line section or not)
3478 helper.CopyVector(x);
3479 helper.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3480 helper.SubtractVector(&Center);
3481 const double lengthA = helper.ScalarProduct(&BaseLine);
3482 helper.CopyVector(x);
3483 helper.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3484 helper.SubtractVector(&Center);
3485 const double lengthB = helper.ScalarProduct(&BaseLine);
3486 if (lengthB*lengthA < 0) { // if have different sign
3487 ClosestLine = LineRunner->second;
3488 MinDistance = distance;
3489 Log() << Verbose(1) << "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << "." << endl;
3490 } else {
3491 Log() << Verbose(1) << "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << "." << endl;
3492 }
3493 } else {
3494 Log() << Verbose(1) << "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << "." << endl;
3495 }
3496 }
3497 }
3498 delete(points);
3499 // check whether closest line is "too close" :), then it's inside
3500 if (ClosestLine == NULL) {
3501 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3502 return NULL;
3503 }
3504 return ClosestLine;
3505};
3506
3507/** Finds the triangle that is closest to a given Vector \a *x.
3508 * \param *out output stream for debugging
3509 * \param *x Vector to look from
3510 * \return BoundaryTriangleSet of nearest triangle or NULL.
3511 */
3512TriangleList * Tesselation::FindClosestTrianglesToVector(const Vector *x, const LinkedCell* LC) const
3513{
3514 Info FunctionInfo(__func__);
3515
3516 // get closest points
3517 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x,LC);
3518 if (points == NULL) {
3519 DoeLog(1) && (eLog()<< Verbose(1) << "There is no nearest point: too far away from the surface." << endl);
3520 return NULL;
3521 }
3522
3523 // for each point, check its lines, remember closest
3524 Log() << Verbose(1) << "Finding closest BoundaryTriangle to " << *x << " ... " << endl;
3525 LineSet ClosestLines;
3526 double MinDistance = 1e+16;
3527 Vector BaseLineIntersection;
3528 Vector Center;
3529 Vector BaseLine;
3530 Vector BaseLineCenter;
3531 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
3532 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
3533
3534 BaseLine.CopyVector((LineRunner->second)->endpoints[0]->node->node);
3535 BaseLine.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3536 const double lengthBase = BaseLine.NormSquared();
3537
3538 BaseLineIntersection.CopyVector(x);
3539 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[0]->node->node);
3540 const double lengthEndA = BaseLineIntersection.NormSquared();
3541
3542 BaseLineIntersection.CopyVector(x);
3543 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3544 const double lengthEndB = BaseLineIntersection.NormSquared();
3545
3546 if ((lengthEndA > lengthBase) || (lengthEndB > lengthBase) || ((lengthEndA < MYEPSILON) || (lengthEndB < MYEPSILON))) { // intersection would be outside, take closer endpoint
3547 const double lengthEnd = Min(lengthEndA, lengthEndB);
3548 if (lengthEnd - MinDistance < -MYEPSILON) { // new best line
3549 ClosestLines.clear();
3550 ClosestLines.insert(LineRunner->second);
3551 MinDistance = lengthEnd;
3552 Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[0]->node << " is closer with " << lengthEnd << "." << endl;
3553 } else if (fabs(lengthEnd - MinDistance) < MYEPSILON) { // additional best candidate
3554 ClosestLines.insert(LineRunner->second);
3555 Log() << Verbose(1) << "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[1]->node << " is equally good with " << lengthEnd << "." << endl;
3556 } else { // line is worse
3557 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;
3558 }
3559 } else { // intersection is closer, calculate
3560 // calculate closest point on line to desired point
3561 BaseLineIntersection.CopyVector(x);
3562 BaseLineIntersection.SubtractVector((LineRunner->second)->endpoints[1]->node->node);
3563 Center.CopyVector(&BaseLineIntersection);
3564 Center.ProjectOntoPlane(&BaseLine);
3565 BaseLineIntersection.SubtractVector(&Center);
3566 const double distance = BaseLineIntersection.NormSquared();
3567 if (Center.NormSquared() > BaseLine.NormSquared()) {
3568 DoeLog(0) && (eLog()<< Verbose(0) << "Algorithmic error: In second case we have intersection outside of baseline!" << endl);
3569 }
3570 if ((ClosestLines.empty()) || (distance < MinDistance)) {
3571 ClosestLines.insert(LineRunner->second);
3572 MinDistance = distance;
3573 Log() << Verbose(1) << "ACCEPT: Intersection in between endpoints, new closest line " << *LineRunner->second << " is " << *ClosestLines.begin() << " with projected distance " << MinDistance << "." << endl;
3574 } else {
3575 Log() << Verbose(2) << "REJECT: Point is further away from line " << *LineRunner->second << " than present closest line: " << distance << " >> " << MinDistance << "." << endl;
3576 }
3577 }
3578 }
3579 }
3580 delete(points);
3581
3582 // check whether closest line is "too close" :), then it's inside
3583 if (ClosestLines.empty()) {
3584 Log() << Verbose(0) << "Is the only point, no one else is closeby." << endl;
3585 return NULL;
3586 }
3587 TriangleList * candidates = new TriangleList;
3588 for (LineSet::iterator LineRunner = ClosestLines.begin(); LineRunner != ClosestLines.end(); LineRunner++)
3589 for (TriangleMap::iterator Runner = (*LineRunner)->triangles.begin(); Runner != (*LineRunner)->triangles.end(); Runner++) {
3590 candidates->push_back(Runner->second);
3591 }
3592 return candidates;
3593};
3594
3595/** Finds closest triangle to a point.
3596 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
3597 * \param *out output stream for debugging
3598 * \param *x Vector to look from
3599 * \param &distance contains found distance on return
3600 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
3601 */
3602class BoundaryTriangleSet * Tesselation::FindClosestTriangleToVector(const Vector *x, const LinkedCell* LC) const
3603{
3604 Info FunctionInfo(__func__);
3605 class BoundaryTriangleSet *result = NULL;
3606 TriangleList *triangles = FindClosestTrianglesToVector(x, LC);
3607 TriangleList candidates;
3608 Vector Center;
3609 Vector helper;
3610
3611 if ((triangles == NULL) || (triangles->empty()))
3612 return NULL;
3613
3614 // go through all and pick the one with the best alignment to x
3615 double MinAlignment = 2.*M_PI;
3616 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++) {
3617 (*Runner)->GetCenter(&Center);
3618 helper.CopyVector(x);
3619 helper.SubtractVector(&Center);
3620 const double Alignment = helper.Angle(&(*Runner)->NormalVector);
3621 if (Alignment < MinAlignment) {
3622 result = *Runner;
3623 MinAlignment = Alignment;
3624 Log() << Verbose(1) << "ACCEPT: Triangle " << *result << " is better aligned with " << MinAlignment << "." << endl;
3625 } else {
3626 Log() << Verbose(1) << "REJECT: Triangle " << *result << " is worse aligned with " << MinAlignment << "." << endl;
3627 }
3628 }
3629 delete(triangles);
3630
3631 return result;
3632};
3633
3634/** Checks whether the provided Vector is within the Tesselation structure.
3635 * Basically calls Tesselation::GetDistanceToSurface() and checks the sign of the return value.
3636 * @param point of which to check the position
3637 * @param *LC LinkedCell structure
3638 *
3639 * @return true if the point is inside the Tesselation structure, false otherwise
3640 */
3641bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell* const LC) const
3642{
3643 Info FunctionInfo(__func__);
3644 TriangleIntersectionList Intersections(&Point,this,LC);
3645
3646 return Intersections.IsInside();
3647};
3648
3649/** Returns the distance to the surface given by the tesselation.
3650 * Calls FindClosestTriangleToVector() and checks whether the resulting triangle's BoundaryTriangleSet#NormalVector points
3651 * towards or away from the given \a &Point. Additionally, we check whether it's normal to the normal vector, i.e. on the
3652 * closest triangle's plane. Then, we have to check whether \a Point is inside the triangle or not to determine whether it's
3653 * an inside or outside point. This is done by calling BoundaryTriangleSet::GetIntersectionInsideTriangle().
3654 * In the end we additionally find the point on the triangle who was smallest distance to \a Point:
3655 * -# Separate distance from point to center in vector in NormalDirection and on the triangle plane.
3656 * -# Check whether vector on triangle plane points inside the triangle or crosses triangle bounds.
3657 * -# If inside, take it to calculate closest distance
3658 * -# If not, take intersection with BoundaryLine as distance
3659 *
3660 * @note distance is squared despite it still contains a sign to determine in-/outside!
3661 *
3662 * @param point of which to check the position
3663 * @param *LC LinkedCell structure
3664 *
3665 * @return >0 if outside, ==0 if on surface, <0 if inside
3666 */
3667double Tesselation::GetDistanceSquaredToTriangle(const Vector &Point, const BoundaryTriangleSet* const triangle) const
3668{
3669 Info FunctionInfo(__func__);
3670 Vector Center;
3671 Vector helper;
3672 Vector DistanceToCenter;
3673 Vector Intersection;
3674 double distance = 0.;
3675
3676 if (triangle == NULL) {// is boundary point or only point in point cloud?
3677 Log() << Verbose(1) << "No triangle given!" << endl;
3678 return -1.;
3679 } else {
3680 Log() << Verbose(1) << "INFO: Closest triangle found is " << *triangle << " with normal vector " << triangle->NormalVector << "." << endl;
3681 }
3682
3683 triangle->GetCenter(&Center);
3684 Log() << Verbose(2) << "INFO: Central point of the triangle is " << Center << "." << endl;
3685 DistanceToCenter.CopyVector(&Center);
3686 DistanceToCenter.SubtractVector(&Point);
3687 Log() << Verbose(2) << "INFO: Vector from point to test to center is " << DistanceToCenter << "." << endl;
3688
3689 // check whether we are on boundary
3690 if (fabs(DistanceToCenter.ScalarProduct(&triangle->NormalVector)) < MYEPSILON) {
3691 // calculate whether inside of triangle
3692 DistanceToCenter.CopyVector(&Point);
3693 Center.CopyVector(&Point);
3694 Center.SubtractVector(&triangle->NormalVector); // points towards MolCenter
3695 DistanceToCenter.AddVector(&triangle->NormalVector); // points outside
3696 Log() << Verbose(1) << "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << "." << endl;
3697 if (triangle->GetIntersectionInsideTriangle(&Center, &DistanceToCenter, &Intersection)) {
3698 Log() << Verbose(1) << Point << " is inner point: sufficiently close to boundary, " << Intersection << "." << endl;
3699 return 0.;
3700 } else {
3701 Log() << Verbose(1) << Point << " is NOT an inner point: on triangle plane but outside of triangle bounds." << endl;
3702 return false;
3703 }
3704 } else {
3705 // calculate smallest distance
3706 distance = triangle->GetClosestPointInsideTriangle(&Point, &Intersection);
3707 Log() << Verbose(1) << "Closest point on triangle is " << Intersection << "." << endl;
3708
3709 // then check direction to boundary
3710 if (DistanceToCenter.ScalarProduct(&triangle->NormalVector) > MYEPSILON) {
3711 Log() << Verbose(1) << Point << " is an inner point, " << distance << " below surface." << endl;
3712 return -distance;
3713 } else {
3714 Log() << Verbose(1) << Point << " is NOT an inner point, " << distance << " above surface." << endl;
3715 return +distance;
3716 }
3717 }
3718};
3719
3720/** Calculates minimum distance from \a&Point to a tesselated surface.
3721 * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
3722 * \param &Point point to calculate distance from
3723 * \param *LC needed for finding closest points fast
3724 * \return distance squared to closest point on surface
3725 */
3726double Tesselation::GetDistanceToSurface(const Vector &Point, const LinkedCell* const LC) const
3727{
3728 Info FunctionInfo(__func__);
3729 TriangleIntersectionList Intersections(&Point,this,LC);
3730
3731 return Intersections.GetSmallestDistance();
3732};
3733
3734/** Calculates minimum distance from \a&Point to a tesselated surface.
3735 * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
3736 * \param &Point point to calculate distance from
3737 * \param *LC needed for finding closest points fast
3738 * \return distance squared to closest point on surface
3739 */
3740BoundaryTriangleSet * Tesselation::GetClosestTriangleOnSurface(const Vector &Point, const LinkedCell* const LC) const
3741{
3742 Info FunctionInfo(__func__);
3743 TriangleIntersectionList Intersections(&Point,this,LC);
3744
3745 return Intersections.GetClosestTriangle();
3746};
3747
3748/** Gets all points connected to the provided point by triangulation lines.
3749 *
3750 * @param *Point of which get all connected points
3751 *
3752 * @return set of the all points linked to the provided one
3753 */
3754TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
3755{
3756 Info FunctionInfo(__func__);
3757 TesselPointSet *connectedPoints = new TesselPointSet;
3758 class BoundaryPointSet *ReferencePoint = NULL;
3759 TesselPoint* current;
3760 bool takePoint = false;
3761
3762 // find the respective boundary point
3763 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
3764 if (PointRunner != PointsOnBoundary.end()) {
3765 ReferencePoint = PointRunner->second;
3766 } else {
3767 DoeLog(2) && (eLog()<< Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl);
3768 ReferencePoint = NULL;
3769 }
3770
3771 // little trick so that we look just through lines connect to the BoundaryPoint
3772 // OR fall-back to look through all lines if there is no such BoundaryPoint
3773 const LineMap *Lines;;
3774 if (ReferencePoint != NULL)
3775 Lines = &(ReferencePoint->lines);
3776 else
3777 Lines = &LinesOnBoundary;
3778 LineMap::const_iterator findLines = Lines->begin();
3779 while (findLines != Lines->end()) {
3780 takePoint = false;
3781
3782 if (findLines->second->endpoints[0]->Nr == Point->nr) {
3783 takePoint = true;
3784 current = findLines->second->endpoints[1]->node;
3785 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
3786 takePoint = true;
3787 current = findLines->second->endpoints[0]->node;
3788 }
3789
3790 if (takePoint) {
3791 Log() << Verbose(1) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
3792 connectedPoints->insert(current);
3793 }
3794
3795 findLines++;
3796 }
3797
3798 if (connectedPoints->empty()) { // if have not found any points
3799 DoeLog(1) && (eLog()<< Verbose(1) << "We have not found any connected points to " << *Point<< "." << endl);
3800 return NULL;
3801 }
3802
3803 return connectedPoints;
3804};
3805
3806
3807/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3808 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3809 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3810 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3811 * triangle we are looking for.
3812 *
3813 * @param *out output stream for debugging
3814 * @param *SetOfNeighbours all points for which the angle should be calculated
3815 * @param *Point of which get all connected points
3816 * @param *Reference Reference vector for zero angle or NULL for no preference
3817 * @return list of the all points linked to the provided one
3818 */
3819TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3820{
3821 Info FunctionInfo(__func__);
3822 map<double, TesselPoint*> anglesOfPoints;
3823 TesselPointList *connectedCircle = new TesselPointList;
3824 Vector PlaneNormal;
3825 Vector AngleZero;
3826 Vector OrthogonalVector;
3827 Vector helper;
3828 const TesselPoint * const TrianglePoints[3] = {Point, NULL, NULL};
3829 TriangleList *triangles = NULL;
3830
3831 if (SetOfNeighbours == NULL) {
3832 DoeLog(2) && (eLog()<< Verbose(2) << "Could not find any connected points!" << endl);
3833 delete(connectedCircle);
3834 return NULL;
3835 }
3836
3837 // calculate central point
3838 triangles = FindTriangles(TrianglePoints);
3839 if ((triangles != NULL) && (!triangles->empty())) {
3840 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
3841 PlaneNormal.AddVector(&(*Runner)->NormalVector);
3842 } else {
3843 DoeLog(0) && (eLog()<< Verbose(0) << "Could not find any triangles for point " << *Point << "." << endl);
3844 performCriticalExit();
3845 }
3846 PlaneNormal.Scale(1.0/triangles->size());
3847 Log() << Verbose(1) << "INFO: Calculated PlaneNormal of all circle points is " << PlaneNormal << "." << endl;
3848 PlaneNormal.Normalize();
3849
3850 // construct one orthogonal vector
3851 if (Reference != NULL) {
3852 AngleZero.CopyVector(Reference);
3853 AngleZero.SubtractVector(Point->node);
3854 AngleZero.ProjectOntoPlane(&PlaneNormal);
3855 }
3856 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3857 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3858 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3859 AngleZero.SubtractVector(Point->node);
3860 AngleZero.ProjectOntoPlane(&PlaneNormal);
3861 if (AngleZero.NormSquared() < MYEPSILON) {
3862 DoeLog(0) && (eLog()<< Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl);
3863 performCriticalExit();
3864 }
3865 }
3866 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3867 if (AngleZero.NormSquared() > MYEPSILON)
3868 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3869 else
3870 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3871 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3872
3873 // go through all connected points and calculate angle
3874 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3875 helper.CopyVector((*listRunner)->node);
3876 helper.SubtractVector(Point->node);
3877 helper.ProjectOntoPlane(&PlaneNormal);
3878 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3879 Log() << Verbose(0) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
3880 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3881 }
3882
3883 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3884 connectedCircle->push_back(AngleRunner->second);
3885 }
3886
3887 return connectedCircle;
3888}
3889
3890/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
3891 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
3892 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
3893 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
3894 * triangle we are looking for.
3895 *
3896 * @param *SetOfNeighbours all points for which the angle should be calculated
3897 * @param *Point of which get all connected points
3898 * @param *Reference Reference vector for zero angle or NULL for no preference
3899 * @return list of the all points linked to the provided one
3900 */
3901TesselPointList * Tesselation::GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector * const Reference) const
3902{
3903 Info FunctionInfo(__func__);
3904 map<double, TesselPoint*> anglesOfPoints;
3905 TesselPointList *connectedCircle = new TesselPointList;
3906 Vector center;
3907 Vector PlaneNormal;
3908 Vector AngleZero;
3909 Vector OrthogonalVector;
3910 Vector helper;
3911
3912 if (SetOfNeighbours == NULL) {
3913 DoeLog(2) && (eLog()<< Verbose(2) << "Could not find any connected points!" << endl);
3914 delete(connectedCircle);
3915 return NULL;
3916 }
3917
3918 // check whether there's something to do
3919 if (SetOfNeighbours->size() < 3) {
3920 for (TesselPointSet::iterator TesselRunner = SetOfNeighbours->begin(); TesselRunner != SetOfNeighbours->end(); TesselRunner++)
3921 connectedCircle->push_back(*TesselRunner);
3922 return connectedCircle;
3923 }
3924
3925 Log() << Verbose(1) << "INFO: Point is " << *Point << " and Reference is " << *Reference << "." << endl;
3926 // calculate central point
3927
3928 TesselPointSet::const_iterator TesselA = SetOfNeighbours->begin();
3929 TesselPointSet::const_iterator TesselB = SetOfNeighbours->begin();
3930 TesselPointSet::const_iterator TesselC = SetOfNeighbours->begin();
3931 TesselB++;
3932 TesselC++;
3933 TesselC++;
3934 int counter = 0;
3935 while (TesselC != SetOfNeighbours->end()) {
3936 helper.MakeNormalVector((*TesselA)->node, (*TesselB)->node, (*TesselC)->node);
3937 Log() << Verbose(0) << "Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper << endl;
3938 counter++;
3939 TesselA++;
3940 TesselB++;
3941 TesselC++;
3942 PlaneNormal.AddVector(&helper);
3943 }
3944 //Log() << Verbose(0) << "Summed vectors " << center << "; number of points " << connectedPoints.size()
3945 // << "; scale factor " << counter;
3946 PlaneNormal.Scale(1.0/(double)counter);
3947// Log() << Verbose(1) << "INFO: Calculated center of all circle points is " << center << "." << endl;
3948//
3949// // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
3950// PlaneNormal.CopyVector(Point->node);
3951// PlaneNormal.SubtractVector(&center);
3952// PlaneNormal.Normalize();
3953 Log() << Verbose(1) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
3954
3955 // construct one orthogonal vector
3956 if (Reference != NULL) {
3957 AngleZero.CopyVector(Reference);
3958 AngleZero.SubtractVector(Point->node);
3959 AngleZero.ProjectOntoPlane(&PlaneNormal);
3960 }
3961 if ((Reference == NULL) || (AngleZero.NormSquared() < MYEPSILON )) {
3962 Log() << Verbose(1) << "Using alternatively " << *(*SetOfNeighbours->begin())->node << " as angle 0 referencer." << endl;
3963 AngleZero.CopyVector((*SetOfNeighbours->begin())->node);
3964 AngleZero.SubtractVector(Point->node);
3965 AngleZero.ProjectOntoPlane(&PlaneNormal);
3966 if (AngleZero.NormSquared() < MYEPSILON) {
3967 DoeLog(0) && (eLog()<< Verbose(0) << "CRITIAL: AngleZero is 0 even with alternative reference. The algorithm has to be changed here!" << endl);
3968 performCriticalExit();
3969 }
3970 }
3971 Log() << Verbose(1) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
3972 if (AngleZero.NormSquared() > MYEPSILON)
3973 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
3974 else
3975 OrthogonalVector.MakeNormalVector(&PlaneNormal);
3976 Log() << Verbose(1) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
3977
3978 // go through all connected points and calculate angle
3979 pair <map<double, TesselPoint*>::iterator, bool > InserterTest;
3980 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3981 helper.CopyVector((*listRunner)->node);
3982 helper.SubtractVector(Point->node);
3983 helper.ProjectOntoPlane(&PlaneNormal);
3984 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3985 if (angle > M_PI) // the correction is of no use here (and not desired)
3986 angle = 2.*M_PI - angle;
3987 Log() << Verbose(0) << "INFO: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << "." << endl;
3988 InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3989 if (!InserterTest.second) {
3990 DoeLog(0) && (eLog()<< Verbose(0) << "GetCircleOfSetOfPoints() got two atoms with same angle: " << *((InserterTest.first)->second) << " and " << (*listRunner) << endl);
3991 performCriticalExit();
3992 }
3993 }
3994
3995 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3996 connectedCircle->push_back(AngleRunner->second);
3997 }
3998
3999 return connectedCircle;
4000}
4001
4002/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
4003 *
4004 * @param *out output stream for debugging
4005 * @param *Point of which get all connected points
4006 * @return list of the all points linked to the provided one
4007 */
4008ListOfTesselPointList * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
4009{
4010 Info FunctionInfo(__func__);
4011 map<double, TesselPoint*> anglesOfPoints;
4012 list< TesselPointList *> *ListOfPaths = new list< TesselPointList *>;
4013 TesselPointList *connectedPath = NULL;
4014 Vector center;
4015 Vector PlaneNormal;
4016 Vector AngleZero;
4017 Vector OrthogonalVector;
4018 Vector helper;
4019 class BoundaryPointSet *ReferencePoint = NULL;
4020 class BoundaryPointSet *CurrentPoint = NULL;
4021 class BoundaryTriangleSet *triangle = NULL;
4022 class BoundaryLineSet *CurrentLine = NULL;
4023 class BoundaryLineSet *StartLine = NULL;
4024
4025 // find the respective boundary point
4026 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->nr);
4027 if (PointRunner != PointsOnBoundary.end()) {
4028 ReferencePoint = PointRunner->second;
4029 } else {
4030 DoeLog(1) && (eLog()<< Verbose(1) << "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl);
4031 return NULL;
4032 }
4033
4034 map <class BoundaryLineSet *, bool> TouchedLine;
4035 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
4036 map <class BoundaryLineSet *, bool>::iterator LineRunner;
4037 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
4038 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
4039 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
4040 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
4041 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
4042 }
4043 if (!ReferencePoint->lines.empty()) {
4044 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
4045 LineRunner = TouchedLine.find(runner->second);
4046 if (LineRunner == TouchedLine.end()) {
4047 DoeLog(1) && (eLog()<< Verbose(1) << "I could not find " << *runner->second << " in the touched list." << endl);
4048 } else if (!LineRunner->second) {
4049 LineRunner->second = true;
4050 connectedPath = new TesselPointList;
4051 triangle = NULL;
4052 CurrentLine = runner->second;
4053 StartLine = CurrentLine;
4054 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
4055 Log() << Verbose(1)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
4056 do {
4057 // push current one
4058 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
4059 connectedPath->push_back(CurrentPoint->node);
4060
4061 // find next triangle
4062 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
4063 Log() << Verbose(1) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
4064 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
4065 triangle = Runner->second;
4066 TriangleRunner = TouchedTriangle.find(triangle);
4067 if (TriangleRunner != TouchedTriangle.end()) {
4068 if (!TriangleRunner->second) {
4069 TriangleRunner->second = true;
4070 Log() << Verbose(1) << "INFO: Connecting triangle is " << *triangle << "." << endl;
4071 break;
4072 } else {
4073 Log() << Verbose(1) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
4074 triangle = NULL;
4075 }
4076 } else {
4077 DoeLog(1) && (eLog()<< Verbose(1) << "I could not find " << *triangle << " in the touched list." << endl);
4078 triangle = NULL;
4079 }
4080 }
4081 }
4082 if (triangle == NULL)
4083 break;
4084 // find next line
4085 for (int i=0;i<3;i++) {
4086 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
4087 CurrentLine = triangle->lines[i];
4088 Log() << Verbose(1) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
4089 break;
4090 }
4091 }
4092 LineRunner = TouchedLine.find(CurrentLine);
4093 if (LineRunner == TouchedLine.end())
4094 DoeLog(1) && (eLog()<< Verbose(1) << "I could not find " << *CurrentLine << " in the touched list." << endl);
4095 else
4096 LineRunner->second = true;
4097 // find next point
4098 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
4099
4100 } while (CurrentLine != StartLine);
4101 // last point is missing, as it's on start line
4102 Log() << Verbose(1) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
4103 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
4104 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
4105
4106 ListOfPaths->push_back(connectedPath);
4107 } else {
4108 Log() << Verbose(1) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
4109 }
4110 }
4111 } else {
4112 DoeLog(1) && (eLog()<< Verbose(1) << "There are no lines attached to " << *ReferencePoint << "." << endl);
4113 }
4114
4115 return ListOfPaths;
4116}
4117
4118/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
4119 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
4120 * @param *out output stream for debugging
4121 * @param *Point of which get all connected points
4122 * @return list of the closed paths
4123 */
4124ListOfTesselPointList * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
4125{
4126 Info FunctionInfo(__func__);
4127 list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
4128 list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *>;
4129 TesselPointList *connectedPath = NULL;
4130 TesselPointList *newPath = NULL;
4131 int count = 0;
4132
4133
4134 TesselPointList::iterator CircleRunner;
4135 TesselPointList::iterator CircleStart;
4136
4137 for(list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
4138 connectedPath = *ListRunner;
4139
4140 Log() << Verbose(1) << "INFO: Current path is " << connectedPath << "." << endl;
4141
4142 // go through list, look for reappearance of starting Point and count
4143 CircleStart = connectedPath->begin();
4144
4145 // go through list, look for reappearance of starting Point and create list
4146 TesselPointList::iterator Marker = CircleStart;
4147 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
4148 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
4149 // we have a closed circle from Marker to new Marker
4150 Log() << Verbose(1) << count+1 << ". closed path consists of: ";
4151 newPath = new TesselPointList;
4152 TesselPointList::iterator CircleSprinter = Marker;
4153 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
4154 newPath->push_back(*CircleSprinter);
4155 Log() << Verbose(0) << (**CircleSprinter) << " <-> ";
4156 }
4157 Log() << Verbose(0) << ".." << endl;
4158 count++;
4159 Marker = CircleRunner;
4160
4161 // add to list
4162 ListofClosedPaths->push_back(newPath);
4163 }
4164 }
4165 }
4166 Log() << Verbose(1) << "INFO: " << count << " closed additional path(s) have been created." << endl;
4167
4168 // delete list of paths
4169 while (!ListofPaths->empty()) {
4170 connectedPath = *(ListofPaths->begin());
4171 ListofPaths->remove(connectedPath);
4172 delete(connectedPath);
4173 }
4174 delete(ListofPaths);
4175
4176 // exit
4177 return ListofClosedPaths;
4178};
4179
4180
4181/** Gets all belonging triangles for a given BoundaryPointSet.
4182 * \param *out output stream for debugging
4183 * \param *Point BoundaryPoint
4184 * \return pointer to allocated list of triangles
4185 */
4186TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
4187{
4188 Info FunctionInfo(__func__);
4189 TriangleSet *connectedTriangles = new TriangleSet;
4190
4191 if (Point == NULL) {
4192 DoeLog(1) && (eLog()<< Verbose(1) << "Point given is NULL." << endl);
4193 } else {
4194 // go through its lines and insert all triangles
4195 for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
4196 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
4197 connectedTriangles->insert(TriangleRunner->second);
4198 }
4199 }
4200
4201 return connectedTriangles;
4202};
4203
4204
4205/** Removes a boundary point from the envelope while keeping it closed.
4206 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
4207 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
4208 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
4209 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
4210 * -# the surface is closed, when the path is empty
4211 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
4212 * \param *out output stream for debugging
4213 * \param *point point to be removed
4214 * \return volume added to the volume inside the tesselated surface by the removal
4215 */
4216double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point) {
4217 class BoundaryLineSet *line = NULL;
4218 class BoundaryTriangleSet *triangle = NULL;
4219 Vector OldPoint, NormalVector;
4220 double volume = 0;
4221 int count = 0;
4222
4223 if (point == NULL) {
4224 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot remove the point " << point << ", it's NULL!" << endl);
4225 return 0.;
4226 } else
4227 Log() << Verbose(0) << "Removing point " << *point << " from tesselated boundary ..." << endl;
4228
4229 // copy old location for the volume
4230 OldPoint.CopyVector(point->node->node);
4231
4232 // get list of connected points
4233 if (point->lines.empty()) {
4234 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot remove the point " << *point << ", it's connected to no lines!" << endl);
4235 return 0.;
4236 }
4237
4238 list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
4239 TesselPointList *connectedPath = NULL;
4240
4241 // gather all triangles
4242 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
4243 count+=LineRunner->second->triangles.size();
4244 TriangleMap Candidates;
4245 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
4246 line = LineRunner->second;
4247 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
4248 triangle = TriangleRunner->second;
4249 Candidates.insert( TrianglePair (triangle->Nr, triangle) );
4250 }
4251 }
4252
4253 // remove all triangles
4254 count=0;
4255 NormalVector.Zero();
4256 for (TriangleMap::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
4257 Log() << Verbose(1) << "INFO: Removing triangle " << *(Runner->second) << "." << endl;
4258 NormalVector.SubtractVector(&Runner->second->NormalVector); // has to point inward
4259 RemoveTesselationTriangle(Runner->second);
4260 count++;
4261 }
4262 Log() << Verbose(1) << count << " triangles were removed." << endl;
4263
4264 list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
4265 list<TesselPointList *>::iterator ListRunner = ListAdvance;
4266 TriangleMap::iterator NumberRunner = Candidates.begin();
4267 TesselPointList::iterator StartNode, MiddleNode, EndNode;
4268 double angle;
4269 double smallestangle;
4270 Vector Point, Reference, OrthogonalVector;
4271 if (count > 2) { // less than three triangles, then nothing will be created
4272 class TesselPoint *TriangleCandidates[3];
4273 count = 0;
4274 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
4275 if (ListAdvance != ListOfClosedPaths->end())
4276 ListAdvance++;
4277
4278 connectedPath = *ListRunner;
4279
4280 // re-create all triangles by going through connected points list
4281 LineList NewLines;
4282 for (;!connectedPath->empty();) {
4283 // search middle node with widest angle to next neighbours
4284 EndNode = connectedPath->end();
4285 smallestangle = 0.;
4286 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
4287 Log() << Verbose(1) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
4288 // construct vectors to next and previous neighbour
4289 StartNode = MiddleNode;
4290 if (StartNode == connectedPath->begin())
4291 StartNode = connectedPath->end();
4292 StartNode--;
4293 //Log() << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
4294 Point.CopyVector((*StartNode)->node);
4295 Point.SubtractVector((*MiddleNode)->node);
4296 StartNode = MiddleNode;
4297 StartNode++;
4298 if (StartNode == connectedPath->end())
4299 StartNode = connectedPath->begin();
4300 //Log() << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
4301 Reference.CopyVector((*StartNode)->node);
4302 Reference.SubtractVector((*MiddleNode)->node);
4303 OrthogonalVector.CopyVector((*MiddleNode)->node);
4304 OrthogonalVector.SubtractVector(&OldPoint);
4305 OrthogonalVector.MakeNormalVector(&Reference);
4306 angle = GetAngle(Point, Reference, OrthogonalVector);
4307 //if (angle < M_PI) // no wrong-sided triangles, please?
4308 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
4309 smallestangle = angle;
4310 EndNode = MiddleNode;
4311 }
4312 }
4313 MiddleNode = EndNode;
4314 if (MiddleNode == connectedPath->end()) {
4315 DoeLog(0) && (eLog()<< Verbose(0) << "CRITICAL: Could not find a smallest angle!" << endl);
4316 performCriticalExit();
4317 }
4318 StartNode = MiddleNode;
4319 if (StartNode == connectedPath->begin())
4320 StartNode = connectedPath->end();
4321 StartNode--;
4322 EndNode++;
4323 if (EndNode == connectedPath->end())
4324 EndNode = connectedPath->begin();
4325 Log() << Verbose(2) << "INFO: StartNode is " << **StartNode << "." << endl;
4326 Log() << Verbose(2) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
4327 Log() << Verbose(2) << "INFO: EndNode is " << **EndNode << "." << endl;
4328 Log() << Verbose(1) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
4329 TriangleCandidates[0] = *StartNode;
4330 TriangleCandidates[1] = *MiddleNode;
4331 TriangleCandidates[2] = *EndNode;
4332 triangle = GetPresentTriangle(TriangleCandidates);
4333 if (triangle != NULL) {
4334 DoeLog(0) && (eLog()<< Verbose(0) << "New triangle already present, skipping!" << endl);
4335 StartNode++;
4336 MiddleNode++;
4337 EndNode++;
4338 if (StartNode == connectedPath->end())
4339 StartNode = connectedPath->begin();
4340 if (MiddleNode == connectedPath->end())
4341 MiddleNode = connectedPath->begin();
4342 if (EndNode == connectedPath->end())
4343 EndNode = connectedPath->begin();
4344 continue;
4345 }
4346 Log() << Verbose(3) << "Adding new triangle points."<< endl;
4347 AddTesselationPoint(*StartNode, 0);
4348 AddTesselationPoint(*MiddleNode, 1);
4349 AddTesselationPoint(*EndNode, 2);
4350 Log() << Verbose(3) << "Adding new triangle lines."<< endl;
4351 AddTesselationLine(NULL, TPS[0], TPS[1], 0);
4352 AddTesselationLine(NULL, TPS[0], TPS[2], 1);
4353 NewLines.push_back(BLS[1]);
4354 AddTesselationLine(NULL, TPS[1], TPS[2], 2);
4355 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4356 BTS->GetNormalVector(NormalVector);
4357 AddTesselationTriangle();
4358 // calculate volume summand as a general tetraeder
4359 volume += CalculateVolumeofGeneralTetraeder(*TPS[0]->node->node, *TPS[1]->node->node, *TPS[2]->node->node, OldPoint);
4360 // advance number
4361 count++;
4362
4363 // prepare nodes for next triangle
4364 StartNode = EndNode;
4365 Log() << Verbose(2) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
4366 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
4367 if (connectedPath->size() == 2) { // we are done
4368 connectedPath->remove(*StartNode); // remove the start node
4369 connectedPath->remove(*EndNode); // remove the end node
4370 break;
4371 } else if (connectedPath->size() < 2) { // something's gone wrong!
4372 DoeLog(0) && (eLog()<< Verbose(0) << "CRITICAL: There are only two endpoints left!" << endl);
4373 performCriticalExit();
4374 } else {
4375 MiddleNode = StartNode;
4376 MiddleNode++;
4377 if (MiddleNode == connectedPath->end())
4378 MiddleNode = connectedPath->begin();
4379 EndNode = MiddleNode;
4380 EndNode++;
4381 if (EndNode == connectedPath->end())
4382 EndNode = connectedPath->begin();
4383 }
4384 }
4385 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
4386 if (NewLines.size() > 1) {
4387 LineList::iterator Candidate;
4388 class BoundaryLineSet *OtherBase = NULL;
4389 double tmp, maxgain;
4390 do {
4391 maxgain = 0;
4392 for(LineList::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
4393 tmp = PickFarthestofTwoBaselines(*Runner);
4394 if (maxgain < tmp) {
4395 maxgain = tmp;
4396 Candidate = Runner;
4397 }
4398 }
4399 if (maxgain != 0) {
4400 volume += maxgain;
4401 Log() << Verbose(1) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
4402 OtherBase = FlipBaseline(*Candidate);
4403 NewLines.erase(Candidate);
4404 NewLines.push_back(OtherBase);
4405 }
4406 } while (maxgain != 0.);
4407 }
4408
4409 ListOfClosedPaths->remove(connectedPath);
4410 delete(connectedPath);
4411 }
4412 Log() << Verbose(0) << count << " triangles were created." << endl;
4413 } else {
4414 while (!ListOfClosedPaths->empty()) {
4415 ListRunner = ListOfClosedPaths->begin();
4416 connectedPath = *ListRunner;
4417 ListOfClosedPaths->remove(connectedPath);
4418 delete(connectedPath);
4419 }
4420 Log() << Verbose(0) << "No need to create any triangles." << endl;
4421 }
4422 delete(ListOfClosedPaths);
4423
4424 Log() << Verbose(0) << "Removed volume is " << volume << "." << endl;
4425
4426 return volume;
4427};
4428
4429
4430
4431/**
4432 * Finds triangles belonging to the three provided points.
4433 *
4434 * @param *Points[3] list, is expected to contain three points (NULL means wildcard)
4435 *
4436 * @return triangles which belong to the provided points, will be empty if there are none,
4437 * will usually be one, in case of degeneration, there will be two
4438 */
4439TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
4440{
4441 Info FunctionInfo(__func__);
4442 TriangleList *result = new TriangleList;
4443 LineMap::const_iterator FindLine;
4444 TriangleMap::const_iterator FindTriangle;
4445 class BoundaryPointSet *TrianglePoints[3];
4446 size_t NoOfWildcards = 0;
4447
4448 for (int i = 0; i < 3; i++) {
4449 if (Points[i] == NULL) {
4450 NoOfWildcards++;
4451 TrianglePoints[i] = NULL;
4452 } else {
4453 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->nr);
4454 if (FindPoint != PointsOnBoundary.end()) {
4455 TrianglePoints[i] = FindPoint->second;
4456 } else {
4457 TrianglePoints[i] = NULL;
4458 }
4459 }
4460 }
4461
4462 switch (NoOfWildcards) {
4463 case 0: // checks lines between the points in the Points for their adjacent triangles
4464 for (int i = 0; i < 3; i++) {
4465 if (TrianglePoints[i] != NULL) {
4466 for (int j = i+1; j < 3; j++) {
4467 if (TrianglePoints[j] != NULL) {
4468 for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr); // is a multimap!
4469 (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->nr);
4470 FindLine++) {
4471 for (FindTriangle = FindLine->second->triangles.begin();
4472 FindTriangle != FindLine->second->triangles.end();
4473 FindTriangle++) {
4474 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
4475 result->push_back(FindTriangle->second);
4476 }
4477 }
4478 }
4479 // Is it sufficient to consider one of the triangle lines for this.
4480 return result;
4481 }
4482 }
4483 }
4484 }
4485 break;
4486 case 1: // copy all triangles of the respective line
4487 {
4488 int i=0;
4489 for (; i < 3; i++)
4490 if (TrianglePoints[i] == NULL)
4491 break;
4492 for (FindLine = TrianglePoints[(i+1)%3]->lines.find(TrianglePoints[(i+2)%3]->node->nr); // is a multimap!
4493 (FindLine != TrianglePoints[(i+1)%3]->lines.end()) && (FindLine->first == TrianglePoints[(i+2)%3]->node->nr);
4494 FindLine++) {
4495 for (FindTriangle = FindLine->second->triangles.begin();
4496 FindTriangle != FindLine->second->triangles.end();
4497 FindTriangle++) {
4498 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
4499 result->push_back(FindTriangle->second);
4500 }
4501 }
4502 }
4503 break;
4504 }
4505 case 2: // copy all triangles of the respective point
4506 {
4507 int i=0;
4508 for (; i < 3; i++)
4509 if (TrianglePoints[i] != NULL)
4510 break;
4511 for (LineMap::const_iterator line = TrianglePoints[i]->lines.begin(); line != TrianglePoints[i]->lines.end(); line++)
4512 for (TriangleMap::const_iterator triangle = line->second->triangles.begin(); triangle != line->second->triangles.end(); triangle++)
4513 result->push_back(triangle->second);
4514 result->sort();
4515 result->unique();
4516 break;
4517 }
4518 case 3: // copy all triangles
4519 {
4520 for (TriangleMap::const_iterator triangle = TrianglesOnBoundary.begin(); triangle != TrianglesOnBoundary.end(); triangle++)
4521 result->push_back(triangle->second);
4522 break;
4523 }
4524 default:
4525 DoeLog(0) && (eLog()<< Verbose(0) << "Number of wildcards is greater than 3, cannot happen!" << endl);
4526 performCriticalExit();
4527 break;
4528 }
4529
4530 return result;
4531}
4532
4533struct BoundaryLineSetCompare {
4534 bool operator() (const BoundaryLineSet * const a, const BoundaryLineSet * const b) {
4535 int lowerNra = -1;
4536 int lowerNrb = -1;
4537
4538 if (a->endpoints[0] < a->endpoints[1])
4539 lowerNra = 0;
4540 else
4541 lowerNra = 1;
4542
4543 if (b->endpoints[0] < b->endpoints[1])
4544 lowerNrb = 0;
4545 else
4546 lowerNrb = 1;
4547
4548 if (a->endpoints[lowerNra] < b->endpoints[lowerNrb])
4549 return true;
4550 else if (a->endpoints[lowerNra] > b->endpoints[lowerNrb])
4551 return false;
4552 else { // both lower-numbered endpoints are the same ...
4553 if (a->endpoints[(lowerNra+1)%2] < b->endpoints[(lowerNrb+1)%2])
4554 return true;
4555 else if (a->endpoints[(lowerNra+1)%2] > b->endpoints[(lowerNrb+1)%2])
4556 return false;
4557 }
4558 return false;
4559 };
4560};
4561
4562#define UniqueLines set < class BoundaryLineSet *, BoundaryLineSetCompare>
4563
4564/**
4565 * Finds all degenerated lines within the tesselation structure.
4566 *
4567 * @return map of keys of degenerated line pairs, each line occurs twice
4568 * in the list, once as key and once as value
4569 */
4570IndexToIndex * Tesselation::FindAllDegeneratedLines()
4571{
4572 Info FunctionInfo(__func__);
4573 UniqueLines AllLines;
4574 IndexToIndex * DegeneratedLines = new IndexToIndex;
4575
4576 // sanity check
4577 if (LinesOnBoundary.empty()) {
4578 DoeLog(2) && (eLog()<< Verbose(2) << "FindAllDegeneratedTriangles() was called without any tesselation structure.");
4579 return DegeneratedLines;
4580 }
4581
4582 LineMap::iterator LineRunner1;
4583 pair< UniqueLines::iterator, bool> tester;
4584 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
4585 tester = AllLines.insert( LineRunner1->second );
4586 if (!tester.second) { // found degenerated line
4587 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr) );
4588 DegeneratedLines->insert ( pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr) );
4589 }
4590 }
4591
4592 AllLines.clear();
4593
4594 Log() << Verbose(0) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
4595 IndexToIndex::iterator it;
4596 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
4597 const LineMap::const_iterator Line1 = LinesOnBoundary.find((*it).first);
4598 const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
4599 if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
4600 Log() << Verbose(0) << *Line1->second << " => " << *Line2->second << endl;
4601 else
4602 DoeLog(1) && (eLog()<< Verbose(1) << "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!" << endl);
4603 }
4604
4605 return DegeneratedLines;
4606}
4607
4608/**
4609 * Finds all degenerated triangles within the tesselation structure.
4610 *
4611 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
4612 * in the list, once as key and once as value
4613 */
4614IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
4615{
4616 Info FunctionInfo(__func__);
4617 IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
4618 IndexToIndex * DegeneratedTriangles = new IndexToIndex;
4619
4620 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
4621 LineMap::iterator Liner;
4622 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
4623
4624 for (IndexToIndex::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
4625 // run over both lines' triangles
4626 Liner = LinesOnBoundary.find(LineRunner->first);
4627 if (Liner != LinesOnBoundary.end())
4628 line1 = Liner->second;
4629 Liner = LinesOnBoundary.find(LineRunner->second);
4630 if (Liner != LinesOnBoundary.end())
4631 line2 = Liner->second;
4632 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
4633 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
4634 if ((TriangleRunner1->second != TriangleRunner2->second)
4635 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
4636 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
4637 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
4638 }
4639 }
4640 }
4641 }
4642 delete(DegeneratedLines);
4643
4644 Log() << Verbose(0) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
4645 IndexToIndex::iterator it;
4646 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
4647 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
4648
4649 return DegeneratedTriangles;
4650}
4651
4652/**
4653 * Purges degenerated triangles from the tesselation structure if they are not
4654 * necessary to keep a single point within the structure.
4655 */
4656void Tesselation::RemoveDegeneratedTriangles()
4657{
4658 Info FunctionInfo(__func__);
4659 IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
4660 TriangleMap::iterator finder;
4661 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
4662 int count = 0;
4663
4664 for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
4665 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
4666 ) {
4667 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
4668 if (finder != TrianglesOnBoundary.end())
4669 triangle = finder->second;
4670 else
4671 break;
4672 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
4673 if (finder != TrianglesOnBoundary.end())
4674 partnerTriangle = finder->second;
4675 else
4676 break;
4677
4678 bool trianglesShareLine = false;
4679 for (int i = 0; i < 3; ++i)
4680 for (int j = 0; j < 3; ++j)
4681 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
4682
4683 if (trianglesShareLine
4684 && (triangle->endpoints[1]->LinesCount > 2)
4685 && (triangle->endpoints[2]->LinesCount > 2)
4686 && (triangle->endpoints[0]->LinesCount > 2)
4687 ) {
4688 // check whether we have to fix lines
4689 BoundaryTriangleSet *Othertriangle = NULL;
4690 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
4691 TriangleMap::iterator TriangleRunner;
4692 for (int i = 0; i < 3; ++i)
4693 for (int j = 0; j < 3; ++j)
4694 if (triangle->lines[i] != partnerTriangle->lines[j]) {
4695 // get the other two triangles
4696 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
4697 if (TriangleRunner->second != triangle) {
4698 Othertriangle = TriangleRunner->second;
4699 }
4700 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
4701 if (TriangleRunner->second != partnerTriangle) {
4702 OtherpartnerTriangle = TriangleRunner->second;
4703 }
4704 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
4705 // the line of triangle receives the degenerated ones
4706 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
4707 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
4708 for (int k=0;k<3;k++)
4709 if (triangle->lines[i] == Othertriangle->lines[k]) {
4710 Othertriangle->lines[k] = partnerTriangle->lines[j];
4711 break;
4712 }
4713 // the line of partnerTriangle receives the non-degenerated ones
4714 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
4715 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
4716 partnerTriangle->lines[j] = triangle->lines[i];
4717 }
4718
4719 // erase the pair
4720 count += (int) DegeneratedTriangles->erase(triangle->Nr);
4721 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
4722 RemoveTesselationTriangle(triangle);
4723 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
4724 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
4725 RemoveTesselationTriangle(partnerTriangle);
4726 } else {
4727 Log() << Verbose(0) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
4728 << " and its partner " << *partnerTriangle << " because it is essential for at"
4729 << " least one of the endpoints to be kept in the tesselation structure." << endl;
4730 }
4731 }
4732 delete(DegeneratedTriangles);
4733 if (count > 0)
4734 LastTriangle = NULL;
4735
4736 Log() << Verbose(0) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
4737}
4738
4739/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
4740 * We look for the closest point on the boundary, we look through its connected boundary lines and
4741 * seek the one with the minimum angle between its center point and the new point and this base line.
4742 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
4743 * \param *out output stream for debugging
4744 * \param *point point to add
4745 * \param *LC Linked Cell structure to find nearest point
4746 */
4747void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell *LC)
4748{
4749 Info FunctionInfo(__func__);
4750 // find nearest boundary point
4751 class TesselPoint *BackupPoint = NULL;
4752 class TesselPoint *NearestPoint = FindClosestTesselPoint(point->node, BackupPoint, LC);
4753 class BoundaryPointSet *NearestBoundaryPoint = NULL;
4754 PointMap::iterator PointRunner;
4755
4756 if (NearestPoint == point)
4757 NearestPoint = BackupPoint;
4758 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
4759 if (PointRunner != PointsOnBoundary.end()) {
4760 NearestBoundaryPoint = PointRunner->second;
4761 } else {
4762 DoeLog(1) && (eLog()<< Verbose(1) << "I cannot find the boundary point." << endl);
4763 return;
4764 }
4765 Log() << Verbose(0) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
4766
4767 // go through its lines and find the best one to split
4768 Vector CenterToPoint;
4769 Vector BaseLine;
4770 double angle, BestAngle = 0.;
4771 class BoundaryLineSet *BestLine = NULL;
4772 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
4773 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
4774 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
4775 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
4776 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
4777 CenterToPoint.Scale(0.5);
4778 CenterToPoint.SubtractVector(point->node);
4779 angle = CenterToPoint.Angle(&BaseLine);
4780 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
4781 BestAngle = angle;
4782 BestLine = Runner->second;
4783 }
4784 }
4785
4786 // remove one triangle from the chosen line
4787 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
4788 BestLine->triangles.erase(TempTriangle->Nr);
4789 int nr = -1;
4790 for (int i=0;i<3; i++) {
4791 if (TempTriangle->lines[i] == BestLine) {
4792 nr = i;
4793 break;
4794 }
4795 }
4796
4797 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
4798 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4799 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4800 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4801 AddTesselationPoint(point, 2);
4802 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4803 AddTesselationLine(NULL, TPS[0], TPS[1], 0);
4804 AddTesselationLine(NULL, TPS[0], TPS[2], 1);
4805 AddTesselationLine(NULL, TPS[1], TPS[2], 2);
4806 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4807 BTS->GetNormalVector(TempTriangle->NormalVector);
4808 BTS->NormalVector.Scale(-1.);
4809 Log() << Verbose(1) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
4810 AddTesselationTriangle();
4811
4812 // create other side of this triangle and close both new sides of the first created triangle
4813 Log() << Verbose(2) << "Adding new triangle points."<< endl;
4814 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4815 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4816 AddTesselationPoint(point, 2);
4817 Log() << Verbose(2) << "Adding new triangle lines."<< endl;
4818 AddTesselationLine(NULL, TPS[0], TPS[1], 0);
4819 AddTesselationLine(NULL, TPS[0], TPS[2], 1);
4820 AddTesselationLine(NULL, TPS[1], TPS[2], 2);
4821 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4822 BTS->GetNormalVector(TempTriangle->NormalVector);
4823 Log() << Verbose(1) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
4824 AddTesselationTriangle();
4825
4826 // add removed triangle to the last open line of the second triangle
4827 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
4828 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
4829 if (BestLine == BTS->lines[i]){
4830 DoeLog(0) && (eLog()<< Verbose(0) << "BestLine is same as found line, something's wrong here!" << endl);
4831 performCriticalExit();
4832 }
4833 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
4834 TempTriangle->lines[nr] = BTS->lines[i];
4835 break;
4836 }
4837 }
4838};
4839
4840/** Writes the envelope to file.
4841 * \param *out otuput stream for debugging
4842 * \param *filename basename of output file
4843 * \param *cloud PointCloud structure with all nodes
4844 */
4845void Tesselation::Output(const char *filename, const PointCloud * const cloud)
4846{
4847 Info FunctionInfo(__func__);
4848 ofstream *tempstream = NULL;
4849 string NameofTempFile;
4850 char NumberName[255];
4851
4852 if (LastTriangle != NULL) {
4853 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
4854 if (DoTecplotOutput) {
4855 string NameofTempFile(filename);
4856 NameofTempFile.append(NumberName);
4857 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4858 NameofTempFile.erase(npos, 1);
4859 NameofTempFile.append(TecplotSuffix);
4860 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4861 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4862 WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
4863 tempstream->close();
4864 tempstream->flush();
4865 delete(tempstream);
4866 }
4867
4868 if (DoRaster3DOutput) {
4869 string NameofTempFile(filename);
4870 NameofTempFile.append(NumberName);
4871 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4872 NameofTempFile.erase(npos, 1);
4873 NameofTempFile.append(Raster3DSuffix);
4874 Log() << Verbose(0) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
4875 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4876 WriteRaster3dFile(tempstream, this, cloud);
4877 IncludeSphereinRaster3D(tempstream, this, cloud);
4878 tempstream->close();
4879 tempstream->flush();
4880 delete(tempstream);
4881 }
4882 }
4883 if (DoTecplotOutput || DoRaster3DOutput)
4884 TriangleFilesWritten++;
4885};
4886
4887struct BoundaryPolygonSetCompare {
4888 bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const {
4889 if (s1->endpoints.size() < s2->endpoints.size())
4890 return true;
4891 else if (s1->endpoints.size() > s2->endpoints.size())
4892 return false;
4893 else { // equality of number of endpoints
4894 PointSet::const_iterator Walker1 = s1->endpoints.begin();
4895 PointSet::const_iterator Walker2 = s2->endpoints.begin();
4896 while ((Walker1 != s1->endpoints.end()) || (Walker2 != s2->endpoints.end())) {
4897 if ((*Walker1)->Nr < (*Walker2)->Nr)
4898 return true;
4899 else if ((*Walker1)->Nr > (*Walker2)->Nr)
4900 return false;
4901 Walker1++;
4902 Walker2++;
4903 }
4904 return false;
4905 }
4906 }
4907};
4908
4909#define UniquePolygonSet set < BoundaryPolygonSet *, BoundaryPolygonSetCompare>
4910
4911/** Finds all degenerated polygons and calls ReTesselateDegeneratedPolygon()/
4912 * \return number of polygons found
4913 */
4914int Tesselation::CorrectAllDegeneratedPolygons()
4915{
4916 Info FunctionInfo(__func__);
4917
4918 /// 2. Go through all BoundaryPointSet's, check their triangles' NormalVector
4919 IndexToIndex *DegeneratedTriangles = FindAllDegeneratedTriangles();
4920 set < BoundaryPointSet *> EndpointCandidateList;
4921 pair < set < BoundaryPointSet *>::iterator, bool > InsertionTester;
4922 pair < map < int, Vector *>::iterator, bool > TriangleInsertionTester;
4923 for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
4924 Log() << Verbose(0) << "Current point is " << *Runner->second << "." << endl;
4925 map < int, Vector *> TriangleVectors;
4926 // gather all NormalVectors
4927 Log() << Verbose(1) << "Gathering triangles ..." << endl;
4928 for (LineMap::const_iterator LineRunner = (Runner->second)->lines.begin(); LineRunner != (Runner->second)->lines.end(); LineRunner++)
4929 for (TriangleMap::const_iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
4930 if (DegeneratedTriangles->find(TriangleRunner->second->Nr) == DegeneratedTriangles->end()) {
4931 TriangleInsertionTester = TriangleVectors.insert( pair< int, Vector *> ((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)) );
4932 if (TriangleInsertionTester.second)
4933 Log() << Verbose(1) << " Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list." << endl;
4934 } else {
4935 Log() << Verbose(1) << " NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one." << endl;
4936 }
4937 }
4938 // check whether there are two that are parallel
4939 Log() << Verbose(1) << "Finding two parallel triangles ..." << endl;
4940 for (map < int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
4941 for (map < int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
4942 if (VectorWalker != VectorRunner) { // skip equals
4943 const double SCP = VectorWalker->second->ScalarProduct(VectorRunner->second); // ScalarProduct should result in -1. for degenerated triangles
4944 Log() << Verbose(1) << "Checking " << *VectorWalker->second<< " against " << *VectorRunner->second << ": " << SCP << endl;
4945 if (fabs(SCP + 1.) < ParallelEpsilon) {
4946 InsertionTester = EndpointCandidateList.insert((Runner->second));
4947 if (InsertionTester.second)
4948 Log() << Verbose(0) << " Adding " << *Runner->second << " to endpoint candidate list." << endl;
4949 // and break out of both loops
4950 VectorWalker = TriangleVectors.end();
4951 VectorRunner = TriangleVectors.end();
4952 break;
4953 }
4954 }
4955 }
4956
4957 /// 3. Find connected endpoint candidates and put them into a polygon
4958 UniquePolygonSet ListofDegeneratedPolygons;
4959 BoundaryPointSet *Walker = NULL;
4960 BoundaryPointSet *OtherWalker = NULL;
4961 BoundaryPolygonSet *Current = NULL;
4962 stack <BoundaryPointSet*> ToCheckConnecteds;
4963 while (!EndpointCandidateList.empty()) {
4964 Walker = *(EndpointCandidateList.begin());
4965 if (Current == NULL) { // create a new polygon with current candidate
4966 Log() << Verbose(0) << "Starting new polygon set at point " << *Walker << endl;
4967 Current = new BoundaryPolygonSet;
4968 Current->endpoints.insert(Walker);
4969 EndpointCandidateList.erase(Walker);
4970 ToCheckConnecteds.push(Walker);
4971 }
4972
4973 // go through to-check stack
4974 while (!ToCheckConnecteds.empty()) {
4975 Walker = ToCheckConnecteds.top(); // fetch ...
4976 ToCheckConnecteds.pop(); // ... and remove
4977 for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
4978 OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
4979 Log() << Verbose(1) << "Checking " << *OtherWalker << endl;
4980 set < BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
4981 if (Finder != EndpointCandidateList.end()) { // found a connected partner
4982 Log() << Verbose(1) << " Adding to polygon." << endl;
4983 Current->endpoints.insert(OtherWalker);
4984 EndpointCandidateList.erase(Finder); // remove from candidates
4985 ToCheckConnecteds.push(OtherWalker); // but check its partners too
4986 } else {
4987 Log() << Verbose(1) << " is not connected to " << *Walker << endl;
4988 }
4989 }
4990 }
4991
4992 Log() << Verbose(0) << "Final polygon is " << *Current << endl;
4993 ListofDegeneratedPolygons.insert(Current);
4994 Current = NULL;
4995 }
4996
4997 const int counter = ListofDegeneratedPolygons.size();
4998
4999 Log() << Verbose(0) << "The following " << counter << " degenerated polygons have been found: " << endl;
5000 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
5001 Log() << Verbose(0) << " " << **PolygonRunner << endl;
5002
5003 /// 4. Go through all these degenerated polygons
5004 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++) {
5005 stack <int> TriangleNrs;
5006 Vector NormalVector;
5007 /// 4a. Gather all triangles of this polygon
5008 TriangleSet *T = (*PolygonRunner)->GetAllContainedTrianglesFromEndpoints();
5009
5010 // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
5011 if (T->size() == 2) {
5012 Log() << Verbose(1) << " Skipping degenerated polygon, is just a (already simply degenerated) triangle." << endl;
5013 delete(T);
5014 continue;
5015 }
5016
5017 // check whether number is even
5018 // If this case occurs, we have to think about it!
5019 // The Problem is probably due to two degenerated polygons being connected by a bridging, non-degenerated polygon, as somehow one node has
5020 // connections to either polygon ...
5021 if (T->size() % 2 != 0) {
5022 DoeLog(0) && (eLog()<< Verbose(0) << " degenerated polygon contains an odd number of triangles, probably contains bridging non-degenerated ones, too!" << endl);
5023 performCriticalExit();
5024 }
5025
5026 TriangleSet::iterator TriangleWalker = T->begin(); // is the inner iterator
5027 /// 4a. Get NormalVector for one side (this is "front")
5028 NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
5029 Log() << Verbose(1) << "\"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector << endl;
5030 TriangleWalker++;
5031 TriangleSet::iterator TriangleSprinter = TriangleWalker; // is the inner advanced iterator
5032 /// 4b. Remove all triangles whose NormalVector is in opposite direction (i.e. "back")
5033 BoundaryTriangleSet *triangle = NULL;
5034 while (TriangleSprinter != T->end()) {
5035 TriangleWalker = TriangleSprinter;
5036 triangle = *TriangleWalker;
5037 TriangleSprinter++;
5038 Log() << Verbose(1) << "Current triangle to test for removal: " << *triangle << endl;
5039 if (triangle->NormalVector.ScalarProduct(&NormalVector) < 0) { // if from other side, then delete and remove from list
5040 Log() << Verbose(1) << " Removing ... " << endl;
5041 TriangleNrs.push(triangle->Nr);
5042 T->erase(TriangleWalker);
5043 RemoveTesselationTriangle(triangle);
5044 } else
5045 Log() << Verbose(1) << " Keeping ... " << endl;
5046 }
5047 /// 4c. Copy all "front" triangles but with inverse NormalVector
5048 TriangleWalker = T->begin();
5049 while (TriangleWalker != T->end()) { // go through all front triangles
5050 Log() << Verbose(1) << " Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector << endl;
5051 for (int i = 0; i < 3; i++)
5052 AddTesselationPoint((*TriangleWalker)->endpoints[i]->node, i);
5053 AddTesselationLine(NULL, TPS[0], TPS[1], 0);
5054 AddTesselationLine(NULL, TPS[0], TPS[2], 1);
5055 AddTesselationLine(NULL, TPS[1], TPS[2], 2);
5056 if (TriangleNrs.empty())
5057 DoeLog(0) && (eLog()<< Verbose(0) << "No more free triangle numbers!" << endl);
5058 BTS = new BoundaryTriangleSet(BLS, TriangleNrs.top()); // copy triangle ...
5059 AddTesselationTriangle(); // ... and add
5060 TriangleNrs.pop();
5061 BTS->NormalVector.CopyVector(&(*TriangleWalker)->NormalVector);
5062 BTS->NormalVector.Scale(-1.);
5063 TriangleWalker++;
5064 }
5065 if (!TriangleNrs.empty()) {
5066 DoeLog(0) && (eLog()<< Verbose(0) << "There have been less triangles created than removed!" << endl);
5067 }
5068 delete(T); // remove the triangleset
5069 }
5070
5071 IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
5072 Log() << Verbose(0) << "Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:" << endl;
5073 IndexToIndex::iterator it;
5074 for (it = SimplyDegeneratedTriangles->begin(); it != SimplyDegeneratedTriangles->end(); it++)
5075 Log() << Verbose(0) << (*it).first << " => " << (*it).second << endl;
5076 delete(SimplyDegeneratedTriangles);
5077
5078 /// 5. exit
5079 UniquePolygonSet::iterator PolygonRunner;
5080 while (!ListofDegeneratedPolygons.empty()) {
5081 PolygonRunner = ListofDegeneratedPolygons.begin();
5082 delete(*PolygonRunner);
5083 ListofDegeneratedPolygons.erase(PolygonRunner);
5084 }
5085
5086 return counter;
5087};
Note: See TracBrowser for help on using the repository browser.