Skip to content

Distance Functions

Xyndra edited this page Nov 23, 2024 · 2 revisions

Distance Functions

In this page, I will detail my procedure to create distance functions taking the example of a sphere:

  1. Get yourself the function for the outside of the shape $(x+o_x)^2 + (y+o_y)^2 + (z+o_z)^2 = r^2$ ($o$ is the inverse of the offset of the sphere from the origin here)

  2. Add a stretch factor to later solve for $(dx+o_x)^2 + (dy+o_y)^2 + (dz+o_z)^2 = r^2$

  3. Solve for $d$

    • $d^2 x^2 +2dxo_x+o_x^2 +d^2 y^2 +2dyo_y+o_y^2 +d^2 z^2 +2dzo_z+o_z^2 =r^2$

    • $d^2 (x^2 +y^2 +z^2) + 2d(xo_x+yo_y+zo_z) + o_x^2 +o_y^2 +o_z^2 =r^2$

    • $d^2 (x^2 +y^2 +z^2) + 2d(xo_x+yo_y+zo_z) + (o_x^2 +o_y^2 +o_z^2 -r^2)=0$

    • $A=x²+y²+z²$, $B=2(xo_x+yo_y+zo_z)$, $C=o_x^2 + o_y^2 + o_z^2 - r^2$; $d^2A + 2dB + C=0$

    • $d=\frac{-B\pm\sqrt{B^2-4AC}}{2A}$

  4. Now, just return $min(d)$ (because of the $\pm$ in the formula) so that you get the front of the sphere

Notes:

  • You can use any kind of variable as a uniform for your function

  • The vector is always assumed as the origin to simplify the calculations, however you must do that with your object too (offsets for the current vector are given)

Clone this wiki locally