source: src/Tesselation/tesselation.cpp@ d289c6

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

FIX: Tesselation::RemoveDegeneratedTriangles() ended up in endless loop.

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