Free Electron
RaySphereIntersect.h
Go to the documentation of this file.
1 /* Copyright (C) 2003-2021 Free Electron Organization
2  Any use of this software requires a license. If a valid license
3  was not distributed with this file, visit freeelectron.org. */
4 
5 /** @file */
6 
7 #ifndef __geometry_RaySphereIntersect_h__
8 #define __geometry_RaySphereIntersect_h__
9 
10 namespace fe
11 {
12 namespace ext
13 {
14 
15 /**************************************************************************//**
16  @brief Find intersection between ray and sphere
17 
18  @ingroup geometry
19 *//***************************************************************************/
20 template <typename T>
22 {
23  public:
24 static T solve(const Vector<3,T>& center,const T radius,
25  const Vector<3,T>& origin,
26  const Vector<3,T>& direction);
27 static void resolveContact(const Vector<3,T>& center,const T radius,
28  const Vector<3,T>& origin,
29  const Vector<3,T>& direction,
30  const T range,
31  Vector<3,T>& intersection,
32  Vector<3,T>& normal);
33 };
34 
35 // direction must be normalized
36 template <typename T>
37 inline T RaySphereIntersect<T>::solve(const Vector<3,T>& center,T radius,
38  const Vector<3,T>& origin, const Vector<3,T>& direction)
39 {
40 // feLog("center %s radius %.6G\n",c_print(center),radius);
41 // feLog("origin: %s\n",c_print(origin));
42 // feLog("direction: %s\n",c_print(direction));
43 
44  const Vector<3,T> to_origin=origin-center;
45  const T b=T(2)*dot(direction,to_origin);
46  const T c=dot(to_origin,to_origin)-radius*radius;
47  const T i=b*b-T(4)*c;
48 
49 // feLog("b %.6G c %.6G i %.6G\n",b,c,i);
50 
51  if(i<T(0))
52  {
53  return T(-1);
54  }
55 #if FALSE
56  const T sq=sqrtf(i);
57  const T t1=(-b+sq);
58  const T t2=(-b-sq);
59 
60 // feLog("t1 %.6G t2 %.6G\n",t1,t2);
61 
62  T range=T(0.5)*((t1<t2)? t1: t2);
63 #else
64  T range=T(-0.5)*(b+sqrtf(i));
65  if(range<0.0)
66  {
67  range=T(-0.5)*(b-sqrtf(i));
68  }
69 #endif
70 
71  return range;
72 }
73 
74 // direction must be normalized
75 template <typename T>
77  const Vector<3,T>& center,const T radius,
78  const Vector<3,T>& origin,
79  const Vector<3,T>& direction,
80  const T range,
81  Vector<3,T>& intersection,
82  Vector<3,T>& normal)
83 {
84  FEASSERT(radius>0.0);
85  intersection=origin+direction*range;
86  normal=(intersection-center)/radius;
87 }
88 
89 } /* namespace ext */
90 } /* namespace fe */
91 
92 #endif /* __geometry_RaySphereIntersect_h__ */
kernel
Definition: namespace.dox:3
Find intersection between ray and sphere.
Definition: RaySphereIntersect.h:21