Debian Codegraph @

vcg/vcg/space/intersection3.h

raw symbols SCIP
1 /****************************************************************************
2 * VCGLib o o *
3 * Visual and Computer Graphics Library o o *
4 * _ O _ *
5 * Copyright(C) 2004 \/)\/ *
6 * Visual Computing Lab /\/| *
7 * ISTI - Italian National Research Council | *
8 * \ *
9 * All rights reserved. *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
20 * for more details. *
21 * *
22 ****************************************************************************/
23 /****************************************************************************
24 History
25
26 $Log: intersection3.h,v $
27 Revision 1.34 2007/06/08 07:40:40 fiorin
28 Corrected error in the comment to method IntersectionSphereTriangle
29
30 Revision 1.33 2007/06/07 15:16:39 fiorin
31 Added IntersectionSphereTriangle
32
33 Revision 1.32 2007/05/29 14:33:29 fiorin
34 Added IntersectionSegmentSphere
35
36 Revision 1.31 2007/04/16 09:08:15 cignoni
37 commented out non compiling intersectionSpherePlane
38
39 Revision 1.30 2007/04/10 22:26:47 pietroni
40 IntersectionPlanePlane first parameter is a const
41
42 Revision 1.29 2007/04/04 23:19:40 pietroni
43 - Changed name of intersection function between plane and triangle from Intersection to IntersectionPlaneTriangle.
44 - Added Intersection_Plane_Sphere function.
45
46 Revision 1.28 2007/02/21 02:40:52 m_di_benedetto
47 Added const qualifier to bbox parameter in Intersection_Triangle_Box().
48
49 Revision 1.27 2006/10/25 16:04:32 pietroni
50 added intersection control between bounding boxes for intersection between segment and triangle function
51
52 Revision 1.26 2006/09/14 08:39:07 ganovelli
53 Intersection_sphere_sphere added
54
55 Revision 1.25 2006/06/06 14:35:31 zifnab1974
56 Changes for compilation on linux AMD64. Some remarks: Linux filenames are case-sensitive. _fileno and _filelength do not exist on linux
57
58 Revision 1.24 2006/06/01 08:38:02 pietroni
59 Added functions:
60
61 - Intersection_Segment_Triangle
62 - Intersection_Plane_Box
63 - Intersection_Triangle_Box
64
65 Revision 1.23 2006/03/29 07:53:36 cignoni
66 Missing ';' (thx Maarten)
67
68 Revision 1.22 2006/03/20 14:42:49 pietroni
69 IntersectionSegmentPlane and Intersection_Segment_Box functions Added
70
71 Revision 1.21 2006/01/20 16:35:51 pietroni
72 added Intersection_Segment_Box function
73
74 Revision 1.20 2005/10/03 16:07:50 ponchio
75 Changed order of functions intersection_line_box and
76 intersectuion_ray_box
77
78 Revision 1.19 2005/09/30 13:11:39 pietroni
79 corrected 1 compiling error on Ray_Box_Intersection function
80
81 Revision 1.18 2005/09/29 15:30:10 pietroni
82 Added function RayBoxIntersection, renamed intersection line box from "Intersection" to "Intersection_Line_Box"
83
84 Revision 1.17 2005/09/29 11:48:00 m_di_benedetto
85 Added functor RayTriangleIntersectionFunctor.
86
87 Revision 1.16 2005/09/28 19:40:55 m_di_benedetto
88 Added intersection for ray-triangle (with Ray3 type).
89
90 Revision 1.15 2005/06/29 15:28:31 callieri
91 changed intersection names to more specific to avoid ambiguity
92
93 Revision 1.14 2005/03/15 11:22:39 ganovelli
94 added intersection between tow planes (porting from old vcg lib)
95
96 Revision 1.13 2005/01/26 10:03:08 spinelli
97 aggiunta intersect ray-box
98
99 Revision 1.12 2004/10/13 12:45:51 cignoni
100 Better Doxygen documentation
101
102 Revision 1.11 2004/09/09 14:41:32 ponchio
103 forgotten typename SEGMENTTYPE::...
104
105 Revision 1.10 2004/08/09 09:48:43 pietroni
106 correcter .dir to .Direction and .ori in .Origin()
107
108 Revision 1.9 2004/08/04 20:55:02 pietroni
109 added rey triangle intersections funtions
110
111 Revision 1.8 2004/07/11 22:08:04 cignoni
112 Added a cast to remove a warning
113
114 Revision 1.7 2004/05/14 03:14:29 ponchio
115 Fixed some minor bugs
116
117 Revision 1.6 2004/05/13 23:43:54 ponchio
118 minor bug
119
120 Revision 1.5 2004/05/05 08:21:55 cignoni
121 syntax errors in inersection plane line.
122
123 Revision 1.4 2004/05/04 02:37:58 ganovelli
124 Triangle3<T> replaced by TRIANGLE
125 Segment<T> replaced by EDGETYPE
126
127 Revision 1.3 2004/04/29 10:48:44 ganovelli
128 error in plane segment corrected
129
130 Revision 1.2 2004/04/26 12:34:50 ganovelli
131 plane line
132 plane segment
133 triangle triangle added
134
135 Revision 1.1 2004/04/21 14:22:27 cignoni
136 Initial Commit
137
138
139 ****************************************************************************/
140
141
142
143 #ifndef __VCGLIB_INTERSECTION_3
144 #define __VCGLIB_INTERSECTION_3
145
146 #include <vcg/math/base.h>
147 #include <vcg/space/point3.h>
148 #include <vcg/space/line3.h>
149 #include <vcg/space/ray3.h>
150 #include <vcg/space/plane3.h>
151 #include <vcg/space/segment3.h>
152 #include <vcg/space/sphere3.h>
153 #include <vcg/space/triangle3.h>
154 #include <vcg/space/intersection/triangle_triangle3.h>
155
156
157
158
159 namespace vcg {
160 /** \addtogroup space */
161 /*@{*/
162 /**
163 Function computing the intersection between couple of geometric primitives in
164 3 dimension
165 */
166 /// interseciton between sphere and line
167 template<class T>
168 inline bool IntersectionLineSphere( const Sphere3<T> & sp, const Line3<T> & li, Point3<T> & p0,Point3<T> & p1 ){
169
170 // Per prima cosa si sposta il sistema di riferimento
171 // fino a portare il centro della sfera nell'origine
172 Point3<T> neworig=li.Origin()-sp.Center();
173 // poi si risolve il sistema di secondo grado (con maple...)
174 T t1 = li.Direction().X()*li.Direction().X();
175 T t2 = li.Direction().Y()*li.Direction().Y();
176 T t3 = li.Direction().Z()*li.Direction().Z();
177 T t6 = neworig.Y()*li.Direction().Y();
178 T t7 = neworig.X()*li.Direction().X();
179 T t8 = neworig.Z()*li.Direction().Z();
180 T t15 = sp.Radius()*sp.Radius();
181 T t17 = neworig.Z()*neworig.Z();
182 T t19 = neworig.Y()*neworig.Y();
183 T t21 = neworig.X()*neworig.X();
184 T t28 = T(2.0*t7*t6+2.0*t6*t8+2.0*t7*t8+t1*t15-t1*t17-t1*t19-t2*t21+t2*t15-t2*t17-t3*t21+t3*t15-t3*t19);
185 if(t28<0) return false;
186 T t29 = sqrt(t28);
187 T val0 = 1/(t1+t2+t3)*(-t6-t7-t8+t29);
188 T val1 = 1/(t1+t2+t3)*(-t6-t7-t8-t29);
189
190 p0=li.P(val0);
191 p1=li.P(val1);
192 return true;
193 }
194
195 /*
196 * Function computing the intersection between a sphere and a segment.
197 * @param[in] sphere the sphere
198 * @param[in] segment the segment
199 * @param[out] intersection the intersection point, meaningful only if the segment intersects the sphere
200 * \return (0, 1 or 2) the number of intersections between the segment and the sphere.
201 * t1 is a valid intersection only if the returned value is at least 1;
202 * similarly t2 is valid iff the returned value is 2.
203 */
204 template < class SCALAR_TYPE >
205 inline int IntersectionSegmentSphere(const Sphere3<SCALAR_TYPE>& sphere, const Segment3<SCALAR_TYPE>& segment, Point3<SCALAR_TYPE> & t0, Point3<SCALAR_TYPE> & t1)
206 {
207 typedef SCALAR_TYPE ScalarType;
208 typedef typename vcg::Point3< ScalarType > Point3t;
209
210 Point3t s = segment.P0() - sphere.Center();
211 Point3t r = segment.P1() - segment.P0();
212
213 ScalarType rho2 = sphere.Radius()*sphere.Radius();
214
215 ScalarType sr = s*r;
216 ScalarType r_squared_norm = r.SquaredNorm();
217 ScalarType s_squared_norm = s.SquaredNorm();
218 ScalarType sigma = sr*sr - r_squared_norm*(s_squared_norm-rho2);
219
220 if (sigma<ScalarType(0.0)) // the line containing the edge doesn't intersect the sphere
221 return 0;
222
223 ScalarType sqrt_sigma = ScalarType(sqrt( ScalarType(sigma) ));
224 ScalarType lambda1 = (-sr - sqrt_sigma)/r_squared_norm;
225 ScalarType lambda2 = (-sr + sqrt_sigma)/r_squared_norm;
226
227 int solution_count = 0;
228 if (ScalarType(0.0)<=lambda1 && lambda1<=ScalarType(1.0))
229 {
230 ScalarType t_enter = vcg::math::Max< ScalarType >(lambda1, ScalarType(0.0));
231 t0 = segment.P0() + r*t_enter;
232 solution_count++;
233 }
234
235 if (ScalarType(0.0)<=lambda2 && lambda2<=ScalarType(1.0))
236 {
237 Point3t *pt = (solution_count>0) ? &t1 : &t0;
238 ScalarType t_exit = vcg::math::Min< ScalarType >(lambda2, ScalarType(1.0));
239 *pt = segment.P0() + r*t_exit;
240 solution_count++;
241 }
242 return solution_count;
243 }; // end of IntersectionSegmentSphere
244
245
246 /*!
247 * Compute the intersection between a sphere and a triangle.
248 * \param[in] sphere the input sphere
249 * \param[in] triangle the input triangle
250 * \param[out] witness it is the point on the triangle nearest to the center of the sphere (even when there isn't intersection)
251 * \param[out] res if not null, in the first item is stored the minimum distance between the triangle and the sphere,
252 * while in the second item is stored the penetration depth
253 * \return true iff there is an intersection between the sphere and the triangle
254 */
255 template < class SCALAR_TYPE >
256 bool IntersectionSphereTriangle(const vcg::Sphere3 < SCALAR_TYPE > & sphere ,
257 const vcg::Triangle3< SCALAR_TYPE > & triangle,
258 vcg::Point3 < SCALAR_TYPE > & witness ,
259 std::pair< SCALAR_TYPE, SCALAR_TYPE > * res=NULL)
260 {
261 typedef SCALAR_TYPE ScalarType;
262 typedef typename vcg::Point3< ScalarType > Point3t;
263 typedef typename vcg::Triangle3< ScalarType > Triangle3t;
264
265 bool penetration_detected = false;
266
267 ScalarType radius = sphere.Radius();
268 Point3t center = sphere.Center();
269 Point3t p0 = triangle.P(0)-center;
270 Point3t p1 = triangle.P(1)-center;
271 Point3t p2 = triangle.P(2)-center;
272
273 Point3t p10 = p1-p0;
274 Point3t p21 = p2-p1;
275 Point3t p20 = p2-p0;
276
277 ScalarType delta0_p01 = p10*p1;
278 ScalarType delta1_p01 = -p10*p0;
279 ScalarType delta0_p02 = p20*p2;
280 ScalarType delta2_p02 = -p20*p0;
281 ScalarType delta1_p12 = p21*p2;
282 ScalarType delta2_p12 = -p21*p1;
283
284 // the closest point can be one of the vertices of the triangle
285 if (delta1_p01<=ScalarType(0.0) && delta2_p02<=ScalarType(0.0)) { witness = p0; }
286 else if (delta0_p01<=ScalarType(0.0) && delta2_p12<=ScalarType(0.0)) { witness = p1; }
287 else if (delta0_p02<=ScalarType(0.0) && delta1_p12<=ScalarType(0.0)) { witness = p2; }
288 else
289 {
290 ScalarType temp = p10*p2;
291 ScalarType delta0_p012 = delta0_p01*delta1_p12 + delta2_p12*temp;
292 ScalarType delta1_p012 = delta1_p01*delta0_p02 - delta2_p02*temp;
293 ScalarType delta2_p012 = delta2_p02*delta0_p01 - delta1_p01*(p20*p1);
294
295 // otherwise, can be a point lying on same edge of the triangle
296 if (delta0_p012<=ScalarType(0.0))
297 {
298 ScalarType denominator = delta1_p12+delta2_p12;
299 ScalarType mu1 = delta1_p12/denominator;
300 ScalarType mu2 = delta2_p12/denominator;
301 witness = (p1*mu1 + p2*mu2);
302 }
303 else if (delta1_p012<=ScalarType(0.0))
304 {
305 ScalarType denominator = delta0_p02+delta2_p02;
306 ScalarType mu0 = delta0_p02/denominator;
307 ScalarType mu2 = delta2_p02/denominator;
308 witness = (p0*mu0 + p2*mu2);
309 }
310 else if (delta2_p012<=ScalarType(0.0))
311 {
312 ScalarType denominator = delta0_p01+delta1_p01;
313 ScalarType mu0 = delta0_p01/denominator;
314 ScalarType mu1 = delta1_p01/denominator;
315 witness = (p0*mu0 + p1*mu1);
316 }
317 else
318 {
319 // or else can be an point internal to the triangle
320 ScalarType denominator = delta0_p012 + delta1_p012 + delta2_p012;
321 ScalarType lambda0 = delta0_p012/denominator;
322 ScalarType lambda1 = delta1_p012/denominator;
323 ScalarType lambda2 = delta2_p012/denominator;
324 witness = p0*lambda0 + p1*lambda1 + p2*lambda2;
325 }
326 }
327
328 if (res!=NULL)
329 {
330 ScalarType witness_norm = witness.Norm();
331 res->first = vcg::math::Max< ScalarType >( witness_norm-radius, ScalarType(0.0) );
332 res->second = vcg::math::Max< ScalarType >( radius-witness_norm, ScalarType(0.0) );
333 }
334 penetration_detected = (witness.SquaredNorm() <= (radius*radius));
335 witness += center;
336 return penetration_detected;
337 }; //end of IntersectionSphereTriangle
338
339
340 /// intersection between line and plane
341 template<class T>
342 inline bool IntersectionLinePlane( const Plane3<T> & pl, const Line3<T> & li, Point3<T> & po){
343 const T epsilon = T(1e-8);
344
345 T k = pl.Direction() * li.Direction(); // Compute 'k' factor
346 if( (k > -epsilon) && (k < epsilon))
347 return false;
348 T r = (pl.Offset() - pl.Direction()*li.Origin())/k; // Compute ray distance
349 po = li.Origin() + li.Direction()*r;
350 return true;
351 }
352
353 /// intersection between segment and plane
354 template<class T>
355 inline bool IntersectionSegmentPlane( const Plane3<T> & pl, const Segment3<T> & s, Point3<T> & po){
356 vcg::Line3<T> l;
357 l.Set(s.P0(),s.P1()-s.P0());
358 l.Normalize();
359 if (IntersectionLinePlane(pl,l,po))
360 return((po-s.P0()).Norm()<=(s.P0()-s.P1()).Norm());
361 return false;
362 }
363
364 /// intersection between segment and plane
365 template<typename SEGMENTTYPE>
366 inline bool Intersection( const Plane3<typename SEGMENTTYPE::ScalarType> & pl,
367 const SEGMENTTYPE & sg,
368 Point3<typename SEGMENTTYPE::ScalarType> & po){
369 typedef typename SEGMENTTYPE::ScalarType T;
370 const T epsilon = T(1e-8);
371
372 T k = pl.Direction() * (sg.P1()-sg.P0());
373 if( (k > -epsilon) && (k < epsilon))
374 return false;
375 T r = (pl.Offset() - pl.Direction()*sg.P0())/k; // Compute ray distance
376 if( (r<0) || (r > 1.0))
377 return false;
378 po = sg.P0()*(1-r)+sg.P1() * r;
379 return true;
380 }
381
382 /// intersection between plane and triangle
383 // not optimal: uses plane-segment intersection (and the fact the two or none edges can be intersected)
384 template<typename TRIANGLETYPE>
385 inline bool IntersectionPlaneTriangle( const Plane3<typename TRIANGLETYPE::ScalarType> & pl,
386 const TRIANGLETYPE & tr,
387 Segment3<typename TRIANGLETYPE::ScalarType> & sg){
388 typedef typename TRIANGLETYPE::ScalarType T;
389 if(Intersection(pl,Segment3<T>(tr.P(0),tr.P(1)),sg.P0())){
390 if(Intersection(pl,Segment3<T>(tr.P(0),tr.P(2)),sg.P1()))
391 return true;
392 else
393 {
394 Intersection(pl,Segment3<T>(tr.P(1),tr.P(2)),sg.P1());
395 return true;
396 }
397 }else
398 {
399 if(Intersection(pl,Segment3<T>(tr.P(1),tr.P(2)),sg.P0()))
400 {
401 Intersection(pl,Segment3<T>(tr.P(0),tr.P(2)),sg.P1());
402 return true;
403 }
404 }
405 return false;
406 }
407
408 /// intersection between two triangles
409 template<typename TRIANGLETYPE>
410 inline bool Intersection(const TRIANGLETYPE & t0,const TRIANGLETYPE & t1){
411 return NoDivTriTriIsect(t0.P0(0),t0.P0(1),t0.P0(2),
412 t1.P0(0),t1.P0(1),t1.P0(2));
413 }
414 template<class T>
415 inline bool Intersection(Point3<T> V0,Point3<T> V1,Point3<T> V2,
416 Point3<T> U0,Point3<T> U1,Point3<T> U2){
417 return NoDivTriTriIsect(V0,V1,V2,U0,U1,U2);
418 }
419
420 template<class T>
421 inline bool Intersection(Point3<T> V0,Point3<T> V1,Point3<T> V2,
422 Point3<T> U0,Point3<T> U1,Point3<T> U2,int *coplanar,
423 Point3<T> &isectpt1,Point3<T> &isectpt2){
424
425 return tri_tri_intersect_with_isectline(V0,V1,V2,U0,U1,U2,
426 coplanar,isectpt1,isectpt2);
427 }
428
429 template<typename TRIANGLETYPE,typename SEGMENTTYPE >
430 inline bool Intersection(const TRIANGLETYPE & t0,const TRIANGLETYPE & t1,bool &coplanar,
431 SEGMENTTYPE & sg){
432 Point3<typename SEGMENTTYPE::PointType> ip0,ip1;
433 return tri_tri_intersect_with_isectline(t0.P0(0),t0.P0(1),t0.P0(2),
434 t1.P0(0),t1.P0(1),t1.P0(2),
435 coplanar,sg.P0(),sg.P1()
436 );
437 }
438
439
440 // ray-triangle, gives barycentric coords of intersection and distance along ray
441 template<class T>
442 bool Intersection( const Line3<T> & ray, const Point3<T> & vert0,
443 const Point3<T> & vert1, const Point3<T> & vert2,
444 T & a ,T & b, T & dist)
445 {
446 // small (hum) borders around triangle
447 const T EPSILON2= T(1e-8);
448
449 const T EPSILON = T(1e-8);
450
451 Point3<T> edge1 = vert1 - vert0;
452 Point3<T> edge2 = vert2 - vert0;
453
454 // determinant
455 Point3<T> pvec = ray.Direction() ^ edge2;
456
457 T det = edge1*pvec;
458
459 // if determinant is near zero, ray lies in plane of triangle
460 if (fabs(det) < EPSILON) return false;
461
462 // calculate distance from vert0 to ray origin
463 Point3<T> tvec = ray.Origin()- vert0;
464
465 // calculate A parameter and test bounds
466 a = tvec * pvec;
467 if (a < -EPSILON2*det || a > det+det*EPSILON2) return false;
468
469 // prepare to test V parameter
470 Point3<T> qvec = tvec ^ edge1;
471
472 // calculate B parameter and test bounds
473 b = ray.Direction() * qvec ;
474 if (b < -EPSILON2*det || b + a > det+det*EPSILON2) return false;
475
476 // calculate t, scale parameters, ray intersects triangle
477 dist = edge2 * qvec;
478 if (dist<0) return false;
479 T inv_det = T(1.0) / det;
480 dist *= inv_det;
481 a *= inv_det;
482 b *= inv_det;
483
484 return true;
485 }
486
487 // ray-triangle, gives barycentric coords of intersection and distance along ray.
488 // Ray3 type used.
489 template<class T>
490 bool Intersection( const Ray3<T> & ray, const Point3<T> & vert0,
491 const Point3<T> & vert1, const Point3<T> & vert2,
492 T & a ,T & b, T & dist)
493 {
494 // small (hum) borders around triangle
495 const T EPSILON2= T(1e-8);
496
497 const T EPSILON = T(1e-8);
498
499 Point3<T> edge1 = vert1 - vert0;
500 Point3<T> edge2 = vert2 - vert0;
501
502 // determinant
503 Point3<T> pvec = ray.Direction() ^ edge2;
504
505 T det = edge1*pvec;
506
507 // if determinant is near zero, ray lies in plane of triangle
508 if (fabs(det) < EPSILON) return false;
509
510 // calculate distance from vert0 to ray origin
511 Point3<T> tvec = ray.Origin()- vert0;
512
513 // calculate A parameter and test bounds
514 a = tvec * pvec;
515 if (a < -EPSILON2*det || a > det+det*EPSILON2) return false;
516
517 // prepare to test V parameter
518 Point3<T> qvec = tvec ^ edge1;
519
520 // calculate B parameter and test bounds
521 b = ray.Direction() * qvec ;
522 if (b < -EPSILON2*det || b + a > det+det*EPSILON2) return false;
523
524 // calculate t, scale parameters, ray intersects triangle
525 dist = edge2 * qvec;
526 if (dist<0) return false;
527 T inv_det = T(1.0) / det;
528 dist *= inv_det;
529 a *= inv_det;
530 b *= inv_det;
531
532 return true;
533 }
534
535 // ray-triangle, gives intersection 3d point and distance along ray
536 template<class T>
537 bool Intersection( const Line3<T> & ray, const Point3<T> & vert0,
538 const Point3<T> & vert1, const Point3<T> & vert2,
539 Point3<T> & inte)
540 {
541
542 // small (hum) borders around triangle
543 const T EPSILON2= T(1e-8);
544
545 const T EPSILON = T(1e-8);
546
547 Point3<T> edge1 = vert1 - vert0;
548 Point3<T> edge2 = vert2 - vert0;
549
550 // determinant
551 Point3<T> pvec = ray.Direction() ^ edge2;
552
553 T det = edge1*pvec;
554
555 // if determinant is near zero, ray lies in plane of triangle
556 if (fabs(det) < EPSILON) return false;
557
558 // calculate distance from vert0 to ray origin
559 Point3<T> tvec = ray.Origin() - vert0;
560
561 // calculate A parameter and test bounds
562 T a = tvec * pvec;
563 if (a < -EPSILON2*det || a > det+det*EPSILON2) return false;
564
565 // prepare to test V parameter
566 Point3<T> qvec = tvec ^ edge1;
567
568 // calculate B parameter and test bounds
569 T b = ray.Direction() * qvec ;
570 if (b < -EPSILON2*det || b + a > det+det*EPSILON2) return false;
571
572 // calculate t, scale parameters, ray intersects triangle
573 double dist = edge2 * qvec;
574 //if (dist<0) return false;
575 T inv_det = 1.0 / det;
576 dist *= inv_det;
577 a *= inv_det;
578 b *= inv_det;
579
580 inte = vert0 + edge1*a + edge2*b;
581 return true;
582 }
583
584 // line-box
585 template<class T>
586 bool Intersection_Line_Box( const Box3<T> & box, const Line3<T> & r, Point3<T> & coord )
587 {
588 const int NUMDIM = 3;
589 const int RIGHT = 0;
590 const int LEFT = 1;
591 const int MIDDLE = 2;
592
593 int inside = 1;
594 char quadrant[NUMDIM];
595 int i;
596 int whichPlane;
597 Point3<T> maxT,candidatePlane;
598
599 // Find candidate planes; this loop can be avoided if
600 // rays cast all from the eye(assume perpsective view)
601 for (i=0; i<NUMDIM; i++)
602 {
603 if(r.Origin()[i] < box.min[i])
604 {
605 quadrant[i] = LEFT;
606 candidatePlane[i] = box.min[i];
607 inside = 0;
608 }
609 else if (r.Origin()[i] > box.max[i])
610 {
611 quadrant[i] = RIGHT;
612 candidatePlane[i] = box.max[i];
613 inside = 0;
614 }
615 else
616 {
617 quadrant[i] = MIDDLE;
618 }
619 }
620
621 // Ray origin inside bounding box
622 if(inside){
623 coord = r.Origin();
624 return true;
625 }
626
627 // Calculate T distances to candidate planes
628 for (i = 0; i < NUMDIM; i++)
629 {
630 if (quadrant[i] != MIDDLE && r.Direction()[i] !=0.)
631 maxT[i] = (candidatePlane[i]-r.Origin()[i]) / r.Direction()[i];
632 else
633 maxT[i] = -1.;
634 }
635
636 // Get largest of the maxT's for final choice of intersection
637 whichPlane = 0;
638 for (i = 1; i < NUMDIM; i++)
639 if (maxT[whichPlane] < maxT[i])
640 whichPlane = i;
641
642 // Check final candidate actually inside box
643 if (maxT[whichPlane] < 0.) return false;
644 for (i = 0; i < NUMDIM; i++)
645 if (whichPlane != i)
646 {
647 coord[i] = r.Origin()[i] + maxT[whichPlane] *r.Direction()[i];
648 if (coord[i] < box.min[i] || coord[i] > box.max[i])
649 return false;
650 }
651 else
652 {
653 coord[i] = candidatePlane[i];
654 }
655 return true; // ray hits box
656 }
657
658 // ray-box
659 template<class T>
660 bool Intersection_Ray_Box( const Box3<T> & box, const Ray3<T> & r, Point3<T> & coord )
661 {
662 Line3<T> l;
663 l.SetOrigin(r.Origin());
664 l.SetDirection(r.Direction());
665 return(Intersection_Line_Box<T>(box,l,coord));
666 }
667
668 // segment-box return fist intersection found from p0 to p1
669 template<class ScalarType>
670 bool Intersection_Segment_Box( const Box3<ScalarType> & box,
671 const Segment3<ScalarType> & s,
672 Point3<ScalarType> & coord )
673 {
674 //as first perform box-box intersection
675 Box3<ScalarType> test;
676 test.Add(s.P0());
677 test.Add(s.P1());
678 if (!test.Collide(box))
679 return false;
680 else
681 {
682 Line3<ScalarType> l;
683 Point3<ScalarType> dir=s.P1()-s.P0();
684 dir.Normalize();
685 l.SetOrigin(s.P0());
686 l.SetDirection(dir);
687 if(Intersection_Line_Box<ScalarType>(box,l,coord))
688 return (test.IsIn(coord));
689 return false;
690 }
691 }
692
693 // segment-box intersection , return number of intersections and intersection points
694 template<class ScalarType>
695 int Intersection_Segment_Box( const Box3<ScalarType> & box,
696 const Segment3<ScalarType> & s,
697 Point3<ScalarType> & coord0,
698 Point3<ScalarType> & coord1 )
699 {
700 int num=0;
701 Segment3<ScalarType> test= s;
702 if (Intersection_Segment_Box(box,test,coord0 ))
703 {
704 num++;
705 Point3<ScalarType> swap=test.P0();
706 test.P0()=test.P1();
707 test.P1()=swap;
708 if (Intersection_Segment_Box(box,test,coord1 ))
709 num++;
710 }
711 return num;
712 }
713
714
715 // segment-triangle intersection
716 template<class ScalarType>
717 bool Intersection_Segment_Triangle( const vcg::Segment3<ScalarType> & seg,
718 const Point3<ScalarType> & vert0,
719 const Point3<ScalarType> & vert1, const
720 Point3<ScalarType> & vert2,
721 ScalarType & a ,ScalarType & b, ScalarType & dist)
722 {
723 //control intersection of bounding boxes
724 vcg::Box3<ScalarType> bb0,bb1;
725 bb0.Add(seg.P0());
726 bb0.Add(seg.P1());
727 bb1.Add(vert0);
728 bb1.Add(vert1);
729 bb1.Add(vert2);
730 Point3<ScalarType> inter;
731 if (!bb0.Collide(bb1))
732 return false;
733 if (!vcg::Intersection_Segment_Box(bb1,seg,inter))
734 return false;
735
736 //first set both directions of ray
737 vcg::Ray3<ScalarType> ray;
738 vcg::Point3<ScalarType> dir;
739 dir=(seg.P1()-seg.P0());
740 dir.Normalize();
741 ray.Set(seg.P0(),dir);
742
743 //then control for each direction the intersection with triangle
744 if ((Intersection<ScalarType>(ray,vert0,vert1,vert2,a,b,dist))
745 ||(Intersection<ScalarType>(ray,vert1,vert0,vert2,b,a,dist)))
746 return (dist<(seg.P1()-seg.P0()).Norm());
747 else
748 return(false);
749 }
750
751 template <class ScalarType>
752 bool Intersection_Plane_Box(const vcg::Plane3<ScalarType> &pl,
753 vcg::Box3<ScalarType> &bbox)
754 {
755
756 typedef typename vcg::Segment3<ScalarType> SegmentType;
757 typedef typename vcg::Point3<ScalarType> CoordType;
758 SegmentType diag[4];
759
760 CoordType intersection;
761 //find the 4 diagonals
762 diag[0]=SegmentType(bbox.P(0),bbox.P(7));
763 diag[1]=SegmentType(bbox.P(1),bbox.P(6));
764 diag[2]=SegmentType(bbox.P(2),bbox.P(5));
765 diag[3]=SegmentType(bbox.P(3),bbox.P(4));
766 ScalarType a,b,dist;
767 for (int i=0;i<3;i++)
768 //call intersection of segment and plane
769 if (vcg::Intersection<SegmentType>(pl,diag[i],intersection))
770 return true;
771 return false;
772 }
773
774 ///if exists return the center and ardius of circle
775 ///that is the intersectionk between the sphere and
776 //the plane
777 template <class ScalarType>
778 bool Intersection_Plane_Sphere(const Plane3<ScalarType> &pl,
779 const Sphere3<ScalarType> &sphere,
780 Point3<ScalarType> &center,
781 ScalarType &radius)
782 {
783 /* ///set the origin on the center of the sphere
784 vcg::Plane3<ScalarType> pl1;
785 vcg::Point3<ScalarType> p_plane=pl.Direction()*pl.Offset();
786 vcg::Point3<ScalarType> p_plane=p_plane-sphere.Center();
787
788 ///set again the plane
789 pl1.Set(p_plane,pl.Direction());
790
791 ///test d must be positive
792 d=pl1.Offset();
793 vcg::Point3<ScalarType> n=pl1.Direction();
794 ///invert d if is <0
795 if (d<0)
796 {
797 n=-n;
798 d=-d;
799 }
800 ///no intersection occour
801 if (d>r)
802 return false;
803 else
804 {
805 ///calculate center and translate in back
806 center=n*d;
807 center+=sphere.Center();
808 radius=math::Sqrt((r*r)-(d*d));
809 }
810 */
811 assert(0);
812 return true;
813 }
814
815
816 template<class ScalarType>
817 bool Intersection_Triangle_Box(const vcg::Box3<ScalarType> &bbox,
818 const vcg::Point3<ScalarType> &p0,
819 const vcg::Point3<ScalarType> &p1,
820 const vcg::Point3<ScalarType> &p2)
821 {
822 typedef typename vcg::Point3<ScalarType> CoordType;
823 CoordType intersection;
824
825 /// control bounding box collision
826 vcg::Box3<ScalarType> test;
827 test.SetNull();
828 test.Add(p0);
829 test.Add(p1);
830 test.Add(p2);
831 if (!test.Collide(bbox))
832 return false;
833 /// control if each point is inside the bouding box
834 if ((bbox.IsIn(p0))||(bbox.IsIn(p1))||(bbox.IsIn(p2)))
835 return true;
836
837 /////control plane of the triangle with bbox
838 //vcg::Plane3<ScalarType> plTri=vcg::Plane3<ScalarType>();
839 //plTri.Init(p0,p1,p2);
840 //if (!Intersection_Plane_Box<ScalarType>(plTri,bbox))
841 // return false;
842
843 ///then control intersection of segments with box
844 if (Intersection_Segment_Box<ScalarType>(bbox,vcg::Segment3<ScalarType>(p0,p1),intersection)||
845 Intersection_Segment_Box<ScalarType>(bbox,vcg::Segment3<ScalarType>(p1,p2),intersection)||
846 Intersection_Segment_Box<ScalarType>(bbox,vcg::Segment3<ScalarType>(p2,p0),intersection))
847 return true;
848 ///control intersection of diagonal of the cube with triangle
849
850 Segment3<ScalarType> diag[4];
851
852 diag[0]=Segment3<ScalarType>(bbox.P(0),bbox.P(7));
853 diag[1]=Segment3<ScalarType>(bbox.P(1),bbox.P(6));
854 diag[2]=Segment3<ScalarType>(bbox.P(2),bbox.P(5));
855 diag[3]=Segment3<ScalarType>(bbox.P(3),bbox.P(4));
856 ScalarType a,b,dist;
857 for (int i=0;i<3;i++)
858 if (Intersection_Segment_Triangle<ScalarType>(diag[i],p0,p1,p2,a,b,dist))
859 return true;
860
861 return false;
862 }
863
864 template <class SphereType>
865 bool Intersection_Sphere_Sphere( const SphereType & s0,const SphereType & s1){
866 return (s0.Center()-s1.Center()).SquaredNorm() < (s0.Radius()+s1.Radius())*(s0.Radius()+s1.Radius());
867 }
868
869 template<class T>
870 bool IntersectionPlanePlane (const Plane3<T> & plane0, const Plane3<T> & plane1,
871 Line3<T> & line)
872 {
873 // If Cross(N0,N1) is zero, then either planes are parallel and separated
874 // or the same plane. In both cases, 'false' is returned. Otherwise,
875 // the intersection line is
876 //
877 // L(t) = t*Cross(N0,N1) + c0*N0 + c1*N1
878 //
879 // for some coefficients c0 and c1 and for t any real number (the line
880 // parameter). Taking dot products with the normals,
881 //
882 // d0 = Dot(N0,L) = c0*Dot(N0,N0) + c1*Dot(N0,N1)
883 // d1 = Dot(N1,L) = c0*Dot(N0,N1) + c1*Dot(N1,N1)
884 //
885 // which are two equations in two unknowns. The solution is
886 //
887 // c0 = (Dot(N1,N1)*d0 - Dot(N0,N1)*d1)/det
888 // c1 = (Dot(N0,N0)*d1 - Dot(N0,N1)*d0)/det
889 //
890 // where det = Dot(N0,N0)*Dot(N1,N1)-Dot(N0,N1)^2.
891
892 T n00 = plane0.Direction()*plane0.Direction();
893 T n01 = plane0.Direction()*plane1.Direction();
894 T n11 = plane1.Direction()*plane1.Direction();
895 T det = n00*n11-n01*n01;
896
897 const T tolerance = (T)(1e-06f);
898 if ( math::Abs(det) < tolerance )
899 return false;
900
901 T invDet = 1.0f/det;
902 T c0 = (n11*plane0.Offset() - n01*plane1.Offset())*invDet;
903 T c1 = (n00*plane1.Offset() - n01*plane0.Offset())*invDet;
904
905 line.SetDirection(plane0.Direction()^plane1.Direction());
906 line.SetOrigin(plane0.Direction()*c0+ plane1.Direction()*c1);
907
908 return true;
909 }
910
911
912 // Ray-Triangle Functor
913 template <bool BACKFACETEST = true>
914 class RayTriangleIntersectionFunctor {
915 public:
916 template <class TRIANGLETYPE, class SCALARTYPE>
917 inline bool operator () (const TRIANGLETYPE & f, const Ray3<SCALARTYPE> & ray, SCALARTYPE & t) {
918 typedef SCALARTYPE ScalarType;
919 ScalarType a;
920 ScalarType b;
921
922 bool bret = Intersection(ray, Point3<SCALARTYPE>::Construct(f.P(0)), Point3<SCALARTYPE>::Construct(f.P(1)), Point3<SCALARTYPE>::Construct(f.P(2)), a, b, t);
923 if (BACKFACETEST) {
924 if (!bret) {
925 bret = Intersection(ray, Point3<SCALARTYPE>::Construct(f.P(0)), Point3<SCALARTYPE>::Construct(f.P(2)), Point3<SCALARTYPE>::Construct(f.P(1)), a, b, t);
926 }
927 }
928 return (bret);
929 }
930 };
931
932
933
934
935 /*@}*/
936
937 } // end namespace
938 #endif