# Implement spherical mapping for texture coordinates

I am using a texture of a world map and I am trying to put that image on a sphere made up of many triangles. Each triangle has points a,b,c with their own (x,y,z) coordinates.

I am trying to use the coordinate system conversions formula from Wikipedia. This is my world to spherical coordinates function:

function worldToSpherical(p) {

const r = Math.sqrt(Math.pow(p[0],2)+ Math.pow(p[1],2) + Math.pow(p[2],2));
const u = Math.atan2(p[1],p[0]);
const i = Math.atan2(Math.sqrt(Math.pow(p[0],2)+Math.pow(p[1],2)),p[2]);

const s =  r * Math.sin(i) * Math.cos(u);
const t =  r * Math.sin(i) * Math.sin(u);
return [s, t];

}


But this is what my output looks like:

It seems to be wrapping around twice. Am I using the wrong formula, or using it wrong?

You just went to a lot of trouble to undo the trig on your u and i variables! Don't re-trig them with cos and sin! Just compress the range from the radian angles to your 0...1 texture coordinate space.

function worldToSpherical(p) {

const radius = Math.sqrt(p[0]*p[0] + p[1]*p[1] + p[2]*p[2]);

// Convert range -PI...PI to 0...1
const s =  longitudeRadians/(2 * Math.PI) + 0.5;

// Convert range -PI/2...PI/2 to 0...1
const t =  latitudeRadians/Math.PI + 0.5;
return [s, t];
}

• Note that if you compute your UV coordinate per vertex, you'll end up with artifacts - especially close to the poles. As demonstrated in this answer, you can fix this by computing your texture coordinates per pixel/per fragment in your shader Apr 21 '20 at 19:52
• Thank you I see where I went wrong on my calculation. The only thing I see problematic currently is the North Pole is looking right at me and not on top of the sphere. Apr 21 '20 at 20:01
• Then you should edit your question to describe the coordinate system you're using. Your initial formula was set up as though z / p[2] is your vertical axis. If that's not the case, we'll need to swap a couple of the axes around, and potentially negate something depending on your handedness. Apr 21 '20 at 20:22