source: src/tesselation.cpp@ 711ac2

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 Candidate_v1.7.0 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 711ac2 was 711ac2, checked in by Frederik Heber <heber@…>, 16 years ago

Memory leak fixes and code cleanup after tesselation rewrite.

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