source: src/Tesselation/tesselation.cpp@ dfe054

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since dfe054 was 75d42a, checked in by Frederik Heber <heber@…>, 11 years ago

FIX: RemovePointFromTesselatedSurface() needs to pick smallest angle when polygon is not convex.

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