myth_render 0.3.0

Core rendering system for the Myth engine (render graph, pipeline, GPU management).
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! Unified Pipeline Cache
//!
//! Central owner of **all** `wgpu::RenderPipeline` and `wgpu::ComputePipeline`
//! instances. Pipelines are stored in contiguous `Vec`s and addressed through
//! lightweight [`RenderPipelineId`] / [`ComputePipelineId`] handles.
//!
//! # Two-Level Caching (L1 / L2)
//!
//! Material-driven geometry pipelines benefit from the existing **L1 fast cache**
//! (`FastPipelineKey` → `RenderPipelineId`) that avoids rebuilding the full
//! descriptor key every frame. L1 keys are cheap `Copy` structs based on
//! resource handles and version counters.
//!
//! All pipeline families share the **L2 canonical cache** keyed by the full
//! state descriptor (`GraphicsPipelineKey`, `FullscreenPipelineKey`,
//! `ComputePipelineKey`, `SimpleGeometryPipelineKey`). A full-state hash is computed
//! only on L1 miss (or for families without L1).
//!
//! # Shader Modules
//!
//! Shader module caching has been extracted into [`ShaderManager`] to decouple
//! concerns. `PipelineCache` depends on `ShaderManager` for module lookup but
//! does not own the module cache.
//!
//! [`ShaderManager`]: super::shader_manager::ShaderManager

#[cfg(feature = "debug_view")]
use myth_scene::DebugViewMode;
use rustc_hash::FxHashMap;
use smallvec::SmallVec;

use crate::core::BindGroupContext;
use crate::core::gpu::{GpuGlobalState, GpuMaterial, Tracked};
use crate::graph::extracted::SceneFeatures;
use crate::pipeline::pipeline_id::{ComputePipelineId, RenderPipelineId};
use crate::pipeline::pipeline_key::{
    ComputePipelineKey, FullscreenPipelineKey, GraphicsPipelineKey, PipelineFlags,
    SimpleGeometryPipelineKey, fx_hash_key,
};
use crate::pipeline::shader_gen::ShaderCompilationOptions;
use crate::pipeline::shader_manager::{ShaderManager, ShaderSource};
use crate::pipeline::vertex::GeneratedVertexLayout;
use myth_assets::{GeometryHandle, MaterialHandle};
use myth_resources::uniforms::{clustered_lighting_structs_wgsl, scene_lighting_structs_wgsl};

// ─── L1 Fast Keys ────────────────────────────────────────────────────────────

/// L1 fast key for material-driven geometry pipelines.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub struct FastPipelineKey {
    pub material_handle: MaterialHandle,
    pub material_version: u64,
    pub geometry_handle: GeometryHandle,
    pub geometry_version: u64,
    pub instance_variants: u32,
    pub global_state_id: u32,
    pub scene_variants: SceneFeatures,
    pub taa_enabled: bool,
    pub pipeline_settings_version: u64,
    #[cfg(feature = "debug_view")]
    pub debug_view_mode: DebugViewMode,
}

/// L1 fast key for shadow depth-only pipelines.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub struct FastShadowPipelineKey {
    pub material_handle: MaterialHandle,
    pub material_version: u64,
    pub geometry_handle: GeometryHandle,
    pub geometry_version: u64,
    pub instance_variants: u32,
    pub pipeline_settings_version: u64,
}

// ─── Pipeline Cache ──────────────────────────────────────────────────────────

/// Central pipeline storage and deduplication cache.
///
/// Alongside every compiled pipeline, the cache can optionally store the
/// pipeline's [`Tracked<wgpu::BindGroupLayout>`] array.  This allows
/// downstream code (e.g. RDG pass nodes) to look up layouts by pipeline
/// ID without holding onto layout objects themselves, enabling stateless
/// pass-node designs.
pub struct PipelineCache {
    // ---- Storage (contiguous, indexed by Id) ----
    render_pipelines: Vec<wgpu::RenderPipeline>,
    compute_pipelines: Vec<wgpu::ComputePipeline>,

    /// Per-render-pipeline tracked bind-group layouts (parallel to `render_pipelines`).
    /// An entry is `None` if the caller did not register layouts for that pipeline.
    render_layouts: Vec<Option<SmallVec<[Tracked<wgpu::BindGroupLayout>; 4]>>>,
    /// Per-compute-pipeline tracked bind-group layouts.
    compute_layouts: Vec<Option<SmallVec<[Tracked<wgpu::BindGroupLayout>; 4]>>>,

    // ---- L2 canonical lookups (full-state hash → Id) ----
    graphics_lookup: FxHashMap<u64, RenderPipelineId>,
    fullscreen_lookup: FxHashMap<u64, RenderPipelineId>,
    simple_geometry_lookup: FxHashMap<u64, RenderPipelineId>,
    compute_lookup: FxHashMap<u64, ComputePipelineId>,

    // ---- L1 fast lookups (handle+version → Id) ----
    fast_cache: FxHashMap<FastPipelineKey, RenderPipelineId>,
    fast_shadow_cache: FxHashMap<FastShadowPipelineKey, RenderPipelineId>,
}

impl Default for PipelineCache {
    fn default() -> Self {
        Self::new()
    }
}

impl PipelineCache {
    #[must_use]
    pub fn new() -> Self {
        Self {
            render_pipelines: Vec::with_capacity(64),
            compute_pipelines: Vec::with_capacity(8),
            render_layouts: Vec::with_capacity(64),
            compute_layouts: Vec::with_capacity(8),
            graphics_lookup: FxHashMap::default(),
            fullscreen_lookup: FxHashMap::default(),
            simple_geometry_lookup: FxHashMap::default(),
            compute_lookup: FxHashMap::default(),
            fast_cache: FxHashMap::default(),
            fast_shadow_cache: FxHashMap::default(),
        }
    }

    // ── Pipeline Retrieval (execute-phase, O(1)) ─────────────────────────────

    /// Retrieve a render pipeline by handle. **Panics** if the id is invalid.
    #[inline]
    #[must_use]
    pub fn get_render_pipeline(&self, id: RenderPipelineId) -> &wgpu::RenderPipeline {
        &self.render_pipelines[id.index()]
    }

    /// Retrieve a compute pipeline by handle. **Panics** if the id is invalid.
    #[inline]
    #[must_use]
    pub fn get_compute_pipeline(&self, id: ComputePipelineId) -> &wgpu::ComputePipeline {
        &self.compute_pipelines[id.index()]
    }

    // ── Layout Registration & Retrieval ──────────────────────────────────────

    /// Associate tracked bind-group layouts with an existing render pipeline.
    ///
    /// Call this immediately after `get_or_create_*` to enable downstream code
    /// to retrieve layouts via [`get_tracked_layout`](Self::get_tracked_layout)
    /// using only the [`RenderPipelineId`].
    pub fn register_render_layouts(
        &mut self,
        id: RenderPipelineId,
        layouts: SmallVec<[Tracked<wgpu::BindGroupLayout>; 4]>,
    ) {
        let idx = id.index();
        if idx >= self.render_layouts.len() {
            self.render_layouts.resize_with(idx + 1, || None);
        }
        self.render_layouts[idx] = Some(layouts);
    }

    /// Associate tracked bind-group layouts with an existing compute pipeline.
    pub fn register_compute_layouts(
        &mut self,
        id: ComputePipelineId,
        layouts: SmallVec<[Tracked<wgpu::BindGroupLayout>; 4]>,
    ) {
        let idx = id.index();
        if idx >= self.compute_layouts.len() {
            self.compute_layouts.resize_with(idx + 1, || None);
        }
        self.compute_layouts[idx] = Some(layouts);
    }

    /// Retrieve a tracked bind-group layout for a render pipeline.
    ///
    /// **Panics** if no layouts were registered for `id`, or if `group_index`
    /// is out of range.
    #[inline]
    #[must_use]
    pub fn get_tracked_layout(
        &self,
        id: RenderPipelineId,
        group_index: usize,
    ) -> &Tracked<wgpu::BindGroupLayout> {
        self.render_layouts[id.index()]
            .as_ref()
            .expect("No layouts registered for this pipeline")
            .get(group_index)
            .expect("group_index out of range")
    }

    /// Retrieve a tracked bind-group layout for a compute pipeline.
    #[inline]
    #[must_use]
    pub fn get_tracked_compute_layout(
        &self,
        id: ComputePipelineId,
        group_index: usize,
    ) -> &Tracked<wgpu::BindGroupLayout> {
        self.compute_layouts[id.index()]
            .as_ref()
            .expect("No layouts registered for this compute pipeline")
            .get(group_index)
            .expect("group_index out of range")
    }

    // ── Cache Invalidation ───────────────────────────────────────────────────

    /// Clears **all** cached pipelines.
    ///
    /// The `ShaderManager` module cache is *not* affected — shader source code
    /// is independent of these settings.
    #[deprecated(note = "Prefer targeted invalidation via version increments")]
    pub fn clear(&mut self) {
        self.render_pipelines.clear();
        self.compute_pipelines.clear();
        self.graphics_lookup.clear();
        self.fullscreen_lookup.clear();
        self.simple_geometry_lookup.clear();
        self.compute_lookup.clear();
        self.fast_cache.clear();
        self.fast_shadow_cache.clear();
    }

    // ── L1 Fast Cache (material geometry pipelines) ──────────────────────────

    #[must_use]
    pub fn get_pipeline_fast(&self, fast_key: FastPipelineKey) -> Option<RenderPipelineId> {
        self.fast_cache.get(&fast_key).copied()
    }

    pub fn insert_pipeline_fast(&mut self, fast_key: FastPipelineKey, id: RenderPipelineId) {
        self.fast_cache.insert(fast_key, id);
    }

    #[must_use]
    pub fn get_shadow_pipeline_fast(
        &self,
        fast_key: FastShadowPipelineKey,
    ) -> Option<RenderPipelineId> {
        self.fast_shadow_cache.get(&fast_key).copied()
    }

    pub fn insert_shadow_pipeline_fast(
        &mut self,
        fast_key: FastShadowPipelineKey,
        id: RenderPipelineId,
    ) {
        self.fast_shadow_cache.insert(fast_key, id);
    }

    // ── L2 Canonical: Material Geometry Pipeline ─────────────────────────────

    /// Look up or create a material-driven geometry pipeline.
    ///
    /// This is the main entry point for `SceneCullPass`.
    #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
    pub fn get_or_create_graphics(
        &mut self,
        device: &wgpu::Device,
        shader_manager: &mut ShaderManager,
        shader_source: ShaderSource<'_>,
        canonical_key: &GraphicsPipelineKey,
        options: &ShaderCompilationOptions,
        vertex_layout: &GeneratedVertexLayout,
        gpu_material: &GpuMaterial,
        object_bind_group: &BindGroupContext,
        gpu_world: &GpuGlobalState,
        screen_bind_group_layout: &wgpu::BindGroupLayout,
    ) -> RenderPipelineId {
        let hash = fx_hash_key(&canonical_key);
        if let Some(&id) = self.graphics_lookup.get(&hash) {
            return id;
        }

        // Compile shader via ShaderManager
        let binding_code = format!(
            "{}\n{}\n{}",
            &gpu_world.binding_wgsl, &gpu_material.binding_wgsl, &object_bind_group.binding_wgsl
        );

        let mut opts = options.clone();
        opts.inject_code("vertex_input_code", &vertex_layout.vertex_input_code);
        opts.inject_code("binding_code", binding_code);
        opts.inject_code("scene_lighting_structs", scene_lighting_structs_wgsl());
        opts.inject_code(
            "clustered_lighting_structs",
            clustered_lighting_structs_wgsl(),
        );

        let (shader_module, _code_hash) =
            shader_manager.get_or_compile(device, shader_source, &opts);

        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Render Pipeline Layout"),
            bind_group_layouts: &[
                Some(&gpu_world.layout),
                Some(&gpu_material.layout),
                Some(&object_bind_group.layout),
                Some(screen_bind_group_layout),
            ],
            immediate_size: 0,
        });

        let vertex_buffers_layout: Vec<_> =
            vertex_layout.buffers.iter().map(|l| l.as_wgpu()).collect();

        let color_targets: Vec<Option<wgpu::ColorTargetState>> = canonical_key
            .color_targets
            .iter()
            .map(|target| {
                Some(wgpu::ColorTargetState {
                    format: target.format,
                    blend: target.blend.as_ref().map(|bk| wgpu::BlendState {
                        color: wgpu::BlendComponent {
                            src_factor: bk.color.src_factor,
                            dst_factor: bk.color.dst_factor,
                            operation: bk.color.operation,
                        },
                        alpha: wgpu::BlendComponent {
                            src_factor: bk.alpha.src_factor,
                            dst_factor: bk.alpha.dst_factor,
                            operation: bk.alpha.operation,
                        },
                    }),
                    write_mask: wgpu::ColorWrites::from_bits_retain(target.write_mask),
                })
            })
            .collect();

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Scene Render Pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: shader_module,
                entry_point: Some("vs_main"),
                buffers: &vertex_buffers_layout,
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader_module,
                entry_point: Some("fs_main"),
                targets: &color_targets,
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: canonical_key.topology,
                front_face: canonical_key.front_face,
                cull_mode: canonical_key.cull_mode,
                ..Default::default()
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: canonical_key.depth_format,
                depth_write_enabled: Some(canonical_key.flags.contains(PipelineFlags::DEPTH_WRITE)),
                depth_compare: Some(canonical_key.depth_compare),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: canonical_key.sample_count,
                mask: !0,
                alpha_to_coverage_enabled: canonical_key
                    .flags
                    .contains(PipelineFlags::ALPHA_TO_COVERAGE),
            },
            multiview_mask: None,
            cache: None,
        });

        let id = self.push_render_pipeline(pipeline);
        self.graphics_lookup.insert(hash, id);
        id
    }

    // ── L2 Canonical: Fullscreen / Post-Process Pipeline ─────────────────────

    /// Look up or create a fullscreen / post-processing render pipeline.
    ///
    /// The caller must supply the pre-created `pipeline_layout` because
    /// bind-group layouts vary widely across post-processing passes.
    ///
    /// Primitive state is hardcoded to standard fullscreen-triangle values:
    /// `TriangleList`, no culling, CCW, no vertex buffers.
    pub fn get_or_create_fullscreen(
        &mut self,
        device: &wgpu::Device,
        shader_module: &wgpu::ShaderModule,
        pipeline_layout: &wgpu::PipelineLayout,
        canonical_key: &FullscreenPipelineKey,
        label: &str,
    ) -> RenderPipelineId {
        let hash = fx_hash_key(canonical_key);
        if let Some(&id) = self.fullscreen_lookup.get(&hash) {
            return id;
        }

        // Rebuild wgpu types from key mirrors
        let color_targets: Vec<Option<wgpu::ColorTargetState>> = canonical_key
            .color_targets
            .iter()
            .map(|ct| {
                Some(wgpu::ColorTargetState {
                    format: ct.format,
                    blend: ct.blend.map(|bk| wgpu::BlendState {
                        color: wgpu::BlendComponent {
                            src_factor: bk.color.src_factor,
                            dst_factor: bk.color.dst_factor,
                            operation: bk.color.operation,
                        },
                        alpha: wgpu::BlendComponent {
                            src_factor: bk.alpha.src_factor,
                            dst_factor: bk.alpha.dst_factor,
                            operation: bk.alpha.operation,
                        },
                    }),
                    write_mask: wgpu::ColorWrites::from_bits_truncate(ct.write_mask),
                })
            })
            .collect();

        let depth_stencil = canonical_key
            .depth_stencil
            .map(|dk| wgpu::DepthStencilState {
                format: dk.format,
                depth_write_enabled: dk.depth_write_enabled,
                depth_compare: dk.depth_compare,
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState {
                        compare: dk.stencil.front.compare,
                        fail_op: dk.stencil.front.fail_op,
                        depth_fail_op: dk.stencil.front.depth_fail_op,
                        pass_op: dk.stencil.front.pass_op,
                    },
                    back: wgpu::StencilFaceState {
                        compare: dk.stencil.back.compare,
                        fail_op: dk.stencil.back.fail_op,
                        depth_fail_op: dk.stencil.back.depth_fail_op,
                        pass_op: dk.stencil.back.pass_op,
                    },
                    read_mask: dk.stencil.read_mask,
                    write_mask: dk.stencil.write_mask,
                },
                bias: wgpu::DepthBiasState {
                    constant: dk.bias.constant,
                    slope_scale: f32::from_bits(dk.bias.slope_scale_bits),
                    clamp: f32::from_bits(dk.bias.clamp_bits),
                },
            });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(pipeline_layout),
            vertex: wgpu::VertexState {
                module: shader_module,
                entry_point: Some("vs_main"),
                buffers: &[],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader_module,
                entry_point: Some("fs_main"),
                targets: &color_targets,
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                ..Default::default()
            },
            depth_stencil,
            multisample: wgpu::MultisampleState {
                count: canonical_key.multisample.count,
                mask: canonical_key.multisample.mask,
                alpha_to_coverage_enabled: canonical_key.multisample.alpha_to_coverage_enabled,
            },
            multiview_mask: None,
            cache: None,
        });

        let id = self.push_render_pipeline(pipeline);
        self.fullscreen_lookup.insert(hash, id);
        id
    }

    // ── L2 Canonical: Simple Geometry Pipeline (Prepass, Shadow) ──────────

    /// Look up or create a simplified geometry pipeline (prepass or shadow).
    ///
    /// These passes render actual meshes with vertex input but skip complex
    /// material/lighting state. The caller supplies pre-compiled shader module,
    /// pipeline layout, and vertex buffer layouts.
    pub fn get_or_create_simple_geometry(
        &mut self,
        device: &wgpu::Device,
        shader_module: &wgpu::ShaderModule,
        pipeline_layout: &wgpu::PipelineLayout,
        canonical_key: &SimpleGeometryPipelineKey,
        label: &str,
        vertex_buffers: &[wgpu::VertexBufferLayout<'_>],
    ) -> RenderPipelineId {
        let hash = fx_hash_key(canonical_key);
        if let Some(&id) = self.simple_geometry_lookup.get(&hash) {
            return id;
        }

        // Rebuild wgpu types from key mirrors
        let color_targets: Vec<Option<wgpu::ColorTargetState>> = canonical_key
            .color_targets
            .iter()
            .map(|ct| {
                Some(wgpu::ColorTargetState {
                    format: ct.format,
                    blend: ct.blend.map(|bk| wgpu::BlendState {
                        color: wgpu::BlendComponent {
                            src_factor: bk.color.src_factor,
                            dst_factor: bk.color.dst_factor,
                            operation: bk.color.operation,
                        },
                        alpha: wgpu::BlendComponent {
                            src_factor: bk.alpha.src_factor,
                            dst_factor: bk.alpha.dst_factor,
                            operation: bk.alpha.operation,
                        },
                    }),
                    write_mask: wgpu::ColorWrites::from_bits_truncate(ct.write_mask),
                })
            })
            .collect();

        let dk = &canonical_key.depth_stencil;
        let depth_stencil = Some(wgpu::DepthStencilState {
            format: dk.format,
            depth_write_enabled: dk.depth_write_enabled,
            depth_compare: dk.depth_compare,
            stencil: wgpu::StencilState {
                front: wgpu::StencilFaceState {
                    compare: dk.stencil.front.compare,
                    fail_op: dk.stencil.front.fail_op,
                    depth_fail_op: dk.stencil.front.depth_fail_op,
                    pass_op: dk.stencil.front.pass_op,
                },
                back: wgpu::StencilFaceState {
                    compare: dk.stencil.back.compare,
                    fail_op: dk.stencil.back.fail_op,
                    depth_fail_op: dk.stencil.back.depth_fail_op,
                    pass_op: dk.stencil.back.pass_op,
                },
                read_mask: dk.stencil.read_mask,
                write_mask: dk.stencil.write_mask,
            },
            bias: wgpu::DepthBiasState {
                constant: dk.bias.constant,
                slope_scale: f32::from_bits(dk.bias.slope_scale_bits),
                clamp: f32::from_bits(dk.bias.clamp_bits),
            },
        });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some(label),
            layout: Some(pipeline_layout),
            vertex: wgpu::VertexState {
                module: shader_module,
                entry_point: Some("vs_main"),
                buffers: vertex_buffers,
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader_module,
                entry_point: Some("fs_main"),
                targets: &color_targets,
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: canonical_key.topology,
                front_face: canonical_key.front_face,
                cull_mode: canonical_key.cull_mode,
                ..Default::default()
            },
            depth_stencil,
            multisample: wgpu::MultisampleState {
                count: canonical_key.sample_count,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache: None,
        });

        let id = self.push_render_pipeline(pipeline);
        self.simple_geometry_lookup.insert(hash, id);
        id
    }

    // ── L2 Canonical: Compute Pipeline ───────────────────────────────────────

    /// Look up or create a compute pipeline.
    pub fn get_or_create_compute(
        &mut self,
        device: &wgpu::Device,
        shader_module: &wgpu::ShaderModule,
        pipeline_layout: &wgpu::PipelineLayout,
        canonical_key: &ComputePipelineKey,
        compilation_options: &wgpu::PipelineCompilationOptions<'_>,
        label: &str,
    ) -> ComputePipelineId {
        let hash = fx_hash_key(canonical_key);
        if let Some(&id) = self.compute_lookup.get(&hash) {
            return id;
        }

        let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some(label),
            layout: Some(pipeline_layout),
            module: shader_module,
            entry_point: Some("main"),
            compilation_options: compilation_options.clone(),
            cache: None,
        });

        let id = self.push_compute_pipeline(pipeline);
        self.compute_lookup.insert(hash, id);
        id
    }

    // ── Stats ────────────────────────────────────────────────────────────────

    /// Number of cached render pipelines.
    #[must_use]
    pub fn render_pipeline_count(&self) -> usize {
        self.render_pipelines.len()
    }

    /// Number of cached compute pipelines.
    #[must_use]
    pub fn compute_pipeline_count(&self) -> usize {
        self.compute_pipelines.len()
    }

    // ── Internal helpers ─────────────────────────────────────────────────────

    fn push_render_pipeline(&mut self, pipeline: wgpu::RenderPipeline) -> RenderPipelineId {
        let id = RenderPipelineId(self.render_pipelines.len() as u32);
        self.render_pipelines.push(pipeline);
        self.render_layouts.push(None);
        id
    }

    fn push_compute_pipeline(&mut self, pipeline: wgpu::ComputePipeline) -> ComputePipelineId {
        let id = ComputePipelineId(self.compute_pipelines.len() as u32);
        self.compute_pipelines.push(pipeline);
        self.compute_layouts.push(None);
        id
    }
}