awsm-renderer 0.4.2

awsm-renderer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! The single GPU-buffer packer for the visibility + transparency geometry
//! streams (see `docs/buffers.md`).
//!
//! All geometry packs through here so its bytes can't drift: `resolve_one`
//! (commit) packs the visibility/transparency streams for BOTH the raw-mesh and
//! glTF sources from their retained `GeometrySource`, and the glTF decode's
//! `cfg(test)` packer-parity references pin byte-identity against it. The byte
//! layouts here are the canonical definition.

use awsm_renderer_core::pipeline::primitive::FrontFace;

/// Barycentric coords per triangle corner (matches the gltf path's
/// `buffers/mesh/visibility.rs`).
const BARYCENTRICS: [[f32; 2]; 3] = [[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]];

/// The default-tangent fallback when no per-vertex tangent is supplied (a surface
/// with no normal map never reads it). Matches the gltf populate path.
const SYNTHETIC_TANGENT: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

/// Visibility geometry — 56 bytes per **exploded** vertex (one record per
/// triangle corner):
/// `position(12) | triangle_index(4) | barycentric(8) | normal(12) | tangent(16)
///   | original_vertex_index(4)`.
///
/// `tangents`, when `Some`, is indexed per original vertex; `None` packs the
/// synthetic fallback.
///
/// `front_face`: [`FrontFace::Cw`] emits each triangle's corners in `[0, 2, 1]`
/// order (with matching barycentrics) so clockwise-authored sources rasterize
/// with the same facing as the default counter-clockwise convention — the same
/// swizzle the gltf populate path applies. [`FrontFace::Ccw`] is the identity
/// order.
pub fn pack_visibility_bytes(
    positions: &[[f32; 3]],
    normals: &[[f32; 3]],
    tangents: Option<&[[f32; 4]]>,
    indices: &[u32],
    front_face: FrontFace,
) -> Vec<u8> {
    // Corner emission order per triangle (and the barycentric that rides with
    // each corner's slot).
    let corner_order: [usize; 3] = match front_face {
        FrontFace::Cw => [0, 2, 1],
        _ => [0, 1, 2],
    };
    let triangle_count = indices.len() / 3;
    let mut out = Vec::with_capacity(triangle_count * 3 * 56);
    for (triangle_index, tri) in indices.chunks_exact(3).enumerate() {
        for (slot, &corner) in corner_order.iter().enumerate() {
            let vertex_index = tri[corner];
            let v = vertex_index as usize;
            let pos = positions[v];
            let normal = normals[v];
            let bary = BARYCENTRICS[corner_order[slot]];
            let tan = tangents.map(|t| t[v]).unwrap_or(SYNTHETIC_TANGENT);
            // position (12)
            out.extend_from_slice(&pos[0].to_le_bytes());
            out.extend_from_slice(&pos[1].to_le_bytes());
            out.extend_from_slice(&pos[2].to_le_bytes());
            // triangle_index (4)
            out.extend_from_slice(&(triangle_index as u32).to_le_bytes());
            // barycentric (8)
            out.extend_from_slice(&bary[0].to_le_bytes());
            out.extend_from_slice(&bary[1].to_le_bytes());
            // normal (12)
            out.extend_from_slice(&normal[0].to_le_bytes());
            out.extend_from_slice(&normal[1].to_le_bytes());
            out.extend_from_slice(&normal[2].to_le_bytes());
            // tangent (16)
            out.extend_from_slice(&tan[0].to_le_bytes());
            out.extend_from_slice(&tan[1].to_le_bytes());
            out.extend_from_slice(&tan[2].to_le_bytes());
            out.extend_from_slice(&tan[3].to_le_bytes());
            // original_vertex_index (4)
            out.extend_from_slice(&vertex_index.to_le_bytes());
        }
    }
    out
}

/// Pack ONE page-pool slot's exploded visibility vertices for Gap-B dynamic
/// paging — the bytes that overwrite a reused slot in the cluster render mesh's
/// visibility-data section when a cluster is streamed in.
///
/// `corner_indices` is the slot's per-triangle-corner ORIGINAL vertex indices in
/// triangle order (a cluster's index slice, padded to `page_verts`, exactly as the
/// scene-loader's `build_slot_geometry` lays a slot out). The same
/// `front_face` corner swizzle the full-mesh packer applies is applied here, so
/// the emitted 56-B records are byte-identical to what
/// [`pack_visibility_bytes`] would have produced for these triangles — EXCEPT the
/// `triangle_index` field, which is made slot-relative:
/// `triangle_index = pool_slot * (page_verts/3) + local_triangle`. That matches
/// the value the full-buffer explode assigned this slot (slot `s`'s exploded
/// corners occupy flat indices `[s*page_verts, +page_verts)`, so corner `j`'s
/// triangle is `j/3`), keeping the visibility-resolve's per-triangle corner fetch
/// self-consistent after the slot is overwritten with a different cluster.
///
/// Tangents are the synthetic fallback (the cluster render mesh has no normal-map
/// material ⇒ the full-mesh packer also used synthetic — see `meshes.rs` tangent
/// gating). `out` is cleared + refilled (reuse across streams ⇒ no per-frame
/// allocation). `corner_indices.len()` must equal `page_verts` (a multiple of 3).
pub fn pack_visibility_slot_bytes(
    positions: &[[f32; 3]],
    normals: &[[f32; 3]],
    corner_indices: &[u32],
    pool_slot: usize,
    page_verts: usize,
    front_face: FrontFace,
    out: &mut Vec<u8>,
) {
    out.clear();
    debug_assert_eq!(
        corner_indices.len(),
        page_verts,
        "slot must be page_verts long"
    );
    let corner_order: [usize; 3] = match front_face {
        FrontFace::Cw => [0, 2, 1],
        _ => [0, 1, 2],
    };
    let tris_per_slot = page_verts / 3;
    let base_triangle = pool_slot * tris_per_slot;
    for (local_triangle, tri) in corner_indices.chunks_exact(3).enumerate() {
        let triangle_index = (base_triangle + local_triangle) as u32;
        for &corner in corner_order.iter() {
            let vertex_index = tri[corner];
            let v = vertex_index as usize;
            let pos = positions[v];
            let normal = normals[v];
            let bary = BARYCENTRICS[corner];
            let tan = SYNTHETIC_TANGENT;
            // position (12)
            out.extend_from_slice(&pos[0].to_le_bytes());
            out.extend_from_slice(&pos[1].to_le_bytes());
            out.extend_from_slice(&pos[2].to_le_bytes());
            // triangle_index (4) — slot-relative
            out.extend_from_slice(&triangle_index.to_le_bytes());
            // barycentric (8)
            out.extend_from_slice(&bary[0].to_le_bytes());
            out.extend_from_slice(&bary[1].to_le_bytes());
            // normal (12)
            out.extend_from_slice(&normal[0].to_le_bytes());
            out.extend_from_slice(&normal[1].to_le_bytes());
            out.extend_from_slice(&normal[2].to_le_bytes());
            // tangent (16)
            out.extend_from_slice(&tan[0].to_le_bytes());
            out.extend_from_slice(&tan[1].to_le_bytes());
            out.extend_from_slice(&tan[2].to_le_bytes());
            out.extend_from_slice(&tan[3].to_le_bytes());
            // original_vertex_index (4)
            out.extend_from_slice(&vertex_index.to_le_bytes());
        }
    }
}

/// Transparency geometry — 40 bytes per **original** (non-exploded) vertex,
/// drawn with the index buffer:
/// `position(12) | normal(12) | tangent(16)`.
pub fn pack_transparency_bytes(
    positions: &[[f32; 3]],
    normals: &[[f32; 3]],
    tangents: Option<&[[f32; 4]]>,
    vertex_count: usize,
) -> Vec<u8> {
    let mut out = Vec::with_capacity(vertex_count * 40);
    for (v, normal) in normals.iter().enumerate().take(vertex_count) {
        let pos = positions[v];
        let tan = tangents.map(|t| t[v]).unwrap_or(SYNTHETIC_TANGENT);
        out.extend_from_slice(&pos[0].to_le_bytes());
        out.extend_from_slice(&pos[1].to_le_bytes());
        out.extend_from_slice(&pos[2].to_le_bytes());
        out.extend_from_slice(&normal[0].to_le_bytes());
        out.extend_from_slice(&normal[1].to_le_bytes());
        out.extend_from_slice(&normal[2].to_le_bytes());
        out.extend_from_slice(&tan[0].to_le_bytes());
        out.extend_from_slice(&tan[1].to_le_bytes());
        out.extend_from_slice(&tan[2].to_le_bytes());
        out.extend_from_slice(&tan[3].to_le_bytes());
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    // A 1-triangle mesh; checks the byte layout is exactly as documented (the
    // regression guard locking the packed format).
    fn tri() -> (Vec<[f32; 3]>, Vec<[f32; 3]>, Vec<[f32; 4]>, Vec<u32>) {
        (
            vec![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]],
            vec![[0.0, 0.0, 1.0]; 3],
            vec![[1.0, 0.0, 0.0, 1.0]; 3],
            vec![0, 1, 2],
        )
    }

    #[test]
    fn visibility_layout_is_56_bytes_per_corner() {
        let (p, n, t, i) = tri();
        let bytes = pack_visibility_bytes(&p, &n, Some(&t), &i, FrontFace::Ccw);
        assert_eq!(bytes.len(), 56 * 3, "56 bytes per exploded corner");
        // corner 0: position == p[0]
        let read_f32 = |off: usize| f32::from_le_bytes(bytes[off..off + 4].try_into().unwrap());
        assert_eq!([read_f32(0), read_f32(4), read_f32(8)], [1.0, 2.0, 3.0]);
        // triangle_index (offset 12) == 0; original_vertex_index (offset 52) == 0
        assert_eq!(u32::from_le_bytes(bytes[12..16].try_into().unwrap()), 0);
        assert_eq!(u32::from_le_bytes(bytes[52..56].try_into().unwrap()), 0);
        // corner 1 original_vertex_index (offset 56+52) == 1
        assert_eq!(u32::from_le_bytes(bytes[108..112].try_into().unwrap()), 1);
    }

    #[test]
    fn transparency_layout_is_40_bytes_per_vertex() {
        let (p, n, t, _) = tri();
        let bytes = pack_transparency_bytes(&p, &n, Some(&t), 3);
        assert_eq!(bytes.len(), 40 * 3, "40 bytes per vertex");
        let read_f32 = |off: usize| f32::from_le_bytes(bytes[off..off + 4].try_into().unwrap());
        // vertex 0: position then normal then tangent
        assert_eq!([read_f32(0), read_f32(4), read_f32(8)], [1.0, 2.0, 3.0]);
        assert_eq!([read_f32(12), read_f32(16), read_f32(20)], [0.0, 0.0, 1.0]);
        assert_eq!(read_f32(36), 1.0); // tangent.w
    }

    #[test]
    fn cw_front_face_swizzles_corners_and_barycentrics() {
        let (p, n, t, i) = tri();
        let ccw = pack_visibility_bytes(&p, &n, Some(&t), &i, FrontFace::Ccw);
        let cw = pack_visibility_bytes(&p, &n, Some(&t), &i, FrontFace::Cw);
        // Cw corner order is [0, 2, 1]: slot 1 carries vertex 2 (+ its
        // barycentric), slot 2 carries vertex 1 — i.e. records permuted.
        assert_eq!(&cw[0..56], &ccw[0..56], "slot 0 identical");
        assert_eq!(&cw[56..112], &ccw[112..168], "slot 1 = ccw corner 2");
        assert_eq!(&cw[112..168], &ccw[56..112], "slot 2 = ccw corner 1");
    }

    #[test]
    fn none_tangents_pack_synthetic() {
        let (p, n, _, i) = tri();
        let bytes = pack_visibility_bytes(&p, &n, None, &i, FrontFace::Ccw);
        // corner 0 tangent at offset 36..52 == [0,0,0,1]
        // (pos 12 + triangle_index 4 + barycentric 8 + normal 12 = 36).
        let read_f32 = |off: usize| f32::from_le_bytes(bytes[off..off + 4].try_into().unwrap());
        assert_eq!(
            [read_f32(36), read_f32(40), read_f32(44), read_f32(48)],
            [0.0, 0.0, 0.0, 1.0]
        );
    }

    // ── parity: every field decodes per-corner, and the two packers agree ──────
    //
    // The single-triangle tests above use identical normals/tangents on every
    // vertex, so they can't catch a per-vertex ATTRIBUTE-INDEXING bug (reading
    // the wrong vertex's normal/tangent) or a barycentric mix-up. This uses a
    // 2-triangle quad with DISTINCT per-vertex attributes and decodes every
    // field at every corner, then asserts the visibility + transparency packers
    // produce the SAME (pos, normal, tangent) for each original vertex — the
    // "both front-ends pack through one source" parity the module promises.

    fn rf(b: &[u8], off: usize) -> f32 {
        f32::from_le_bytes(b[off..off + 4].try_into().unwrap())
    }
    fn ru(b: &[u8], off: usize) -> u32 {
        u32::from_le_bytes(b[off..off + 4].try_into().unwrap())
    }
    // Decode one 56-byte visibility corner.
    fn vis_corner(b: &[u8], rec: usize) -> ([f32; 3], u32, [f32; 2], [f32; 3], [f32; 4], u32) {
        let o = rec * 56;
        (
            [rf(b, o), rf(b, o + 4), rf(b, o + 8)],        // position
            ru(b, o + 12),                                 // triangle_index
            [rf(b, o + 16), rf(b, o + 20)],                // barycentric
            [rf(b, o + 24), rf(b, o + 28), rf(b, o + 32)], // normal
            [rf(b, o + 36), rf(b, o + 40), rf(b, o + 44), rf(b, o + 48)], // tangent
            ru(b, o + 52),                                 // original_vertex_index
        )
    }

    #[test]
    fn pack_field_decode_and_visibility_transparency_parity() {
        // Quad: 4 distinct vertices, 2 triangles [0,1,2] + [0,2,3].
        let positions = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [1.0, 1.0, 0.0],
            [0.0, 1.0, 0.0],
        ];
        let normals = vec![
            [0.1, 0.2, 0.3],
            [0.4, 0.5, 0.6],
            [0.7, 0.8, 0.9],
            [-0.1, -0.2, -0.3],
        ];
        let tangents = vec![
            [1.0, 0.0, 0.0, 1.0],
            [0.0, 1.0, 0.0, -1.0],
            [0.0, 0.0, 1.0, 1.0],
            [0.5, 0.5, 0.0, -1.0],
        ];
        let indices = vec![0u32, 1, 2, 0, 2, 3];

        let vis = pack_visibility_bytes(
            &positions,
            &normals,
            Some(&tangents),
            &indices,
            FrontFace::Ccw,
        );
        assert_eq!(vis.len(), 56 * 6, "2 tris × 3 corners");

        // Every corner: position/normal/tangent come from its ORIGINAL vertex,
        // barycentric matches the slot, triangle_index increments.
        for (rec, (tri, corner)) in [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
            .into_iter()
            .enumerate()
        {
            let orig = indices[tri * 3 + corner] as usize;
            let (pos, tri_idx, bary, normal, tangent, ovi) = vis_corner(&vis, rec);
            assert_eq!(pos, positions[orig], "corner {rec} position");
            assert_eq!(
                normal, normals[orig],
                "corner {rec} normal (per-vertex index)"
            );
            assert_eq!(
                tangent, tangents[orig],
                "corner {rec} tangent (per-vertex index)"
            );
            assert_eq!(bary, BARYCENTRICS[corner], "corner {rec} barycentric");
            assert_eq!(tri_idx, tri as u32, "corner {rec} triangle_index");
            assert_eq!(ovi, orig as u32, "corner {rec} original_vertex_index");
        }

        // Transparency packs per ORIGINAL vertex; same pos/normal/tangent.
        let tr = pack_transparency_bytes(&positions, &normals, Some(&tangents), positions.len());
        assert_eq!(tr.len(), 40 * 4);
        for v in 0..positions.len() {
            let o = v * 40;
            let pos = [rf(&tr, o), rf(&tr, o + 4), rf(&tr, o + 8)];
            let normal = [rf(&tr, o + 12), rf(&tr, o + 16), rf(&tr, o + 20)];
            let tangent = [
                rf(&tr, o + 24),
                rf(&tr, o + 28),
                rf(&tr, o + 32),
                rf(&tr, o + 36),
            ];
            // PARITY: the transparency record matches the inputs (and therefore
            // any visibility corner referencing the same original vertex).
            assert_eq!(pos, positions[v], "transparency v{v} position");
            assert_eq!(normal, normals[v], "transparency v{v} normal");
            assert_eq!(tangent, tangents[v], "transparency v{v} tangent");
        }
    }

    // ── Gap-B dynamic paging: slot packer matches the full-mesh packer ─────────
    #[test]
    fn slot_pack_matches_full_packer_except_triangle_index() {
        // 6-vertex, 4-triangle "cluster"; page_verts = 6 (2 triangles/slot) so the
        // slot math is exercised with >1 triangle. Distinct per-vertex normals so a
        // mis-indexing bug shows. Synthetic tangents (the cluster mesh path).
        let positions = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [1.0, 1.0, 0.0],
            [0.0, 1.0, 0.0],
            [2.0, 0.0, 0.0],
            [2.0, 1.0, 0.0],
        ];
        let normals = vec![
            [0.1, 0.0, 0.9],
            [0.2, 0.0, 0.8],
            [0.3, 0.0, 0.7],
            [0.4, 0.0, 0.6],
            [0.5, 0.0, 0.5],
            [0.6, 0.0, 0.4],
        ];
        let page_verts = 6usize; // 2 triangles per slot
                                 // Slot's triangle-order corner indices (one cluster's two triangles).
        let slot_indices = vec![0u32, 1, 2, 1, 4, 5];

        // Slot 0 must be byte-identical to the full-mesh packer (synthetic tangents,
        // triangle_index base 0).
        let full = pack_visibility_bytes(&positions, &normals, None, &slot_indices, FrontFace::Ccw);
        let mut slot0 = Vec::new();
        pack_visibility_slot_bytes(
            &positions,
            &normals,
            &slot_indices,
            0,
            page_verts,
            FrontFace::Ccw,
            &mut slot0,
        );
        assert_eq!(slot0, full, "slot 0 is byte-identical to the full packer");
        assert_eq!(slot0.len(), 56 * page_verts);

        // Slot 3 differs ONLY in triangle_index: base = 3 * (6/3) = 6, so the two
        // triangles are 6 and 7; every other byte equals slot 0's.
        let mut slot3 = Vec::new();
        pack_visibility_slot_bytes(
            &positions,
            &normals,
            &slot_indices,
            3,
            page_verts,
            FrontFace::Ccw,
            &mut slot3,
        );
        for rec in 0..page_verts {
            let o = rec * 56;
            // triangle_index (offset 12) is slot-relative: 6 + rec/3.
            assert_eq!(
                u32::from_le_bytes(slot3[o + 12..o + 16].try_into().unwrap()),
                6 + (rec / 3) as u32,
                "slot 3 record {rec} triangle_index"
            );
            // All other bytes (before + after the 4-byte triangle_index) match slot 0.
            assert_eq!(slot3[o..o + 12], slot0[o..o + 12], "record {rec} pos");
            assert_eq!(
                slot3[o + 16..o + 56],
                slot0[o + 16..o + 56],
                "record {rec} rest"
            );
        }

        // out is reused (cleared) — a second pack of a smaller-base slot leaves no
        // stale tail.
        pack_visibility_slot_bytes(
            &positions,
            &normals,
            &slot_indices,
            0,
            page_verts,
            FrontFace::Ccw,
            &mut slot3,
        );
        assert_eq!(slot3, slot0, "reused buffer cleared + refilled correctly");
    }
}