How do I get started with a 3D Magnifying Glass Effect
Usable shader with an artifact bug:
shader_type spatial;
render_mode unshaded;
uniform sampler2D screen_texture : hint_screen_texture;
vec2 convert_to_local_screen_space(vec2 screen_UV, vec2 screen_centre_UV, vec2 model_UV){
// Calculate the distance, in terms of screen uv values, on the centre of the model to any corner bounds.
vec2 distance_from_centre = abs(1.0/(abs(0.5-model_UV)*2.0)) * abs(screen_UV-screen_centre_UV);
vec2 full_size = distance_from_centre * 2.0;
// Convert distance from centre to the minimum bounds (this should be our 0.0).
vec2 minimum_bounds = screen_centre_UV - distance_from_centre;
// Adjust our current position to get the local bounds.
vec2 local_screen_UV = (screen_UV - minimum_bounds) / full_size;
return local_screen_UV;
}
vec2 convert_to_full_screen_space(vec2 local_screen_UV, vec2 screen_UV, vec2 screen_centre_UV, vec2 model_UV){
// Calculate the distance, in terms of screen uv values, on the centre of the model to any corner bounds.
vec2 distance_from_centre = abs(1.0/(abs(0.5-model_UV)*2.0)) * abs(screen_UV-screen_centre_UV);
vec2 full_size = distance_from_centre * 2.0;
// Convert distance from centre to the minimum bounds (this should be our 0.0).
vec2 minimum_bounds = screen_centre_UV - distance_from_centre;
return local_screen_UV * full_size + minimum_bounds;
}
float calculate_model_screen_aspect_ratio(vec2 screen_UV, vec2 screen_centre_UV, vec2 model_UV){
// Calculate the distance, in terms of screen uv values, on the centre of the model to any corner bounds.
vec2 distance_from_centre = abs(1.0/(abs(0.5-model_UV)*2.0)) * abs(screen_UV-screen_centre_UV);
vec2 full_size = distance_from_centre * 2.0;
return full_size.y / full_size.x;
}
vec2 fish_eye(vec2 UV_position, vec2 screen_UV, vec2 centre_UV) {
// Shift the initial and final coordinate to adjust it to the model shape.
vec2 shifted_UV = UV_position * vec2(2.0) - vec2(1.0);
float UV_distance = length(shifted_UV);
float z = sqrt(1.0 - (shifted_UV.x * shifted_UV.x) - (shifted_UV.y * shifted_UV.y));
float r = atan(UV_distance, z) / PI;
float phi = atan(shifted_UV.y, shifted_UV.x);
return convert_to_full_screen_space(vec2(r * cos(phi) + 0.5, r * sin(phi) + 0.5), screen_UV, centre_UV, UV_position);
}
void fragment() {
/*
1) Get the centre of the object in terms of SCREEN_UV.
2) Pass the fragment SCREEN_UV and centre SCREEN_UV to the distort function.
3) Feed the distorted SCREEN_UV to the texture sampler.
*/
vec4 clip_position = PROJECTION_MATRIX * vec4(NODE_POSITION_VIEW, 1.0);
vec2 centre_screen_uv = (clip_position.xy * vec2(0.5) + vec2(clip_position.w/2.0)) / clip_position.w;
vec2 distorted_screen_uv = fish_eye(UV, SCREEN_UV, centre_screen_uv);
ALBEDO = textureLod(screen_texture, distorted_screen_uv, 0.0).rgb;
}