source: src/Tesselation/tesselation.cpp@ d93d2c

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

Added check whether all points remain inside surface and whether it is convex to ConvexEnvelopeAction.

  • Property mode set to 100644
File size: 197.9 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
1746bool Tesselation::isConvex() const
1747{
1748 bool status = true;
1749 // go through all lines on boundary
1750 for (LineMap::const_iterator lineiter = LinesOnBoundary.begin();
1751 lineiter != LinesOnBoundary.end(); ++lineiter) {
1752 if (!lineiter->second->CheckConvexityCriterion()) {
1753 LOG(2, "DEBUG: Line " << *lineiter->second << " is not convex.");
1754 status = false;
1755 }
1756 }
1757 return status;
1758}
1759
1760/** Checks whether the quadragon of the two triangles connect to \a *Base is convex.
1761 * We look whether the closest point on \a *Base with respect to the other baseline is outside
1762 * of the segment formed by both endpoints (concave) or not (convex).
1763 * \param *out output stream for debugging
1764 * \param *Base line to be flipped
1765 * \return NULL - convex, otherwise endpoint that makes it concave
1766 */
1767class BoundaryPointSet *Tesselation::IsConvexRectangle(class BoundaryLineSet *Base)
1768{
1769 //Info FunctionInfo(__func__);
1770 class BoundaryPointSet *Spot = NULL;
1771 class BoundaryLineSet *OtherBase;
1772 Vector *ClosestPoint;
1773
1774 int m = 0;
1775 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1776 for (int j = 0; j < 3; j++) // all of their endpoints and baselines
1777 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1778 BPS[m++] = runner->second->endpoints[j];
1779 OtherBase = new class BoundaryLineSet(BPS, -1);
1780
1781 LOG(3, "DEBUG: Current base line is " << *Base << ".");
1782 LOG(3, "DEBUG: Other base line is " << *OtherBase << ".");
1783
1784 // get the closest point on each line to the other line
1785 ClosestPoint = GetClosestPointBetweenLine(Base, OtherBase);
1786
1787 // delete the temporary other base line
1788 delete (OtherBase);
1789
1790 // get the distance vector from Base line to OtherBase line
1791 Vector DistanceToIntersection[2], BaseLine;
1792 double distance[2];
1793 BaseLine = (Base->endpoints[1]->node->getPosition()) - (Base->endpoints[0]->node->getPosition());
1794 for (int i = 0; i < 2; i++) {
1795 DistanceToIntersection[i] = (*ClosestPoint) - (Base->endpoints[i]->node->getPosition());
1796 distance[i] = BaseLine.ScalarProduct(DistanceToIntersection[i]);
1797 }
1798 delete (ClosestPoint);
1799 if ((distance[0] * distance[1]) > 0) { // have same sign?
1800 LOG(4, "REJECT: Both SKPs have same sign: " << distance[0] << " and " << distance[1] << ". " << *Base << "' rectangle is concave.");
1801 if (distance[0] < distance[1]) {
1802 Spot = Base->endpoints[0];
1803 } else {
1804 Spot = Base->endpoints[1];
1805 }
1806 return Spot;
1807 } else { // different sign, i.e. we are in between
1808 LOG(3, "ACCEPT: Rectangle of triangles of base line " << *Base << " is convex.");
1809 return NULL;
1810 }
1811
1812}
1813;
1814
1815void Tesselation::PrintAllBoundaryPoints(ofstream *out) const
1816{
1817 //Info FunctionInfo(__func__);
1818 // print all lines
1819 std::stringstream output;
1820 for (PointMap::const_iterator PointRunner = PointsOnBoundary.begin(); PointRunner != PointsOnBoundary.end(); PointRunner++)
1821 output << " " << *(PointRunner->second);
1822 LOG(3, "DEBUG: Printing all boundary points for debugging:" << output.str());
1823}
1824;
1825
1826void Tesselation::PrintAllBoundaryLines(ofstream *out) const
1827{
1828 //Info FunctionInfo(__func__);
1829 // print all lines
1830 std::stringstream output;
1831 for (LineMap::const_iterator LineRunner = LinesOnBoundary.begin(); LineRunner != LinesOnBoundary.end(); LineRunner++)
1832 output << " " << *(LineRunner->second);
1833 LOG(3, "DEBUG: Printing all boundary lines for debugging:" << output.str());
1834}
1835;
1836
1837void Tesselation::PrintAllBoundaryTriangles(ofstream *out) const
1838{
1839 //Info FunctionInfo(__func__);
1840 // print all triangles
1841 std::stringstream output;
1842 for (TriangleMap::const_iterator TriangleRunner = TrianglesOnBoundary.begin(); TriangleRunner != TrianglesOnBoundary.end(); TriangleRunner++)
1843 output << " " << *(TriangleRunner->second);
1844 LOG(3, "DEBUG: Printing all boundary triangles for debugging:" << output.str());
1845}
1846;
1847
1848/** For a given boundary line \a *Base and its two triangles, picks the central baseline that is "higher".
1849 * \param *out output stream for debugging
1850 * \param *Base line to be flipped
1851 * \return volume change due to flipping (0 - then no flipped occured)
1852 */
1853double Tesselation::PickFarthestofTwoBaselines(class BoundaryLineSet *Base)
1854{
1855 //Info FunctionInfo(__func__);
1856 class BoundaryLineSet *OtherBase;
1857 Vector *ClosestPoint[2];
1858 double volume;
1859
1860 int m = 0;
1861 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1862 for (int j = 0; j < 3; j++) // all of their endpoints and baselines
1863 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1864 BPS[m++] = runner->second->endpoints[j];
1865 OtherBase = new class BoundaryLineSet(BPS, -1);
1866
1867 LOG(3, "DEBUG: Current base line is " << *Base << ".");
1868 LOG(3, "DEBUG: Other base line is " << *OtherBase << ".");
1869
1870 // get the closest point on each line to the other line
1871 ClosestPoint[0] = GetClosestPointBetweenLine(Base, OtherBase);
1872 ClosestPoint[1] = GetClosestPointBetweenLine(OtherBase, Base);
1873
1874 // get the distance vector from Base line to OtherBase line
1875 Vector Distance = (*ClosestPoint[1]) - (*ClosestPoint[0]);
1876
1877 // calculate volume
1878 volume = CalculateVolumeofGeneralTetraeder(Base->endpoints[1]->node->getPosition(), OtherBase->endpoints[0]->node->getPosition(), OtherBase->endpoints[1]->node->getPosition(), Base->endpoints[0]->node->getPosition());
1879
1880 // delete the temporary other base line and the closest points
1881 delete (ClosestPoint[0]);
1882 delete (ClosestPoint[1]);
1883 delete (OtherBase);
1884
1885 if (Distance.NormSquared() < MYEPSILON) { // check for intersection
1886 LOG(3, "REJECT: Both lines have an intersection: Nothing to do.");
1887 return false;
1888 } else { // check for sign against BaseLineNormal
1889 Vector BaseLineNormal;
1890 BaseLineNormal.Zero();
1891 if (Base->triangles.size() < 2) {
1892 ELOG(1, "Less than two triangles are attached to this baseline!");
1893 return 0.;
1894 }
1895 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
1896 LOG(4, "DEBUG: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << ".");
1897 BaseLineNormal += (runner->second->NormalVector);
1898 }
1899 BaseLineNormal.Scale(1. / 2.);
1900
1901 if (Distance.ScalarProduct(BaseLineNormal) > MYEPSILON) { // Distance points outwards, hence OtherBase higher than Base -> flip
1902 LOG(3, "ACCEPT: Other base line would be higher: Flipping baseline.");
1903 // calculate volume summand as a general tetraeder
1904 return volume;
1905 } else { // Base higher than OtherBase -> do nothing
1906 LOG(3, "REJECT: Base line is higher: Nothing to do.");
1907 return 0.;
1908 }
1909 }
1910}
1911;
1912
1913/** For a given baseline and its two connected triangles, flips the baseline.
1914 * I.e. we create the new baseline between the other two endpoints of these four
1915 * endpoints and reconstruct the two triangles accordingly.
1916 * \param *out output stream for debugging
1917 * \param *Base line to be flipped
1918 * \return pointer to allocated new baseline - flipping successful, NULL - something went awry
1919 */
1920class BoundaryLineSet * Tesselation::FlipBaseline(class BoundaryLineSet *Base)
1921{
1922 //Info FunctionInfo(__func__);
1923 class BoundaryLineSet *OldLines[4], *NewLine;
1924 class BoundaryPointSet *OldPoints[2];
1925 Vector BaseLineNormal[2];
1926 Vector OtherEndpoint[2]; // fourth point to either triangle
1927 int OldTriangleNrs[2], OldBaseLineNr;
1928 int i, m;
1929
1930 // calculate NormalVector for later use
1931 if (Base->triangles.size() < 2) {
1932 ELOG(1, "Less than two triangles are attached to this baseline!");
1933 return NULL;
1934 }
1935 {
1936 int i=0;
1937 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++) {
1938 LOG(5, "INFO: Adding NormalVector " << runner->second->NormalVector << " of triangle " << *(runner->second) << ".");
1939 OtherEndpoint[(i+1)%2] = runner->second->GetThirdEndpoint(Base)->node->getPosition();
1940 BaseLineNormal[i++] = (runner->second->NormalVector);
1941 ASSERT( i <= 2,
1942 "Tesselation::FlipBaseline() - not exactly two triangles found.");
1943 }
1944 }
1945
1946 // get the two triangles
1947 // gather four endpoints and four lines
1948 for (int j = 0; j < 4; j++)
1949 OldLines[j] = NULL;
1950 for (int j = 0; j < 2; j++)
1951 OldPoints[j] = NULL;
1952 i = 0;
1953 m = 0;
1954
1955 // print OldLines and OldPoints for debugging
1956 if (DoLog(3)) {
1957 std::stringstream output;
1958 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1959 for (int j = 0; j < 3; j++) // all of their endpoints and baselines
1960 if (runner->second->lines[j] != Base) // pick not the central baseline
1961 output << *runner->second->lines[j] << "\t";
1962 LOG(3, "DEBUG: The four old lines are: " << output.str());
1963 }
1964 if (DoLog(3)) {
1965 std::stringstream output;
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 output << *runner->second->endpoints[j] << "\t";
1970 LOG(3, "DEBUG: The two old points are: " << output.str());
1971 }
1972
1973 // index OldLines and OldPoints
1974 // note that oldlines[0,1] belong to first triangle and hence first normal
1975 // vector and oldlines[2,3] belong to second triangle and its normal vector
1976 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1977 for (int j = 0; j < 3; j++) // all of their endpoints and baselines
1978 if (runner->second->lines[j] != Base) // pick not the central baseline
1979 OldLines[i++] = runner->second->lines[j];
1980 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); runner++)
1981 for (int j = 0; j < 3; j++) // all of their endpoints and baselines
1982 if (!Base->ContainsBoundaryPoint(runner->second->endpoints[j])) // and neither of its endpoints
1983 OldPoints[m++] = runner->second->endpoints[j];
1984
1985 Vector BasePoints[2]; // endpoints of Base
1986 if (OldLines[0]->ContainsBoundaryPoint(Base->endpoints[0])) {
1987 BasePoints[0] = Base->endpoints[0]->node->getPosition();
1988 BasePoints[1] = Base->endpoints[1]->node->getPosition();
1989 } else {
1990 BasePoints[0] = Base->endpoints[1]->node->getPosition();
1991 BasePoints[1] = Base->endpoints[0]->node->getPosition();
1992 }
1993 // check whether everything is in place to create new lines and triangles
1994 if (i < 4) {
1995 ELOG(1, "We have not gathered enough baselines!");
1996 return NULL;
1997 }
1998 for (int j = 0; j < 4; j++)
1999 if (OldLines[j] == NULL) {
2000 ELOG(1, "We have not gathered enough baselines!");
2001 return NULL;
2002 }
2003 for (int j = 0; j < 2; j++)
2004 if (OldPoints[j] == NULL) {
2005 ELOG(1, "We have not gathered enough endpoints!");
2006 return NULL;
2007 }
2008
2009 // construct plane of first triangle for calculating normal vectors later
2010 const Plane triangleplane = Base->triangles.begin()->second->getPlane();
2011 // get fourth point projected down onto this plane
2012 const Vector Intersection = triangleplane.getClosestPoint(OtherEndpoint[0]);
2013
2014 // remove triangles and baseline removes itself
2015 LOG(3, "DEBUG: Deleting baseline " << *Base << " from global list.");
2016 OldBaseLineNr = Base->Nr;
2017 m = 0;
2018 // first obtain all triangle to delete ... (otherwise we pull the carpet (Base) from under the for-loop's feet)
2019 list<BoundaryTriangleSet *> TrianglesOfBase;
2020 for (TriangleMap::iterator runner = Base->triangles.begin(); runner != Base->triangles.end(); ++runner)
2021 TrianglesOfBase.push_back(runner->second);
2022 // .. then delete each triangle (which deletes the line as well)
2023 for (list<BoundaryTriangleSet *>::iterator runner = TrianglesOfBase.begin(); !TrianglesOfBase.empty(); runner = TrianglesOfBase.begin()) {
2024 LOG(3, "DEBUG: Deleting triangle " << *(*runner) << ".");
2025 OldTriangleNrs[m++] = (*runner)->Nr;
2026 RemoveTesselationTriangle((*runner));
2027 TrianglesOfBase.erase(runner);
2028 }
2029
2030 // construct new baseline (with same number as old one)
2031 BPS[0] = OldPoints[0];
2032 BPS[1] = OldPoints[1];
2033 NewLine = new class BoundaryLineSet(BPS, OldBaseLineNr);
2034 LinesOnBoundary.insert(LinePair(OldBaseLineNr, NewLine)); // no need for check for unique insertion as NewLine is definitely a new one
2035 LOG(3, "DEBUG: Created new baseline " << *NewLine << ".");
2036
2037 // Explanation for normal vector choice:
2038 // Decisive for the normal vector of the new triangle is whether the fourth
2039 // endpoint is with respect to the joining boundary line on one side or on
2040 // the other with respect to the endpoint of the plane triangle that is not
2041 // contained in the joining boundary line.
2042
2043 // construct new triangles with flipped baseline
2044 i = -1;
2045 if (OldLines[0]->IsConnectedTo(OldLines[2]))
2046 i = 2;
2047 if (OldLines[0]->IsConnectedTo(OldLines[3]))
2048 i = 3;
2049 if (i != -1) {
2050 BLS[0] = OldLines[0];
2051 BLS[1] = OldLines[i];
2052 BLS[2] = NewLine;
2053 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[0]);
2054 {
2055 Line joiningline = makeLineThrough(
2056 OldLines[0]->endpoints[0]->node->getPosition(),
2057 OldLines[0]->endpoints[1]->node->getPosition());
2058 // BasePoints[1] is not contained in OldLines[0], hence is third endpoint
2059 // of plane triangle. BasePoints[0] is in the joining OldLines[0] and
2060 // we check whether Intersection is on same side as BasePoints[1] or not.
2061 const Vector pointinginside =
2062 joiningline.getClosestPoint(BasePoints[1]) - BasePoints[1];
2063 const Vector pointingtointersection =
2064 joiningline.getClosestPoint(Intersection) - Intersection;
2065 const double sign_of_intersection =
2066 pointingtointersection.ScalarProduct(pointinginside);
2067 LOG(4, "DEBUG: Sign of SKP between both lines w.r.t " << *OldLines[0]
2068 << " is " << sign_of_intersection << ".");
2069 const double sign_of_normal = (sign_of_intersection >= 0) ? -1. : +1.;
2070 LOG(4, "DEBUG: Opposite normal direction is "
2071 << sign_of_normal * BaseLineNormal[0] << ".");
2072 BTS->GetNormalVector(sign_of_normal * BaseLineNormal[0]);
2073 }
2074 AddTesselationTriangle(OldTriangleNrs[0]);
2075 LOG(3, "DEBUG: Created new triangle " << *BTS << ".");
2076
2077 BLS[0] = (i == 2 ? OldLines[3] : OldLines[2]);
2078 BLS[1] = OldLines[1];
2079 BLS[2] = NewLine;
2080 BTS = new class BoundaryTriangleSet(BLS, OldTriangleNrs[1]);
2081 {
2082 Line joiningline = makeLineThrough(
2083 OldLines[1]->endpoints[0]->node->getPosition(),
2084 OldLines[1]->endpoints[1]->node->getPosition());
2085 // BasePoints[0] is not contained in OldLines[1], hence is third endpoint
2086 // of plane triangle. BasePoints[1] is in th1e joining OldLines[1] and
2087 // we check whether Intersection is on same side as BasePoints[0] or not.
2088 const Vector pointinginside =
2089 joiningline.getClosestPoint(BasePoints[0]) - BasePoints[0];
2090 const Vector pointingtointersection =
2091 joiningline.getClosestPoint(Intersection) - Intersection;
2092 const double sign_of_intersection =
2093 pointingtointersection.ScalarProduct(pointinginside);
2094 LOG(4, "DEBUG: Sign of SKP between both lines w.r.t " << *OldLines[1]
2095 << " is " << sign_of_intersection << ".");
2096 const double sign_of_normal = (sign_of_intersection >= 0) ? -1. : +1.;
2097 LOG(4, "DEBUG: Opposite normal direction is "
2098 << sign_of_normal * BaseLineNormal[0] << ".");
2099 BTS->GetNormalVector(sign_of_normal * BaseLineNormal[0]);
2100 }
2101 AddTesselationTriangle(OldTriangleNrs[1]);
2102 LOG(3, "DEBUG: Created new triangle " << *BTS << ".");
2103 } else {
2104 ELOG(0, "The four old lines do not connect, something's utterly wrong here!");
2105 return NULL;
2106 }
2107
2108 return NewLine;
2109}
2110;
2111
2112/** Finds the second point of starting triangle.
2113 * \param *a first node
2114 * \param Oben vector indicating the outside
2115 * \param OptCandidate reference to recommended candidate on return
2116 * \param Storage[3] array storing angles and other candidate information
2117 * \param RADIUS radius of virtual sphere
2118 * \param *LC LinkedCell_deprecated structure with neighbouring points
2119 */
2120void Tesselation::FindSecondPointForTesselation(TesselPoint* a, Vector Oben, TesselPoint*& OptCandidate, double Storage[3], double RADIUS, const LinkedCell_deprecated *LC)
2121{
2122 //Info FunctionInfo(__func__);
2123 Vector AngleCheck;
2124 class TesselPoint* Candidate = NULL;
2125 double norm = -1.;
2126 double angle = 0.;
2127 int N[NDIM];
2128 int Nlower[NDIM];
2129 int Nupper[NDIM];
2130
2131 if (LC->SetIndexToNode(a)) { // get cell for the starting point
2132 for (int i = 0; i < NDIM; i++) // store indices of this cell
2133 N[i] = LC->n[i];
2134 } else {
2135 ELOG(1, "Point " << *a << " is not found in cell " << LC->index << ".");
2136 return;
2137 }
2138 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2139 for (int i = 0; i < NDIM; i++) {
2140 Nlower[i] = ((N[i] - 1) >= 0) ? N[i] - 1 : 0;
2141 Nupper[i] = ((N[i] + 1) < LC->N[i]) ? N[i] + 1 : LC->N[i] - 1;
2142 }
2143 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] << "], ");
2144
2145 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2146 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2147 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2148 const TesselPointSTLList *List = LC->GetCurrentCell();
2149 //LOG(1, "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << ".");
2150 if (List != NULL) {
2151 for (TesselPointSTLList::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2152 Candidate = (*Runner);
2153 // check if we only have one unique point yet ...
2154 if (a != Candidate) {
2155 // Calculate center of the circle with radius RADIUS through points a and Candidate
2156 Vector OrthogonalizedOben, aCandidate, Center;
2157 double distance, scaleFactor;
2158
2159 OrthogonalizedOben = Oben;
2160 aCandidate = (a->getPosition()) - (Candidate->getPosition());
2161 OrthogonalizedOben.ProjectOntoPlane(aCandidate);
2162 OrthogonalizedOben.Normalize();
2163 distance = 0.5 * aCandidate.Norm();
2164 scaleFactor = sqrt(((RADIUS * RADIUS) - (distance * distance)));
2165 OrthogonalizedOben.Scale(scaleFactor);
2166
2167 Center = 0.5 * ((Candidate->getPosition()) + (a->getPosition()));
2168 Center += OrthogonalizedOben;
2169
2170 AngleCheck = Center - (a->getPosition());
2171 norm = aCandidate.Norm();
2172 // second point shall have smallest angle with respect to Oben vector
2173 if (norm < RADIUS * 2.) {
2174 angle = AngleCheck.Angle(Oben);
2175 if (angle < Storage[0]) {
2176 //LOG(1, "INFO: Old values of Storage is " << Storage[0] << ", " << Storage[1]);
2177 LOG(4, "DEBUG: Current candidate is " << *Candidate << ": Is a better candidate with distance " << norm << " and angle " << angle << " to oben " << Oben << ".");
2178 OptCandidate = Candidate;
2179 Storage[0] = angle;
2180 //LOG(4, "DEBUG: Changing something in Storage is " << Storage[0] << ", " << Storage[1]);
2181 } else {
2182 //LOG(4, "DEBUG: Current candidate is " << *Candidate << ": Looses with angle " << angle << " to a better candidate " << *OptCandidate);
2183 }
2184 } else {
2185 //LOG(4, "DEBUG: Current candidate is " << *Candidate << ": Refused due to Radius " << norm);
2186 }
2187 } else {
2188 //LOG(4, "DEBUG: Current candidate is " << *Candidate << ": Candidate is equal to first endpoint." << *a << ".");
2189 }
2190 }
2191 } else {
2192 LOG(4, "DEBUG: Linked cell list is empty.");
2193 }
2194 }
2195}
2196;
2197
2198/** This recursive function finds a third point, to form a triangle with two given ones.
2199 * Note that this function is for the starting triangle.
2200 * The idea is as follows: A sphere with fixed radius is (almost) uniquely defined in space by three points
2201 * that sit on its boundary. Hence, when two points are given and we look for the (next) third point, then
2202 * the center of the sphere is still fixed up to a single parameter. The band of possible values
2203 * describes a circle in 3D-space. The old center of the sphere for the current base triangle gives
2204 * us the "null" on this circle, the new center of the candidate point will be some way along this
2205 * circle. The shorter the way the better is the candidate. Note that the direction is clearly given
2206 * by the normal vector of the base triangle that always points outwards by construction.
2207 * Hence, we construct a Center of this circle which sits right in the middle of the current base line.
2208 * We construct the normal vector that defines the plane this circle lies in, it is just in the
2209 * direction of the baseline. And finally, we need the radius of the circle, which is given by the rest
2210 * with respect to the length of the baseline and the sphere's fixed \a RADIUS.
2211 * Note that there is one difficulty: The circumcircle is uniquely defined, but for the circumsphere's center
2212 * there are two possibilities which becomes clear from the construction as seen below. Hence, we must check
2213 * both.
2214 * Note also that the acos() function is not unique on [0, 2.*M_PI). Hence, we need an additional check
2215 * to decide for one of the two possible angles. Therefore we need a SearchDirection and to make this check
2216 * sensible we need OldSphereCenter to be orthogonal to it. Either we construct SearchDirection orthogonal
2217 * right away, or -- what we do here -- we rotate the relative sphere centers such that this orthogonality
2218 * holds. Then, the normalized projection onto the SearchDirection is either +1 or -1 and thus states whether
2219 * the angle is uniquely in either (0,M_PI] or [M_PI, 2.*M_PI).
2220 * @param NormalVector normal direction of the base triangle (here the unit axis vector, \sa FindStartingTriangle())
2221 * @param SearchDirection general direction where to search for the next point, relative to center of BaseLine
2222 * @param OldSphereCenter center of sphere for base triangle, relative to center of BaseLine, giving null angle for the parameter circle
2223 * @param CandidateLine CandidateForTesselation with the current base line and list of candidates and ShortestAngle
2224 * @param ThirdPoint third point to avoid in search
2225 * @param RADIUS radius of sphere
2226 * @param *LC LinkedCell_deprecated structure with neighbouring points
2227 */
2228void 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
2229{
2230 //Info FunctionInfo(__func__);
2231 Vector CircleCenter; // center of the circle, i.e. of the band of sphere's centers
2232 Vector CirclePlaneNormal; // normal vector defining the plane this circle lives in
2233 Vector SphereCenter;
2234 Vector NewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, first possibility
2235 Vector OtherNewSphereCenter; // center of the sphere defined by the two points of BaseLine and the one of Candidate, second possibility
2236 Vector NewNormalVector; // normal vector of the Candidate's triangle
2237 Vector helper, OptCandidateCenter, OtherOptCandidateCenter;
2238 Vector RelativeOldSphereCenter;
2239 Vector NewPlaneCenter;
2240 double CircleRadius; // radius of this circle
2241 double radius;
2242 double otherradius;
2243 double alpha, Otheralpha; // angles (i.e. parameter for the circle).
2244 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2245 TesselPoint *Candidate = NULL;
2246
2247 LOG(4, "DEBUG: NormalVector of BaseTriangle is " << NormalVector << ".");
2248
2249 // copy old center
2250 CandidateLine.OldCenter = OldSphereCenter;
2251 CandidateLine.ThirdPoint = ThirdPoint;
2252 CandidateLine.pointlist.clear();
2253
2254 // construct center of circle
2255 CircleCenter = 0.5 * ((CandidateLine.BaseLine->endpoints[0]->node->getPosition()) + (CandidateLine.BaseLine->endpoints[1]->node->getPosition()));
2256
2257 // construct normal vector of circle
2258 CirclePlaneNormal = (CandidateLine.BaseLine->endpoints[0]->node->getPosition()) - (CandidateLine.BaseLine->endpoints[1]->node->getPosition());
2259
2260 RelativeOldSphereCenter = OldSphereCenter - CircleCenter;
2261
2262 // calculate squared radius TesselPoint *ThirdPoint,f circle
2263 radius = CirclePlaneNormal.NormSquared() / 4.;
2264 if (radius < RADIUS * RADIUS) {
2265 CircleRadius = RADIUS * RADIUS - radius;
2266 CirclePlaneNormal.Normalize();
2267 LOG(4, "DEBUG: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << ".");
2268
2269 // test whether old center is on the band's plane
2270 if (fabs(RelativeOldSphereCenter.ScalarProduct(CirclePlaneNormal)) > HULLEPSILON) {
2271 ELOG(1, "Something's very wrong here: RelativeOldSphereCenter is not on the band's plane as desired by " << fabs(RelativeOldSphereCenter.ScalarProduct(CirclePlaneNormal)) << "!");
2272 RelativeOldSphereCenter.ProjectOntoPlane(CirclePlaneNormal);
2273 }
2274 radius = RelativeOldSphereCenter.NormSquared();
2275 if (fabs(radius - CircleRadius) < HULLEPSILON) {
2276 LOG(4, "DEBUG: RelativeOldSphereCenter is at " << RelativeOldSphereCenter << ".");
2277
2278 // check SearchDirection
2279 LOG(4, "DEBUG: SearchDirection is " << SearchDirection << ".");
2280 if (fabs(RelativeOldSphereCenter.ScalarProduct(SearchDirection)) > HULLEPSILON) { // rotated the wrong way!
2281 ELOG(1, "SearchDirection and RelativeOldSphereCenter are not orthogonal!");
2282 }
2283
2284 // get cell for the starting point
2285 if (LC->SetIndexToVector(CircleCenter)) {
2286 for (int i = 0; i < NDIM; i++) // store indices of this cell
2287 N[i] = LC->n[i];
2288 //LOG(1, "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << ".");
2289 } else {
2290 ELOG(1, "Vector " << CircleCenter << " is outside of LinkedCell's bounding box.");
2291 return;
2292 }
2293 // then go through the current and all neighbouring cells and check the contained points for possible candidates
2294// if (DoLog(3)) {
2295// std::stringstream output;
2296// output << "LC Intervals:";
2297// for (int i = 0; i < NDIM; i++)
2298// output << " [" << Nlower[i] << "," << Nupper[i] << "] ";
2299// LOG(0, output.str());
2300// }
2301 for (int i = 0; i < NDIM; i++) {
2302 Nlower[i] = ((N[i] - 1) >= 0) ? N[i] - 1 : 0;
2303 Nupper[i] = ((N[i] + 1) < LC->N[i]) ? N[i] + 1 : LC->N[i] - 1;
2304 }
2305 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2306 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2307 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2308 const TesselPointSTLList *List = LC->GetCurrentCell();
2309 //LOG(1, "Current cell is " << LC->n[0] << ", " << LC->n[1] << ", " << LC->n[2] << " with No. " << LC->index << ".");
2310 if (List != NULL) {
2311 for (TesselPointSTLList::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2312 Candidate = (*Runner);
2313
2314 // check for three unique points
2315 LOG(4, "DEBUG: Current Candidate is " << *Candidate << " for BaseLine " << *CandidateLine.BaseLine << " with OldSphereCenter " << OldSphereCenter << ".");
2316 if ((Candidate != CandidateLine.BaseLine->endpoints[0]->node) && (Candidate != CandidateLine.BaseLine->endpoints[1]->node)) {
2317
2318 // find center on the plane
2319 GetCenterofCircumcircle(NewPlaneCenter, CandidateLine.BaseLine->endpoints[0]->node->getPosition(), CandidateLine.BaseLine->endpoints[1]->node->getPosition(), Candidate->getPosition());
2320 LOG(5, "DEBUG: NewPlaneCenter is " << NewPlaneCenter << ".");
2321
2322 try {
2323 NewNormalVector = Plane((CandidateLine.BaseLine->endpoints[0]->node->getPosition()), (CandidateLine.BaseLine->endpoints[1]->node->getPosition()), (Candidate->getPosition())).getNormal();
2324 LOG(5, "DEBUG: NewNormalVector is " << NewNormalVector << ".");
2325 radius = CandidateLine.BaseLine->endpoints[0]->node->DistanceSquared(NewPlaneCenter);
2326 LOG(5, "DEBUG: CircleCenter is at " << CircleCenter << ", CirclePlaneNormal is " << CirclePlaneNormal << " with circle radius " << sqrt(CircleRadius) << ".");
2327 LOG(5, "DEBUG: SearchDirection is " << SearchDirection << ".");
2328 LOG(5, "DEBUG: Radius of CircumCenterCircle is " << radius << ".");
2329 if (radius < RADIUS * RADIUS) {
2330 otherradius = CandidateLine.BaseLine->endpoints[1]->node->DistanceSquared(NewPlaneCenter);
2331 if (fabs(radius - otherradius) < HULLEPSILON) {
2332 // construct both new centers
2333 NewSphereCenter = NewPlaneCenter;
2334 OtherNewSphereCenter = NewPlaneCenter;
2335 helper = NewNormalVector;
2336 helper.Scale(sqrt(RADIUS * RADIUS - radius));
2337 LOG(5, "DEBUG: Distance of NewPlaneCenter " << NewPlaneCenter << " to either NewSphereCenter is " << helper.Norm() << " of vector " << helper << " with sphere radius " << RADIUS << ".");
2338 NewSphereCenter += helper;
2339 LOG(5, "DEBUG: NewSphereCenter is at " << NewSphereCenter << ".");
2340 // OtherNewSphereCenter is created by the same vector just in the other direction
2341 helper.Scale(-1.);
2342 OtherNewSphereCenter += helper;
2343 LOG(5, "DEBUG: OtherNewSphereCenter is at " << OtherNewSphereCenter << ".");
2344 alpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, NewSphereCenter, OldSphereCenter, NormalVector, SearchDirection, HULLEPSILON);
2345 Otheralpha = GetPathLengthonCircumCircle(CircleCenter, CirclePlaneNormal, CircleRadius, OtherNewSphereCenter, OldSphereCenter, NormalVector, SearchDirection, HULLEPSILON);
2346 if ((ThirdPoint != NULL) && (Candidate == ThirdPoint->node)) { // in that case only the other circlecenter is valid
2347 if (OldSphereCenter.DistanceSquared(NewSphereCenter) < OldSphereCenter.DistanceSquared(OtherNewSphereCenter))
2348 alpha = Otheralpha;
2349 } else
2350 alpha = min(alpha, Otheralpha);
2351 // if there is a better candidate, drop the current list and add the new candidate
2352 // otherwise ignore the new candidate and keep the list
2353 if (CandidateLine.ShortestAngle > (alpha - HULLEPSILON)) {
2354 if (fabs(alpha - Otheralpha) > MYEPSILON) {
2355 CandidateLine.OptCenter = NewSphereCenter;
2356 CandidateLine.OtherOptCenter = OtherNewSphereCenter;
2357 } else {
2358 CandidateLine.OptCenter = OtherNewSphereCenter;
2359 CandidateLine.OtherOptCenter = NewSphereCenter;
2360 }
2361 // if there is an equal candidate, add it to the list without clearing the list
2362 if ((CandidateLine.ShortestAngle - HULLEPSILON) < alpha) {
2363 CandidateLine.pointlist.push_back(Candidate);
2364 LOG(3, "ACCEPT: We have found an equally good candidate: " << *(Candidate) << " with " << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << ".");
2365 } else {
2366 // remove all candidates from the list and then the list itself
2367 CandidateLine.pointlist.clear();
2368 CandidateLine.pointlist.push_back(Candidate);
2369 LOG(3, "ACCEPT: We have found a better candidate: " << *(Candidate) << " with " << alpha << " and circumsphere's center at " << CandidateLine.OptCenter << ".");
2370 }
2371 CandidateLine.ShortestAngle = alpha;
2372 LOG(4, "DEBUG: There are " << CandidateLine.pointlist.size() << " candidates in the list now.");
2373 } else {
2374 if ((Candidate != NULL) && (CandidateLine.pointlist.begin() != CandidateLine.pointlist.end())) {
2375 LOG(4, "REJECT: Old candidate " << *(*CandidateLine.pointlist.begin()) << " with " << CandidateLine.ShortestAngle << " is better than new one " << *Candidate << " with " << alpha << " .");
2376 } else {
2377 LOG(4, "REJECT: Candidate " << *Candidate << " with " << alpha << " was rejected.");
2378 }
2379 }
2380 } else {
2381 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)));
2382 }
2383 } else {
2384 LOG(4, "REJECT: NewSphereCenter " << NewSphereCenter << " for " << *Candidate << " is too far away: " << radius << ".");
2385 }
2386 } catch (LinearDependenceException &excp) {
2387 LOG(4, boost::diagnostic_information(excp));
2388 LOG(4, "REJECT: Three points from " << *CandidateLine.BaseLine << " and Candidate " << *Candidate << " are linear-dependent.");
2389 }
2390 } else {
2391 if (ThirdPoint != NULL) {
2392 LOG(4, "REJECT: Base triangle " << *CandidateLine.BaseLine << " and " << *ThirdPoint << " contains Candidate " << *Candidate << ".");
2393 } else {
2394 LOG(4, "REJECT: Base triangle " << *CandidateLine.BaseLine << " contains Candidate " << *Candidate << ".");
2395 }
2396 }
2397 }
2398 }
2399 }
2400 } else {
2401 ELOG(1, "The projected center of the old sphere has radius " << radius << " instead of " << CircleRadius << ".");
2402 }
2403 } else {
2404 if (ThirdPoint != NULL)
2405 LOG(4, "DEBUG: Circumcircle for base line " << *CandidateLine.BaseLine << " and third node " << *ThirdPoint << " is too big!");
2406 else
2407 LOG(4, "DEBUG: Circumcircle for base line " << *CandidateLine.BaseLine << " is too big!");
2408 }
2409
2410 LOG(5, "DEBUG: Sorting candidate list ...");
2411 if (CandidateLine.pointlist.size() > 1) {
2412 CandidateLine.pointlist.unique();
2413 CandidateLine.pointlist.sort(); //SortCandidates);
2414 }
2415
2416 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!"));
2417}
2418;
2419
2420/** Finds the endpoint two lines are sharing.
2421 * \param *line1 first line
2422 * \param *line2 second line
2423 * \return point which is shared or NULL if none
2424 */
2425class BoundaryPointSet *Tesselation::GetCommonEndpoint(const BoundaryLineSet * line1, const BoundaryLineSet * line2) const
2426{
2427 //Info FunctionInfo(__func__);
2428 const BoundaryLineSet * lines[2] = {line1, line2};
2429 class BoundaryPointSet *node = NULL;
2430 PointMap OrderMap;
2431 PointTestPair OrderTest;
2432 for (int i = 0; i < 2; i++)
2433 // for both lines
2434 for (int j = 0; j < 2; j++) { // for both endpoints
2435 OrderTest = OrderMap.insert(pair<int, class BoundaryPointSet *>(lines[i]->endpoints[j]->Nr, lines[i]->endpoints[j]));
2436 if (!OrderTest.second) { // if insertion fails, we have common endpoint
2437 node = OrderTest.first->second;
2438 LOG(1, "Common endpoint of lines " << *line1 << " and " << *line2 << " is: " << *node << ".");
2439 j = 2;
2440 i = 2;
2441 break;
2442 }
2443 }
2444 return node;
2445}
2446;
2447
2448/** Finds the boundary points that are closest to a given Vector \a *x.
2449 * \param *out output stream for debugging
2450 * \param *x Vector to look from
2451 * \return map of BoundaryPointSet of closest points sorted by squared distance or NULL.
2452 */
2453DistanceToPointMap * Tesselation::FindClosestBoundaryPointsToVector(const Vector &x, const LinkedCell_deprecated* LC) const
2454{
2455 //Info FunctionInfo(__func__);
2456 PointMap::const_iterator FindPoint;
2457 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
2458
2459 if (LinesOnBoundary.empty()) {
2460 ELOG(1, "There is no tesselation structure to compare the point with, please create one first.");
2461 return NULL;
2462 }
2463
2464 // gather all points close to the desired one
2465 LC->SetIndexToVector(x); // ignore status as we calculate bounds below sensibly
2466 for (int i = 0; i < NDIM; i++) // store indices of this cell
2467 N[i] = LC->n[i];
2468 LOG(2, "DEBUG: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << ".");
2469 DistanceToPointMap * points = new DistanceToPointMap;
2470 LC->GetNeighbourBounds(Nlower, Nupper);
2471 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
2472 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
2473 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
2474 const TesselPointSTLList *List = LC->GetCurrentCell();
2475 //LOG(1, "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2]);
2476 if (List != NULL) {
2477 for (TesselPointSTLList::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
2478 FindPoint = PointsOnBoundary.find((*Runner)->getNr());
2479 if (FindPoint != PointsOnBoundary.end()) {
2480 // when the closest point is on the edge of a triangle (and hence
2481 // we find two closes triangles due to it having an adjacent one)
2482 // we should make sure that both triangles end up in the same entry
2483 // in the distance multimap. Hence, we round to 6 digit precision.
2484 const double distance = 1e-6 * floor(FindPoint->second->node->DistanceSquared(x) * 1e+6);
2485 points->insert(DistanceToPointPair(distance, FindPoint->second));
2486 LOG(3, "DEBUG: Putting " << *FindPoint->second << " into the list.");
2487 }
2488 }
2489 } else {
2490 ELOG(1, "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << " is invalid!");
2491 }
2492 }
2493
2494 // check whether we found some points
2495 if (points->empty()) {
2496 ELOG(1, "There is no nearest point: too far away from the surface.");
2497 delete (points);
2498 return NULL;
2499 }
2500 return points;
2501}
2502;
2503
2504/** Finds the boundary line that is closest to a given Vector \a *x.
2505 * \param *out output stream for debugging
2506 * \param *x Vector to look from
2507 * \return closest BoundaryLineSet or NULL in degenerate case.
2508 */
2509BoundaryLineSet * Tesselation::FindClosestBoundaryLineToVector(const Vector &x, const LinkedCell_deprecated* LC) const
2510{
2511 //Info FunctionInfo(__func__);
2512 // get closest points
2513 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x, LC);
2514 if (points == NULL) {
2515 ELOG(1, "There is no nearest point: too far away from the surface.");
2516 return NULL;
2517 }
2518
2519 // for each point, check its lines, remember closest
2520 LOG(1, "Finding closest BoundaryLine to " << x << " ... ");
2521 BoundaryLineSet *ClosestLine = NULL;
2522 double MinDistance = -1.;
2523 Vector helper;
2524 Vector Center;
2525 Vector BaseLine;
2526 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
2527 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
2528 // calculate closest point on line to desired point
2529 helper = 0.5 * (((LineRunner->second)->endpoints[0]->node->getPosition()) + ((LineRunner->second)->endpoints[1]->node->getPosition()));
2530 Center = (x) - helper;
2531 BaseLine = ((LineRunner->second)->endpoints[0]->node->getPosition()) - ((LineRunner->second)->endpoints[1]->node->getPosition());
2532 Center.ProjectOntoPlane(BaseLine);
2533 const double distance = Center.NormSquared();
2534 if ((ClosestLine == NULL) || (distance < MinDistance)) {
2535 // additionally calculate intersection on line (whether it's on the line section or not)
2536 helper = (x) - ((LineRunner->second)->endpoints[0]->node->getPosition()) - Center;
2537 const double lengthA = helper.ScalarProduct(BaseLine);
2538 helper = (x) - ((LineRunner->second)->endpoints[1]->node->getPosition()) - Center;
2539 const double lengthB = helper.ScalarProduct(BaseLine);
2540 if (lengthB * lengthA < 0) { // if have different sign
2541 ClosestLine = LineRunner->second;
2542 MinDistance = distance;
2543 LOG(1, "ACCEPT: New closest line is " << *ClosestLine << " with projected distance " << MinDistance << ".");
2544 } else {
2545 LOG(1, "REJECT: Intersection is outside of the line section: " << lengthA << " and " << lengthB << ".");
2546 }
2547 } else {
2548 LOG(1, "REJECT: Point is too further away than present line: " << distance << " >> " << MinDistance << ".");
2549 }
2550 }
2551 }
2552 delete (points);
2553 // check whether closest line is "too close" :), then it's inside
2554 if (ClosestLine == NULL) {
2555 LOG(2, "DEBUG: Is the only point, no one else is closeby.");
2556 return NULL;
2557 }
2558 return ClosestLine;
2559}
2560;
2561
2562/** Finds the triangle that is closest to a given Vector \a *x.
2563 * \param *out output stream for debugging
2564 * \param *x Vector to look from
2565 * \return BoundaryTriangleSet of nearest triangle or NULL.
2566 */
2567TriangleList * Tesselation::FindClosestTrianglesToVector(const Vector &x, const LinkedCell_deprecated* LC) const
2568{
2569 //Info FunctionInfo(__func__);
2570 // get closest points
2571 DistanceToPointMap * points = FindClosestBoundaryPointsToVector(x, LC);
2572 if (points == NULL) {
2573 ELOG(1, "There is no nearest point: too far away from the surface.");
2574 return NULL;
2575 }
2576
2577 // for each point, check its lines, remember closest
2578 LOG(1, "Finding closest BoundaryTriangle to " << x << " ... ");
2579 LineSet ClosestLines;
2580 double MinDistance = 1e+16;
2581 Vector BaseLineIntersection;
2582 Vector Center;
2583 Vector BaseLine;
2584 Vector BaseLineCenter;
2585 for (DistanceToPointMap::iterator Runner = points->begin(); Runner != points->end(); Runner++) {
2586 for (LineMap::iterator LineRunner = Runner->second->lines.begin(); LineRunner != Runner->second->lines.end(); LineRunner++) {
2587
2588 BaseLine = ((LineRunner->second)->endpoints[0]->node->getPosition()) - ((LineRunner->second)->endpoints[1]->node->getPosition());
2589 const double lengthBase = BaseLine.NormSquared();
2590
2591 BaseLineIntersection = (x) - ((LineRunner->second)->endpoints[0]->node->getPosition());
2592 const double lengthEndA = BaseLineIntersection.NormSquared();
2593
2594 BaseLineIntersection = (x) - ((LineRunner->second)->endpoints[1]->node->getPosition());
2595 const double lengthEndB = BaseLineIntersection.NormSquared();
2596
2597 if ((lengthEndA > lengthBase) || (lengthEndB > lengthBase) || ((lengthEndA < MYEPSILON) || (lengthEndB < MYEPSILON))) { // intersection would be outside, take closer endpoint
2598 const double lengthEnd = std::min(lengthEndA, lengthEndB);
2599 if (lengthEnd - MinDistance < -MYEPSILON) { // new best line
2600 ClosestLines.clear();
2601 ClosestLines.insert(LineRunner->second);
2602 MinDistance = lengthEnd;
2603 LOG(1, "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[0]->node << " is closer with " << lengthEnd << ".");
2604 } else
2605 if (fabs(lengthEnd - MinDistance) < MYEPSILON) { // additional best candidate
2606 ClosestLines.insert(LineRunner->second);
2607 LOG(1, "ACCEPT: Line " << *LineRunner->second << " to endpoint " << *LineRunner->second->endpoints[1]->node << " is equally good with " << lengthEnd << ".");
2608 } else { // line is worse
2609 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 << ".");
2610 }
2611 } else { // intersection is closer, calculate
2612 // calculate closest point on line to desired point
2613 BaseLineIntersection = (x) - ((LineRunner->second)->endpoints[1]->node->getPosition());
2614 Center = BaseLineIntersection;
2615 Center.ProjectOntoPlane(BaseLine);
2616 BaseLineIntersection -= Center;
2617 const double distance = BaseLineIntersection.NormSquared();
2618 if (Center.NormSquared() > BaseLine.NormSquared()) {
2619 ELOG(0, "Algorithmic error: In second case we have intersection outside of baseline!");
2620 }
2621 if ((ClosestLines.empty()) || (distance < MinDistance)) {
2622 ClosestLines.insert(LineRunner->second);
2623 MinDistance = distance;
2624 LOG(1, "ACCEPT: Intersection in between endpoints, new closest line " << *LineRunner->second << " is " << *ClosestLines.begin() << " with projected distance " << MinDistance << ".");
2625 } else {
2626 LOG(2, "REJECT: Point is further away from line " << *LineRunner->second << " than present closest line: " << distance << " >> " << MinDistance << ".");
2627 }
2628 }
2629 }
2630 }
2631 delete (points);
2632
2633 // check whether closest line is "too close" :), then it's inside
2634 if (ClosestLines.empty()) {
2635 LOG(2, "DEBUG: Is the only point, no one else is closeby.");
2636 return NULL;
2637 }
2638 TriangleList * candidates = new TriangleList;
2639 for (LineSet::iterator LineRunner = ClosestLines.begin(); LineRunner != ClosestLines.end(); LineRunner++)
2640 for (TriangleMap::iterator Runner = (*LineRunner)->triangles.begin(); Runner != (*LineRunner)->triangles.end(); Runner++) {
2641 candidates->push_back(Runner->second);
2642 }
2643 return candidates;
2644}
2645;
2646
2647/** Finds closest triangle to a point.
2648 * This basically just takes care of the degenerate case, which is not handled in FindClosestTrianglesToPoint().
2649 * \param *out output stream for debugging
2650 * \param *x Vector to look from
2651 * \param &distance contains found distance on return
2652 * \return list of BoundaryTriangleSet of nearest triangles or NULL.
2653 */
2654class BoundaryTriangleSet * Tesselation::FindClosestTriangleToVector(const Vector &x, const LinkedCell_deprecated* LC) const
2655{
2656 //Info FunctionInfo(__func__);
2657 class BoundaryTriangleSet *result = NULL;
2658 TriangleList *triangles = FindClosestTrianglesToVector(x, LC);
2659 TriangleList candidates;
2660 Vector Center;
2661 Vector helper;
2662
2663 if ((triangles == NULL) || (triangles->empty()))
2664 return NULL;
2665
2666 // go through all and pick the one with the best alignment to x
2667 double MinAlignment = 2. * M_PI;
2668 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++) {
2669 (*Runner)->GetCenter(Center);
2670 helper = (x) - Center;
2671 const double Alignment = helper.Angle((*Runner)->NormalVector);
2672 if (Alignment < MinAlignment) {
2673 result = *Runner;
2674 MinAlignment = Alignment;
2675 LOG(1, "ACCEPT: Triangle " << *result << " is better aligned with " << MinAlignment << ".");
2676 } else {
2677 LOG(1, "REJECT: Triangle " << *result << " is worse aligned with " << MinAlignment << ".");
2678 }
2679 }
2680 delete (triangles);
2681
2682 return result;
2683}
2684;
2685
2686/** Checks whether the provided Vector is within the Tesselation structure.
2687 * Basically calls Tesselation::GetDistanceToSurface() and checks the sign of the return value.
2688 * @param point of which to check the position
2689 * @param *LC LinkedCell_deprecated structure
2690 *
2691 * @return true if the point is inside the Tesselation structure, false otherwise
2692 */
2693bool Tesselation::IsInnerPoint(const Vector &Point, const LinkedCell_deprecated* const LC) const
2694{
2695 TriangleIntersectionList Intersections(Point, this, LC);
2696 return Intersections.IsInside();
2697}
2698
2699Vector Tesselation::getNormal(const Vector &Point, const LinkedCell_deprecated* const LC) const
2700{
2701 TriangleIntersectionList Intersections(Point, this, LC);
2702 BoundaryTriangleSet *triangle = Intersections.GetClosestTriangle();
2703 if (triangle != NULL) {
2704 return triangle->NormalVector;
2705 } else
2706 return zeroVec;
2707}
2708
2709/** Returns the distance to the surface given by the tesselation.
2710 * Calls FindClosestTriangleToVector() and checks whether the resulting triangle's BoundaryTriangleSet#NormalVector points
2711 * towards or away from the given \a &Point. Additionally, we check whether it's normal to the normal vector, i.e. on the
2712 * closest triangle's plane. Then, we have to check whether \a Point is inside the triangle or not to determine whether it's
2713 * an inside or outside point. This is done by calling BoundaryTriangleSet::GetIntersectionInsideTriangle().
2714 * In the end we additionally find the point on the triangle who was smallest distance to \a Point:
2715 * -# Separate distance from point to center in vector in NormalDirection and on the triangle plane.
2716 * -# Check whether vector on triangle plane points inside the triangle or crosses triangle bounds.
2717 * -# If inside, take it to calculate closest distance
2718 * -# If not, take intersection with BoundaryLine as distance
2719 *
2720 * @note distance is squared despite it still contains a sign to determine in-/outside!
2721 *
2722 * @param point of which to check the position
2723 * @param *LC LinkedCell_deprecated structure
2724 *
2725 * @return >0 if outside, ==0 if on surface, <0 if inside
2726 */
2727double Tesselation::GetDistanceSquaredToTriangle(const Vector &Point, const BoundaryTriangleSet* const triangle) const
2728{
2729 //Info FunctionInfo(__func__);
2730 Vector Center;
2731 Vector helper;
2732 Vector DistanceToCenter;
2733 Vector Intersection;
2734 double distance = 0.;
2735
2736 if (triangle == NULL) { // is boundary point or only point in point cloud?
2737 LOG(1, "No triangle given!");
2738 return -1.;
2739 } else {
2740 LOG(1, "INFO: Closest triangle found is " << *triangle << " with normal vector " << triangle->NormalVector << ".");
2741 }
2742
2743 triangle->GetCenter(Center);
2744 LOG(2, "INFO: Central point of the triangle is " << Center << ".");
2745 DistanceToCenter = Center - Point;
2746 LOG(2, "INFO: Vector from point to test to center is " << DistanceToCenter << ".");
2747
2748 // check whether we are on boundary
2749 if (fabs(DistanceToCenter.ScalarProduct(triangle->NormalVector)) < MYEPSILON) {
2750 // calculate whether inside of triangle
2751 DistanceToCenter = Point + triangle->NormalVector; // points outside
2752 Center = Point - triangle->NormalVector; // points towards MolCenter
2753 LOG(1, "INFO: Calling Intersection with " << Center << " and " << DistanceToCenter << ".");
2754 if (triangle->GetIntersectionInsideTriangle(Center, DistanceToCenter, Intersection)) {
2755 LOG(1, Point << " is inner point: sufficiently close to boundary, " << Intersection << ".");
2756 return 0.;
2757 } else {
2758 LOG(1, Point << " is NOT an inner point: on triangle plane but outside of triangle bounds.");
2759 return false;
2760 }
2761 } else {
2762 // calculate smallest distance
2763 distance = triangle->GetClosestPointInsideTriangle(Point, Intersection);
2764 LOG(1, "Closest point on triangle is " << Intersection << ".");
2765
2766 // then check direction to boundary
2767 if (DistanceToCenter.ScalarProduct(triangle->NormalVector) > MYEPSILON) {
2768 LOG(1, Point << " is an inner point, " << distance << " below surface.");
2769 return -distance;
2770 } else {
2771 LOG(1, Point << " is NOT an inner point, " << distance << " above surface.");
2772 return +distance;
2773 }
2774 }
2775}
2776;
2777
2778/** Calculates minimum distance from \a&Point to a tesselated surface.
2779 * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
2780 * \param &Point point to calculate distance from
2781 * \param *LC needed for finding closest points fast
2782 * \return distance squared to closest point on surface
2783 */
2784double Tesselation::GetDistanceToSurface(const Vector &Point, const LinkedCell_deprecated* const LC) const
2785{
2786 //Info FunctionInfo(__func__);
2787 TriangleIntersectionList Intersections(Point, this, LC);
2788
2789 return Intersections.GetSmallestDistance();
2790}
2791;
2792
2793/** Calculates minimum distance from \a&Point to a tesselated surface.
2794 * Combines \sa FindClosestTrianglesToVector() and \sa GetDistanceSquaredToTriangle().
2795 * \param &Point point to calculate distance from
2796 * \param *LC needed for finding closest points fast
2797 * \return distance squared to closest point on surface
2798 */
2799BoundaryTriangleSet * Tesselation::GetClosestTriangleOnSurface(const Vector &Point, const LinkedCell_deprecated* const LC) const
2800{
2801 //Info FunctionInfo(__func__);
2802 TriangleIntersectionList Intersections(Point, this, LC);
2803
2804 return Intersections.GetClosestTriangle();
2805}
2806;
2807
2808/** Gets all points connected to the provided point by triangulation lines.
2809 *
2810 * @param *Point of which get all connected points
2811 *
2812 * @return set of the all points linked to the provided one
2813 */
2814TesselPointSet * Tesselation::GetAllConnectedPoints(const TesselPoint* const Point) const
2815{
2816 //Info FunctionInfo(__func__);
2817 TesselPointSet *connectedPoints = new TesselPointSet;
2818 class BoundaryPointSet *ReferencePoint = NULL;
2819 TesselPoint* current;
2820 bool takePoint = false;
2821 // find the respective boundary point
2822 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->getNr());
2823 if (PointRunner != PointsOnBoundary.end()) {
2824 ReferencePoint = PointRunner->second;
2825 } else {
2826 ELOG(2, "GetAllConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << ".");
2827 ReferencePoint = NULL;
2828 }
2829
2830 // little trick so that we look just through lines connect to the BoundaryPoint
2831 // OR fall-back to look through all lines if there is no such BoundaryPoint
2832 const LineMap *Lines;
2833 ;
2834 if (ReferencePoint != NULL)
2835 Lines = &(ReferencePoint->lines);
2836 else
2837 Lines = &LinesOnBoundary;
2838 LineMap::const_iterator findLines = Lines->begin();
2839 while (findLines != Lines->end()) {
2840 takePoint = false;
2841
2842 if (findLines->second->endpoints[0]->Nr == Point->getNr()) {
2843 takePoint = true;
2844 current = findLines->second->endpoints[1]->node;
2845 } else
2846 if (findLines->second->endpoints[1]->Nr == Point->getNr()) {
2847 takePoint = true;
2848 current = findLines->second->endpoints[0]->node;
2849 }
2850
2851 if (takePoint) {
2852 LOG(1, "INFO: Endpoint " << *current << " of line " << *(findLines->second) << " is enlisted.");
2853 connectedPoints->insert(current);
2854 }
2855
2856 findLines++;
2857 }
2858
2859 if (connectedPoints->empty()) { // if have not found any points
2860 ELOG(1, "We have not found any connected points to " << *Point << ".");
2861 return NULL;
2862 }
2863
2864 return connectedPoints;
2865}
2866;
2867
2868/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2869 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2870 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2871 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2872 * triangle we are looking for.
2873 *
2874 * @param *out output stream for debugging
2875 * @param *SetOfNeighbours all points for which the angle should be calculated
2876 * @param *Point of which get all connected points
2877 * @param *Reference Reference vector for zero angle or NULL for no preference
2878 * @return list of the all points linked to the provided one
2879 */
2880TesselPointList * Tesselation::GetCircleOfConnectedTriangles(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector &Reference) const
2881{
2882 //Info FunctionInfo(__func__);
2883 map<double, TesselPoint*> anglesOfPoints;
2884 TesselPointList *connectedCircle = new TesselPointList;
2885 Vector PlaneNormal;
2886 Vector AngleZero;
2887 Vector OrthogonalVector;
2888 Vector helper;
2889 const TesselPoint * const TrianglePoints[3] = {Point, NULL, NULL};
2890 TriangleList *triangles = NULL;
2891
2892 if (SetOfNeighbours == NULL) {
2893 ELOG(2, "Could not find any connected points!");
2894 delete (connectedCircle);
2895 return NULL;
2896 }
2897
2898 // calculate central point
2899 triangles = FindTriangles(TrianglePoints);
2900 ASSERT((triangles == NULL) || (triangles->empty()), std::string("Tesselation::GetCircleOfConnectedTriangles()") + std::string("Could not find any triangles for point " + toString(*Point) + "."));
2901 for (TriangleList::iterator Runner = triangles->begin(); Runner != triangles->end(); Runner++)
2902 PlaneNormal += (*Runner)->NormalVector;
2903 PlaneNormal.Scale(1.0 / triangles->size());
2904 LOG(4, "DEBUG: Calculated PlaneNormal of all circle points is " << PlaneNormal << ".");
2905 PlaneNormal.Normalize();
2906
2907 // construct one orthogonal vector
2908 AngleZero = (Reference) - (Point->getPosition());
2909 AngleZero.ProjectOntoPlane(PlaneNormal);
2910 if ((AngleZero.NormSquared() < MYEPSILON)) {
2911 LOG(4, "DEBUG: Using alternatively " << (*SetOfNeighbours->begin())->getPosition() << " as angle 0 referencer.");
2912 AngleZero = ((*SetOfNeighbours->begin())->getPosition()) - (Point->getPosition());
2913 AngleZero.ProjectOntoPlane(PlaneNormal);
2914 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!"));
2915 }
2916 LOG(4, "DEBUG: Reference vector on this plane representing angle 0 is " << AngleZero << ".");
2917 if (AngleZero.NormSquared() > MYEPSILON)
2918 OrthogonalVector = Plane(PlaneNormal, AngleZero, 0).getNormal();
2919 else
2920 OrthogonalVector.MakeNormalTo(PlaneNormal);
2921 LOG(4, "DEBUG: OrthogonalVector on plane is " << OrthogonalVector << ".");
2922
2923 // go through all connected points and calculate angle
2924 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
2925 helper = ((*listRunner)->getPosition()) - (Point->getPosition());
2926 helper.ProjectOntoPlane(PlaneNormal);
2927 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
2928 LOG(4, "DEBUG" << angle << " for point " << **listRunner << ".");
2929 anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
2930 }
2931
2932 for (map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
2933 connectedCircle->push_back(AngleRunner->second);
2934 }
2935
2936 return connectedCircle;
2937}
2938
2939/** Gets all points connected to the provided point by triangulation lines, ordered such that we have the circle round the point.
2940 * Maps them down onto the plane designated by the axis \a *Point and \a *Reference. The center of all points
2941 * connected in the tesselation to \a *Point is mapped to spherical coordinates with the zero angle being given
2942 * by the mapped down \a *Reference. Hence, the biggest and the smallest angles are those of the two shanks of the
2943 * triangle we are looking for.
2944 *
2945 * @param *SetOfNeighbours all points for which the angle should be calculated
2946 * @param *Point of which get all connected points
2947 * @param *Reference Reference vector for zero angle or (0,0,0) for no preference
2948 * @return list of the all points linked to the provided one
2949 */
2950TesselPointList * Tesselation::GetCircleOfSetOfPoints(TesselPointSet *SetOfNeighbours, const TesselPoint* const Point, const Vector &Reference) const
2951{
2952 //Info FunctionInfo(__func__);
2953 map<double, TesselPoint*> anglesOfPoints;
2954 TesselPointList *connectedCircle = new TesselPointList;
2955 Vector center;
2956 Vector PlaneNormal;
2957 Vector AngleZero;
2958 Vector OrthogonalVector;
2959 Vector helper;
2960
2961 if (SetOfNeighbours == NULL) {
2962 ELOG(2, "Could not find any connected points!");
2963 delete (connectedCircle);
2964 return NULL;
2965 }
2966
2967 // check whether there's something to do
2968 if (SetOfNeighbours->size() < 3) {
2969 for (TesselPointSet::iterator TesselRunner = SetOfNeighbours->begin(); TesselRunner != SetOfNeighbours->end(); TesselRunner++)
2970 connectedCircle->push_back(*TesselRunner);
2971 return connectedCircle;
2972 }
2973
2974 LOG(1, "INFO: Point is " << *Point << " and Reference is " << Reference << ".");
2975 // calculate central point
2976 TesselPointSet::const_iterator TesselA = SetOfNeighbours->begin();
2977 TesselPointSet::const_iterator TesselB = SetOfNeighbours->begin();
2978 TesselPointSet::const_iterator TesselC = SetOfNeighbours->begin();
2979 TesselB++;
2980 TesselC++;
2981 TesselC++;
2982 int counter = 0;
2983 while (TesselC != SetOfNeighbours->end()) {
2984 helper = Plane(((*TesselA)->getPosition()), ((*TesselB)->getPosition()), ((*TesselC)->getPosition())).getNormal();
2985 LOG(5, "DEBUG: Making normal vector out of " << *(*TesselA) << ", " << *(*TesselB) << " and " << *(*TesselC) << ":" << helper);
2986 counter++;
2987 TesselA++;
2988 TesselB++;
2989 TesselC++;
2990 PlaneNormal += helper;
2991 }
2992 //LOG(0, "Summed vectors " << center << "; number of points " << connectedPoints.size() << "; scale factor " << counter);
2993 PlaneNormal.Scale(1.0 / (double)counter);
2994 // LOG(1, "INFO: Calculated center of all circle points is " << center << ".");
2995 //
2996 // // projection plane of the circle is at the closes Point and normal is pointing away from center of all circle points
2997 // PlaneNormal.CopyVector(Point->node);
2998 // PlaneNormal.SubtractVector(&center);
2999 // PlaneNormal.Normalize();
3000 LOG(4, "DEBUG: Calculated plane normal of circle is " << PlaneNormal << ".");
3001
3002 // construct one orthogonal vector
3003 if (!Reference.IsZero()) {
3004 AngleZero = (Reference) - (Point->getPosition());
3005 AngleZero.ProjectOntoPlane(PlaneNormal);
3006 }
3007 if ((Reference.IsZero()) || (AngleZero.NormSquared() < MYEPSILON)) {
3008 LOG(4, "DEBUG: Using alternatively " << (*SetOfNeighbours->begin())->getPosition() << " as angle 0 referencer.");
3009 AngleZero = ((*SetOfNeighbours->begin())->getPosition()) - (Point->getPosition());
3010 AngleZero.ProjectOntoPlane(PlaneNormal);
3011 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!"));
3012 }
3013 LOG(4, "DEBUG: Reference vector on this plane representing angle 0 is " << AngleZero << ".");
3014 if (AngleZero.NormSquared() > MYEPSILON)
3015 OrthogonalVector = Plane(PlaneNormal, AngleZero, 0).getNormal();
3016 else
3017 OrthogonalVector.MakeNormalTo(PlaneNormal);
3018 LOG(4, "DEBUG: OrthogonalVector on plane is " << OrthogonalVector << ".");
3019
3020 // go through all connected points and calculate angle
3021 pair<map<double, TesselPoint*>::iterator, bool> InserterTest;
3022 for (TesselPointSet::iterator listRunner = SetOfNeighbours->begin(); listRunner != SetOfNeighbours->end(); listRunner++) {
3023 helper = ((*listRunner)->getPosition()) - (Point->getPosition());
3024 helper.ProjectOntoPlane(PlaneNormal);
3025 double angle = GetAngle(helper, AngleZero, OrthogonalVector);
3026 if (angle > M_PI) // the correction is of no use here (and not desired)
3027 angle = 2. * M_PI - angle;
3028 LOG(4, "DEBUG: Calculated angle between " << helper << " and " << AngleZero << " is " << angle << " for point " << **listRunner << ".");
3029 InserterTest = anglesOfPoints.insert(pair<double, TesselPoint*>(angle, (*listRunner)));
3030 ASSERT(InserterTest.second, std::string("Tesselation::GetCircleOfSetOfPoints() - ") + std::string("got two atoms with same angle " + toString(*((InserterTest.first)->second))) + std::string(" and " + toString((*listRunner))));
3031 }
3032
3033 for (map<double, TesselPoint*>::iterator AngleRunner = anglesOfPoints.begin(); AngleRunner != anglesOfPoints.end(); AngleRunner++) {
3034 connectedCircle->push_back(AngleRunner->second);
3035 }
3036
3037 return connectedCircle;
3038}
3039
3040/** Gets all points connected to the provided point by triangulation lines, ordered such that we walk along a closed path.
3041 *
3042 * @param *out output stream for debugging
3043 * @param *Point of which get all connected points
3044 * @return list of the all points linked to the provided one
3045 */
3046ListOfTesselPointList * Tesselation::GetPathsOfConnectedPoints(const TesselPoint* const Point) const
3047{
3048 //Info FunctionInfo(__func__);
3049 map<double, TesselPoint*> anglesOfPoints;
3050 list<TesselPointList *> *ListOfPaths = new list<TesselPointList *>;
3051 TesselPointList *connectedPath = NULL;
3052 Vector center;
3053 Vector PlaneNormal;
3054 Vector AngleZero;
3055 Vector OrthogonalVector;
3056 Vector helper;
3057 class BoundaryPointSet *ReferencePoint = NULL;
3058 class BoundaryPointSet *CurrentPoint = NULL;
3059 class BoundaryTriangleSet *triangle = NULL;
3060 class BoundaryLineSet *CurrentLine = NULL;
3061 class BoundaryLineSet *StartLine = NULL;
3062 // find the respective boundary point
3063 PointMap::const_iterator PointRunner = PointsOnBoundary.find(Point->getNr());
3064 if (PointRunner != PointsOnBoundary.end()) {
3065 ReferencePoint = PointRunner->second;
3066 } else {
3067 ELOG(1, "GetPathOfConnectedPoints() could not find the BoundaryPoint belonging to " << *Point << ".");
3068 return NULL;
3069 }
3070
3071 map<class BoundaryLineSet *, bool> TouchedLine;
3072 map<class BoundaryTriangleSet *, bool> TouchedTriangle;
3073 map<class BoundaryLineSet *, bool>::iterator LineRunner;
3074 map<class BoundaryTriangleSet *, bool>::iterator TriangleRunner;
3075 for (LineMap::iterator Runner = ReferencePoint->lines.begin(); Runner != ReferencePoint->lines.end(); Runner++) {
3076 LOG(4, "DEBUG: Adding " << *Runner->second << " to TouchedLine map.");
3077 TouchedLine.insert(pair<class BoundaryLineSet *, bool>(Runner->second, false));
3078 for (TriangleMap::iterator Sprinter = Runner->second->triangles.begin(); Sprinter != Runner->second->triangles.end(); Sprinter++) {
3079 LOG(4, "DEBUG: Adding " << *Sprinter->second << " to TouchedTriangle map.");
3080 TouchedTriangle.insert(pair<class BoundaryTriangleSet *, bool>(Sprinter->second, false));
3081 }
3082 }
3083 if (!ReferencePoint->lines.empty()) {
3084 for (LineMap::iterator runner = ReferencePoint->lines.begin(); runner != ReferencePoint->lines.end(); runner++) {
3085 LineRunner = TouchedLine.find(runner->second);
3086 if (LineRunner == TouchedLine.end()) {
3087 ELOG(1, "I could not find " << *runner->second << " in the touched list.");
3088 } else
3089 if (!LineRunner->second) {
3090 LineRunner->second = true;
3091 connectedPath = new TesselPointList;
3092 triangle = NULL;
3093 CurrentLine = runner->second;
3094 StartLine = CurrentLine;
3095 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3096 LOG(3, "INFO: Beginning path retrieval at " << *CurrentPoint << " of line " << *CurrentLine << ".");
3097 do {
3098 // push current one
3099 LOG(3, "INFO: Putting " << *CurrentPoint << " at end of path.");
3100 connectedPath->push_back(CurrentPoint->node);
3101
3102 // find next triangle
3103 for (TriangleMap::iterator Runner = CurrentLine->triangles.begin(); Runner != CurrentLine->triangles.end(); Runner++) {
3104 LOG(4, "DEBUG: Inspecting triangle " << *Runner->second << ".");
3105 if ((Runner->second != triangle)) { // look for first triangle not equal to old one
3106 triangle = Runner->second;
3107 TriangleRunner = TouchedTriangle.find(triangle);
3108 if (TriangleRunner != TouchedTriangle.end()) {
3109 if (!TriangleRunner->second) {
3110 TriangleRunner->second = true;
3111 LOG(4, "DEBUG: Connecting triangle is " << *triangle << ".");
3112 break;
3113 } else {
3114 LOG(4, "DEBUG: Skipping " << *triangle << ", as we have already visited it.");
3115 triangle = NULL;
3116 }
3117 } else {
3118 ELOG(1, "I could not find " << *triangle << " in the touched list.");
3119 triangle = NULL;
3120 }
3121 } else {
3122 // as we have stumbled upon the same triangle, we don't need the check anymore
3123 triangle = NULL;
3124 }
3125 }
3126 if (triangle == NULL)
3127 break;
3128 // find next line
3129 for (int i = 0; i < 3; i++) {
3130 if ((triangle->lines[i] != CurrentLine) && (triangle->lines[i]->ContainsBoundaryPoint(ReferencePoint))) { // not the current line and still containing Point
3131 CurrentLine = triangle->lines[i];
3132 LOG(3, "INFO: Connecting line is " << *CurrentLine << ".");
3133 break;
3134 }
3135 }
3136 LineRunner = TouchedLine.find(CurrentLine);
3137 if (LineRunner == TouchedLine.end())
3138 ELOG(1, "I could not find " << *CurrentLine << " in the touched list.");
3139 else
3140 LineRunner->second = true;
3141 // find next point
3142 CurrentPoint = CurrentLine->GetOtherEndpoint(ReferencePoint);
3143
3144 } while (CurrentLine != StartLine);
3145 // last point is missing, as it's on start line
3146 if (StartLine->GetOtherEndpoint(ReferencePoint)->node != connectedPath->back()) {
3147 LOG(3, "INFO: Putting " << *CurrentPoint << " at end of path to close it.");
3148 connectedPath->push_back(StartLine->GetOtherEndpoint(ReferencePoint)->node);
3149 }
3150
3151 ListOfPaths->push_back(connectedPath);
3152 } else {
3153 LOG(3, "DEBUG: Skipping " << *runner->second << ", as we have already visited it.");
3154 }
3155 }
3156 } else {
3157 ELOG(1, "There are no lines attached to " << *ReferencePoint << ".");
3158 }
3159
3160 return ListOfPaths;
3161}
3162
3163/** Gets all closed paths on the circle of points connected to the provided point by triangulation lines, if this very point is removed.
3164 * From GetPathsOfConnectedPoints() extracts all single loops of intracrossing paths in the list of closed paths.
3165 * @param *out output stream for debugging
3166 * @param *Point of which get all connected points
3167 * @return list of the closed paths
3168 */
3169ListOfTesselPointList * Tesselation::GetClosedPathsOfConnectedPoints(const TesselPoint* const Point) const
3170{
3171 //Info FunctionInfo(__func__);
3172 list<TesselPointList *> *ListofPaths = GetPathsOfConnectedPoints(Point);
3173 list<TesselPointList *> *ListofClosedPaths = new list<TesselPointList *>;
3174 TesselPointList *connectedPath = NULL;
3175 TesselPointList *newPath = NULL;
3176 int count = 0;
3177 TesselPointList::iterator CircleRunner;
3178 TesselPointList::iterator CircleStart;
3179
3180 for (list<TesselPointList *>::iterator ListRunner = ListofPaths->begin(); ListRunner != ListofPaths->end(); ListRunner++) {
3181 connectedPath = *ListRunner;
3182
3183 if (DoLog(2)) {
3184 std::stringstream output;
3185 output << "INFO: Current path is ";
3186 BOOST_FOREACH(const TesselPoint * const item, *connectedPath) {
3187 output << *item << " ";
3188 }
3189 LOG(1, output.str());
3190 }
3191
3192 // go through list, look for reappearance of starting Point and count
3193 CircleStart = connectedPath->begin();
3194 // go through list, look for reappearance of starting Point and create list
3195 TesselPointList::iterator Marker = CircleStart;
3196 for (CircleRunner = CircleStart; CircleRunner != connectedPath->end(); CircleRunner++) {
3197 if ((*CircleRunner == *CircleStart) && (CircleRunner != CircleStart)) { // is not the very first point
3198 // we have a closed circle from Marker to new Marker
3199 if (DoLog(3)) {
3200 std::stringstream output;
3201 output << "DEBUG: " << count + 1 << ". closed path consists of: ";
3202 for (TesselPointList::iterator CircleSprinter = Marker; CircleSprinter != CircleRunner; CircleSprinter++)
3203 output << (**CircleSprinter) << " <-> ";
3204 LOG(1, output.str());
3205 }
3206 newPath = new TesselPointList;
3207 TesselPointList::iterator CircleSprinter = Marker;
3208 for (; CircleSprinter != CircleRunner; CircleSprinter++)
3209 newPath->push_back(*CircleSprinter);
3210 count++;
3211 Marker = CircleRunner;
3212
3213 // add to list
3214 ListofClosedPaths->push_back(newPath);
3215 }
3216 }
3217 }
3218 LOG(2, "DEBUG: " << count << " closed additional path(s) have been created.");
3219
3220 // delete list of paths
3221 while (!ListofPaths->empty()) {
3222 connectedPath = *(ListofPaths->begin());
3223 ListofPaths->remove(connectedPath);
3224 delete (connectedPath);
3225 }
3226 delete (ListofPaths);
3227
3228 // exit
3229 return ListofClosedPaths;
3230}
3231;
3232
3233/** Gets all belonging triangles for a given BoundaryPointSet.
3234 * \param *out output stream for debugging
3235 * \param *Point BoundaryPoint
3236 * \return pointer to allocated list of triangles
3237 */
3238TriangleSet *Tesselation::GetAllTriangles(const BoundaryPointSet * const Point) const
3239{
3240 //Info FunctionInfo(__func__);
3241 TriangleSet *connectedTriangles = new TriangleSet;
3242
3243 if (Point == NULL) {
3244 ELOG(1, "Point given is NULL.");
3245 } else {
3246 // go through its lines and insert all triangles
3247 for (LineMap::const_iterator LineRunner = Point->lines.begin(); LineRunner != Point->lines.end(); LineRunner++)
3248 for (TriangleMap::iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
3249 connectedTriangles->insert(TriangleRunner->second);
3250 }
3251 }
3252
3253 return connectedTriangles;
3254}
3255;
3256
3257struct CloserToPiHalf
3258{
3259 bool operator()(double angle, double smallestangle)
3260 {
3261 return (fabs(angle - M_PI / 2.) < fabs(smallestangle - M_PI / 2.));
3262 }
3263};
3264
3265bool Tesselation::IsPointBelowSurroundingPolygon(const BoundaryPointSet *_point) const
3266{
3267 // check for NULL
3268 if (_point == NULL) {
3269 return false;
3270 }
3271
3272 // get list of connected points
3273 if (_point->lines.empty()) {
3274 LOG(1, "INFO: point " << *_point << " is not connected to any lines.");
3275 return false;
3276 }
3277 bool PointIsBelow = true;
3278
3279 // create Orthogonal vector as reference for angle (pointing into [pi,2pi) interval)
3280 Vector OrthogonalVector;
3281 for (LineMap::const_iterator lineiter = _point->lines.begin();
3282 lineiter != _point->lines.end(); ++lineiter)
3283 for (TriangleMap::const_iterator triangleiter = lineiter->second->triangles.begin();
3284 triangleiter != lineiter->second->triangles.end();
3285 ++triangleiter)
3286 OrthogonalVector += triangleiter->second->NormalVector;
3287 OrthogonalVector.Normalize();
3288
3289 // go through all closed paths for this point
3290 typedef list<TesselPointList *> TPL_list_t;
3291 const TPL_list_t *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(_point->node);
3292 for (TPL_list_t::const_iterator closedpathsiter = ListOfClosedPaths->begin();
3293 (closedpathsiter != ListOfClosedPaths->end()) && PointIsBelow;
3294 ++closedpathsiter) {
3295 const TesselPointList *connectedPath = *closedpathsiter;
3296
3297 TesselPointList::const_iterator ListAdvance = connectedPath->begin(); // gives angle direction
3298 TesselPointList::const_iterator ListRunner = ListAdvance++;
3299 for (; (ListAdvance != connectedPath->end()) && PointIsBelow;
3300 ListRunner = ListAdvance++) { // go through all closed paths
3301 LOG(2, "DEBUG: Current reference node is " << **ListRunner
3302 << ", advanced node is " << **ListAdvance);
3303
3304 // reference vector to point to check for this point of connected path
3305 const Vector Reference =
3306 ((*ListAdvance)->getPosition()) - ((*ListRunner)->getPosition());
3307
3308 // go through all other points in this connected path
3309 for (TesselPointList::const_iterator OtherRunner = ListAdvance;
3310 (OtherRunner != ListRunner) && PointIsBelow;
3311 ++OtherRunner == connectedPath->end() ?
3312 OtherRunner = connectedPath->begin() :
3313 OtherRunner) {
3314 if (OtherRunner == ListAdvance)
3315 continue;
3316 LOG(3, "DEBUG: Current other node is " << **OtherRunner);
3317
3318 // build the plane with normal vector
3319 const Vector onebeam =
3320 ((*OtherRunner)->getPosition()) - ((*ListAdvance)->getPosition());
3321 Vector NormalVector = Reference;
3322 NormalVector.VectorProduct(onebeam);
3323 // needs to point in same general direction as average NormalVector of all triangles
3324 if (NormalVector.ScalarProduct(OrthogonalVector) < 0)
3325 NormalVector *= -1.;
3326 try {
3327 Plane plane(NormalVector, ((*ListRunner)->getPosition()));
3328
3329 // check whether point is below
3330 if (plane.SignedDistance(_point->node->getPosition()) > 0) {
3331 LOG(2, "DEBUG: For plane " << plane << " point " << *_point
3332 << " would remain above.");
3333 PointIsBelow = false;
3334 }
3335 } catch (ZeroVectorException &e) {
3336 ELOG(3, "Vectors are linear dependent, skipping.");
3337 }
3338 }
3339 }
3340 }
3341 delete ListOfClosedPaths;
3342
3343 return PointIsBelow;
3344}
3345
3346double Tesselation::RemovePointSurroundedByPolygon(
3347 TesselPointList *connectedPath,
3348 BoundaryPointSet *point)
3349{
3350 double volume = 0.;
3351 const Vector OldPoint = point->node->getPosition();
3352
3353 TesselPoint *oldNode = point->node;
3354 // remove present triangles for this connectedPath
3355 unsigned int count = 0;
3356 for (TesselPointList::const_iterator iter = connectedPath->begin();
3357 iter != connectedPath->end(); ++iter)
3358 LOG(4, "DEBUG: Node in connectedPath is " << **iter);
3359
3360 {
3361 TesselPointList::iterator FirstNode, SecondNode;
3362 SecondNode = connectedPath->begin();
3363 FirstNode = SecondNode++;
3364 for (;FirstNode != connectedPath->end(); ++SecondNode, ++FirstNode) {
3365 LOG(3, "DEBUG: MiddleNode is " << **FirstNode << ".");
3366 if (SecondNode == connectedPath->end())
3367 SecondNode = connectedPath->begin();
3368 TesselPoint *TriangleCandidates[3];
3369 TriangleCandidates[0] = *FirstNode;
3370 TriangleCandidates[1] = *SecondNode;
3371 TriangleCandidates[2] = oldNode;
3372 BoundaryTriangleSet *triangle = GetPresentTriangle(TriangleCandidates);
3373 ASSERT( triangle != NULL,
3374 "Tesselation::RemovePointSurroundedByPolygon() - triangle to points "
3375 +toString((**SecondNode))+", "+toString((**FirstNode))+" and "
3376 +toString(*oldNode)+" does not exist.");
3377 LOG(3, "DEBUG: Removing triangle " << *triangle << ".");
3378 RemoveTesselationTriangle(triangle);
3379 ++count;
3380 }
3381 LOG(2, "INFO: " << count << " triangles were removed.");
3382 }
3383
3384 // re-create all triangles by going through connected points list
3385 LineList NewLines;
3386 typedef std::vector<double> angles_t;
3387 angles_t angles;
3388 count = 0;
3389 for (; !connectedPath->empty();) {
3390 // search middle node with widest angle to next neighbours
3391 TesselPointList::iterator StartNode, MiddleNode, EndNode;
3392 for (MiddleNode = connectedPath->begin(); MiddleNode != connectedPath->end(); MiddleNode++) {
3393 LOG(3, "INFO: MiddleNode is " << **MiddleNode << ".");
3394 // construct vectors to next and previous neighbour
3395 StartNode = MiddleNode;
3396 if (StartNode == connectedPath->begin())
3397 StartNode = connectedPath->end();
3398 StartNode--;
3399 //LOG(3, "INFO: StartNode is " << **StartNode << ".");
3400 const Vector Point = ((*StartNode)->getPosition()) - ((*MiddleNode)->getPosition());
3401 EndNode = MiddleNode;
3402 EndNode++;
3403 if (EndNode == connectedPath->end())
3404 EndNode = connectedPath->begin();
3405 //LOG(3, "INFO: EndNode is " << **StartNode << ".");
3406 const Vector Reference = ((*EndNode)->getPosition()) - ((*MiddleNode)->getPosition());
3407 Vector OrthogonalVector = ((*MiddleNode)->getPosition()) - OldPoint;
3408 OrthogonalVector.MakeNormalTo(Reference);
3409 angles.push_back(GetAngle(Point, Reference, OrthogonalVector));
3410 }
3411 ASSERT( !angles.empty(),
3412 "Tesselation::RemovePointSurroundedByPolygon() - angles empty");
3413 const angles_t::const_iterator maxiter = std::max_element(angles.begin(), angles.end());
3414 angles_t::const_iterator miniter = angles.begin();
3415 // distinguish between convex and nonconvex polygon
3416 if (*maxiter > M_PI) {
3417 // connectedPath is not convex: The idea is to fill any kinks pointing
3418 // inside into the connectedPath close to this concave spot first, making
3419 // it eventually become convex.
3420 // Hence, use adjacent (and convex) fill-in point
3421 miniter = (maxiter == angles.begin()) ? angles.end()-1 : maxiter-1;
3422 if (*miniter > M_PI) {
3423 miniter = (maxiter+1 == angles.end()) ? angles.begin() : maxiter+1;
3424 if (*miniter > M_PI) {
3425 miniter = std::min_element(angles.begin(), angles.end());
3426 }
3427 }
3428 } else {
3429 // is convex
3430 miniter = std::min_element(angles.begin(), angles.end(), CloserToPiHalf());
3431 }
3432 MiddleNode = connectedPath->begin();
3433 std::advance(MiddleNode, std::distance(const_cast<const angles_t &>(angles).begin(), miniter));
3434
3435 ASSERT(MiddleNode != connectedPath->end(),
3436 "Tesselation::RemovePointSurroundedByPolygon() - Could not find a smallest angle!");
3437 angles.clear();
3438 StartNode = MiddleNode;
3439 EndNode = MiddleNode;
3440 if (StartNode == connectedPath->begin())
3441 StartNode = connectedPath->end();
3442 StartNode--;
3443 EndNode++;
3444 if (EndNode == connectedPath->end())
3445 EndNode = connectedPath->begin();
3446 LOG(2, "INFO: StartNode is " << **StartNode << ".");
3447 LOG(2, "INFO: MiddleNode is " << **MiddleNode << ".");
3448 LOG(2, "INFO: EndNode is " << **EndNode << ".");
3449 LOG(1, "INFO: Attempting to create triangle " << (*StartNode)->getName() << ", " << (*MiddleNode)->getName() << " and " << (*EndNode)->getName() << ".");
3450 TesselPoint *TriangleCandidates[3];
3451 TriangleCandidates[0] = *StartNode;
3452 TriangleCandidates[1] = *MiddleNode;
3453 TriangleCandidates[2] = *EndNode;
3454 BoundaryTriangleSet *triangle = GetPresentTriangle(TriangleCandidates);
3455 if (triangle != NULL) {
3456 const Vector center = 1./3. * ((*StartNode)->getPosition()
3457 + (*MiddleNode)->getPosition()
3458 + (*EndNode)->getPosition());
3459 const Vector NormalVector = OldPoint - center;
3460 // check orientation of normal vector (that points inside)
3461 ASSERT( triangle->NormalVector.ScalarProduct(NormalVector) > std::numeric_limits<double>::epsilon()*1e2,
3462 "Tesselation::RemovePointSurroundedByPolygon() - New triangle with same orientation already present as "
3463 +toString(*triangle)+"!");
3464 }
3465
3466 LOG(3, "DEBUG: Adding new triangle points.");
3467 AddTesselationPoint(*StartNode, 0);
3468 AddTesselationPoint(*MiddleNode, 1);
3469 AddTesselationPoint(*EndNode, 2);
3470 LOG(3, "DEBUG: Adding new triangle lines.");
3471 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
3472 // line between start and end must be new (except for very last triangle)
3473 if (AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1))
3474 NewLines.push_back(BLS[1]);
3475 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
3476 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
3477 const Vector center = 1./3. * ((*StartNode)->getPosition()
3478 + (*MiddleNode)->getPosition()
3479 + (*EndNode)->getPosition());
3480 const Vector NormalVector = OldPoint - center;
3481 BTS->GetNormalVector(NormalVector);
3482 AddTesselationTriangle();
3483 // calculate volume summand as a general tetraeder
3484 volume += CalculateVolumeofGeneralTetraeder(
3485 TPS[0]->node->getPosition(),
3486 TPS[1]->node->getPosition(),
3487 TPS[2]->node->getPosition(),
3488 OldPoint);
3489 // advance number
3490 ++count;
3491
3492 // prepare nodes for next triangle
3493 LOG(3, "DEBUG: Removing " << **MiddleNode << " from closed path.");
3494 connectedPath->remove(*MiddleNode); // remove the middle node (it is surrounded by triangles)
3495 LOG(3, "DEBUG: Remaining points: " << connectedPath->size() << ".");
3496 ASSERT(connectedPath->size() >= 2,
3497 "Tesselation::RemovePointSurroundedByPolygon() - There are only two endpoints left!");
3498 if (connectedPath->size() == 2) { // we are done
3499 connectedPath->remove(*StartNode); // remove the start node
3500 connectedPath->remove(*EndNode); // remove the end node
3501 }
3502 }
3503 LOG(1, "INFO: " << count << " triangles were created.");
3504
3505 return volume;
3506}
3507
3508/** Removes a boundary point from the envelope while keeping it closed.
3509 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
3510 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
3511 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
3512 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
3513 * -# the surface is closed, when the path is empty
3514 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
3515 * \param *out output stream for debugging
3516 * \param *point point to be removed
3517 * \return volume added to the volume inside the tesselated surface by the removal
3518 */
3519double Tesselation::RemovePointFromTesselatedSurface(class BoundaryPointSet *point)
3520{
3521 double volume = 0;
3522
3523 if (point == NULL) {
3524 ELOG(1, "Cannot remove the point " << point << ", it's NULL!");
3525 return 0.;
3526 } else
3527 LOG(4, "DEBUG: Removing point " << *point << " from tesselated boundary ...");
3528
3529 // get list of connected points
3530 if (point->lines.empty()) {
3531 ELOG(1, "Cannot remove the point " << *point << ", it's connected to no lines!");
3532 return 0.;
3533 }
3534
3535 list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
3536 list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
3537 list<TesselPointList *>::iterator ListRunner = ListAdvance;
3538// TriangleMap::iterator NumberRunner = Candidates.begin();
3539 Vector Point, Reference, OrthogonalVector;
3540 for (; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3541 if (ListAdvance != ListOfClosedPaths->end())
3542 ListAdvance++;
3543
3544 TesselPointList *connectedPath = *ListRunner;
3545
3546 volume += RemovePointSurroundedByPolygon(connectedPath, point);
3547
3548 ListOfClosedPaths->remove(connectedPath);
3549 delete (connectedPath);
3550 }
3551 delete (ListOfClosedPaths);
3552
3553 LOG(1, "INFO: Removed volume is " << volume << ".");
3554
3555 return volume;
3556}
3557;
3558
3559bool Tesselation::CheckAllConcaveInPolygon(
3560 const TesselPointList *connectedPath,
3561 const BoundaryPointSet *point
3562 )
3563{
3564 // check whether lines in this path to point to remove are all concave
3565 bool all_lines_concave = true;
3566 if (connectedPath->size() >= 2) {
3567 TesselPointList::const_iterator StartNode, MiddleNode, EndNode;
3568 // have nearest neighbors to a middle node to know adjacent triangles
3569 for (MiddleNode = connectedPath->begin();
3570 all_lines_concave && (MiddleNode != connectedPath->end());
3571 MiddleNode++) {
3572 LOG(3, "INFO: MiddleNode is " << **MiddleNode << ".");
3573 EndNode = MiddleNode;
3574 if (EndNode == connectedPath->begin())
3575 EndNode = connectedPath->end();
3576 --EndNode;
3577 StartNode = MiddleNode;
3578 ++StartNode;
3579 if (StartNode == connectedPath->end())
3580 StartNode = connectedPath->begin();
3581
3582 AddTesselationPoint(point->node, 0);
3583 AddTesselationPoint(*MiddleNode, 1);
3584
3585 ASSERT( point->lines.find((*MiddleNode)->getNr()) != point->lines.end(),
3586 "Tesselation::CheckAllConcaveInPolygon() - MiddleNode "
3587 +toString(**MiddleNode)+" not present in "
3588 +toString(*point)+"'s lines.");
3589
3590 // get line between Node and point and check
3591 std::pair<LineMap::const_iterator, LineMap::const_iterator> FindPair =
3592 point->lines.equal_range((*MiddleNode)->getNr());
3593 LineMap::const_iterator FindLine = FindPair.first;
3594 for (; FindLine != FindPair.second; ++FindLine) {
3595 // line has got two triangles, check whether they resemble those
3596 // with start and endnode
3597 const BoundaryLineSet *currentline = FindLine->second;
3598 unsigned int matching_triangles = 0;
3599 for (TriangleMap::const_iterator triangleiter = currentline->triangles.begin();
3600 triangleiter != currentline->triangles.end(); ++triangleiter) {
3601 const BoundaryTriangleSet *triangle = triangleiter->second;
3602 AddTesselationPoint(*StartNode, 2);
3603 if (triangle->IsPresentTupel(TPS))
3604 ++matching_triangles;
3605 AddTesselationPoint(*EndNode, 2);
3606 if (triangle->IsPresentTupel(TPS))
3607 ++matching_triangles;
3608 }
3609 if (matching_triangles == 2)
3610 break;
3611 }
3612 if (FindLine != FindPair.second) {
3613 LOG(3, "INFO: Current line of point " << *point << " is " << *FindLine->second << ".");
3614 all_lines_concave &= !FindLine->second->CheckConvexityCriterion();
3615 }
3616 }
3617 } else {
3618 // check the single line
3619 if (connectedPath->empty())
3620 return false;
3621 LineMap::const_iterator FindLine = point->lines.find((*connectedPath->begin())->getNr());
3622 ASSERT( FindLine != point->lines.end(),
3623 "Tesselation::CheckAllConcaveInPolygon() - point "
3624 +toString((*connectedPath->begin())->getNr())+" not present in "
3625 +toString(*point)+"'s lines.");
3626 return !FindLine->second->CheckConvexityCriterion();
3627 }
3628
3629 return all_lines_concave;
3630}
3631
3632/** Removes a boundary point from the envelope while keeping it closed.
3633 * We remove the old triangles connected to the point and re-create new triangles to close the surface following this ansatz:
3634 * -# a closed path(s) of boundary points surrounding the point to be removed is constructed
3635 * -# on each closed path, we pick three adjacent points, create a triangle with them and subtract the middle point from the path
3636 * -# we advance two points (i.e. the next triangle will start at the ending point of the last triangle) and continue as before
3637 * -# the surface is closed, when the path is empty
3638 * Thereby, we (hopefully) make sure that the removed points remains beneath the surface (this is checked via IsInnerPoint eventually).
3639 * \param *out output stream for debugging
3640 * \param *point point to be removed
3641 * \return volume added to the volume inside the tesselated surface by the removal
3642 */
3643double Tesselation::RemoveFullConcavePointFromTesselatedSurface(class BoundaryPointSet *point)
3644{
3645 double volume = 0;
3646
3647 if (point == NULL) {
3648 ELOG(1, "Cannot remove the point " << point << ", it's NULL!");
3649 return 0.;
3650 } else
3651 LOG(4, "DEBUG: Removing point " << *point << " from tesselated boundary ...");
3652
3653 // get list of connected points
3654 if (point->lines.empty()) {
3655 ELOG(1, "Cannot remove the point " << *point << ", it's connected to no lines!");
3656 return 0.;
3657 }
3658
3659 list<TesselPointList *> *ListOfClosedPaths = GetClosedPathsOfConnectedPoints(point->node);
3660 list<TesselPointList *>::iterator ListAdvance = ListOfClosedPaths->begin();
3661 list<TesselPointList *>::iterator ListRunner = ListAdvance;
3662// TriangleMap::iterator NumberRunner = Candidates.begin();
3663 TesselPointList::iterator StartNode, MiddleNode, EndNode;
3664 Vector Point, Reference, OrthogonalVector;
3665 for (; ListRunner != ListOfClosedPaths->end(); ListRunner = ListAdvance) { // go through all closed paths
3666 if (ListAdvance != ListOfClosedPaths->end())
3667 ListAdvance++;
3668
3669 TesselPointList *connectedPath = *ListRunner;
3670
3671 if (CheckAllConcaveInPolygon(connectedPath, point)) {
3672 LOG(1, "INFO: ... point " << *point << " cannot be on convex envelope, all lines concave.");
3673 volume += RemovePointSurroundedByPolygon(connectedPath, point);
3674 }
3675
3676 ListOfClosedPaths->remove(connectedPath);
3677 delete (connectedPath);
3678 }
3679 delete (ListOfClosedPaths);
3680
3681 if (volume > 0.)
3682 LOG(1, "INFO: Removed volume is " << volume << ".");
3683
3684 return volume;
3685}
3686;
3687
3688/**
3689 * Finds triangles belonging to the three provided points.
3690 *
3691 * @param *Points[3] list, is expected to contain three points (NULL means wildcard)
3692 *
3693 * @return triangles which belong to the provided points, will be empty if there are none,
3694 * will usually be one, in case of degeneration, there will be two
3695 */
3696TriangleList *Tesselation::FindTriangles(const TesselPoint* const Points[3]) const
3697{
3698 //Info FunctionInfo(__func__);
3699 TriangleList *result = new TriangleList;
3700 LineMap::const_iterator FindLine;
3701 TriangleMap::const_iterator FindTriangle;
3702 class BoundaryPointSet *TrianglePoints[3];
3703 size_t NoOfWildcards = 0;
3704
3705 for (int i = 0; i < 3; i++) {
3706 if (Points[i] == NULL) {
3707 NoOfWildcards++;
3708 TrianglePoints[i] = NULL;
3709 } else {
3710 PointMap::const_iterator FindPoint = PointsOnBoundary.find(Points[i]->getNr());
3711 if (FindPoint != PointsOnBoundary.end()) {
3712 TrianglePoints[i] = FindPoint->second;
3713 } else {
3714 TrianglePoints[i] = NULL;
3715 }
3716 }
3717 }
3718
3719 switch (NoOfWildcards) {
3720 case 0: // checks lines between the points in the Points for their adjacent triangles
3721 for (int i = 0; i < 3; i++) {
3722 if (TrianglePoints[i] != NULL) {
3723 for (int j = i + 1; j < 3; j++) {
3724 if (TrianglePoints[j] != NULL) {
3725 for (FindLine = TrianglePoints[i]->lines.find(TrianglePoints[j]->node->getNr()); // is a multimap!
3726 (FindLine != TrianglePoints[i]->lines.end()) && (FindLine->first == TrianglePoints[j]->node->getNr()); FindLine++) {
3727 for (FindTriangle = FindLine->second->triangles.begin(); FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
3728 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3729 result->push_back(FindTriangle->second);
3730 }
3731 }
3732 }
3733 // Is it sufficient to consider one of the triangle lines for this.
3734 return result;
3735 }
3736 }
3737 }
3738 }
3739 break;
3740 case 1: // copy all triangles of the respective line
3741 {
3742 int i = 0;
3743 for (; i < 3; i++)
3744 if (TrianglePoints[i] == NULL)
3745 break;
3746 for (FindLine = TrianglePoints[(i + 1) % 3]->lines.find(TrianglePoints[(i + 2) % 3]->node->getNr()); // is a multimap!
3747 (FindLine != TrianglePoints[(i + 1) % 3]->lines.end()) && (FindLine->first == TrianglePoints[(i + 2) % 3]->node->getNr()); FindLine++) {
3748 for (FindTriangle = FindLine->second->triangles.begin(); FindTriangle != FindLine->second->triangles.end(); FindTriangle++) {
3749 if (FindTriangle->second->IsPresentTupel(TrianglePoints)) {
3750 result->push_back(FindTriangle->second);
3751 }
3752 }
3753 }
3754 break;
3755 }
3756 case 2: // copy all triangles of the respective point
3757 {
3758 int i = 0;
3759 for (; i < 3; i++)
3760 if (TrianglePoints[i] != NULL)
3761 break;
3762 for (LineMap::const_iterator line = TrianglePoints[i]->lines.begin(); line != TrianglePoints[i]->lines.end(); line++)
3763 for (TriangleMap::const_iterator triangle = line->second->triangles.begin(); triangle != line->second->triangles.end(); triangle++)
3764 result->push_back(triangle->second);
3765 result->sort();
3766 result->unique();
3767 break;
3768 }
3769 case 3: // copy all triangles
3770 {
3771 for (TriangleMap::const_iterator triangle = TrianglesOnBoundary.begin(); triangle != TrianglesOnBoundary.end(); triangle++)
3772 result->push_back(triangle->second);
3773 break;
3774 }
3775 default:
3776 ASSERT(0, "Tesselation::FindTriangles() - Number of wildcards is greater than 3, cannot happen!");
3777 break;
3778 }
3779
3780 return result;
3781}
3782
3783struct BoundaryLineSetCompare
3784{
3785 bool operator()(const BoundaryLineSet * const a, const BoundaryLineSet * const b)
3786 {
3787 int lowerNra = -1;
3788 int lowerNrb = -1;
3789
3790 if (a->endpoints[0] < a->endpoints[1])
3791 lowerNra = 0;
3792 else
3793 lowerNra = 1;
3794
3795 if (b->endpoints[0] < b->endpoints[1])
3796 lowerNrb = 0;
3797 else
3798 lowerNrb = 1;
3799
3800 if (a->endpoints[lowerNra] < b->endpoints[lowerNrb])
3801 return true;
3802 else
3803 if (a->endpoints[lowerNra] > b->endpoints[lowerNrb])
3804 return false;
3805 else { // both lower-numbered endpoints are the same ...
3806 if (a->endpoints[(lowerNra + 1) % 2] < b->endpoints[(lowerNrb + 1) % 2])
3807 return true;
3808 else
3809 if (a->endpoints[(lowerNra + 1) % 2] > b->endpoints[(lowerNrb + 1) % 2])
3810 return false;
3811 }
3812 return false;
3813 }
3814 ;
3815};
3816
3817#define UniqueLines set < class BoundaryLineSet *, BoundaryLineSetCompare>
3818
3819/**
3820 * Finds all degenerated lines within the tesselation structure.
3821 *
3822 * @return map of keys of degenerated line pairs, each line occurs twice
3823 * in the list, once as key and once as value
3824 */
3825IndexToIndex * Tesselation::FindAllDegeneratedLines()
3826{
3827 //Info FunctionInfo(__func__);
3828 UniqueLines AllLines;
3829 IndexToIndex * DegeneratedLines = new IndexToIndex;
3830
3831 // sanity check
3832 if (LinesOnBoundary.empty()) {
3833 ELOG(2, "FindAllDegeneratedTriangles() was called without any tesselation structure.");
3834 return DegeneratedLines;
3835 }
3836 LineMap::iterator LineRunner1;
3837 pair<UniqueLines::iterator, bool> tester;
3838 for (LineRunner1 = LinesOnBoundary.begin(); LineRunner1 != LinesOnBoundary.end(); ++LineRunner1) {
3839 tester = AllLines.insert(LineRunner1->second);
3840 if (!tester.second) { // found degenerated line
3841 DegeneratedLines->insert(pair<int, int> (LineRunner1->second->Nr, (*tester.first)->Nr));
3842 DegeneratedLines->insert(pair<int, int> ((*tester.first)->Nr, LineRunner1->second->Nr));
3843 }
3844 }
3845
3846 AllLines.clear();
3847
3848 LOG(2, "DEBUG: FindAllDegeneratedLines() found " << DegeneratedLines->size() << " lines.");
3849 IndexToIndex::iterator it;
3850 for (it = DegeneratedLines->begin(); it != DegeneratedLines->end(); it++) {
3851 const LineMap::const_iterator Line1 = LinesOnBoundary.find((*it).first);
3852 const LineMap::const_iterator Line2 = LinesOnBoundary.find((*it).second);
3853 if (Line1 != LinesOnBoundary.end() && Line2 != LinesOnBoundary.end())
3854 LOG(3, "DEBUG: " << *Line1->second << " => " << *Line2->second);
3855 else
3856 ELOG(1, "Either " << (*it).first << " or " << (*it).second << " are not in LinesOnBoundary!");
3857 }
3858
3859 return DegeneratedLines;
3860}
3861
3862/**
3863 * Finds all degenerated triangles within the tesselation structure.
3864 *
3865 * @return map of keys of degenerated triangle pairs, each triangle occurs twice
3866 * in the list, once as key and once as value
3867 */
3868IndexToIndex * Tesselation::FindAllDegeneratedTriangles()
3869{
3870 //Info FunctionInfo(__func__);
3871 IndexToIndex * DegeneratedLines = FindAllDegeneratedLines();
3872 IndexToIndex * DegeneratedTriangles = new IndexToIndex;
3873 TriangleMap::iterator TriangleRunner1, TriangleRunner2;
3874 LineMap::iterator Liner;
3875 class BoundaryLineSet *line1 = NULL, *line2 = NULL;
3876
3877 for (IndexToIndex::iterator LineRunner = DegeneratedLines->begin(); LineRunner != DegeneratedLines->end(); ++LineRunner) {
3878 // run over both lines' triangles
3879 Liner = LinesOnBoundary.find(LineRunner->first);
3880 if (Liner != LinesOnBoundary.end())
3881 line1 = Liner->second;
3882 Liner = LinesOnBoundary.find(LineRunner->second);
3883 if (Liner != LinesOnBoundary.end())
3884 line2 = Liner->second;
3885 for (TriangleRunner1 = line1->triangles.begin(); TriangleRunner1 != line1->triangles.end(); ++TriangleRunner1) {
3886 for (TriangleRunner2 = line2->triangles.begin(); TriangleRunner2 != line2->triangles.end(); ++TriangleRunner2) {
3887 if ((TriangleRunner1->second != TriangleRunner2->second) && (TriangleRunner1->second->IsPresentTupel(TriangleRunner2->second))) {
3888 DegeneratedTriangles->insert(pair<int, int>(TriangleRunner1->second->Nr, TriangleRunner2->second->Nr));
3889 DegeneratedTriangles->insert(pair<int, int>(TriangleRunner2->second->Nr, TriangleRunner1->second->Nr));
3890 }
3891 }
3892 }
3893 }
3894 delete (DegeneratedLines);
3895
3896 LOG(3, "DEBUG: FindAllDegeneratedTriangles() found " << DegeneratedTriangles->size() << " triangles:");
3897 for (IndexToIndex::iterator it = DegeneratedTriangles->begin(); it != DegeneratedTriangles->end(); it++)
3898 LOG(3, "DEBUG: " << (*it).first << " => " << (*it).second);
3899
3900 return DegeneratedTriangles;
3901}
3902
3903/**
3904 * Purges degenerated triangles from the tesselation structure if they are not
3905 * necessary to keep a single point within the structure.
3906 */
3907void Tesselation::RemoveDegeneratedTriangles()
3908{
3909 //Info FunctionInfo(__func__);
3910 IndexToIndex * DegeneratedTriangles = FindAllDegeneratedTriangles();
3911 TriangleMap::iterator finder;
3912 BoundaryTriangleSet *triangle = NULL, *partnerTriangle = NULL;
3913 int count = 0;
3914
3915 // iterate over all degenerated triangles
3916 for (IndexToIndex::iterator TriangleKeyRunner = DegeneratedTriangles->begin();
3917 !DegeneratedTriangles->empty();
3918 TriangleKeyRunner = DegeneratedTriangles->begin()) {
3919 LOG(3, "DEBUG: Checking presence of triangles " << TriangleKeyRunner->first << " and " << TriangleKeyRunner->second << ".");
3920 // both ways are stored in the map, only use one
3921 if (TriangleKeyRunner->first > TriangleKeyRunner->second)
3922 continue;
3923
3924 // determine from the keys in the map the two _present_ triangles
3925 finder = TrianglesOnBoundary.find(TriangleKeyRunner->first);
3926 if (finder != TrianglesOnBoundary.end())
3927 triangle = finder->second;
3928 else
3929 continue;
3930 finder = TrianglesOnBoundary.find(TriangleKeyRunner->second);
3931 if (finder != TrianglesOnBoundary.end())
3932 partnerTriangle = finder->second;
3933 else
3934 continue;
3935
3936 // determine which lines are shared by the two triangles
3937 bool trianglesShareLine = false;
3938 for (int i = 0; i < 3; ++i)
3939 for (int j = 0; j < 3; ++j)
3940 trianglesShareLine = trianglesShareLine || triangle->lines[i] == partnerTriangle->lines[j];
3941
3942 if (trianglesShareLine && (triangle->endpoints[1]->LinesCount > 2) && (triangle->endpoints[2]->LinesCount > 2) && (triangle->endpoints[0]->LinesCount > 2)) {
3943 // check whether we have to fix lines
3944 BoundaryTriangleSet *Othertriangle = NULL;
3945// BoundaryTriangleSet *OtherpartnerTriangle = NULL;
3946 TriangleMap::iterator TriangleRunner;
3947 for (int i = 0; i < 3; ++i)
3948 for (int j = 0; j < 3; ++j)
3949 if (triangle->lines[i] != partnerTriangle->lines[j]) {
3950 // get the other two triangles
3951 for (TriangleRunner = triangle->lines[i]->triangles.begin(); TriangleRunner != triangle->lines[i]->triangles.end(); ++TriangleRunner)
3952 if (TriangleRunner->second != triangle) {
3953 Othertriangle = TriangleRunner->second;
3954 }
3955 for (TriangleRunner = partnerTriangle->lines[i]->triangles.begin(); TriangleRunner != partnerTriangle->lines[i]->triangles.end(); ++TriangleRunner)
3956// if (TriangleRunner->second != partnerTriangle) {
3957// OtherpartnerTriangle = TriangleRunner->second;
3958// }
3959 /// interchanges their lines so that triangle->lines[i] == partnerTriangle->lines[j]
3960 // the line of triangle receives the degenerated ones
3961 triangle->lines[i]->triangles.erase(Othertriangle->Nr);
3962 triangle->lines[i]->triangles.insert(TrianglePair(partnerTriangle->Nr, partnerTriangle));
3963 for (int k = 0; k < 3; k++)
3964 if (triangle->lines[i] == Othertriangle->lines[k]) {
3965 Othertriangle->lines[k] = partnerTriangle->lines[j];
3966 break;
3967 }
3968 // the line of partnerTriangle receives the non-degenerated ones
3969 partnerTriangle->lines[j]->triangles.erase(partnerTriangle->Nr);
3970 partnerTriangle->lines[j]->triangles.insert(TrianglePair(Othertriangle->Nr, Othertriangle));
3971 partnerTriangle->lines[j] = triangle->lines[i];
3972 }
3973
3974 // erase the pair
3975 count += (int)DegeneratedTriangles->erase(triangle->Nr);
3976 LOG(4, "DEBUG: RemoveDegeneratedTriangles() removes triangle " << *triangle << ".");
3977 RemoveTesselationTriangle(triangle);
3978 count += (int)DegeneratedTriangles->erase(partnerTriangle->Nr);
3979 LOG(4, "DEBUG: RemoveDegeneratedTriangles() removes triangle " << *partnerTriangle << ".");
3980 RemoveTesselationTriangle(partnerTriangle);
3981 } else {
3982 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.");
3983 // we need to remove them from the list nonetheless
3984 DegeneratedTriangles->erase(triangle->Nr);
3985 DegeneratedTriangles->erase(partnerTriangle->Nr);
3986 }
3987 }
3988 delete (DegeneratedTriangles);
3989 if (count > 0)
3990 LastTriangle = NULL;
3991
3992 LOG(2, "INFO: RemoveDegeneratedTriangles() removed " << count << " triangles:");
3993}
3994
3995/** Adds an outside Tesselpoint to the envelope via (two) degenerated triangles.
3996 * We look for the closest point on the boundary, we look through its connected boundary lines and
3997 * seek the one with the minimum angle between its center point and the new point and this base line.
3998 * We open up the line by adding a degenerated triangle, whose other side closes the base line again.
3999 * \param *out output stream for debugging
4000 * \param *point point to add
4001 * \param *LC Linked Cell structure to find nearest point
4002 */
4003void Tesselation::AddBoundaryPointByDegeneratedTriangle(class TesselPoint *point, LinkedCell_deprecated *LC)
4004{
4005 //Info FunctionInfo(__func__);
4006 // find nearest boundary point
4007 class TesselPoint *BackupPoint = NULL;
4008 class TesselPoint *NearestPoint = FindClosestTesselPoint(point->getPosition(), BackupPoint, LC);
4009 class BoundaryPointSet *NearestBoundaryPoint = NULL;
4010 PointMap::iterator PointRunner;
4011
4012 if (NearestPoint == point)
4013 NearestPoint = BackupPoint;
4014 PointRunner = PointsOnBoundary.find(NearestPoint->getNr());
4015 if (PointRunner != PointsOnBoundary.end()) {
4016 NearestBoundaryPoint = PointRunner->second;
4017 } else {
4018 ELOG(1, "I cannot find the boundary point.");
4019 return;
4020 }
4021 LOG(3, "DEBUG: Nearest point on boundary is " << NearestPoint->getName() << ".");
4022
4023 // go through its lines and find the best one to split
4024 Vector CenterToPoint;
4025 Vector BaseLine;
4026 double angle, BestAngle = 0.;
4027 class BoundaryLineSet *BestLine = NULL;
4028 for (LineMap::iterator Runner = NearestBoundaryPoint->lines.begin(); Runner != NearestBoundaryPoint->lines.end(); Runner++) {
4029 BaseLine = (Runner->second->endpoints[0]->node->getPosition()) - (Runner->second->endpoints[1]->node->getPosition());
4030 CenterToPoint = 0.5 * ((Runner->second->endpoints[0]->node->getPosition()) + (Runner->second->endpoints[1]->node->getPosition()));
4031 CenterToPoint -= (point->getPosition());
4032 angle = CenterToPoint.Angle(BaseLine);
4033 if (fabs(angle - M_PI / 2.) < fabs(BestAngle - M_PI / 2.)) {
4034 BestAngle = angle;
4035 BestLine = Runner->second;
4036 }
4037 }
4038
4039 // remove one triangle from the chosen line
4040 class BoundaryTriangleSet *TempTriangle = (BestLine->triangles.begin())->second;
4041 BestLine->triangles.erase(TempTriangle->Nr);
4042 int nr = -1;
4043 for (int i = 0; i < 3; i++) {
4044 if (TempTriangle->lines[i] == BestLine) {
4045 nr = i;
4046 break;
4047 }
4048 }
4049
4050 // create new triangle to connect point (connects automatically with the missing spot of the chosen line)
4051 LOG(2, "Adding new triangle points.");
4052 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4053 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4054 AddTesselationPoint(point, 2);
4055 LOG(2, "Adding new triangle lines.");
4056 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
4057 AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
4058 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
4059 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4060 BTS->GetNormalVector(TempTriangle->NormalVector);
4061 BTS->NormalVector.Scale(-1.);
4062 LOG(1, "INFO: NormalVector of new triangle is " << BTS->NormalVector << ".");
4063 AddTesselationTriangle();
4064
4065 // create other side of this triangle and close both new sides of the first created triangle
4066 LOG(2, "Adding new triangle points.");
4067 AddTesselationPoint((BestLine->endpoints[0]->node), 0);
4068 AddTesselationPoint((BestLine->endpoints[1]->node), 1);
4069 AddTesselationPoint(point, 2);
4070 LOG(2, "Adding new triangle lines.");
4071 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
4072 AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
4073 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
4074 BTS = new class BoundaryTriangleSet(BLS, TrianglesOnBoundaryCount);
4075 BTS->GetNormalVector(TempTriangle->NormalVector);
4076 LOG(1, "INFO: NormalVector of other new triangle is " << BTS->NormalVector << ".");
4077 AddTesselationTriangle();
4078
4079 // add removed triangle to the last open line of the second triangle
4080 for (int i = 0; i < 3; i++) { // look for the same line as BestLine (only it's its degenerated companion)
4081 if ((BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[0])) && (BTS->lines[i]->ContainsBoundaryPoint(BestLine->endpoints[1]))) {
4082 ASSERT(BestLine != BTS->lines[i], std::string("Tesselation::AddBoundaryPointByDegeneratedTriangle() - ") + std::string("BestLine is same as found line, something's wrong here!"));
4083 BTS->lines[i]->triangles.insert(pair<int, class BoundaryTriangleSet *>(TempTriangle->Nr, TempTriangle));
4084 TempTriangle->lines[nr] = BTS->lines[i];
4085 break;
4086 }
4087 }
4088}
4089;
4090
4091/** Writes the envelope to file.
4092 * \param *out otuput stream for debugging
4093 * \param *filename basename of output file
4094 * \param *cloud IPointCloud structure with all nodes
4095 */
4096void Tesselation::Output(const char *filename, IPointCloud & cloud)
4097{
4098 //Info FunctionInfo(__func__);
4099 ofstream *tempstream = NULL;
4100 string NameofTempFile;
4101 string NumberName;
4102
4103 if (LastTriangle != NULL) {
4104 stringstream sstr;
4105 sstr << "-" << TrianglesOnBoundary.size() << "-" << LastTriangle->getEndpointName(0) << "_" << LastTriangle->getEndpointName(1) << "_" << LastTriangle->getEndpointName(2);
4106 NumberName = sstr.str();
4107 if (DoTecplotOutput) {
4108 string NameofTempFile(filename);
4109 NameofTempFile.append(NumberName);
4110 for (size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4111 NameofTempFile.erase(npos, 1);
4112 NameofTempFile.append(TecplotSuffix);
4113 LOG(1, "INFO: Writing temporary non convex hull to file " << NameofTempFile << ".");
4114 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4115 WriteTecplotFile(tempstream, this, cloud, TriangleFilesWritten);
4116 tempstream->close();
4117 tempstream->flush();
4118 delete (tempstream);
4119 }
4120
4121 if (DoRaster3DOutput) {
4122 string NameofTempFile(filename);
4123 NameofTempFile.append(NumberName);
4124 for (size_t npos = NameofTempFile.find_first_of(' '); npos != string::npos; npos = NameofTempFile.find(' ', npos))
4125 NameofTempFile.erase(npos, 1);
4126 NameofTempFile.append(Raster3DSuffix);
4127 LOG(1, "INFO: Writing temporary non convex hull to file " << NameofTempFile << ".");
4128 tempstream = new ofstream(NameofTempFile.c_str(), ios::trunc);
4129 WriteRaster3dFile(tempstream, this, cloud);
4130 IncludeSphereinRaster3D(tempstream, this, cloud);
4131 tempstream->close();
4132 tempstream->flush();
4133 delete (tempstream);
4134 }
4135 }
4136 if (DoTecplotOutput || DoRaster3DOutput)
4137 TriangleFilesWritten++;
4138}
4139;
4140
4141struct BoundaryPolygonSetCompare
4142{
4143 bool operator()(const BoundaryPolygonSet * s1, const BoundaryPolygonSet * s2) const
4144 {
4145 if (s1->endpoints.size() < s2->endpoints.size())
4146 return true;
4147 else
4148 if (s1->endpoints.size() > s2->endpoints.size())
4149 return false;
4150 else { // equality of number of endpoints
4151 PointSet::const_iterator Walker1 = s1->endpoints.begin();
4152 PointSet::const_iterator Walker2 = s2->endpoints.begin();
4153 while ((Walker1 != s1->endpoints.end()) || (Walker2 != s2->endpoints.end())) {
4154 if ((*Walker1)->Nr < (*Walker2)->Nr)
4155 return true;
4156 else
4157 if ((*Walker1)->Nr > (*Walker2)->Nr)
4158 return false;
4159 Walker1++;
4160 Walker2++;
4161 }
4162 return false;
4163 }
4164 }
4165};
4166
4167#define UniquePolygonSet set < BoundaryPolygonSet *, BoundaryPolygonSetCompare>
4168
4169/** Finds all degenerated polygons and calls ReTesselateDegeneratedPolygon()/
4170 * \return number of polygons found
4171 */
4172int Tesselation::CorrectAllDegeneratedPolygons()
4173{
4174 //Info FunctionInfo(__func__);
4175 /// 2. Go through all BoundaryPointSet's, check their triangles' NormalVector
4176 IndexToIndex *DegeneratedTriangles = FindAllDegeneratedTriangles();
4177 set<BoundaryPointSet *> EndpointCandidateList;
4178 pair<set<BoundaryPointSet *>::iterator, bool> InsertionTester;
4179 pair<map<int, Vector *>::iterator, bool> TriangleInsertionTester;
4180 for (PointMap::const_iterator Runner = PointsOnBoundary.begin(); Runner != PointsOnBoundary.end(); Runner++) {
4181 LOG(3, "DEBUG: Current point is " << *Runner->second << ".");
4182 map<int, Vector *> TriangleVectors;
4183 // gather all NormalVectors
4184 LOG(4, "DEBUG: Gathering triangles ...");
4185 for (LineMap::const_iterator LineRunner = (Runner->second)->lines.begin(); LineRunner != (Runner->second)->lines.end(); LineRunner++)
4186 for (TriangleMap::const_iterator TriangleRunner = (LineRunner->second)->triangles.begin(); TriangleRunner != (LineRunner->second)->triangles.end(); TriangleRunner++) {
4187 if (DegeneratedTriangles->find(TriangleRunner->second->Nr) == DegeneratedTriangles->end()) {
4188 TriangleInsertionTester = TriangleVectors.insert(pair<int, Vector *>((TriangleRunner->second)->Nr, &((TriangleRunner->second)->NormalVector)));
4189 if (TriangleInsertionTester.second)
4190 LOG(5, "DEBUG: Adding triangle " << *(TriangleRunner->second) << " to triangles to check-list.");
4191 } else {
4192 LOG(5, "DEBUG: NOT adding triangle " << *(TriangleRunner->second) << " as it's a simply degenerated one.");
4193 }
4194 }
4195 // check whether there are two that are parallel
4196 LOG(3, "DEBUG: Finding two parallel triangles ...");
4197 for (map<int, Vector *>::iterator VectorWalker = TriangleVectors.begin(); VectorWalker != TriangleVectors.end(); VectorWalker++)
4198 for (map<int, Vector *>::iterator VectorRunner = VectorWalker; VectorRunner != TriangleVectors.end(); VectorRunner++)
4199 if (VectorWalker != VectorRunner) { // skip equals
4200 const double SCP = VectorWalker->second->ScalarProduct(*VectorRunner->second); // ScalarProduct should result in -1. for degenerated triangles
4201 LOG(4, "DEBUG: Checking " << *(VectorWalker->second) << " against " << *(VectorRunner->second) << ": " << SCP);
4202 if (fabs(SCP + 1.) < ParallelEpsilon) {
4203 InsertionTester = EndpointCandidateList.insert((Runner->second));
4204 if (InsertionTester.second)
4205 LOG(4, "DEBUG: Adding " << *Runner->second << " to endpoint candidate list.");
4206 // and break out of both loops
4207 VectorWalker = TriangleVectors.end();
4208 VectorRunner = TriangleVectors.end();
4209 break;
4210 }
4211 }
4212 }
4213 delete DegeneratedTriangles;
4214
4215 /// 3. Find connected endpoint candidates and put them into a polygon
4216 UniquePolygonSet ListofDegeneratedPolygons;
4217 BoundaryPointSet *Walker = NULL;
4218 BoundaryPointSet *OtherWalker = NULL;
4219 BoundaryPolygonSet *Current = NULL;
4220 stack<BoundaryPointSet*> ToCheckConnecteds;
4221 while (!EndpointCandidateList.empty()) {
4222 Walker = *(EndpointCandidateList.begin());
4223 if (Current == NULL) { // create a new polygon with current candidate
4224 LOG(3, "DEBUG: Starting new polygon set at point " << *Walker);
4225 Current = new BoundaryPolygonSet;
4226 Current->endpoints.insert(Walker);
4227 EndpointCandidateList.erase(Walker);
4228 ToCheckConnecteds.push(Walker);
4229 }
4230
4231 // go through to-check stack
4232 while (!ToCheckConnecteds.empty()) {
4233 Walker = ToCheckConnecteds.top(); // fetch ...
4234 ToCheckConnecteds.pop(); // ... and remove
4235 for (LineMap::const_iterator LineWalker = Walker->lines.begin(); LineWalker != Walker->lines.end(); LineWalker++) {
4236 OtherWalker = (LineWalker->second)->GetOtherEndpoint(Walker);
4237 LOG(4, "DEBUG: Checking " << *OtherWalker);
4238 set<BoundaryPointSet *>::iterator Finder = EndpointCandidateList.find(OtherWalker);
4239 if (Finder != EndpointCandidateList.end()) { // found a connected partner
4240 LOG(5, "DEBUG: Adding to polygon.");
4241 Current->endpoints.insert(OtherWalker);
4242 EndpointCandidateList.erase(Finder); // remove from candidates
4243 ToCheckConnecteds.push(OtherWalker); // but check its partners too
4244 } else {
4245 LOG(5, "DEBUG: is not connected to " << *Walker);
4246 }
4247 }
4248 }
4249
4250 LOG(3, "DEBUG: Final polygon is " << *Current);
4251 ListofDegeneratedPolygons.insert(Current);
4252 Current = NULL;
4253 }
4254
4255 const int counter = ListofDegeneratedPolygons.size();
4256
4257 if (DoLog(0)) {
4258 std::stringstream output;
4259 output << "The following " << counter << " degenerated polygons have been found: ";
4260 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++)
4261 output << " " << **PolygonRunner;
4262 LOG(3, "DEBUG: " << output.str());
4263 }
4264
4265 /// 4. Go through all these degenerated polygons
4266 for (UniquePolygonSet::iterator PolygonRunner = ListofDegeneratedPolygons.begin(); PolygonRunner != ListofDegeneratedPolygons.end(); PolygonRunner++) {
4267 stack<int> TriangleNrs;
4268 Vector NormalVector;
4269 /// 4a. Gather all triangles of this polygon
4270 TriangleSet *T = (*PolygonRunner)->GetAllContainedTrianglesFromEndpoints();
4271
4272 // check whether number is bigger than 2, otherwise it's just a simply degenerated one and nothing to do.
4273 if (T->size() == 2) {
4274 LOG(4, "DEBUG: Skipping degenerated polygon, is just a (already simply degenerated) triangle.");
4275 delete (T);
4276 continue;
4277 }
4278
4279 // check whether number is even
4280 // If this case occurs, we have to think about it!
4281 // The Problem is probably due to two degenerated polygons being connected by a bridging, non-degenerated polygon, as somehow one node has
4282 // connections to either polygon ...
4283 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!"));
4284 TriangleSet::iterator TriangleWalker = T->begin(); // is the inner iterator
4285 /// 4a. Get NormalVector for one side (this is "front")
4286 NormalVector = (*TriangleWalker)->NormalVector;
4287 LOG(4, "DEBUG: \"front\" defining triangle is " << **TriangleWalker << " and Normal vector of \"front\" side is " << NormalVector);
4288 TriangleWalker++;
4289 TriangleSet::iterator TriangleSprinter = TriangleWalker; // is the inner advanced iterator
4290 /// 4b. Remove all triangles whose NormalVector is in opposite direction (i.e. "back")
4291 BoundaryTriangleSet *triangle = NULL;
4292 while (TriangleSprinter != T->end()) {
4293 TriangleWalker = TriangleSprinter;
4294 triangle = *TriangleWalker;
4295 TriangleSprinter++;
4296 LOG(4, "DEBUG: Current triangle to test for removal: " << *triangle);
4297 if (triangle->NormalVector.ScalarProduct(NormalVector) < 0) { // if from other side, then delete and remove from list
4298 LOG(5, "DEBUG: Removing ... ");
4299 TriangleNrs.push(triangle->Nr);
4300 T->erase(TriangleWalker);
4301 RemoveTesselationTriangle(triangle);
4302 } else
4303 LOG(5, "DEBUG: Keeping ... ");
4304 }
4305 /// 4c. Copy all "front" triangles but with inverse NormalVector
4306 TriangleWalker = T->begin();
4307 while (TriangleWalker != T->end()) { // go through all front triangles
4308 LOG(4, "DEBUG: Re-creating triangle " << **TriangleWalker << " with NormalVector " << (*TriangleWalker)->NormalVector);
4309 for (int i = 0; i < 3; i++)
4310 AddTesselationPoint((*TriangleWalker)->endpoints[i]->node, i);
4311 AddTesselationLine(NULL, NULL, TPS[0], TPS[1], 0);
4312 AddTesselationLine(NULL, NULL, TPS[0], TPS[2], 1);
4313 AddTesselationLine(NULL, NULL, TPS[1], TPS[2], 2);
4314 if (TriangleNrs.empty())
4315 ELOG(0, "No more free triangle numbers!");
4316 BTS = new BoundaryTriangleSet(BLS, TriangleNrs.top()); // copy triangle ...
4317 AddTesselationTriangle(); // ... and add
4318 TriangleNrs.pop();
4319 BTS->NormalVector = -1 * (*TriangleWalker)->NormalVector;
4320 TriangleWalker++;
4321 }
4322 if (!TriangleNrs.empty()) {
4323 ELOG(0, "There have been less triangles created than removed!");
4324 }
4325 delete (T); // remove the triangleset
4326 }
4327 IndexToIndex * SimplyDegeneratedTriangles = FindAllDegeneratedTriangles();
4328 LOG(2, "DEBUG: Final list of simply degenerated triangles found, containing " << SimplyDegeneratedTriangles->size() << " triangles:");
4329 IndexToIndex::iterator it;
4330 for (it = SimplyDegeneratedTriangles->begin(); it != SimplyDegeneratedTriangles->end(); it++)
4331 LOG(2, "DEBUG: " << (*it).first << " => " << (*it).second);
4332 delete (SimplyDegeneratedTriangles);
4333 /// 5. exit
4334 UniquePolygonSet::iterator PolygonRunner;
4335 while (!ListofDegeneratedPolygons.empty()) {
4336 PolygonRunner = ListofDegeneratedPolygons.begin();
4337 delete (*PolygonRunner);
4338 ListofDegeneratedPolygons.erase(PolygonRunner);
4339 }
4340
4341 return counter;
4342}
4343;
Note: See TracBrowser for help on using the repository browser.