Skip to main content

runmat_plot/gpu/shaders/vertex/
grid_plane.rs

1pub const SHADER: &str = r#"// Procedural XY grid plane shader (CAD-like helper)
2
3struct Uniforms {
4    view_proj: mat4x4<f32>,
5    model: mat4x4<f32>,
6    normal_matrix: mat3x4<f32>,
7}
8
9@group(0) @binding(0)
10var<uniform> uniforms: Uniforms;
11
12struct GridParams {
13    major_step: f32,
14    minor_step: f32,
15    fade_start: f32,
16    fade_end: f32,
17    camera_pos: vec3<f32>,
18    _pad0: f32,
19    target_pos: vec3<f32>,
20    _pad1: f32,
21    major_color: vec4<f32>,
22    minor_color: vec4<f32>,
23}
24
25@group(1) @binding(0)
26var<uniform> grid: GridParams;
27
28struct VertexInput {
29    @location(0) position: vec3<f32>,
30    @location(1) color: vec4<f32>,
31    @location(2) normal: vec3<f32>,
32    @location(3) tex_coords: vec2<f32>,
33}
34
35struct VertexOutput {
36    @builtin(position) clip_position: vec4<f32>,
37    @location(0) world_position: vec3<f32>,
38}
39
40@vertex
41fn vs_main(input: VertexInput) -> VertexOutput {
42    var out: VertexOutput;
43    let world_position = uniforms.model * vec4<f32>(input.position, 1.0);
44    out.clip_position = uniforms.view_proj * world_position;
45    out.world_position = world_position.xyz;
46    return out;
47}
48
49fn grid_line(coord: f32, step: f32) -> f32 {
50    if !(step > 0.0) {
51        return 0.0;
52    }
53    let u = coord / step;
54    let f = fract(u);
55    let d = min(f, 1.0 - f); // distance to nearest integer grid line in [0, 0.5]
56    let w = fwidth(u);
57    // 1-pixel-ish antialiased line in param space
58    return 1.0 - smoothstep(0.0, w * 1.5, d);
59}
60
61@fragment
62fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
63    let x = input.world_position.x;
64    let y = input.world_position.y;
65
66    let minor = max(grid_line(x, grid.minor_step), grid_line(y, grid.minor_step));
67    let major = max(grid_line(x, grid.major_step), grid_line(y, grid.major_step));
68    let minor_only = minor * (1.0 - major);
69
70    // Fade out towards edges of the grid patch (and keep it subtle when very large).
71    let dxy = length(vec2<f32>(x - grid.target_pos.x, y - grid.target_pos.y));
72    let fade = 1.0 - smoothstep(grid.fade_start, grid.fade_end, dxy);
73
74    let c = grid.major_color * major + grid.minor_color * minor_only;
75    return vec4<f32>(c.rgb, c.a * fade);
76}
77"#;