How do I convert from Cartesian to spherical coordinates?

This seems like a fairly basic and common problem. Is there a builtin way to achieve it or do I have to write the algorithm on my own? If I do, how should it work?

• @Anko Your edit pretty much changes the objective of the question^^ But it is probably better for future reference... – iolo Dec 22 '14 at 9:10

Not that I'm aware of (you're asking if there's some sort of glsl function that would do the conversion, right?)

It's a pretty simple conversion though, just three lines; here it is in pseudocode:

r = sqrt(x*x+y*y+z*z);
theta = atan2(y,x);
phi = atan2(sqrt(x*x+y*y),z);

• Yeah, I know, but one has to sort out the case when x is zero if I read the spec of atan() correctly. I just thought, people must be doing this all the time, so a builtin function might be available. – iolo Nov 15 '14 at 16:41
• x being 0 shouldn't be a problem, you'd only have issues with the above if r = 0 en.wikipedia.org/wiki/Atan2#Definition_and_computation – DudeMan2000 Nov 15 '14 at 16:50
• According to opengl.org/sdk/docs/man/html/atan.xhtml atan(y,x) is undefined whenever x is zero. – iolo Nov 15 '14 at 16:54
• Oh crap... it looks like there isn't an atan2 function in glsl after all, my bad. Out of curiosity, what are you using the spherical coordinates for? Do they get plugged into other trig functions after you've converted them? – DudeMan2000 Nov 15 '14 at 16:58
• Well the glsl atan() with 2 args works just like atan2(). I am building an app that displays certain aspects of the wave function of a hydrogen atom (and I am teaching myself OpenGL). – iolo Nov 15 '14 at 17:12