Skip to content

Instantly share code, notes, and snippets.

@andrew-wilkes
Created May 21, 2024 09:58
Show Gist options
  • Save andrew-wilkes/e6249f7bf9b2a35886012856be250436 to your computer and use it in GitHub Desktop.
Save andrew-wilkes/e6249f7bf9b2a35886012856be250436 to your computer and use it in GitHub Desktop.
Godot Cube Mapper Shader for a strip of 6 face images
// Code adapted from: https://www.shadertoy.com/view/WlsSRr Cubemap sampling
shader_type spatial;
uniform sampler2D tex;
varying vec3 v;
void vertex() {
v = normalize(VERTEX);
}
// direction -> cubemap face normal
vec3 GetCubeFaceDir(vec3 dir)
{
vec3 absDir = abs(dir);
float maxDir = max(max(absDir.x, absDir.y), absDir.z);
vec3 faceDir;
faceDir.x = step(maxDir, absDir.x) * sign(dir.x);
faceDir.y = step(maxDir, absDir.y) * sign(dir.y);
faceDir.z = step(maxDir, absDir.z) * sign(dir.z);
return faceDir;
}
// cubemap face normal -> face ID
float CubeFaceDirToID(vec3 faceDir)
{
return dot(clamp(faceDir, 0., 1.), vec3(0., 1., 2.)) + dot(clamp(-faceDir, 0., 1.), vec3(3., 4., 5.));
}
// cubemap face normal, direction -> face UVs
vec2 CubeFaceCoords(vec3 faceDir, vec3 viewDir)
{
vec3 uv3d = viewDir / dot(viewDir, faceDir) - faceDir;
vec3 uDir = vec3(faceDir.z + abs(faceDir.y), 0, -faceDir.x);
vec3 vDir = vec3(0, 1. - abs(faceDir.y), -faceDir.y);
return vec2(dot(uv3d, uDir), dot(uv3d, vDir)) * .5 + .5;
}
vec3 get_albedo(float face_idx, vec2 uv) {
return texture(tex, vec2((uv.x + face_idx) / 6.0, uv.y)).rgb;
}
void fragment() {
vec3 faceDir = GetCubeFaceDir(v);
float faceId = CubeFaceDirToID(faceDir);
vec2 faceCoords = CubeFaceCoords(faceDir, v);
ALBEDO = get_albedo(faceId, faceCoords);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment