source: src/Tesselation/tesselation.cpp

Candidate_v1.6.1
Last change on this file was 9eb71b3, checked in by Frederik Heber <frederik.heber@…>, 8 years ago

Commented out MemDebug include and Memory::ignore.

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