source: src/Tesselation/tesselation.cpp@ d470a6

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

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

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