source: src/Tesselation/tesselation.cpp@ e26c35

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

FIX: Tesselation::RemovePointFromTesselatedSurface() uses wrong NormalVector.

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