source: src/tesselation.cpp@ bf3817

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

Added ifdef HAVE_CONFIG and config.h include to each and every cpp file.

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