source: src/tesselation.cpp@ a479fa

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

Renamed ParticleInfo::nr to ParticleInfo::ParticleInfo_nr for easier privatization.

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