| 1 | // WebGPU-safe 2D triangle mesh warp renderer for Fusion `SurfaceTracker`. |
| 2 | // |
| 3 | // Vertex positions are supplied in Fusion normalized Y-up [0..1] coordinates: |
| 4 | // - `cur_pos`: tracked mesh vertex position at the evaluated frame |
| 5 | // - `ref_pos`: reference mesh vertex position at `ReferenceFrame` |
| 6 | // - `photo_weight`: per-vertex photometric weight ratio (`cur_pw / ref_pw`) |
| 7 | // |
| 8 | // The fragment shader projects `ref_pos` through the inverse `WarpableCanvas` |
| 9 | // 3x3 projective homography `H_inv` into Overlay normalized Y-up [0..1] space, |
| 10 | // converts to top-down texture UV, and bilinearly samples `overlay_tex`. |
| 11 | |
| 12 | struct MeshWarpUniform { |
| 13 | // Row-major 3x3 inverse homography mapping ref_pos (Fusion Y-up) -> Overlay (Fusion Y-up): |
| 14 | // h0 = (h00, h01, h02, h10) |
| 15 | // h1 = (h11, h12, h20, h21) |
| 16 | // h2 = (h22, photo_strength, 0.0, 0.0) |
| 17 | h0: vec4<f32>, |
| 18 | h1: vec4<f32>, |
| 19 | h2: vec4<f32>, |
| 20 | extra: vec4<f32>, |
| 21 | }; |
| 22 | |
| 23 | @group(0) @binding(0) var overlay_tex: texture_2d<f32>; |
| 24 | @group(0) @binding(1) var lin_samp: sampler; |
| 25 | @group(0) @binding(2) var<uniform> u: MeshWarpUniform; |
| 26 | |
| 27 | struct VsIn { |
| 28 | @location(0) cur_pos: vec2<f32>, |
| 29 | @location(1) ref_pos: vec2<f32>, |
| 30 | @location(2) photo_weight: f32, |
| 31 | }; |
| 32 | |
| 33 | struct VsOut { |
| 34 | @builtin(position) pos: vec4<f32>, |
| 35 | @location(0) ref_pos: vec2<f32>, |
| 36 | @location(1) photo_weight: f32, |
| 37 | }; |
| 38 | |
| 39 | @vertex |
| 40 | fn vs_mesh(in: VsIn) -> VsOut { |
| 41 | var out: VsOut; |
| 42 | // Fusion Y-up [0..1] maps directly to WebGPU NDC [-1..1] (where +1 is top, -1 is bottom). |
| 43 | let ndc = vec2<f32>(in.cur_pos.x * 2.0 - 1.0, in.cur_pos.y * 2.0 - 1.0); |
| 44 | out.pos = vec4<f32>(ndc, 0.0, 1.0); |
| 45 | out.ref_pos = in.ref_pos; |
| 46 | out.photo_weight = in.photo_weight; |
| 47 | return out; |
| 48 | } |
| 49 | |
| 50 | @fragment |
| 51 | fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> { |
| 52 | let rx = in.ref_pos.x; |
| 53 | let ry = in.ref_pos.y; |
| 54 | let sx = u.h0.x * rx + u.h0.y * ry + u.h0.z; |
| 55 | let sy = u.h0.w * rx + u.h1.x * ry + u.h1.y; |
| 56 | let sw = u.h1.z * rx + u.h1.w * ry + u.h2.x; |
| 57 | if (abs(sw) < 1e-6) { |
| 58 | discard; |
| 59 | } |
| 60 | let fu_uv = vec2<f32>(sx / sw, sy / sw); |
| 61 | if (fu_uv.x < 0.0 || fu_uv.x > 1.0 || fu_uv.y < 0.0 || fu_uv.y > 1.0) { |
| 62 | discard; |
| 63 | } |
| 64 | let tex_uv = vec2<f32>(fu_uv.x, 1.0 - fu_uv.y); |
| 65 | var col = textureSampleLevel(overlay_tex, lin_samp, tex_uv, 0.0); |
| 66 | let photo_strength = clamp(u.h2.y, 0.0, 1.0); |
| 67 | if (photo_strength > 0.0) { |
| 68 | let pw = mix(1.0, max(in.photo_weight, 0.0), photo_strength); |
| 69 | col = vec4<f32>(col.rgb * pw, col.a); |
| 70 | } |
| 71 | return col; |
| 72 | } |