source: src/tesselationhelpers.cpp@ cfa795

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

GetCenterofCircumcircle(0 - Removed old calculation that is superceded by use of barycentric coordinates.

Signed-off-by: Frederik Heber <heber@…>

  • Property mode set to 100644
File size: 43.5 KB
Line 
1/*
2 * TesselationHelpers.cpp
3 *
4 * Created on: Aug 3, 2009
5 * Author: heber
6 */
7
8#include "Helpers/MemDebug.hpp"
9
10#include <fstream>
11
12#include "info.hpp"
13#include "linkedcell.hpp"
14#include "linearsystemofequations.hpp"
15#include "log.hpp"
16#include "tesselation.hpp"
17#include "tesselationhelpers.hpp"
18#include "vector.hpp"
19#include "Line.hpp"
20#include "vector_ops.hpp"
21#include "verbose.hpp"
22#include "Plane.hpp"
23
24double DetGet(gsl_matrix * const A, const int inPlace)
25{
26 Info FunctionInfo(__func__);
27 /*
28 inPlace = 1 => A is replaced with the LU decomposed copy.
29 inPlace = 0 => A is retained, and a copy is used for LU.
30 */
31
32 double det;
33 int signum;
34 gsl_permutation *p = gsl_permutation_alloc(A->size1);
35 gsl_matrix *tmpA=0;
36
37 if (inPlace)
38 tmpA = A;
39 else {
40 gsl_matrix *tmpA = gsl_matrix_alloc(A->size1, A->size2);
41 gsl_matrix_memcpy(tmpA , A);
42 }
43
44
45 gsl_linalg_LU_decomp(tmpA , p , &signum);
46 det = gsl_linalg_LU_det(tmpA , signum);
47 gsl_permutation_free(p);
48 if (! inPlace)
49 gsl_matrix_free(tmpA);
50
51 return det;
52};
53
54void GetSphere(Vector * const center, const Vector &a, const Vector &b, const Vector &c, const double RADIUS)
55{
56 Info FunctionInfo(__func__);
57 gsl_matrix *A = gsl_matrix_calloc(3,3);
58 double m11, m12, m13, m14;
59
60 for(int i=0;i<3;i++) {
61 gsl_matrix_set(A, i, 0, a[i]);
62 gsl_matrix_set(A, i, 1, b[i]);
63 gsl_matrix_set(A, i, 2, c[i]);
64 }
65 m11 = DetGet(A, 1);
66
67 for(int i=0;i<3;i++) {
68 gsl_matrix_set(A, i, 0, a[i]*a[i] + b[i]*b[i] + c[i]*c[i]);
69 gsl_matrix_set(A, i, 1, b[i]);
70 gsl_matrix_set(A, i, 2, c[i]);
71 }
72 m12 = DetGet(A, 1);
73
74 for(int i=0;i<3;i++) {
75 gsl_matrix_set(A, i, 0, a[i]*a[i] + b[i]*b[i] + c[i]*c[i]);
76 gsl_matrix_set(A, i, 1, a[i]);
77 gsl_matrix_set(A, i, 2, c[i]);
78 }
79 m13 = DetGet(A, 1);
80
81 for(int i=0;i<3;i++) {
82 gsl_matrix_set(A, i, 0, a[i]*a[i] + b[i]*b[i] + c[i]*c[i]);
83 gsl_matrix_set(A, i, 1, a[i]);
84 gsl_matrix_set(A, i, 2, b[i]);
85 }
86 m14 = DetGet(A, 1);
87
88 if (fabs(m11) < MYEPSILON)
89 DoeLog(1) && (eLog()<< Verbose(1) << "three points are colinear." << endl);
90
91 center->at(0) = 0.5 * m12/ m11;
92 center->at(1) = -0.5 * m13/ m11;
93 center->at(2) = 0.5 * m14/ m11;
94
95 if (fabs(a.distance(*center) - RADIUS) > MYEPSILON)
96 DoeLog(1) && (eLog()<< Verbose(1) << "The given center is further way by " << fabs(a.distance(*center) - RADIUS) << " from a than RADIUS." << endl);
97
98 gsl_matrix_free(A);
99};
100
101
102
103/**
104 * Function returns center of sphere with RADIUS, which rests on points a, b, c
105 * @param Center this vector will be used for return
106 * @param a vector first point of triangle
107 * @param b vector second point of triangle
108 * @param c vector third point of triangle
109 * @param *Umkreismittelpunkt new center point of circumference
110 * @param Direction vector indicates up/down
111 * @param AlternativeDirection Vector, needed in case the triangles have 90 deg angle
112 * @param Halfplaneindicator double indicates whether Direction is up or down
113 * @param AlternativeIndicator double indicates in case of orthogonal triangles which direction of AlternativeDirection is suitable
114 * @param alpha double angle at a
115 * @param beta double, angle at b
116 * @param gamma, double, angle at c
117 * @param Radius, double
118 * @param Umkreisradius double radius of circumscribing circle
119 */
120void GetCenterOfSphere(Vector* const & Center, const Vector &a, const Vector &b, const Vector &c, Vector * const NewUmkreismittelpunkt, const Vector* const Direction, const Vector* const AlternativeDirection,
121 const double HalfplaneIndicator, const double AlternativeIndicator, const double alpha, const double beta, const double gamma, const double RADIUS, const double Umkreisradius)
122{
123 Info FunctionInfo(__func__);
124 Vector TempNormal, helper;
125 double Restradius;
126 Vector OtherCenter;
127 Center->Zero();
128 helper = sin(2.*alpha) * a;
129 (*Center) += helper;
130 helper = sin(2.*beta) * b;
131 (*Center) += helper;
132 helper = sin(2.*gamma) * c;
133 (*Center) += helper;
134 //*Center = a * sin(2.*alpha) + b * sin(2.*beta) + c * sin(2.*gamma) ;
135 Center->Scale(1./(sin(2.*alpha) + sin(2.*beta) + sin(2.*gamma)));
136 (*NewUmkreismittelpunkt) = (*Center);
137 DoLog(1) && (Log() << Verbose(1) << "Center of new circumference is " << *NewUmkreismittelpunkt << ".\n");
138 // Here we calculated center of circumscribing circle, using barycentric coordinates
139 DoLog(1) && (Log() << Verbose(1) << "Center of circumference is " << *Center << " in direction " << *Direction << ".\n");
140
141 TempNormal = a - b;
142 helper = a - c;
143 TempNormal.VectorProduct(helper);
144 if (fabs(HalfplaneIndicator) < MYEPSILON)
145 {
146 if ((TempNormal.ScalarProduct(*AlternativeDirection) <0 && AlternativeIndicator >0) || (TempNormal.ScalarProduct(*AlternativeDirection) >0 && AlternativeIndicator <0))
147 {
148 TempNormal *= -1;
149 }
150 }
151 else
152 {
153 if (((TempNormal.ScalarProduct(*Direction)<0) && (HalfplaneIndicator >0)) || ((TempNormal.ScalarProduct(*Direction)>0) && (HalfplaneIndicator<0)))
154 {
155 TempNormal *= -1;
156 }
157 }
158
159 TempNormal.Normalize();
160 Restradius = sqrt(RADIUS*RADIUS - Umkreisradius*Umkreisradius);
161 DoLog(1) && (Log() << Verbose(1) << "Height of center of circumference to center of sphere is " << Restradius << ".\n");
162 TempNormal.Scale(Restradius);
163 DoLog(1) && (Log() << Verbose(1) << "Shift vector to sphere of circumference is " << TempNormal << ".\n");
164 (*Center) += TempNormal;
165 DoLog(1) && (Log() << Verbose(1) << "Center of sphere of circumference is " << *Center << ".\n");
166 GetSphere(&OtherCenter, a, b, c, RADIUS);
167 DoLog(1) && (Log() << Verbose(1) << "OtherCenter of sphere of circumference is " << OtherCenter << ".\n");
168};
169
170
171/** Constructs the center of the circumcircle defined by three points \a *a, \a *b and \a *c.
172 * \param *Center new center on return
173 * \param *a first point
174 * \param *b second point
175 * \param *c third point
176 */
177void GetCenterofCircumcircle(Vector * const Center, const Vector &a, const Vector &b, const Vector &c)
178{
179 Info FunctionInfo(__func__);
180 Vector helper;
181 double alpha, beta, gamma;
182 Vector SideA = b - c;
183 Vector SideB = c - a;
184 Vector SideC = a - b;
185
186 helper[0] = SideA.NormSquared()*(SideB.NormSquared()+SideC.NormSquared() - SideA.NormSquared());
187 helper[1] = SideB.NormSquared()*(SideC.NormSquared()+SideA.NormSquared() - SideB.NormSquared());
188 helper[2] = SideC.NormSquared()*(SideA.NormSquared()+SideB.NormSquared() - SideC.NormSquared());
189
190 Center->Zero();
191 *Center += helper[0] * a;
192 *Center += helper[1] * b;
193 *Center += helper[2] * c;
194 Center->Scale(1./(helper[0]+helper[1]+helper[2]));
195 Log() << Verbose(1) << "INFO: Center (2nd algo) is at " << *Center << "." << endl;
196};
197
198/** Returns the parameter "path length" for a given \a NewSphereCenter relative to \a OldSphereCenter on a circle on the plane \a CirclePlaneNormal with center \a CircleCenter and radius \a CircleRadius.
199 * Test whether the \a NewSphereCenter is really on the given plane and in distance \a CircleRadius from \a CircleCenter.
200 * It calculates the angle, making it unique on [0,2.*M_PI) by comparing to SearchDirection.
201 * Also the new center is invalid if it the same as the old one and does not lie right above (\a NormalVector) the base line (\a CircleCenter).
202 * \param CircleCenter Center of the parameter circle
203 * \param CirclePlaneNormal normal vector to plane of the parameter circle
204 * \param CircleRadius radius of the parameter circle
205 * \param NewSphereCenter new center of a circumcircle
206 * \param OldSphereCenter old center of a circumcircle, defining the zero "path length" on the parameter circle
207 * \param NormalVector normal vector
208 * \param SearchDirection search direction to make angle unique on return.
209 * \return Angle between \a NewSphereCenter and \a OldSphereCenter relative to \a CircleCenter, 2.*M_PI if one test fails
210 */
211double GetPathLengthonCircumCircle(const Vector &CircleCenter, const Vector &CirclePlaneNormal, const double CircleRadius, const Vector &NewSphereCenter, const Vector &OldSphereCenter, const Vector &NormalVector, const Vector &SearchDirection)
212{
213 Info FunctionInfo(__func__);
214 Vector helper;
215 double radius, alpha;
216
217 Vector RelativeOldSphereCenter = OldSphereCenter - CircleCenter;
218 Vector RelativeNewSphereCenter = NewSphereCenter - CircleCenter;
219 helper = RelativeNewSphereCenter;
220 // test whether new center is on the parameter circle's plane
221 if (fabs(helper.ScalarProduct(CirclePlaneNormal)) > HULLEPSILON) {
222 DoeLog(1) && (eLog()<< Verbose(1) << "Something's very wrong here: NewSphereCenter is not on the band's plane as desired by " <<fabs(helper.ScalarProduct(CirclePlaneNormal)) << "!" << endl);
223 helper.ProjectOntoPlane(CirclePlaneNormal);
224 }
225 radius = helper.NormSquared();
226 // test whether the new center vector has length of CircleRadius
227 if (fabs(radius - CircleRadius) > HULLEPSILON)
228 DoeLog(1) && (eLog()<< Verbose(1) << "The projected center of the new sphere has radius " << radius << " instead of " << CircleRadius << "." << endl);
229 alpha = helper.Angle(RelativeOldSphereCenter);
230 // make the angle unique by checking the halfplanes/search direction
231 if (helper.ScalarProduct(SearchDirection) < -HULLEPSILON) // acos is not unique on [0, 2.*M_PI), hence extra check to decide between two half intervals
232 alpha = 2.*M_PI - alpha;
233 DoLog(1) && (Log() << Verbose(1) << "INFO: RelativeNewSphereCenter is " << helper << ", RelativeOldSphereCenter is " << RelativeOldSphereCenter << " and resulting angle is " << alpha << "." << endl);
234 radius = helper.distance(RelativeOldSphereCenter);
235 helper.ProjectOntoPlane(NormalVector);
236 // check whether new center is somewhat away or at least right over the current baseline to prevent intersecting triangles
237 if ((radius > HULLEPSILON) || (helper.Norm() < HULLEPSILON)) {
238 DoLog(1) && (Log() << Verbose(1) << "INFO: Distance between old and new center is " << radius << " and between new center and baseline center is " << helper.Norm() << "." << endl);
239 return alpha;
240 } else {
241 DoLog(1) && (Log() << Verbose(1) << "INFO: NewSphereCenter " << RelativeNewSphereCenter << " is too close to RelativeOldSphereCenter" << RelativeOldSphereCenter << "." << endl);
242 return 2.*M_PI;
243 }
244};
245
246struct Intersection {
247 Vector x1;
248 Vector x2;
249 Vector x3;
250 Vector x4;
251};
252
253/**
254 * Intersection calculation function.
255 *
256 * @param x to find the result for
257 * @param function parameter
258 */
259double MinIntersectDistance(const gsl_vector * x, void *params)
260{
261 Info FunctionInfo(__func__);
262 double retval = 0;
263 struct Intersection *I = (struct Intersection *)params;
264 Vector intersection;
265 for (int i=0;i<NDIM;i++)
266 intersection[i] = gsl_vector_get(x, i);
267
268 Vector SideA = I->x1 -I->x2 ;
269 Vector HeightA = intersection - I->x1;
270 HeightA.ProjectOntoPlane(SideA);
271
272 Vector SideB = I->x3 - I->x4;
273 Vector HeightB = intersection - I->x3;
274 HeightB.ProjectOntoPlane(SideB);
275
276 retval = HeightA.ScalarProduct(HeightA) + HeightB.ScalarProduct(HeightB);
277 //Log() << Verbose(1) << "MinIntersectDistance called, result: " << retval << endl;
278
279 return retval;
280};
281
282
283/**
284 * Calculates whether there is an intersection between two lines. The first line
285 * always goes through point 1 and point 2 and the second line is given by the
286 * connection between point 4 and point 5.
287 *
288 * @param point 1 of line 1
289 * @param point 2 of line 1
290 * @param point 1 of line 2
291 * @param point 2 of line 2
292 *
293 * @return true if there is an intersection between the given lines, false otherwise
294 */
295bool existsIntersection(const Vector &point1, const Vector &point2, const Vector &point3, const Vector &point4)
296{
297 Info FunctionInfo(__func__);
298 bool result;
299
300 struct Intersection par;
301 par.x1 = point1;
302 par.x2 = point2;
303 par.x3 = point3;
304 par.x4 = point4;
305
306 const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;
307 gsl_multimin_fminimizer *s = NULL;
308 gsl_vector *ss, *x;
309 gsl_multimin_function minexFunction;
310
311 size_t iter = 0;
312 int status;
313 double size;
314
315 /* Starting point */
316 x = gsl_vector_alloc(NDIM);
317 gsl_vector_set(x, 0, point1[0]);
318 gsl_vector_set(x, 1, point1[1]);
319 gsl_vector_set(x, 2, point1[2]);
320
321 /* Set initial step sizes to 1 */
322 ss = gsl_vector_alloc(NDIM);
323 gsl_vector_set_all(ss, 1.0);
324
325 /* Initialize method and iterate */
326 minexFunction.n = NDIM;
327 minexFunction.f = &MinIntersectDistance;
328 minexFunction.params = (void *)&par;
329
330 s = gsl_multimin_fminimizer_alloc(T, NDIM);
331 gsl_multimin_fminimizer_set(s, &minexFunction, x, ss);
332
333 do {
334 iter++;
335 status = gsl_multimin_fminimizer_iterate(s);
336
337 if (status) {
338 break;
339 }
340
341 size = gsl_multimin_fminimizer_size(s);
342 status = gsl_multimin_test_size(size, 1e-2);
343
344 if (status == GSL_SUCCESS) {
345 DoLog(1) && (Log() << Verbose(1) << "converged to minimum" << endl);
346 }
347 } while (status == GSL_CONTINUE && iter < 100);
348
349 // check whether intersection is in between or not
350 Vector intersection;
351 double t1, t2;
352 for (int i = 0; i < NDIM; i++) {
353 intersection[i] = gsl_vector_get(s->x, i);
354 }
355
356 Vector SideA = par.x2 - par.x1;
357 Vector HeightA = intersection - par.x1;
358
359 t1 = HeightA.ScalarProduct(SideA)/SideA.ScalarProduct(SideA);
360
361 Vector SideB = par.x4 - par.x3;
362 Vector HeightB = intersection - par.x3;
363
364 t2 = HeightB.ScalarProduct(SideB)/SideB.ScalarProduct(SideB);
365
366 Log() << Verbose(1) << "Intersection " << intersection << " is at "
367 << t1 << " for (" << point1 << "," << point2 << ") and at "
368 << t2 << " for (" << point3 << "," << point4 << "): ";
369
370 if (((t1 >= 0) && (t1 <= 1)) && ((t2 >= 0) && (t2 <= 1))) {
371 DoLog(1) && (Log() << Verbose(1) << "true intersection." << endl);
372 result = true;
373 } else {
374 DoLog(1) && (Log() << Verbose(1) << "intersection out of region of interest." << endl);
375 result = false;
376 }
377
378 // free minimizer stuff
379 gsl_vector_free(x);
380 gsl_vector_free(ss);
381 gsl_multimin_fminimizer_free(s);
382
383 return result;
384};
385
386/** Gets the angle between a point and a reference relative to the provided center.
387 * We have two shanks point and reference between which the angle is calculated
388 * and by scalar product with OrthogonalVector we decide the interval.
389 * @param point to calculate the angle for
390 * @param reference to which to calculate the angle
391 * @param OrthogonalVector points in direction of [pi,2pi] interval
392 *
393 * @return angle between point and reference
394 */
395double GetAngle(const Vector &point, const Vector &reference, const Vector &OrthogonalVector)
396{
397 Info FunctionInfo(__func__);
398 if (reference.IsZero())
399 return M_PI;
400
401 // calculate both angles and correct with in-plane vector
402 if (point.IsZero())
403 return M_PI;
404 double phi = point.Angle(reference);
405 if (OrthogonalVector.ScalarProduct(point) > 0) {
406 phi = 2.*M_PI - phi;
407 }
408
409 DoLog(1) && (Log() << Verbose(1) << "INFO: " << point << " has angle " << phi << " with respect to reference " << reference << "." << endl);
410
411 return phi;
412}
413
414
415/** Calculates the volume of a general tetraeder.
416 * \param *a first vector
417 * \param *b second vector
418 * \param *c third vector
419 * \param *d fourth vector
420 * \return \f$ \frac{1}{6} \cdot ((a-d) \times (a-c) \cdot (a-b)) \f$
421 */
422double CalculateVolumeofGeneralTetraeder(const Vector &a, const Vector &b, const Vector &c, const Vector &d)
423{
424 Info FunctionInfo(__func__);
425 Vector Point, TetraederVector[3];
426 double volume;
427
428 TetraederVector[0] = a;
429 TetraederVector[1] = b;
430 TetraederVector[2] = c;
431 for (int j=0;j<3;j++)
432 TetraederVector[j].SubtractVector(d);
433 Point = TetraederVector[0];
434 Point.VectorProduct(TetraederVector[1]);
435 volume = 1./6. * fabs(Point.ScalarProduct(TetraederVector[2]));
436 return volume;
437};
438
439/** Calculates the area of a general triangle.
440 * We use the Heron's formula of area, [Bronstein, S. 138]
441 * \param &A first vector
442 * \param &B second vector
443 * \param &C third vector
444 * \return \f$ \frac{1}{6} \cdot ((a-d) \times (a-c) \cdot (a-b)) \f$
445 */
446double CalculateAreaofGeneralTriangle(const Vector &A, const Vector &B, const Vector &C)
447{
448 Info FunctionInfo(__func__);
449
450 const double sidea = B.distance(C);
451 const double sideb = A.distance(C);
452 const double sidec = A.distance(B);
453 const double s = (sidea+sideb+sidec)/2.;
454
455 const double area = sqrt(s*(s-sidea)*(s-sideb)*(s-sidec));
456 return area;
457};
458
459
460/** Checks for a new special triangle whether one of its edges is already present with one one triangle connected.
461 * This enforces that special triangles (i.e. degenerated ones) should at last close the open-edge frontier and not
462 * make it bigger (i.e. closing one (the baseline) and opening two new ones).
463 * \param TPS[3] nodes of the triangle
464 * \return true - there is such a line (i.e. creation of degenerated triangle is valid), false - no such line (don't create)
465 */
466bool CheckLineCriteriaForDegeneratedTriangle(const BoundaryPointSet * const nodes[3])
467{
468 Info FunctionInfo(__func__);
469 bool result = false;
470 int counter = 0;
471
472 // check all three points
473 for (int i=0;i<3;i++)
474 for (int j=i+1; j<3; j++) {
475 if (nodes[i] == NULL) {
476 DoLog(1) && (Log() << Verbose(1) << "Node nr. " << i << " is not yet present." << endl);
477 result = true;
478 } else if (nodes[i]->lines.find(nodes[j]->node->nr) != nodes[i]->lines.end()) { // there already is a line
479 LineMap::const_iterator FindLine;
480 pair<LineMap::const_iterator,LineMap::const_iterator> FindPair;
481 FindPair = nodes[i]->lines.equal_range(nodes[j]->node->nr);
482 for (FindLine = FindPair.first; FindLine != FindPair.second; ++FindLine) {
483 // If there is a line with less than two attached triangles, we don't need a new line.
484 if (FindLine->second->triangles.size() < 2) {
485 counter++;
486 break; // increase counter only once per edge
487 }
488 }
489 } else { // no line
490 DoLog(1) && (Log() << Verbose(1) << "The line between " << *nodes[i] << " and " << *nodes[j] << " is not yet present, hence no need for a degenerate triangle." << endl);
491 result = true;
492 }
493 }
494 if ((!result) && (counter > 1)) {
495 DoLog(1) && (Log() << Verbose(1) << "INFO: Degenerate triangle is ok, at least two, here " << counter << ", existing lines are used." << endl);
496 result = true;
497 }
498 return result;
499};
500
501
502///** Sort function for the candidate list.
503// */
504//bool SortCandidates(const CandidateForTesselation* candidate1, const CandidateForTesselation* candidate2)
505//{
506// Info FunctionInfo(__func__);
507// Vector BaseLineVector, OrthogonalVector, helper;
508// if (candidate1->BaseLine != candidate2->BaseLine) { // sanity check
509// DoeLog(1) && (eLog()<< Verbose(1) << "sortCandidates was called for two different baselines: " << candidate1->BaseLine << " and " << candidate2->BaseLine << "." << endl);
510// //return false;
511// exit(1);
512// }
513// // create baseline vector
514// BaseLineVector.CopyVector(candidate1->BaseLine->endpoints[1]->node->node);
515// BaseLineVector.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
516// BaseLineVector.Normalize();
517//
518// // create normal in-plane vector to cope with acos() non-uniqueness on [0,2pi] (note that is pointing in the "right" direction already, hence ">0" test!)
519// helper.CopyVector(candidate1->BaseLine->endpoints[0]->node->node);
520// helper.SubtractVector(candidate1->point->node);
521// OrthogonalVector.CopyVector(&helper);
522// helper.VectorProduct(&BaseLineVector);
523// OrthogonalVector.SubtractVector(&helper);
524// OrthogonalVector.Normalize();
525//
526// // calculate both angles and correct with in-plane vector
527// helper.CopyVector(candidate1->point->node);
528// helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
529// double phi = BaseLineVector.Angle(&helper);
530// if (OrthogonalVector.ScalarProduct(&helper) > 0) {
531// phi = 2.*M_PI - phi;
532// }
533// helper.CopyVector(candidate2->point->node);
534// helper.SubtractVector(candidate1->BaseLine->endpoints[0]->node->node);
535// double psi = BaseLineVector.Angle(&helper);
536// if (OrthogonalVector.ScalarProduct(&helper) > 0) {
537// psi = 2.*M_PI - psi;
538// }
539//
540// Log() << Verbose(1) << *candidate1->point << " has angle " << phi << endl;
541// Log() << Verbose(1) << *candidate2->point << " has angle " << psi << endl;
542//
543// // return comparison
544// return phi < psi;
545//};
546
547/**
548 * Finds the point which is second closest to the provided one.
549 *
550 * @param Point to which to find the second closest other point
551 * @param linked cell structure
552 *
553 * @return point which is second closest to the provided one
554 */
555TesselPoint* FindSecondClosestTesselPoint(const Vector* Point, const LinkedCell* const LC)
556{
557 Info FunctionInfo(__func__);
558 TesselPoint* closestPoint = NULL;
559 TesselPoint* secondClosestPoint = NULL;
560 double distance = 1e16;
561 double secondDistance = 1e16;
562 Vector helper;
563 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
564
565 LC->SetIndexToVector(Point); // ignore status as we calculate bounds below sensibly
566 for(int i=0;i<NDIM;i++) // store indices of this cell
567 N[i] = LC->n[i];
568 DoLog(1) && (Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl);
569
570 LC->GetNeighbourBounds(Nlower, Nupper);
571 //Log() << Verbose(1) << endl;
572 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
573 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
574 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
575 const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
576 //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
577 if (List != NULL) {
578 for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
579 helper = (*Point) - (*(*Runner)->node);
580 double currentNorm = helper. Norm();
581 if (currentNorm < distance) {
582 // remember second point
583 secondDistance = distance;
584 secondClosestPoint = closestPoint;
585 // mark down new closest point
586 distance = currentNorm;
587 closestPoint = (*Runner);
588 //Log() << Verbose(2) << "INFO: New Second Nearest Neighbour is " << *secondClosestPoint << "." << endl;
589 }
590 }
591 } else {
592 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << ","
593 << LC->n[2] << " is invalid!" << endl;
594 }
595 }
596
597 return secondClosestPoint;
598};
599
600/**
601 * Finds the point which is closest to the provided one.
602 *
603 * @param Point to which to find the closest other point
604 * @param SecondPoint the second closest other point on return, NULL if none found
605 * @param linked cell structure
606 *
607 * @return point which is closest to the provided one, NULL if none found
608 */
609TesselPoint* FindClosestTesselPoint(const Vector* Point, TesselPoint *&SecondPoint, const LinkedCell* const LC)
610{
611 Info FunctionInfo(__func__);
612 TesselPoint* closestPoint = NULL;
613 SecondPoint = NULL;
614 double distance = 1e16;
615 double secondDistance = 1e16;
616 Vector helper;
617 int N[NDIM], Nlower[NDIM], Nupper[NDIM];
618
619 LC->SetIndexToVector(Point); // ignore status as we calculate bounds below sensibly
620 for(int i=0;i<NDIM;i++) // store indices of this cell
621 N[i] = LC->n[i];
622 DoLog(1) && (Log() << Verbose(1) << "INFO: Center cell is " << N[0] << ", " << N[1] << ", " << N[2] << " with No. " << LC->index << "." << endl);
623
624 LC->GetNeighbourBounds(Nlower, Nupper);
625 //Log() << Verbose(1) << endl;
626 for (LC->n[0] = Nlower[0]; LC->n[0] <= Nupper[0]; LC->n[0]++)
627 for (LC->n[1] = Nlower[1]; LC->n[1] <= Nupper[1]; LC->n[1]++)
628 for (LC->n[2] = Nlower[2]; LC->n[2] <= Nupper[2]; LC->n[2]++) {
629 const LinkedCell::LinkedNodes *List = LC->GetCurrentCell();
630 //Log() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << "," << LC->n[2] << endl;
631 if (List != NULL) {
632 for (LinkedCell::LinkedNodes::const_iterator Runner = List->begin(); Runner != List->end(); Runner++) {
633 helper = (*Point) - (*(*Runner)->node);
634 double currentNorm = helper.NormSquared();
635 if (currentNorm < distance) {
636 secondDistance = distance;
637 SecondPoint = closestPoint;
638 distance = currentNorm;
639 closestPoint = (*Runner);
640 //Log() << Verbose(1) << "INFO: New Nearest Neighbour is " << *closestPoint << "." << endl;
641 } else if (currentNorm < secondDistance) {
642 secondDistance = currentNorm;
643 SecondPoint = (*Runner);
644 //Log() << Verbose(1) << "INFO: New Second Nearest Neighbour is " << *SecondPoint << "." << endl;
645 }
646 }
647 } else {
648 eLog() << Verbose(1) << "The current cell " << LC->n[0] << "," << LC->n[1] << ","
649 << LC->n[2] << " is invalid!" << endl;
650 }
651 }
652 // output
653 if (closestPoint != NULL) {
654 DoLog(1) && (Log() << Verbose(1) << "Closest point is " << *closestPoint);
655 if (SecondPoint != NULL)
656 DoLog(0) && (Log() << Verbose(0) << " and second closest is " << *SecondPoint);
657 DoLog(0) && (Log() << Verbose(0) << "." << endl);
658 }
659 return closestPoint;
660};
661
662/** Returns the closest point on \a *Base with respect to \a *OtherBase.
663 * \param *out output stream for debugging
664 * \param *Base reference line
665 * \param *OtherBase other base line
666 * \return Vector on reference line that has closest distance
667 */
668Vector * GetClosestPointBetweenLine(const BoundaryLineSet * const Base, const BoundaryLineSet * const OtherBase)
669{
670 Info FunctionInfo(__func__);
671 // construct the plane of the two baselines (i.e. take both their directional vectors)
672 Vector Baseline = (*Base->endpoints[1]->node->node) - (*Base->endpoints[0]->node->node);
673 Vector OtherBaseline = (*OtherBase->endpoints[1]->node->node) - (*OtherBase->endpoints[0]->node->node);
674 Vector Normal = Baseline;
675 Normal.VectorProduct(OtherBaseline);
676 Normal.Normalize();
677 DoLog(1) && (Log() << Verbose(1) << "First direction is " << Baseline << ", second direction is " << OtherBaseline << ", normal of intersection plane is " << Normal << "." << endl);
678
679 // project one offset point of OtherBase onto this plane (and add plane offset vector)
680 Vector NewOffset = (*OtherBase->endpoints[0]->node->node) - (*Base->endpoints[0]->node->node);
681 NewOffset.ProjectOntoPlane(Normal);
682 NewOffset += (*Base->endpoints[0]->node->node);
683 Vector NewDirection = NewOffset + OtherBaseline;
684
685 // calculate the intersection between this projected baseline and Base
686 Vector *Intersection = new Vector;
687 Line line1 = makeLineThrough(*(Base->endpoints[0]->node->node),*(Base->endpoints[1]->node->node));
688 Line line2 = makeLineThrough(NewOffset, NewDirection);
689 *Intersection = line1.getIntersection(line2);
690 Normal = (*Intersection) - (*Base->endpoints[0]->node->node);
691 DoLog(1) && (Log() << Verbose(1) << "Found closest point on " << *Base << " at " << *Intersection << ", factor in line is " << fabs(Normal.ScalarProduct(Baseline)/Baseline.NormSquared()) << "." << endl);
692
693 return Intersection;
694};
695
696/** Returns the distance to the plane defined by \a *triangle
697 * \param *out output stream for debugging
698 * \param *x Vector to calculate distance to
699 * \param *triangle triangle defining plane
700 * \return distance between \a *x and plane defined by \a *triangle, -1 - if something went wrong
701 */
702double DistanceToTrianglePlane(const Vector *x, const BoundaryTriangleSet * const triangle)
703{
704 Info FunctionInfo(__func__);
705 double distance = 0.;
706 if (x == NULL) {
707 return -1;
708 }
709 distance = x->DistanceToSpace(triangle->getPlane());
710 return distance;
711};
712
713/** Creates the objects in a VRML file.
714 * \param *out output stream for debugging
715 * \param *vrmlfile output stream for tecplot data
716 * \param *Tess Tesselation structure with constructed triangles
717 * \param *mol molecule structure with atom positions
718 */
719void WriteVrmlFile(ofstream * const vrmlfile, const Tesselation * const Tess, const PointCloud * const cloud)
720{
721 Info FunctionInfo(__func__);
722 TesselPoint *Walker = NULL;
723 int i;
724 Vector *center = cloud->GetCenter();
725 if (vrmlfile != NULL) {
726 //Log() << Verbose(1) << "Writing Raster3D file ... ";
727 *vrmlfile << "#VRML V2.0 utf8" << endl;
728 *vrmlfile << "#Created by molecuilder" << endl;
729 *vrmlfile << "#All atoms as spheres" << endl;
730 cloud->GoToFirst();
731 while (!cloud->IsEnd()) {
732 Walker = cloud->GetPoint();
733 *vrmlfile << "Sphere {" << endl << " "; // 2 is sphere type
734 for (i=0;i<NDIM;i++)
735 *vrmlfile << Walker->node->at(i)-center->at(i) << " ";
736 *vrmlfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
737 cloud->GoToNext();
738 }
739
740 *vrmlfile << "# All tesselation triangles" << endl;
741 for (TriangleMap::const_iterator TriangleRunner = Tess->TrianglesOnBoundary.begin(); TriangleRunner != Tess->TrianglesOnBoundary.end(); TriangleRunner++) {
742 *vrmlfile << "1" << endl << " "; // 1 is triangle type
743 for (i=0;i<3;i++) { // print each node
744 for (int j=0;j<NDIM;j++) // and for each node all NDIM coordinates
745 *vrmlfile << TriangleRunner->second->endpoints[i]->node->node->at(j)-center->at(j) << " ";
746 *vrmlfile << "\t";
747 }
748 *vrmlfile << "1. 0. 0." << endl; // red as colour
749 *vrmlfile << "18" << endl << " 0.5 0.5 0.5" << endl; // 18 is transparency type for previous object
750 }
751 } else {
752 DoeLog(1) && (eLog()<< Verbose(1) << "Given vrmlfile is " << vrmlfile << "." << endl);
753 }
754 delete(center);
755};
756
757/** Writes additionally the current sphere (i.e. the last triangle to file).
758 * \param *out output stream for debugging
759 * \param *rasterfile output stream for tecplot data
760 * \param *Tess Tesselation structure with constructed triangles
761 * \param *mol molecule structure with atom positions
762 */
763void IncludeSphereinRaster3D(ofstream * const rasterfile, const Tesselation * const Tess, const PointCloud * const cloud)
764{
765 Info FunctionInfo(__func__);
766 Vector helper;
767
768 if (Tess->LastTriangle != NULL) {
769 // include the current position of the virtual sphere in the temporary raster3d file
770 Vector *center = cloud->GetCenter();
771 // make the circumsphere's center absolute again
772 Vector helper = (1./3.) * ((*Tess->LastTriangle->endpoints[0]->node->node) +
773 (*Tess->LastTriangle->endpoints[1]->node->node) +
774 (*Tess->LastTriangle->endpoints[2]->node->node));
775 helper -= (*center);
776 // and add to file plus translucency object
777 *rasterfile << "# current virtual sphere\n";
778 *rasterfile << "8\n 25.0 0.6 -1.0 -1.0 -1.0 0.2 0 0 0 0\n";
779 *rasterfile << "2\n " << helper[0] << " " << helper[1] << " " << helper[2] << "\t" << 5. << "\t1 0 0\n";
780 *rasterfile << "9\n terminating special property\n";
781 delete(center);
782 }
783};
784
785/** Creates the objects in a raster3d file (renderable with a header.r3d).
786 * \param *out output stream for debugging
787 * \param *rasterfile output stream for tecplot data
788 * \param *Tess Tesselation structure with constructed triangles
789 * \param *mol molecule structure with atom positions
790 */
791void WriteRaster3dFile(ofstream * const rasterfile, const Tesselation * const Tess, const PointCloud * const cloud)
792{
793 Info FunctionInfo(__func__);
794 TesselPoint *Walker = NULL;
795 int i;
796 Vector *center = cloud->GetCenter();
797 if (rasterfile != NULL) {
798 //Log() << Verbose(1) << "Writing Raster3D file ... ";
799 *rasterfile << "# Raster3D object description, created by MoleCuilder" << endl;
800 *rasterfile << "@header.r3d" << endl;
801 *rasterfile << "# All atoms as spheres" << endl;
802 cloud->GoToFirst();
803 while (!cloud->IsEnd()) {
804 Walker = cloud->GetPoint();
805 *rasterfile << "2" << endl << " "; // 2 is sphere type
806 for (int j=0;j<NDIM;j++) { // and for each node all NDIM coordinates
807 const double tmp = Walker->node->at(j)-center->at(j);
808 *rasterfile << ((fabs(tmp) < MYEPSILON) ? 0 : tmp) << " ";
809 }
810 *rasterfile << "\t0.1\t1. 1. 1." << endl; // radius 0.05 and white as colour
811 cloud->GoToNext();
812 }
813
814 *rasterfile << "# All tesselation triangles" << endl;
815 *rasterfile << "8\n 25. -1. 1. 1. 1. 0.0 0 0 0 2\n SOLID 1.0 0.0 0.0\n BACKFACE 0.3 0.3 1.0 0 0\n";
816 for (TriangleMap::const_iterator TriangleRunner = Tess->TrianglesOnBoundary.begin(); TriangleRunner != Tess->TrianglesOnBoundary.end(); TriangleRunner++) {
817 *rasterfile << "1" << endl << " "; // 1 is triangle type
818 for (i=0;i<3;i++) { // print each node
819 for (int j=0;j<NDIM;j++) { // and for each node all NDIM coordinates
820 const double tmp = TriangleRunner->second->endpoints[i]->node->node->at(j)-center->at(j);
821 *rasterfile << ((fabs(tmp) < MYEPSILON) ? 0 : tmp) << " ";
822 }
823 *rasterfile << "\t";
824 }
825 *rasterfile << "1. 0. 0." << endl; // red as colour
826 //*rasterfile << "18" << endl << " 0.5 0.5 0.5" << endl; // 18 is transparency type for previous object
827 }
828 *rasterfile << "9\n# terminating special property\n";
829 } else {
830 DoeLog(1) && (eLog()<< Verbose(1) << "Given rasterfile is " << rasterfile << "." << endl);
831 }
832 IncludeSphereinRaster3D(rasterfile, Tess, cloud);
833 delete(center);
834};
835
836/** This function creates the tecplot file, displaying the tesselation of the hull.
837 * \param *out output stream for debugging
838 * \param *tecplot output stream for tecplot data
839 * \param N arbitrary number to differentiate various zones in the tecplot format
840 */
841void WriteTecplotFile(ofstream * const tecplot, const Tesselation * const TesselStruct, const PointCloud * const cloud, const int N)
842{
843 Info FunctionInfo(__func__);
844 if ((tecplot != NULL) && (TesselStruct != NULL)) {
845 // write header
846 *tecplot << "TITLE = \"3D CONVEX SHELL\"" << endl;
847 *tecplot << "VARIABLES = \"X\" \"Y\" \"Z\" \"U\"" << endl;
848 *tecplot << "ZONE T=\"";
849 if (N < 0) {
850 *tecplot << cloud->GetName();
851 } else {
852 *tecplot << N << "-";
853 if (TesselStruct->LastTriangle != NULL) {
854 for (int i=0;i<3;i++)
855 *tecplot << (i==0 ? "" : "_") << TesselStruct->LastTriangle->endpoints[i]->node->getName();
856 } else {
857 *tecplot << "none";
858 }
859 }
860 *tecplot << "\", N=" << TesselStruct->PointsOnBoundary.size() << ", E=" << TesselStruct->TrianglesOnBoundary.size() << ", DATAPACKING=POINT, ZONETYPE=FETRIANGLE" << endl;
861 const int MaxId=cloud->GetMaxId();
862 int *LookupList = new int[MaxId];
863 for (int i=0; i< MaxId ; i++){
864 LookupList[i] = -1;
865 }
866
867 // print atom coordinates
868 int Counter = 1;
869 TesselPoint *Walker = NULL;
870 for (PointMap::const_iterator target = TesselStruct->PointsOnBoundary.begin(); target != TesselStruct->PointsOnBoundary.end(); ++target) {
871 Walker = target->second->node;
872 LookupList[Walker->nr] = Counter++;
873 for (int i=0;i<NDIM;i++) {
874 const double tmp = Walker->node->at(i);
875 *tecplot << ((fabs(tmp) < MYEPSILON) ? 0 : tmp) << " ";
876 }
877 *tecplot << target->second->value << endl;
878 }
879 *tecplot << endl;
880 // print connectivity
881 DoLog(1) && (Log() << Verbose(1) << "The following triangles were created:" << endl);
882 for (TriangleMap::const_iterator runner = TesselStruct->TrianglesOnBoundary.begin(); runner != TesselStruct->TrianglesOnBoundary.end(); runner++) {
883 DoLog(1) && (Log() << Verbose(1) << " " << runner->second->endpoints[0]->node->getName() << "<->" << runner->second->endpoints[1]->node->getName() << "<->" << runner->second->endpoints[2]->node->getName() << endl);
884 *tecplot << LookupList[runner->second->endpoints[0]->node->nr] << " " << LookupList[runner->second->endpoints[1]->node->nr] << " " << LookupList[runner->second->endpoints[2]->node->nr] << endl;
885 }
886 delete[] (LookupList);
887 }
888};
889
890/** Calculates the concavity for each of the BoundaryPointSet's in a Tesselation.
891 * Sets BoundaryPointSet::value equal to the number of connected lines that are not convex.
892 * \param *out output stream for debugging
893 * \param *TesselStruct pointer to Tesselation structure
894 */
895void CalculateConcavityPerBoundaryPoint(const Tesselation * const TesselStruct)
896{
897 Info FunctionInfo(__func__);
898 class BoundaryPointSet *point = NULL;
899 class BoundaryLineSet *line = NULL;
900 class BoundaryTriangleSet *triangle = NULL;
901 double ConcavityPerLine = 0.;
902 double ConcavityPerTriangle = 0.;
903 double area = 0.;
904 double totalarea = 0.;
905
906 for (PointMap::const_iterator PointRunner = TesselStruct->PointsOnBoundary.begin(); PointRunner != TesselStruct->PointsOnBoundary.end(); PointRunner++) {
907 point = PointRunner->second;
908 DoLog(1) && (Log() << Verbose(1) << "INFO: Current point is " << *point << "." << endl);
909
910 // calculate mean concavity over all connected line
911 ConcavityPerLine = 0.;
912 for (LineMap::iterator LineRunner = point->lines.begin(); LineRunner != point->lines.end(); LineRunner++) {
913 line = LineRunner->second;
914 //Log() << Verbose(1) << "INFO: Current line of point " << *point << " is " << *line << "." << endl;
915 ConcavityPerLine -= line->CalculateConvexity();
916 }
917 ConcavityPerLine /= point->lines.size();
918
919 // weigh with total area of the surrounding triangles
920 totalarea = 0.;
921 TriangleSet *triangles = TesselStruct->GetAllTriangles(PointRunner->second);
922 for (TriangleSet::iterator TriangleRunner = triangles->begin(); TriangleRunner != triangles->end(); ++TriangleRunner) {
923 totalarea += CalculateAreaofGeneralTriangle(*(*TriangleRunner)->endpoints[0]->node->node, *(*TriangleRunner)->endpoints[1]->node->node, *(*TriangleRunner)->endpoints[2]->node->node);
924 }
925 ConcavityPerLine *= totalarea;
926
927 // calculate mean concavity over all attached triangles
928 ConcavityPerTriangle = 0.;
929 for (TriangleSet::const_iterator TriangleRunner = triangles->begin(); TriangleRunner != triangles->end(); ++TriangleRunner) {
930 line = (*TriangleRunner)->GetThirdLine(PointRunner->second);
931 triangle = line->GetOtherTriangle(*TriangleRunner);
932 area = CalculateAreaofGeneralTriangle(*triangle->endpoints[0]->node->node, *triangle->endpoints[1]->node->node, *triangle->endpoints[2]->node->node);
933 area += CalculateAreaofGeneralTriangle(*(*TriangleRunner)->endpoints[0]->node->node, *(*TriangleRunner)->endpoints[1]->node->node, *(*TriangleRunner)->endpoints[2]->node->node);
934 area *= -line->CalculateConvexity();
935 if (area > 0)
936 ConcavityPerTriangle += area;
937// else
938// ConcavityPerTriangle -= area;
939 }
940 ConcavityPerTriangle /= triangles->size()/totalarea;
941 delete(triangles);
942
943 // add up
944 point->value = ConcavityPerLine + ConcavityPerTriangle;
945 }
946};
947
948
949
950/** Calculates the concavity for each of the BoundaryPointSet's in a Tesselation.
951 * Sets BoundaryPointSet::value equal to the nearest distance to convex envelope.
952 * \param *out output stream for debugging
953 * \param *TesselStruct pointer to Tesselation structure
954 * \param *Convex pointer to convex Tesselation structure as reference
955 */
956void CalculateConstrictionPerBoundaryPoint(const Tesselation * const TesselStruct, const Tesselation * const Convex)
957{
958 Info FunctionInfo(__func__);
959 double distance = 0.;
960
961 for (PointMap::const_iterator PointRunner = TesselStruct->PointsOnBoundary.begin(); PointRunner != TesselStruct->PointsOnBoundary.end(); PointRunner++) {
962 DoeLog(1) && (eLog() << Verbose(1) << "INFO: Current point is " << * PointRunner->second << "." << endl);
963
964 distance = 0.;
965 for (TriangleMap::const_iterator TriangleRunner = Convex->TrianglesOnBoundary.begin(); TriangleRunner != Convex->TrianglesOnBoundary.end(); TriangleRunner++) {
966 const double CurrentDistance = Convex->GetDistanceSquaredToTriangle(*PointRunner->second->node->node, TriangleRunner->second);
967 if (CurrentDistance < distance)
968 distance = CurrentDistance;
969 }
970
971 PointRunner->second->value = distance;
972 }
973};
974
975/** Checks whether each BoundaryLineSet in the Tesselation has two triangles.
976 * \param *out output stream for debugging
977 * \param *TesselStruct
978 * \return true - all have exactly two triangles, false - some not, list is printed to screen
979 */
980bool CheckListOfBaselines(const Tesselation * const TesselStruct)
981{
982 Info FunctionInfo(__func__);
983 LineMap::const_iterator testline;
984 bool result = false;
985 int counter = 0;
986
987 DoLog(1) && (Log() << Verbose(1) << "Check: List of Baselines with not two connected triangles:" << endl);
988 for (testline = TesselStruct->LinesOnBoundary.begin(); testline != TesselStruct->LinesOnBoundary.end(); testline++) {
989 if (testline->second->triangles.size() != 2) {
990 DoLog(2) && (Log() << Verbose(2) << *testline->second << "\t" << testline->second->triangles.size() << endl);
991 counter++;
992 }
993 }
994 if (counter == 0) {
995 DoLog(1) && (Log() << Verbose(1) << "None." << endl);
996 result = true;
997 }
998 return result;
999}
1000
1001/** Counts the number of triangle pairs that contain the given polygon.
1002 * \param *P polygon with endpoints to look for
1003 * \param *T set of triangles to create pairs from containing \a *P
1004 */
1005int CountTrianglePairContainingPolygon(const BoundaryPolygonSet * const P, const TriangleSet * const T)
1006{
1007 Info FunctionInfo(__func__);
1008 // check number of endpoints in *P
1009 if (P->endpoints.size() != 4) {
1010 DoeLog(1) && (eLog()<< Verbose(1) << "CountTrianglePairContainingPolygon works only on polygons with 4 nodes!" << endl);
1011 return 0;
1012 }
1013
1014 // check number of triangles in *T
1015 if (T->size() < 2) {
1016 DoeLog(1) && (eLog()<< Verbose(1) << "Not enough triangles to have pairs!" << endl);
1017 return 0;
1018 }
1019
1020 DoLog(0) && (Log() << Verbose(0) << "Polygon is " << *P << endl);
1021 // create each pair, get the endpoints and check whether *P is contained.
1022 int counter = 0;
1023 PointSet Trianglenodes;
1024 class BoundaryPolygonSet PairTrianglenodes;
1025 for(TriangleSet::iterator Walker = T->begin(); Walker != T->end(); Walker++) {
1026 for (int i=0;i<3;i++)
1027 Trianglenodes.insert((*Walker)->endpoints[i]);
1028
1029 for(TriangleSet::iterator PairWalker = Walker; PairWalker != T->end(); PairWalker++) {
1030 if (Walker != PairWalker) { // skip first
1031 PairTrianglenodes.endpoints = Trianglenodes;
1032 for (int i=0;i<3;i++)
1033 PairTrianglenodes.endpoints.insert((*PairWalker)->endpoints[i]);
1034 const int size = PairTrianglenodes.endpoints.size();
1035 if (size == 4) {
1036 DoLog(0) && (Log() << Verbose(0) << " Current pair of triangles: " << **Walker << "," << **PairWalker << " with " << size << " distinct endpoints:" << PairTrianglenodes << endl);
1037 // now check
1038 if (PairTrianglenodes.ContainsPresentTupel(P)) {
1039 counter++;
1040 DoLog(0) && (Log() << Verbose(0) << " ACCEPT: Matches with " << *P << endl);
1041 } else {
1042 DoLog(0) && (Log() << Verbose(0) << " REJECT: No match with " << *P << endl);
1043 }
1044 } else {
1045 DoLog(0) && (Log() << Verbose(0) << " REJECT: Less than four endpoints." << endl);
1046 }
1047 }
1048 }
1049 Trianglenodes.clear();
1050 }
1051 return counter;
1052};
1053
1054/** Checks whether two give polygons have two or more points in common.
1055 * \param *P1 first polygon
1056 * \param *P2 second polygon
1057 * \return true - are connected, false = are note
1058 */
1059bool ArePolygonsEdgeConnected(const BoundaryPolygonSet * const P1, const BoundaryPolygonSet * const P2)
1060{
1061 Info FunctionInfo(__func__);
1062 int counter = 0;
1063 for(PointSet::const_iterator Runner = P1->endpoints.begin(); Runner != P1->endpoints.end(); Runner++) {
1064 if (P2->ContainsBoundaryPoint((*Runner))) {
1065 counter++;
1066 DoLog(1) && (Log() << Verbose(1) << *(*Runner) << " of second polygon is found in the first one." << endl);
1067 return true;
1068 }
1069 }
1070 return false;
1071};
1072
1073/** Combines second into the first and deletes the second.
1074 * \param *P1 first polygon, contains all nodes on return
1075 * \param *&P2 second polygon, is deleted.
1076 */
1077void CombinePolygons(BoundaryPolygonSet * const P1, BoundaryPolygonSet * &P2)
1078{
1079 Info FunctionInfo(__func__);
1080 pair <PointSet::iterator, bool> Tester;
1081 for(PointSet::iterator Runner = P2->endpoints.begin(); Runner != P2->endpoints.end(); Runner++) {
1082 Tester = P1->endpoints.insert((*Runner));
1083 if (Tester.second)
1084 DoLog(0) && (Log() << Verbose(0) << "Inserting endpoint " << *(*Runner) << " into first polygon." << endl);
1085 }
1086 P2->endpoints.clear();
1087 delete(P2);
1088};
1089
Note: See TracBrowser for help on using the repository browser.