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.

More from Qtan1

Dynamic Depth of Field

Screen Space God Rays (Godot.4.3)

Related shaders

global vertex snapping with 3dresolution scaling

Pixelized (by distance) Shader

Fade by distance to character

Subscribe
Notify of
guest

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
flynsarmy
flynsarmy
1 year ago

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

Moomit
Moomit
1 year ago

How do i use this shader? I tried to attach it to MeshInstance3D but it does not seem to work