source: src/Tesselation/tesselation.cpp@ 311137

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

VERBOSE: Subsequent change in verbosity levels of many tesselation functions after Info removal.

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