In 2019, I wanted have spherical harmonics \(Y_\ell^m\) in shader, solved in real time instead of from precomputed functions. After looking at some papers, one approach was to solve them using the hypergeometric function, which gives \(P_\ell^m\) as
P_\ell^m(x) = \frac{1}{\Gamma(1-m)} \frac{(1+z)^{m/2}}{(1-z)^{m/2}} {_2F_1}\left( -n, n + 1, 1-m, \frac{1-x}{2} \right).
This requires computing a series consisting of many factorials, which is slow and results in precision problems


As it turns out, there is a better approach using Clenshaw's algorithm! A review of different methods is given in arXiv:1410.1748 [physics.chem-ph]. Now I could get up to high values of \(\ell\) and \(m\) without everything blowing up! From the ALPs we can then simply obtain the SHs as
Y_\ell^m(\theta, \phi) = \sqrt{\frac{(2 \ell + 1) (\ell - m)!}{4\pi (\ell + m)!}} P_\ell^m (\cos \theta) e^{i m \phi}.
The final code can be viewed at, which borrows from iq's shader

· · Web · 1 · 0 · 7

@roninkoi Very nicely done! I had planned to write an improvement of Quilez's original demo after writing my own implementation of Clenshaw for other orthogonal polynomials (e.g., but real life got in the way. Thanks for making it so I no longer have to. ;)

@tpfto Thanks! Your posts have helped me many times over the years

Sign in to participate in the conversation

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!