In Ray-Sphere intersection is $b=2*(O-C) \cdot dirv$?

Where $dirv$ is the Ray direction vector. $O$ is origin and $C$ is center of the sphere.

I've also seen this without the $2$, i.e. $b=(O-C)\cdot dirv$.

Particularly here it's calculated like:

// Compute:
//    d = L - E ; // Direction vector of ray, from start to end
//    f = E - C ; // Vector from center sphere to ray start
const Vector &d = ray.direction ;
Vector f = ray.startPos - this->pos ;
real a = d • d ;  // a is non-negative, this is actually always 1.0
real b = 2*(f • d) ;
real c = f • f - radius*radius ;

real discriminant = b*b-4*a*c;

TL;DR $b = 2(f \cdot d)$

I'll try to derive it and then we can see what $b$ should be. If the sphere is centered at point $a$ with radius $r$, its equation is $|p - a| = r$, where $p$ is a point on the sphere. $|p - a|$ is the distance from a point $p$ to the centre of the sphere, and if that is equal to the radius, then it's a point on the sphere.

We'll assume the centre of the sphere is at the origin, so $a = 0$ and we have $|\vec{p}| = r$. Squaring both sides gives $|\vec{p}|^2 = r^2$ which I'm going to write as $$\vec{p}^2 = r^2 \tag{1}$$

Ray has equation $$x + td\tag{2}$$ where $x$ is the endpoint, $d$ is the direction, and $t$ is the parameter.

If the ray doesn't intersect the sphere, we will not be able to find a $t$ satisfying the ray equation. In the quadratic equation the discriminant (the bit under the square root) will be $< 0$. If it grazes the sphere (i.e. tangent) then we'll have a single point of intersection and a single $t$ and the discriminant will be $0$. If it goes through the sphere, we'll get a $t$ for the sphere entry, and a distinct $t$ for the sphere exit and the discriminant will be $> 0$. We need to plug $(2)$ into $(1)$ and solve for $t$:

$$ \begin{alignat}{2} &&(x + td)^2 &= r^2\\ &\Rightarrow\quad &(x + td)(x + td) &= r^2\\ &\Rightarrow\quad &x \cdot x + 2t(x \cdot d) + t^2(d \cdot d) &= r^2\\ &\Rightarrow\quad &(d \cdot d)t^2 + 2(x \cdot d)t + (x \cdot x - r^2) &= 0 \tag{3}\\ \end{alignat}$$

Equation $3$ is a quadratic expression in $t$ (i.e. $at^2 + bt + c = 0$) where $$a = (d \cdot d)$$ $$b = 2(x \cdot d)$$ $$c = (x \cdot x - r^2)$$

This matches the code you posted, but the code is allowing spheres to be centered at an arbitrary point C. The code then has this line:

// f = E - C ; // Vector from center sphere to ray start

which effectively translates the endpoint of the ray E to a new endpoint f so that we can now consider the sphere to be centered at the origin. The ray direction is unchanged.

  • $\begingroup$ I wonder what the $b$ without $2$ is then. I've seen it used somewhere, but cannot find it now. $\endgroup$
    – mavavilj
    Mar 13 '17 at 16:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.