source: src/tesselation.cpp@ 62bb91

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

Fixes for concave hull creation

  • Property mode set to 100644
File size: 100.7 KB
Line 
1/*
2 * tesselation.cpp
3 *
4 * Created on: Aug 3, 2009
5 * Author: heber
6 */
7
8#include "tesselation.hpp"
9
10// ======================================== Points on Boundary =================================
11
12BoundaryPointSet::BoundaryPointSet()
13{
14 LinesCount = 0;
15 Nr = -1;
16}
17;
18
19BoundaryPointSet::BoundaryPointSet(TesselPoint *Walker)
20{
21 node = Walker;
22 LinesCount = 0;
23 Nr = Walker->nr;
24}
25;
26
27BoundaryPointSet::~BoundaryPointSet()
28{
29 cout << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
30 if (!lines.empty())
31 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some lines." << endl;
32 node = NULL;
33}
34;
35
36void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
37{
38 cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
39 << endl;
40 if (line->endpoints[0] == this)
41 {
42 lines.insert(LinePair(line->endpoints[1]->Nr, line));
43 }
44 else
45 {
46 lines.insert(LinePair(line->endpoints[0]->Nr, line));
47 }
48 LinesCount++;
49}
50;
51
52ostream &
53operator <<(ostream &ost, BoundaryPointSet &a)
54{
55 ost << "[" << a.Nr << "|" << a.node->Name << "]";
56 return ost;
57}
58;
59
60// ======================================== Lines on Boundary =================================
61
62BoundaryLineSet::BoundaryLineSet()
63{
64 for (int i = 0; i < 2; i++)
65 endpoints[i] = NULL;
66 TrianglesCount = 0;
67 Nr = -1;
68}
69;
70
71BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], int number)
72{
73 // set number
74 Nr = number;
75 // set endpoints in ascending order
76 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
77 // add this line to the hash maps of both endpoints
78 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
79 Point[1]->AddLine(this); //
80 // clear triangles list
81 TrianglesCount = 0;
82 cout << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
83}
84;
85
86BoundaryLineSet::~BoundaryLineSet()
87{
88 int Numbers[2];
89 Numbers[0] = endpoints[1]->Nr;
90 Numbers[1] = endpoints[0]->Nr;
91 for (int i = 0; i < 2; i++) {
92 cout << Verbose(5) << "Erasing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
93 // 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
94 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
95 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
96 if ((*Runner).second == this) {
97 endpoints[i]->lines.erase(Runner);
98 break;
99 }
100 if (endpoints[i]->lines.empty()) {
101 cout << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
102 if (endpoints[i] != NULL) {
103 delete(endpoints[i]);
104 endpoints[i] = NULL;
105 } else
106 cerr << "ERROR: Endpoint " << i << " has already been free'd." << endl;
107 } else
108 cout << Verbose(5) << *endpoints[i] << " has still lines it's attached to." << endl;
109 }
110 if (!triangles.empty())
111 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some triangles." << endl;
112}
113;
114
115void
116BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
117{
118 cout << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "."
119 << endl;
120 triangles.insert(TrianglePair(triangle->Nr, triangle));
121 TrianglesCount++;
122}
123;
124
125/** Checks whether we have a common endpoint with given \a *line.
126 * \param *line other line to test
127 * \return true - common endpoint present, false - not connected
128 */
129bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
130{
131 if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
132 return true;
133 else
134 return false;
135};
136
137/** Checks whether the adjacent triangles of a baseline are convex or not.
138 * We sum the two angles of each normal vector with a ficticious normnal vector from this baselinbe pointing outwards.
139 * If greater/equal M_PI than we are convex.
140 * \param *out output stream for debugging
141 * \return true - triangles are convex, false - concave or less than two triangles connected
142 */
143bool BoundaryLineSet::CheckConvexityCriterion(ofstream *out)
144{
145 Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2];
146 // get the two triangles
147 if (TrianglesCount != 2) {
148 *out << Verbose(1) << "ERROR: Baseline " << this << " is connect to less than two triangles, Tesselation incomplete!" << endl;
149 return false;
150 }
151 // have a normal vector on the base line pointing outwards
152 *out << Verbose(3) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
153 BaseLineCenter.CopyVector(endpoints[0]->node->node);
154 BaseLineCenter.AddVector(endpoints[1]->node->node);
155 BaseLineCenter.Scale(1./2.);
156 BaseLine.CopyVector(endpoints[0]->node->node);
157 BaseLine.SubtractVector(endpoints[1]->node->node);
158 *out << Verbose(3) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
159
160 BaseLineNormal.Zero();
161 int i=0;
162 class BoundaryPointSet *node = NULL;
163 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
164 *out << Verbose(3) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
165 BaseLineNormal.SubtractVector(&runner->second->NormalVector); // we subtract as BaseLineNormal has to point inward in direction of [pi,2pi]
166 node = runner->second->GetThirdEndpoint(this);
167 if (node != NULL) {
168 *out << Verbose(3) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
169 helper[i].CopyVector(node->node->node);
170 helper[i].SubtractVector(&BaseLineCenter);
171 helper[i].MakeNormalVector(&BaseLine); // we want to compare the triangle's heights' angles!
172 *out << Verbose(4) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
173 i++;
174 } else {
175 *out << Verbose(2) << "WARNING: I cannot find third node in triangle, something's wrong." << endl;
176 return true;
177 }
178 }
179 *out << Verbose(3) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
180 double angle = helper[0].Angle(&helper[1]);
181 if (BaseLineNormal.ScalarProduct(&helper[1]) > 0) {
182 angle = 2.*M_PI - angle;
183 }
184 *out << Verbose(3) << "The angle is " << angle << "." << endl;
185 if ((angle - M_PI) > -MYEPSILON)
186 return true;
187 else
188 return false;
189}
190
191/** Checks whether point is any of the two endpoints this line contains.
192 * \param *point point to test
193 * \return true - point is of the line, false - is not
194 */
195bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
196{
197 for(int i=0;i<2;i++)
198 if (point == endpoints[i])
199 return true;
200 return false;
201};
202
203/** Returns other endpoint of the line.
204 * \param *point other endpoint
205 * \return NULL - if endpoint not contained in BoundaryLineSet, or pointer to BoundaryPointSet otherwise
206 */
207inline class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(class BoundaryPointSet *point)
208{
209 if (endpoints[0] == point)
210 return endpoints[1];
211 else if (endpoints[1] == point)
212 return endpoints[0];
213 else
214 return NULL;
215};
216
217
218ostream &
219operator <<(ostream &ost, BoundaryLineSet &a)
220{
221 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << "," << a.endpoints[1]->node->Name << "]";
222 return ost;
223}
224;
225
226// ======================================== Triangles on Boundary =================================
227
228
229BoundaryTriangleSet::BoundaryTriangleSet()
230{
231 for (int i = 0; i < 3; i++)
232 {
233 endpoints[i] = NULL;
234 lines[i] = NULL;
235 }
236 Nr = -1;
237}
238;
239
240BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
241{
242 // set number
243 Nr = number;
244 // set lines
245 cout << Verbose(5) << "New triangle " << Nr << ":" << endl;
246 for (int i = 0; i < 3; i++)
247 {
248 lines[i] = line[i];
249 lines[i]->AddTriangle(this);
250 }
251 // get ascending order of endpoints
252 map<int, class BoundaryPointSet *> OrderMap;
253 for (int i = 0; i < 3; i++)
254 // for all three lines
255 for (int j = 0; j < 2; j++)
256 { // for both endpoints
257 OrderMap.insert(pair<int, class BoundaryPointSet *> (
258 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
259 // and we don't care whether insertion fails
260 }
261 // set endpoints
262 int Counter = 0;
263 cout << Verbose(6) << " with end points ";
264 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
265 != OrderMap.end(); runner++)
266 {
267 endpoints[Counter] = runner->second;
268 cout << " " << *endpoints[Counter];
269 Counter++;
270 }
271 if (Counter < 3)
272 {
273 cerr << "ERROR! We have a triangle with only two distinct endpoints!"
274 << endl;
275 //exit(1);
276 }
277 cout << "." << endl;
278}
279;
280
281BoundaryTriangleSet::~BoundaryTriangleSet()
282{
283 for (int i = 0; i < 3; i++) {
284 cout << Verbose(5) << "Erasing triangle Nr." << Nr << endl;
285 lines[i]->triangles.erase(Nr);
286 if (lines[i]->triangles.empty()) {
287 if (lines[i] != NULL) {
288 cout << Verbose(5) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
289 delete (lines[i]);
290 lines[i] = NULL;
291 } else
292 cerr << "ERROR: This line " << i << " has already been free'd." << endl;
293 } else
294 cout << Verbose(5) << *lines[i] << " is still attached to another triangle." << endl;
295 }
296}
297;
298
299/** Calculates the normal vector for this triangle.
300 * Is made unique by comparison with \a OtherVector to point in the other direction.
301 * \param &OtherVector direction vector to make normal vector unique.
302 */
303void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
304{
305 // get normal vector
306 NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
307
308 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
309 if (NormalVector.Projection(&OtherVector) > 0)
310 NormalVector.Scale(-1.);
311};
312
313/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
314 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
315 * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
316 * The latter is done as follows: if it's really outside, then for any endpoint of the triangle and it's opposite
317 * base line, the intersection between the line from endpoint to intersection and the base line will have a Vector::NormSquared()
318 * smaller than the first line.
319 * \param *out output stream for debugging
320 * \param *MolCenter offset vector of line
321 * \param *x second endpoint of line, minus \a *MolCenter is directional vector of line
322 * \param *Intersection intersection on plane on return
323 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
324 */
325bool BoundaryTriangleSet::GetIntersectionInsideTriangle(ofstream *out, Vector *MolCenter, Vector *x, Vector *Intersection)
326{
327 Vector CrossPoint;
328 Vector helper;
329 int i=0;
330
331 if (Intersection->GetIntersectionWithPlane(out, &NormalVector, endpoints[0]->node->node, MolCenter, x)) {
332 *out << Verbose(1) << "Alas! [Bronstein] failed - at least numerically - the intersection is not on the plane!" << endl;
333 return false;
334 }
335
336 // Calculate cross point between one baseline and the line from the third endpoint to intersection
337 do {
338 CrossPoint.GetIntersectionOfTwoLinesOnPlane(out, endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection);
339 helper.CopyVector(endpoints[(i+1)%3]->node->node);
340 helper.SubtractVector(endpoints[i%3]->node->node);
341 i++;
342 if (i>3)
343 break;
344 } while (CrossPoint.NormSquared() < MYEPSILON);
345 if (i>3) {
346 *out << Verbose(1) << "ERROR: Could not find any cross points, something's utterly wrong here!" << endl;
347 exit(255);
348 }
349 CrossPoint.SubtractVector(endpoints[i%3]->node->node);
350
351 // check whether intersection is inside or not by comparing length of intersection and length of cross point
352 if ((CrossPoint.NormSquared() - helper.NormSquared()) > -MYEPSILON) { // inside
353 return true;
354 } else { // outside!
355 Intersection->Zero();
356 return false;
357 }
358};
359
360/** Checks whether lines is any of the three boundary lines this triangle contains.
361 * \param *line line to test
362 * \return true - line is of the triangle, false - is not
363 */
364bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
365{
366 for(int i=0;i<3;i++)
367 if (line == lines[i])
368 return true;
369 return false;
370};
371
372/** Checks whether point is any of the three endpoints this triangle contains.
373 * \param *point point to test
374 * \return true - point is of the triangle, false - is not
375 */
376bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
377{
378 for(int i=0;i<3;i++)
379 if (point == endpoints[i])
380 return true;
381 return false;
382};
383
384/** Checks whether three given \a *Points coincide with triangle's endpoints.
385 * \param *Points[3] pointer to BoundaryPointSet
386 * \return true - is the very triangle, false - is not
387 */
388bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
389{
390 return (((endpoints[0] == Points[0])
391 || (endpoints[0] == Points[1])
392 || (endpoints[0] == Points[2])
393 ) && (
394 (endpoints[1] == Points[0])
395 || (endpoints[1] == Points[1])
396 || (endpoints[1] == Points[2])
397 ) && (
398 (endpoints[2] == Points[0])
399 || (endpoints[2] == Points[1])
400 || (endpoints[2] == Points[2])
401
402 ));
403};
404
405/** Returns the endpoint which is not contained in the given \a *line.
406 * \param *line baseline defining two endpoints
407 * \return pointer third endpoint or NULL if line does not belong to triangle.
408 */
409class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(class BoundaryLineSet *line)
410{
411 // sanity check
412 if (!ContainsBoundaryLine(line))
413 return NULL;
414 for(int i=0;i<3;i++)
415 if (!line->ContainsBoundaryPoint(endpoints[i]))
416 return endpoints[i];
417 // actually, that' impossible :)
418 return NULL;
419};
420
421/** Calculates the center point of the triangle.
422 * Is third of the sum of all endpoints.
423 * \param *center central point on return.
424 */
425void BoundaryTriangleSet::GetCenter(Vector *center)
426{
427 center->Zero();
428 for(int i=0;i<3;i++)
429 center->AddVector(endpoints[i]->node->node);
430 center->Scale(1./3.);
431}
432
433ostream &
434operator <<(ostream &ost, BoundaryTriangleSet &a)
435{
436 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << ","
437 << a.endpoints[1]->node->Name << "," << a.endpoints[2]->node->Name << "]";
438 return ost;
439}
440;
441
442// =========================================================== class TESSELPOINT ===========================================
443
444/** Constructor of class TesselPoint.
445 */
446TesselPoint::TesselPoint()
447{
448 node = NULL;
449 nr = -1;
450 Name = NULL;
451};
452
453/** Destructor for class TesselPoint.
454 */
455TesselPoint::~TesselPoint()
456{
457 Free((void **)&Name, "TesselPoint::~TesselPoint: *Name");
458};
459
460/** Prints LCNode to screen.
461 */
462ostream & operator << (ostream &ost, const TesselPoint &a)
463{
464 ost << "[" << (a.Name) << "|" << &a << "]";
465 return ost;
466};
467
468
469// =========================================================== class POINTCLOUD ============================================
470
471/** Constructor of class PointCloud.
472 */
473PointCloud::PointCloud()
474{
475
476};
477
478/** Destructor for class PointCloud.
479 */
480PointCloud::~PointCloud()
481{
482
483};
484
485// ============================ CandidateForTesselation =============================
486
487/** Constructor of class CandidateForTesselation.
488 */
489CandidateForTesselation::CandidateForTesselation(TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) {
490 point = candidate;
491 BaseLine = line;
492 OptCenter.CopyVector(&OptCandidateCenter);
493 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
494};
495
496/** Destructor for class CandidateForTesselation.
497 */
498CandidateForTesselation::~CandidateForTesselation() {
499 point = NULL;
500 BaseLine = NULL;
501};
502
503// =========================================================== class TESSELATION ===========================================
504
505/** Constructor of class Tesselation.
506 */
507Tesselation::Tesselation()
508{
509 PointsOnBoundaryCount = 0;
510 LinesOnBoundaryCount = 0;
511 TrianglesOnBoundaryCount = 0;
512}
513;
514
515/** Destructor of class Tesselation.
516 * We have to free all points, lines and triangles.
517 */
518Tesselation::~Tesselation()
519{
520 cout << Verbose(1) << "Free'ing TesselStruct ... " << endl;
521 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
522 if (runner->second != NULL) {
523 delete (runner->second);
524 runner->second = NULL;
525 } else
526 cerr << "ERROR: The triangle " << runner->first << " has already been free'd." << endl;
527 }
528}
529;
530
531/** Gueses first starting triangle of the convex envelope.
532 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
533 * \param *out output stream for debugging
534 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
535 */
536void
537Tesselation::GuessStartingTriangle(ofstream *out)
538{
539 // 4b. create a starting triangle
540 // 4b1. create all distances
541 DistanceMultiMap DistanceMMap;
542 double distance, tmp;
543 Vector PlaneVector, TrialVector;
544 PointMap::iterator A, B, C; // three nodes of the first triangle
545 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
546
547 // with A chosen, take each pair B,C and sort
548 if (A != PointsOnBoundary.end())
549 {
550 B = A;
551 B++;
552 for (; B != PointsOnBoundary.end(); B++)
553 {
554 C = B;
555 C++;
556 for (; C != PointsOnBoundary.end(); C++)
557 {
558 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
559 distance = tmp * tmp;
560 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
561 distance += tmp * tmp;
562 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
563 distance += tmp * tmp;
564 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
565 }
566 }
567 }
568 // // listing distances
569 // *out << Verbose(1) << "Listing DistanceMMap:";
570 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
571 // *out << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
572 // }
573 // *out << endl;
574 // 4b2. pick three baselines forming a triangle
575 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
576 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
577 for (; baseline != DistanceMMap.end(); baseline++)
578 {
579 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
580 // 2. next, we have to check whether all points reside on only one side of the triangle
581 // 3. construct plane vector
582 PlaneVector.MakeNormalVector(A->second->node->node,
583 baseline->second.first->second->node->node,
584 baseline->second.second->second->node->node);
585 *out << Verbose(2) << "Plane vector of candidate triangle is ";
586 PlaneVector.Output(out);
587 *out << endl;
588 // 4. loop over all points
589 double sign = 0.;
590 PointMap::iterator checker = PointsOnBoundary.begin();
591 for (; checker != PointsOnBoundary.end(); checker++)
592 {
593 // (neglecting A,B,C)
594 if ((checker == A) || (checker == baseline->second.first) || (checker
595 == baseline->second.second))
596 continue;
597 // 4a. project onto plane vector
598 TrialVector.CopyVector(checker->second->node->node);
599 TrialVector.SubtractVector(A->second->node->node);
600 distance = TrialVector.Projection(&PlaneVector);
601 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
602 continue;
603 *out << Verbose(3) << "Projection of " << checker->second->node->Name
604 << " yields distance of " << distance << "." << endl;
605 tmp = distance / fabs(distance);
606 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
607 if ((sign != 0) && (tmp != sign))
608 {
609 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
610 *out << Verbose(2) << "Current candidates: "
611 << A->second->node->Name << ","
612 << baseline->second.first->second->node->Name << ","
613 << baseline->second.second->second->node->Name << " leaves "
614 << checker->second->node->Name << " outside the convex hull."
615 << endl;
616 break;
617 }
618 else
619 { // note the sign for later
620 *out << Verbose(2) << "Current candidates: "
621 << A->second->node->Name << ","
622 << baseline->second.first->second->node->Name << ","
623 << baseline->second.second->second->node->Name << " leave "
624 << checker->second->node->Name << " inside the convex hull."
625 << endl;
626 sign = tmp;
627 }
628 // 4d. Check whether the point is inside the triangle (check distance to each node
629 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
630 int innerpoint = 0;
631 if ((tmp < A->second->node->node->DistanceSquared(
632 baseline->second.first->second->node->node)) && (tmp
633 < A->second->node->node->DistanceSquared(
634 baseline->second.second->second->node->node)))
635 innerpoint++;
636 tmp = checker->second->node->node->DistanceSquared(
637 baseline->second.first->second->node->node);
638 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
639 A->second->node->node)) && (tmp
640 < baseline->second.first->second->node->node->DistanceSquared(
641 baseline->second.second->second->node->node)))
642 innerpoint++;
643 tmp = checker->second->node->node->DistanceSquared(
644 baseline->second.second->second->node->node);
645 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
646 baseline->second.first->second->node->node)) && (tmp
647 < baseline->second.second->second->node->node->DistanceSquared(
648 A->second->node->node)))
649 innerpoint++;
650 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
651 if (innerpoint == 3)
652 break;
653 }
654 // 5. come this far, all on same side? Then break 1. loop and construct triangle
655 if (checker == PointsOnBoundary.end())
656 {
657 *out << "Looks like we have a candidate!" << endl;
658 break;
659 }
660 }
661 if (baseline != DistanceMMap.end())
662 {
663 BPS[0] = baseline->second.first->second;
664 BPS[1] = baseline->second.second->second;
665 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
666 BPS[0] = A->second;
667 BPS[1] = baseline->second.second->second;
668 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
669 BPS[0] = baseline->second.first->second;
670 BPS[1] = A->second;
671 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
672
673 // 4b3. insert created triangle
674 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
675 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
676 TrianglesOnBoundaryCount++;
677 for (int i = 0; i < NDIM; i++)
678 {
679 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
680 LinesOnBoundaryCount++;
681 }
682
683 *out << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
684 }
685 else
686 {
687 *out << Verbose(1) << "No starting triangle found." << endl;
688 exit(255);
689 }
690}
691;
692
693/** Tesselates the convex envelope of a cluster from a single starting triangle.
694 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
695 * 2 triangles. Hence, we go through all current lines:
696 * -# if the lines contains to only one triangle
697 * -# We search all points in the boundary
698 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
699 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
700 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
701 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
702 * \param *out output stream for debugging
703 * \param *configuration for IsAngstroem
704 * \param *cloud cluster of points
705 */
706void Tesselation::TesselateOnBoundary(ofstream *out, PointCloud *cloud)
707{
708 bool flag;
709 PointMap::iterator winner;
710 class BoundaryPointSet *peak = NULL;
711 double SmallestAngle, TempAngle;
712 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
713 LineMap::iterator LineChecker[2];
714
715 Center = cloud->GetCenter(out);
716 // create a first tesselation with the given BoundaryPoints
717 do {
718 flag = false;
719 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
720 if (baseline->second->TrianglesCount == 1) {
721 // 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)
722 SmallestAngle = M_PI;
723
724 // get peak point with respect to this base line's only triangle
725 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
726 *out << Verbose(2) << "Current baseline is between " << *(baseline->second) << "." << endl;
727 for (int i = 0; i < 3; i++)
728 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
729 peak = BTS->endpoints[i];
730 *out << Verbose(3) << " and has peak " << *peak << "." << endl;
731
732 // prepare some auxiliary vectors
733 Vector BaseLineCenter, BaseLine;
734 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
735 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
736 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
737 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
738 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
739
740 // offset to center of triangle
741 CenterVector.Zero();
742 for (int i = 0; i < 3; i++)
743 CenterVector.AddVector(BTS->endpoints[i]->node->node);
744 CenterVector.Scale(1. / 3.);
745 *out << Verbose(4) << "CenterVector of base triangle is " << CenterVector << endl;
746
747 // normal vector of triangle
748 NormalVector.CopyVector(Center);
749 NormalVector.SubtractVector(&CenterVector);
750 BTS->GetNormalVector(NormalVector);
751 NormalVector.CopyVector(&BTS->NormalVector);
752 *out << Verbose(4) << "NormalVector of base triangle is " << NormalVector << endl;
753
754 // vector in propagation direction (out of triangle)
755 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
756 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
757 TempVector.CopyVector(&CenterVector);
758 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
759 //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
760 if (PropagationVector.Projection(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
761 PropagationVector.Scale(-1.);
762 *out << Verbose(4) << "PropagationVector of base triangle is " << PropagationVector << endl;
763 winner = PointsOnBoundary.end();
764
765 // loop over all points and calculate angle between normal vector of new and present triangle
766 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
767 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
768 *out << Verbose(3) << "Target point is " << *(target->second) << ":" << endl;
769
770 // first check direction, so that triangles don't intersect
771 VirtualNormalVector.CopyVector(target->second->node->node);
772 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
773 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
774 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
775 *out << Verbose(4) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
776 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
777 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
778 continue;
779 } else
780 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
781
782 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
783 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
784 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
785 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->TrianglesCount == 2))) {
786 *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->TrianglesCount << " triangles." << endl;
787 continue;
788 }
789 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->TrianglesCount == 2))) {
790 *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->TrianglesCount << " triangles." << endl;
791 continue;
792 }
793
794 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
795 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)))) {
796 *out << Verbose(4) << "Current target is peak!" << endl;
797 continue;
798 }
799
800 // check for linear dependence
801 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
802 TempVector.SubtractVector(target->second->node->node);
803 helper.CopyVector(baseline->second->endpoints[1]->node->node);
804 helper.SubtractVector(target->second->node->node);
805 helper.ProjectOntoPlane(&TempVector);
806 if (fabs(helper.NormSquared()) < MYEPSILON) {
807 *out << Verbose(4) << "Chosen set of vectors is linear dependent." << endl;
808 continue;
809 }
810
811 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
812 flag = true;
813 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
814 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
815 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
816 TempVector.AddVector(target->second->node->node);
817 TempVector.Scale(1./3.);
818 TempVector.SubtractVector(Center);
819 // make it always point outward
820 if (VirtualNormalVector.Projection(&TempVector) < 0)
821 VirtualNormalVector.Scale(-1.);
822 // calculate angle
823 TempAngle = NormalVector.Angle(&VirtualNormalVector);
824 *out << Verbose(4) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
825 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
826 SmallestAngle = TempAngle;
827 winner = target;
828 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
829 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
830 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
831 helper.CopyVector(target->second->node->node);
832 helper.SubtractVector(&BaseLineCenter);
833 helper.ProjectOntoPlane(&BaseLine);
834 // ...the one with the smaller angle is the better candidate
835 TempVector.CopyVector(target->second->node->node);
836 TempVector.SubtractVector(&BaseLineCenter);
837 TempVector.ProjectOntoPlane(&VirtualNormalVector);
838 TempAngle = TempVector.Angle(&helper);
839 TempVector.CopyVector(winner->second->node->node);
840 TempVector.SubtractVector(&BaseLineCenter);
841 TempVector.ProjectOntoPlane(&VirtualNormalVector);
842 if (TempAngle < TempVector.Angle(&helper)) {
843 TempAngle = NormalVector.Angle(&VirtualNormalVector);
844 SmallestAngle = TempAngle;
845 winner = target;
846 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
847 } else
848 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
849 } else
850 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
851 }
852 } // end of loop over all boundary points
853
854 // 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
855 if (winner != PointsOnBoundary.end()) {
856 *out << Verbose(2) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
857 // create the lins of not yet present
858 BLS[0] = baseline->second;
859 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
860 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
861 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
862 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
863 BPS[0] = baseline->second->endpoints[0];
864 BPS[1] = winner->second;
865 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
866 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
867 LinesOnBoundaryCount++;
868 } else
869 BLS[1] = LineChecker[0]->second;
870 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
871 BPS[0] = baseline->second->endpoints[1];
872 BPS[1] = winner->second;
873 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
874 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
875 LinesOnBoundaryCount++;
876 } else
877 BLS[2] = LineChecker[1]->second;
878 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
879 BTS->GetCenter(&helper);
880 helper.SubtractVector(Center);
881 helper.Scale(-1);
882 BTS->GetNormalVector(helper);
883 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
884 TrianglesOnBoundaryCount++;
885 } else {
886 *out << Verbose(1) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
887 }
888
889 // 5d. If the set of lines is not yet empty, go to 5. and continue
890 } else
891 *out << Verbose(2) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->TrianglesCount << "." << endl;
892 } while (flag);
893
894 // exit
895 delete(Center);
896};
897
898/** Inserts all points outside of the tesselated surface into it by adding new triangles.
899 * \param *out output stream for debugging
900 * \param *cloud cluster of points
901 * \param *LC LinkedCell structure to find nearest point quickly
902 * \return true - all straddling points insert, false - something went wrong
903 */
904bool Tesselation::InsertStraddlingPoints(ofstream *out, PointCloud *cloud, LinkedCell *LC)
905{
906 Vector Intersection;
907 TesselPoint *Walker = NULL;
908 Vector *Center = cloud->GetCenter(out);
909 list<BoundaryTriangleSet*> *triangles = NULL;
910
911 *out << Verbose(1) << "Begin of InsertStraddlingPoints" << endl;
912
913 cloud->GoToFirst();
914 while (!cloud->IsLast()) { // we only have to go once through all points, as boundary can become only bigger
915 Walker = cloud->GetPoint();
916 *out << Verbose(2) << "Current point is " << *Walker << "." << endl;
917 // get the next triangle
918 triangles = FindClosestTrianglesToPoint(out, Walker->node, LC);
919 if (triangles == NULL) {
920 *out << Verbose(1) << "No triangles found, probably a tesselation point itself." << endl;
921 cloud->GoToNext();
922 continue;
923 } else {
924 BTS = triangles->front();
925 }
926 *out << Verbose(2) << "Closest triangle is " << BTS << "." << endl;
927 // get the intersection point
928 if (BTS->GetIntersectionInsideTriangle(out, Center, Walker->node, &Intersection)) {
929 *out << Verbose(2) << "We have an intersection at " << Intersection << "." << endl;
930 // we have the intersection, check whether in- or outside of boundary
931 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
932 // inside, next!
933 *out << Verbose(4) << Walker << " is inside wrt triangle " << BTS << "." << endl;
934 } else {
935 // outside!
936 *out << Verbose(3) << Walker << " is outside wrt triangle " << BTS << "." << endl;
937 class BoundaryLineSet *OldLines[3], *NewLines[3];
938 class BoundaryPointSet *OldPoints[3], *NewPoint;
939 // store the three old lines and old points
940 for (int i=0;i<3;i++) {
941 OldLines[i] = BTS->lines[i];
942 OldPoints[i] = BTS->endpoints[i];
943 }
944 // add Walker to boundary points
945 AddPoint(Walker);
946 if (BPS[0] == NULL)
947 NewPoint = BPS[0];
948 else
949 continue;
950 // remove triangle
951 TrianglesOnBoundary.erase(BTS->Nr);
952 // create three new boundary lines
953 for (int i=0;i<3;i++) {
954 BPS[0] = NewPoint;
955 BPS[1] = OldPoints[i];
956 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
957 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
958 LinesOnBoundaryCount++;
959 }
960 // create three new triangle with new point
961 for (int i=0;i<3;i++) { // find all baselines
962 BLS[0] = OldLines[i];
963 int n = 1;
964 for (int j=0;j<3;j++) {
965 if (NewLines[j]->IsConnectedTo(BLS[0])) {
966 if (n>2) {
967 *out << Verbose(1) << "ERROR: " << BLS[0] << " connects to all of the new lines?!" << endl;
968 return false;
969 } else
970 BLS[n++] = NewLines[j];
971 }
972 }
973 // create the triangle
974 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
975 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
976 TrianglesOnBoundaryCount++;
977 }
978 }
979 } else { // something is wrong with FindClosestTriangleToPoint!
980 *out << Verbose(1) << "ERROR: The closest triangle did not produce an intersection!" << endl;
981 return false;
982 }
983 cloud->GoToNext();
984 }
985
986 // exit
987 delete(Center);
988 *out << Verbose(1) << "End of InsertStraddlingPoints" << endl;
989 return true;
990};
991
992/** Adds an point to the tesselation::PointsOnBoundary list.
993 * \param *Walker point to add
994 */
995void
996Tesselation::AddPoint(TesselPoint *Walker)
997{
998 PointTestPair InsertUnique;
999 BPS[0] = new class BoundaryPointSet(Walker);
1000 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[0]));
1001 if (InsertUnique.second) // if new point was not present before, increase counter
1002 PointsOnBoundaryCount++;
1003 else {
1004 delete(BPS[0]);
1005 BPS[0] = NULL;
1006 }
1007}
1008;
1009
1010/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1011 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1012 * @param Candidate point to add
1013 * @param n index for this point in Tesselation::TPS array
1014 */
1015void
1016Tesselation::AddTrianglePoint(TesselPoint* Candidate, int n)
1017{
1018 PointTestPair InsertUnique;
1019 TPS[n] = new class BoundaryPointSet(Candidate);
1020 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1021 if (InsertUnique.second) { // if new point was not present before, increase counter
1022 PointsOnBoundaryCount++;
1023 } else {
1024 delete TPS[n];
1025 cout << Verbose(3) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1026 TPS[n] = (InsertUnique.first)->second;
1027 }
1028}
1029;
1030
1031/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1032 * If successful it raises the line count and inserts the new line into the BLS,
1033 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1034 * @param *a first endpoint
1035 * @param *b second endpoint
1036 * @param n index of Tesselation::BLS giving the line with both endpoints
1037 */
1038void Tesselation::AddTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n) {
1039 bool insertNewLine = true;
1040
1041 if (a->lines.find(b->node->nr) != a->lines.end()) {
1042 LineMap::iterator FindLine;
1043 pair<LineMap::iterator,LineMap::iterator> FindPair;
1044 FindPair = a->lines.equal_range(b->node->nr);
1045
1046 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
1047 // If there is a line with less than two attached triangles, we don't need a new line.
1048 if (FindLine->second->TrianglesCount < 2) {
1049 insertNewLine = false;
1050 cout << Verbose(3) << "Using existing line " << *FindLine->second << endl;
1051
1052 BPS[0] = FindLine->second->endpoints[0];
1053 BPS[1] = FindLine->second->endpoints[1];
1054 BLS[n] = FindLine->second;
1055
1056 break;
1057 }
1058 }
1059 }
1060
1061 if (insertNewLine) {
1062 AlwaysAddTriangleLine(a, b, n);
1063 }
1064}
1065;
1066
1067/**
1068 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1069 * Raises the line count and inserts the new line into the BLS.
1070 *
1071 * @param *a first endpoint
1072 * @param *b second endpoint
1073 * @param n index of Tesselation::BLS giving the line with both endpoints
1074 */
1075void Tesselation::AlwaysAddTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n)
1076{
1077 cout << Verbose(3) << "Adding line between " << *(a->node) << " and " << *(b->node) << "." << endl;
1078 BPS[0] = a;
1079 BPS[1] = b;
1080 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1081 // add line to global map
1082 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1083 // increase counter
1084 LinesOnBoundaryCount++;
1085};
1086
1087/** Function tries to add Triangle just created to Triangle and remarks if already existent (Failure of algorithm).
1088 * Furthermore it adds the triangle to all of its lines, in order to recognize those which are saturated later.
1089 */
1090void
1091Tesselation::AddTriangle()
1092{
1093 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1094
1095 // add triangle to global map
1096 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1097 TrianglesOnBoundaryCount++;
1098
1099 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1100}
1101;
1102
1103
1104
1105/** Checks whether the triangle consisting of the three points is already present.
1106 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1107 * lines. If any of the three edges already has two triangles attached, false is
1108 * returned.
1109 * \param *out output stream for debugging
1110 * \param *Candidates endpoints of the triangle candidate
1111 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1112 * triangles exist which is the maximum for three points
1113 */
1114int Tesselation::CheckPresenceOfTriangle(ofstream *out, TesselPoint *Candidates[3]) {
1115 int adjacentTriangleCount = 0;
1116 class BoundaryPointSet *Points[3];
1117
1118 *out << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1119 // builds a triangle point set (Points) of the end points
1120 for (int i = 0; i < 3; i++) {
1121 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1122 if (FindPoint != PointsOnBoundary.end()) {
1123 Points[i] = FindPoint->second;
1124 } else {
1125 Points[i] = NULL;
1126 }
1127 }
1128
1129 // checks lines between the points in the Points for their adjacent triangles
1130 for (int i = 0; i < 3; i++) {
1131 if (Points[i] != NULL) {
1132 for (int j = i; j < 3; j++) {
1133 if (Points[j] != NULL) {
1134 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1135 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1136 TriangleMap *triangles = &FindLine->second->triangles;
1137 *out << Verbose(3) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1138 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1139 if (FindTriangle->second->IsPresentTupel(Points)) {
1140 adjacentTriangleCount++;
1141 }
1142 }
1143 *out << Verbose(3) << "end." << endl;
1144 }
1145 // Only one of the triangle lines must be considered for the triangle count.
1146 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1147 return adjacentTriangleCount;
1148 }
1149 }
1150 }
1151 }
1152
1153 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1154 *out << Verbose(2) << "End of CheckPresenceOfTriangle" << endl;
1155 return adjacentTriangleCount;
1156};
1157
1158
1159/** Finds the starting triangle for find_non_convex_border().
1160 * Looks at the outermost point per axis, then Find_second_point_for_Tesselation()
1161 * for the second and Find_next_suitable_point_via_Angle_of_Sphere() for the third
1162 * point are called.
1163 * \param *out output stream for debugging
1164 * \param RADIUS radius of virtual rolling sphere
1165 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1166 */
1167void Tesselation::Find_starting_triangle(ofstream *out, const double RADIUS, LinkedCell *LC)
1168{
1169 cout << Verbose(1) << "Begin of Find_starting_triangle\n";
1170 int i = 0;
1171 LinkedNodes *List = NULL;
1172 TesselPoint* FirstPoint = NULL;
1173 TesselPoint* SecondPoint = NULL;
1174 TesselPoint* MaxPoint[NDIM];
1175 double max_coordinate[NDIM];
1176 Vector Oben;
1177 Vector helper;
1178 Vector Chord;
1179 Vector SearchDirection;
1180
1181 Oben.Zero();
1182
1183 for (i = 0; i < 3; i++) {
1184 MaxPoint[i] = NULL;
1185 max_coordinate[i] = -1;
1186 }
1187
1188 // 1. searching topmost point with respect to each axis
1189 for (int i=0;i<NDIM;i++) { // each axis
1190 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1191 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1192 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1193 List = LC->GetCurrentCell();
1194 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1195 if (List != NULL) {
1196 for (LinkedNodes::iterator Runner = List->begin();Runner != List->end();Runner++) {
1197 if ((*Runner)->node->x[i] > max_coordinate[i]) {
1198 cout << Verbose(2) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1199 max_coordinate[i] = (*Runner)->node->x[i];
1200 MaxPoint[i] = (*Runner);
1201 }
1202 }
1203 } else {
1204 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1205 }
1206 }
1207 }
1208
1209 cout << Verbose(2) << "Found maximum coordinates: ";
1210 for (int i=0;i<NDIM;i++)
1211 cout << i << ": " << *MaxPoint[i] << "\t";
1212 cout << endl;
1213
1214 BTS = NULL;
1215 CandidateList *Opt_Candidates = new CandidateList();
1216 for (int k=0;k<NDIM;k++) {
1217 Oben.x[k] = 1.;
1218 FirstPoint = MaxPoint[k];
1219 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1220
1221 double ShortestAngle;
1222 TesselPoint* Opt_Candidate = NULL;
1223 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.
1224
1225 Find_second_point_for_Tesselation(FirstPoint, NULL, Oben, Opt_Candidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1226 SecondPoint = Opt_Candidate;
1227 if (SecondPoint == NULL) // have we found a second point?
1228 continue;
1229 else
1230 cout << Verbose(1) << "Found second point is at " << *SecondPoint->node << ".\n";
1231
1232 helper.CopyVector(FirstPoint->node);
1233 helper.SubtractVector(SecondPoint->node);
1234 helper.Normalize();
1235 Oben.ProjectOntoPlane(&helper);
1236 Oben.Normalize();
1237 helper.VectorProduct(&Oben);
1238 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1239
1240 Chord.CopyVector(FirstPoint->node); // bring into calling function
1241 Chord.SubtractVector(SecondPoint->node);
1242 double radius = Chord.ScalarProduct(&Chord);
1243 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1244 helper.CopyVector(&Oben);
1245 helper.Scale(CircleRadius);
1246 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
1247
1248 // look in one direction of baseline for initial candidate
1249 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
1250
1251 // adding point 1 and point 2 and the line between them
1252 AddTrianglePoint(FirstPoint, 0);
1253 AddTrianglePoint(SecondPoint, 1);
1254 AddTriangleLine(TPS[0], TPS[1], 0);
1255
1256 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
1257 Find_third_point_for_Tesselation(
1258 Oben, SearchDirection, helper, BLS[0], NULL, *&Opt_Candidates, &ShortestAngle, RADIUS, LC
1259 );
1260 cout << Verbose(1) << "List of third Points is ";
1261 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1262 cout << " " << *(*it)->point;
1263 }
1264 cout << endl;
1265
1266 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1267 // add third triangle point
1268 AddTrianglePoint((*it)->point, 2);
1269 // add the second and third line
1270 AddTriangleLine(TPS[1], TPS[2], 1);
1271 AddTriangleLine(TPS[0], TPS[2], 2);
1272 // ... and triangles to the Maps of the Tesselation class
1273 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1274 AddTriangle();
1275 // ... and calculate its normal vector (with correct orientation)
1276 (*it)->OptCenter.Scale(-1.);
1277 cout << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
1278 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
1279 cout << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
1280 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
1281
1282 // if we do not reach the end with the next step of iteration, we need to setup a new first line
1283 if (it != Opt_Candidates->end()--) {
1284 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
1285 SecondPoint = (*it)->point;
1286 // adding point 1 and point 2 and the line between them
1287 AddTrianglePoint(FirstPoint, 0);
1288 AddTrianglePoint(SecondPoint, 1);
1289 AddTriangleLine(TPS[0], TPS[1], 0);
1290 }
1291 cout << Verbose(2) << "Projection is " << BTS->NormalVector.Projection(&Oben) << "." << endl;
1292 }
1293 if (BTS != NULL) // we have created one starting triangle
1294 break;
1295 else {
1296 // remove all candidates from the list and then the list itself
1297 class CandidateForTesselation *remover = NULL;
1298 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1299 remover = *it;
1300 delete(remover);
1301 }
1302 Opt_Candidates->clear();
1303 }
1304 }
1305
1306 // remove all candidates from the list and then the list itself
1307 class CandidateForTesselation *remover = NULL;
1308 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1309 remover = *it;
1310 delete(remover);
1311 }
1312 delete(Opt_Candidates);
1313 cout << Verbose(1) << "End of Find_starting_triangle\n";
1314};
1315
1316
1317/** This function finds a triangle to a line, adjacent to an existing one.
1318 * @param out output stream for debugging
1319 * @param Line current baseline to search from
1320 * @param T current triangle which \a Line is edge of
1321 * @param RADIUS radius of the rolling ball
1322 * @param N number of found triangles
1323 * @param *LC LinkedCell structure with neighbouring points
1324 */
1325bool Tesselation::Find_next_suitable_triangle(ofstream *out, BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, int N, LinkedCell *LC)
1326{
1327 cout << Verbose(0) << "Begin of Find_next_suitable_triangle\n";
1328 bool result = true;
1329 CandidateList *Opt_Candidates = new CandidateList();
1330
1331 Vector CircleCenter;
1332 Vector CirclePlaneNormal;
1333 Vector OldSphereCenter;
1334 Vector SearchDirection;
1335 Vector helper;
1336 TesselPoint *ThirdNode = NULL;
1337 LineMap::iterator testline;
1338 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1339 double radius, CircleRadius;
1340
1341 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
1342 for (int i=0;i<3;i++)
1343 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
1344 ThirdNode = T.endpoints[i]->node;
1345
1346 // construct center of circle
1347 CircleCenter.CopyVector(Line.endpoints[0]->node->node);
1348 CircleCenter.AddVector(Line.endpoints[1]->node->node);
1349 CircleCenter.Scale(0.5);
1350
1351 // construct normal vector of circle
1352 CirclePlaneNormal.CopyVector(Line.endpoints[0]->node->node);
1353 CirclePlaneNormal.SubtractVector(Line.endpoints[1]->node->node);
1354
1355 // calculate squared radius of circle
1356 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1357 if (radius/4. < RADIUS*RADIUS) {
1358 CircleRadius = RADIUS*RADIUS - radius/4.;
1359 CirclePlaneNormal.Normalize();
1360 cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1361
1362 // construct old center
1363 GetCenterofCircumcircle(&OldSphereCenter, T.endpoints[0]->node->node, T.endpoints[1]->node->node, T.endpoints[2]->node->node);
1364 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
1365 radius = Line.endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
1366 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1367 OldSphereCenter.AddVector(&helper);
1368 OldSphereCenter.SubtractVector(&CircleCenter);
1369 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
1370
1371 // construct SearchDirection
1372 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
1373 helper.CopyVector(Line.endpoints[0]->node->node);
1374 helper.SubtractVector(ThirdNode->node);
1375 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
1376 SearchDirection.Scale(-1.);
1377 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
1378 SearchDirection.Normalize();
1379 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1380 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
1381 // rotated the wrong way!
1382 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
1383 }
1384
1385 // add third point
1386 Find_third_point_for_Tesselation(
1387 T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, Opt_Candidates,
1388 &ShortestAngle, RADIUS, LC
1389 );
1390
1391 } else {
1392 cout << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
1393 }
1394
1395 if (Opt_Candidates->begin() == Opt_Candidates->end()) {
1396 cerr << "WARNING: Could not find a suitable candidate." << endl;
1397 return false;
1398 }
1399 cout << Verbose(1) << "Third Points are ";
1400 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1401 cout << " " << *(*it)->point;
1402 }
1403 cout << endl;
1404
1405 BoundaryLineSet *BaseRay = &Line;
1406 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1407 cout << Verbose(1) << " Third point candidate is " << *(*it)->point
1408 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
1409 cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
1410
1411 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
1412 TesselPoint *PointCandidates[3];
1413 PointCandidates[0] = (*it)->point;
1414 PointCandidates[1] = BaseRay->endpoints[0]->node;
1415 PointCandidates[2] = BaseRay->endpoints[1]->node;
1416 int existentTrianglesCount = CheckPresenceOfTriangle(out, PointCandidates);
1417
1418 BTS = NULL;
1419 // If there is no triangle, add it regularly.
1420 if (existentTrianglesCount == 0) {
1421 AddTrianglePoint((*it)->point, 0);
1422 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
1423 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
1424
1425 AddTriangleLine(TPS[0], TPS[1], 0);
1426 AddTriangleLine(TPS[0], TPS[2], 1);
1427 AddTriangleLine(TPS[1], TPS[2], 2);
1428
1429 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1430 AddTriangle();
1431 (*it)->OptCenter.Scale(-1.);
1432 BTS->GetNormalVector((*it)->OptCenter);
1433 (*it)->OptCenter.Scale(-1.);
1434
1435 cout << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1436 << " for this triangle ... " << endl;
1437 //cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
1438 } else if (existentTrianglesCount == 1) { // If there is a planar region within the structure, we need this triangle a second time.
1439 AddTrianglePoint((*it)->point, 0);
1440 AddTrianglePoint(BaseRay->endpoints[0]->node, 1);
1441 AddTrianglePoint(BaseRay->endpoints[1]->node, 2);
1442
1443 // 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)
1444 // i.e. at least one of the three lines must be present with TriangleCount <= 1
1445 if (CheckLineCriteriaforDegeneratedTriangle(TPS)) {
1446 AddTriangleLine(TPS[0], TPS[1], 0);
1447 AddTriangleLine(TPS[0], TPS[2], 1);
1448 AddTriangleLine(TPS[1], TPS[2], 2);
1449
1450 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1451 AddTriangle();
1452
1453 (*it)->OtherOptCenter.Scale(-1.);
1454 BTS->GetNormalVector((*it)->OtherOptCenter);
1455 (*it)->OtherOptCenter.Scale(-1.);
1456
1457 cout << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1458 << " for this triangle ... " << endl;
1459 cout << Verbose(1) << "We have "<< BaseRay->TrianglesCount << " for line " << BaseRay << "." << endl;
1460 } else {
1461 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1462 cout << *(*it)->point << ", ";
1463 cout << *BaseRay->endpoints[0]->node << " and ";
1464 cout << *BaseRay->endpoints[1]->node << " ";
1465 cout << "exists and is not added, as it does not seem helpful!" << endl;
1466 result = false;
1467 }
1468 } else {
1469 cout << Verbose(1) << "This triangle consisting of ";
1470 cout << *(*it)->point << ", ";
1471 cout << *BaseRay->endpoints[0]->node << " and ";
1472 cout << *BaseRay->endpoints[1]->node << " ";
1473 cout << "is invalid!" << endl;
1474 result = false;
1475 }
1476
1477 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
1478 BaseRay = BLS[0];
1479 }
1480
1481 // remove all candidates from the list and then the list itself
1482 class CandidateForTesselation *remover = NULL;
1483 for (CandidateList::iterator it = Opt_Candidates->begin(); it != Opt_Candidates->end(); ++it) {
1484 remover = *it;
1485 delete(remover);
1486 }
1487 delete(Opt_Candidates);
1488 cout << Verbose(0) << "End of Find_next_suitable_triangle\n";
1489 return result;
1490};
1491
1492
1493/** Goes over all baselines and checks whether adjacent triangles and convex to each other.
1494 * \param *out output stream for debugging
1495 * \return true - all baselines were corrected, false - there are still concave pieces
1496 */
1497bool Tesselation::CorrectConcaveBaselines(ofstream *out)
1498{
1499 class BoundaryLineSet *OldLines[4], *NewLine;
1500 class BoundaryPointSet *OldPoints[2];
1501 Vector BaseLineNormal;
1502 class BoundaryLineSet *Base = NULL;
1503 int OldTriangles[2], OldBaseLine;
1504 int i,m;
1505
1506 *out << Verbose(1) << "Begin of CorrectConcaveBaselines" << endl;
1507
1508 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++) {
1509 Base = baseline->second;
1510 *out << Verbose(2) << "Current baseline is " << *Base << " ... " << endl;
1511 // check convexity
1512 if (Base->CheckConvexityCriterion(out)) { // triangles are convex
1513 *out << Verbose(2) << "... has two convex triangles." << endl;
1514 } else { // not convex!
1515 *out << Verbose(2) << "... has two concave triangles!" << endl;
1516 // get the two triangles
1517 // gather four endpoints and four lines
1518 for (int j=0;j<4;j++)
1519 OldLines[j] = NULL;
1520 for (int j=0;j<2;j++)
1521 OldPoints[j] = NULL;
1522 i=0;
1523 m=0;
1524 *out << Verbose(3) << "The four old lines are: ";
1525 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1526 for (int j=0;j<3;j++) // all of their endpoints and baselines
1527 if (runner->second->lines[j] != Base) { // pick not the central baseline
1528 OldLines[i++] = runner->second->lines[j];
1529 *out << *runner->second->lines[j] << "\t";
1530 }
1531 *out << endl;
1532 *out << Verbose(3) << "The two old points are: ";
1533 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1534 for (int j=0;j<3;j++) // all of their endpoints and baselines
1535 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
1536 OldPoints[m++] = runner->second->endpoints[j];
1537 *out << *runner->second->endpoints[j] << "\t";
1538 }
1539 *out << endl;
1540 if (i<4) {
1541 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
1542 return false;
1543 }
1544 for (int j=0;j<4;j++)
1545 if (OldLines[j] == NULL) {
1546 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
1547 return false;
1548 }
1549 for (int j=0;j<2;j++)
1550 if (OldPoints[j] == NULL) {
1551 *out << Verbose(1) << "ERROR: We have not gathered enough endpoints!" << endl;
1552 return false;
1553 }
1554
1555 // remove triangles and baseline removes itself
1556 m=0;
1557 OldBaseLine = Base->Nr;
1558 LinesOnBoundary.erase(OldBaseLine);
1559 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
1560 TrianglesOnBoundary.erase(OldTriangles[m++] = runner->second->Nr);
1561 delete(runner->second);
1562 }
1563
1564 // construct new baseline (with same number as old one)
1565 BPS[0] = OldPoints[0];
1566 BPS[1] = OldPoints[1];
1567 NewLine = new class BoundaryLineSet(BPS, OldBaseLine);
1568 LinesOnBoundary.insert(LinePair(OldBaseLine, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
1569
1570 // construct new triangles with flipped baseline
1571 i=-1;
1572 if (OldLines[0]->IsConnectedTo(OldLines[2]))
1573 i=2;
1574 if (OldLines[0]->IsConnectedTo(OldLines[3]))
1575 i=3;
1576 if (i!=-1) {
1577 BLS[0] = OldLines[0];
1578 BLS[1] = OldLines[i];
1579 BLS[2] = NewLine;
1580 BTS = new class BoundaryTriangleSet(BLS, OldTriangles[0]);
1581 TrianglesOnBoundary.insert(TrianglePair(OldTriangles[0], BTS));
1582
1583 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
1584 BLS[1] = OldLines[1];
1585 BLS[2] = NewLine;
1586 BTS = new class BoundaryTriangleSet(BLS, OldTriangles[1]);
1587 TrianglesOnBoundary.insert(TrianglePair(OldTriangles[1], BTS));
1588 } else {
1589 *out << Verbose(1) << "The four old lines do not connect, something's utterly wrong here!" << endl;
1590 return false;
1591 }
1592 }
1593 }
1594 *out << Verbose(1) << "End of CorrectConcaveBaselines" << endl;
1595 return true;
1596};
1597
1598/** Finds the second point of starting triangle.
1599 * \param *a first node
1600 * \param *Candidate pointer to candidate node on return
1601 * \param Oben vector indicating the outside
1602 * \param Opt_Candidate reference to recommended candidate on return
1603 * \param Storage[3] array storing angles and other candidate information
1604 * \param RADIUS radius of virtual sphere
1605 * \param *LC LinkedCell structure with neighbouring points
1606 */
1607void Tesselation::Find_second_point_for_Tesselation(TesselPoint* a, TesselPoint* Candidate, Vector Oben, TesselPoint*& Opt_Candidate, double Storage[3], double RADIUS, LinkedCell *LC)
1608{
1609 cout << Verbose(2) << "Begin of Find_second_point_for_Tesselation" << endl;
1610 Vector AngleCheck;
1611 double norm = -1., angle;
1612 LinkedNodes *List = NULL;
1613 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
1614
1615 if (LC->SetIndexToNode(a)) { // get cell for the starting point
1616 for(int i=0;i<NDIM;i++) // store indices of this cell
1617 N[i] = LC->n[i];
1618 } else {
1619 cerr << "ERROR: Point " << *a << " is not found in cell " << LC->index << "." << endl;
1620 return;
1621 }
1622 // then go through the current and all neighbouring cells and check the contained points for possible candidates
1623 cout << Verbose(3) << "LC Intervals from [";
1624 for (int i=0;i<NDIM;i++) {
1625 cout << " " << N[i] << "<->" << LC->N[i];
1626 }
1627 cout << "] :";
1628 for (int i=0;i<NDIM;i++) {
1629 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
1630 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
1631 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
1632 }
1633 cout << endl;
1634
1635
1636 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
1637 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
1638 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
1639 List = LC->GetCurrentCell();
1640 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1641 if (List != NULL) {
1642 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
1643 Candidate = (*Runner);
1644 // check if we only have one unique point yet ...
1645 if (a != Candidate) {
1646 // Calculate center of the circle with radius RADIUS through points a and Candidate
1647 Vector OrthogonalizedOben, a_Candidate, Center;
1648 double distance, scaleFactor;
1649
1650 OrthogonalizedOben.CopyVector(&Oben);
1651 a_Candidate.CopyVector(a->node);
1652 a_Candidate.SubtractVector(Candidate->node);
1653 OrthogonalizedOben.ProjectOntoPlane(&a_Candidate);
1654 OrthogonalizedOben.Normalize();
1655 distance = 0.5 * a_Candidate.Norm();
1656 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
1657 OrthogonalizedOben.Scale(scaleFactor);
1658
1659 Center.CopyVector(Candidate->node);
1660 Center.AddVector(a->node);
1661 Center.Scale(0.5);
1662 Center.AddVector(&OrthogonalizedOben);
1663
1664 AngleCheck.CopyVector(&Center);
1665 AngleCheck.SubtractVector(a->node);
1666 norm = a_Candidate.Norm();
1667 // second point shall have smallest angle with respect to Oben vector
1668 if (norm < RADIUS*2.) {
1669 angle = AngleCheck.Angle(&Oben);
1670 if (angle < Storage[0]) {
1671 //cout << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
1672 cout << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
1673 Opt_Candidate = Candidate;
1674 Storage[0] = angle;
1675 //cout << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
1676 } else {
1677 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *Opt_Candidate << endl;
1678 }
1679 } else {
1680 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
1681 }
1682 } else {
1683 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
1684 }
1685 }
1686 } else {
1687 cout << Verbose(3) << "Linked cell list is empty." << endl;
1688 }
1689 }
1690 cout << Verbose(2) << "End of Find_second_point_for_Tesselation" << endl;
1691};
1692
1693
1694/** This recursive function finds a third point, to form a triangle with two given ones.
1695 * Note that this function is for the starting triangle.
1696 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
1697 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
1698 * the center of the sphere is still fixed up to a single parameter. The band of possible values
1699 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
1700 * us the "null" on this circle, the new center of the candidate point will be some way along this
1701 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
1702 * by the normal vector of the base triangle that always points outwards by construction.
1703 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
1704 * We construct the normal vector that defines the plane this circle lies in, it is just in the
1705 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
1706 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
1707 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
1708 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
1709 * both.
1710 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
1711 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
1712 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
1713 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
1714 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
1715 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
1716 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa Find_starting_triangle())
1717 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
1718 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
1719 * @param BaseLine BoundaryLineSet with the current base line
1720 * @param ThirdNode third point to avoid in search
1721 * @param candidates list of equally good candidates to return
1722 * @param ShortestAngle the current path length on this circle band for the current Opt_Candidate
1723 * @param RADIUS radius of sphere
1724 * @param *LC LinkedCell structure with neighbouring points
1725 */
1726void Tesselation::Find_third_point_for_Tesselation(Vector NormalVector, Vector SearchDirection, Vector OldSphereCenter, class BoundaryLineSet *BaseLine, class TesselPoint *ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, LinkedCell *LC)
1727{
1728 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
1729 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
1730 Vector SphereCenter;
1731 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
1732 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
1733 Vector NewNormalVector; // normal vector of the Candidate's triangle
1734 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
1735 LinkedNodes *List = NULL;
1736 double CircleRadius; // radius of this circle
1737 double radius;
1738 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
1739 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
1740 TesselPoint *Candidate = NULL;
1741 CandidateForTesselation *optCandidate = NULL;
1742
1743 cout << Verbose(1) << "Begin of Find_third_point_for_Tesselation" << endl;
1744
1745 //cout << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
1746
1747 // construct center of circle
1748 CircleCenter.CopyVector(BaseLine->endpoints[0]->node->node);
1749 CircleCenter.AddVector(BaseLine->endpoints[1]->node->node);
1750 CircleCenter.Scale(0.5);
1751
1752 // construct normal vector of circle
1753 CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
1754 CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
1755
1756 // calculate squared radius TesselPoint *ThirdNode,f circle
1757 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1758 if (radius/4. < RADIUS*RADIUS) {
1759 CircleRadius = RADIUS*RADIUS - radius/4.;
1760 CirclePlaneNormal.Normalize();
1761 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1762
1763 // test whether old center is on the band's plane
1764 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
1765 cerr << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
1766 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
1767 }
1768 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
1769 if (fabs(radius - CircleRadius) < HULLEPSILON) {
1770
1771 // check SearchDirection
1772 //cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1773 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
1774 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
1775 }
1776
1777 // get cell for the starting point
1778 if (LC->SetIndexToVector(&CircleCenter)) {
1779 for(int i=0;i<NDIM;i++) // store indices of this cell
1780 N[i] = LC->n[i];
1781 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
1782 } else {
1783 cerr << "ERROR: Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
1784 return;
1785 }
1786 // then go through the current and all neighbouring cells and check the contained points for possible candidates
1787 //cout << Verbose(2) << "LC Intervals:";
1788 for (int i=0;i<NDIM;i++) {
1789 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
1790 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
1791 //cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
1792 }
1793 //cout << endl;
1794 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
1795 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
1796 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
1797 List = LC->GetCurrentCell();
1798 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1799 if (List != NULL) {
1800 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
1801 Candidate = (*Runner);
1802
1803 // check for three unique points
1804 //cout << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->x << "." << endl;
1805 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
1806
1807 // construct both new centers
1808 GetCenterofCircumcircle(&NewSphereCenter, BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node);
1809 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
1810
1811 if ((NewNormalVector.MakeNormalVector(BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node))
1812 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
1813 ) {
1814 helper.CopyVector(&NewNormalVector);
1815 //cout << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
1816 radius = BaseLine->endpoints[0]->node->node->DistanceSquared(&NewSphereCenter);
1817 if (radius < RADIUS*RADIUS) {
1818 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1819 //cout << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
1820 NewSphereCenter.AddVector(&helper);
1821 NewSphereCenter.SubtractVector(&CircleCenter);
1822 //cout << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
1823
1824 // OtherNewSphereCenter is created by the same vector just in the other direction
1825 helper.Scale(-1.);
1826 OtherNewSphereCenter.AddVector(&helper);
1827 OtherNewSphereCenter.SubtractVector(&CircleCenter);
1828 //cout << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
1829
1830 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
1831 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
1832 alpha = min(alpha, Otheralpha);
1833 // if there is a better candidate, drop the current list and add the new candidate
1834 // otherwise ignore the new candidate and keep the list
1835 if (*ShortestAngle > (alpha - HULLEPSILON)) {
1836 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
1837 if (fabs(alpha - Otheralpha) > MYEPSILON) {
1838 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
1839 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
1840 } else {
1841 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
1842 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
1843 }
1844 // if there is an equal candidate, add it to the list without clearing the list
1845 if ((*ShortestAngle - HULLEPSILON) < alpha) {
1846 candidates->push_back(optCandidate);
1847 cout << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
1848 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
1849 } else {
1850 // remove all candidates from the list and then the list itself
1851 class CandidateForTesselation *remover = NULL;
1852 for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
1853 remover = *it;
1854 delete(remover);
1855 }
1856 candidates->clear();
1857 candidates->push_back(optCandidate);
1858 cout << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
1859 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
1860 }
1861 *ShortestAngle = alpha;
1862 //cout << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
1863 } else {
1864 if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
1865 //cout << Verbose(2) << "REJECT: Old candidate: " << *(optCandidate->point) << " is better than " << alpha << " with " << *ShortestAngle << "." << endl;
1866 } else {
1867 //cout << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
1868 }
1869 }
1870
1871 } else {
1872 //cout << Verbose(2) << "REJECT: NewSphereCenter " << NewSphereCenter << " is too far away: " << radius << "." << endl;
1873 }
1874 } else {
1875 //cout << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
1876 }
1877 } else {
1878 if (ThirdNode != NULL) {
1879 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
1880 } else {
1881 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
1882 }
1883 }
1884 }
1885 }
1886 }
1887 } else {
1888 cerr << Verbose(2) << "ERROR: The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
1889 }
1890 } else {
1891 if (ThirdNode != NULL)
1892 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
1893 else
1894 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
1895 }
1896
1897 //cout << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
1898 if (candidates->size() > 1) {
1899 candidates->unique();
1900 candidates->sort(sortCandidates);
1901 }
1902
1903 cout << Verbose(1) << "End of Find_third_point_for_Tesselation" << endl;
1904};
1905
1906/** Finds the endpoint two lines are sharing.
1907 * \param *line1 first line
1908 * \param *line2 second line
1909 * \return point which is shared or NULL if none
1910 */
1911class BoundaryPointSet *Tesselation::GetCommonEndpoint(class BoundaryLineSet * line1, class BoundaryLineSet * line2)
1912{
1913 class BoundaryLineSet * lines[2] =
1914 { line1, line2 };
1915 class BoundaryPointSet *node = NULL;
1916 map<int, class BoundaryPointSet *> OrderMap;
1917 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
1918 for (int i = 0; i < 2; i++)
1919 // for both lines
1920 for (int j = 0; j < 2; j++)
1921 { // for both endpoints
1922 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
1923 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
1924 if (!OrderTest.second)
1925 { // if insertion fails, we have common endpoint
1926 node = OrderTest.first->second;
1927 cout << Verbose(5) << "Common endpoint of lines " << *line1
1928 << " and " << *line2 << " is: " << *node << "." << endl;
1929 j = 2;
1930 i = 2;
1931 break;
1932 }
1933 }
1934 return node;
1935};
1936
1937/** Finds the triangle that is closest to a given Vector \a *x.
1938 * \param *out output stream for debugging
1939 * \param *x Vector to look from
1940 * \return list of BoundaryTriangleSet of nearest triangles or NULL in degenerate case.
1941 */
1942list<BoundaryTriangleSet*> * Tesselation::FindClosestTrianglesToPoint(ofstream *out, Vector *x, LinkedCell* LC)
1943{
1944 class TesselPoint *trianglePoints[3];
1945
1946 if (LinesOnBoundary.empty()) {
1947 *out << Verbose(0) << "Error: There is no tesselation structure to compare the point with, " << "please create one first.";
1948 return NULL;
1949 }
1950
1951 trianglePoints[0] = findClosestPoint(x, LC);
1952 // check whether closest point is "too close" :), then it's inside
1953 if (trianglePoints[0]->node->DistanceSquared(x) < MYEPSILON) {
1954 *out << Verbose(1) << "Point is right on a tesselation point, no nearest triangle." << endl;
1955 return NULL;
1956 }
1957 list<TesselPoint*> *connectedClosestPoints = getCircleOfConnectedPoints(out, trianglePoints[0], x);
1958 trianglePoints[1] = connectedClosestPoints->front();
1959 trianglePoints[2] = connectedClosestPoints->back();
1960 for (int i=0;i<3;i++) {
1961 if (trianglePoints[i] == NULL) {
1962 *out << Verbose(1) << "IsInnerPoint encounters serious error, point " << i << " not found." << endl;
1963 }
1964 *out << Verbose(1) << "List of possible points:" << endl;
1965 *out << *trianglePoints[i] << endl;
1966 }
1967 delete(connectedClosestPoints);
1968
1969 list<BoundaryTriangleSet*> *triangles = FindTriangles(trianglePoints);
1970
1971 if (triangles->empty()) {
1972 *out << Verbose(0) << "Error: There is no nearest triangle. Please check the tesselation structure.";
1973 return NULL;
1974 } else
1975 return triangles;
1976};
1977
1978/** Finds closest triangle to a point.
1979 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
1980 * \param *out output stream for debugging
1981 * \param *x Vector to look from
1982 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
1983 */
1984class BoundaryTriangleSet * Tesselation::FindClosestTriangleToPoint(ofstream *out, Vector *x, LinkedCell* LC)
1985{
1986 class BoundaryTriangleSet *result = NULL;
1987 list<BoundaryTriangleSet*> *triangles = FindClosestTrianglesToPoint(out, x, LC);
1988
1989 if (triangles == NULL)
1990 return NULL;
1991
1992 if (x->ScalarProduct(&triangles->front()->NormalVector) < 0)
1993 result = triangles->back();
1994 else
1995 result = triangles->front();
1996
1997 delete(triangles);
1998 return result;
1999};
2000
2001/** Checks whether the provided Vector is within the tesselation structure.
2002 *
2003 * @param point of which to check the position
2004 * @param *LC LinkedCell structure
2005 *
2006 * @return true if the point is inside the tesselation structure, false otherwise
2007 */
2008bool Tesselation::IsInnerPoint(ofstream *out, Vector Point, LinkedCell* LC)
2009{
2010 class BoundaryTriangleSet *result = FindClosestTriangleToPoint(out, &Point, LC);
2011 if (result == NULL)
2012 return true;
2013 if (Point.ScalarProduct(&result->NormalVector) < 0)
2014 return true;
2015 else
2016 return false;
2017}
2018
2019/** Checks whether the provided TesselPoint is within the tesselation structure.
2020 *
2021 * @param *Point of which to check the position
2022 * @param *LC Linked Cell structure
2023 *
2024 * @return true if the point is inside the tesselation structure, false otherwise
2025 */
2026bool Tesselation::IsInnerPoint(ofstream *out, TesselPoint *Point, LinkedCell* LC)
2027{
2028 class BoundaryTriangleSet *result = FindClosestTriangleToPoint(out, Point->node, LC);
2029 if (result == NULL)
2030 return true;
2031 if (Point->node->ScalarProduct(&result->NormalVector) < 0)
2032 return true;
2033 else
2034 return false;
2035}
2036
2037/** Gets all points connected to the provided point by triangulation lines.
2038 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2039 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2040 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2041 * triangle we are looking for.
2042 *
2043 * @param *Point of which get all connected points
2044 * @param *Reference Vector to be checked whether it is an inner point
2045 *
2046 * @return list of the two points linked to the provided one and closest to the point to be checked,
2047 */
2048list<TesselPoint*> * Tesselation::getCircleOfConnectedPoints(ofstream *out, TesselPoint* Point, Vector* Reference)
2049{
2050 list<TesselPoint*> connectedPoints;
2051 map<double, TesselPoint*> anglesOfPoints;
2052 map<double, TesselPoint*>::iterator runner;
2053 list<TesselPoint*>::iterator listRunner;
2054 Vector center, planeNorm, currentPoint, OrthogonalVector, helper;
2055 TesselPoint* current;
2056 bool takePoint = false;
2057
2058 planeNorm.CopyVector(Point->node);
2059 planeNorm.SubtractVector(Reference);
2060 planeNorm.Normalize();
2061
2062 LineMap::iterator findLines = LinesOnBoundary.begin();
2063 while (findLines != LinesOnBoundary.end()) {
2064 takePoint = false;
2065
2066 if (findLines->second->endpoints[0]->Nr == Point->nr) {
2067 takePoint = true;
2068 current = findLines->second->endpoints[1]->node;
2069 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
2070 takePoint = true;
2071 current = findLines->second->endpoints[0]->node;
2072 }
2073
2074 if (takePoint) {
2075 connectedPoints.push_back(current);
2076 currentPoint.CopyVector(current->node);
2077 currentPoint.ProjectOntoPlane(&planeNorm);
2078 center.AddVector(&currentPoint);
2079 }
2080
2081 findLines++;
2082 }
2083
2084 *out << "Summed vectors " << center << "; number of points " << connectedPoints.size()
2085 << "; scale factor " << 1.0/connectedPoints.size();
2086
2087 center.Scale(1.0/connectedPoints.size());
2088 listRunner = connectedPoints.begin();
2089
2090 *out << " calculated center " << center << endl;
2091
2092 // construct one orthogonal vector
2093 helper.CopyVector(Reference);
2094 helper.ProjectOntoPlane(&planeNorm);
2095 OrthogonalVector.MakeNormalVector(&center, &helper, (*listRunner)->node);
2096 while (listRunner != connectedPoints.end()) {
2097 double angle = getAngle(*((*listRunner)->node), *(Reference), center, OrthogonalVector);
2098 *out << "Calculated angle " << angle << " for point " << **listRunner << endl;
2099 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
2100 listRunner++;
2101 }
2102
2103 list<TesselPoint*> *result = new list<TesselPoint*>;
2104 runner = anglesOfPoints.begin();
2105 *out << "First value is " << *runner->second << endl;
2106 result->push_back(runner->second);
2107 runner = anglesOfPoints.end();
2108 runner--;
2109 *out << "Second value is " << *runner->second << endl;
2110 result->push_back(runner->second);
2111
2112 *out << "List of closest points has " << result->size() << " elements, which are "
2113 << *(result->front()) << " and " << *(result->back()) << endl;
2114
2115 return result;
2116}
2117
2118/** Checks for a new special triangle whether one of its edges is already present with one one triangle connected.
2119 * This enforces that special triangles (i.e. degenerated ones) should at last close the open-edge frontier and not
2120 * make it bigger (i.e. closing one (the baseline) and opening two new ones).
2121 * \param TPS[3] nodes of the triangle
2122 * \return true - there is such a line (i.e. creation of degenerated triangle is valid), false - no such line (don't create)
2123 */
2124bool CheckLineCriteriaforDegeneratedTriangle(class BoundaryPointSet *nodes[3])
2125{
2126 bool result = false;
2127 int counter = 0;
2128
2129 // check all three points
2130 for (int i=0;i<3;i++)
2131 for (int j=i+1; j<3; j++) {
2132 if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) { // there already is a line
2133 LineMap::iterator FindLine;
2134 pair<LineMap::iterator,LineMap::iterator> FindPair;
2135 FindPair = nodes[i]->lines.equal_range(nodes[j]->node->nr);
2136 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
2137 // If there is a line with less than two attached triangles, we don't need a new line.
2138 if (FindLine->second->TrianglesCount < 2) {
2139 counter++;
2140 break; // increase counter only once per edge
2141 }
2142 }
2143 } else { // no line
2144 cout << Verbose(1) << "ERROR: The line between " << nodes[i] << " and " << nodes[j] << " is not yet present, hence no need for a degenerate triangle!" << endl;
2145 result = true;
2146 }
2147 }
2148 if (counter > 1) {
2149 cout << Verbose(2) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl;
2150 result = true;
2151 }
2152 return result;
2153};
2154
2155
2156/** Sort function for the candidate list.
2157 */
2158bool sortCandidates(CandidateForTesselation* candidate1, CandidateForTesselation* candidate2)
2159{
2160 Vector BaseLineVector, OrthogonalVector, helper;
2161 if (candidate1->BaseLine != candidate2->BaseLine) { // sanity check
2162 cout << Verbose(0) << "ERROR: sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl;
2163 //return false;
2164 exit(1);
2165 }
2166 // create baseline vector
2167 BaseLineVector.CopyVector(candidate1->BaseLine->endpoints[1]->node->node);
2168 BaseLineVector.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
2169 BaseLineVector.Normalize();
2170
2171 // create normal in-plane vector to cope with acos() non-uniqueness on [0,2pi] (note that is pointing in the "right" direction already, hence ">0" test!)
2172 helper.CopyVector(candidate1->BaseLine->endpoints[0]->node->node);
2173 helper.SubtractVector(candidate1->point->node);
2174 OrthogonalVector.CopyVector(&helper);
2175 helper.VectorProduct(&BaseLineVector);
2176 OrthogonalVector.SubtractVector(&helper);
2177 OrthogonalVector.Normalize();
2178
2179 // calculate both angles and correct with in-plane vector
2180 helper.CopyVector(candidate1->point->node);
2181 helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
2182 double phi = BaseLineVector.Angle(&helper);
2183 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2184 phi = 2.*M_PI - phi;
2185 }
2186 helper.CopyVector(candidate2->point->node);
2187 helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
2188 double psi = BaseLineVector.Angle(&helper);
2189 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2190 psi = 2.*M_PI - psi;
2191 }
2192
2193 cout << Verbose(2) << *candidate1->point << " has angle " << phi << endl;
2194 cout << Verbose(2) << *candidate2->point << " has angle " << psi << endl;
2195
2196 // return comparison
2197 return phi < psi;
2198};
2199
2200
2201
2202/**
2203 * Finds the point which is closest to the provided one.
2204 *
2205 * @param Point to which to find the closest other point
2206 * @param linked cell structure
2207 *
2208 * @return point which is closest to the provided one
2209 */
2210TesselPoint* findClosestPoint(const Vector* Point, LinkedCell* LC)
2211{
2212 LinkedNodes *List = NULL;
2213 TesselPoint* closestPoint = NULL;
2214 double distance = 1e16;
2215 Vector helper;
2216 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2217
2218 LC->SetIndexToVector(Point); // ignore status as we calculate bounds below sensibly
2219 for(int i=0;i<NDIM;i++) // store indices of this cell
2220 N[i] = LC->n[i];
2221 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2222
2223 LC->GetNeighbourBounds(Nlower, Nupper);
2224 //cout << endl;
2225 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2226 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2227 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2228 List = LC->GetCurrentCell();
2229 //cout << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
2230 if (List != NULL) {
2231 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2232 helper.CopyVector(Point);
2233 helper.SubtractVector((*Runner)->node);
2234 double currentNorm = helper. Norm();
2235 if (currentNorm < distance) {
2236 distance = currentNorm;
2237 closestPoint = (*Runner);
2238 }
2239 }
2240 } else {
2241 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << ","
2242 << LC->n[2] << " is invalid!" << endl;
2243 }
2244 }
2245
2246 return closestPoint;
2247}
2248
2249
2250/**
2251 * Finds triangles belonging to the three provided points.
2252 *
2253 * @param *Points[3] list, is expected to contain three points
2254 *
2255 * @return triangles which belong to the provided points, will be empty if there are none,
2256 * will usually be one, in case of degeneration, there will be two
2257 */
2258list<BoundaryTriangleSet*> *Tesselation::FindTriangles(TesselPoint* Points[3])
2259{
2260 list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
2261 LineMap::iterator FindLine;
2262 PointMap::iterator FindPoint;
2263 TriangleMap::iterator FindTriangle;
2264 class BoundaryPointSet *TrianglePoints[3];
2265
2266 for (int i = 0; i < 3; i++) {
2267 FindPoint = PointsOnBoundary.find(Points[i]->nr);
2268 if (FindPoint != PointsOnBoundary.end()) {
2269 TrianglePoints[i] = FindPoint->second;
2270 } else {
2271 TrianglePoints[i] = NULL;
2272 }
2273 }
2274
2275 // checks lines between the points in the Points for their adjacent triangles
2276 for (int i = 0; i < 3; i++) {
2277 if (TrianglePoints[i] != NULL) {
2278 for (int j = i; j < 3; j++) {
2279 if (TrianglePoints[j] != NULL) {
2280 FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr);
2281 if (FindLine != TrianglePoints[i]->lines.end()) {
2282 for (; FindLine->first == TrianglePoints[j]->node->nr; FindLine++) {
2283 FindTriangle = FindLine->second->triangles.begin();
2284 for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
2285 if ((
2286 (FindTriangle->second->endpoints[0] == TrianglePoints[0])
2287 || (FindTriangle->second->endpoints[0] == TrianglePoints[1])
2288 || (FindTriangle->second->endpoints[0] == TrianglePoints[2])
2289 ) && (
2290 (FindTriangle->second->endpoints[1] == TrianglePoints[0])
2291 || (FindTriangle->second->endpoints[1] == TrianglePoints[1])
2292 || (FindTriangle->second->endpoints[1] == TrianglePoints[2])
2293 ) && (
2294 (FindTriangle->second->endpoints[2] == TrianglePoints[0])
2295 || (FindTriangle->second->endpoints[2] == TrianglePoints[1])
2296 || (FindTriangle->second->endpoints[2] == TrianglePoints[2])
2297 )
2298 ) {
2299 result->push_back(FindTriangle->second);
2300 }
2301 }
2302 }
2303 // Is it sufficient to consider one of the triangle lines for this.
2304 return result;
2305
2306 }
2307 }
2308 }
2309 }
2310 }
2311
2312 return result;
2313}
2314
2315/** Gets the angle between a point and a reference relative to the provided center.
2316 * We have two shanks (point, center) and (reference, center) between which the angle is calculated
2317 * and by scalar product with OrthogonalVector we decide the interval.
2318 * @param point to calculate the angle for
2319 * @param reference to which to calculate the angle
2320 * @param center for which to calculate the angle between the vectors
2321 * @param OrthogonalVector points in direction of [pi,2pi] interval
2322 *
2323 * @return angle between point and reference
2324 */
2325double getAngle(const Vector &point, const Vector &reference, const Vector &center, Vector OrthogonalVector)
2326{
2327 Vector ReferenceVector, helper;
2328 cout << Verbose(4) << center << " is our center " << endl;
2329 // create baseline vector
2330 ReferenceVector.CopyVector(&reference);
2331 ReferenceVector.SubtractVector(&center);
2332 OrthogonalVector.MakeNormalVector(&ReferenceVector);
2333 cout << Verbose(4) << ReferenceVector << " is our reference " << endl;
2334 if (ReferenceVector.IsNull())
2335 return M_PI;
2336
2337 // calculate both angles and correct with in-plane vector
2338 helper.CopyVector(&point);
2339 helper.SubtractVector(&center);
2340 if (helper.IsNull())
2341 return M_PI;
2342 double phi = ReferenceVector.Angle(&helper);
2343 if (OrthogonalVector.ScalarProduct(&helper) > 0) {
2344 phi = 2.*M_PI - phi;
2345 }
2346
2347 cout << Verbose(3) << helper << " has angle " << phi << " with respect to reference." << endl;
2348
2349 return phi;
2350}
2351
Note: See TracBrowser for help on using the repository browser.