source: src/Tesselation/tesselation.cpp@ 47d041

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 47d041 was 47d041, checked in by Frederik Heber <heber@…>, 13 years ago

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

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