source: src/Tesselation/tesselation.cpp@ f6ad4d

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

Added verbosity to some tesselation functions.

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