RustToDust/client/terrain_surface.gdshader

56 lines
1.8 KiB
Text

shader_type spatial;
render_mode cull_back, depth_draw_opaque;
uniform sampler2D height_tex : filter_linear, repeat_disable;
uniform sampler2D albedo_tex : filter_linear, repeat_disable;
uniform float height_min = -18.0;
uniform float height_max = 52.0;
uniform float tile_size = 192.0;
uniform float inner_span = 253.0;
uniform float tex_size = 256.0;
uniform float gutter_offset = 1.5;
float decode_height(float h_norm) {
return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0));
}
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
vec2 to_baked_uv(vec2 mesh_uv) {
return (mesh_uv * inner_span + gutter_offset) / tex_size;
}
void vertex() {
float h_norm = textureLod(height_tex, to_baked_uv(UV), 0.0).r;
VERTEX.y += decode_height(h_norm);
}
void fragment() {
vec2 uv_baked = to_baked_uv(UV);
float texel_step = 1.0 / tex_size;
float world_step = tile_size / inner_span;
float hL = decode_height(texture(height_tex, uv_baked - vec2(texel_step, 0.0)).r);
float hR = decode_height(texture(height_tex, uv_baked + vec2(texel_step, 0.0)).r);
float hD = decode_height(texture(height_tex, uv_baked - vec2(0.0, texel_step)).r);
float hU = decode_height(texture(height_tex, uv_baked + vec2(0.0, texel_step)).r);
vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU));
NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz);
vec4 mat = texture(height_tex, uv_baked);
vec3 alb = texture(albedo_tex, uv_baked).rgb;
// Subtle desert sand grain so dunes read crisply under sunlight
float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045;
float scorch = clamp(mat.b, 0.0, 1.0);
alb = clamp(alb + vec3(grain), 0.0, 1.0) * (1.0 - 0.30 * scorch);
ALBEDO = alb;
ROUGHNESS = clamp(mat.g, 0.25, 1.0);
METALLIC = 0.05;
}