// SPDX-License-Identifier: CC-BY-SA-4.0 // Copyright © Paweł Redman #import "/common.typ": post, static, img #show: post.with( title: "Ray vs. sphere", date: datetime(year: 2018, month: 5, day: 9), ) #figure( img(static("math/ray_vs_sphere.png")), caption: [A drawing of a ray intersecting a sphere in two dimensions.], ) In $RR^N$, a ray of origin $bold(x)_r$ and direction $bold(v)$ and an N-sphere of origin $bold(x)_s$ and radius $r$ intersect at $bold(x)_I$ given by: $ bold(x)_I = bold(x)_r + t_(plus.minus) bold(v) $ where: $ t_(plus.minus) &= (bold(v) dot bold(u) plus.minus sqrt((bold(v) dot bold(u))^2 - v^2 (u^2 - r^2))) / v^2 \ bold(u) &= bold(x)_s - bold(x)_r $ If the expression under the square root is negative, there is no intersection. If it's zero, $t_+ = t_-$ and there is only one intersection. Notice that since $t v$ is the distance to intersection, $t_-$ corresponds to the *closer one* and $t_+$ to the *further*. Depending on the application, you might want to discard negative $t$'s (intersections "behind" the ray). = Surface normal The surface normal $hat(bold(n))$ at an intersection is given by: $ bold(r) &= t_(plus.minus) bold(v) - bold(u) \ hat(bold(n)) &= hat(bold(r)) $ = Normalized v Notice that the expression for $t_(plus.minus)$ becomes appreciably simpler if $v = 1$: $ t_(plus.minus) &= bold(v) dot bold(u) plus.minus sqrt((bold(v) dot bold(u))^2 - (u^2 - r^2)) $ = Derivation Notice that the point of intersection lies somewhere on the line defined by the ray: $ bold(x)_I = bold(x)_r + t bold(v) $ for some real $t$. It also lies somewhere on the sphere: $ bold(x)_I = bold(x)_s + bold(r) $ for some vector $bold(r)$ of length $r$. Combining the two equations and solving for $bold(r)$ yields: $ bold(x)_r + t bold(v) - bold(x)_s = bold(r) $ To simplify the algebra, substitute $bold(x)_s - bold(x)_r = bold(u)$: $ t bold(v) - bold(u) = bold(r) $ Since only the length of $bold(r)$ is known, the only thing that can be done at this point is equating the norms of both sides. Squared norms are more convenient in this particular case: $ (t bold(v) - bold(u))^2 &= r^2 \ t^2 v^2 + u^2 - 2 t bold(v) dot bold(u) &= r^2 \ v^2 t^2 - 2 bold(v) dot bold(u) t + u^2 - r^2 &= 0 $ Solving the quadratic equation and simplifying: $ t_(plus.minus) &= (2 bold(v) dot bold(u) plus.minus sqrt(4 (bold(v) dot bold(u))^2 - 4 v^2 (u^2 - r^2))) / (2 v^2) \ t_(plus.minus) &= (bold(v) dot bold(u) plus.minus sqrt((bold(v) dot bold(u))^2 - v^2 (u^2 - r^2))) / v^2 $ As with any quadratic equation, there is no real solution if the expression under the square root is negative and if it's zero, the solutions coincide. Notice that $bold(r)$ is perpendicular to the sphere at an intersection. Normalizing this vector yields the surface normal $hat(bold(n))$.