source: src/tesselation.cpp@ fcd7b6

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

Fixed testsuite, removed some minor bugs.

  • TesselationUnitTest_SOURCES lacked memoryallocator stuff
  • Free does not give a message anymore, as there can be no error.
  • testsuite was fixed for suite 2 and 3, mostly due to changed options that were not accomodated for in the testsuite
  • Property mode set to 100644
File size: 153.9 KB
Line 
1/*
2 * tesselation.cpp
3 *
4 * Created on: Aug 3, 2009
5 * Author: heber
6 */
7
8#include "helpers.hpp"
9#include "linkedcell.hpp"
10#include "memoryallocator.hpp"
11#include "tesselation.hpp"
12#include "tesselationhelpers.hpp"
13#include "vector.hpp"
14
15class molecule;
16
17// ======================================== Points on Boundary =================================
18
19/** Constructor of BoundaryPointSet.
20 */
21BoundaryPointSet::BoundaryPointSet()
22{
23 LinesCount = 0;
24 Nr = -1;
25 value = 0.;
26};
27
28/** Constructor of BoundaryPointSet with Tesselpoint.
29 * \param *Walker TesselPoint this boundary point represents
30 */
31BoundaryPointSet::BoundaryPointSet(TesselPoint *Walker)
32{
33 node = Walker;
34 LinesCount = 0;
35 Nr = Walker->nr;
36 value = 0.;
37};
38
39/** Destructor of BoundaryPointSet.
40 * Sets node to NULL to avoid removing the original, represented TesselPoint.
41 * \note When removing point from a class Tesselation, use RemoveTesselationPoint()
42 */
43BoundaryPointSet::~BoundaryPointSet()
44{
45 //cout << Verbose(5) << "Erasing point nr. " << Nr << "." << endl;
46 if (!lines.empty())
47 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some lines." << endl;
48 node = NULL;
49};
50
51/** Add a line to the LineMap of this point.
52 * \param *line line to add
53 */
54void BoundaryPointSet::AddLine(class BoundaryLineSet *line)
55{
56 cout << Verbose(6) << "Adding " << *this << " to line " << *line << "."
57 << endl;
58 if (line->endpoints[0] == this)
59 {
60 lines.insert(LinePair(line->endpoints[1]->Nr, line));
61 }
62 else
63 {
64 lines.insert(LinePair(line->endpoints[0]->Nr, line));
65 }
66 LinesCount++;
67};
68
69/** output operator for BoundaryPointSet.
70 * \param &ost output stream
71 * \param &a boundary point
72 */
73ostream & operator <<(ostream &ost, BoundaryPointSet &a)
74{
75 ost << "[" << a.Nr << "|" << a.node->Name << " at " << *a.node->node << "]";
76 return ost;
77}
78;
79
80// ======================================== Lines on Boundary =================================
81
82/** Constructor of BoundaryLineSet.
83 */
84BoundaryLineSet::BoundaryLineSet()
85{
86 for (int i = 0; i < 2; i++)
87 endpoints[i] = NULL;
88 Nr = -1;
89};
90
91/** Constructor of BoundaryLineSet with two endpoints.
92 * Adds line automatically to each endpoints' LineMap
93 * \param *Point[2] array of two boundary points
94 * \param number number of the list
95 */
96BoundaryLineSet::BoundaryLineSet(class BoundaryPointSet *Point[2], int number)
97{
98 // set number
99 Nr = number;
100 // set endpoints in ascending order
101 SetEndpointsOrdered(endpoints, Point[0], Point[1]);
102 // add this line to the hash maps of both endpoints
103 Point[0]->AddLine(this); //Taken out, to check whether we can avoid unwanted double adding.
104 Point[1]->AddLine(this); //
105 // clear triangles list
106 cout << Verbose(5) << "New Line with endpoints " << *this << "." << endl;
107};
108
109/** Destructor for BoundaryLineSet.
110 * Removes itself from each endpoints' LineMap, calling RemoveTrianglePoint() when point not connected anymore.
111 * \note When removing lines from a class Tesselation, use RemoveTesselationLine()
112 */
113BoundaryLineSet::~BoundaryLineSet()
114{
115 int Numbers[2];
116
117 // get other endpoint number of finding copies of same line
118 if (endpoints[1] != NULL)
119 Numbers[0] = endpoints[1]->Nr;
120 else
121 Numbers[0] = -1;
122 if (endpoints[0] != NULL)
123 Numbers[1] = endpoints[0]->Nr;
124 else
125 Numbers[1] = -1;
126
127 for (int i = 0; i < 2; i++) {
128 if (endpoints[i] != NULL) {
129 if (Numbers[i] != -1) { // as there may be multiple lines with same endpoints, we have to go through each and find in the endpoint's line list this line set
130 pair<LineMap::iterator, LineMap::iterator> erasor = endpoints[i]->lines.equal_range(Numbers[i]);
131 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
132 if ((*Runner).second == this) {
133 //cout << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
134 endpoints[i]->lines.erase(Runner);
135 break;
136 }
137 } else { // there's just a single line left
138 if (endpoints[i]->lines.erase(Nr)) {
139 //cout << Verbose(5) << "Removing Line Nr. " << Nr << " in boundary point " << *endpoints[i] << "." << endl;
140 }
141 }
142 if (endpoints[i]->lines.empty()) {
143 //cout << Verbose(5) << *endpoints[i] << " has no more lines it's attached to, erasing." << endl;
144 if (endpoints[i] != NULL) {
145 delete(endpoints[i]);
146 endpoints[i] = NULL;
147 }
148 }
149 }
150 }
151 if (!triangles.empty())
152 cerr << "WARNING: Memory Leak! I " << *this << " am still connected to some triangles." << endl;
153};
154
155/** Add triangle to TriangleMap of this boundary line.
156 * \param *triangle to add
157 */
158void BoundaryLineSet::AddTriangle(class BoundaryTriangleSet *triangle)
159{
160 cout << Verbose(6) << "Add " << triangle->Nr << " to line " << *this << "." << endl;
161 triangles.insert(TrianglePair(triangle->Nr, triangle));
162};
163
164/** Checks whether we have a common endpoint with given \a *line.
165 * \param *line other line to test
166 * \return true - common endpoint present, false - not connected
167 */
168bool BoundaryLineSet::IsConnectedTo(class BoundaryLineSet *line)
169{
170 if ((endpoints[0] == line->endpoints[0]) || (endpoints[1] == line->endpoints[0]) || (endpoints[0] == line->endpoints[1]) || (endpoints[1] == line->endpoints[1]))
171 return true;
172 else
173 return false;
174};
175
176/** Checks whether the adjacent triangles of a baseline are convex or not.
177 * We sum the two angles of each height vector with respect to the center of the baseline.
178 * If greater/equal M_PI than we are convex.
179 * \param *out output stream for debugging
180 * \return true - triangles are convex, false - concave or less than two triangles connected
181 */
182bool BoundaryLineSet::CheckConvexityCriterion(ofstream *out)
183{
184 Vector BaseLineCenter, BaseLineNormal, BaseLine, helper[2], NormalCheck;
185 // get the two triangles
186 if (triangles.size() != 2) {
187 *out << Verbose(1) << "ERROR: Baseline " << *this << " is connected to less than two triangles, Tesselation incomplete!" << endl;
188 return true;
189 }
190 // check normal vectors
191 // have a normal vector on the base line pointing outwards
192 //*out << Verbose(3) << "INFO: " << *this << " has vectors at " << *(endpoints[0]->node->node) << " and at " << *(endpoints[1]->node->node) << "." << endl;
193 BaseLineCenter.CopyVector(endpoints[0]->node->node);
194 BaseLineCenter.AddVector(endpoints[1]->node->node);
195 BaseLineCenter.Scale(1./2.);
196 BaseLine.CopyVector(endpoints[0]->node->node);
197 BaseLine.SubtractVector(endpoints[1]->node->node);
198 //*out << Verbose(3) << "INFO: Baseline is " << BaseLine << " and its center is at " << BaseLineCenter << "." << endl;
199
200 BaseLineNormal.Zero();
201 NormalCheck.Zero();
202 double sign = -1.;
203 int i=0;
204 class BoundaryPointSet *node = NULL;
205 for(TriangleMap::iterator runner = triangles.begin(); runner != triangles.end(); runner++) {
206 //*out << Verbose(3) << "INFO: NormalVector of " << *(runner->second) << " is " << runner->second->NormalVector << "." << endl;
207 NormalCheck.AddVector(&runner->second->NormalVector);
208 NormalCheck.Scale(sign);
209 sign = -sign;
210 if (runner->second->NormalVector.NormSquared() > MYEPSILON)
211 BaseLineNormal.CopyVector(&runner->second->NormalVector); // yes, copy second on top of first
212 else {
213 *out << Verbose(1) << "CRITICAL: Triangle " << *runner->second << " has zero normal vector!" << endl;
214 exit(255);
215 }
216 node = runner->second->GetThirdEndpoint(this);
217 if (node != NULL) {
218 //*out << Verbose(3) << "INFO: Third node for triangle " << *(runner->second) << " is " << *node << " at " << *(node->node->node) << "." << endl;
219 helper[i].CopyVector(node->node->node);
220 helper[i].SubtractVector(&BaseLineCenter);
221 helper[i].MakeNormalVector(&BaseLine); // we want to compare the triangle's heights' angles!
222 //*out << Verbose(4) << "INFO: Height vector with respect to baseline is " << helper[i] << "." << endl;
223 i++;
224 } else {
225 //*out << Verbose(2) << "ERROR: I cannot find third node in triangle, something's wrong." << endl;
226 return true;
227 }
228 }
229 //*out << Verbose(3) << "INFO: BaselineNormal is " << BaseLineNormal << "." << endl;
230 if (NormalCheck.NormSquared() < MYEPSILON) {
231 *out << Verbose(3) << "ACCEPT: Normalvectors of both triangles are the same: convex." << endl;
232 return true;
233 }
234 BaseLineNormal.Scale(-1.);
235 double angle = GetAngle(helper[0], helper[1], BaseLineNormal);
236 if ((angle - M_PI) > -MYEPSILON) {
237 *out << Verbose(3) << "ACCEPT: Angle is greater than pi: convex." << endl;
238 return true;
239 } else {
240 *out << Verbose(3) << "REJECT: Angle is less than pi: concave." << endl;
241 return false;
242 }
243}
244
245/** Checks whether point is any of the two endpoints this line contains.
246 * \param *point point to test
247 * \return true - point is of the line, false - is not
248 */
249bool BoundaryLineSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
250{
251 for(int i=0;i<2;i++)
252 if (point == endpoints[i])
253 return true;
254 return false;
255};
256
257/** Returns other endpoint of the line.
258 * \param *point other endpoint
259 * \return NULL - if endpoint not contained in BoundaryLineSet, or pointer to BoundaryPointSet otherwise
260 */
261class BoundaryPointSet *BoundaryLineSet::GetOtherEndpoint(class BoundaryPointSet *point)
262{
263 if (endpoints[0] == point)
264 return endpoints[1];
265 else if (endpoints[1] == point)
266 return endpoints[0];
267 else
268 return NULL;
269};
270
271/** output operator for BoundaryLineSet.
272 * \param &ost output stream
273 * \param &a boundary line
274 */
275ostream & operator <<(ostream &ost, BoundaryLineSet &a)
276{
277 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << "," << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "]";
278 return ost;
279};
280
281// ======================================== Triangles on Boundary =================================
282
283/** Constructor for BoundaryTriangleSet.
284 */
285BoundaryTriangleSet::BoundaryTriangleSet()
286{
287 for (int i = 0; i < 3; i++)
288 {
289 endpoints[i] = NULL;
290 lines[i] = NULL;
291 }
292 Nr = -1;
293};
294
295/** Constructor for BoundaryTriangleSet with three lines.
296 * \param *line[3] lines that make up the triangle
297 * \param number number of triangle
298 */
299BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet *line[3], int number)
300{
301 // set number
302 Nr = number;
303 // set lines
304 cout << Verbose(5) << "New triangle " << Nr << ":" << endl;
305 for (int i = 0; i < 3; i++)
306 {
307 lines[i] = line[i];
308 lines[i]->AddTriangle(this);
309 }
310 // get ascending order of endpoints
311 map<int, class BoundaryPointSet *> OrderMap;
312 for (int i = 0; i < 3; i++)
313 // for all three lines
314 for (int j = 0; j < 2; j++)
315 { // for both endpoints
316 OrderMap.insert(pair<int, class BoundaryPointSet *> (
317 line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
318 // and we don't care whether insertion fails
319 }
320 // set endpoints
321 int Counter = 0;
322 cout << Verbose(6) << " with end points ";
323 for (map<int, class BoundaryPointSet *>::iterator runner = OrderMap.begin(); runner
324 != OrderMap.end(); runner++)
325 {
326 endpoints[Counter] = runner->second;
327 cout << " " << *endpoints[Counter];
328 Counter++;
329 }
330 if (Counter < 3)
331 {
332 cerr << "ERROR! We have a triangle with only two distinct endpoints!"
333 << endl;
334 //exit(1);
335 }
336 cout << "." << endl;
337};
338
339/** Destructor of BoundaryTriangleSet.
340 * Removes itself from each of its lines' LineMap and removes them if necessary.
341 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
342 */
343BoundaryTriangleSet::~BoundaryTriangleSet()
344{
345 for (int i = 0; i < 3; i++) {
346 if (lines[i] != NULL) {
347 if (lines[i]->triangles.erase(Nr)) {
348 //cout << Verbose(5) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
349 }
350 if (lines[i]->triangles.empty()) {
351 //cout << Verbose(5) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
352 delete (lines[i]);
353 lines[i] = NULL;
354 }
355 }
356 }
357 //cout << Verbose(5) << "Erasing triangle Nr." << Nr << " itself." << endl;
358};
359
360/** Calculates the normal vector for this triangle.
361 * Is made unique by comparison with \a OtherVector to point in the other direction.
362 * \param &OtherVector direction vector to make normal vector unique.
363 */
364void BoundaryTriangleSet::GetNormalVector(Vector &OtherVector)
365{
366 // get normal vector
367 NormalVector.MakeNormalVector(endpoints[0]->node->node, endpoints[1]->node->node, endpoints[2]->node->node);
368
369 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
370 if (NormalVector.ScalarProduct(&OtherVector) > 0.)
371 NormalVector.Scale(-1.);
372};
373
374/** Finds the point on the triangle \a *BTS the line defined by \a *MolCenter and \a *x crosses through.
375 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
376 * This we test if it's really on the plane and whether it's inside the triangle on the plane or not.
377 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
378 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
379 * the first two basepoints) or not.
380 * \param *out output stream for debugging
381 * \param *MolCenter offset vector of line
382 * \param *x second endpoint of line, minus \a *MolCenter is directional vector of line
383 * \param *Intersection intersection on plane on return
384 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
385 */
386bool BoundaryTriangleSet::GetIntersectionInsideTriangle(ofstream *out, Vector *MolCenter, Vector *x, Vector *Intersection)
387{
388 Vector CrossPoint;
389 Vector helper;
390
391 if (!Intersection->GetIntersectionWithPlane(out, &NormalVector, endpoints[0]->node->node, MolCenter, x)) {
392 *out << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl;
393 return false;
394 }
395
396 // Calculate cross point between one baseline and the line from the third endpoint to intersection
397 int i=0;
398 do {
399 if (CrossPoint.GetIntersectionOfTwoLinesOnPlane(out, endpoints[i%3]->node->node, endpoints[(i+1)%3]->node->node, endpoints[(i+2)%3]->node->node, Intersection, &NormalVector)) {
400 helper.CopyVector(endpoints[(i+1)%3]->node->node);
401 helper.SubtractVector(endpoints[i%3]->node->node);
402 } else
403 i++;
404 if (i>2)
405 break;
406 } while (CrossPoint.NormSquared() < MYEPSILON);
407 if (i==3) {
408 *out << Verbose(1) << "ERROR: Could not find any cross points, something's utterly wrong here!" << endl;
409 exit(255);
410 }
411 CrossPoint.SubtractVector(endpoints[i%3]->node->node); // cross point was returned as absolute vector
412
413 // check whether intersection is inside or not by comparing length of intersection and length of cross point
414 if ((CrossPoint.NormSquared() - helper.NormSquared()) < MYEPSILON) { // inside
415 return true;
416 } else { // outside!
417 Intersection->Zero();
418 return false;
419 }
420};
421
422/** Checks whether lines is any of the three boundary lines this triangle contains.
423 * \param *line line to test
424 * \return true - line is of the triangle, false - is not
425 */
426bool BoundaryTriangleSet::ContainsBoundaryLine(class BoundaryLineSet *line)
427{
428 for(int i=0;i<3;i++)
429 if (line == lines[i])
430 return true;
431 return false;
432};
433
434/** Checks whether point is any of the three endpoints this triangle contains.
435 * \param *point point to test
436 * \return true - point is of the triangle, false - is not
437 */
438bool BoundaryTriangleSet::ContainsBoundaryPoint(class BoundaryPointSet *point)
439{
440 for(int i=0;i<3;i++)
441 if (point == endpoints[i])
442 return true;
443 return false;
444};
445
446/** Checks whether point is any of the three endpoints this triangle contains.
447 * \param *point TesselPoint to test
448 * \return true - point is of the triangle, false - is not
449 */
450bool BoundaryTriangleSet::ContainsBoundaryPoint(class TesselPoint *point)
451{
452 for(int i=0;i<3;i++)
453 if (point == endpoints[i]->node)
454 return true;
455 return false;
456};
457
458/** Checks whether three given \a *Points coincide with triangle's endpoints.
459 * \param *Points[3] pointer to BoundaryPointSet
460 * \return true - is the very triangle, false - is not
461 */
462bool BoundaryTriangleSet::IsPresentTupel(class BoundaryPointSet *Points[3])
463{
464 return (((endpoints[0] == Points[0])
465 || (endpoints[0] == Points[1])
466 || (endpoints[0] == Points[2])
467 ) && (
468 (endpoints[1] == Points[0])
469 || (endpoints[1] == Points[1])
470 || (endpoints[1] == Points[2])
471 ) && (
472 (endpoints[2] == Points[0])
473 || (endpoints[2] == Points[1])
474 || (endpoints[2] == Points[2])
475
476 ));
477};
478
479/** Checks whether three given \a *Points coincide with triangle's endpoints.
480 * \param *Points[3] pointer to BoundaryPointSet
481 * \return true - is the very triangle, false - is not
482 */
483bool BoundaryTriangleSet::IsPresentTupel(class BoundaryTriangleSet *T)
484{
485 return (((endpoints[0] == T->endpoints[0])
486 || (endpoints[0] == T->endpoints[1])
487 || (endpoints[0] == T->endpoints[2])
488 ) && (
489 (endpoints[1] == T->endpoints[0])
490 || (endpoints[1] == T->endpoints[1])
491 || (endpoints[1] == T->endpoints[2])
492 ) && (
493 (endpoints[2] == T->endpoints[0])
494 || (endpoints[2] == T->endpoints[1])
495 || (endpoints[2] == T->endpoints[2])
496
497 ));
498};
499
500/** Returns the endpoint which is not contained in the given \a *line.
501 * \param *line baseline defining two endpoints
502 * \return pointer third endpoint or NULL if line does not belong to triangle.
503 */
504class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(class BoundaryLineSet *line)
505{
506 // sanity check
507 if (!ContainsBoundaryLine(line))
508 return NULL;
509 for(int i=0;i<3;i++)
510 if (!line->ContainsBoundaryPoint(endpoints[i]))
511 return endpoints[i];
512 // actually, that' impossible :)
513 return NULL;
514};
515
516/** Calculates the center point of the triangle.
517 * Is third of the sum of all endpoints.
518 * \param *center central point on return.
519 */
520void BoundaryTriangleSet::GetCenter(Vector *center)
521{
522 center->Zero();
523 for(int i=0;i<3;i++)
524 center->AddVector(endpoints[i]->node->node);
525 center->Scale(1./3.);
526}
527
528/** output operator for BoundaryTriangleSet.
529 * \param &ost output stream
530 * \param &a boundary triangle
531 */
532ostream &operator <<(ostream &ost, BoundaryTriangleSet &a)
533{
534 ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
535 << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
536 return ost;
537};
538
539// =========================================================== class TESSELPOINT ===========================================
540
541/** Constructor of class TesselPoint.
542 */
543TesselPoint::TesselPoint()
544{
545 node = NULL;
546 nr = -1;
547 Name = NULL;
548};
549
550/** Destructor for class TesselPoint.
551 */
552TesselPoint::~TesselPoint()
553{
554};
555
556/** Prints LCNode to screen.
557 */
558ostream & operator << (ostream &ost, const TesselPoint &a)
559{
560 ost << "[" << (a.Name) << "|" << a.Name << " at " << *a.node << "]";
561 return ost;
562};
563
564/** Prints LCNode to screen.
565 */
566ostream & TesselPoint::operator << (ostream &ost)
567{
568 ost << "[" << (Name) << "|" << this << "]";
569 return ost;
570};
571
572
573// =========================================================== class POINTCLOUD ============================================
574
575/** Constructor of class PointCloud.
576 */
577PointCloud::PointCloud()
578{
579
580};
581
582/** Destructor for class PointCloud.
583 */
584PointCloud::~PointCloud()
585{
586
587};
588
589// ============================ CandidateForTesselation =============================
590
591/** Constructor of class CandidateForTesselation.
592 */
593CandidateForTesselation::CandidateForTesselation(TesselPoint *candidate, BoundaryLineSet* line, Vector OptCandidateCenter, Vector OtherOptCandidateCenter) {
594 point = candidate;
595 BaseLine = line;
596 OptCenter.CopyVector(&OptCandidateCenter);
597 OtherOptCenter.CopyVector(&OtherOptCandidateCenter);
598};
599
600/** Destructor for class CandidateForTesselation.
601 */
602CandidateForTesselation::~CandidateForTesselation() {
603 point = NULL;
604 BaseLine = NULL;
605};
606
607// =========================================================== class TESSELATION ===========================================
608
609/** Constructor of class Tesselation.
610 */
611Tesselation::Tesselation()
612{
613 PointsOnBoundaryCount = 0;
614 LinesOnBoundaryCount = 0;
615 TrianglesOnBoundaryCount = 0;
616 InternalPointer = PointsOnBoundary.begin();
617 LastTriangle = NULL;
618 TriangleFilesWritten = 0;
619}
620;
621
622/** Destructor of class Tesselation.
623 * We have to free all points, lines and triangles.
624 */
625Tesselation::~Tesselation()
626{
627 cout << Verbose(1) << "Free'ing TesselStruct ... " << endl;
628 for (TriangleMap::iterator runner = TrianglesOnBoundary.begin(); runner != TrianglesOnBoundary.end(); runner++) {
629 if (runner->second != NULL) {
630 delete (runner->second);
631 runner->second = NULL;
632 } else
633 cerr << "ERROR: The triangle " << runner->first << " has already been free'd." << endl;
634 }
635 cout << "This envelope was written to file " << TriangleFilesWritten << " times(s)." << endl;
636}
637;
638
639/** PointCloud implementation of GetCenter
640 * Uses PointsOnBoundary and STL stuff.
641 */
642Vector * Tesselation::GetCenter(ofstream *out)
643{
644 Vector *Center = new Vector(0.,0.,0.);
645 int num=0;
646 for (GoToFirst(); (!IsEnd()); GoToNext()) {
647 Center->AddVector(GetPoint()->node);
648 num++;
649 }
650 Center->Scale(1./num);
651 return Center;
652};
653
654/** PointCloud implementation of GoPoint
655 * Uses PointsOnBoundary and STL stuff.
656 */
657TesselPoint * Tesselation::GetPoint()
658{
659 return (InternalPointer->second->node);
660};
661
662/** PointCloud implementation of GetTerminalPoint.
663 * Uses PointsOnBoundary and STL stuff.
664 */
665TesselPoint * Tesselation::GetTerminalPoint()
666{
667 PointMap::iterator Runner = PointsOnBoundary.end();
668 Runner--;
669 return (Runner->second->node);
670};
671
672/** PointCloud implementation of GoToNext.
673 * Uses PointsOnBoundary and STL stuff.
674 */
675void Tesselation::GoToNext()
676{
677 if (InternalPointer != PointsOnBoundary.end())
678 InternalPointer++;
679};
680
681/** PointCloud implementation of GoToPrevious.
682 * Uses PointsOnBoundary and STL stuff.
683 */
684void Tesselation::GoToPrevious()
685{
686 if (InternalPointer != PointsOnBoundary.begin())
687 InternalPointer--;
688};
689
690/** PointCloud implementation of GoToFirst.
691 * Uses PointsOnBoundary and STL stuff.
692 */
693void Tesselation::GoToFirst()
694{
695 InternalPointer = PointsOnBoundary.begin();
696};
697
698/** PointCloud implementation of GoToLast.
699 * Uses PointsOnBoundary and STL stuff.
700 */
701void Tesselation::GoToLast()
702{
703 InternalPointer = PointsOnBoundary.end();
704 InternalPointer--;
705};
706
707/** PointCloud implementation of IsEmpty.
708 * Uses PointsOnBoundary and STL stuff.
709 */
710bool Tesselation::IsEmpty()
711{
712 return (PointsOnBoundary.empty());
713};
714
715/** PointCloud implementation of IsLast.
716 * Uses PointsOnBoundary and STL stuff.
717 */
718bool Tesselation::IsEnd()
719{
720 return (InternalPointer == PointsOnBoundary.end());
721};
722
723
724/** Gueses first starting triangle of the convex envelope.
725 * We guess the starting triangle by taking the smallest distance between two points and looking for a fitting third.
726 * \param *out output stream for debugging
727 * \param PointsOnBoundary set of boundary points defining the convex envelope of the cluster
728 */
729void
730Tesselation::GuessStartingTriangle(ofstream *out)
731{
732 // 4b. create a starting triangle
733 // 4b1. create all distances
734 DistanceMultiMap DistanceMMap;
735 double distance, tmp;
736 Vector PlaneVector, TrialVector;
737 PointMap::iterator A, B, C; // three nodes of the first triangle
738 A = PointsOnBoundary.begin(); // the first may be chosen arbitrarily
739
740 // with A chosen, take each pair B,C and sort
741 if (A != PointsOnBoundary.end())
742 {
743 B = A;
744 B++;
745 for (; B != PointsOnBoundary.end(); B++)
746 {
747 C = B;
748 C++;
749 for (; C != PointsOnBoundary.end(); C++)
750 {
751 tmp = A->second->node->node->DistanceSquared(B->second->node->node);
752 distance = tmp * tmp;
753 tmp = A->second->node->node->DistanceSquared(C->second->node->node);
754 distance += tmp * tmp;
755 tmp = B->second->node->node->DistanceSquared(C->second->node->node);
756 distance += tmp * tmp;
757 DistanceMMap.insert(DistanceMultiMapPair(distance, pair<PointMap::iterator, PointMap::iterator> (B, C)));
758 }
759 }
760 }
761 // // listing distances
762 // *out << Verbose(1) << "Listing DistanceMMap:";
763 // for(DistanceMultiMap::iterator runner = DistanceMMap.begin(); runner != DistanceMMap.end(); runner++) {
764 // *out << " " << runner->first << "(" << *runner->second.first->second << ", " << *runner->second.second->second << ")";
765 // }
766 // *out << endl;
767 // 4b2. pick three baselines forming a triangle
768 // 1. we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
769 DistanceMultiMap::iterator baseline = DistanceMMap.begin();
770 for (; baseline != DistanceMMap.end(); baseline++)
771 {
772 // we take from the smallest sum of squared distance as the base line BC (with peak A) onward as the triangle candidate
773 // 2. next, we have to check whether all points reside on only one side of the triangle
774 // 3. construct plane vector
775 PlaneVector.MakeNormalVector(A->second->node->node,
776 baseline->second.first->second->node->node,
777 baseline->second.second->second->node->node);
778 *out << Verbose(2) << "Plane vector of candidate triangle is ";
779 PlaneVector.Output(out);
780 *out << endl;
781 // 4. loop over all points
782 double sign = 0.;
783 PointMap::iterator checker = PointsOnBoundary.begin();
784 for (; checker != PointsOnBoundary.end(); checker++)
785 {
786 // (neglecting A,B,C)
787 if ((checker == A) || (checker == baseline->second.first) || (checker
788 == baseline->second.second))
789 continue;
790 // 4a. project onto plane vector
791 TrialVector.CopyVector(checker->second->node->node);
792 TrialVector.SubtractVector(A->second->node->node);
793 distance = TrialVector.ScalarProduct(&PlaneVector);
794 if (fabs(distance) < 1e-4) // we need to have a small epsilon around 0 which is still ok
795 continue;
796 *out << Verbose(3) << "Projection of " << checker->second->node->Name
797 << " yields distance of " << distance << "." << endl;
798 tmp = distance / fabs(distance);
799 // 4b. Any have different sign to than before? (i.e. would lie outside convex hull with this starting triangle)
800 if ((sign != 0) && (tmp != sign))
801 {
802 // 4c. If so, break 4. loop and continue with next candidate in 1. loop
803 *out << Verbose(2) << "Current candidates: "
804 << A->second->node->Name << ","
805 << baseline->second.first->second->node->Name << ","
806 << baseline->second.second->second->node->Name << " leaves "
807 << checker->second->node->Name << " outside the convex hull."
808 << endl;
809 break;
810 }
811 else
812 { // note the sign for later
813 *out << Verbose(2) << "Current candidates: "
814 << A->second->node->Name << ","
815 << baseline->second.first->second->node->Name << ","
816 << baseline->second.second->second->node->Name << " leave "
817 << checker->second->node->Name << " inside the convex hull."
818 << endl;
819 sign = tmp;
820 }
821 // 4d. Check whether the point is inside the triangle (check distance to each node
822 tmp = checker->second->node->node->DistanceSquared(A->second->node->node);
823 int innerpoint = 0;
824 if ((tmp < A->second->node->node->DistanceSquared(
825 baseline->second.first->second->node->node)) && (tmp
826 < A->second->node->node->DistanceSquared(
827 baseline->second.second->second->node->node)))
828 innerpoint++;
829 tmp = checker->second->node->node->DistanceSquared(
830 baseline->second.first->second->node->node);
831 if ((tmp < baseline->second.first->second->node->node->DistanceSquared(
832 A->second->node->node)) && (tmp
833 < baseline->second.first->second->node->node->DistanceSquared(
834 baseline->second.second->second->node->node)))
835 innerpoint++;
836 tmp = checker->second->node->node->DistanceSquared(
837 baseline->second.second->second->node->node);
838 if ((tmp < baseline->second.second->second->node->node->DistanceSquared(
839 baseline->second.first->second->node->node)) && (tmp
840 < baseline->second.second->second->node->node->DistanceSquared(
841 A->second->node->node)))
842 innerpoint++;
843 // 4e. If so, break 4. loop and continue with next candidate in 1. loop
844 if (innerpoint == 3)
845 break;
846 }
847 // 5. come this far, all on same side? Then break 1. loop and construct triangle
848 if (checker == PointsOnBoundary.end())
849 {
850 *out << "Looks like we have a candidate!" << endl;
851 break;
852 }
853 }
854 if (baseline != DistanceMMap.end())
855 {
856 BPS[0] = baseline->second.first->second;
857 BPS[1] = baseline->second.second->second;
858 BLS[0] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
859 BPS[0] = A->second;
860 BPS[1] = baseline->second.second->second;
861 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
862 BPS[0] = baseline->second.first->second;
863 BPS[1] = A->second;
864 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
865
866 // 4b3. insert created triangle
867 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
868 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
869 TrianglesOnBoundaryCount++;
870 for (int i = 0; i < NDIM; i++)
871 {
872 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BTS->lines[i]));
873 LinesOnBoundaryCount++;
874 }
875
876 *out << Verbose(1) << "Starting triangle is " << *BTS << "." << endl;
877 }
878 else
879 {
880 *out << Verbose(1) << "No starting triangle found." << endl;
881 exit(255);
882 }
883}
884;
885
886/** Tesselates the convex envelope of a cluster from a single starting triangle.
887 * The starting triangle is made out of three baselines. Each line in the final tesselated cluster may belong to at most
888 * 2 triangles. Hence, we go through all current lines:
889 * -# if the lines contains to only one triangle
890 * -# We search all points in the boundary
891 * -# if the triangle is in forward direction of the baseline (at most 90 degrees angle between vector orthogonal to
892 * baseline in triangle plane pointing out of the triangle and normal vector of new triangle)
893 * -# if the triangle with the baseline and the current point has the smallest of angles (comparison between normal vectors)
894 * -# then we have a new triangle, whose baselines we again add (or increase their TriangleCount)
895 * \param *out output stream for debugging
896 * \param *configuration for IsAngstroem
897 * \param *cloud cluster of points
898 */
899void Tesselation::TesselateOnBoundary(ofstream *out, PointCloud *cloud)
900{
901 bool flag;
902 PointMap::iterator winner;
903 class BoundaryPointSet *peak = NULL;
904 double SmallestAngle, TempAngle;
905 Vector NormalVector, VirtualNormalVector, CenterVector, TempVector, helper, PropagationVector, *Center = NULL;
906 LineMap::iterator LineChecker[2];
907
908 Center = cloud->GetCenter(out);
909 // create a first tesselation with the given BoundaryPoints
910 do {
911 flag = false;
912 for (LineMap::iterator baseline = LinesOnBoundary.begin(); baseline != LinesOnBoundary.end(); baseline++)
913 if (baseline->second->triangles.size() == 1) {
914 // 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)
915 SmallestAngle = M_PI;
916
917 // get peak point with respect to this base line's only triangle
918 BTS = baseline->second->triangles.begin()->second; // there is only one triangle so far
919 *out << Verbose(2) << "Current baseline is between " << *(baseline->second) << "." << endl;
920 for (int i = 0; i < 3; i++)
921 if ((BTS->endpoints[i] != baseline->second->endpoints[0]) && (BTS->endpoints[i] != baseline->second->endpoints[1]))
922 peak = BTS->endpoints[i];
923 *out << Verbose(3) << " and has peak " << *peak << "." << endl;
924
925 // prepare some auxiliary vectors
926 Vector BaseLineCenter, BaseLine;
927 BaseLineCenter.CopyVector(baseline->second->endpoints[0]->node->node);
928 BaseLineCenter.AddVector(baseline->second->endpoints[1]->node->node);
929 BaseLineCenter.Scale(1. / 2.); // points now to center of base line
930 BaseLine.CopyVector(baseline->second->endpoints[0]->node->node);
931 BaseLine.SubtractVector(baseline->second->endpoints[1]->node->node);
932
933 // offset to center of triangle
934 CenterVector.Zero();
935 for (int i = 0; i < 3; i++)
936 CenterVector.AddVector(BTS->endpoints[i]->node->node);
937 CenterVector.Scale(1. / 3.);
938 *out << Verbose(4) << "CenterVector of base triangle is " << CenterVector << endl;
939
940 // normal vector of triangle
941 NormalVector.CopyVector(Center);
942 NormalVector.SubtractVector(&CenterVector);
943 BTS->GetNormalVector(NormalVector);
944 NormalVector.CopyVector(&BTS->NormalVector);
945 *out << Verbose(4) << "NormalVector of base triangle is " << NormalVector << endl;
946
947 // vector in propagation direction (out of triangle)
948 // project center vector onto triangle plane (points from intersection plane-NormalVector to plane-CenterVector intersection)
949 PropagationVector.MakeNormalVector(&BaseLine, &NormalVector);
950 TempVector.CopyVector(&CenterVector);
951 TempVector.SubtractVector(baseline->second->endpoints[0]->node->node); // TempVector is vector on triangle plane pointing from one baseline egde towards center!
952 //*out << Verbose(2) << "Projection of propagation onto temp: " << PropagationVector.Projection(&TempVector) << "." << endl;
953 if (PropagationVector.ScalarProduct(&TempVector) > 0) // make sure normal propagation vector points outward from baseline
954 PropagationVector.Scale(-1.);
955 *out << Verbose(4) << "PropagationVector of base triangle is " << PropagationVector << endl;
956 winner = PointsOnBoundary.end();
957
958 // loop over all points and calculate angle between normal vector of new and present triangle
959 for (PointMap::iterator target = PointsOnBoundary.begin(); target != PointsOnBoundary.end(); target++) {
960 if ((target->second != baseline->second->endpoints[0]) && (target->second != baseline->second->endpoints[1])) { // don't take the same endpoints
961 *out << Verbose(3) << "Target point is " << *(target->second) << ":" << endl;
962
963 // first check direction, so that triangles don't intersect
964 VirtualNormalVector.CopyVector(target->second->node->node);
965 VirtualNormalVector.SubtractVector(&BaseLineCenter); // points from center of base line to target
966 VirtualNormalVector.ProjectOntoPlane(&NormalVector);
967 TempAngle = VirtualNormalVector.Angle(&PropagationVector);
968 *out << Verbose(4) << "VirtualNormalVector is " << VirtualNormalVector << " and PropagationVector is " << PropagationVector << "." << endl;
969 if (TempAngle > (M_PI/2.)) { // no bends bigger than Pi/2 (90 degrees)
970 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", bad direction!" << endl;
971 continue;
972 } else
973 *out << Verbose(4) << "Angle on triangle plane between propagation direction and base line to " << *(target->second) << " is " << TempAngle << ", good direction!" << endl;
974
975 // check first and second endpoint (if any connecting line goes to target has at least not more than 1 triangle)
976 LineChecker[0] = baseline->second->endpoints[0]->lines.find(target->first);
977 LineChecker[1] = baseline->second->endpoints[1]->lines.find(target->first);
978 if (((LineChecker[0] != baseline->second->endpoints[0]->lines.end()) && (LineChecker[0]->second->triangles.size() == 2))) {
979 *out << Verbose(4) << *(baseline->second->endpoints[0]) << " has line " << *(LineChecker[0]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[0]->second->triangles.size() << " triangles." << endl;
980 continue;
981 }
982 if (((LineChecker[1] != baseline->second->endpoints[1]->lines.end()) && (LineChecker[1]->second->triangles.size() == 2))) {
983 *out << Verbose(4) << *(baseline->second->endpoints[1]) << " has line " << *(LineChecker[1]->second) << " to " << *(target->second) << " as endpoint with " << LineChecker[1]->second->triangles.size() << " triangles." << endl;
984 continue;
985 }
986
987 // check whether the envisaged triangle does not already exist (if both lines exist and have same endpoint)
988 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)))) {
989 *out << Verbose(4) << "Current target is peak!" << endl;
990 continue;
991 }
992
993 // check for linear dependence
994 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
995 TempVector.SubtractVector(target->second->node->node);
996 helper.CopyVector(baseline->second->endpoints[1]->node->node);
997 helper.SubtractVector(target->second->node->node);
998 helper.ProjectOntoPlane(&TempVector);
999 if (fabs(helper.NormSquared()) < MYEPSILON) {
1000 *out << Verbose(4) << "Chosen set of vectors is linear dependent." << endl;
1001 continue;
1002 }
1003
1004 // in case NOT both were found, create virtually this triangle, get its normal vector, calculate angle
1005 flag = true;
1006 VirtualNormalVector.MakeNormalVector(baseline->second->endpoints[0]->node->node, baseline->second->endpoints[1]->node->node, target->second->node->node);
1007 TempVector.CopyVector(baseline->second->endpoints[0]->node->node);
1008 TempVector.AddVector(baseline->second->endpoints[1]->node->node);
1009 TempVector.AddVector(target->second->node->node);
1010 TempVector.Scale(1./3.);
1011 TempVector.SubtractVector(Center);
1012 // make it always point outward
1013 if (VirtualNormalVector.ScalarProduct(&TempVector) < 0)
1014 VirtualNormalVector.Scale(-1.);
1015 // calculate angle
1016 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1017 *out << Verbose(4) << "NormalVector is " << VirtualNormalVector << " and the angle is " << TempAngle << "." << endl;
1018 if ((SmallestAngle - TempAngle) > MYEPSILON) { // set to new possible winner
1019 SmallestAngle = TempAngle;
1020 winner = target;
1021 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1022 } else if (fabs(SmallestAngle - TempAngle) < MYEPSILON) { // check the angle to propagation, both possible targets are in one plane! (their normals have same angle)
1023 // hence, check the angles to some normal direction from our base line but in this common plane of both targets...
1024 helper.CopyVector(target->second->node->node);
1025 helper.SubtractVector(&BaseLineCenter);
1026 helper.ProjectOntoPlane(&BaseLine);
1027 // ...the one with the smaller angle is the better candidate
1028 TempVector.CopyVector(target->second->node->node);
1029 TempVector.SubtractVector(&BaseLineCenter);
1030 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1031 TempAngle = TempVector.Angle(&helper);
1032 TempVector.CopyVector(winner->second->node->node);
1033 TempVector.SubtractVector(&BaseLineCenter);
1034 TempVector.ProjectOntoPlane(&VirtualNormalVector);
1035 if (TempAngle < TempVector.Angle(&helper)) {
1036 TempAngle = NormalVector.Angle(&VirtualNormalVector);
1037 SmallestAngle = TempAngle;
1038 winner = target;
1039 *out << Verbose(4) << "New winner " << *winner->second->node << " due to smaller angle " << TempAngle << " to propagation direction." << endl;
1040 } else
1041 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle to propagation direction." << endl;
1042 } else
1043 *out << Verbose(4) << "Keeping old winner " << *winner->second->node << " due to smaller angle between normal vectors." << endl;
1044 }
1045 } // end of loop over all boundary points
1046
1047 // 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
1048 if (winner != PointsOnBoundary.end()) {
1049 *out << Verbose(2) << "Winning target point is " << *(winner->second) << " with angle " << SmallestAngle << "." << endl;
1050 // create the lins of not yet present
1051 BLS[0] = baseline->second;
1052 // 5c. add lines to the line set if those were new (not yet part of a triangle), delete lines that belong to two triangles)
1053 LineChecker[0] = baseline->second->endpoints[0]->lines.find(winner->first);
1054 LineChecker[1] = baseline->second->endpoints[1]->lines.find(winner->first);
1055 if (LineChecker[0] == baseline->second->endpoints[0]->lines.end()) { // create
1056 BPS[0] = baseline->second->endpoints[0];
1057 BPS[1] = winner->second;
1058 BLS[1] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1059 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[1]));
1060 LinesOnBoundaryCount++;
1061 } else
1062 BLS[1] = LineChecker[0]->second;
1063 if (LineChecker[1] == baseline->second->endpoints[1]->lines.end()) { // create
1064 BPS[0] = baseline->second->endpoints[1];
1065 BPS[1] = winner->second;
1066 BLS[2] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1067 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[2]));
1068 LinesOnBoundaryCount++;
1069 } else
1070 BLS[2] = LineChecker[1]->second;
1071 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1072 BTS->GetCenter(&helper);
1073 helper.SubtractVector(Center);
1074 helper.Scale(-1);
1075 BTS->GetNormalVector(helper);
1076 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1077 TrianglesOnBoundaryCount++;
1078 } else {
1079 *out << Verbose(1) << "I could not determine a winner for this baseline " << *(baseline->second) << "." << endl;
1080 }
1081
1082 // 5d. If the set of lines is not yet empty, go to 5. and continue
1083 } else
1084 *out << Verbose(2) << "Baseline candidate " << *(baseline->second) << " has a triangle count of " << baseline->second->triangles.size() << "." << endl;
1085 } while (flag);
1086
1087 // exit
1088 delete(Center);
1089};
1090
1091/** Inserts all points outside of the tesselated surface into it by adding new triangles.
1092 * \param *out output stream for debugging
1093 * \param *cloud cluster of points
1094 * \param *LC LinkedCell structure to find nearest point quickly
1095 * \return true - all straddling points insert, false - something went wrong
1096 */
1097bool Tesselation::InsertStraddlingPoints(ofstream *out, PointCloud *cloud, LinkedCell *LC)
1098{
1099 Vector Intersection, Normal;
1100 TesselPoint *Walker = NULL;
1101 Vector *Center = cloud->GetCenter(out);
1102 list<BoundaryTriangleSet*> *triangles = NULL;
1103 bool AddFlag = false;
1104 LinkedCell *BoundaryPoints = NULL;
1105
1106 *out << Verbose(1) << "Begin of InsertStraddlingPoints" << endl;
1107
1108 cloud->GoToFirst();
1109 BoundaryPoints = new LinkedCell(this, 5.);
1110 while (!cloud->IsEnd()) { // we only have to go once through all points, as boundary can become only bigger
1111 if (AddFlag) {
1112 delete(BoundaryPoints);
1113 BoundaryPoints = new LinkedCell(this, 5.);
1114 AddFlag = false;
1115 }
1116 Walker = cloud->GetPoint();
1117 *out << Verbose(2) << "Current point is " << *Walker << "." << endl;
1118 // get the next triangle
1119 triangles = FindClosestTrianglesToPoint(out, Walker->node, BoundaryPoints);
1120 BTS = triangles->front();
1121 if ((triangles == NULL) || (BTS->ContainsBoundaryPoint(Walker))) {
1122 *out << Verbose(2) << "No triangles found, probably a tesselation point itself." << endl;
1123 cloud->GoToNext();
1124 continue;
1125 } else {
1126 }
1127 *out << Verbose(2) << "Closest triangle is " << *BTS << "." << endl;
1128 // get the intersection point
1129 if (BTS->GetIntersectionInsideTriangle(out, Center, Walker->node, &Intersection)) {
1130 *out << Verbose(2) << "We have an intersection at " << Intersection << "." << endl;
1131 // we have the intersection, check whether in- or outside of boundary
1132 if ((Center->DistanceSquared(Walker->node) - Center->DistanceSquared(&Intersection)) < -MYEPSILON) {
1133 // inside, next!
1134 *out << Verbose(2) << *Walker << " is inside wrt triangle " << *BTS << "." << endl;
1135 } else {
1136 // outside!
1137 *out << Verbose(2) << *Walker << " is outside wrt triangle " << *BTS << "." << endl;
1138 class BoundaryLineSet *OldLines[3], *NewLines[3];
1139 class BoundaryPointSet *OldPoints[3], *NewPoint;
1140 // store the three old lines and old points
1141 for (int i=0;i<3;i++) {
1142 OldLines[i] = BTS->lines[i];
1143 OldPoints[i] = BTS->endpoints[i];
1144 }
1145 Normal.CopyVector(&BTS->NormalVector);
1146 // add Walker to boundary points
1147 *out << Verbose(2) << "Adding " << *Walker << " to BoundaryPoints." << endl;
1148 AddFlag = true;
1149 if (AddBoundaryPoint(Walker,0))
1150 NewPoint = BPS[0];
1151 else
1152 continue;
1153 // remove triangle
1154 *out << Verbose(2) << "Erasing triangle " << *BTS << "." << endl;
1155 TrianglesOnBoundary.erase(BTS->Nr);
1156 delete(BTS);
1157 // create three new boundary lines
1158 for (int i=0;i<3;i++) {
1159 BPS[0] = NewPoint;
1160 BPS[1] = OldPoints[i];
1161 NewLines[i] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount);
1162 *out << Verbose(3) << "Creating new line " << *NewLines[i] << "." << endl;
1163 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, NewLines[i])); // no need for check for unique insertion as BPS[0] is definitely a new one
1164 LinesOnBoundaryCount++;
1165 }
1166 // create three new triangle with new point
1167 for (int i=0;i<3;i++) { // find all baselines
1168 BLS[0] = OldLines[i];
1169 int n = 1;
1170 for (int j=0;j<3;j++) {
1171 if (NewLines[j]->IsConnectedTo(BLS[0])) {
1172 if (n>2) {
1173 *out << Verbose(1) << "ERROR: " << BLS[0] << " connects to all of the new lines?!" << endl;
1174 return false;
1175 } else
1176 BLS[n++] = NewLines[j];
1177 }
1178 }
1179 // create the triangle
1180 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1181 Normal.Scale(-1.);
1182 BTS->GetNormalVector(Normal);
1183 Normal.Scale(-1.);
1184 *out << Verbose(2) << "Created new triangle " << *BTS << "." << endl;
1185 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1186 TrianglesOnBoundaryCount++;
1187 }
1188 }
1189 } else { // something is wrong with FindClosestTriangleToPoint!
1190 *out << Verbose(1) << "ERROR: The closest triangle did not produce an intersection!" << endl;
1191 return false;
1192 }
1193 cloud->GoToNext();
1194 }
1195
1196 // exit
1197 delete(Center);
1198 *out << Verbose(1) << "End of InsertStraddlingPoints" << endl;
1199 return true;
1200};
1201
1202/** Adds a point to the tesselation::PointsOnBoundary list.
1203 * \param *Walker point to add
1204 * \param n TesselStruct::BPS index to put pointer into
1205 * \return true - new point was added, false - point already present
1206 */
1207bool
1208Tesselation::AddBoundaryPoint(TesselPoint *Walker, int n)
1209{
1210 PointTestPair InsertUnique;
1211 BPS[n] = new class BoundaryPointSet(Walker);
1212 InsertUnique = PointsOnBoundary.insert(PointPair(Walker->nr, BPS[n]));
1213 if (InsertUnique.second) { // if new point was not present before, increase counter
1214 PointsOnBoundaryCount++;
1215 return true;
1216 } else {
1217 delete(BPS[n]);
1218 BPS[n] = InsertUnique.first->second;
1219 return false;
1220 }
1221}
1222;
1223
1224/** Adds point to Tesselation::PointsOnBoundary if not yet present.
1225 * Tesselation::TPS is set to either this new BoundaryPointSet or to the existing one of not unique.
1226 * @param Candidate point to add
1227 * @param n index for this point in Tesselation::TPS array
1228 */
1229void
1230Tesselation::AddTesselationPoint(TesselPoint* Candidate, int n)
1231{
1232 PointTestPair InsertUnique;
1233 TPS[n] = new class BoundaryPointSet(Candidate);
1234 InsertUnique = PointsOnBoundary.insert(PointPair(Candidate->nr, TPS[n]));
1235 if (InsertUnique.second) { // if new point was not present before, increase counter
1236 PointsOnBoundaryCount++;
1237 } else {
1238 delete TPS[n];
1239 cout << Verbose(4) << "Node " << *((InsertUnique.first)->second->node) << " is already present in PointsOnBoundary." << endl;
1240 TPS[n] = (InsertUnique.first)->second;
1241 }
1242}
1243;
1244
1245/** Function tries to add line from current Points in BPS to BoundaryLineSet.
1246 * If successful it raises the line count and inserts the new line into the BLS,
1247 * if unsuccessful, it writes the line which had been present into the BLS, deleting the new constructed one.
1248 * @param *a first endpoint
1249 * @param *b second endpoint
1250 * @param n index of Tesselation::BLS giving the line with both endpoints
1251 */
1252void Tesselation::AddTesselationLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n) {
1253 bool insertNewLine = true;
1254
1255 if (a->lines.find(b->node->nr) != a->lines.end()) {
1256 LineMap::iterator FindLine = a->lines.find(b->node->nr);
1257 pair<LineMap::iterator,LineMap::iterator> FindPair;
1258 FindPair = a->lines.equal_range(b->node->nr);
1259 cout << Verbose(5) << "INFO: There is at least one line between " << *a << " and " << *b << ": " << *(FindLine->second) << "." << endl;
1260
1261 for (FindLine = FindPair.first; FindLine != FindPair.second; FindLine++) {
1262 // If there is a line with less than two attached triangles, we don't need a new line.
1263 if (FindLine->second->triangles.size() < 2) {
1264 insertNewLine = false;
1265 cout << Verbose(4) << "Using existing line " << *FindLine->second << endl;
1266
1267 BPS[0] = FindLine->second->endpoints[0];
1268 BPS[1] = FindLine->second->endpoints[1];
1269 BLS[n] = FindLine->second;
1270
1271 break;
1272 }
1273 }
1274 }
1275
1276 if (insertNewLine) {
1277 AlwaysAddTesselationTriangleLine(a, b, n);
1278 }
1279}
1280;
1281
1282/**
1283 * Adds lines from each of the current points in the BPS to BoundaryLineSet.
1284 * Raises the line count and inserts the new line into the BLS.
1285 *
1286 * @param *a first endpoint
1287 * @param *b second endpoint
1288 * @param n index of Tesselation::BLS giving the line with both endpoints
1289 */
1290void Tesselation::AlwaysAddTesselationTriangleLine(class BoundaryPointSet *a, class BoundaryPointSet *b, int n)
1291{
1292 cout << Verbose(4) << "Adding line [" << LinesOnBoundaryCount << "|" << *(a->node) << " and " << *(b->node) << "." << endl;
1293 BPS[0] = a;
1294 BPS[1] = b;
1295 BLS[n] = new class BoundaryLineSet(BPS, LinesOnBoundaryCount); // this also adds the line to the local maps
1296 // add line to global map
1297 LinesOnBoundary.insert(LinePair(LinesOnBoundaryCount, BLS[n]));
1298 // increase counter
1299 LinesOnBoundaryCount++;
1300};
1301
1302/** Function adds triangle to global list.
1303 * Furthermore, the triangle receives the next free id and id counter \a TrianglesOnBoundaryCount is increased.
1304 */
1305void Tesselation::AddTesselationTriangle()
1306{
1307 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1308
1309 // add triangle to global map
1310 TrianglesOnBoundary.insert(TrianglePair(TrianglesOnBoundaryCount, BTS));
1311 TrianglesOnBoundaryCount++;
1312
1313 // set as last new triangle
1314 LastTriangle = BTS;
1315
1316 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1317};
1318
1319/** Function adds triangle to global list.
1320 * Furthermore, the triangle number is set to \a nr.
1321 * \param nr triangle number
1322 */
1323void Tesselation::AddTesselationTriangle(int nr)
1324{
1325 cout << Verbose(1) << "Adding triangle to global TrianglesOnBoundary map." << endl;
1326
1327 // add triangle to global map
1328 TrianglesOnBoundary.insert(TrianglePair(nr, BTS));
1329
1330 // set as last new triangle
1331 LastTriangle = BTS;
1332
1333 // NOTE: add triangle to local maps is done in constructor of BoundaryTriangleSet
1334};
1335
1336/** Removes a triangle from the tesselation.
1337 * Removes itself from the TriangleMap's of its lines, calls for them RemoveTriangleLine() if they are no more connected.
1338 * Removes itself from memory.
1339 * \param *triangle to remove
1340 */
1341void Tesselation::RemoveTesselationTriangle(class BoundaryTriangleSet *triangle)
1342{
1343 if (triangle == NULL)
1344 return;
1345 for (int i = 0; i < 3; i++) {
1346 if (triangle->lines[i] != NULL) {
1347 cout << Verbose(5) << "Removing triangle Nr." << triangle->Nr << " in line " << *triangle->lines[i] << "." << endl;
1348 triangle->lines[i]->triangles.erase(triangle->Nr);
1349 if (triangle->lines[i]->triangles.empty()) {
1350 cout << Verbose(5) << *triangle->lines[i] << " is no more attached to any triangle, erasing." << endl;
1351 RemoveTesselationLine(triangle->lines[i]);
1352 } else {
1353 cout << Verbose(5) << *triangle->lines[i] << " is still attached to another triangle: ";
1354 for(TriangleMap::iterator TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); TriangleRunner++)
1355 cout << "[" << (TriangleRunner->second)->Nr << "|" << *((TriangleRunner->second)->endpoints[0]) << ", " << *((TriangleRunner->second)->endpoints[1]) << ", " << *((TriangleRunner->second)->endpoints[2]) << "] \t";
1356 cout << endl;
1357// for (int j=0;j<2;j++) {
1358// cout << Verbose(5) << "Lines of endpoint " << *(triangle->lines[i]->endpoints[j]) << ": ";
1359// for(LineMap::iterator LineRunner = triangle->lines[i]->endpoints[j]->lines.begin(); LineRunner != triangle->lines[i]->endpoints[j]->lines.end(); LineRunner++)
1360// cout << "[" << *(LineRunner->second) << "] \t";
1361// cout << endl;
1362// }
1363 }
1364 triangle->lines[i] = NULL; // free'd or not: disconnect
1365 } else
1366 cerr << "ERROR: This line " << i << " has already been free'd." << endl;
1367 }
1368
1369 if (TrianglesOnBoundary.erase(triangle->Nr))
1370 cout << Verbose(5) << "Removing triangle Nr. " << triangle->Nr << "." << endl;
1371 delete(triangle);
1372};
1373
1374/** Removes a line from the tesselation.
1375 * Removes itself from each endpoints' LineMap, then removes itself from global LinesOnBoundary list and free's the line.
1376 * \param *line line to remove
1377 */
1378void Tesselation::RemoveTesselationLine(class BoundaryLineSet *line)
1379{
1380 int Numbers[2];
1381
1382 if (line == NULL)
1383 return;
1384 // get other endpoint number for finding copies of same line
1385 if (line->endpoints[1] != NULL)
1386 Numbers[0] = line->endpoints[1]->Nr;
1387 else
1388 Numbers[0] = -1;
1389 if (line->endpoints[0] != NULL)
1390 Numbers[1] = line->endpoints[0]->Nr;
1391 else
1392 Numbers[1] = -1;
1393
1394 for (int i = 0; i < 2; i++) {
1395 if (line->endpoints[i] != NULL) {
1396 if (Numbers[i] != -1) { // as there may be multiple lines with same endpoints, we have to go through each and find in the endpoint's line list this line set
1397 pair<LineMap::iterator, LineMap::iterator> erasor = line->endpoints[i]->lines.equal_range(Numbers[i]);
1398 for (LineMap::iterator Runner = erasor.first; Runner != erasor.second; Runner++)
1399 if ((*Runner).second == line) {
1400 cout << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1401 line->endpoints[i]->lines.erase(Runner);
1402 break;
1403 }
1404 } else { // there's just a single line left
1405 if (line->endpoints[i]->lines.erase(line->Nr))
1406 cout << Verbose(5) << "Removing Line Nr. " << line->Nr << " in boundary point " << *line->endpoints[i] << "." << endl;
1407 }
1408 if (line->endpoints[i]->lines.empty()) {
1409 cout << Verbose(5) << *line->endpoints[i] << " has no more lines it's attached to, erasing." << endl;
1410 RemoveTesselationPoint(line->endpoints[i]);
1411 } else {
1412 cout << Verbose(5) << *line->endpoints[i] << " has still lines it's attached to: ";
1413 for(LineMap::iterator LineRunner = line->endpoints[i]->lines.begin(); LineRunner != line->endpoints[i]->lines.end(); LineRunner++)
1414 cout << "[" << *(LineRunner->second) << "] \t";
1415 cout << endl;
1416 }
1417 line->endpoints[i] = NULL; // free'd or not: disconnect
1418 } else
1419 cerr << "ERROR: Endpoint " << i << " has already been free'd." << endl;
1420 }
1421 if (!line->triangles.empty())
1422 cerr << "WARNING: Memory Leak! I " << *line << " am still connected to some triangles." << endl;
1423
1424 if (LinesOnBoundary.erase(line->Nr))
1425 cout << Verbose(5) << "Removing line Nr. " << line->Nr << "." << endl;
1426 delete(line);
1427};
1428
1429/** Removes a point from the tesselation.
1430 * Checks whether there are still lines connected, removes from global PointsOnBoundary list, then free's the point.
1431 * \note If a point should be removed, while keep the tesselated surface intact (i.e. closed), use RemovePointFromTesselatedSurface()
1432 * \param *point point to remove
1433 */
1434void Tesselation::RemoveTesselationPoint(class BoundaryPointSet *point)
1435{
1436 if (point == NULL)
1437 return;
1438 if (PointsOnBoundary.erase(point->Nr))
1439 cout << Verbose(5) << "Removing point Nr. " << point->Nr << "." << endl;
1440 delete(point);
1441};
1442
1443/** Checks whether the triangle consisting of the three points is already present.
1444 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1445 * lines. If any of the three edges already has two triangles attached, false is
1446 * returned.
1447 * \param *out output stream for debugging
1448 * \param *Candidates endpoints of the triangle candidate
1449 * \return integer 0 if no triangle exists, 1 if one triangle exists, 2 if two
1450 * triangles exist which is the maximum for three points
1451 */
1452int Tesselation::CheckPresenceOfTriangle(ofstream *out, TesselPoint *Candidates[3]) {
1453 int adjacentTriangleCount = 0;
1454 class BoundaryPointSet *Points[3];
1455
1456 *out << Verbose(2) << "Begin of CheckPresenceOfTriangle" << endl;
1457 // builds a triangle point set (Points) of the end points
1458 for (int i = 0; i < 3; i++) {
1459 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1460 if (FindPoint != PointsOnBoundary.end()) {
1461 Points[i] = FindPoint->second;
1462 } else {
1463 Points[i] = NULL;
1464 }
1465 }
1466
1467 // checks lines between the points in the Points for their adjacent triangles
1468 for (int i = 0; i < 3; i++) {
1469 if (Points[i] != NULL) {
1470 for (int j = i; j < 3; j++) {
1471 if (Points[j] != NULL) {
1472 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1473 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1474 TriangleMap *triangles = &FindLine->second->triangles;
1475 *out << Verbose(3) << "Current line is " << FindLine->first << ": " << *(FindLine->second) << " with triangles " << triangles << "." << endl;
1476 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1477 if (FindTriangle->second->IsPresentTupel(Points)) {
1478 adjacentTriangleCount++;
1479 }
1480 }
1481 *out << Verbose(3) << "end." << endl;
1482 }
1483 // Only one of the triangle lines must be considered for the triangle count.
1484 //*out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1485 //return adjacentTriangleCount;
1486 }
1487 }
1488 }
1489 }
1490
1491 *out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1492 *out << Verbose(2) << "End of CheckPresenceOfTriangle" << endl;
1493 return adjacentTriangleCount;
1494};
1495
1496/** Checks whether the triangle consisting of the three points is already present.
1497 * Searches for the points in Tesselation::PointsOnBoundary and checks their
1498 * lines. If any of the three edges already has two triangles attached, false is
1499 * returned.
1500 * \param *out output stream for debugging
1501 * \param *Candidates endpoints of the triangle candidate
1502 * \return NULL - none found or pointer to triangle
1503 */
1504class BoundaryTriangleSet * Tesselation::GetPresentTriangle(ofstream *out, TesselPoint *Candidates[3])
1505{
1506 class BoundaryTriangleSet *triangle = NULL;
1507 class BoundaryPointSet *Points[3];
1508
1509 // builds a triangle point set (Points) of the end points
1510 for (int i = 0; i < 3; i++) {
1511 PointMap::iterator FindPoint = PointsOnBoundary.find(Candidates[i]->nr);
1512 if (FindPoint != PointsOnBoundary.end()) {
1513 Points[i] = FindPoint->second;
1514 } else {
1515 Points[i] = NULL;
1516 }
1517 }
1518
1519 // checks lines between the points in the Points for their adjacent triangles
1520 for (int i = 0; i < 3; i++) {
1521 if (Points[i] != NULL) {
1522 for (int j = i; j < 3; j++) {
1523 if (Points[j] != NULL) {
1524 LineMap::iterator FindLine = Points[i]->lines.find(Points[j]->node->nr);
1525 for (; (FindLine != Points[i]->lines.end()) && (FindLine->first == Points[j]->node->nr); FindLine++) {
1526 TriangleMap *triangles = &FindLine->second->triangles;
1527 for (TriangleMap::iterator FindTriangle = triangles->begin(); FindTriangle != triangles->end(); FindTriangle++) {
1528 if (FindTriangle->second->IsPresentTupel(Points)) {
1529 if ((triangle == NULL) || (triangle->Nr > FindTriangle->second->Nr))
1530 triangle = FindTriangle->second;
1531 }
1532 }
1533 }
1534 // Only one of the triangle lines must be considered for the triangle count.
1535 //*out << Verbose(2) << "Found " << adjacentTriangleCount << " adjacent triangles for the point set." << endl;
1536 //return adjacentTriangleCount;
1537 }
1538 }
1539 }
1540 }
1541
1542 return triangle;
1543};
1544
1545
1546/** Finds the starting triangle for FindNonConvexBorder().
1547 * Looks at the outermost point per axis, then FindSecondPointForTesselation()
1548 * for the second and FindNextSuitablePointViaAngleOfSphere() for the third
1549 * point are called.
1550 * \param *out output stream for debugging
1551 * \param RADIUS radius of virtual rolling sphere
1552 * \param *LC LinkedCell structure with neighbouring TesselPoint's
1553 */
1554void Tesselation::FindStartingTriangle(ofstream *out, const double RADIUS, LinkedCell *LC)
1555{
1556 cout << Verbose(1) << "Begin of FindStartingTriangle\n";
1557 int i = 0;
1558 LinkedNodes *List = NULL;
1559 TesselPoint* FirstPoint = NULL;
1560 TesselPoint* SecondPoint = NULL;
1561 TesselPoint* MaxPoint[NDIM];
1562 double maxCoordinate[NDIM];
1563 Vector Oben;
1564 Vector helper;
1565 Vector Chord;
1566 Vector SearchDirection;
1567
1568 Oben.Zero();
1569
1570 for (i = 0; i < 3; i++) {
1571 MaxPoint[i] = NULL;
1572 maxCoordinate[i] = -1;
1573 }
1574
1575 // 1. searching topmost point with respect to each axis
1576 for (int i=0;i<NDIM;i++) { // each axis
1577 LC->n[i] = LC->N[i]-1; // current axis is topmost cell
1578 for (LC->n[(i+1)%NDIM]=0;LC->n[(i+1)%NDIM]<LC->N[(i+1)%NDIM];LC->n[(i+1)%NDIM]++)
1579 for (LC->n[(i+2)%NDIM]=0;LC->n[(i+2)%NDIM]<LC->N[(i+2)%NDIM];LC->n[(i+2)%NDIM]++) {
1580 List = LC->GetCurrentCell();
1581 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
1582 if (List != NULL) {
1583 for (LinkedNodes::iterator Runner = List->begin();Runner != List->end();Runner++) {
1584 if ((*Runner)->node->x[i] > maxCoordinate[i]) {
1585 cout << Verbose(2) << "New maximal for axis " << i << " node is " << *(*Runner) << " at " << *(*Runner)->node << "." << endl;
1586 maxCoordinate[i] = (*Runner)->node->x[i];
1587 MaxPoint[i] = (*Runner);
1588 }
1589 }
1590 } else {
1591 cerr << "ERROR: The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!" << endl;
1592 }
1593 }
1594 }
1595
1596 cout << Verbose(2) << "Found maximum coordinates: ";
1597 for (int i=0;i<NDIM;i++)
1598 cout << i << ": " << *MaxPoint[i] << "\t";
1599 cout << endl;
1600
1601 BTS = NULL;
1602 CandidateList *OptCandidates = new CandidateList();
1603 for (int k=0;k<NDIM;k++) {
1604 Oben.Zero();
1605 Oben.x[k] = 1.;
1606 FirstPoint = MaxPoint[k];
1607 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1608
1609 double ShortestAngle;
1610 TesselPoint* OptCandidate = NULL;
1611 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.
1612
1613 FindSecondPointForTesselation(FirstPoint, Oben, OptCandidate, &ShortestAngle, RADIUS, LC); // we give same point as next candidate as its bonds are looked into in find_second_...
1614 SecondPoint = OptCandidate;
1615 if (SecondPoint == NULL) // have we found a second point?
1616 continue;
1617
1618 helper.CopyVector(FirstPoint->node);
1619 helper.SubtractVector(SecondPoint->node);
1620 helper.Normalize();
1621 Oben.ProjectOntoPlane(&helper);
1622 Oben.Normalize();
1623 helper.VectorProduct(&Oben);
1624 ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1625
1626 Chord.CopyVector(FirstPoint->node); // bring into calling function
1627 Chord.SubtractVector(SecondPoint->node);
1628 double radius = Chord.ScalarProduct(&Chord);
1629 double CircleRadius = sqrt(RADIUS*RADIUS - radius/4.);
1630 helper.CopyVector(&Oben);
1631 helper.Scale(CircleRadius);
1632 // Now, oben and helper are two orthonormalized vectors in the plane defined by Chord (not normalized)
1633
1634 // look in one direction of baseline for initial candidate
1635 SearchDirection.MakeNormalVector(&Chord, &Oben); // whether we look "left" first or "right" first is not important ...
1636
1637 // adding point 1 and point 2 and add the line between them
1638 cout << Verbose(1) << "Coordinates of start node at " << *FirstPoint->node << "." << endl;
1639 AddTesselationPoint(FirstPoint, 0);
1640 cout << Verbose(1) << "Found second point is at " << *SecondPoint->node << ".\n";
1641 AddTesselationPoint(SecondPoint, 1);
1642 AddTesselationLine(TPS[0], TPS[1], 0);
1643
1644 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << helper << ".\n";
1645 FindThirdPointForTesselation(
1646 Oben, SearchDirection, helper, BLS[0], NULL, *&OptCandidates, &ShortestAngle, RADIUS, LC
1647 );
1648 cout << Verbose(1) << "List of third Points is ";
1649 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1650 cout << " " << *(*it)->point;
1651 }
1652 cout << endl;
1653
1654 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1655 // add third triangle point
1656 AddTesselationPoint((*it)->point, 2);
1657 // add the second and third line
1658 AddTesselationLine(TPS[1], TPS[2], 1);
1659 AddTesselationLine(TPS[0], TPS[2], 2);
1660 // ... and triangles to the Maps of the Tesselation class
1661 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1662 AddTesselationTriangle();
1663 // ... and calculate its normal vector (with correct orientation)
1664 (*it)->OptCenter.Scale(-1.);
1665 cout << Verbose(2) << "Anti-Oben is currently " << (*it)->OptCenter << "." << endl;
1666 BTS->GetNormalVector((*it)->OptCenter); // vector to compare with should point inwards
1667 cout << Verbose(0) << "==> Found starting triangle consists of " << *FirstPoint << ", " << *SecondPoint << " and "
1668 << *(*it)->point << " with normal vector " << BTS->NormalVector << ".\n";
1669
1670 // if we do not reach the end with the next step of iteration, we need to setup a new first line
1671 if (it != OptCandidates->end()--) {
1672 FirstPoint = (*it)->BaseLine->endpoints[0]->node;
1673 SecondPoint = (*it)->point;
1674 // adding point 1 and point 2 and the line between them
1675 AddTesselationPoint(FirstPoint, 0);
1676 AddTesselationPoint(SecondPoint, 1);
1677 AddTesselationLine(TPS[0], TPS[1], 0);
1678 }
1679 cout << Verbose(2) << "Projection is " << BTS->NormalVector.ScalarProduct(&Oben) << "." << endl;
1680 }
1681 if (BTS != NULL) // we have created one starting triangle
1682 break;
1683 else {
1684 // remove all candidates from the list and then the list itself
1685 class CandidateForTesselation *remover = NULL;
1686 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1687 remover = *it;
1688 delete(remover);
1689 }
1690 OptCandidates->clear();
1691 }
1692 }
1693
1694 // remove all candidates from the list and then the list itself
1695 class CandidateForTesselation *remover = NULL;
1696 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1697 remover = *it;
1698 delete(remover);
1699 }
1700 delete(OptCandidates);
1701 cout << Verbose(1) << "End of FindStartingTriangle\n";
1702};
1703
1704
1705/** This function finds a triangle to a line, adjacent to an existing one.
1706 * @param out output stream for debugging
1707 * @param Line current baseline to search from
1708 * @param T current triangle which \a Line is edge of
1709 * @param RADIUS radius of the rolling ball
1710 * @param N number of found triangles
1711 * @param *LC LinkedCell structure with neighbouring points
1712 */
1713bool Tesselation::FindNextSuitableTriangle(ofstream *out, BoundaryLineSet &Line, BoundaryTriangleSet &T, const double& RADIUS, LinkedCell *LC)
1714{
1715 cout << Verbose(0) << "Begin of FindNextSuitableTriangle\n";
1716 bool result = true;
1717 CandidateList *OptCandidates = new CandidateList();
1718
1719 Vector CircleCenter;
1720 Vector CirclePlaneNormal;
1721 Vector OldSphereCenter;
1722 Vector SearchDirection;
1723 Vector helper;
1724 TesselPoint *ThirdNode = NULL;
1725 LineMap::iterator testline;
1726 double ShortestAngle = 2.*M_PI; // This will indicate the quadrant.
1727 double radius, CircleRadius;
1728
1729 cout << Verbose(1) << "Current baseline is " << Line << " of triangle " << T << "." << endl;
1730 for (int i=0;i<3;i++)
1731 if ((T.endpoints[i]->node != Line.endpoints[0]->node) && (T.endpoints[i]->node != Line.endpoints[1]->node))
1732 ThirdNode = T.endpoints[i]->node;
1733
1734 // construct center of circle
1735 CircleCenter.CopyVector(Line.endpoints[0]->node->node);
1736 CircleCenter.AddVector(Line.endpoints[1]->node->node);
1737 CircleCenter.Scale(0.5);
1738
1739 // construct normal vector of circle
1740 CirclePlaneNormal.CopyVector(Line.endpoints[0]->node->node);
1741 CirclePlaneNormal.SubtractVector(Line.endpoints[1]->node->node);
1742
1743 // calculate squared radius of circle
1744 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
1745 if (radius/4. < RADIUS*RADIUS) {
1746 CircleRadius = RADIUS*RADIUS - radius/4.;
1747 CirclePlaneNormal.Normalize();
1748 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
1749
1750 // construct old center
1751 GetCenterofCircumcircle(&OldSphereCenter, T.endpoints[0]->node->node, T.endpoints[1]->node->node, T.endpoints[2]->node->node);
1752 helper.CopyVector(&T.NormalVector); // normal vector ensures that this is correct center of the two possible ones
1753 radius = Line.endpoints[0]->node->node->DistanceSquared(&OldSphereCenter);
1754 helper.Scale(sqrt(RADIUS*RADIUS - radius));
1755 OldSphereCenter.AddVector(&helper);
1756 OldSphereCenter.SubtractVector(&CircleCenter);
1757 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
1758
1759 // construct SearchDirection
1760 SearchDirection.MakeNormalVector(&T.NormalVector, &CirclePlaneNormal);
1761 helper.CopyVector(Line.endpoints[0]->node->node);
1762 helper.SubtractVector(ThirdNode->node);
1763 if (helper.ScalarProduct(&SearchDirection) < -HULLEPSILON)// ohoh, SearchDirection points inwards!
1764 SearchDirection.Scale(-1.);
1765 SearchDirection.ProjectOntoPlane(&OldSphereCenter);
1766 SearchDirection.Normalize();
1767 cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
1768 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) {
1769 // rotated the wrong way!
1770 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are still not orthogonal!" << endl;
1771 }
1772
1773 // add third point
1774 FindThirdPointForTesselation(
1775 T.NormalVector, SearchDirection, OldSphereCenter, &Line, ThirdNode, OptCandidates,
1776 &ShortestAngle, RADIUS, LC
1777 );
1778
1779 } else {
1780 cout << Verbose(1) << "Circumcircle for base line " << Line << " and base triangle " << T << " is too big!" << endl;
1781 }
1782
1783 if (OptCandidates->begin() == OptCandidates->end()) {
1784 cerr << "WARNING: Could not find a suitable candidate." << endl;
1785 return false;
1786 }
1787 cout << Verbose(1) << "Third Points are ";
1788 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1789 cout << " " << *(*it)->point;
1790 }
1791 cout << endl;
1792
1793 BoundaryLineSet *BaseRay = &Line;
1794 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1795 cout << Verbose(1) << " Third point candidate is " << *(*it)->point
1796 << " with circumsphere's center at " << (*it)->OptCenter << "." << endl;
1797 cout << Verbose(1) << " Baseline is " << *BaseRay << endl;
1798
1799 // check whether all edges of the new triangle still have space for one more triangle (i.e. TriangleCount <2)
1800 TesselPoint *PointCandidates[3];
1801 PointCandidates[0] = (*it)->point;
1802 PointCandidates[1] = BaseRay->endpoints[0]->node;
1803 PointCandidates[2] = BaseRay->endpoints[1]->node;
1804 int existentTrianglesCount = CheckPresenceOfTriangle(out, PointCandidates);
1805
1806 BTS = NULL;
1807 // If there is no triangle, add it regularly.
1808 if (existentTrianglesCount == 0) {
1809 AddTesselationPoint((*it)->point, 0);
1810 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1811 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1812
1813 if (CheckLineCriteriaForDegeneratedTriangle(TPS)) {
1814 AddTesselationLine(TPS[0], TPS[1], 0);
1815 AddTesselationLine(TPS[0], TPS[2], 1);
1816 AddTesselationLine(TPS[1], TPS[2], 2);
1817
1818 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1819 AddTesselationTriangle();
1820 (*it)->OptCenter.Scale(-1.);
1821 BTS->GetNormalVector((*it)->OptCenter);
1822 (*it)->OptCenter.Scale(-1.);
1823
1824 cout << "--> New triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1825 << " for this triangle ... " << endl;
1826 //cout << Verbose(1) << "We have "<< TrianglesOnBoundaryCount << " for line " << *BaseRay << "." << endl;
1827 } else {
1828 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1829 cout << *(*it)->point << ", ";
1830 cout << *BaseRay->endpoints[0]->node << " and ";
1831 cout << *BaseRay->endpoints[1]->node << " ";
1832 cout << "exists and is not added, as it does not seem helpful!" << endl;
1833 result = false;
1834 }
1835 } else if ((existentTrianglesCount >= 1) && (existentTrianglesCount <= 3)) { // If there is a planar region within the structure, we need this triangle a second time.
1836 AddTesselationPoint((*it)->point, 0);
1837 AddTesselationPoint(BaseRay->endpoints[0]->node, 1);
1838 AddTesselationPoint(BaseRay->endpoints[1]->node, 2);
1839
1840 // 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)
1841 // i.e. at least one of the three lines must be present with TriangleCount <= 1
1842 if (CheckLineCriteriaForDegeneratedTriangle(TPS)) {
1843 AddTesselationLine(TPS[0], TPS[1], 0);
1844 AddTesselationLine(TPS[0], TPS[2], 1);
1845 AddTesselationLine(TPS[1], TPS[2], 2);
1846
1847 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
1848 AddTesselationTriangle(); // add to global map
1849
1850 (*it)->OtherOptCenter.Scale(-1.);
1851 BTS->GetNormalVector((*it)->OtherOptCenter);
1852 (*it)->OtherOptCenter.Scale(-1.);
1853
1854 cout << "--> WARNING: Special new triangle with " << *BTS << " and normal vector " << BTS->NormalVector
1855 << " for this triangle ... " << endl;
1856 cout << Verbose(1) << "We have "<< BaseRay->triangles.size() << " for line " << BaseRay << "." << endl;
1857 } else {
1858 cout << Verbose(1) << "WARNING: This triangle consisting of ";
1859 cout << *(*it)->point << ", ";
1860 cout << *BaseRay->endpoints[0]->node << " and ";
1861 cout << *BaseRay->endpoints[1]->node << " ";
1862 cout << "exists and is not added, as it does not seem helpful!" << endl;
1863 result = false;
1864 }
1865 } else {
1866 cout << Verbose(1) << "This triangle consisting of ";
1867 cout << *(*it)->point << ", ";
1868 cout << *BaseRay->endpoints[0]->node << " and ";
1869 cout << *BaseRay->endpoints[1]->node << " ";
1870 cout << "is invalid!" << endl;
1871 result = false;
1872 }
1873
1874 // set baseline to new ray from ref point (here endpoints[0]->node) to current candidate (here (*it)->point))
1875 BaseRay = BLS[0];
1876 if ((BTS != NULL) && (BTS->NormalVector.NormSquared() < MYEPSILON)) {
1877 *out << Verbose(1) << "CRITICAL: Triangle " << *BTS << " has zero normal vector!" << endl;
1878 exit(255);
1879 }
1880
1881 }
1882
1883 // remove all candidates from the list and then the list itself
1884 class CandidateForTesselation *remover = NULL;
1885 for (CandidateList::iterator it = OptCandidates->begin(); it != OptCandidates->end(); ++it) {
1886 remover = *it;
1887 delete(remover);
1888 }
1889 delete(OptCandidates);
1890 cout << Verbose(0) << "End of FindNextSuitableTriangle\n";
1891 return result;
1892};
1893
1894/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
1895 * We look whether the closest point on \a *Base with respect to the other baseline is outside
1896 * of the segment formed by both endpoints (concave) or not (convex).
1897 * \param *out output stream for debugging
1898 * \param *Base line to be flipped
1899 * \return NULL - convex, otherwise endpoint that makes it concave
1900 */
1901class BoundaryPointSet *Tesselation::IsConvexRectangle(ofstream *out, class BoundaryLineSet *Base)
1902{
1903 class BoundaryPointSet *Spot = NULL;
1904 class BoundaryLineSet *OtherBase;
1905 Vector *ClosestPoint;
1906
1907 int m=0;
1908 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1909 for (int j=0;j<3;j++) // all of their endpoints and baselines
1910 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1911 BPS[m++] = runner->second->endpoints[j];
1912 OtherBase = new class BoundaryLineSet(BPS,-1);
1913
1914 *out << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
1915 *out << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
1916
1917 // get the closest point on each line to the other line
1918 ClosestPoint = GetClosestPointBetweenLine(out, Base, OtherBase);
1919
1920 // delete the temporary other base line
1921 delete(OtherBase);
1922
1923 // get the distance vector from Base line to OtherBase line
1924 Vector DistanceToIntersection[2], BaseLine;
1925 double distance[2];
1926 BaseLine.CopyVector(Base->endpoints[1]->node->node);
1927 BaseLine.SubtractVector(Base->endpoints[0]->node->node);
1928 for (int i=0;i<2;i++) {
1929 DistanceToIntersection[i].CopyVector(ClosestPoint);
1930 DistanceToIntersection[i].SubtractVector(Base->endpoints[i]->node->node);
1931 distance[i] = BaseLine.ScalarProduct(&DistanceToIntersection[i]);
1932 }
1933 delete(ClosestPoint);
1934 if ((distance[0] * distance[1]) > 0) { // have same sign?
1935 *out << Verbose(3) << "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave." << endl;
1936 if (distance[0] < distance[1]) {
1937 Spot = Base->endpoints[0];
1938 } else {
1939 Spot = Base->endpoints[1];
1940 }
1941 return Spot;
1942 } else { // different sign, i.e. we are in between
1943 *out << Verbose(3) << "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex." << endl;
1944 return NULL;
1945 }
1946
1947};
1948
1949void Tesselation::PrintAllBoundaryPoints(ofstream *out)
1950{
1951 // print all lines
1952 *out << Verbose(1) << "Printing all boundary points for debugging:" << endl;
1953 for (PointMap::iterator PointRunner = PointsOnBoundary.begin();PointRunner != PointsOnBoundary.end(); PointRunner++)
1954 *out << Verbose(2) << *(PointRunner->second) << endl;
1955};
1956
1957void Tesselation::PrintAllBoundaryLines(ofstream *out)
1958{
1959 // print all lines
1960 *out << Verbose(1) << "Printing all boundary lines for debugging:" << endl;
1961 for (LineMap::iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
1962 *out << Verbose(2) << *(LineRunner->second) << endl;
1963};
1964
1965void Tesselation::PrintAllBoundaryTriangles(ofstream *out)
1966{
1967 // print all triangles
1968 *out << Verbose(1) << "Printing all boundary triangles for debugging:" << endl;
1969 for (TriangleMap::iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
1970 *out << Verbose(2) << *(TriangleRunner->second) << endl;
1971};
1972
1973/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
1974 * \param *out output stream for debugging
1975 * \param *Base line to be flipped
1976 * \return volume change due to flipping (0 - then no flipped occured)
1977 */
1978double Tesselation::PickFarthestofTwoBaselines(ofstream *out, class BoundaryLineSet *Base)
1979{
1980 class BoundaryLineSet *OtherBase;
1981 Vector *ClosestPoint[2];
1982 double volume;
1983
1984 int m=0;
1985 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1986 for (int j=0;j<3;j++) // all of their endpoints and baselines
1987 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1988 BPS[m++] = runner->second->endpoints[j];
1989 OtherBase = new class BoundaryLineSet(BPS,-1);
1990
1991 *out << Verbose(3) << "INFO: Current base line is " << *Base << "." << endl;
1992 *out << Verbose(3) << "INFO: Other base line is " << *OtherBase << "." << endl;
1993
1994 // get the closest point on each line to the other line
1995 ClosestPoint[0] = GetClosestPointBetweenLine(out, Base, OtherBase);
1996 ClosestPoint[1] = GetClosestPointBetweenLine(out, OtherBase, Base);
1997
1998 // get the distance vector from Base line to OtherBase line
1999 Vector Distance;
2000 Distance.CopyVector(ClosestPoint[1]);
2001 Distance.SubtractVector(ClosestPoint[0]);
2002
2003 // calculate volume
2004 volume = CalculateVolumeofGeneralTetraeder(Base->endpoints[1]->node->node, OtherBase->endpoints[0]->node->node, OtherBase->endpoints[1]->node->node, Base->endpoints[0]->node->node);
2005
2006 // delete the temporary other base line and the closest points
2007 delete(ClosestPoint[0]);
2008 delete(ClosestPoint[1]);
2009 delete(OtherBase);
2010
2011 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
2012 *out << Verbose(3) << "REJECT: Both lines have an intersection: Nothing to do." << endl;
2013 return false;
2014 } else { // check for sign against BaseLineNormal
2015 Vector BaseLineNormal;
2016 BaseLineNormal.Zero();
2017 if (Base->triangles.size() < 2) {
2018 *out << Verbose(2) << "ERROR: Less than two triangles are attached to this baseline!" << endl;
2019 return 0.;
2020 }
2021 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2022 *out << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2023 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2024 }
2025 BaseLineNormal.Scale(1./2.);
2026
2027 if (Distance.ScalarProduct(&BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
2028 *out << Verbose(2) << "ACCEPT: Other base line would be higher: Flipping baseline." << endl;
2029 // calculate volume summand as a general tetraeder
2030 return volume;
2031 } else { // Base higher than OtherBase -> do nothing
2032 *out << Verbose(2) << "REJECT: Base line is higher: Nothing to do." << endl;
2033 return 0.;
2034 }
2035 }
2036};
2037
2038/** For a given baseline and its two connected triangles, flips the baseline.
2039 * I.e. we create the new baseline between the other two endpoints of these four
2040 * endpoints and reconstruct the two triangles accordingly.
2041 * \param *out output stream for debugging
2042 * \param *Base line to be flipped
2043 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
2044 */
2045class BoundaryLineSet * Tesselation::FlipBaseline(ofstream *out, class BoundaryLineSet *Base)
2046{
2047 class BoundaryLineSet *OldLines[4], *NewLine;
2048 class BoundaryPointSet *OldPoints[2];
2049 Vector BaseLineNormal;
2050 int OldTriangleNrs[2], OldBaseLineNr;
2051 int i,m;
2052
2053 *out << Verbose(1) << "Begin of FlipBaseline" << endl;
2054
2055 // calculate NormalVector for later use
2056 BaseLineNormal.Zero();
2057 if (Base->triangles.size() < 2) {
2058 *out << Verbose(2) << "ERROR: Less than two triangles are attached to this baseline!" << endl;
2059 return NULL;
2060 }
2061 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2062 *out << Verbose(4) << "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << "." << endl;
2063 BaseLineNormal.AddVector(&(runner->second->NormalVector));
2064 }
2065 BaseLineNormal.Scale(-1./2.); // has to point inside for BoundaryTriangleSet::GetNormalVector()
2066
2067 // get the two triangles
2068 // gather four endpoints and four lines
2069 for (int j=0;j<4;j++)
2070 OldLines[j] = NULL;
2071 for (int j=0;j<2;j++)
2072 OldPoints[j] = NULL;
2073 i=0;
2074 m=0;
2075 *out << Verbose(3) << "The four old lines are: ";
2076 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2077 for (int j=0;j<3;j++) // all of their endpoints and baselines
2078 if (runner->second->lines[j] != Base) { // pick not the central baseline
2079 OldLines[i++] = runner->second->lines[j];
2080 *out << *runner->second->lines[j] << "\t";
2081 }
2082 *out << endl;
2083 *out << Verbose(3) << "The two old points are: ";
2084 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
2085 for (int j=0;j<3;j++) // all of their endpoints and baselines
2086 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) { // and neither of its endpoints
2087 OldPoints[m++] = runner->second->endpoints[j];
2088 *out << *runner->second->endpoints[j] << "\t";
2089 }
2090 *out << endl;
2091
2092 // check whether everything is in place to create new lines and triangles
2093 if (i<4) {
2094 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
2095 return NULL;
2096 }
2097 for (int j=0;j<4;j++)
2098 if (OldLines[j] == NULL) {
2099 *out << Verbose(1) << "ERROR: We have not gathered enough baselines!" << endl;
2100 return NULL;
2101 }
2102 for (int j=0;j<2;j++)
2103 if (OldPoints[j] == NULL) {
2104 *out << Verbose(1) << "ERROR: We have not gathered enough endpoints!" << endl;
2105 return NULL;
2106 }
2107
2108 // remove triangles and baseline removes itself
2109 *out << Verbose(3) << "INFO: Deleting baseline " << *Base << " from global list." << endl;
2110 OldBaseLineNr = Base->Nr;
2111 m=0;
2112 for(TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
2113 *out << Verbose(3) << "INFO: Deleting triangle " << *(runner->second) << "." << endl;
2114 OldTriangleNrs[m++] = runner->second->Nr;
2115 RemoveTesselationTriangle(runner->second);
2116 }
2117
2118 // construct new baseline (with same number as old one)
2119 BPS[0] = OldPoints[0];
2120 BPS[1] = OldPoints[1];
2121 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2122 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2123 *out << Verbose(3) << "INFO: Created new baseline " << *NewLine << "." << endl;
2124
2125 // construct new triangles with flipped baseline
2126 i=-1;
2127 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2128 i=2;
2129 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2130 i=3;
2131 if (i!=-1) {
2132 BLS[0] = OldLines[0];
2133 BLS[1] = OldLines[i];
2134 BLS[2] = NewLine;
2135 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2136 BTS->GetNormalVector(BaseLineNormal);
2137 AddTesselationTriangle(OldTriangleNrs[0]);
2138 *out << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2139
2140 BLS[0] = (i==2 ? OldLines[3] : OldLines[2]);
2141 BLS[1] = OldLines[1];
2142 BLS[2] = NewLine;
2143 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2144 BTS->GetNormalVector(BaseLineNormal);
2145 AddTesselationTriangle(OldTriangleNrs[1]);
2146 *out << Verbose(3) << "INFO: Created new triangle " << *BTS << "." << endl;
2147 } else {
2148 *out << Verbose(1) << "The four old lines do not connect, something's utterly wrong here!" << endl;
2149 return NULL;
2150 }
2151
2152 *out << Verbose(1) << "End of FlipBaseline" << endl;
2153 return NewLine;
2154};
2155
2156
2157/** Finds the second point of starting triangle.
2158 * \param *a first node
2159 * \param Oben vector indicating the outside
2160 * \param OptCandidate reference to recommended candidate on return
2161 * \param Storage[3] array storing angles and other candidate information
2162 * \param RADIUS radius of virtual sphere
2163 * \param *LC LinkedCell structure with neighbouring points
2164 */
2165void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, LinkedCell *LC)
2166{
2167 cout << Verbose(2) << "Begin of FindSecondPointForTesselation" << endl;
2168 Vector AngleCheck;
2169 class TesselPoint* Candidate = NULL;
2170 double norm = -1., angle;
2171 LinkedNodes *List = NULL;
2172 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2173
2174 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2175 for(int i=0;i<NDIM;i++) // store indices of this cell
2176 N[i] = LC->n[i];
2177 } else {
2178 cerr << "ERROR: Point " << *a << " is not found in cell " << LC->index << "." << endl;
2179 return;
2180 }
2181 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2182 cout << Verbose(3) << "LC Intervals from [";
2183 for (int i=0;i<NDIM;i++) {
2184 cout << " " << N[i] << "<->" << LC->N[i];
2185 }
2186 cout << "] :";
2187 for (int i=0;i<NDIM;i++) {
2188 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2189 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2190 cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2191 }
2192 cout << endl;
2193
2194
2195 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2196 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2197 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2198 List = LC->GetCurrentCell();
2199 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2200 if (List != NULL) {
2201 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2202 Candidate = (*Runner);
2203 // check if we only have one unique point yet ...
2204 if (a != Candidate) {
2205 // Calculate center of the circle with radius RADIUS through points a and Candidate
2206 Vector OrthogonalizedOben, aCandidate, Center;
2207 double distance, scaleFactor;
2208
2209 OrthogonalizedOben.CopyVector(&Oben);
2210 aCandidate.CopyVector(a->node);
2211 aCandidate.SubtractVector(Candidate->node);
2212 OrthogonalizedOben.ProjectOntoPlane(&aCandidate);
2213 OrthogonalizedOben.Normalize();
2214 distance = 0.5 * aCandidate.Norm();
2215 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2216 OrthogonalizedOben.Scale(scaleFactor);
2217
2218 Center.CopyVector(Candidate->node);
2219 Center.AddVector(a->node);
2220 Center.Scale(0.5);
2221 Center.AddVector(&OrthogonalizedOben);
2222
2223 AngleCheck.CopyVector(&Center);
2224 AngleCheck.SubtractVector(a->node);
2225 norm = aCandidate.Norm();
2226 // second point shall have smallest angle with respect to Oben vector
2227 if (norm < RADIUS*2.) {
2228 angle = AngleCheck.Angle(&Oben);
2229 if (angle < Storage[0]) {
2230 //cout << Verbose(3) << "Old values of Storage: %lf %lf \n", Storage[0], Storage[1]);
2231 cout << Verbose(3) << "Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".\n";
2232 OptCandidate = Candidate;
2233 Storage[0] = angle;
2234 //cout << Verbose(3) << "Changing something in Storage: %lf %lf. \n", Storage[0], Storage[2]);
2235 } else {
2236 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate << endl;
2237 }
2238 } else {
2239 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Refused due to Radius " << norm << endl;
2240 }
2241 } else {
2242 //cout << Verbose(3) << "Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << "." << endl;
2243 }
2244 }
2245 } else {
2246 cout << Verbose(3) << "Linked cell list is empty." << endl;
2247 }
2248 }
2249 cout << Verbose(2) << "End of FindSecondPointForTesselation" << endl;
2250};
2251
2252
2253/** This recursive function finds a third point, to form a triangle with two given ones.
2254 * Note that this function is for the starting triangle.
2255 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2256 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2257 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2258 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2259 * us the "null" on this circle, the new center of the candidate point will be some way along this
2260 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2261 * by the normal vector of the base triangle that always points outwards by construction.
2262 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2263 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2264 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2265 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2266 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2267 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2268 * both.
2269 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2270 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2271 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2272 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2273 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2274 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2275 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2276 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2277 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2278 * @param BaseLine BoundaryLineSet with the current base line
2279 * @param ThirdNode third point to avoid in search
2280 * @param candidates list of equally good candidates to return
2281 * @param ShortestAngle the current path length on this circle band for the current OptCandidate
2282 * @param RADIUS radius of sphere
2283 * @param *LC LinkedCell structure with neighbouring points
2284 */
2285void Tesselation::FindThirdPointForTesselation(Vector NormalVector, Vector SearchDirection, Vector OldSphereCenter, class BoundaryLineSet *BaseLine, class TesselPoint *ThirdNode, CandidateList* &candidates, double *ShortestAngle, const double RADIUS, LinkedCell *LC)
2286{
2287 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2288 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2289 Vector SphereCenter;
2290 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2291 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2292 Vector NewNormalVector; // normal vector of the Candidate's triangle
2293 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2294 LinkedNodes *List = NULL;
2295 double CircleRadius; // radius of this circle
2296 double radius;
2297 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2298 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2299 TesselPoint *Candidate = NULL;
2300 CandidateForTesselation *optCandidate = NULL;
2301
2302 cout << Verbose(1) << "Begin of FindThirdPointForTesselation" << endl;
2303
2304 cout << Verbose(2) << "INFO: NormalVector of BaseTriangle is " << NormalVector << "." << endl;
2305
2306 // construct center of circle
2307 CircleCenter.CopyVector(BaseLine->endpoints[0]->node->node);
2308 CircleCenter.AddVector(BaseLine->endpoints[1]->node->node);
2309 CircleCenter.Scale(0.5);
2310
2311 // construct normal vector of circle
2312 CirclePlaneNormal.CopyVector(BaseLine->endpoints[0]->node->node);
2313 CirclePlaneNormal.SubtractVector(BaseLine->endpoints[1]->node->node);
2314
2315 // calculate squared radius TesselPoint *ThirdNode,f circle
2316 radius = CirclePlaneNormal.ScalarProduct(&CirclePlaneNormal);
2317 if (radius/4. < RADIUS*RADIUS) {
2318 CircleRadius = RADIUS*RADIUS - radius/4.;
2319 CirclePlaneNormal.Normalize();
2320 //cout << Verbose(2) << "INFO: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << "." << endl;
2321
2322 // test whether old center is on the band's plane
2323 if (fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) > HULLEPSILON) {
2324 cerr << "ERROR: Something's very wrong here: OldSphereCenter is not on the band's plane as desired by " << fabs(OldSphereCenter.ScalarProduct(&CirclePlaneNormal)) << "!" << endl;
2325 OldSphereCenter.ProjectOntoPlane(&CirclePlaneNormal);
2326 }
2327 radius = OldSphereCenter.ScalarProduct(&OldSphereCenter);
2328 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2329 //cout << Verbose(2) << "INFO: OldSphereCenter is at " << OldSphereCenter << "." << endl;
2330
2331 // check SearchDirection
2332 //cout << Verbose(2) << "INFO: SearchDirection is " << SearchDirection << "." << endl;
2333 if (fabs(OldSphereCenter.ScalarProduct(&SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2334 cerr << "ERROR: SearchDirection and RelativeOldSphereCenter are not orthogonal!" << endl;
2335 }
2336
2337 // get cell for the starting point
2338 if (LC->SetIndexToVector(&CircleCenter)) {
2339 for(int i=0;i<NDIM;i++) // store indices of this cell
2340 N[i] = LC->n[i];
2341 //cout << Verbose(2) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl;
2342 } else {
2343 cerr << "ERROR: Vector " << CircleCenter << " is outside of LinkedCell's bounding box." << endl;
2344 return;
2345 }
2346 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2347 //cout << Verbose(2) << "LC Intervals:";
2348 for (int i=0;i<NDIM;i++) {
2349 Nlower[i] = ((N[i]-1) >= 0) ? N[i]-1 : 0;
2350 Nupper[i] = ((N[i]+1) < LC->N[i]) ? N[i]+1 : LC->N[i]-1;
2351 //cout << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2352 }
2353 //cout << endl;
2354 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2355 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2356 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2357 List = LC->GetCurrentCell();
2358 //cout << Verbose(2) << "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << "." << endl;
2359 if (List != NULL) {
2360 for (LinkedNodes::iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2361 Candidate = (*Runner);
2362
2363 // check for three unique points
2364 //cout << Verbose(2) << "INFO: Current Candidate is " << *Candidate << " at " << Candidate->node << "." << endl;
2365 if ((Candidate != BaseLine->endpoints[0]->node) && (Candidate != BaseLine->endpoints[1]->node) ){
2366
2367 // construct both new centers
2368 GetCenterofCircumcircle(&NewSphereCenter, BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node);
2369 OtherNewSphereCenter.CopyVector(&NewSphereCenter);
2370
2371 if ((NewNormalVector.MakeNormalVector(BaseLine->endpoints[0]->node->node, BaseLine->endpoints[1]->node->node, Candidate->node))
2372 && (fabs(NewNormalVector.ScalarProduct(&NewNormalVector)) > HULLEPSILON)
2373 ) {
2374 helper.CopyVector(&NewNormalVector);
2375 //cout << Verbose(2) << "INFO: NewNormalVector is " << NewNormalVector << "." << endl;
2376 radius = BaseLine->endpoints[0]->node->node->DistanceSquared(&NewSphereCenter);
2377 if (radius < RADIUS*RADIUS) {
2378 helper.Scale(sqrt(RADIUS*RADIUS - radius));
2379 //cout << Verbose(2) << "INFO: Distance of NewCircleCenter to NewSphereCenter is " << helper.Norm() << " with sphere radius " << RADIUS << "." << endl;
2380 NewSphereCenter.AddVector(&helper);
2381 NewSphereCenter.SubtractVector(&CircleCenter);
2382 //cout << Verbose(2) << "INFO: NewSphereCenter is at " << NewSphereCenter << "." << endl;
2383
2384 // OtherNewSphereCenter is created by the same vector just in the other direction
2385 helper.Scale(-1.);
2386 OtherNewSphereCenter.AddVector(&helper);
2387 OtherNewSphereCenter.SubtractVector(&CircleCenter);
2388 //cout << Verbose(2) << "INFO: OtherNewSphereCenter is at " << OtherNewSphereCenter << "." << endl;
2389
2390 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2391 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection);
2392 alpha = min(alpha, Otheralpha);
2393 // if there is a better candidate, drop the current list and add the new candidate
2394 // otherwise ignore the new candidate and keep the list
2395 if (*ShortestAngle > (alpha - HULLEPSILON)) {
2396 optCandidate = new CandidateForTesselation(Candidate, BaseLine, OptCandidateCenter, OtherOptCandidateCenter);
2397 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2398 optCandidate->OptCenter.CopyVector(&NewSphereCenter);
2399 optCandidate->OtherOptCenter.CopyVector(&OtherNewSphereCenter);
2400 } else {
2401 optCandidate->OptCenter.CopyVector(&OtherNewSphereCenter);
2402 optCandidate->OtherOptCenter.CopyVector(&NewSphereCenter);
2403 }
2404 // if there is an equal candidate, add it to the list without clearing the list
2405 if ((*ShortestAngle - HULLEPSILON) < alpha) {
2406 candidates->push_back(optCandidate);
2407 cout << Verbose(2) << "ACCEPT: We have found an equally good candidate: " << *(optCandidate->point) << " with "
2408 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2409 } else {
2410 // remove all candidates from the list and then the list itself
2411 class CandidateForTesselation *remover = NULL;
2412 for (CandidateList::iterator it = candidates->begin(); it != candidates->end(); ++it) {
2413 remover = *it;
2414 delete(remover);
2415 }
2416 candidates->clear();
2417 candidates->push_back(optCandidate);
2418 cout << Verbose(2) << "ACCEPT: We have found a better candidate: " << *(optCandidate->point) << " with "
2419 << alpha << " and circumsphere's center at " << optCandidate->OptCenter << "." << endl;
2420 }
2421 *ShortestAngle = alpha;
2422 //cout << Verbose(2) << "INFO: There are " << candidates->size() << " candidates in the list now." << endl;
2423 } else {
2424 if ((optCandidate != NULL) && (optCandidate->point != NULL)) {
2425 //cout << Verbose(2) << "REJECT: Old candidate " << *(optCandidate->point) << " with " << *ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " ." << endl;
2426 } else {
2427 //cout << Verbose(2) << "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected." << endl;
2428 }
2429 }
2430
2431 } else {
2432 //cout << Verbose(2) << "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << "." << endl;
2433 }
2434 } else {
2435 //cout << Verbose(2) << "REJECT: Three points from " << *BaseLine << " and Candidate " << *Candidate << " are linear-dependent." << endl;
2436 }
2437 } else {
2438 if (ThirdNode != NULL) {
2439 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " and " << *ThirdNode << " contains Candidate " << *Candidate << "." << endl;
2440 } else {
2441 //cout << Verbose(2) << "REJECT: Base triangle " << *BaseLine << " contains Candidate " << *Candidate << "." << endl;
2442 }
2443 }
2444 }
2445 }
2446 }
2447 } else {
2448 cerr << Verbose(2) << "ERROR: The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << "." << endl;
2449 }
2450 } else {
2451 if (ThirdNode != NULL)
2452 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " and third node " << *ThirdNode << " is too big!" << endl;
2453 else
2454 cout << Verbose(2) << "Circumcircle for base line " << *BaseLine << " is too big!" << endl;
2455 }
2456
2457 //cout << Verbose(2) << "INFO: Sorting candidate list ..." << endl;
2458 if (candidates->size() > 1) {
2459 candidates->unique();
2460 candidates->sort(SortCandidates);
2461 }
2462
2463 cout << Verbose(1) << "End of FindThirdPointForTesselation" << endl;
2464};
2465
2466/** Finds the endpoint two lines are sharing.
2467 * \param *line1 first line
2468 * \param *line2 second line
2469 * \return point which is shared or NULL if none
2470 */
2471class BoundaryPointSet *Tesselation::GetCommonEndpoint(class BoundaryLineSet * line1, class BoundaryLineSet * line2)
2472{
2473 class BoundaryLineSet * lines[2] =
2474 { line1, line2 };
2475 class BoundaryPointSet *node = NULL;
2476 map<int, class BoundaryPointSet *> OrderMap;
2477 pair<map<int, class BoundaryPointSet *>::iterator, bool> OrderTest;
2478 for (int i = 0; i < 2; i++)
2479 // for both lines
2480 for (int j = 0; j < 2; j++)
2481 { // for both endpoints
2482 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *> (
2483 lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
2484 if (!OrderTest.second)
2485 { // if insertion fails, we have common endpoint
2486 node = OrderTest.first->second;
2487 cout << Verbose(5) << "Common endpoint of lines " << *line1
2488 << " and " << *line2 << " is: " << *node << "." << endl;
2489 j = 2;
2490 i = 2;
2491 break;
2492 }
2493 }
2494 return node;
2495};
2496
2497/** Finds the triangle that is closest to a given Vector \a *x.
2498 * \param *out output stream for debugging
2499 * \param *x Vector to look from
2500 * \return list of BoundaryTriangleSet of nearest triangles or NULL in degenerate case.
2501 */
2502list<BoundaryTriangleSet*> * Tesselation::FindClosestTrianglesToPoint(ofstream *out, Vector *x, LinkedCell* LC)
2503{
2504 TesselPoint *trianglePoints[3];
2505 TesselPoint *SecondPoint = NULL;
2506 list<BoundaryTriangleSet*> *triangles = NULL;
2507
2508 if (LinesOnBoundary.empty()) {
2509 *out << Verbose(0) << "Error: There is no tesselation structure to compare the point with, please create one first.";
2510 return NULL;
2511 }
2512
2513 trianglePoints[0] = FindClosestPoint(x, SecondPoint, LC);
2514
2515 // check whether closest point is "too close" :), then it's inside
2516 if (trianglePoints[0] == NULL) {
2517 *out << Verbose(2) << "Is the only point, no one else is closeby." << endl;
2518 return NULL;
2519 }
2520 if (trianglePoints[0]->node->DistanceSquared(x) < MYEPSILON) {
2521 *out << Verbose(3) << "Point is right on a tesselation point, no nearest triangle." << endl;
2522 PointMap::iterator PointRunner = PointsOnBoundary.find(trianglePoints[0]->nr);
2523 triangles = new list<BoundaryTriangleSet*>;
2524 if (PointRunner != PointsOnBoundary.end()) {
2525 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2526 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2527 triangles->push_back(TriangleRunner->second);
2528 triangles->sort();
2529 triangles->unique();
2530 } else {
2531 PointRunner = PointsOnBoundary.find(SecondPoint->nr);
2532 trianglePoints[0] = SecondPoint;
2533 if (PointRunner != PointsOnBoundary.end()) {
2534 for(LineMap::iterator LineRunner = PointRunner->second->lines.begin(); LineRunner != PointRunner->second->lines.end(); LineRunner++)
2535 for(TriangleMap::iterator TriangleRunner = LineRunner->second->triangles.begin(); TriangleRunner != LineRunner->second->triangles.end(); TriangleRunner++)
2536 triangles->push_back(TriangleRunner->second);
2537 triangles->sort();
2538 triangles->unique();
2539 } else {
2540 *out << Verbose(1) << "ERROR: I cannot find a boundary point to the tessel point " << *trianglePoints[0] << "." << endl;
2541 return NULL;
2542 }
2543 }
2544 } else {
2545 list<TesselPoint*> *connectedClosestPoints = GetCircleOfConnectedPoints(out, trianglePoints[0], x);
2546 trianglePoints[1] = connectedClosestPoints->front();
2547 trianglePoints[2] = connectedClosestPoints->back();
2548 for (int i=0;i<3;i++) {
2549 if (trianglePoints[i] == NULL) {
2550 *out << Verbose(1) << "ERROR: IsInnerPoint encounters serious error, point " << i << " not found." << endl;
2551 }
2552 //*out << Verbose(2) << "List of triangle points:" << endl;
2553 //*out << Verbose(3) << *trianglePoints[i] << endl;
2554 }
2555
2556 triangles = FindTriangles(trianglePoints);
2557 *out << Verbose(2) << "List of possible triangles:" << endl;
2558 for(list<BoundaryTriangleSet*>::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
2559 *out << Verbose(3) << **Runner << endl;
2560
2561 delete(connectedClosestPoints);
2562 }
2563
2564 if (triangles->empty()) {
2565 *out << Verbose(0) << "ERROR: There is no nearest triangle. Please check the tesselation structure.";
2566 delete(triangles);
2567 return NULL;
2568 } else
2569 return triangles;
2570};
2571
2572/** Finds closest triangle to a point.
2573 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
2574 * \param *out output stream for debugging
2575 * \param *x Vector to look from
2576 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
2577 */
2578class BoundaryTriangleSet * Tesselation::FindClosestTriangleToPoint(ofstream *out, Vector *x, LinkedCell* LC)
2579{
2580 class BoundaryTriangleSet *result = NULL;
2581 list<BoundaryTriangleSet*> *triangles = FindClosestTrianglesToPoint(out, x, LC);
2582 Vector Center;
2583
2584 if (triangles == NULL)
2585 return NULL;
2586
2587 if (triangles->size() == 1) { // there is no degenerate case
2588 result = triangles->front();
2589 *out << Verbose(2) << "Normal Vector of this triangle is " << result->NormalVector << "." << endl;
2590 } else {
2591 result = triangles->front();
2592 result->GetCenter(&Center);
2593 Center.SubtractVector(x);
2594 *out << Verbose(2) << "Normal Vector of this front side is " << result->NormalVector << "." << endl;
2595 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2596 result = triangles->back();
2597 *out << Verbose(2) << "Normal Vector of this back side is " << result->NormalVector << "." << endl;
2598 if (Center.ScalarProduct(&result->NormalVector) < 0) {
2599 *out << Verbose(1) << "ERROR: Front and back side yield NormalVector in wrong direction!" << endl;
2600 }
2601 }
2602 }
2603 delete(triangles);
2604 return result;
2605};
2606
2607/** Checks whether the provided Vector is within the tesselation structure.
2608 *
2609 * @param point of which to check the position
2610 * @param *LC LinkedCell structure
2611 *
2612 * @return true if the point is inside the tesselation structure, false otherwise
2613 */
2614bool Tesselation::IsInnerPoint(ofstream *out, Vector Point, LinkedCell* LC)
2615{
2616 class BoundaryTriangleSet *result = FindClosestTriangleToPoint(out, &Point, LC);
2617 Vector Center;
2618
2619 if (result == NULL) {// is boundary point or only point in point cloud?
2620 *out << Verbose(1) << Point << " is the only point in vicinity." << endl;
2621 return false;
2622 }
2623
2624 result->GetCenter(&Center);
2625 *out << Verbose(3) << "INFO: Central point of the triangle is " << Center << "." << endl;
2626 Center.SubtractVector(&Point);
2627 *out << Verbose(3) << "INFO: Vector from center to point to test is " << Center << "." << endl;
2628 if (Center.ScalarProduct(&result->NormalVector) > -MYEPSILON) {
2629 *out << Verbose(1) << Point << " is an inner point." << endl;
2630 return true;
2631 } else {
2632 *out << Verbose(1) << Point << " is NOT an inner point." << endl;
2633 return false;
2634 }
2635}
2636
2637/** Checks whether the provided TesselPoint is within the tesselation structure.
2638 *
2639 * @param *Point of which to check the position
2640 * @param *LC Linked Cell structure
2641 *
2642 * @return true if the point is inside the tesselation structure, false otherwise
2643 */
2644bool Tesselation::IsInnerPoint(ofstream *out, TesselPoint *Point, LinkedCell* LC)
2645{
2646 return IsInnerPoint(out, *(Point->node), LC);
2647}
2648
2649/** Gets all points connected to the provided point by triangulation lines.
2650 *
2651 * @param *Point of which get all connected points
2652 *
2653 * @return set of the all points linked to the provided one
2654 */
2655set<TesselPoint*> * Tesselation::GetAllConnectedPoints(ofstream *out, TesselPoint* Point)
2656{
2657 set<TesselPoint*> *connectedPoints = new set<TesselPoint*>;
2658 class BoundaryPointSet *ReferencePoint = NULL;
2659 TesselPoint* current;
2660 bool takePoint = false;
2661
2662 // find the respective boundary point
2663 PointMap::iterator PointRunner = PointsOnBoundary.find(Point->nr);
2664 if (PointRunner != PointsOnBoundary.end()) {
2665 ReferencePoint = PointRunner->second;
2666 } else {
2667 *out << Verbose(2) << "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2668 ReferencePoint = NULL;
2669 }
2670
2671 // little trick so that we look just through lines connect to the BoundaryPoint
2672 // OR fall-back to look through all lines if there is no such BoundaryPoint
2673 LineMap *Lines = &LinesOnBoundary;
2674 if (ReferencePoint != NULL)
2675 Lines = &(ReferencePoint->lines);
2676 LineMap::iterator findLines = Lines->begin();
2677 while (findLines != Lines->end()) {
2678 takePoint = false;
2679
2680 if (findLines->second->endpoints[0]->Nr == Point->nr) {
2681 takePoint = true;
2682 current = findLines->second->endpoints[1]->node;
2683 } else if (findLines->second->endpoints[1]->Nr == Point->nr) {
2684 takePoint = true;
2685 current = findLines->second->endpoints[0]->node;
2686 }
2687
2688 if (takePoint) {
2689 *out << Verbose(5) << "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted." << endl;
2690 connectedPoints->insert(current);
2691 }
2692
2693 findLines++;
2694 }
2695
2696 if (connectedPoints->size() == 0) { // if have not found any points
2697 *out << Verbose(1) << "ERROR: We have not found any connected points to " << *Point<< "." << endl;
2698 return NULL;
2699 }
2700
2701 return connectedPoints;
2702};
2703
2704
2705/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2706 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2707 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2708 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2709 * triangle we are looking for.
2710 *
2711 * @param *out output stream for debugging
2712 * @param *Point of which get all connected points
2713 * @param *Reference Reference vector for zero angle or NULL for no preference
2714 * @return list of the all points linked to the provided one
2715 */
2716list<TesselPoint*> * Tesselation::GetCircleOfConnectedPoints(ofstream *out, TesselPoint* Point, Vector *Reference)
2717{
2718 map<double, TesselPoint*> anglesOfPoints;
2719 set<TesselPoint*> *connectedPoints = GetAllConnectedPoints(out, Point);
2720 list<TesselPoint*> *connectedCircle = new list<TesselPoint*>;
2721 Vector center;
2722 Vector PlaneNormal;
2723 Vector AngleZero;
2724 Vector OrthogonalVector;
2725 Vector helper;
2726
2727 // calculate central point
2728 for (set<TesselPoint*>::iterator TesselRunner = connectedPoints->begin(); TesselRunner != connectedPoints->end(); TesselRunner++)
2729 center.AddVector((*TesselRunner)->node);
2730 //*out << "Summed vectors " << center << "; number of points " << connectedPoints.size()
2731 // << "; scale factor " << 1.0/connectedPoints.size();
2732 center.Scale(1.0/connectedPoints->size());
2733 *out << Verbose(4) << "INFO: Calculated center of all circle points is " << center << "." << endl;
2734
2735 // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
2736 PlaneNormal.CopyVector(Point->node);
2737 PlaneNormal.SubtractVector(&center);
2738 PlaneNormal.Normalize();
2739 *out << Verbose(4) << "INFO: Calculated plane normal of circle is " << PlaneNormal << "." << endl;
2740
2741 // construct one orthogonal vector
2742 if (Reference != NULL)
2743 AngleZero.CopyVector(Reference);
2744 else
2745 AngleZero.CopyVector((*connectedPoints->begin())->node);
2746 AngleZero.SubtractVector(Point->node);
2747 AngleZero.ProjectOntoPlane(&PlaneNormal);
2748 *out << Verbose(4) << "INFO: Reference vector on this plane representing angle 0 is " << AngleZero << "." << endl;
2749 OrthogonalVector.MakeNormalVector(&PlaneNormal, &AngleZero);
2750 *out << Verbose(4) << "INFO: OrthogonalVector on plane is " << OrthogonalVector << "." << endl;
2751
2752 // go through all connected points and calculate angle
2753 for (set<TesselPoint*>::iterator listRunner = connectedPoints->begin(); listRunner != connectedPoints->end(); listRunner++) {
2754 helper.CopyVector((*listRunner)->node);
2755 helper.SubtractVector(Point->node);
2756 helper.ProjectOntoPlane(&PlaneNormal);
2757 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
2758 *out << Verbose(3) << "INFO: Calculated angle is " << angle << " for point " << **listRunner << "." << endl;
2759 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
2760 }
2761
2762 for(map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
2763 connectedCircle->push_back(AngleRunner->second);
2764 }
2765
2766 delete(connectedPoints);
2767 return connectedCircle;
2768}
2769
2770/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
2771 *
2772 * @param *out output stream for debugging
2773 * @param *Point of which get all connected points
2774 * @return list of the all points linked to the provided one
2775 */
2776list<list<TesselPoint*> *> * Tesselation::GetPathsOfConnectedPoints(ofstream *out, TesselPoint* Point)
2777{
2778 map<double, TesselPoint*> anglesOfPoints;
2779 list<list<TesselPoint*> *> *ListOfPaths = new list<list<TesselPoint*> *>;
2780 list<TesselPoint*> *connectedPath = NULL;
2781 Vector center;
2782 Vector PlaneNormal;
2783 Vector AngleZero;
2784 Vector OrthogonalVector;
2785 Vector helper;
2786 class BoundaryPointSet *ReferencePoint = NULL;
2787 class BoundaryPointSet *CurrentPoint = NULL;
2788 class BoundaryTriangleSet *triangle = NULL;
2789 class BoundaryLineSet *CurrentLine = NULL;
2790 class BoundaryLineSet *StartLine = NULL;
2791
2792 // find the respective boundary point
2793 PointMap::iterator PointRunner = PointsOnBoundary.find(Point->nr);
2794 if (PointRunner != PointsOnBoundary.end()) {
2795 ReferencePoint = PointRunner->second;
2796 } else {
2797 *out << Verbose(2) << "ERROR: GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << "." << endl;
2798 return NULL;
2799 }
2800
2801 map <class BoundaryLineSet *, bool> TouchedLine;
2802 map <class BoundaryTriangleSet *, bool> TouchedTriangle;
2803 map <class BoundaryLineSet *, bool>::iterator LineRunner;
2804 map <class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
2805 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
2806 TouchedLine.insert( pair <class BoundaryLineSet *, bool>(Runner->second, false) );
2807 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++)
2808 TouchedTriangle.insert( pair <class BoundaryTriangleSet *, bool>(Sprinter->second, false) );
2809 }
2810 if (!ReferencePoint->lines.empty()) {
2811 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
2812 LineRunner = TouchedLine.find(runner->second);
2813 if (LineRunner == TouchedLine.end()) {
2814 *out << Verbose(2) << "ERROR: I could not find " << *runner->second << " in the touched list." << endl;
2815 } else if (!LineRunner->second) {
2816 LineRunner->second = true;
2817 connectedPath = new list<TesselPoint*>;
2818 triangle = NULL;
2819 CurrentLine = runner->second;
2820 StartLine = CurrentLine;
2821 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
2822 *out << Verbose(3)<< "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << "." << endl;
2823 do {
2824 // push current one
2825 *out << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
2826 connectedPath->push_back(CurrentPoint->node);
2827
2828 // find next triangle
2829 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
2830 *out << Verbose(3) << "INFO: Inspecting triangle " << *Runner->second << "." << endl;
2831 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
2832 triangle = Runner->second;
2833 TriangleRunner = TouchedTriangle.find(triangle);
2834 if (TriangleRunner != TouchedTriangle.end()) {
2835 if (!TriangleRunner->second) {
2836 TriangleRunner->second = true;
2837 *out << Verbose(3) << "INFO: Connecting triangle is " << *triangle << "." << endl;
2838 break;
2839 } else {
2840 *out << Verbose(3) << "INFO: Skipping " << *triangle << ", as we have already visited it." << endl;
2841 triangle = NULL;
2842 }
2843 } else {
2844 *out << Verbose(2) << "ERROR: I could not find " << *triangle << " in the touched list." << endl;
2845 triangle = NULL;
2846 }
2847 }
2848 }
2849 if (triangle == NULL)
2850 break;
2851 // find next line
2852 for (int i=0;i<3;i++) {
2853 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
2854 CurrentLine = triangle->lines[i];
2855 *out << Verbose(3) << "INFO: Connecting line is " << *CurrentLine << "." << endl;
2856 break;
2857 }
2858 }
2859 LineRunner = TouchedLine.find(CurrentLine);
2860 if (LineRunner == TouchedLine.end())
2861 *out << Verbose(2) << "ERROR: I could not find " << *CurrentLine << " in the touched list." << endl;
2862 else
2863 LineRunner->second = true;
2864 // find next point
2865 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
2866
2867 } while (CurrentLine != StartLine);
2868 // last point is missing, as it's on start line
2869 *out << Verbose(3) << "INFO: Putting " << *CurrentPoint << " at end of path." << endl;
2870 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back())
2871 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
2872
2873 ListOfPaths->push_back(connectedPath);
2874 } else {
2875 *out << Verbose(3) << "INFO: Skipping " << *runner->second << ", as we have already visited it." << endl;
2876 }
2877 }
2878 } else {
2879 *out << Verbose(1) << "ERROR: There are no lines attached to " << *ReferencePoint << "." << endl;
2880 }
2881
2882 return ListOfPaths;
2883}
2884
2885/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
2886 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
2887 * @param *out output stream for debugging
2888 * @param *Point of which get all connected points
2889 * @return list of the closed paths
2890 */
2891list<list<TesselPoint*> *> * Tesselation::GetClosedPathsOfConnectedPoints(ofstream *out, TesselPoint* Point)
2892{
2893 list<list<TesselPoint*> *> *ListofPaths = GetPathsOfConnectedPoints(out, Point);
2894 list<list<TesselPoint*> *> *ListofClosedPaths = new list<list<TesselPoint*> *>;
2895 list<TesselPoint*> *connectedPath = NULL;
2896 list<TesselPoint*> *newPath = NULL;
2897 int count = 0;
2898
2899
2900 list<TesselPoint*>::iterator CircleRunner;
2901 list<TesselPoint*>::iterator CircleStart;
2902
2903 for(list<list<TesselPoint*> *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
2904 connectedPath = *ListRunner;
2905
2906 *out << Verbose(2) << "INFO: Current path is " << connectedPath << "." << endl;
2907
2908 // go through list, look for reappearance of starting Point and count
2909 CircleStart = connectedPath->begin();
2910
2911 // go through list, look for reappearance of starting Point and create list
2912 list<TesselPoint*>::iterator Marker = CircleStart;
2913 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
2914 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
2915 // we have a closed circle from Marker to new Marker
2916 *out << Verbose(3) << count+1 << ". closed path consists of: ";
2917 newPath = new list<TesselPoint*>;
2918 list<TesselPoint*>::iterator CircleSprinter = Marker;
2919 for (; CircleSprinter != CircleRunner; CircleSprinter++) {
2920 newPath->push_back(*CircleSprinter);
2921 *out << (**CircleSprinter) << " <-> ";
2922 }
2923 *out << ".." << endl;
2924 count++;
2925 Marker = CircleRunner;
2926
2927 // add to list
2928 ListofClosedPaths->push_back(newPath);
2929 }
2930 }
2931 }
2932 *out << Verbose(3) << "INFO: " << count << " closed additional path(s) have been created." << endl;
2933
2934 // delete list of paths
2935 while (!ListofPaths->empty()) {
2936 connectedPath = *(ListofPaths->begin());
2937 ListofPaths->remove(connectedPath);
2938 delete(connectedPath);
2939 }
2940 delete(ListofPaths);
2941
2942 // exit
2943 return ListofClosedPaths;
2944};
2945
2946
2947/** Gets all belonging triangles for a given BoundaryPointSet.
2948 * \param *out output stream for debugging
2949 * \param *Point BoundaryPoint
2950 * \return pointer to allocated list of triangles
2951 */
2952set<BoundaryTriangleSet*> *Tesselation::GetAllTriangles(ofstream *out, class BoundaryPointSet *Point)
2953{
2954 set<BoundaryTriangleSet*> *connectedTriangles = new set<BoundaryTriangleSet*>;
2955
2956 if (Point == NULL) {
2957 *out << Verbose(1) << "ERROR: Point given is NULL." << endl;
2958 } else {
2959 // go through its lines and insert all triangles
2960 for (LineMap::iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
2961 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
2962 connectedTriangles->insert(TriangleRunner->second);
2963 }
2964 }
2965
2966 return connectedTriangles;
2967};
2968
2969
2970/** Removes a boundary point from the envelope while keeping it closed.
2971 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
2972 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
2973 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
2974 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
2975 * -# the surface is closed, when the path is empty
2976 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
2977 * \param *out output stream for debugging
2978 * \param *point point to be removed
2979 * \return volume added to the volume inside the tesselated surface by the removal
2980 */
2981double Tesselation::RemovePointFromTesselatedSurface(ofstream *out, class BoundaryPointSet *point) {
2982 class BoundaryLineSet *line = NULL;
2983 class BoundaryTriangleSet *triangle = NULL;
2984 Vector OldPoint, NormalVector;
2985 double volume = 0;
2986 int count = 0;
2987
2988 if (point == NULL) {
2989 *out << Verbose(1) << "ERROR: Cannot remove the point " << point << ", it's NULL!" << endl;
2990 return 0.;
2991 } else
2992 *out << Verbose(2) << "Removing point " << *point << " from tesselated boundary ..." << endl;
2993
2994 // copy old location for the volume
2995 OldPoint.CopyVector(point->node->node);
2996
2997 // get list of connected points
2998 if (point->lines.empty()) {
2999 *out << Verbose(1) << "ERROR: Cannot remove the point " << *point << ", it's connected to no lines!" << endl;
3000 return 0.;
3001 }
3002
3003 list<list<TesselPoint*> *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(out, point->node);
3004 list<TesselPoint*> *connectedPath = NULL;
3005
3006 // gather all triangles
3007 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++)
3008 count+=LineRunner->second->triangles.size();
3009 map<class BoundaryTriangleSet *, int> Candidates;
3010 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
3011 line = LineRunner->second;
3012 for (TriangleMap::iterator TriangleRunner = line->triangles.begin(); TriangleRunner != line->triangles.end(); TriangleRunner++) {
3013 triangle = TriangleRunner->second;
3014 Candidates.insert( pair<class BoundaryTriangleSet *, int> (triangle, triangle->Nr) );
3015 }
3016 }
3017
3018 // remove all triangles
3019 count=0;
3020 NormalVector.Zero();
3021 for (map<class BoundaryTriangleSet *, int>::iterator Runner = Candidates.begin(); Runner != Candidates.end(); Runner++) {
3022 *out << Verbose(3) << "INFO: Removing triangle " << *(Runner->first) << "." << endl;
3023 NormalVector.SubtractVector(&Runner->first->NormalVector); // has to point inward
3024 RemoveTesselationTriangle(Runner->first);
3025 count++;
3026 }
3027 *out << Verbose(1) << count << " triangles were removed." << endl;
3028
3029 list<list<TesselPoint*> *>::iterator ListAdvance = ListOfClosedPaths->begin();
3030 list<list<TesselPoint*> *>::iterator ListRunner = ListAdvance;
3031 map<class BoundaryTriangleSet *, int>::iterator NumberRunner = Candidates.begin();
3032 list<TesselPoint*>::iterator StartNode, MiddleNode, EndNode;
3033 double angle;
3034 double smallestangle;
3035 Vector Point, Reference, OrthogonalVector;
3036 if (count > 2) { // less than three triangles, then nothing will be created
3037 class TesselPoint *TriangleCandidates[3];
3038 count = 0;
3039 for ( ; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3040 if (ListAdvance != ListOfClosedPaths->end())
3041 ListAdvance++;
3042
3043 connectedPath = *ListRunner;
3044
3045 // re-create all triangles by going through connected points list
3046 list<class BoundaryLineSet *> NewLines;
3047 for (;!connectedPath->empty();) {
3048 // search middle node with widest angle to next neighbours
3049 EndNode = connectedPath->end();
3050 smallestangle = 0.;
3051 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3052 cout << Verbose(3) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3053 // construct vectors to next and previous neighbour
3054 StartNode = MiddleNode;
3055 if (StartNode == connectedPath->begin())
3056 StartNode = connectedPath->end();
3057 StartNode--;
3058 //cout << Verbose(3) << "INFO: StartNode is " << **StartNode << "." << endl;
3059 Point.CopyVector((*StartNode)->node);
3060 Point.SubtractVector((*MiddleNode)->node);
3061 StartNode = MiddleNode;
3062 StartNode++;
3063 if (StartNode == connectedPath->end())
3064 StartNode = connectedPath->begin();
3065 //cout << Verbose(3) << "INFO: EndNode is " << **StartNode << "." << endl;
3066 Reference.CopyVector((*StartNode)->node);
3067 Reference.SubtractVector((*MiddleNode)->node);
3068 OrthogonalVector.CopyVector((*MiddleNode)->node);
3069 OrthogonalVector.SubtractVector(&OldPoint);
3070 OrthogonalVector.MakeNormalVector(&Reference);
3071 angle = GetAngle(Point, Reference, OrthogonalVector);
3072 //if (angle < M_PI) // no wrong-sided triangles, please?
3073 if(fabs(angle - M_PI) < fabs(smallestangle - M_PI)) { // get straightest angle (i.e. construct those triangles with smallest area first)
3074 smallestangle = angle;
3075 EndNode = MiddleNode;
3076 }
3077 }
3078 MiddleNode = EndNode;
3079 if (MiddleNode == connectedPath->end()) {
3080 cout << Verbose(1) << "CRITICAL: Could not find a smallest angle!" << endl;
3081 exit(255);
3082 }
3083 StartNode = MiddleNode;
3084 if (StartNode == connectedPath->begin())
3085 StartNode = connectedPath->end();
3086 StartNode--;
3087 EndNode++;
3088 if (EndNode == connectedPath->end())
3089 EndNode = connectedPath->begin();
3090 cout << Verbose(4) << "INFO: StartNode is " << **StartNode << "." << endl;
3091 cout << Verbose(4) << "INFO: MiddleNode is " << **MiddleNode << "." << endl;
3092 cout << Verbose(4) << "INFO: EndNode is " << **EndNode << "." << endl;
3093 *out << Verbose(3) << "INFO: Attempting to create triangle " << (*StartNode)->Name << ", " << (*MiddleNode)->Name << " and " << (*EndNode)->Name << "." << endl;
3094 TriangleCandidates[0] = *StartNode;
3095 TriangleCandidates[1] = *MiddleNode;
3096 TriangleCandidates[2] = *EndNode;
3097 triangle = GetPresentTriangle(out, TriangleCandidates);
3098 if (triangle != NULL) {
3099 cout << Verbose(1) << "WARNING: New triangle already present, skipping!" << endl;
3100 StartNode++;
3101 MiddleNode++;
3102 EndNode++;
3103 if (StartNode == connectedPath->end())
3104 StartNode = connectedPath->begin();
3105 if (MiddleNode == connectedPath->end())
3106 MiddleNode = connectedPath->begin();
3107 if (EndNode == connectedPath->end())
3108 EndNode = connectedPath->begin();
3109 continue;
3110 }
3111 *out << Verbose(5) << "Adding new triangle points."<< endl;
3112 AddTesselationPoint(*StartNode, 0);
3113 AddTesselationPoint(*MiddleNode, 1);
3114 AddTesselationPoint(*EndNode, 2);
3115 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3116 AddTesselationLine(TPS[0], TPS[1], 0);
3117 AddTesselationLine(TPS[0], TPS[2], 1);
3118 NewLines.push_back(BLS[1]);
3119 AddTesselationLine(TPS[1], TPS[2], 2);
3120 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3121 BTS->GetNormalVector(NormalVector);
3122 AddTesselationTriangle();
3123 // calculate volume summand as a general tetraeder
3124 volume += CalculateVolumeofGeneralTetraeder(TPS[0]->node->node, TPS[1]->node->node, TPS[2]->node->node, &OldPoint);
3125 // advance number
3126 count++;
3127
3128 // prepare nodes for next triangle
3129 StartNode = EndNode;
3130 cout << Verbose(4) << "Removing " << **MiddleNode << " from closed path, remaining points: " << connectedPath->size() << "." << endl;
3131 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3132 if (connectedPath->size() == 2) { // we are done
3133 connectedPath->remove(*StartNode); // remove the start node
3134 connectedPath->remove(*EndNode); // remove the end node
3135 break;
3136 } else if (connectedPath->size() < 2) { // something's gone wrong!
3137 cout << Verbose(1) << "CRITICAL: There are only two endpoints left!" << endl;
3138 exit(255);
3139 } else {
3140 MiddleNode = StartNode;
3141 MiddleNode++;
3142 if (MiddleNode == connectedPath->end())
3143 MiddleNode = connectedPath->begin();
3144 EndNode = MiddleNode;
3145 EndNode++;
3146 if (EndNode == connectedPath->end())
3147 EndNode = connectedPath->begin();
3148 }
3149 }
3150 // maximize the inner lines (we preferentially created lines with a huge angle, which is for the tesselation not wanted though useful for the closing)
3151 if (NewLines.size() > 1) {
3152 list<class BoundaryLineSet *>::iterator Candidate;
3153 class BoundaryLineSet *OtherBase = NULL;
3154 double tmp, maxgain;
3155 do {
3156 maxgain = 0;
3157 for(list<class BoundaryLineSet *>::iterator Runner = NewLines.begin(); Runner != NewLines.end(); Runner++) {
3158 tmp = PickFarthestofTwoBaselines(out, *Runner);
3159 if (maxgain < tmp) {
3160 maxgain = tmp;
3161 Candidate = Runner;
3162 }
3163 }
3164 if (maxgain != 0) {
3165 volume += maxgain;
3166 cout << Verbose(3) << "Flipping baseline with highest volume" << **Candidate << "." << endl;
3167 OtherBase = FlipBaseline(out, *Candidate);
3168 NewLines.erase(Candidate);
3169 NewLines.push_back(OtherBase);
3170 }
3171 } while (maxgain != 0.);
3172 }
3173
3174 ListOfClosedPaths->remove(connectedPath);
3175 delete(connectedPath);
3176 }
3177 *out << Verbose(1) << count << " triangles were created." << endl;
3178 } else {
3179 while (!ListOfClosedPaths->empty()) {
3180 ListRunner = ListOfClosedPaths->begin();
3181 connectedPath = *ListRunner;
3182 ListOfClosedPaths->remove(connectedPath);
3183 delete(connectedPath);
3184 }
3185 *out << Verbose(1) << "No need to create any triangles." << endl;
3186 }
3187 delete(ListOfClosedPaths);
3188
3189 *out << Verbose(1) << "Removed volume is " << volume << "." << endl;
3190
3191 return volume;
3192};
3193
3194
3195
3196/**
3197 * Finds triangles belonging to the three provided points.
3198 *
3199 * @param *Points[3] list, is expected to contain three points
3200 *
3201 * @return triangles which belong to the provided points, will be empty if there are none,
3202 * will usually be one, in case of degeneration, there will be two
3203 */
3204list<BoundaryTriangleSet*> *Tesselation::FindTriangles(TesselPoint* Points[3])
3205{
3206 list<BoundaryTriangleSet*> *result = new list<BoundaryTriangleSet*>;
3207 LineMap::iterator FindLine;
3208 PointMap::iterator FindPoint;
3209 TriangleMap::iterator FindTriangle;
3210 class BoundaryPointSet *TrianglePoints[3];
3211
3212 for (int i = 0; i < 3; i++) {
3213 FindPoint = PointsOnBoundary.find(Points[i]->nr);
3214 if (FindPoint != PointsOnBoundary.end()) {
3215 TrianglePoints[i] = FindPoint->second;
3216 } else {
3217 TrianglePoints[i] = NULL;
3218 }
3219 }
3220
3221 // checks lines between the points in the Points for their adjacent triangles
3222 for (int i = 0; i < 3; i++) {
3223 if (TrianglePoints[i] != NULL) {
3224 for (int j = i; j < 3; j++) {
3225 if (TrianglePoints[j] != NULL) {
3226 FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->nr);
3227 if (FindLine != TrianglePoints[i]->lines.end()) {
3228 for (; FindLine->first == TrianglePoints[j]->node->nr; FindLine++) {
3229 FindTriangle = FindLine->second->triangles.begin();
3230 for (; FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
3231 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3232 result->push_back(FindTriangle->second);
3233 }
3234 }
3235 }
3236 // Is it sufficient to consider one of the triangle lines for this.
3237 return result;
3238
3239 }
3240 }
3241 }
3242 }
3243 }
3244
3245 return result;
3246}
3247
3248/**
3249 * Finds all degenerated lines within the tesselation structure.
3250 *
3251 * @return map of keys of degenerated line pairs, each line occurs twice
3252 * in the list, once as key and once as value
3253 */
3254map<int, int> * Tesselation::FindAllDegeneratedLines()
3255{
3256 map<int, class BoundaryLineSet *> AllLines;
3257 map<int, int> * DegeneratedLines = new map<int, int>;
3258
3259 // sanity check
3260 if (LinesOnBoundary.empty()) {
3261 cout << Verbose(1) << "Warning: FindAllDegeneratedTriangles() was called without any tesselation structure.";
3262 return DegeneratedLines;
3263 }
3264
3265 LineMap::iterator LineRunner1;
3266 pair<LineMap::iterator, bool> tester;
3267 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
3268 tester = AllLines.insert( pair<int,BoundaryLineSet *> (LineRunner1->second->endpoints[0]->Nr, LineRunner1->second) );
3269 if ((!tester.second) && (tester.first->second->endpoints[1]->Nr == LineRunner1->second->endpoints[1]->Nr)) { // found degenerated line
3270 DegeneratedLines->insert ( pair<int, int> (LineRunner1->second->Nr, tester.first->second->Nr) );
3271 DegeneratedLines->insert ( pair<int, int> (tester.first->second->Nr, LineRunner1->second->Nr) );
3272 }
3273 }
3274
3275 AllLines.clear();
3276
3277 cout << Verbose(1) << "FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines." << endl;
3278 map<int,int>::iterator it;
3279 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++)
3280 cout << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3281
3282 return DegeneratedLines;
3283}
3284
3285/**
3286 * Finds all degenerated triangles within the tesselation structure.
3287 *
3288 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
3289 * in the list, once as key and once as value
3290 */
3291map<int, int> * Tesselation::FindAllDegeneratedTriangles()
3292{
3293 map<int, int> * DegeneratedLines = FindAllDegeneratedLines();
3294 map<int, int> * DegeneratedTriangles = new map<int, int>;
3295
3296 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
3297 LineMap::iterator Liner;
3298 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
3299
3300 for (map<int, int>::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
3301 // run over both lines' triangles
3302 Liner = LinesOnBoundary.find(LineRunner->first);
3303 if (Liner != LinesOnBoundary.end())
3304 line1 = Liner->second;
3305 Liner = LinesOnBoundary.find(LineRunner->second);
3306 if (Liner != LinesOnBoundary.end())
3307 line2 = Liner->second;
3308 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
3309 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
3310 if ((TriangleRunner1->second != TriangleRunner2->second)
3311 && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
3312 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner1->second->Nr, TriangleRunner2->second->Nr) );
3313 DegeneratedTriangles->insert( pair<int, int> (TriangleRunner2->second->Nr, TriangleRunner1->second->Nr) );
3314 }
3315 }
3316 }
3317 }
3318 delete(DegeneratedLines);
3319
3320 cout << Verbose(1) << "FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:" << endl;
3321 map<int,int>::iterator it;
3322 for (it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
3323 cout << Verbose(2) << (*it).first << " => " << (*it).second << endl;
3324
3325 return DegeneratedTriangles;
3326}
3327
3328/**
3329 * Purges degenerated triangles from the tesselation structure if they are not
3330 * necessary to keep a single point within the structure.
3331 */
3332void Tesselation::RemoveDegeneratedTriangles()
3333{
3334 map<int, int> * DegeneratedTriangles = FindAllDegeneratedTriangles();
3335 TriangleMap::iterator finder;
3336 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
3337 int count = 0;
3338
3339 cout << Verbose(1) << "Begin of RemoveDegeneratedTriangles" << endl;
3340
3341 for (map<int, int>::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
3342 TriangleKeyRunner != DegeneratedTriangles->end(); ++TriangleKeyRunner
3343 ) {
3344 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
3345 if (finder != TrianglesOnBoundary.end())
3346 triangle = finder->second;
3347 else
3348 break;
3349 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
3350 if (finder != TrianglesOnBoundary.end())
3351 partnerTriangle = finder->second;
3352 else
3353 break;
3354
3355 bool trianglesShareLine = false;
3356 for (int i = 0; i < 3; ++i)
3357 for (int j = 0; j < 3; ++j)
3358 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
3359
3360 if (trianglesShareLine
3361 && (triangle->endpoints[1]->LinesCount > 2)
3362 && (triangle->endpoints[2]->LinesCount > 2)
3363 && (triangle->endpoints[0]->LinesCount > 2)
3364 ) {
3365 // check whether we have to fix lines
3366 BoundaryTriangleSet *Othertriangle = NULL;
3367 BoundaryTriangleSet *OtherpartnerTriangle = NULL;
3368 TriangleMap::iterator TriangleRunner;
3369 for (int i = 0; i < 3; ++i)
3370 for (int j = 0; j < 3; ++j)
3371 if (triangle->lines[i] != partnerTriangle->lines[j]) {
3372 // get the other two triangles
3373 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
3374 if (TriangleRunner->second != triangle) {
3375 Othertriangle = TriangleRunner->second;
3376 }
3377 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
3378 if (TriangleRunner->second != partnerTriangle) {
3379 OtherpartnerTriangle = TriangleRunner->second;
3380 }
3381 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
3382 // the line of triangle receives the degenerated ones
3383 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
3384 triangle->lines[i]->triangles.insert( TrianglePair( partnerTriangle->Nr, partnerTriangle) );
3385 for (int k=0;k<3;k++)
3386 if (triangle->lines[i] == Othertriangle->lines[k]) {
3387 Othertriangle->lines[k] = partnerTriangle->lines[j];
3388 break;
3389 }
3390 // the line of partnerTriangle receives the non-degenerated ones
3391 partnerTriangle->lines[j]->triangles.erase( partnerTriangle->Nr);
3392 partnerTriangle->lines[j]->triangles.insert( TrianglePair( Othertriangle->Nr, Othertriangle) );
3393 partnerTriangle->lines[j] = triangle->lines[i];
3394 }
3395
3396 // erase the pair
3397 count += (int) DegeneratedTriangles->erase(triangle->Nr);
3398 cout << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *triangle << "." << endl;
3399 RemoveTesselationTriangle(triangle);
3400 count += (int) DegeneratedTriangles->erase(partnerTriangle->Nr);
3401 cout << Verbose(1) << "RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << "." << endl;
3402 RemoveTesselationTriangle(partnerTriangle);
3403 } else {
3404 cout << Verbose(1) << "RemoveDegeneratedTriangles() does not remove triangle " << *triangle
3405 << " and its partner " << *partnerTriangle << " because it is essential for at"
3406 << " least one of the endpoints to be kept in the tesselation structure." << endl;
3407 }
3408 }
3409 delete(DegeneratedTriangles);
3410
3411 cout << Verbose(1) << "RemoveDegeneratedTriangles() removed " << count << " triangles:" << endl;
3412 cout << Verbose(1) << "End of RemoveDegeneratedTriangles" << endl;
3413}
3414
3415/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
3416 * We look for the closest point on the boundary, we look through its connected boundary lines and
3417 * seek the one with the minimum angle between its center point and the new point and this base line.
3418 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
3419 * \param *out output stream for debugging
3420 * \param *point point to add
3421 * \param *LC Linked Cell structure to find nearest point
3422 */
3423void Tesselation::AddBoundaryPointByDegeneratedTriangle(ofstream *out, class TesselPoint *point, LinkedCell *LC)
3424{
3425 *out << Verbose(2) << "Begin of AddBoundaryPointByDegeneratedTriangle" << endl;
3426
3427 // find nearest boundary point
3428 class TesselPoint *BackupPoint = NULL;
3429 class TesselPoint *NearestPoint = FindClosestPoint(point->node, BackupPoint, LC);
3430 class BoundaryPointSet *NearestBoundaryPoint = NULL;
3431 PointMap::iterator PointRunner;
3432
3433 if (NearestPoint == point)
3434 NearestPoint = BackupPoint;
3435 PointRunner = PointsOnBoundary.find(NearestPoint->nr);
3436 if (PointRunner != PointsOnBoundary.end()) {
3437 NearestBoundaryPoint = PointRunner->second;
3438 } else {
3439 *out << Verbose(1) << "ERROR: I cannot find the boundary point." << endl;
3440 return;
3441 }
3442 *out << Verbose(2) << "Nearest point on boundary is " << NearestPoint->Name << "." << endl;
3443
3444 // go through its lines and find the best one to split
3445 Vector CenterToPoint;
3446 Vector BaseLine;
3447 double angle, BestAngle = 0.;
3448 class BoundaryLineSet *BestLine = NULL;
3449 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
3450 BaseLine.CopyVector(Runner->second->endpoints[0]->node->node);
3451 BaseLine.SubtractVector(Runner->second->endpoints[1]->node->node);
3452 CenterToPoint.CopyVector(Runner->second->endpoints[0]->node->node);
3453 CenterToPoint.AddVector(Runner->second->endpoints[1]->node->node);
3454 CenterToPoint.Scale(0.5);
3455 CenterToPoint.SubtractVector(point->node);
3456 angle = CenterToPoint.Angle(&BaseLine);
3457 if (fabs(angle - M_PI/2.) < fabs(BestAngle - M_PI/2.)) {
3458 BestAngle = angle;
3459 BestLine = Runner->second;
3460 }
3461 }
3462
3463 // remove one triangle from the chosen line
3464 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
3465 BestLine->triangles.erase(TempTriangle->Nr);
3466 int nr = -1;
3467 for (int i=0;i<3; i++) {
3468 if (TempTriangle->lines[i] == BestLine) {
3469 nr = i;
3470 break;
3471 }
3472 }
3473
3474 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
3475 *out << Verbose(5) << "Adding new triangle points."<< endl;
3476 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3477 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3478 AddTesselationPoint(point, 2);
3479 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3480 AddTesselationLine(TPS[0], TPS[1], 0);
3481 AddTesselationLine(TPS[0], TPS[2], 1);
3482 AddTesselationLine(TPS[1], TPS[2], 2);
3483 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3484 BTS->GetNormalVector(TempTriangle->NormalVector);
3485 BTS->NormalVector.Scale(-1.);
3486 *out << Verbose(3) << "INFO: NormalVector of new triangle is " << BTS->NormalVector << "." << endl;
3487 AddTesselationTriangle();
3488
3489 // create other side of this triangle and close both new sides of the first created triangle
3490 *out << Verbose(5) << "Adding new triangle points."<< endl;
3491 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
3492 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
3493 AddTesselationPoint(point, 2);
3494 *out << Verbose(5) << "Adding new triangle lines."<< endl;
3495 AddTesselationLine(TPS[0], TPS[1], 0);
3496 AddTesselationLine(TPS[0], TPS[2], 1);
3497 AddTesselationLine(TPS[1], TPS[2], 2);
3498 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3499 BTS->GetNormalVector(TempTriangle->NormalVector);
3500 *out << Verbose(3) << "INFO: NormalVector of other new triangle is " << BTS->NormalVector << "." << endl;
3501 AddTesselationTriangle();
3502
3503 // add removed triangle to the last open line of the second triangle
3504 for (int i=0;i<3;i++) { // look for the same line as BestLine (only it's its degenerated companion)
3505 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
3506 if (BestLine == BTS->lines[i]){
3507 *out << Verbose(1) << "CRITICAL: BestLine is same as found line, something's wrong here!" << endl;
3508 exit(255);
3509 }
3510 BTS->lines[i]->triangles.insert( pair<int, class BoundaryTriangleSet *> (TempTriangle->Nr, TempTriangle) );
3511 TempTriangle->lines[nr] = BTS->lines[i];
3512 break;
3513 }
3514 }
3515
3516 // exit
3517 *out << Verbose(2) << "End of AddBoundaryPointByDegeneratedTriangle" << endl;
3518};
3519
3520/** Writes the envelope to file.
3521 * \param *out otuput stream for debugging
3522 * \param *filename basename of output file
3523 * \param *cloud PointCloud structure with all nodes
3524 */
3525void Tesselation::Output(ofstream *out, const char *filename, PointCloud *cloud)
3526{
3527 ofstream *tempstream = NULL;
3528 string NameofTempFile;
3529 char NumberName[255];
3530
3531 if (LastTriangle != NULL) {
3532 sprintf(NumberName, "-%04d-%s_%s_%s", (int)TrianglesOnBoundary.size(), LastTriangle->endpoints[0]->node->Name, LastTriangle->endpoints[1]->node->Name, LastTriangle->endpoints[2]->node->Name);
3533 if (DoTecplotOutput) {
3534 string NameofTempFile(filename);
3535 NameofTempFile.append(NumberName);
3536 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3537 NameofTempFile.erase(npos, 1);
3538 NameofTempFile.append(TecplotSuffix);
3539 *out << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3540 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3541 WriteTecplotFile(out, tempstream, this, cloud, TriangleFilesWritten);
3542 tempstream->close();
3543 tempstream->flush();
3544 delete(tempstream);
3545 }
3546
3547 if (DoRaster3DOutput) {
3548 string NameofTempFile(filename);
3549 NameofTempFile.append(NumberName);
3550 for(size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
3551 NameofTempFile.erase(npos, 1);
3552 NameofTempFile.append(Raster3DSuffix);
3553 *out << Verbose(1) << "Writing temporary non convex hull to file " << NameofTempFile << ".\n";
3554 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
3555 WriteRaster3dFile(out, tempstream, this, cloud);
3556 IncludeSphereinRaster3D(out, tempstream, this, cloud);
3557 tempstream->close();
3558 tempstream->flush();
3559 delete(tempstream);
3560 }
3561 }
3562 if (DoTecplotOutput || DoRaster3DOutput)
3563 TriangleFilesWritten++;
3564};
Note: See TracBrowser for help on using the repository browser.