Camera Distance UV Scaling

This is a simple script which interpolates the UV scaling based on the distance to the camera. Very useful for smoothly changing the texture quality of large distant objects like mountains and such.

Edit:
For Godot 4.0  replace CAMERA_MATRIX  with INV_VIEW_MATRIX. Thanks flynsarmy, for the tip.

Shader code
shader_type spatial;

uniform sampler2D main_tex;
uniform float max_dist = 50;
uniform float min_dist = 10;
uniform float res_high = 16.0;
uniform float res_low = 2.0;

void fragment () {
	vec3 world_camera = (CAMERA_MATRIX * vec4(vec3(0.0), 1.0)).xyz;
	vec4 a = CAMERA_MATRIX * vec4(VERTEX, 1.0);
	vec3 low_tex = texture(main_tex, UV * res_low).rgb;
	vec3 hi_tex = texture(main_tex, UV * res_high).rgb;
	ALBEDO = mix(hi_tex, low_tex, smoothstep(min_dist, max_dist, distance(a.xyz, world_camera)));
}
Tags
Distance, terrain, UV Scaling
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

Underwater Camera effect

Pixelized (by distance) Shader

guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
flynsarmy
flynsarmy
1 month ago

CAMERA_MATRIX was renamed to INV_VIEW_MATRIX in Godot 4. See https://github.com/godotengine/godot/pull/59268