source: src/tesselation.cpp@ d74077

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since d74077 was d74077, checked in by Frederik Heber <heber@…>, 15 years ago

Member variable Vector and element of class atom are now private.

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