Search across packages, versions, files, declarations, and comments. Use multiple terms to narrow results (AND), and add @vertex, @fragment, or @compute to filter by shader stage.
1// The lens distortion postprocessing effect.
3#define_import_path bevy_post_process::effect_stack::lens_distortion
5// See `bevy_post_process::effect_stack::LensDistortion` for more
6// information on these fields.
7struct LensDistortionSettings {
8 intensity: f32,
9 scale: f32,
10 multiplier: vec2<f32>,
11 center: vec2<f32>,
12 edge_curvature: f32,
13 unused: u32,
16const VISUAL_THRESHOLD: f32 = 1e-4;
17const MATH_EPSILON: f32 = 1e-6;
19// The settings supplied by the developer.
20@group(0) @binding(5) var<uniform> lens_distortion_settings: LensDistortionSettings;
22fn lens_distortion(uv: vec2<f32>) -> vec2<f32> {
23 let intensity = lens_distortion_settings.intensity;
24 if (abs(intensity) < VISUAL_THRESHOLD) {
25 return uv;
26 }
27 let multiplier = lens_distortion_settings.multiplier;
28 let center = lens_distortion_settings.center;
30 let uv_centered = uv - center;
31 // Prevent division by zero.
32 let radius = max(length(uv_centered), MATH_EPSILON);
34 let direction = uv_centered / radius;
35 let adjust = dot(abs(direction), multiplier);
37 // Maintains the correlation between k2 and k1, while ensuring the sign of k2
38 // is determined solely by `edge_curvature` rather than being influenced by intensity.
39 let k1 = intensity * adjust;
40 let k2 = k1 * intensity * lens_distortion_settings.edge_curvature;
42 let r2 = radius * radius;
43 let r_distorted = radius * (1.0 + (k1 + k2 * r2) * r2);
45 let uv_distorted = direction * r_distorted + center;
47 // Compensates for the distortion pushing pixels outside the [0,1] UV bounds.
48 let uv_scaled = (uv_distorted - center) / lens_distortion_settings.scale + center;
50 // Discard out-of-bounds pixels to prevent edge bleeding artifacts.
51 let uv_safe = clamp(uv_scaled, vec2<f32>(0.0), vec2<f32>(1.0));
53 return uv_safe;
Contents