source: src/BoundaryTriangleSet.cpp@ a700c4

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 a700c4 was 06aedc, checked in by Frederik Heber <heber@…>, 14 years ago

libMolecuilderLinearAlgebra is now a self-contained library fit for external use.

  • Property mode set to 100644
File size: 17.4 KB
Line 
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
8/*
9 * BoundaryTriangleSet.cpp
10 *
11 * Created on: Jul 29, 2010
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "CodePatterns/MemDebug.hpp"
21
22#include "BoundaryTriangleSet.hpp"
23
24#include <iostream>
25
26#include "BoundaryLineSet.hpp"
27#include "BoundaryPointSet.hpp"
28#include "TesselPoint.hpp"
29
30#include "Helpers/defs.hpp"
31
32#include "CodePatterns/Assert.hpp"
33#include "CodePatterns/Info.hpp"
34#include "CodePatterns/Log.hpp"
35#include "CodePatterns/Verbose.hpp"
36#include "LinearAlgebra/Line.hpp"
37#include "LinearAlgebra/Plane.hpp"
38#include "LinearAlgebra/Vector.hpp"
39
40using namespace std;
41
42/** Constructor for BoundaryTriangleSet.
43 */
44BoundaryTriangleSet::BoundaryTriangleSet() :
45 Nr(-1)
46{
47 Info FunctionInfo(__func__);
48 for (int i = 0; i < 3; i++) {
49 endpoints[i] = NULL;
50 lines[i] = NULL;
51 }
52}
53;
54
55/** Constructor for BoundaryTriangleSet with three lines.
56 * \param *line[3] lines that make up the triangle
57 * \param number number of triangle
58 */
59BoundaryTriangleSet::BoundaryTriangleSet(class BoundaryLineSet * const line[3], const int number) :
60 Nr(number)
61{
62 Info FunctionInfo(__func__);
63 // set number
64 // set lines
65 for (int i = 0; i < 3; i++) {
66 lines[i] = line[i];
67 lines[i]->AddTriangle(this);
68 }
69 // get ascending order of endpoints
70 PointMap OrderMap;
71 for (int i = 0; i < 3; i++) {
72 // for all three lines
73 for (int j = 0; j < 2; j++) { // for both endpoints
74 OrderMap.insert(pair<int, class BoundaryPointSet *> (line[i]->endpoints[j]->Nr, line[i]->endpoints[j]));
75 // and we don't care whether insertion fails
76 }
77 }
78 // set endpoints
79 int Counter = 0;
80 DoLog(0) && (Log() << Verbose(0) << "New triangle " << Nr << " with end points: " << endl);
81 for (PointMap::iterator runner = OrderMap.begin(); runner != OrderMap.end(); runner++) {
82 endpoints[Counter] = runner->second;
83 DoLog(0) && (Log() << Verbose(0) << " " << *endpoints[Counter] << endl);
84 Counter++;
85 }
86 ASSERT(Counter >= 3,"We have a triangle with only two distinct endpoints!");
87};
88
89
90/** Destructor of BoundaryTriangleSet.
91 * Removes itself from each of its lines' LineMap and removes them if necessary.
92 * \note When removing triangles from a class Tesselation, use RemoveTesselationTriangle()
93 */
94BoundaryTriangleSet::~BoundaryTriangleSet()
95{
96 Info FunctionInfo(__func__);
97 for (int i = 0; i < 3; i++) {
98 if (lines[i] != NULL) {
99 if (lines[i]->triangles.erase(Nr)) {
100 //Log() << Verbose(0) << "Triangle Nr." << Nr << " erased in line " << *lines[i] << "." << endl;
101 }
102 if (lines[i]->triangles.empty()) {
103 //Log() << Verbose(0) << *lines[i] << " is no more attached to any triangle, erasing." << endl;
104 delete (lines[i]);
105 lines[i] = NULL;
106 }
107 }
108 }
109 //Log() << Verbose(0) << "Erasing triangle Nr." << Nr << " itself." << endl;
110}
111;
112
113/** Calculates the normal vector for this triangle.
114 * Is made unique by comparison with \a OtherVector to point in the other direction.
115 * \param &OtherVector direction vector to make normal vector unique.
116 */
117void BoundaryTriangleSet::GetNormalVector(const Vector &OtherVector)
118{
119 Info FunctionInfo(__func__);
120 // get normal vector
121 NormalVector = Plane((endpoints[0]->node->getPosition()),
122 (endpoints[1]->node->getPosition()),
123 (endpoints[2]->node->getPosition())).getNormal();
124
125 // make it always point inward (any offset vector onto plane projected onto normal vector suffices)
126 if (NormalVector.ScalarProduct(OtherVector) > 0.)
127 NormalVector.Scale(-1.);
128 DoLog(1) && (Log() << Verbose(1) << "Normal Vector is " << NormalVector << "." << endl);
129}
130;
131
132/** Finds the point on the triangle \a *BTS through which the line defined by \a *MolCenter and \a *x crosses.
133 * We call Vector::GetIntersectionWithPlane() to receive the intersection point with the plane
134 * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
135 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
136 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
137 * the first two basepoints) or not.
138 * \param *out output stream for debugging
139 * \param &MolCenter offset vector of line
140 * \param &x second endpoint of line, minus \a *MolCenter is directional vector of line
141 * \param &Intersection intersection on plane on return
142 * \return true - \a *Intersection contains intersection on plane defined by triangle, false - zero vector if outside of triangle.
143 */
144
145bool BoundaryTriangleSet::GetIntersectionInsideTriangle(const Vector & MolCenter, const Vector & x, Vector &Intersection) const
146{
147 Info FunctionInfo(__func__);
148 Vector CrossPoint;
149 Vector helper;
150
151 try {
152 Line centerLine = makeLineThrough(MolCenter, x);
153 Intersection = Plane(NormalVector, (endpoints[0]->node->getPosition())).GetIntersection(centerLine);
154
155 DoLog(1) && (Log() << Verbose(1) << "INFO: Triangle is " << *this << "." << endl);
156 DoLog(1) && (Log() << Verbose(1) << "INFO: Line is from " << MolCenter << " to " << x << "." << endl);
157 DoLog(1) && (Log() << Verbose(1) << "INFO: Intersection is " << Intersection << "." << endl);
158
159 if (Intersection.DistanceSquared(endpoints[0]->node->getPosition()) < MYEPSILON) {
160 DoLog(1) && (Log() << Verbose(1) << "Intersection coindices with first endpoint." << endl);
161 return true;
162 } else if (Intersection.DistanceSquared(endpoints[1]->node->getPosition()) < MYEPSILON) {
163 DoLog(1) && (Log() << Verbose(1) << "Intersection coindices with second endpoint." << endl);
164 return true;
165 } else if (Intersection.DistanceSquared(endpoints[2]->node->getPosition()) < MYEPSILON) {
166 DoLog(1) && (Log() << Verbose(1) << "Intersection coindices with third endpoint." << endl);
167 return true;
168 }
169 // Calculate cross point between one baseline and the line from the third endpoint to intersection
170 int i = 0;
171 do {
172 Line line1 = makeLineThrough((endpoints[i%3]->node->getPosition()),(endpoints[(i+1)%3]->node->getPosition()));
173 Line line2 = makeLineThrough((endpoints[(i+2)%3]->node->getPosition()),Intersection);
174 CrossPoint = line1.getIntersection(line2);
175 helper = (endpoints[(i+1)%3]->node->getPosition()) - (endpoints[i%3]->node->getPosition());
176 CrossPoint -= (endpoints[i%3]->node->getPosition()); // cross point was returned as absolute vector
177 const double s = CrossPoint.ScalarProduct(helper)/helper.NormSquared();
178 DoLog(1) && (Log() << Verbose(1) << "INFO: Factor s is " << s << "." << endl);
179 if ((s < -MYEPSILON) || ((s-1.) > MYEPSILON)) {
180 DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << "outside of triangle." << endl);
181 return false;
182 }
183 i++;
184 } while (i < 3);
185 DoLog(1) && (Log() << Verbose(1) << "INFO: Crosspoint " << CrossPoint << " inside of triangle." << endl);
186 return true;
187 }
188 catch (MathException &excp) {
189 Log() << Verbose(1) << excp;
190 DoeLog(1) && (eLog() << Verbose(1) << "Alas! Intersection with plane failed - at least numerically - the intersection is not on the plane!" << endl);
191 return false;
192 }
193}
194;
195
196/** Finds the point on the triangle to the point \a *x.
197 * We call Vector::GetIntersectionWithPlane() with \a * and the center of the triangle to receive an intersection point.
198 * Then we check the in-plane part (the part projected down onto plane). We check whether it crosses one of the
199 * boundary lines. If it does, we return this intersection as closest point, otherwise the projected point down.
200 * Thus we test if it's really on the plane and whether it's inside the triangle on the plane or not.
201 * The latter is done as follows: We calculate the cross point of one of the triangle's baseline with the line
202 * given by the intersection and the third basepoint. Then, we check whether it's on the baseline (i.e. between
203 * the first two basepoints) or not.
204 * \param *x point
205 * \param *ClosestPoint desired closest point inside triangle to \a *x, is absolute vector
206 * \return Distance squared between \a *x and closest point inside triangle
207 */
208double BoundaryTriangleSet::GetClosestPointInsideTriangle(const Vector &x, Vector &ClosestPoint) const
209{
210 Info FunctionInfo(__func__);
211 Vector Direction;
212
213 // 1. get intersection with plane
214 DoLog(1) && (Log() << Verbose(1) << "INFO: Looking for closest point of triangle " << *this << " to " << x << "." << endl);
215 GetCenter(Direction);
216 try {
217 Line l = makeLineThrough(x, Direction);
218 ClosestPoint = Plane(NormalVector, (endpoints[0]->node->getPosition())).GetIntersection(l);
219 }
220 catch (MathException &excp) {
221 (ClosestPoint) = (x);
222 }
223
224 // 2. Calculate in plane part of line (x, intersection)
225 Vector InPlane = (x) - (ClosestPoint); // points from plane intersection to straight-down point
226 InPlane.ProjectOntoPlane(NormalVector);
227 InPlane += ClosestPoint;
228
229 DoLog(2) && (Log() << Verbose(2) << "INFO: Triangle is " << *this << "." << endl);
230 DoLog(2) && (Log() << Verbose(2) << "INFO: Line is from " << Direction << " to " << x << "." << endl);
231 DoLog(2) && (Log() << Verbose(2) << "INFO: In-plane part is " << InPlane << "." << endl);
232
233 // Calculate cross point between one baseline and the desired point such that distance is shortest
234 double ShortestDistance = -1.;
235 bool InsideFlag = false;
236 Vector CrossDirection[3];
237 Vector CrossPoint[3];
238 Vector helper;
239 for (int i = 0; i < 3; i++) {
240 // treat direction of line as normal of a (cut)plane and the desired point x as the plane offset, the intersect line with point
241 Direction = (endpoints[(i+1)%3]->node->getPosition()) - (endpoints[i%3]->node->getPosition());
242 // calculate intersection, line can never be parallel to Direction (is the same vector as PlaneNormal);
243 Line l = makeLineThrough((endpoints[i%3]->node->getPosition()), (endpoints[(i+1)%3]->node->getPosition()));
244 CrossPoint[i] = Plane(Direction, InPlane).GetIntersection(l);
245 CrossDirection[i] = CrossPoint[i] - InPlane;
246 CrossPoint[i] -= (endpoints[i%3]->node->getPosition()); // cross point was returned as absolute vector
247 const double s = CrossPoint[i].ScalarProduct(Direction)/Direction.NormSquared();
248 DoLog(2) && (Log() << Verbose(2) << "INFO: Factor s is " << s << "." << endl);
249 if ((s >= -MYEPSILON) && ((s-1.) <= MYEPSILON)) {
250 CrossPoint[i] += (endpoints[i%3]->node->getPosition()); // make cross point absolute again
251 DoLog(2) && (Log() << Verbose(2) << "INFO: Crosspoint is " << CrossPoint[i] << ", intersecting BoundaryLine between " << endpoints[i % 3]->node->getPosition() << " and " << endpoints[(i + 1) % 3]->node->getPosition() << "." << endl);
252 const double distance = CrossPoint[i].DistanceSquared(x);
253 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
254 ShortestDistance = distance;
255 (ClosestPoint) = CrossPoint[i];
256 }
257 } else
258 CrossPoint[i].Zero();
259 }
260 InsideFlag = true;
261 for (int i = 0; i < 3; i++) {
262 const double sign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 1) % 3]);
263 const double othersign = CrossDirection[i].ScalarProduct(CrossDirection[(i + 2) % 3]);
264
265 if ((sign > -MYEPSILON) && (othersign > -MYEPSILON)) // have different sign
266 InsideFlag = false;
267 }
268 if (InsideFlag) {
269 (ClosestPoint) = InPlane;
270 ShortestDistance = InPlane.DistanceSquared(x);
271 } else { // also check endnodes
272 for (int i = 0; i < 3; i++) {
273 const double distance = x.DistanceSquared(endpoints[i]->node->getPosition());
274 if ((ShortestDistance < 0.) || (ShortestDistance > distance)) {
275 ShortestDistance = distance;
276 (ClosestPoint) = (endpoints[i]->node->getPosition());
277 }
278 }
279 }
280 DoLog(1) && (Log() << Verbose(1) << "INFO: Closest Point is " << ClosestPoint << " with shortest squared distance is " << ShortestDistance << "." << endl);
281 return ShortestDistance;
282}
283;
284
285/** Checks whether lines is any of the three boundary lines this triangle contains.
286 * \param *line line to test
287 * \return true - line is of the triangle, false - is not
288 */
289bool BoundaryTriangleSet::ContainsBoundaryLine(const BoundaryLineSet * const line) const
290{
291 Info FunctionInfo(__func__);
292 for (int i = 0; i < 3; i++)
293 if (line == lines[i])
294 return true;
295 return false;
296}
297;
298
299/** Checks whether point is any of the three endpoints this triangle contains.
300 * \param *point point to test
301 * \return true - point is of the triangle, false - is not
302 */
303bool BoundaryTriangleSet::ContainsBoundaryPoint(const BoundaryPointSet * const point) const
304{
305 Info FunctionInfo(__func__);
306 for (int i = 0; i < 3; i++)
307 if (point == endpoints[i])
308 return true;
309 return false;
310}
311;
312
313/** Checks whether point is any of the three endpoints this triangle contains.
314 * \param *point TesselPoint to test
315 * \return true - point is of the triangle, false - is not
316 */
317bool BoundaryTriangleSet::ContainsBoundaryPoint(const TesselPoint * const point) const
318{
319 Info FunctionInfo(__func__);
320 for (int i = 0; i < 3; i++)
321 if (point == endpoints[i]->node)
322 return true;
323 return false;
324}
325;
326
327/** Checks whether three given \a *Points coincide with triangle's endpoints.
328 * \param *Points[3] pointer to BoundaryPointSet
329 * \return true - is the very triangle, false - is not
330 */
331bool BoundaryTriangleSet::IsPresentTupel(const BoundaryPointSet * const Points[3]) const
332{
333 Info FunctionInfo(__func__);
334 DoLog(1) && (Log() << Verbose(1) << "INFO: Checking " << Points[0] << "," << Points[1] << "," << Points[2] << " against " << endpoints[0] << "," << endpoints[1] << "," << endpoints[2] << "." << endl);
335 return (((endpoints[0] == Points[0]) || (endpoints[0] == Points[1]) || (endpoints[0] == Points[2])) && ((endpoints[1] == Points[0]) || (endpoints[1] == Points[1]) || (endpoints[1] == Points[2])) && ((endpoints[2] == Points[0]) || (endpoints[2] == Points[1]) || (endpoints[2] == Points[2])
336
337 ));
338}
339;
340
341/** Checks whether three given \a *Points coincide with triangle's endpoints.
342 * \param *Points[3] pointer to BoundaryPointSet
343 * \return true - is the very triangle, false - is not
344 */
345bool BoundaryTriangleSet::IsPresentTupel(const BoundaryTriangleSet * const T) const
346{
347 Info FunctionInfo(__func__);
348 return (((endpoints[0] == T->endpoints[0]) || (endpoints[0] == T->endpoints[1]) || (endpoints[0] == T->endpoints[2])) && ((endpoints[1] == T->endpoints[0]) || (endpoints[1] == T->endpoints[1]) || (endpoints[1] == T->endpoints[2])) && ((endpoints[2] == T->endpoints[0]) || (endpoints[2] == T->endpoints[1]) || (endpoints[2] == T->endpoints[2])
349
350 ));
351}
352;
353
354/** Returns the endpoint which is not contained in the given \a *line.
355 * \param *line baseline defining two endpoints
356 * \return pointer third endpoint or NULL if line does not belong to triangle.
357 */
358class BoundaryPointSet *BoundaryTriangleSet::GetThirdEndpoint(const BoundaryLineSet * const line) const
359{
360 Info FunctionInfo(__func__);
361 // sanity check
362 if (!ContainsBoundaryLine(line))
363 return NULL;
364 for (int i = 0; i < 3; i++)
365 if (!line->ContainsBoundaryPoint(endpoints[i]))
366 return endpoints[i];
367 // actually, that' impossible :)
368 return NULL;
369}
370;
371
372/** Returns the baseline which does not contain the given boundary point \a *point.
373 * \param *point endpoint which is neither endpoint of the desired line
374 * \return pointer to desired third baseline
375 */
376class BoundaryLineSet *BoundaryTriangleSet::GetThirdLine(const BoundaryPointSet * const point) const
377{
378 Info FunctionInfo(__func__);
379 // sanity check
380 if (!ContainsBoundaryPoint(point))
381 return NULL;
382 for (int i = 0; i < 3; i++)
383 if (!lines[i]->ContainsBoundaryPoint(point))
384 return lines[i];
385 // actually, that' impossible :)
386 return NULL;
387}
388;
389
390/** Calculates the center point of the triangle.
391 * Is third of the sum of all endpoints.
392 * \param *center central point on return.
393 */
394void BoundaryTriangleSet::GetCenter(Vector & center) const
395{
396 Info FunctionInfo(__func__);
397 center.Zero();
398 for (int i = 0; i < 3; i++)
399 (center) += (endpoints[i]->node->getPosition());
400 center.Scale(1. / 3.);
401 DoLog(1) && (Log() << Verbose(1) << "INFO: Center is at " << center << "." << endl);
402}
403
404/**
405 * gets the Plane defined by the three triangle Basepoints
406 */
407Plane BoundaryTriangleSet::getPlane() const{
408 ASSERT(endpoints[0] && endpoints[1] && endpoints[2], "Triangle not fully defined");
409
410 return Plane(endpoints[0]->node->getPosition(),
411 endpoints[1]->node->getPosition(),
412 endpoints[2]->node->getPosition());
413}
414
415Vector BoundaryTriangleSet::getEndpoint(int i) const{
416 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
417
418 return endpoints[i]->node->getPosition();
419}
420
421string BoundaryTriangleSet::getEndpointName(int i) const{
422 ASSERT(i>=0 && i<3,"Index of Endpoint out of Range");
423
424 return endpoints[i]->node->getName();
425}
426
427/** output operator for BoundaryTriangleSet.
428 * \param &ost output stream
429 * \param &a boundary triangle
430 */
431ostream &operator <<(ostream &ost, const BoundaryTriangleSet &a)
432{
433 ost << "[" << a.Nr << "|" << a.getEndpointName(0) << "," << a.getEndpointName(1) << "," << a.getEndpointName(2) << "]";
434 // ost << "[" << a.Nr << "|" << a.endpoints[0]->node->Name << " at " << *a.endpoints[0]->node->node << ","
435 // << a.endpoints[1]->node->Name << " at " << *a.endpoints[1]->node->node << "," << a.endpoints[2]->node->Name << " at " << *a.endpoints[2]->node->node << "]";
436 return ost;
437}
438;
439
Note: See TracBrowser for help on using the repository browser.