Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active February 22, 2024 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unitycoder/626ca11da5dcadea3bffe51a6541edd7 to your computer and use it in GitHub Desktop.
Save unitycoder/626ca11da5dcadea3bffe51a6541edd7 to your computer and use it in GitHub Desktop.
shader code to do equirectangular lookups on a texture
// https://forum.unity.com/threads/mapping-a-point-in-world-space-to-a-uv-of-a-sphere.760868/
// https://forum.unity.com/threads/what-is-wrong-with-unitys-spherical-mapping-how-to-fix-it.321205/#post-2083408
Shader "Custom/Equirectangular" {
Properties {
_Color ("Main Color", Color) = (1,1,1,1)
_MainTex ("Diffuse (RGB) Alpha (A)", 2D) = "gray" {}
}
SubShader{
Pass {
Tags {"LightMode" = "Always"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#pragma glsl
#pragma target 3.0
#include "UnityCG.cginc"
struct appdata {
float4 vertex : POSITION;
float3 normal : NORMAL;
};
struct v2f
{
float4 pos : SV_POSITION;
float3 normal : TEXCOORD0;
};
v2f vert (appdata v)
{
v2f o;
o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
o.normal = v.normal;
return o;
}
sampler2D _MainTex;
#define PI 3.141592653589793
inline float2 RadialCoords(float3 a_coords)
{
float3 a_coords_n = normalize(a_coords);
float lon = atan2(a_coords_n.z, a_coords_n.x);
float lat = acos(a_coords_n.y);
float2 sphereCoords = float2(lon, lat) * (1.0 / PI);
return float2(sphereCoords.x * 0.5 + 0.5, 1 - sphereCoords.y);
}
float4 frag(v2f IN) : COLOR
{
float2 equiUV = RadialCoords(IN.normal);
return tex2D(_MainTex, equiUV);
}
ENDCG
}
}
FallBack "VertexLit"
}
@gilberths1
Copy link

Hey there, im sorry if this is a newbie question, but i am currently using this shader but i don't quite understand the math in RadialCoords(), do you have any reference on that? or maybe just a source for me to learn or a keyword to learn the method? thanks :)

@unitycoder
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment