source: src/Tesselation/tesselation.cpp@ 0aa122

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

Updated all source files's copyright note to current year 2012.

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