source: src/Tesselation/tesselation.cpp@ c2f306

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 Candidate_v1.7.0 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 c2f306 was c2f306, checked in by Frederik Heber <heber@…>, 11 years ago

FIX: RemoveTesselationLine() needs to erase line from OpenLines if present.

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