source: src/tesselation.cpp@ 88b400

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

converted #define's to enums, consts and typedefs [Meyers, "Effective C++", item 1].

basic changes:

  • #define bla 1.3 -> const double bla = 1.3
  • #define bla "test" -> const char * const bla = "test
  • use class specific constants! (HULLEPSILON)

const int Class::bla = 1.3; (in .cpp)
static const int bla; (in .hpp inside class private section)

  • "enum hack": #define bla 5 -> enum { bla = 5 };
    • if const int bla=5; impossible
    • e.g. necessary if constant is used in array declaration (int blabla[bla];)

details:

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