I want to write a simple ray tracing(?) algorithm in WebGL with continuous refraction. So my idea was, what if you have a material whose optical density varies continuously, if this is physically possible?

So say you have some closed zero-set $A\subseteq\mathbf{R}^3$ and the optical density of some point $x$ in your world is $n(x):=\exp(-d(x,A)^2)$ where $d(x,A)$ is the distance between $x$ and (one of) the closest point to $x$ in $A$. I couldn't find a formula for this, but I assume it would be some limit of Snell's law where you you round $n(x)$ to some multiple of $\epsilon$ and let $\epsilon$ approach $0$.

What would be a good algorithm to approximate this? Basically my idea is to have a position and a direction, which describe the current stat of your ray, then you loop over some fixed number of iterations and in each step do

  • compute the vector $v$ from the current position to the closest point in $A$ (I hope the set of $x$ with more than one closest point in $A$ is a zero-set and I will never encounter it),
  • compute length of $v$ and its angle relative to the current travelling direction,
  • then compute a new direction and some distance to travel, update the position and continue the loop, or break if you encounter some texture inbetween.

The idea is that the travel distances are shorter when you are closer to $A$, as the refraction index changes more rapidly here. How could the function for the last step look like?

  • $\begingroup$ See this paper: "Interactive Rendering of Non-Constant, Refractive Media Using the Ray Equations of Gradient-Index Optics", and potentially "Ray Tracing in Non-Constant Media" by Stam. Essentially you need to do some kind of ray-marching. You need to find a potentially curved path up to some precision such that it minimises time traveled (i.e. geodesic curves). $\endgroup$
    – lightxbulb
    Commented Jun 8, 2022 at 15:31

1 Answer 1


You can refer to the available literature on the topic. The papers I am aware of are:

Ray Tracing in Non-Constant Media


Interactive Rendering of Non-Constant, Refractive Media Using the Ray Equations of Gradient-Index Optics

The general algorithm for handling a varying index of refraction is ray-marching, where the size of the steps is related to the accuracy of your solution.

  • $\begingroup$ This is what I came up with BTW, it's not 100 % physically correct, but I really like the look! $\endgroup$
    – fweth
    Commented Jun 20, 2022 at 8:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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