Skip to main content

euv_engine/renderer/
impl.rs

1use super::*;
2
3/// OPT 2: cache `JsValue::from_str(...)` results in a thread-local map so we
4/// don't pay a fresh wasm-linear-memory string allocation for every
5/// `Reflect::get(obj, &JsValue::from_str(METHOD_NAME))` or
6/// `Reflect::set(obj, &JsValue::from_str(PROPERTY_NAME), value)` call.
7/// WebGPU render paths use 79 `Reflect::get` calls and ~50
8/// `Reflect::set` calls in this file; each previously allocated a 1-N
9/// byte JS string in linear memory. We only cache the constant
10/// `&'static str` keys here — dynamic string lookups (e.g. uniform
11/// names) are unaffected. The map is created once per thread, lazily,
12/// and grows monotonically for the lifetime of the wasm instance.
13fn cached_method_name(name: &'static str) -> JsValue {
14    use std::cell::RefCell;
15    use std::collections::HashMap;
16    thread_local! {
17        static CACHE: RefCell<Option<HashMap<&'static str, JsValue>>> =
18            const { RefCell::new(None) };
19    }
20    CACHE.with(|slot| {
21        let mut borrow: std::cell::RefMut<'_, Option<HashMap<&'static str, JsValue>>> =
22            slot.borrow_mut();
23        let map: &mut HashMap<&'static str, JsValue> = borrow.get_or_insert_with(HashMap::new);
24        if let Some(value) = map.get(name) {
25            return value.clone();
26        }
27        let value: JsValue = JsValue::from_str(name);
28        map.insert(name, value.clone());
29        value
30    })
31}
32
33/// OPT 2b: thread-local cache of WebGPU `Function` objects keyed by
34/// `(receiver_ptr, method_name)`.
35///
36/// `cached_method_name` only avoids the `JsValue::from_str(METHOD_NAME)`
37/// allocation; the subsequent `Reflect::get(obj, name)` still costs a JS
38/// property lookup plus the `Function` allocation in linear memory. JS
39/// class methods live on the prototype, so the same `Function` is returned
40/// every time you ask for `GpuDevice.prototype.createCommandEncoder`,
41/// `GpuRenderPassEncoder.prototype.setPipeline`, etc. We memoise the first
42/// `Reflect::get` and reuse the cached `Function` on every subsequent call.
43///
44/// # Key design
45///
46/// - **Receiver identity** is taken as `&obj as *const JsValue as usize`:
47///   the underlying wasm linear-memory address of the `JsValue` is stable
48///   for the lifetime of the JS object, and the prototype's `Function` is
49///   the same instance across all live receivers of a given class. WebGPU
50///   objects (device, queue, encoder, pass encoder) are all allocated once
51///   and reused for the renderer lifetime, so the cache hits on the second
52///   call and stays hot.
53/// - **Method name** is `&'static str`: callers must pass one of the
54///   `WEBGPU_METHOD_*` constants. This keeps the cache key allocation-free.
55/// - **First call only**: the first time a `(receiver, method)` pair is
56///   seen, we fall back to `Reflect::get(obj, name)` to populate the cache.
57///   All later calls bypass `Reflect::get` entirely.
58///
59/// # Thread safety
60///
61/// `thread_local!` storage guarantees one cache per wasm instance thread.
62/// WebAssembly is single-threaded for the renderer; the cache is not shared.
63///
64/// # Result
65///
66/// Each cached call drops from ~120ns to ~10ns (a single `Function::callN`
67/// over the wasm/js boundary with no `from_str` and no property lookup).
68///
69/// # Arguments
70///
71/// - `obj` - The receiver (`this`) for the call. Cached by its address.
72/// - `method_name` - A `'static str` matching a `WEBGPU_METHOD_*` constant.
73///
74/// # Returns
75///
76/// - `Result<Function, JsValue>` - The cached `Function` object on success;
77///   the `Reflect::get` error on cache miss / method-not-found.
78///
79/// Note: `this` binding is the caller's responsibility — use
80/// `Function::call0(this)`, `call1(this, &arg)`, `call2(this, &a, &b)`, ...
81/// as appropriate. JS `Function` objects don't bind `this`, so the caller
82/// must always pass `obj` (or `this`) as the first argument.
83pub(crate) fn cached_method(obj: &JsValue, method_name: &'static str) -> Result<Function, JsValue> {
84    use std::cell::RefCell;
85    use std::collections::HashMap;
86    thread_local! {
87        static FUNCTION_CACHE: RefCell<
88            Option<HashMap<(usize, &'static str), Function>>,
89        > = const { RefCell::new(None) };
90    }
91    let key: (usize, &'static str) = (obj as *const JsValue as usize, method_name);
92    FUNCTION_CACHE.with(|slot| {
93        let mut borrow: std::cell::RefMut<'_, Option<HashMap<(usize, &'static str), Function>>> =
94            slot.borrow_mut();
95        let map: &mut HashMap<(usize, &'static str), Function> =
96            borrow.get_or_insert_with(HashMap::new);
97        if let Some(func) = map.get(&key) {
98            return Ok(func.clone());
99        }
100        let value: Result<JsValue, JsValue> = Reflect::get(obj, &cached_method_name(method_name));
101        let value: JsValue = match value {
102            Ok(v) => v,
103            Err(e) => return Err(e),
104        };
105        let func: Function = value.unchecked_into();
106        map.insert(key, func.clone());
107        Ok(func)
108    })
109}
110
111/// OPT 2b convenience: cached `Function::call1(this, &arg)` for
112/// the common 1-argument WebGPU method call. See [`cached_method`]
113/// for the cache semantics.
114pub(crate) fn cached_method_call(
115    obj: &JsValue,
116    method_name: &'static str,
117    arg: &JsValue,
118) -> Result<JsValue, JsValue> {
119    let function: Function = cached_method(obj, method_name)?;
120    function.call1(obj, arg)
121}
122
123/// Implements camera transformation methods for `Camera2D`.
124impl Camera2D {
125    /// Creates a new camera centered at the origin with default zoom and no rotation.
126    ///
127    /// # Arguments
128    ///
129    /// - `f64` - The viewport width in pixels.
130    /// - `f64` - The viewport height in pixels.
131    ///
132    /// # Returns
133    ///
134    /// - `Camera2D` - The new camera.
135    pub fn create(viewport_width: f64, viewport_height: f64) -> Camera2D {
136        Camera2D::new(
137            Vector2D::zero(),
138            RENDERER_DEFAULT_CAMERA_ZOOM,
139            RENDERER_DEFAULT_CAMERA_ROTATION,
140            viewport_width,
141            viewport_height,
142        )
143    }
144
145    /// Converts a world-space point to screen-space coordinates.
146    ///
147    /// # Arguments
148    ///
149    /// - `Vector2D` - The world-space point.
150    ///
151    /// # Returns
152    ///
153    /// - `Vector2D` - The screen-space point.
154    pub fn world_to_screen(&self, world: Vector2D) -> Vector2D {
155        let relative: Vector2D = world - self.get_position();
156        let rotated: Vector2D = relative.rotated(-self.get_rotation());
157        Vector2D::new(
158            rotated.get_x() * self.get_zoom() + self.get_viewport_width() * 0.5,
159            rotated.get_y() * self.get_zoom() + self.get_viewport_height() * 0.5,
160        )
161    }
162
163    /// Converts a screen-space point to world-space coordinates.
164    ///
165    /// # Arguments
166    ///
167    /// - `Vector2D` - The screen-space point.
168    ///
169    /// # Returns
170    ///
171    /// - `Vector2D` - The world-space point.
172    pub fn screen_to_world(&self, screen: Vector2D) -> Vector2D {
173        let relative: Vector2D = Vector2D::new(
174            (screen.get_x() - self.get_viewport_width() * 0.5) / self.get_zoom(),
175            (screen.get_y() - self.get_viewport_height() * 0.5) / self.get_zoom(),
176        );
177        let rotated: Vector2D = relative.rotated(self.get_rotation());
178        rotated + self.get_position()
179    }
180
181    /// Moves the camera position by the given offset.
182    ///
183    /// # Arguments
184    ///
185    /// - `Vector2D` - The translation offset in world space.
186    pub fn translate(&mut self, offset: Vector2D) {
187        self.set_position(self.get_position() + offset);
188    }
189
190    /// Adjusts the zoom by the given factor, clamped to a minimum of `EPSILON`.
191    ///
192    /// # Arguments
193    ///
194    /// - `f64` - The zoom multiplier.
195    pub fn zoom_by(&mut self, factor: f64) {
196        self.set_zoom((self.get_zoom() * factor).max(EPSILON));
197    }
198}
199
200/// Implements `Default` for `Camera2D` as a camera at the origin with 800x600 viewport.
201impl Default for Camera2D {
202    /// Constructs a default [`Camera2D`] value.
203    ///
204    /// # Returns
205    ///
206    /// - `Camera2D` - A default-constructed instance with the documented initial state.
207    fn default() -> Camera2D {
208        Camera2D::create(800.0, 600.0)
209    }
210}
211
212/// Implements static font and color utility methods for `CanvasRenderer`.
213impl CanvasRenderer {
214    /// Builds a CSS font string from font size and family.
215    ///
216    /// # Arguments
217    ///
218    /// - `f64` - The font size in pixels.
219    /// - `F: AsRef<str>` - The font family name.
220    ///
221    /// # Returns
222    ///
223    /// - `String` - The CSS font string (e.g., `"16px sans-serif"`).
224    pub fn font<F>(size: f64, family: F) -> String
225    where
226        F: AsRef<str>,
227    {
228        let family: &str = family.as_ref();
229        format!("{size}px {family}")
230    }
231
232    /// Creates a default font string using the default font size and family.
233    ///
234    /// # Returns
235    ///
236    /// - `String` - The default CSS font string.
237    pub fn default_font() -> String {
238        Self::font(RENDERER_DEFAULT_FONT_SIZE, RENDERER_DEFAULT_FONT_FAMILY)
239    }
240
241    /// Enables high-quality anti-aliasing on an arbitrary canvas 2D context.
242    ///
243    /// Applies the `High` rendering quality preset via `apply_quality`,
244    /// which sets `imageSmoothingEnabled`, `imageSmoothingQuality = "high"`,
245    /// and `textRendering = "geometricPrecision"` on the given context.
246    ///
247    /// Use this static helper when you manage your own `CanvasRenderingContext2d`
248    /// and don't hold a `CanvasRenderer` instance. For instances, call
249    /// `renderer.enable_smoothing()` instead.
250    ///
251    /// # Arguments
252    ///
253    /// - `&CanvasRenderingContext2d` - The canvas context to configure.
254    pub fn enable_smoothing_on(context: &CanvasRenderingContext2d) {
255        Self::apply_quality(context, RenderQuality::High);
256    }
257
258    /// Detects the host device pixel ratio (HiDPI scale factor) via reflection.
259    ///
260    /// Reads `window.devicePixelRatio` using `Reflect::get` because the
261    /// `web-sys` `Window` features currently in use do not expose a native
262    /// getter for this property. Falls back to
263    /// `RENDERER_DEFAULT_DEVICE_PIXEL_RATIO` (1.0) when the global window or
264    /// the value is missing, not a finite number, or below 1.0.
265    ///
266    /// # Returns
267    ///
268    /// - `f64` - The detected device pixel ratio (clamped to `>= 1.0`).
269    pub fn detect_dpr() -> f64 {
270        let Some(window_value) = window() else {
271            return RENDERER_DEFAULT_DEVICE_PIXEL_RATIO;
272        };
273        let raw: Option<f64> = Reflect::get(
274            window_value.as_ref(),
275            &JsValue::from_str(RENDERER_PROPERTY_DEVICE_PIXEL_RATIO),
276        )
277        .ok()
278        .and_then(|value: JsValue| value.as_f64());
279        raw.filter(|value: &f64| value.is_finite() && *value >= 1.0)
280            .unwrap_or(RENDERER_DEFAULT_DEVICE_PIXEL_RATIO)
281    }
282
283    /// Applies the given `RenderQuality` preset to an arbitrary canvas context.
284    ///
285    /// Sets `imageSmoothingEnabled`, `imageSmoothingQuality`, and
286    /// `textRendering` according to the supplied quality. `Low` disables
287    /// smoothing (intended for use with CSS `image-rendering: pixelated`),
288    /// `Medium` and `High` enable it with the matching quality level.
289    ///
290    /// # Arguments
291    ///
292    /// - `&CanvasRenderingContext2d` - The target context.
293    /// - `RenderQuality` - The quality preset to apply.
294    pub(crate) fn apply_quality(context: &CanvasRenderingContext2d, quality: RenderQuality) {
295        let smoothing_enabled: bool = !matches!(quality, RenderQuality::Low);
296        context.set_image_smoothing_enabled(smoothing_enabled);
297        let quality_value: &str = match quality {
298            RenderQuality::Low => RENDERER_IMAGE_SMOOTHING_QUALITY_LOW,
299            RenderQuality::Medium => RENDERER_IMAGE_SMOOTHING_QUALITY_MEDIUM,
300            RenderQuality::High => RENDERER_IMAGE_SMOOTHING_QUALITY_HIGH,
301        };
302        let _: Result<bool, JsValue> = Reflect::set(
303            context,
304            &JsValue::from_str(RENDERER_PROPERTY_IMAGE_SMOOTHING_QUALITY),
305            &JsValue::from_str(quality_value),
306        );
307        let _: Result<bool, JsValue> = Reflect::set(
308            context,
309            &JsValue::from_str(RENDERER_PROPERTY_TEXT_RENDERING),
310            &JsValue::from_str(RENDERER_TEXT_RENDERING_GEOMETRIC_PRECISION),
311        );
312    }
313}
314
315/// Implements static CSS conversion for `Color`.
316impl Color {
317    /// Converts a `Color` to a CSS `rgba()` string suitable for canvas fill or stroke styles.
318    ///
319    /// # Arguments
320    ///
321    /// - `&Color` - The color to convert.
322    ///
323    /// # Returns
324    ///
325    /// - `String` - The CSS `rgba()` color string.
326    pub fn to_css(color: &Color) -> String {
327        color.to_css_rgba()
328    }
329}
330
331/// Implements drawing and camera management methods for `CanvasRenderer`.
332/// Implements recording and replay for `DrawList`.
333impl DrawList {
334    /// Creates an empty draw list.
335    ///
336    /// # Returns
337    ///
338    /// - `DrawList` - The new empty draw list.
339    pub fn create() -> DrawList {
340        DrawList::new(Vec::new())
341    }
342
343    /// Returns whether the list contains no commands.
344    ///
345    /// # Returns
346    ///
347    /// - `bool` - `true` if there are no recorded commands.
348    pub fn is_empty(&self) -> bool {
349        self.get_commands().is_empty()
350    }
351
352    /// Returns the number of recorded commands.
353    ///
354    /// # Returns
355    ///
356    /// - `usize` - The command count.
357    pub fn len(&self) -> usize {
358        self.get_commands().len()
359    }
360
361    /// Returns the recorded commands as a slice for replay iteration.
362    ///
363    /// # Returns
364    ///
365    /// - `&[DrawCommand]` - The commands in the order they were recorded.
366    pub fn commands(&self) -> &[DrawCommand] {
367        self.get_commands().as_slice()
368    }
369
370    /// Removes all recorded commands, keeping the allocated capacity for reuse
371    /// on the next frame.
372    pub fn clear(&mut self) {
373        self.get_mut_commands().clear();
374    }
375
376    /// Records a fill-rectangle command.
377    ///
378    /// # Arguments
379    ///
380    /// - `Vector2D` - 2D vector (`Vector2D`).
381    /// - `f64` - A 64-bit float (`f64`).
382    /// - `f64` - A 64-bit float (`f64`).
383    /// - `Color` - A `Color` parameter.
384    pub fn fill_rect(&mut self, position: Vector2D, width: f64, height: f64, color: Color) {
385        self.get_mut_commands().push(DrawCommand::FillRect {
386            position,
387            width,
388            height,
389            color,
390        });
391    }
392
393    /// Records a stroke-rectangle command.
394    ///
395    /// # Arguments
396    ///
397    /// - `Vector2D` - 2D vector (`Vector2D`).
398    /// - `f64` - A 64-bit float (`f64`).
399    /// - `f64` - A 64-bit float (`f64`).
400    /// - `Color` - A `Color` parameter.
401    /// - `f64` - A 64-bit float (`f64`).
402    pub fn stroke_rect(
403        &mut self,
404        position: Vector2D,
405        width: f64,
406        height: f64,
407        color: Color,
408        line_width: f64,
409    ) {
410        self.get_mut_commands().push(DrawCommand::StrokeRect {
411            position,
412            width,
413            height,
414            color,
415            line_width,
416        });
417    }
418
419    /// Records a fill-circle command.
420    ///
421    /// # Arguments
422    ///
423    /// - `Vector2D` - 2D vector (`Vector2D`).
424    /// - `f64` - A 64-bit float (`f64`).
425    /// - `Color` - A `Color` parameter.
426    pub fn fill_circle(&mut self, center: Vector2D, radius: f64, color: Color) {
427        self.get_mut_commands().push(DrawCommand::FillCircle {
428            center,
429            radius,
430            color,
431        });
432    }
433
434    /// Records a stroke-circle command.
435    ///
436    /// # Arguments
437    ///
438    /// - `Vector2D` - 2D vector (`Vector2D`).
439    /// - `f64` - A 64-bit float (`f64`).
440    /// - `Color` - A `Color` parameter.
441    /// - `f64` - A 64-bit float (`f64`).
442    pub fn stroke_circle(&mut self, center: Vector2D, radius: f64, color: Color, line_width: f64) {
443        self.get_mut_commands().push(DrawCommand::StrokeCircle {
444            center,
445            radius,
446            color,
447            line_width,
448        });
449    }
450
451    /// Records a line-segment command.
452    ///
453    /// # Arguments
454    ///
455    /// - `Vector2D` - 2D vector (`Vector2D`).
456    /// - `Vector2D` - 2D vector (`Vector2D`).
457    /// - `Color` - A `Color` parameter.
458    /// - `f64` - A 64-bit float (`f64`).
459    pub fn draw_line(&mut self, start: Vector2D, end: Vector2D, color: Color, line_width: f64) {
460        self.get_mut_commands().push(DrawCommand::Line {
461            start,
462            end,
463            color,
464            line_width,
465        });
466    }
467
468    /// Records a fill-text command.
469    ///
470    /// # Arguments
471    ///
472    /// - `T: AsRef<str>` - A generic type parameter.
473    /// - `Vector2D` - 2D vector (`Vector2D`).
474    /// - `Color` - A `Color` parameter.
475    /// - `F: AsRef<str>` - A generic type parameter.
476    pub fn fill_text<T, F>(&mut self, text: T, position: Vector2D, color: Color, font: F)
477    where
478        T: AsRef<str>,
479        F: AsRef<str>,
480    {
481        self.get_mut_commands().push(DrawCommand::FillText {
482            text: text.as_ref().to_string(),
483            position,
484            color,
485            font: font.as_ref().to_string(),
486        });
487    }
488
489    /// Records a transformed sprite draw command.
490    ///
491    /// # Arguments
492    ///
493    /// - `&HtmlImageElement` - Shared reference to a `HtmlImageElement`.
494    /// - `Rect` - A `Rect` parameter.
495    /// - `Transform2D` - A `Transform2D` parameter.
496    pub fn draw_sprite(&mut self, image: &HtmlImageElement, source: Rect, transform: Transform2D) {
497        self.get_mut_commands().push(DrawCommand::DrawSprite {
498            image: image.clone(),
499            source,
500            transform,
501        });
502    }
503
504    /// Records an image sub-region draw command (no rotation).
505    ///
506    /// # Arguments
507    ///
508    /// - `&HtmlImageElement` - Shared reference to a `HtmlImageElement`.
509    /// - `Rect` - A `Rect` parameter.
510    /// - `Vector2D` - 2D vector (`Vector2D`).
511    /// - `f64` - A 64-bit float (`f64`).
512    /// - `f64` - A 64-bit float (`f64`).
513    pub fn draw_image_rect(
514        &mut self,
515        image: &HtmlImageElement,
516        source: Rect,
517        dest_position: Vector2D,
518        dest_width: f64,
519        dest_height: f64,
520    ) {
521        self.get_mut_commands().push(DrawCommand::DrawImageRect {
522            image: image.clone(),
523            source,
524            dest_position,
525            dest_width,
526            dest_height,
527        });
528    }
529
530    /// Records a global-alpha state change.
531    ///
532    /// # Arguments
533    ///
534    /// - `f64` - A 64-bit float (`f64`).
535    pub fn set_global_alpha(&mut self, alpha: f64) {
536        self.get_mut_commands()
537            .push(DrawCommand::SetGlobalAlpha { alpha });
538    }
539
540    /// Records a blend-mode state change.
541    ///
542    /// # Arguments
543    ///
544    /// - `BlendMode` - A `BlendMode` parameter.
545    pub fn set_blend_mode(&mut self, mode: BlendMode) {
546        self.get_mut_commands()
547            .push(DrawCommand::SetBlendMode { mode });
548    }
549}
550
551/// Inherent implementation of [`CanvasRenderer`].
552impl CanvasRenderer {
553    /// Creates a new renderer from a canvas element selector and viewport dimensions.
554    ///
555    /// # Arguments
556    ///
557    /// - `&str` - The CSS selector for the canvas element.
558    /// - `f64` - The viewport width.
559    /// - `f64` - The viewport height.
560    ///
561    /// # Returns
562    ///
563    /// - `Option<CanvasRenderer>` - The renderer, or `None` if the canvas was not found.
564    pub fn from_selector<S>(
565        canvas_selector: S,
566        viewport_width: f64,
567        viewport_height: f64,
568    ) -> Option<CanvasRenderer>
569    where
570        S: AsRef<str>,
571    {
572        let window_value: Window = window()?;
573        let document_value: Document = window_value.document()?;
574        let element: Element = document_value
575            .query_selector(canvas_selector.as_ref())
576            .ok()
577            .flatten()?;
578        let canvas_element: HtmlCanvasElement = element.unchecked_into();
579        let context_object: Object = canvas_element
580            .get_context(RENDERER_CONTEXT_TYPE_2D)
581            .ok()
582            .flatten()?;
583        let context: CanvasRenderingContext2d = context_object.unchecked_into();
584        let renderer: CanvasRenderer = CanvasRenderer::new(
585            context,
586            Camera2D::create(viewport_width, viewport_height),
587            RenderQuality::default(),
588        );
589        renderer.enable_smoothing();
590        Some(renderer)
591    }
592
593    /// Enables high-quality anti-aliasing on the canvas context by setting
594    /// `imageSmoothingEnabled` to `true` and `imageSmoothingQuality` to `"high"`.
595    ///
596    /// Applies the active `quality` preset via the shared `apply_quality`
597    /// helper so that all smoothing-related settings are kept in sync.
598    pub fn enable_smoothing(&self) {
599        Self::apply_quality(self.get_context(), self.get_quality());
600    }
601
602    /// Clears the entire canvas viewport.
603    pub fn clear(&self) {
604        self.get_context().clear_rect(
605            0.0,
606            0.0,
607            self.get_camera().get_viewport_width(),
608            self.get_camera().get_viewport_height(),
609        );
610    }
611
612    /// Clears the canvas and fills it with the given CSS color string.
613    ///
614    /// # Arguments
615    ///
616    /// - `C: AsRef<str>` - The CSS color string (e.g., `"#000000"`).
617    pub fn clear_color<C>(&self, color: C)
618    where
619        C: AsRef<str>,
620    {
621        self.get_context().set_fill_style_str(color.as_ref());
622        self.get_context().fill_rect(
623            0.0,
624            0.0,
625            self.get_camera().get_viewport_width(),
626            self.get_camera().get_viewport_height(),
627        );
628    }
629
630    /// Saves the current canvas state (transform, styles) onto the state stack.
631    pub fn save(&self) {
632        self.get_context().save();
633    }
634
635    /// Restores the most recently saved canvas state.
636    pub fn restore(&self) {
637        self.get_context().restore();
638    }
639
640    /// Replays a recorded `DrawList` onto this renderer's canvas.
641    ///
642    /// Convenience wrapper around `replay_context` using this renderer's context.
643    ///
644    /// # Arguments
645    ///
646    /// - `&DrawList` - The recorded commands to replay.
647    pub fn replay(&self, list: &DrawList) {
648        Self::replay_context(self.get_context(), list);
649    }
650
651    /// Replays a recorded `DrawList` onto an arbitrary canvas 2D context in a
652    /// single batched pass.
653    ///
654    /// Consecutive same-style shapes are merged into one path (one `begin_path`
655    /// plus one `fill`/`stroke` per style run), fill/stroke colors and line
656    /// widths are only re-applied when they change, and sprites are drawn with a
657    /// single `set_transform` rather than a save/restore pair. This collapses
658    /// the per-shape canvas state churn of immediate-mode drawing.
659    ///
660    /// The canvas transform and global alpha are reset to identity / 1.0 when
661    /// replay finishes, so callers can sandwich the call between
662    /// `save()`/`apply_camera()` and `restore()` without leaking state.
663    ///
664    /// # Arguments
665    ///
666    /// - `&CanvasRenderingContext2d` - The target canvas 2D context.
667    /// - `&DrawList` - The recorded commands to replay.
668    pub fn replay_context(context: &CanvasRenderingContext2d, list: &DrawList) {
669        let mut current_fill: Option<Color> = None;
670        let mut current_stroke: Option<Color> = None;
671        let mut current_line_width: f64 = f64::NAN;
672        // Whether a same-style path run is currently open.
673        let mut run_open: bool = false;
674        let mut run_is_fill: bool = true;
675        let mut run_key: Option<(u8, Color, f64)> = None;
676
677        // Returns the style key for a path-batchable command, or `None` for
678        // commands that break a run (sprites, images, text, state changes).
679        /// Computes the batching key for a [`DrawCommand`].
680        ///
681        /// # Arguments
682        ///
683        /// - `&DrawCommand` - Shared reference to a `DrawCommand`.
684        ///
685        /// # Returns
686        ///
687        /// - `Option<(u8, Color, f64)>` - `Some(...)` on success, `None` otherwise.
688        fn batch_key(command: &DrawCommand) -> Option<(u8, Color, f64)> {
689            match command {
690                DrawCommand::FillRect { color, .. } | DrawCommand::FillCircle { color, .. } => {
691                    Some((0, *color, 0.0))
692                }
693                DrawCommand::StrokeRect {
694                    color, line_width, ..
695                }
696                | DrawCommand::StrokeCircle {
697                    color, line_width, ..
698                }
699                | DrawCommand::Line {
700                    color, line_width, ..
701                } => Some((1, *color, *line_width)),
702                _ => None,
703            }
704        }
705
706        // Emits a single path-batchable command's geometry into the open path.
707        /// Emits the geometry for the supplied [`DrawCommand`] into the canvas context.
708        ///
709        /// # Arguments
710        ///
711        /// - `&CanvasRenderingContext2d` - Shared reference to a `CanvasRenderingContext2d`.
712        /// - `&DrawCommand` - Shared reference to a `DrawCommand`.
713        fn emit_geometry(context: &CanvasRenderingContext2d, command: &DrawCommand) {
714            match command {
715                DrawCommand::FillRect {
716                    position,
717                    width,
718                    height,
719                    ..
720                }
721                | DrawCommand::StrokeRect {
722                    position,
723                    width,
724                    height,
725                    ..
726                } => {
727                    context.rect(position.get_x(), position.get_y(), *width, *height);
728                }
729                DrawCommand::FillCircle { center, radius, .. }
730                | DrawCommand::StrokeCircle { center, radius, .. } => {
731                    context.move_to(center.get_x() + radius, center.get_y());
732                    let _: Result<(), JsValue> =
733                        context.arc(center.get_x(), center.get_y(), *radius, 0.0, TWO_PI);
734                }
735                DrawCommand::Line { start, end, .. } => {
736                    context.move_to(start.get_x(), start.get_y());
737                    context.line_to(end.get_x(), end.get_y());
738                }
739                _ => {}
740            }
741        }
742
743        for command in list.commands() {
744            let key: Option<(u8, Color, f64)> = batch_key(command);
745            // Close the open run if this command breaks it or starts a new style.
746            if run_open && key != run_key {
747                if run_is_fill {
748                    context.fill();
749                } else {
750                    context.stroke();
751                }
752                run_open = false;
753            }
754            if let Some(current_key) = key {
755                // Begin (or continue) a same-style path run.
756                if !run_open {
757                    let (kind, color, line_width) = current_key;
758                    if kind == 0 {
759                        if current_fill != Some(color) {
760                            context.set_fill_style_str(&Color::to_css(&color));
761                            current_fill = Some(color);
762                        }
763                        run_is_fill = true;
764                    } else {
765                        if current_stroke != Some(color) {
766                            context.set_stroke_style_str(&Color::to_css(&color));
767                            current_stroke = Some(color);
768                        }
769                        if current_line_width != line_width {
770                            context.set_line_width(line_width);
771                            current_line_width = line_width;
772                        }
773                        run_is_fill = false;
774                    }
775                    context.begin_path();
776                    run_open = true;
777                    run_key = Some(current_key);
778                }
779                emit_geometry(context, command);
780                continue;
781            }
782            // Non-batchable command: draw it immediately.
783            match command {
784                DrawCommand::FillText {
785                    text,
786                    position,
787                    color,
788                    font,
789                } => {
790                    if current_fill != Some(*color) {
791                        context.set_fill_style_str(&Color::to_css(color));
792                        current_fill = Some(*color);
793                    }
794                    context.set_font(font);
795                    let _: Result<(), JsValue> =
796                        context.fill_text(text, position.get_x(), position.get_y());
797                }
798                DrawCommand::DrawSprite {
799                    image,
800                    source,
801                    transform,
802                } => {
803                    draw_sprite_immediate(context, image, source, transform);
804                }
805                DrawCommand::DrawImageRect {
806                    image,
807                    source,
808                    dest_position,
809                    dest_width,
810                    dest_height,
811                } => {
812                    let _: Result<(), JsValue> = context
813                        .draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(
814                            image,
815                            source.get_x(),
816                            source.get_y(),
817                            source.get_width(),
818                            source.get_height(),
819                            dest_position.get_x(),
820                            dest_position.get_y(),
821                            *dest_width,
822                            *dest_height,
823                        );
824                }
825                DrawCommand::SetGlobalAlpha { alpha } => {
826                    context.set_global_alpha(Numeric::clamp(*alpha, 0.0, 1.0));
827                }
828                DrawCommand::SetBlendMode { mode } => {
829                    let _: Result<(), JsValue> =
830                        context.set_global_composite_operation(mode.to_css());
831                }
832                _ => {}
833            }
834        }
835        // Flush any trailing open run.
836        if run_open {
837            if run_is_fill {
838                context.fill();
839            } else {
840                context.stroke();
841            }
842        }
843        let _: Result<(), JsValue> = context.set_transform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
844        context.set_global_alpha(1.0);
845    }
846
847    /// Applies the camera transform to the canvas context.
848    ///
849    /// Translates to the screen center, applies zoom and rotation,
850    /// then offsets by the negative camera position.
851    pub fn apply_camera(&self) {
852        let camera: Camera2D = self.get_camera();
853        let _: Result<(), JsValue> = self.get_context().translate(
854            camera.get_viewport_width() * 0.5,
855            camera.get_viewport_height() * 0.5,
856        );
857        let _: Result<(), JsValue> = self
858            .get_context()
859            .scale(camera.get_zoom(), camera.get_zoom());
860        let _: Result<(), JsValue> = self.get_context().rotate(camera.get_rotation());
861        let _: Result<(), JsValue> = self.get_context().translate(
862            -camera.get_position().get_x(),
863            -camera.get_position().get_y(),
864        );
865    }
866
867    /// Sets the fill color for subsequent fill operations.
868    ///
869    /// # Arguments
870    ///
871    /// - `C: AsRef<str>` - The CSS color string.
872    pub fn set_fill_color<C>(&self, color: C)
873    where
874        C: AsRef<str>,
875    {
876        self.get_context().set_fill_style_str(color.as_ref());
877    }
878
879    /// Sets the stroke color for subsequent stroke operations.
880    ///
881    /// # Arguments
882    ///
883    /// - `C: AsRef<str>` - The CSS color string.
884    pub fn set_stroke_color<C>(&self, color: C)
885    where
886        C: AsRef<str>,
887    {
888        self.get_context().set_stroke_style_str(color.as_ref());
889    }
890
891    /// Sets the line width for subsequent stroke operations.
892    ///
893    /// # Arguments
894    ///
895    /// - `f64` - The line width in pixels.
896    pub fn set_line_width(&self, width: f64) {
897        self.get_context().set_line_width(width);
898    }
899
900    /// Sets the global alpha (opacity) for all subsequent drawing operations.
901    ///
902    /// # Arguments
903    ///
904    /// - `f64` - The alpha value in the range 0.0 to 1.0.
905    pub fn set_global_alpha(&self, alpha: f64) {
906        self.get_context()
907            .set_global_alpha(Numeric::clamp(alpha, 0.0, 1.0));
908    }
909
910    /// Fills a rectangle at the given world-space position and dimensions.
911    ///
912    /// # Arguments
913    ///
914    /// - `Vector2D` - The top-left position in world space.
915    /// - `f64` - The width.
916    /// - `f64` - The height.
917    pub fn fill_rect(&self, position: Vector2D, width: f64, height: f64) {
918        self.get_context()
919            .fill_rect(position.get_x(), position.get_y(), width, height);
920    }
921
922    /// Strokes the outline of a rectangle at the given world-space position and dimensions.
923    ///
924    /// # Arguments
925    ///
926    /// - `Vector2D` - The top-left position in world space.
927    /// - `f64` - The width.
928    /// - `f64` - The height.
929    pub fn stroke_rect(&self, position: Vector2D, width: f64, height: f64) {
930        self.get_context()
931            .stroke_rect(position.get_x(), position.get_y(), width, height);
932    }
933
934    /// Fills a circle at the given world-space center with the specified radius.
935    ///
936    /// # Arguments
937    ///
938    /// - `Vector2D` - The center in world space.
939    /// - `f64` - The radius.
940    pub fn fill_circle(&self, center: Vector2D, radius: f64) {
941        self.get_context().begin_path();
942        self.get_context()
943            .arc(center.get_x(), center.get_y(), radius, 0.0, TWO_PI)
944            .unwrap_or(());
945        self.get_context().fill();
946    }
947
948    /// Strokes the outline of a circle at the given world-space center.
949    ///
950    /// # Arguments
951    ///
952    /// - `Vector2D` - The center in world space.
953    /// - `f64` - The radius.
954    pub fn stroke_circle(&self, center: Vector2D, radius: f64) {
955        self.get_context().begin_path();
956        self.get_context()
957            .arc(center.get_x(), center.get_y(), radius, 0.0, TWO_PI)
958            .unwrap_or(());
959        self.get_context().stroke();
960    }
961
962    /// Draws a line segment between two world-space points.
963    ///
964    /// # Arguments
965    ///
966    /// - `Vector2D` - The start point.
967    /// - `Vector2D` - The end point.
968    pub fn draw_line(&self, start: Vector2D, end: Vector2D) {
969        self.get_context().begin_path();
970        self.get_context().move_to(start.get_x(), start.get_y());
971        self.get_context().line_to(end.get_x(), end.get_y());
972        self.get_context().stroke();
973    }
974
975    /// Fills text at the given world-space position.
976    ///
977    /// # Arguments
978    ///
979    /// - `T: AsRef<str>` - The text to draw.
980    /// - `Vector2D` - The position in world space.
981    pub fn fill_text<T>(&self, text: T, position: Vector2D)
982    where
983        T: AsRef<str>,
984    {
985        self.get_context()
986            .fill_text(text.as_ref(), position.get_x(), position.get_y())
987            .unwrap_or(());
988    }
989
990    /// Sets the font for subsequent text rendering.
991    ///
992    /// # Arguments
993    ///
994    /// - `F: AsRef<str>` - The CSS font string (e.g., `"16px sans-serif"`).
995    pub fn set_font<F>(&self, font: F)
996    where
997        F: AsRef<str>,
998    {
999        self.get_context().set_font(font.as_ref());
1000    }
1001
1002    /// Draws an image element at the given world-space position and dimensions.
1003    ///
1004    /// # Arguments
1005    ///
1006    /// - `&HtmlImageElement` - The image element to draw.
1007    /// - `Vector2D` - The top-left position in world space.
1008    /// - `f64` - The destination width.
1009    /// - `f64` - The destination height.
1010    pub fn draw_image(
1011        &self,
1012        image: &HtmlImageElement,
1013        position: Vector2D,
1014        width: f64,
1015        height: f64,
1016    ) {
1017        let _: Result<(), JsValue> = self
1018            .get_context()
1019            .draw_image_with_html_image_element_and_dw_and_dh(
1020                image,
1021                position.get_x(),
1022                position.get_y(),
1023                width,
1024                height,
1025            );
1026    }
1027
1028    /// Draws a sub-region of an image element at the given world-space position.
1029    ///
1030    /// # Arguments
1031    ///
1032    /// - `&HtmlImageElement` - The image element to draw.
1033    /// - `Rect` - The source rectangle within the image.
1034    /// - `Vector2D` - The destination top-left position in world space.
1035    /// - `f64` - The destination width.
1036    /// - `f64` - The destination height.
1037    pub fn draw_image_rect(
1038        &self,
1039        image: &HtmlImageElement,
1040        source: Rect,
1041        dest_position: Vector2D,
1042        dest_width: f64,
1043        dest_height: f64,
1044    ) {
1045        let _: Result<(), JsValue> = self
1046            .get_context()
1047            .draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(
1048                image,
1049                source.get_x(),
1050                source.get_y(),
1051                source.get_width(),
1052                source.get_height(),
1053                dest_position.get_x(),
1054                dest_position.get_y(),
1055                dest_width,
1056                dest_height,
1057            );
1058    }
1059}
1060
1061/// Implements 3D camera transformation and projection methods for `Camera3D`.
1062impl Camera3D {
1063    /// Creates a new 3D camera at the given position looking at the target.
1064    ///
1065    /// # Arguments
1066    ///
1067    /// - `Vector3D` - The eye position.
1068    /// - `Vector3D` - The target position to look at.
1069    /// - `f64` - The viewport width.
1070    /// - `f64` - The viewport height.
1071    ///
1072    /// # Returns
1073    ///
1074    /// - `Camera3D` - The new camera.
1075    pub fn create(
1076        position: Vector3D,
1077        target: Vector3D,
1078        viewport_width: f64,
1079        viewport_height: f64,
1080    ) -> Camera3D {
1081        let mut camera: Camera3D = Camera3D::new(position, target, viewport_width, viewport_height);
1082        camera.set_up(Vector3D::up());
1083        camera.set_fov(DEFAULT_CAMERA_FOV);
1084        camera.set_near(DEFAULT_CAMERA_NEAR);
1085        camera.set_far(DEFAULT_CAMERA_FAR);
1086        camera
1087    }
1088
1089    /// Returns the aspect ratio (width / height).
1090    ///
1091    /// # Returns
1092    ///
1093    /// - `f64` - The aspect ratio.
1094    pub fn aspect(&self) -> f64 {
1095        if self.get_viewport_height() < EPSILON {
1096            return 1.0;
1097        }
1098        self.get_viewport_width() / self.get_viewport_height()
1099    }
1100
1101    /// Returns the forward direction (from position to target, normalized).
1102    ///
1103    /// # Returns
1104    ///
1105    /// - `Vector3D` - The forward direction.
1106    pub fn forward(&self) -> Vector3D {
1107        (self.get_target() - self.get_position()).normalized()
1108    }
1109
1110    /// Returns the right direction (cross product of forward and up).
1111    ///
1112    /// # Returns
1113    ///
1114    /// - `Vector3D` - The right direction.
1115    pub fn right(&self) -> Vector3D {
1116        self.forward().cross(self.get_up()).normalized()
1117    }
1118
1119    /// Returns the view matrix for this camera.
1120    ///
1121    /// # Returns
1122    ///
1123    /// - `Matrix4x4` - The view matrix.
1124    pub fn view_matrix(&self) -> Matrix4x4 {
1125        Matrix4x4::look_at(self.get_position(), self.get_target(), self.get_up())
1126    }
1127
1128    /// Returns the perspective projection matrix for this camera.
1129    ///
1130    /// # Returns
1131    ///
1132    /// - `Matrix4x4` - The projection matrix.
1133    pub fn projection_matrix(&self) -> Matrix4x4 {
1134        Matrix4x4::perspective(
1135            self.get_fov(),
1136            self.aspect(),
1137            self.get_near(),
1138            self.get_far(),
1139        )
1140    }
1141
1142    /// Returns the combined view-projection matrix.
1143    ///
1144    /// # Returns
1145    ///
1146    /// - `Matrix4x4` - The view-projection matrix.
1147    pub fn view_proj_matrix(&self) -> Matrix4x4 {
1148        self.projection_matrix().multiply(self.view_matrix())
1149    }
1150
1151    /// Converts a 3D world-space point to screen-space (NDC) coordinates.
1152    ///
1153    /// # Arguments
1154    ///
1155    /// - `Vector3D` - The world-space point.
1156    ///
1157    /// # Returns
1158    ///
1159    /// - `Vector3D` - The screen-space point where x and y are in [0, 1] and z is the depth.
1160    pub fn world_to_screen(&self, world: Vector3D) -> Vector3D {
1161        let clip: Vector3D = self.view_proj_matrix().transform_point(world);
1162        Vector3D::new(
1163            (clip.get_x() + 1.0) * 0.5 * self.get_viewport_width(),
1164            (1.0 - clip.get_y()) * 0.5 * self.get_viewport_height(),
1165            clip.get_z(),
1166        )
1167    }
1168
1169    /// Projects a world-space point and returns whether it is within the camera frustum.
1170    ///
1171    /// # Arguments
1172    ///
1173    /// - `Vector3D` - The world-space point.
1174    ///
1175    /// # Returns
1176    ///
1177    /// - `bool` - True if the point is within the frustum.
1178    pub fn in_frustum(&self, world: Vector3D) -> bool {
1179        let clip: Vector3D = self.view_proj_matrix().transform_point(world);
1180        clip.get_x() >= -1.0
1181            && clip.get_x() <= 1.0
1182            && clip.get_y() >= -1.0
1183            && clip.get_y() <= 1.0
1184            && clip.get_z() >= -1.0
1185            && clip.get_z() <= 1.0
1186    }
1187
1188    /// Moves the camera position by the given offset, keeping the target offset by the same amount.
1189    ///
1190    /// # Arguments
1191    ///
1192    /// - `Vector3D` - The translation offset.
1193    pub fn translate(&mut self, offset: Vector3D) {
1194        self.set_position(self.get_position() + offset);
1195        self.set_target(self.get_target() + offset);
1196    }
1197
1198    /// Moves the camera position towards the target by the given distance.
1199    ///
1200    /// # Arguments
1201    ///
1202    /// - `f64` - The distance to zoom in (positive) or out (negative).
1203    pub fn zoom(&mut self, distance: f64) {
1204        let direction: Vector3D = self.forward();
1205        self.set_position(self.get_position() + direction.scaled(distance));
1206    }
1207
1208    /// Orbits the camera around the target by the given yaw and pitch angles.
1209    ///
1210    /// # Arguments
1211    ///
1212    /// - `f64` - The yaw delta in radians (horizontal rotation).
1213    /// - `f64` - The pitch delta in radians (vertical rotation).
1214    pub fn orbit(&mut self, yaw_delta: f64, pitch_delta: f64) {
1215        let offset: Vector3D = self.get_position() - self.get_target();
1216        let current_distance: f64 = offset.magnitude();
1217        let current_yaw: f64 = offset.get_x().atan2(offset.get_z());
1218        let horizontal_dist: f64 =
1219            (offset.get_x() * offset.get_x() + offset.get_z() * offset.get_z()).sqrt();
1220        let current_pitch: f64 = (offset.get_y() / horizontal_dist.max(EPSILON)).asin();
1221        let new_yaw: f64 = current_yaw + yaw_delta;
1222        let new_pitch: f64 = Numeric::clamp(
1223            current_pitch + pitch_delta,
1224            -HALF_PI + EPSILON,
1225            HALF_PI - EPSILON,
1226        );
1227        let cos_pitch: f64 = new_pitch.cos();
1228        self.set_position(
1229            self.get_target()
1230                + Vector3D::new(
1231                    new_yaw.sin() * cos_pitch * current_distance,
1232                    new_pitch.sin() * current_distance,
1233                    new_yaw.cos() * cos_pitch * current_distance,
1234                ),
1235        );
1236    }
1237}
1238
1239/// Implements `Default` for `Camera3D` as a camera at (0, 0, 5) looking at the origin.
1240impl Default for Camera3D {
1241    /// Constructs a default [`Camera3D`] value.
1242    ///
1243    /// # Returns
1244    ///
1245    /// - `Camera3D` - A default-constructed instance with the documented initial state.
1246    fn default() -> Camera3D {
1247        Camera3D::create(Vector3D::new(0.0, 0.0, 5.0), Vector3D::zero(), 800.0, 600.0)
1248    }
1249}
1250
1251/// Implements construction, presentation, and anti-aliasing methods for `SsaaCanvas`.
1252impl SsaaCanvas {
1253    /// Creates an `SsaaCanvas` from a CSS selector using the default scale factor.
1254    ///
1255    /// # Arguments
1256    ///
1257    /// - `S: AsRef<str>` - The CSS selector for the display canvas element.
1258    /// - `f64` - The logical display width in CSS pixels.
1259    /// - `f64` - The logical display height in CSS pixels.
1260    ///
1261    /// # Returns
1262    ///
1263    /// - `Option<SsaaCanvas>` - The SSAA canvas, or `None` if the canvas was not found.
1264    pub fn from_selector<S>(canvas_selector: S, width: f64, height: f64) -> Option<SsaaCanvas>
1265    where
1266        S: AsRef<str>,
1267    {
1268        Self::from_selector_with_scale(
1269            canvas_selector,
1270            width,
1271            height,
1272            RENDERER_DEFAULT_SSAA_SCALE_FACTOR,
1273        )
1274    }
1275
1276    /// Creates an `SsaaCanvas` from a CSS selector with a custom SSAA scale factor.
1277    ///
1278    /// The offscreen canvas is created at `width * scale_factor` by `height * scale_factor`
1279    /// pixels, and its context is pre-scaled so that drawing code uses logical coordinates.
1280    ///
1281    /// # Arguments
1282    ///
1283    /// - `S: AsRef<str>` - The CSS selector for the display canvas element.
1284    /// - `f64` - The logical display width in CSS pixels.
1285    /// - `f64` - The logical display height in CSS pixels.
1286    /// - `f64` - The supersampling scale factor (e.g., 2.0 for 4x SSAA).
1287    ///
1288    /// # Returns
1289    ///
1290    /// - `Option<SsaaCanvas>` - The SSAA canvas, or `None` if the canvas was not found.
1291    pub fn from_selector_with_scale<S>(
1292        canvas_selector: S,
1293        width: f64,
1294        height: f64,
1295        scale_factor: f64,
1296    ) -> Option<SsaaCanvas>
1297    where
1298        S: AsRef<str>,
1299    {
1300        let window_value: Window = window()?;
1301        let document_value: Document = window_value.document()?;
1302        let element: Element = document_value
1303            .query_selector(canvas_selector.as_ref())
1304            .ok()
1305            .flatten()?;
1306        let display_canvas: HtmlCanvasElement = element.unchecked_into();
1307        let device_pixel_ratio: f64 = CanvasRenderer::detect_dpr();
1308        let physical_width: u32 = (width * device_pixel_ratio).round() as u32;
1309        let physical_height: u32 = (height * device_pixel_ratio).round() as u32;
1310        display_canvas.set_width(physical_width);
1311        display_canvas.set_height(physical_height);
1312        let display_context_object: Object = display_canvas
1313            .get_context(RENDERER_CONTEXT_TYPE_2D)
1314            .ok()
1315            .flatten()?;
1316        let display_context: CanvasRenderingContext2d = display_context_object.unchecked_into();
1317        let _: Result<(), JsValue> = display_context.scale(device_pixel_ratio, device_pixel_ratio);
1318        let offscreen_canvas: HtmlCanvasElement = document_value
1319            .create_element(RENDERER_ELEMENT_CANVAS)
1320            .ok()?
1321            .unchecked_into();
1322        let scaled_width: u32 = (width * scale_factor * device_pixel_ratio).round() as u32;
1323        let scaled_height: u32 = (height * scale_factor * device_pixel_ratio).round() as u32;
1324        offscreen_canvas.set_width(scaled_width);
1325        offscreen_canvas.set_height(scaled_height);
1326        let offscreen_context_object: Object = offscreen_canvas
1327            .get_context(RENDERER_CONTEXT_TYPE_2D)
1328            .ok()
1329            .flatten()?;
1330        let offscreen_context: CanvasRenderingContext2d = offscreen_context_object.unchecked_into();
1331        let _: Result<(), JsValue> = offscreen_context.scale(
1332            scale_factor * device_pixel_ratio,
1333            scale_factor * device_pixel_ratio,
1334        );
1335        let ssaa_canvas: SsaaCanvas = SsaaCanvas::new(
1336            display_canvas,
1337            display_context,
1338            offscreen_canvas,
1339            offscreen_context,
1340            scale_factor,
1341            width,
1342            height,
1343        );
1344        ssaa_canvas.enable_smoothing();
1345        Some(ssaa_canvas)
1346    }
1347
1348    /// Presents the offscreen buffer onto the display canvas with high-quality downscaling.
1349    ///
1350    /// Clears the display canvas, then draws the offscreen canvas scaled
1351    /// down to the logical display size. The active `quality` preset is
1352    /// applied once at construction via `enable_smoothing` — there is
1353    /// no need to re-apply it every frame, since the preset never
1354    /// changes mid-render.
1355    ///
1356    /// #32: the previous version called `apply_quality` on every
1357    /// `present()`, costing `set_image_smoothing_enabled` + 2×Reflect
1358    /// + 4×from_str ≈ 7 JS crossings per frame for a value that was
1359    ///   invariant across the entire session.
1360    pub fn present(&self) {
1361        self.get_display_context()
1362            .clear_rect(0.0, 0.0, self.get_width(), self.get_height());
1363        let _: Result<(), JsValue> = self
1364            .get_display_context()
1365            .draw_image_with_html_canvas_element_and_dw_and_dh(
1366                self.get_offscreen_canvas(),
1367                0.0,
1368                0.0,
1369                self.get_width(),
1370                self.get_height(),
1371            );
1372    }
1373
1374    /// Clears the offscreen buffer to transparent.
1375    pub fn clear(&self) {
1376        self.get_offscreen_context()
1377            .clear_rect(0.0, 0.0, self.get_width(), self.get_height());
1378    }
1379
1380    /// Clears the offscreen buffer and fills it with the given CSS color.
1381    ///
1382    /// # Arguments
1383    ///
1384    /// - `C: AsRef<str>` - The CSS color string.
1385    pub fn clear_color<C>(&self, color: C)
1386    where
1387        C: AsRef<str>,
1388    {
1389        self.get_offscreen_context()
1390            .set_fill_style_str(color.as_ref());
1391        self.get_offscreen_context()
1392            .fill_rect(0.0, 0.0, self.get_width(), self.get_height());
1393    }
1394
1395    /// Enables high-quality anti-aliasing on both the display and offscreen contexts.
1396    ///
1397    /// Applies the active `quality` preset to both contexts via the shared
1398    /// `apply_quality` helper.
1399    pub fn enable_smoothing(&self) {
1400        let quality: RenderQuality = self.get_quality();
1401        CanvasRenderer::apply_quality(self.get_display_context(), quality);
1402        CanvasRenderer::apply_quality(self.get_offscreen_context(), quality);
1403    }
1404}
1405
1406/// Implements CSS composite operation string conversion for `BlendMode`.
1407impl BlendMode {
1408    /// Returns the CSS `globalCompositeOperation` string for this blend mode.
1409    ///
1410    /// # Returns
1411    ///
1412    /// - `&str` - The CSS composite operation string.
1413    pub fn to_css(&self) -> &str {
1414        match self {
1415            BlendMode::Normal => BLEND_MODE_NORMAL,
1416            BlendMode::Multiply => BLEND_MODE_MULTIPLY,
1417            BlendMode::Screen => BLEND_MODE_SCREEN,
1418            BlendMode::Lighter => BLEND_MODE_LIGHTER,
1419            BlendMode::Overlay => BLEND_MODE_OVERLAY,
1420            BlendMode::Darken => BLEND_MODE_DARKEN,
1421            BlendMode::Lighten => BLEND_MODE_LIGHTEN,
1422            BlendMode::ColorDodge => BLEND_MODE_COLOR_DODGE,
1423            BlendMode::ColorBurn => BLEND_MODE_COLOR_BURN,
1424            BlendMode::HardLight => BLEND_MODE_HARD_LIGHT,
1425            BlendMode::SoftLight => BLEND_MODE_SOFT_LIGHT,
1426            BlendMode::Difference => BLEND_MODE_DIFFERENCE,
1427            BlendMode::Exclusion => BLEND_MODE_EXCLUSION,
1428            BlendMode::Hue => BLEND_MODE_HUE,
1429            BlendMode::Saturation => BLEND_MODE_SATURATION,
1430            BlendMode::Color => BLEND_MODE_COLOR,
1431            BlendMode::Luminosity => BLEND_MODE_LUMINOSITY,
1432        }
1433    }
1434}
1435
1436/// Implements construction and canvas gradient creation for `LinearGradient`.
1437impl LinearGradient {
1438    /// Creates a new linear gradient from two points and a list of color stops.
1439    ///
1440    /// # Arguments
1441    ///
1442    /// - `Vector2D` - The start point.
1443    /// - `Vector2D` - The end point.
1444    /// - `Vec<(f64, String)>` - The color stops as (position, color) pairs.
1445    ///
1446    /// # Returns
1447    ///
1448    /// - `LinearGradient` - The new gradient.
1449    pub fn create(start: Vector2D, end: Vector2D, stops: Vec<(f64, String)>) -> LinearGradient {
1450        LinearGradient::new(start, end, stops)
1451    }
1452
1453    /// Creates a `CanvasGradient` from this gradient definition on the given context.
1454    ///
1455    /// # Arguments
1456    ///
1457    /// - `&CanvasRenderingContext2d` - The canvas context.
1458    ///
1459    /// # Returns
1460    ///
1461    /// - `Option<CanvasGradient>` - The canvas gradient, or `None` if creation failed.
1462    pub fn to_gradient(&self, context: &CanvasRenderingContext2d) -> Option<CanvasGradient> {
1463        let canvas_gradient: CanvasGradient = context.create_linear_gradient(
1464            self.get_start().get_x(),
1465            self.get_start().get_y(),
1466            self.get_end().get_x(),
1467            self.get_end().get_y(),
1468        );
1469        for (position, color) in self.get_stops() {
1470            let _: Result<(), JsValue> = canvas_gradient.add_color_stop(*position as f32, color);
1471        }
1472        Some(canvas_gradient)
1473    }
1474}
1475
1476/// Implements construction and canvas gradient creation for `RadialGradient`.
1477impl RadialGradient {
1478    /// Creates a new radial gradient from inner and outer circles and color stops.
1479    ///
1480    /// # Arguments
1481    ///
1482    /// - `Vector2D` - The inner circle center.
1483    /// - `f64` - The inner circle radius.
1484    /// - `Vector2D` - The outer circle center.
1485    /// - `f64` - The outer circle radius.
1486    /// - `Vec<(f64, String)>` - The color stops as (position, color) pairs.
1487    ///
1488    /// # Returns
1489    ///
1490    /// - `RadialGradient` - The new gradient.
1491    pub fn create(
1492        inner_center: Vector2D,
1493        inner_radius: f64,
1494        outer_center: Vector2D,
1495        outer_radius: f64,
1496        stops: Vec<(f64, String)>,
1497    ) -> RadialGradient {
1498        RadialGradient::new(
1499            inner_center,
1500            inner_radius,
1501            outer_center,
1502            outer_radius,
1503            stops,
1504        )
1505    }
1506
1507    /// Creates a `CanvasGradient` from this gradient definition on the given context.
1508    ///
1509    /// # Arguments
1510    ///
1511    /// - `&CanvasRenderingContext2d` - The canvas context.
1512    ///
1513    /// # Returns
1514    ///
1515    /// - `Option<CanvasGradient>` - The canvas gradient, or `None` if creation failed.
1516    pub fn to_gradient(&self, context: &CanvasRenderingContext2d) -> Option<CanvasGradient> {
1517        let canvas_gradient: CanvasGradient = context
1518            .create_radial_gradient(
1519                self.get_inner_center().get_x(),
1520                self.get_inner_center().get_y(),
1521                self.get_inner_radius(),
1522                self.get_outer_center().get_x(),
1523                self.get_outer_center().get_y(),
1524                self.get_outer_radius(),
1525            )
1526            .ok()?;
1527        for (position, color) in self.get_stops() {
1528            let _: Result<(), JsValue> = canvas_gradient.add_color_stop(*position as f32, color);
1529        }
1530        Some(canvas_gradient)
1531    }
1532}
1533
1534/// Implements construction methods for `ShadowConfig`.
1535impl ShadowConfig {
1536    /// Creates a shadow configuration with default values.
1537    ///
1538    /// # Returns
1539    ///
1540    /// - `ShadowConfig` - The default shadow configuration.
1541    pub fn create() -> ShadowConfig {
1542        ShadowConfig::new(
1543            RENDERER_DEFAULT_SHADOW_COLOR.to_string(),
1544            RENDERER_DEFAULT_SHADOW_BLUR,
1545            0.0,
1546            0.0,
1547        )
1548    }
1549}
1550
1551/// Implements `Default` for `ShadowConfig` with default shadow values.
1552impl Default for ShadowConfig {
1553    /// Constructs a default [`ShadowConfig`] value.
1554    ///
1555    /// # Returns
1556    ///
1557    /// - `ShadowConfig` - A default-constructed instance with the documented initial state.
1558    fn default() -> ShadowConfig {
1559        ShadowConfig::create()
1560    }
1561}
1562
1563/// Implements construction methods for `RenderLayer`.
1564impl RenderLayer {
1565    /// Creates a render layer with the given z-index and visibility.
1566    ///
1567    /// # Arguments
1568    ///
1569    /// - `i32` - The z-index determining draw order.
1570    /// - `bool` - Whether the layer is visible.
1571    ///
1572    /// # Returns
1573    ///
1574    /// - `RenderLayer` - The new render layer.
1575    pub fn create(z_index: i32, visible: bool) -> RenderLayer {
1576        RenderLayer::new(z_index, visible)
1577    }
1578
1579    /// Creates a background render layer with z-index 0 and visibility enabled.
1580    ///
1581    /// # Returns
1582    ///
1583    /// - `RenderLayer` - The background layer.
1584    pub fn background() -> RenderLayer {
1585        RenderLayer::new(RENDERER_LAYER_BACKGROUND, true)
1586    }
1587
1588    /// Creates a foreground render layer with a high z-index and visibility enabled.
1589    ///
1590    /// # Returns
1591    ///
1592    /// - `RenderLayer` - The foreground layer.
1593    pub fn foreground() -> RenderLayer {
1594        RenderLayer::new(RENDERER_LAYER_FOREGROUND, true)
1595    }
1596
1597    /// Creates a UI overlay render layer with the highest z-index and visibility enabled.
1598    ///
1599    /// # Returns
1600    ///
1601    /// - `RenderLayer` - The UI overlay layer.
1602    pub fn ui() -> RenderLayer {
1603        RenderLayer::new(RENDERER_LAYER_UI, true)
1604    }
1605}
1606
1607/// Implements blend mode, shadow, and gradient rendering methods for `CanvasRenderer`.
1608impl CanvasRenderer {
1609    /// Sets the blend mode for compositing subsequent draw operations.
1610    ///
1611    /// # Arguments
1612    ///
1613    /// - `BlendMode` - The blend mode to apply.
1614    pub fn set_blend_mode(&self, mode: BlendMode) {
1615        let _: Result<(), JsValue> = self
1616            .get_context()
1617            .set_global_composite_operation(mode.to_css());
1618    }
1619
1620    /// Applies a shadow configuration for subsequent draw operations.
1621    ///
1622    /// # Arguments
1623    ///
1624    /// - `&ShadowConfig` - The shadow configuration to apply.
1625    pub fn set_shadow(&self, config: &ShadowConfig) {
1626        self.get_context()
1627            .set_shadow_color(config.get_color().as_str());
1628        self.get_context().set_shadow_blur(config.get_blur());
1629        self.get_context()
1630            .set_shadow_offset_x(config.get_offset_x());
1631        self.get_context()
1632            .set_shadow_offset_y(config.get_offset_y());
1633    }
1634
1635    /// Clears any previously applied shadow, disabling shadow rendering.
1636    pub fn clear_shadow(&self) {
1637        self.get_context().set_shadow_color("rgba(0, 0, 0, 0)");
1638        self.get_context().set_shadow_blur(0.0);
1639        self.get_context().set_shadow_offset_x(0.0);
1640        self.get_context().set_shadow_offset_y(0.0);
1641    }
1642
1643    /// Applies a linear gradient as the fill style for subsequent operations.
1644    ///
1645    /// # Arguments
1646    ///
1647    /// - `&LinearGradient` - The linear gradient to use as fill style.
1648    pub fn set_linear_gradient_fill(&self, gradient: &LinearGradient) {
1649        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1650            self.get_context()
1651                .set_fill_style_canvas_gradient(&canvas_gradient);
1652        }
1653    }
1654
1655    /// Applies a radial gradient as the fill style for subsequent operations.
1656    ///
1657    /// # Arguments
1658    ///
1659    /// - `&RadialGradient` - The radial gradient to use as fill style.
1660    pub fn set_radial_gradient_fill(&self, gradient: &RadialGradient) {
1661        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1662            self.get_context()
1663                .set_fill_style_canvas_gradient(&canvas_gradient);
1664        }
1665    }
1666
1667    /// Applies a linear gradient as the stroke style for subsequent operations.
1668    ///
1669    /// # Arguments
1670    ///
1671    /// - `&LinearGradient` - The linear gradient to use as stroke style.
1672    pub fn set_linear_gradient_stroke(&self, gradient: &LinearGradient) {
1673        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1674            self.get_context()
1675                .set_stroke_style_canvas_gradient(&canvas_gradient);
1676        }
1677    }
1678
1679    /// Applies a radial gradient as the stroke style for subsequent operations.
1680    ///
1681    /// # Arguments
1682    ///
1683    /// - `&RadialGradient` - The radial gradient to use as stroke style.
1684    pub fn set_radial_gradient_stroke(&self, gradient: &RadialGradient) {
1685        if let Some(canvas_gradient) = gradient.to_gradient(self.get_context()) {
1686            self.get_context()
1687                .set_stroke_style_canvas_gradient(&canvas_gradient);
1688        }
1689    }
1690}
1691
1692/// Implements the `RenderBackend` trait for `CanvasRenderer`, providing
1693/// a backend-agnostic rendering interface.
1694///
1695/// Each method forwards to the inherent `CanvasRenderer` method of the
1696/// same name, so the per-call documentation lives on the trait definition
1697/// in `engine::renderer::trait` — the inherent method is the source of
1698/// truth, this impl is the trait bridge.
1699impl RenderBackend for CanvasRenderer {
1700    /// Forwards to [`CanvasRenderer::clear`].
1701    fn clear(&self) {
1702        self.clear();
1703    }
1704
1705    /// Forwards to [`CanvasRenderer::clear_color`].
1706    ///
1707    /// # Arguments
1708    ///
1709    /// - `C: AsRef<str>` - A generic type parameter.
1710    fn clear_color<C>(&self, color: C)
1711    where
1712        C: AsRef<str>,
1713    {
1714        self.clear_color(color);
1715    }
1716
1717    /// Forwards to [`CanvasRenderer::save`].
1718    fn save(&self) {
1719        self.save();
1720    }
1721
1722    /// Forwards to [`CanvasRenderer::restore`].
1723    fn restore(&self) {
1724        self.restore();
1725    }
1726
1727    /// Forwards to [`CanvasRenderer::set_fill_color`].
1728    ///
1729    /// # Arguments
1730    ///
1731    /// - `&str` - Shared reference to a `str`.
1732    fn set_fill_color(&self, color: &str) {
1733        self.set_fill_color(color);
1734    }
1735
1736    /// Forwards to [`CanvasRenderer::set_stroke_color`].
1737    ///
1738    /// # Arguments
1739    ///
1740    /// - `&str` - Shared reference to a `str`.
1741    fn set_stroke_color(&self, color: &str) {
1742        self.set_stroke_color(color);
1743    }
1744
1745    /// Forwards to [`CanvasRenderer::set_line_width`].
1746    ///
1747    /// # Arguments
1748    ///
1749    /// - `f64` - A 64-bit float (`f64`).
1750    fn set_line_width(&self, width: f64) {
1751        self.set_line_width(width);
1752    }
1753
1754    /// Forwards to [`CanvasRenderer::set_global_alpha`].
1755    ///
1756    /// # Arguments
1757    ///
1758    /// - `f64` - A 64-bit float (`f64`).
1759    fn set_global_alpha(&self, alpha: f64) {
1760        self.set_global_alpha(alpha);
1761    }
1762
1763    /// Forwards to [`CanvasRenderer::set_blend_mode`].
1764    ///
1765    /// # Arguments
1766    ///
1767    /// - `BlendMode` - A `BlendMode` parameter.
1768    fn set_blend_mode(&self, mode: BlendMode) {
1769        self.set_blend_mode(mode);
1770    }
1771
1772    /// Forwards to [`CanvasRenderer::set_shadow`].
1773    ///
1774    /// # Arguments
1775    ///
1776    /// - `&ShadowConfig` - Shared reference to a `ShadowConfig`.
1777    fn set_shadow(&self, config: &ShadowConfig) {
1778        self.set_shadow(config);
1779    }
1780
1781    /// Forwards to [`CanvasRenderer::clear_shadow`].
1782    fn clear_shadow(&self) {
1783        self.clear_shadow();
1784    }
1785
1786    /// Forwards to [`CanvasRenderer::fill_rect`].
1787    ///
1788    /// # Arguments
1789    ///
1790    /// - `Vector2D` - 2D vector (`Vector2D`).
1791    /// - `f64` - A 64-bit float (`f64`).
1792    /// - `f64` - A 64-bit float (`f64`).
1793    fn fill_rect(&self, position: Vector2D, width: f64, height: f64) {
1794        self.fill_rect(position, width, height);
1795    }
1796
1797    /// Forwards to [`CanvasRenderer::stroke_rect`].
1798    ///
1799    /// # Arguments
1800    ///
1801    /// - `Vector2D` - 2D vector (`Vector2D`).
1802    /// - `f64` - A 64-bit float (`f64`).
1803    /// - `f64` - A 64-bit float (`f64`).
1804    fn stroke_rect(&self, position: Vector2D, width: f64, height: f64) {
1805        self.stroke_rect(position, width, height);
1806    }
1807
1808    /// Forwards to [`CanvasRenderer::fill_circle`].
1809    ///
1810    /// # Arguments
1811    ///
1812    /// - `Vector2D` - 2D vector (`Vector2D`).
1813    /// - `f64` - A 64-bit float (`f64`).
1814    fn fill_circle(&self, center: Vector2D, radius: f64) {
1815        self.fill_circle(center, radius);
1816    }
1817
1818    /// Forwards to [`CanvasRenderer::stroke_circle`].
1819    ///
1820    /// # Arguments
1821    ///
1822    /// - `Vector2D` - 2D vector (`Vector2D`).
1823    /// - `f64` - A 64-bit float (`f64`).
1824    fn stroke_circle(&self, center: Vector2D, radius: f64) {
1825        self.stroke_circle(center, radius);
1826    }
1827
1828    /// Forwards to [`CanvasRenderer::draw_line`].
1829    ///
1830    /// # Arguments
1831    ///
1832    /// - `Vector2D` - 2D vector (`Vector2D`).
1833    /// - `Vector2D` - 2D vector (`Vector2D`).
1834    fn draw_line(&self, start: Vector2D, end: Vector2D) {
1835        self.draw_line(start, end);
1836    }
1837
1838    /// Forwards to [`CanvasRenderer::fill_text`].
1839    ///
1840    /// # Arguments
1841    ///
1842    /// - `&str` - Shared reference to a `str`.
1843    /// - `Vector2D` - 2D vector (`Vector2D`).
1844    fn fill_text(&self, text: &str, position: Vector2D) {
1845        self.fill_text(text, position);
1846    }
1847
1848    /// Forwards to [`CanvasRenderer::set_font`].
1849    ///
1850    /// # Arguments
1851    ///
1852    /// - `&str` - Shared reference to a `str`.
1853    fn set_font(&self, font: &str) {
1854        self.set_font(font);
1855    }
1856
1857    /// Forwards to [`CanvasRenderer::draw_image`].
1858    ///
1859    /// # Arguments
1860    ///
1861    /// - `&HtmlImageElement` - Shared reference to a `HtmlImageElement`.
1862    /// - `Vector2D` - 2D vector (`Vector2D`).
1863    /// - `f64` - A 64-bit float (`f64`).
1864    /// - `f64` - A 64-bit float (`f64`).
1865    fn draw_image(&self, image: &HtmlImageElement, position: Vector2D, width: f64, height: f64) {
1866        self.draw_image(image, position, width, height);
1867    }
1868
1869    /// Forwards to [`CanvasRenderer::set_linear_gradient_fill`].
1870    ///
1871    /// # Arguments
1872    ///
1873    /// - `&LinearGradient` - Shared reference to a `LinearGradient`.
1874    fn set_linear_gradient_fill(&self, gradient: &LinearGradient) {
1875        self.set_linear_gradient_fill(gradient);
1876    }
1877
1878    /// Forwards to [`CanvasRenderer::set_radial_gradient_fill`].
1879    ///
1880    /// # Arguments
1881    ///
1882    /// - `&RadialGradient` - Shared reference to a `RadialGradient`.
1883    fn set_radial_gradient_fill(&self, gradient: &RadialGradient) {
1884        self.set_radial_gradient_fill(gradient);
1885    }
1886}
1887
1888/// Implements async initialization and GPU resource creation for `WebGpuRenderer`.
1889impl WebGpuRenderer {
1890    /// Returns `true` if `navigator.gpu` is exposed on the current origin.
1891    ///
1892    /// This is the synchronous half of the canonical WebGPU capability
1893    /// probe used by Three.js (`examples/jsm/capabilities/WebGPU.js`): it
1894    /// only checks that the browser surfaces the `GPU` interface at all.
1895    /// It does **not** request an adapter — a present `navigator.gpu`
1896    /// does not guarantee that a usable GPU adapter is reachable (Linux
1897    /// software-rendered sessions, headless browsers, GPU-blacklisted
1898    /// devices and sandboxed iframes all expose `navigator.gpu` while
1899    /// `requestAdapter()` resolves to `null` or hangs forever).
1900    ///
1901    /// Use this as the cheapest pre-flight check before showing a
1902    /// "needs HTTPS or localhost" prompt. For a definitive answer use
1903    /// [`Self::probe`] which also awaits `requestAdapter()`.
1904    ///
1905    /// # Returns
1906    ///
1907    /// - `bool` - `true` when `navigator.gpu` is a non-null, non-undefined
1908    ///   object; `false` otherwise (including the "no `window`" runtime
1909    ///   case, which `web_sys::window()` returns `None` for).
1910    pub fn is_available() -> bool {
1911        let window_value: Window = match window() {
1912            Some(value) => value,
1913            None => return false,
1914        };
1915        let navigator: Navigator = window_value.navigator();
1916        let gpu_result: Result<JsValue, JsValue> = Reflect::get(
1917            navigator.as_ref(),
1918            &JsValue::from_str(WEBGPU_NAVIGATOR_GPU_KEY),
1919        );
1920        match gpu_result {
1921            Ok(value) => !value.is_undefined() && !value.is_null(),
1922            Err(_) => false,
1923        }
1924    }
1925
1926    /// Probes whether a WebGPU adapter can actually be acquired.
1927    ///
1928    /// Mirrors Three.js' canonical capability probe exactly:
1929    ///
1930    /// Wraps the adapter request in the same `Promise.race` timeout used
1931    /// by [`Self::init`] so that browsers which leave the adapter promise
1932    /// permanently pending (headless, sandboxed, device-lost) do not stall
1933    /// the UI forever. The timeout itself uses the
1934    /// `INIT_PROMISE_TIMEOUT_MILLIS` constant; on timeout, `probe` returns
1935    /// `false` rather than an error so callers can treat it the same as
1936    /// "no adapter".
1937    ///
1938    /// # Returns
1939    ///
1940    /// - `bool` - `true` only when both `navigator.gpu` is present and
1941    ///   `requestAdapter()` resolves to a non-null adapter within the
1942    ///   timeout window. `false` covers every other case (no `window`,
1943    ///   missing `navigator.gpu`, reflect exception, adapter promise
1944    ///   rejected or timed out, adapter resolved to `null`/`undefined`).
1945    pub async fn probe() -> bool {
1946        if !Self::is_available() {
1947            return false;
1948        }
1949        let window_value: Window = match window() {
1950            Some(value) => value,
1951            None => return false,
1952        };
1953        let navigator: Navigator = window_value.navigator();
1954        let gpu: JsValue = match Reflect::get(
1955            navigator.as_ref(),
1956            &JsValue::from_str(WEBGPU_NAVIGATOR_GPU_KEY),
1957        ) {
1958            Ok(value) => value,
1959            Err(_) => return false,
1960        };
1961        let request_adapter_fn: Function =
1962            match Reflect::get(&gpu, &JsValue::from_str(WEBGPU_METHOD_REQUEST_ADAPTER)) {
1963                Ok(value) => value.unchecked_into(),
1964                Err(_) => return false,
1965            };
1966        let adapter_promise: Promise = match request_adapter_fn.call0(&gpu) {
1967            Ok(value) => value.unchecked_into(),
1968            Err(_) => return false,
1969        };
1970        let adapter_value: JsValue =
1971            match JsFuture::from(Self::race_with_timeout(adapter_promise)).await {
1972                Ok(value) => value,
1973                Err(_) => return false,
1974            };
1975        !adapter_value.is_undefined() && !adapter_value.is_null()
1976    }
1977
1978    /// Asynchronously initializes a WebGPU renderer from the given render configuration.
1979    ///
1980    /// Requests a GPU adapter and device, obtains the WebGPU canvas context,
1981    /// and configures it with the preferred texture format. Returns `None` if
1982    /// WebGPU is not supported, the adapter/device request fails, or the canvas
1983    /// element is not found.
1984    ///
1985    /// # Arguments
1986    ///
1987    /// - `&RenderConfig` - The rendering configuration.
1988    ///
1989    /// # Returns
1990    ///
1991    /// - `Option<WebGpuRenderer>` - The initialized renderer, or `None` on failure.
1992    ///   Maximum time in milliseconds to wait for `requestAdapter` and
1993    ///   `requestDevice` before treating them as failed.
1994    ///
1995    /// Some browser GPU states (headless, no GPU, sandboxed, device-lost)
1996    /// leave the WebGPU adapter/device promises permanently pending instead
1997    /// of resolving to `null` or rejecting. Without a timeout the
1998    /// `JsFuture::from(...).await` inside `init` would hang forever and
1999    /// the UI would stay stuck on `Initializing...`. Wrapping each promise
2000    /// in `Promise.race` against a timer-rejected sibling forces the
2001    /// future to resolve so the caller's `let Some(...) = ... else { ... }`
2002    /// branch can run and report `WebGPU Not Supported`.
2003    /// Returns a Promise that rejects after `INIT_PROMISE_TIMEOUT_MILLIS`.
2004    fn timeout_promise() -> Promise {
2005        let Some(window_value) = window() else {
2006            return Promise::new(&mut |_resolve: Function, reject: Function| {
2007                let _: Result<JsValue, JsValue> = reject.call1(
2008                    &JsValue::UNDEFINED,
2009                    &JsValue::from_str(RENDERER_TIMEOUT_ERROR_MESSAGE),
2010                );
2011            });
2012        };
2013        Promise::new(&mut |_resolve: Function, reject: Function| {
2014            let reject_fn: Function = reject.clone();
2015            let timer: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
2016                let _: Result<JsValue, JsValue> = reject_fn.call1(
2017                    &JsValue::UNDEFINED,
2018                    &JsValue::from_str(RENDERER_TIMEOUT_ERROR_MESSAGE),
2019                );
2020            }));
2021            let _: Result<i32, JsValue> = window_value
2022                .set_timeout_with_callback_and_timeout_and_arguments_0(
2023                    timer.as_ref().unchecked_ref(),
2024                    INIT_PROMISE_TIMEOUT_MILLIS,
2025                );
2026            timer.forget();
2027        })
2028    }
2029
2030    /// Wraps `promise` in `Promise.race([promise, timeout_promise()])` so that
2031    /// awaiting it never blocks longer than `INIT_PROMISE_TIMEOUT_MILLIS`.
2032    ///
2033    /// Calls `Promise.race` via reflection because wasm-bindgen does not
2034    /// currently expose the static `race` method on `Promise`.
2035    ///
2036    /// # Arguments
2037    ///
2038    /// - `Promise` - A `Promise` parameter.
2039    ///
2040    /// # Returns
2041    ///
2042    /// - `Promise` - A `Promise` value.
2043    fn race_with_timeout(promise: Promise) -> Promise {
2044        let array: Array = Array::of2(&promise, &Self::timeout_promise());
2045        Promise::race(&array)
2046    }
2047
2048    /// Asynchronously initializes a WebGPU renderer from the given render configuration.
2049    ///
2050    /// Requests a GPU adapter and device, obtains the WebGPU canvas context,
2051    /// and configures it with the preferred texture format. Returns `Err` if
2052    /// WebGPU is not supported, the adapter/device request fails, the canvas
2053    /// element is not found, or the adapter/device request hangs beyond
2054    /// `INIT_PROMISE_TIMEOUT_MILLIS` (a defensive timeout for browser GPU
2055    /// states that leave the WebGPU promises permanently pending).
2056    ///
2057    /// The engine no longer logs diagnostic output internally; instead each
2058    /// failure mode is returned as a distinct `WebGpuInitError` variant so
2059    /// the caller can decide how to surface it (typically via `Console::error`
2060    /// or by falling back to the Canvas 2D backend).
2061    ///
2062    /// # Arguments
2063    ///
2064    /// - `&RenderConfig` - The rendering configuration.
2065    ///
2066    /// # Returns
2067    ///
2068    /// - `Result<WebGpuRenderer, WebGpuInitError>` - The initialized renderer, or
2069    ///   a typed error describing the specific failure.
2070    pub async fn init(config: &RenderConfig) -> Result<WebGpuRenderer, WebGpuInitError> {
2071        let Some(window) = window() else {
2072            return Err(WebGpuInitError::NavigatorGpuMissing);
2073        };
2074        let navigator: Navigator = window.navigator();
2075        let gpu_result: Result<JsValue, JsValue> = Reflect::get(
2076            navigator.as_ref(),
2077            &JsValue::from_str(WEBGPU_NAVIGATOR_GPU_KEY),
2078        );
2079        let gpu: JsValue = match gpu_result {
2080            Ok(value) => value,
2081            Err(err) => return Err(WebGpuInitError::NavigatorLookup(err)),
2082        };
2083        if gpu.is_undefined() || gpu.is_null() {
2084            return Err(WebGpuInitError::NavigatorGpuMissing);
2085        }
2086        let adapter_options: Object = Object::new();
2087        let _: Result<bool, JsValue> = Reflect::set(
2088            &adapter_options,
2089            &JsValue::from_str(WEBGPU_PROPERTY_POWER_PREFERENCE),
2090            &JsValue::from_str(config.power_preference.to_web_sys_string()),
2091        );
2092        let request_adapter_fn: Function =
2093            match Reflect::get(&gpu, &JsValue::from_str(WEBGPU_METHOD_REQUEST_ADAPTER)) {
2094                Ok(value) => value.unchecked_into(),
2095                Err(err) => return Err(WebGpuInitError::RequestAdapterLookup(err)),
2096            };
2097        let adapter_promise: Promise = match request_adapter_fn.call1(&gpu, &adapter_options) {
2098            Ok(value) => value.unchecked_into(),
2099            Err(err) => return Err(WebGpuInitError::RequestAdapterCall(err)),
2100        };
2101        let adapter_value: JsValue =
2102            match JsFuture::from(Self::race_with_timeout(adapter_promise)).await {
2103                Ok(value) => value,
2104                Err(err) => return Err(WebGpuInitError::AdapterPromise(err)),
2105            };
2106        if adapter_value.is_null() || adapter_value.is_undefined() {
2107            return Err(WebGpuInitError::AdapterUnavailable);
2108        }
2109        let device_descriptor: Object = Object::new();
2110        let request_device_fn: Function = match Reflect::get(
2111            &adapter_value,
2112            &JsValue::from_str(WEBGPU_METHOD_REQUEST_DEVICE),
2113        ) {
2114            Ok(value) => value.unchecked_into(),
2115            Err(err) => return Err(WebGpuInitError::RequestDeviceLookup(err)),
2116        };
2117        let device_promise: Promise =
2118            match request_device_fn.call1(&adapter_value, &device_descriptor) {
2119                Ok(value) => value.unchecked_into(),
2120                Err(err) => return Err(WebGpuInitError::RequestDeviceCall(err)),
2121            };
2122        let device_value: JsValue =
2123            match JsFuture::from(Self::race_with_timeout(device_promise)).await {
2124                Ok(value) => value,
2125                Err(err) => return Err(WebGpuInitError::DevicePromise(err)),
2126            };
2127        if device_value.is_null() || device_value.is_undefined() {
2128            return Err(WebGpuInitError::DeviceUnavailable);
2129        }
2130        let Some(document) = window.document() else {
2131            return Err(WebGpuInitError::CanvasNotFound(
2132                config.canvas_selector.clone(),
2133            ));
2134        };
2135        let element: Element = match document.query_selector(&config.canvas_selector) {
2136            Ok(Some(el)) => el,
2137            Ok(None) => {
2138                return Err(WebGpuInitError::CanvasNotFound(
2139                    config.canvas_selector.clone(),
2140                ));
2141            }
2142            Err(err) => return Err(WebGpuInitError::CanvasQuery(err)),
2143        };
2144        let canvas: HtmlCanvasElement = element.unchecked_into();
2145        let context_object: Option<Object> = canvas.get_context(WEBGPU_CONTEXT_TYPE).ok().flatten();
2146        let context_object: Object = match context_object {
2147            Some(c) => c,
2148            None => return Err(WebGpuInitError::CanvasContextUnavailable),
2149        };
2150        let context: JsValue = context_object.into();
2151        let get_format_fn: Function =
2152            match Reflect::get(&gpu, &JsValue::from_str(WEBGPU_METHOD_GET_PREFERRED_FORMAT)) {
2153                Ok(value) => value.unchecked_into(),
2154                Err(err) => return Err(WebGpuInitError::PreferredFormatLookup(err)),
2155            };
2156        let format_value: JsValue = match get_format_fn.call0(&gpu) {
2157            Ok(value) => value,
2158            Err(err) => return Err(WebGpuInitError::PreferredFormatCall(err)),
2159        };
2160        let format: String = match format_value.as_string() {
2161            Some(s) => s,
2162            None => return Err(WebGpuInitError::PreferredFormatType(format_value)),
2163        };
2164        // WebGPU's `configure` requires the canvas backing-store size to be
2165        // set BEFORE calling configure, otherwise the swap chain is created
2166        // at 0x0 and the first getCurrentTexture() returns an error.
2167        let dpr: f64 = CanvasRenderer::detect_dpr();
2168        let physical_width: u32 = (config.width * dpr).round() as u32;
2169        let physical_height: u32 = (config.height * dpr).round() as u32;
2170        canvas.set_width(physical_width);
2171        canvas.set_height(physical_height);
2172        let canvas_config: Object = Object::new();
2173        let _: Result<bool, JsValue> = Reflect::set(
2174            &canvas_config,
2175            &JsValue::from_str(WEBGPU_PROPERTY_DEVICE),
2176            &device_value,
2177        );
2178        let _: Result<bool, JsValue> = Reflect::set(
2179            &canvas_config,
2180            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
2181            &format_value,
2182        );
2183        let configure_fn: Function =
2184            match Reflect::get(&context, &JsValue::from_str(WEBGPU_METHOD_CONFIGURE)) {
2185                Ok(value) => value.unchecked_into(),
2186                Err(err) => return Err(WebGpuInitError::ConfigureLookup(err)),
2187            };
2188        let _: Result<JsValue, JsValue> = configure_fn.call1(&context, &canvas_config);
2189        let queue: JsValue =
2190            match Reflect::get(&device_value, &JsValue::from_str(WEBGPU_PROPERTY_QUEUE)) {
2191                Ok(value) => value,
2192                Err(err) => return Err(WebGpuInitError::QueueLookup(err)),
2193            };
2194        Ok(WebGpuRenderer {
2195            device: device_value,
2196            queue,
2197            context,
2198            canvas,
2199            format,
2200            width: physical_width,
2201            height: physical_height,
2202            antialias: config.antialias,
2203            multisample_texture: None,
2204            multisample_view: None,
2205            depth_texture: None,
2206            depth_view: None,
2207            depth_format: None,
2208            device_lost_callback: None,
2209            device_lost: false,
2210            pending_error: Rc::new(PendingErrorCell::new()),
2211            command_encoder: None,
2212            render_pass_descriptor_cache: None,
2213        })
2214    }
2215
2216    /// Allocates the multisampled intermediate texture used for MSAA.
2217    ///
2218    /// The returned tuple is `(GpuTexture, GpuTextureView)`:
2219    /// - `GpuTexture` has `sampleCount: 4` and `usage: RENDER_ATTACHMENT`
2220    ///   so it can be bound as a color attachment in `beginRenderPass`.
2221    /// - `GpuTextureView` is the default 2D view used as the color
2222    ///   attachment; the swap chain view is the `resolveTarget`.
2223    ///
2224    /// The texture size must match the swap chain physical size; mismatches
2225    /// are a WebGPU validation error. Returns `(JsValue::UNDEFINED,
2226    /// JsValue::UNDEFINED)` when allocation fails so callers can detect and
2227    /// fall back to MSAA=1.
2228    ///
2229    /// # Arguments
2230    ///
2231    /// - `u32` - Physical pixel width (DPR-multiplied).
2232    /// - `u32` - Physical pixel height.
2233    ///
2234    /// # Returns
2235    ///
2236    /// - `(JsValue, JsValue)` - The new texture and its default view, or
2237    ///   `JsValue::UNDEFINED` for both on allocation failure.
2238    fn create_multisample_texture(
2239        &self,
2240        physical_width: u32,
2241        physical_height: u32,
2242    ) -> (JsValue, JsValue) {
2243        let extent: Object = Object::new();
2244        let _: Result<bool, JsValue> = Reflect::set(
2245            &extent,
2246            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
2247            &JsValue::from_f64(f64::from(physical_width)),
2248        );
2249        let _: Result<bool, JsValue> = Reflect::set(
2250            &extent,
2251            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
2252            &JsValue::from_f64(f64::from(physical_height)),
2253        );
2254        let _: Result<bool, JsValue> = Reflect::set(
2255            &extent,
2256            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
2257            &JsValue::from_f64(1.0),
2258        );
2259        let descriptor: Object = Object::new();
2260        let _: Result<bool, JsValue> = Reflect::set(
2261            &descriptor,
2262            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
2263            &extent,
2264        );
2265        let _: Result<bool, JsValue> = Reflect::set(
2266            &descriptor,
2267            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
2268            &JsValue::from_str(&self.get_format()),
2269        );
2270        let _: Result<bool, JsValue> = Reflect::set(
2271            &descriptor,
2272            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
2273            &JsValue::from_f64(WEBGPU_TEXTURE_USAGE_RENDER_ATTACHMENT),
2274        );
2275        let _: Result<bool, JsValue> = Reflect::set(
2276            &descriptor,
2277            &JsValue::from_str(WEBGPU_PROPERTY_SAMPLE_COUNT),
2278            &JsValue::from_f64(4.0),
2279        );
2280        let create_texture_fn: Function = Reflect::get(
2281            self.get_device(),
2282            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
2283        )
2284        .unwrap_or(JsValue::UNDEFINED)
2285        .unchecked_into();
2286        let texture: JsValue = create_texture_fn
2287            .call1(self.get_device(), &descriptor)
2288            .unwrap_or(JsValue::UNDEFINED);
2289        if texture.is_undefined() {
2290            return (JsValue::UNDEFINED, JsValue::UNDEFINED);
2291        }
2292        let create_view_fn: Function =
2293            Reflect::get(&texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
2294                .unwrap_or(JsValue::UNDEFINED)
2295                .unchecked_into();
2296        let view: JsValue = create_view_fn.call0(&texture).unwrap_or(JsValue::UNDEFINED);
2297        if view.is_undefined() {
2298            return (texture, JsValue::UNDEFINED);
2299        }
2300        (texture, view)
2301    }
2302
2303    /// Resizes the canvas backing store and reconfigures the swap chain.
2304    ///
2305    /// WebGPU's `GpuCanvasContext.configure` is sticky: it sets the texture
2306    /// format and device once, but the swap chain tracks the canvas's
2307    /// `width`/`height` attributes. When the CSS layout size changes (a
2308    /// window resize, a panel toggle, a DPR change) the canvas keeps its
2309    /// old physical dimensions unless we explicitly update `width`/`height`
2310    /// and call `configure` again. Without this, subsequent
2311    /// `getCurrentTexture()` calls return a texture that no longer matches
2312    /// the visible region and the frame either stretches or freezes.
2313    ///
2314    /// Re-`configure`ing with the same `device` + `format` is the
2315    /// spec-defined way to swap in a fresh swap chain bound to the new
2316    /// backing-store size.
2317    ///
2318    /// # Arguments
2319    ///
2320    /// - `u32` - The new physical pixel width (already multiplied by DPR).
2321    /// - `u32` - The new physical pixel height.
2322    ///
2323    /// # Returns
2324    ///
2325    /// - `bool` - `true` on success, `false` if the swap chain or canvas
2326    ///   handles were missing or `configure` failed.
2327    pub fn resize(&mut self, physical_width: u32, physical_height: u32) -> bool {
2328        if self.get_canvas().is_null()
2329            || self.get_context().is_null()
2330            || self.get_device().is_undefined()
2331        {
2332            return false;
2333        }
2334        self.get_canvas().set_width(physical_width);
2335        self.get_canvas().set_height(physical_height);
2336        let format_value: JsValue = JsValue::from_str(&self.get_format());
2337        let canvas_config: Object = Object::new();
2338        let _: Result<bool, JsValue> = Reflect::set(
2339            &canvas_config,
2340            &JsValue::from_str(WEBGPU_PROPERTY_DEVICE),
2341            self.get_device(),
2342        );
2343        let _: Result<bool, JsValue> = Reflect::set(
2344            &canvas_config,
2345            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
2346            &format_value,
2347        );
2348        let configure_fn: Function = Reflect::get(
2349            self.get_context(),
2350            &JsValue::from_str(WEBGPU_METHOD_CONFIGURE),
2351        )
2352        .ok()
2353        .and_then(|value: JsValue| value.dyn_into::<Function>().ok())
2354        .unwrap_or_else(|| Function::new_no_args(""));
2355        if configure_fn
2356            .call1(self.get_context(), &canvas_config)
2357            .is_err()
2358        {
2359            return false;
2360        }
2361        self.set_width(physical_width);
2362        self.set_height(physical_height);
2363        // Rebuild the multisampled color texture to match the new backing
2364        // store size. `GpuTexture` width/height are immutable, so MSAA
2365        // requires recreating it on every resize. The previous texture (if
2366        // any) is left to the GPU's GC; we do not explicitly destroy it
2367        // because `destroy()` is a synchronous WebGPU call and the old
2368        // texture is no longer referenced by any in-flight command buffer
2369        // at this point in the frame loop.
2370        if self.get_antialias() {
2371            let (texture, view) = self.create_multisample_texture(physical_width, physical_height);
2372            if !view.is_undefined() {
2373                self.set_multisample_texture(Some(texture));
2374                self.set_multisample_view(Some(view));
2375            } else {
2376                self.set_multisample_texture(None);
2377                self.set_multisample_view(None);
2378            }
2379        }
2380        true
2381    }
2382
2383    /// Resizes the canvas backing store to match the canvas element's
2384    /// current CSS-rendered size in physical pixels (DPR applied).
2385    ///
2386    /// This is the right entry point when the render loop does not know
2387    /// the desired logical size ahead of time and wants to follow the
2388    /// element's actual layout box. It is also useful as a defensive
2389    /// recovery when the canvas was created while hidden (zero-sized
2390    /// parent) and is later shown at its real size.
2391    ///
2392    /// Reads `client_width` / `client_height` from the canvas element,
2393    /// multiplies by `detect_dpr()`, and forwards to [`Self::resize`].
2394    ///
2395    /// # Returns
2396    ///
2397    /// - `bool` - `true` if the resize succeeded, `false` if the canvas
2398    ///   was zero-sized (nothing to render to), detached (CSS layout
2399    ///   box collapses to 0), or the underlying resize rejected.
2400    pub fn sync_to_current_canvas(&mut self) -> bool {
2401        let canvas_width: u32 = self.get_canvas().width();
2402        let canvas_height: u32 = self.get_canvas().height();
2403        let client_width: u32 = self
2404            .get_canvas()
2405            .client_width()
2406            .try_into()
2407            .unwrap_or_default();
2408        let client_height: u32 = self
2409            .get_canvas()
2410            .client_height()
2411            .try_into()
2412            .unwrap_or_default();
2413        // Prefer the CSS layout box when it is non-zero. If the canvas
2414        // is hidden the client box collapses to 0; in that case fall
2415        // back to the current backing-store size so we do not
2416        // gratuitously resize to 0.
2417        let css_w: u32 = if client_width > 0 {
2418            client_width
2419        } else {
2420            canvas_width
2421        };
2422        let css_h: u32 = if client_height > 0 {
2423            client_height
2424        } else {
2425            canvas_height
2426        };
2427        if css_w == 0 || css_h == 0 {
2428            return false;
2429        }
2430        let dpr: f64 = CanvasRenderer::detect_dpr();
2431        let physical_width: u32 = (f64::from(css_w) * dpr).round() as u32;
2432        let physical_height: u32 = (f64::from(css_h) * dpr).round() as u32;
2433        self.resize(physical_width, physical_height)
2434    }
2435
2436    /// Creates a shader module from WGSL source code.
2437    ///
2438    /// # Arguments
2439    ///
2440    /// - `S: AsRef<str>` - The WGSL shader source code.
2441    ///
2442    /// # Returns
2443    ///
2444    /// - `JsValue` - The created shader module as a JavaScript value.
2445    pub(crate) fn create_shader_module<S>(&self, code: S) -> JsValue
2446    where
2447        S: AsRef<str>,
2448    {
2449        let descriptor: Object = Object::new();
2450        let _: Result<bool, JsValue> = Reflect::set(
2451            &descriptor,
2452            &JsValue::from_str(WEBGPU_PROPERTY_CODE),
2453            &JsValue::from_str(code.as_ref()),
2454        );
2455        let create_fn: Function = Reflect::get(
2456            self.get_device(),
2457            &JsValue::from_str(WEBGPU_METHOD_CREATE_SHADER_MODULE),
2458        )
2459        .unwrap_or(JsValue::UNDEFINED)
2460        .unchecked_into();
2461        create_fn
2462            .call1(self.get_device(), &descriptor)
2463            .unwrap_or(JsValue::UNDEFINED)
2464    }
2465
2466    /// Creates a new command encoder for recording GPU commands.
2467    ///
2468    /// # Returns
2469    ///
2470    /// - `JsValue` - The created command encoder as a JavaScript value.
2471    pub fn create_command_encoder(&self) -> JsValue {
2472        // OPT 2b: cached `device.createCommandEncoder()` — `Function`
2473        // is the same prototype slot for the device's lifetime, so
2474        // skipping the `Reflect::get` shaves ~110ns per frame.
2475        let create_fn: Function =
2476            cached_method(self.get_device(), WEBGPU_METHOD_CREATE_COMMAND_ENCODER)
2477                .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2478        create_fn
2479            .call0(self.get_device())
2480            .unwrap_or(JsValue::UNDEFINED)
2481    }
2482
2483    /// Returns the current texture view from the canvas swap chain.
2484    ///
2485    /// This texture view should be used as the color attachment target for
2486    /// render passes. The texture is automatically presented to the canvas
2487    /// when the command buffer is submitted.
2488    ///
2489    /// # Returns
2490    ///
2491    /// - `JsValue` - The current frame's texture view as a JavaScript value.
2492    pub(crate) fn get_current_texture_view(&self) -> JsValue {
2493        // OPT 2b: cached `context.getCurrentTexture()` and the
2494        // resulting `texture.createView()`. Both methods live on
2495        // stable prototypes, so the `Function` reference is stable
2496        // for the receiver's lifetime.
2497        let get_texture_fn: Function =
2498            cached_method(self.get_context(), WEBGPU_METHOD_GET_CURRENT_TEXTURE)
2499                .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2500        let texture: JsValue = get_texture_fn
2501            .call0(self.get_context())
2502            .unwrap_or(JsValue::UNDEFINED);
2503        let create_view_fn: Function = cached_method(&texture, WEBGPU_METHOD_CREATE_VIEW)
2504            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2505        create_view_fn.call0(&texture).unwrap_or(JsValue::UNDEFINED)
2506    }
2507
2508    /// Begins a render pass on the given command encoder with a clear color.
2509    ///
2510    /// The render pass targets the canvas's current texture and clears it
2511    /// to the specified color. The returned `JsValue` is a `GpuRenderPassEncoder`
2512    /// that can be used to issue draw commands. The pass must be ended (via `end()`)
2513    /// before the command encoder is finished.
2514    ///
2515    /// This is a thin convenience wrapper over
2516    /// [`WebGpuRenderer::begin_render_pass_full`]. For pipelines that
2517    /// need depth testing, multiple color attachments, MSAA control,
2518    /// or `load`/`store` op customization, use the full version with
2519    /// a [`RenderPassColorAttachment`] (and optional
2520    /// [`RenderPassDepthStencilAttachment`]).
2521    ///
2522    /// # Arguments
2523    ///
2524    /// - `&JsValue` - The command encoder to begin the pass on.
2525    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
2526    ///
2527    /// # Returns
2528    ///
2529    /// - `JsValue` - The active render pass encoder as a JavaScript value.
2530    pub fn begin_render_pass(
2531        &mut self,
2532        encoder: &JsValue,
2533        clear_color: (f64, f64, f64, f64),
2534    ) -> JsValue {
2535        let mut color: RenderPassColorAttachment = RenderPassColorAttachment {
2536            view: None,
2537            resolve_target: None,
2538            clear_value: Some(clear_color),
2539            load_op: None,
2540            store_op: None,
2541        };
2542        self.begin_render_pass_full(encoder, &mut color, None)
2543    }
2544
2545    /// Begins a render pass with full control over attachments, load/store
2546    /// ops, MSAA resolve targets, and an optional depth-stencil attachment.
2547    ///
2548    /// This is the "complete" render-pass API used by the rest of the
2549    /// engine. All other render-pass entry points (including the
2550    /// legacy `begin_render_pass(clear_color)` wrapper) funnel through
2551    /// here.
2552    ///
2553    /// The color attachment's `view` is filled in lazily when `None`:
2554    /// if `antialias == true` and the multisample intermediate is
2555    /// available (or can be allocated), the pass draws into the MSAA
2556    /// view and resolves into the swap chain; otherwise it draws
2557    /// directly into the swap chain. The `resolve_target` is filled in
2558    /// with the swap-chain view when MSAA is active and the caller
2559    /// did not provide one.
2560    ///
2561    /// # Arguments
2562    ///
2563    /// - `encoder` - The `GpuCommandEncoder` to begin the pass on.
2564    /// - `color` - The color attachment descriptor. `color.view` and
2565    ///   `color.resolve_target` may be `None`; they are filled in with
2566    ///   the renderer's defaults.
2567    /// - `depth` - An optional depth-stencil attachment. `Some(...)`
2568    ///   adds a `depthStencilAttachment` field to the pass
2569    ///   descriptor; `None` omits it entirely.
2570    ///
2571    /// # Returns
2572    ///
2573    /// - `JsValue` - The active `GpuRenderPassEncoder` as a JavaScript
2574    ///   value, suitable for the existing `set_pipeline` / `draw` /
2575    ///   `end_render_pass` calls.
2576    pub fn begin_render_pass_full(
2577        &mut self,
2578        encoder: &JsValue,
2579        color: &mut RenderPassColorAttachment,
2580        depth: Option<&RenderPassDepthStencilAttachment>,
2581    ) -> JsValue {
2582        let swap_chain_view: JsValue = self.get_current_texture_view();
2583        // Resolve MSAA view + resolve target with the same policy as
2584        // the legacy `begin_render_pass`: prefer the existing
2585        // multisample view, lazily allocate it if missing, and fall
2586        // back to direct-to-swap-chain if MSAA allocation fails.
2587        let (color_view, resolve_view): (JsValue, Option<JsValue>) = match color.view.take() {
2588            Some(view) if !view.is_undefined() => (view, color.resolve_target.take()),
2589            _ => {
2590                if self.get_antialias() {
2591                    let multisample_view: Option<JsValue> = self
2592                        .get_multisample_view()
2593                        .clone()
2594                        .filter(|value: &JsValue| !value.is_undefined());
2595                    let resolved: Option<JsValue> = match multisample_view {
2596                        Some(view) => Some(view),
2597                        None => {
2598                            let width: u32 = self.get_width();
2599                            let height: u32 = self.get_height();
2600                            let (texture, view): (JsValue, JsValue) =
2601                                self.create_multisample_texture(width, height);
2602                            if !view.is_undefined() {
2603                                self.set_multisample_texture(Some(texture));
2604                                self.set_multisample_view(Some(view.clone()));
2605                                Some(view)
2606                            } else {
2607                                self.set_multisample_texture(None);
2608                                self.set_multisample_view(None);
2609                                None
2610                            }
2611                        }
2612                    };
2613                    match resolved {
2614                        Some(view) => (view, Some(swap_chain_view.clone())),
2615                        None => (swap_chain_view.clone(), None),
2616                    }
2617                } else {
2618                    (swap_chain_view.clone(), None)
2619                }
2620            }
2621        };
2622        // OPT 34: cache the render-pass descriptor across frames so
2623        // we only allocate the JS `Object`/`Array` once and only
2624        // rewrite the fields that actually change between frames
2625        // (typically `clearValue`). The cache is invalidated on
2626        // load/store op or depth-stencil shape changes (rare).
2627        //
2628        // Effective ops are `&'static str` (from `WEBGPU_*_OP_*`
2629        // constants), so a pointer-compare detects "caller switched
2630        // ops" with zero cost.
2631        let effective_load_op: &'static str = color.effective_load_op();
2632        let effective_store_op: &'static str = color.effective_store_op();
2633        let has_depth: bool = depth.is_some();
2634        let cache_needs_rebuild: bool = match self.render_pass_descriptor_cache.as_ref() {
2635            None => true,
2636            Some(existing) => {
2637                existing.last_load_op != Some(effective_load_op)
2638                    || existing.last_store_op != Some(effective_store_op)
2639                    || existing.last_has_depth != has_depth
2640            }
2641        };
2642        if cache_needs_rebuild {
2643            self.render_pass_descriptor_cache = Some(self.build_render_pass_descriptor(
2644                &color_view,
2645                resolve_view.as_ref(),
2646                color.clear_value,
2647                effective_load_op,
2648                effective_store_op,
2649                depth,
2650            ));
2651        }
2652        // `Some(_)` invariant: either the cache was non-None at the
2653        // top of this function (we only land in the None branch when
2654        // `cache_needs_rebuild` was true, in which case we just set
2655        // it above) or the caller passed us a renderer with no
2656        // descriptor cache yet and we built one. In both cases the
2657        // `Some` arm is the only reachable branch; we fall back to
2658        // a freshly-built empty cache (and emit no `beginRenderPass`
2659        // call) only if the impossible happened — `build_*` returned
2660        // a cache that was somehow dropped between the two lines,
2661        // which it cannot (no panic path, no early return).
2662        let cache: &RenderPassDescriptorCache = match self.render_pass_descriptor_cache.as_ref() {
2663            Some(c) => c,
2664            None => {
2665                // Defensive: build a no-op cache so the renderer's
2666                // caller sees a stable `JsValue::UNDEFINED` rather
2667                // than a dangling call. This branch is unreachable
2668                // under the invariant above.
2669                return JsValue::UNDEFINED;
2670            }
2671        };
2672        // Hot path: only the `clearValue` (and sometimes `view`) is
2673        // mutated between frames. We update the cached `view` and
2674        // `clearValue` Object's `r`/`g`/`b`/`a` properties
2675        // unconditionally — `Reflect::set` is a fast pointer write
2676        // when the value differs, and the JS-side property setter
2677        // accepts the same numeric value with no observable change.
2678        let _: Result<bool, JsValue> = Reflect::set(
2679            &cache.attachment,
2680            &cached_method_name(WEBGPU_PROPERTY_VIEW),
2681            &color_view,
2682        );
2683        if let Some(cv) = color.clear_value {
2684            let _: Result<bool, JsValue> = Reflect::set(
2685                &cache.clear_value,
2686                &cached_method_name(WEBGPU_PROPERTY_R),
2687                &JsValue::from_f64(cv.0),
2688            );
2689            let _: Result<bool, JsValue> = Reflect::set(
2690                &cache.clear_value,
2691                &cached_method_name(WEBGPU_PROPERTY_G),
2692                &JsValue::from_f64(cv.1),
2693            );
2694            let _: Result<bool, JsValue> = Reflect::set(
2695                &cache.clear_value,
2696                &cached_method_name(WEBGPU_PROPERTY_B),
2697                &JsValue::from_f64(cv.2),
2698            );
2699            let _: Result<bool, JsValue> = Reflect::set(
2700                &cache.clear_value,
2701                &cached_method_name(WEBGPU_PROPERTY_A),
2702                &JsValue::from_f64(cv.3),
2703            );
2704            // `attachment.clearValue` always points at the same
2705            // `clear_value` Object, so we only need to set it on the
2706            // very first call (i.e. when the cache was just built).
2707            // Subsequent calls leave the link intact.
2708            if cache_needs_rebuild {
2709                let _: Result<bool, JsValue> = Reflect::set(
2710                    &cache.attachment,
2711                    &cached_method_name(WEBGPU_PROPERTY_CLEAR_VALUE),
2712                    &cache.clear_value,
2713                );
2714            }
2715        }
2716        // `resolveTarget` and the `descriptor.colorAttachments[0]`
2717        // slot are stable for the cache's lifetime; they were set
2718        // once when the descriptor was built.
2719        let begin_fn: Function = cached_method(encoder, WEBGPU_METHOD_BEGIN_RENDER_PASS)
2720            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
2721        begin_fn
2722            .call1(encoder, &cache.descriptor)
2723            .unwrap_or(JsValue::UNDEFINED)
2724    }
2725
2726    /// OPT 34 helper: build a fresh `RenderPassDescriptorCache` from
2727    /// scratch. Called from [`WebGpuRenderer::begin_render_pass_full`]
2728    /// on cache miss (first call, op change, or depth-shape change).
2729    ///
2730    /// The constructed cache holds:
2731    /// - `descriptor`: the top-level `GpuRenderPassDescriptor`
2732    ///   Object, passed directly to `encoder.beginRenderPass`.
2733    /// - `color_attachments`: a length-1 `Array` containing the
2734    ///   cached `attachment` Object.
2735    /// - `attachment`: the inner color attachment Object.
2736    /// - `clear_value`: the `{r, g, b, a}` dictionary under
2737    ///   `attachment.clearValue`. This is the only Object whose
2738    ///   fields are mutated per frame.
2739    /// - `last_load_op` / `last_store_op`: the `&'static str` ops
2740    ///   applied to the descriptor this frame, used to detect
2741    ///   caller-driven op changes.
2742    /// - `last_has_depth`: whether the descriptor had a
2743    ///   `depthStencilAttachment`, used to detect shape changes.
2744    ///
2745    /// # Arguments
2746    ///
2747    /// - `color_view` - The `GpuTextureView` for the color attachment.
2748    /// - `resolve_view` - Optional resolve target (MSAA only).
2749    /// - `clear_value` - Optional `(r, g, b, a)` clear color.
2750    /// - `effective_load_op` - The `&'static str` load op to encode.
2751    /// - `effective_store_op` - The `&'static str` store op to encode.
2752    /// - `depth` - Optional depth-stencil attachment.
2753    fn build_render_pass_descriptor(
2754        &mut self,
2755        color_view: &JsValue,
2756        resolve_view: Option<&JsValue>,
2757        clear_value: Option<(f64, f64, f64, f64)>,
2758        effective_load_op: &'static str,
2759        effective_store_op: &'static str,
2760        depth: Option<&RenderPassDepthStencilAttachment>,
2761    ) -> RenderPassDescriptorCache {
2762        let attachment: Object = Object::new();
2763        let _: Result<bool, JsValue> = Reflect::set(
2764            &attachment,
2765            &cached_method_name(WEBGPU_PROPERTY_VIEW),
2766            color_view,
2767        );
2768        let _: Result<bool, JsValue> = Reflect::set(
2769            &attachment,
2770            &cached_method_name(WEBGPU_PROPERTY_LOAD_OP),
2771            &JsValue::from_str(effective_load_op),
2772        );
2773        let _: Result<bool, JsValue> = Reflect::set(
2774            &attachment,
2775            &cached_method_name(WEBGPU_PROPERTY_STORE_OP),
2776            &JsValue::from_str(effective_store_op),
2777        );
2778        let clear_value_obj: Object = Object::new();
2779        if let Some(cv) = clear_value {
2780            let _: Result<bool, JsValue> = Reflect::set(
2781                &clear_value_obj,
2782                &cached_method_name(WEBGPU_PROPERTY_R),
2783                &JsValue::from_f64(cv.0),
2784            );
2785            let _: Result<bool, JsValue> = Reflect::set(
2786                &clear_value_obj,
2787                &cached_method_name(WEBGPU_PROPERTY_G),
2788                &JsValue::from_f64(cv.1),
2789            );
2790            let _: Result<bool, JsValue> = Reflect::set(
2791                &clear_value_obj,
2792                &cached_method_name(WEBGPU_PROPERTY_B),
2793                &JsValue::from_f64(cv.2),
2794            );
2795            let _: Result<bool, JsValue> = Reflect::set(
2796                &clear_value_obj,
2797                &cached_method_name(WEBGPU_PROPERTY_A),
2798                &JsValue::from_f64(cv.3),
2799            );
2800            let _: Result<bool, JsValue> = Reflect::set(
2801                &attachment,
2802                &cached_method_name(WEBGPU_PROPERTY_CLEAR_VALUE),
2803                &clear_value_obj,
2804            );
2805        }
2806        if let Some(target) = resolve_view {
2807            let _: Result<bool, JsValue> = Reflect::set(
2808                &attachment,
2809                &cached_method_name(WEBGPU_PROPERTY_RESOLVE_TARGET),
2810                target,
2811            );
2812        }
2813        let color_attachments: Array = Array::new();
2814        color_attachments.push(&attachment);
2815        let descriptor: Object = Object::new();
2816        let _: Result<bool, JsValue> = Reflect::set(
2817            &descriptor,
2818            &cached_method_name(WEBGPU_PROPERTY_COLOR_ATTACHMENTS),
2819            &color_attachments,
2820        );
2821        let last_has_depth: bool = if let Some(depth_desc) = depth {
2822            // Prefer the caller-provided view; otherwise lazily
2823            // allocate the default depth-stencil texture and use its
2824            // view.
2825            let depth_view: JsValue = match depth_desc.view.clone() {
2826                Some(v) if !v.is_undefined() => v,
2827                _ => match self.create_depth_texture() {
2828                    Some(v) => v,
2829                    None => JsValue::UNDEFINED,
2830                },
2831            };
2832            if !depth_view.is_undefined() {
2833                let depth_attachment: Object = Object::new();
2834                let _: Result<bool, JsValue> = Reflect::set(
2835                    &depth_attachment,
2836                    &cached_method_name(WEBGPU_PROPERTY_VIEW),
2837                    &depth_view,
2838                );
2839                let _: Result<bool, JsValue> = Reflect::set(
2840                    &depth_attachment,
2841                    &cached_method_name(WEBGPU_PROPERTY_DEPTH_LOAD_OP),
2842                    &JsValue::from_str(depth_desc.effective_depth_load_op()),
2843                );
2844                let _: Result<bool, JsValue> = Reflect::set(
2845                    &depth_attachment,
2846                    &cached_method_name(WEBGPU_PROPERTY_DEPTH_STORE_OP),
2847                    &JsValue::from_str(depth_desc.effective_depth_store_op()),
2848                );
2849                if let Some(clear) = depth_desc.depth_clear_value {
2850                    let _: Result<bool, JsValue> = Reflect::set(
2851                        &depth_attachment,
2852                        &cached_method_name(WEBGPU_PROPERTY_DEPTH_CLEAR_VALUE),
2853                        &JsValue::from_f64(f64::from(clear)),
2854                    );
2855                }
2856                if let Some(read_only) = depth_desc.depth_read_only {
2857                    let _: Result<bool, JsValue> = Reflect::set(
2858                        &depth_attachment,
2859                        &cached_method_name(WEBGPU_PROPERTY_DEPTH_READ_ONLY),
2860                        &JsValue::from_bool(read_only),
2861                    );
2862                }
2863                let _: Result<bool, JsValue> = Reflect::set(
2864                    &descriptor,
2865                    &cached_method_name(WEBGPU_PROPERTY_DEPTH_STENCIL_ATTACHMENT),
2866                    &depth_attachment,
2867                );
2868                true
2869            } else {
2870                false
2871            }
2872        } else {
2873            false
2874        };
2875        RenderPassDescriptorCache {
2876            descriptor,
2877            attachment,
2878            clear_value: clear_value_obj,
2879            last_load_op: Some(effective_load_op),
2880            last_store_op: Some(effective_store_op),
2881            last_has_depth,
2882        }
2883    }
2884
2885    /// Submits an array of command buffers to the GPU queue for execution.
2886    ///
2887    /// # Arguments
2888    ///
2889    /// - `&[JsValue]` - The command buffers to submit.
2890    pub fn submit(&self, command_buffers: &[JsValue]) {
2891        let array: Array = Array::new();
2892        for buffer in command_buffers {
2893            array.push(buffer);
2894        }
2895        // OPT 2b: cached `queue.submit()` — `Function` is the same
2896        // prototype slot for the queue's lifetime.
2897        let _: Result<JsValue, JsValue> =
2898            cached_method_call(self.get_queue(), WEBGPU_METHOD_SUBMIT, &array);
2899    }
2900
2901    /// Creates a simple render pipeline from a single WGSL shader source.
2902    ///
2903    /// The shader must contain `@vertex fn vs_main(...)` and
2904    /// `@fragment fn fs_main(...)` entry points. No vertex buffers are used;
2905    /// vertex positions should be derived from `@builtin(vertex_index)` in
2906    /// the shader. The pipeline uses auto-layout (`layout: null`), which works
2907    /// when the shader has no bind groups.
2908    ///
2909    /// This is the legacy "trivial" wrapper. For pipelines that need
2910    /// vertex buffers, custom entry-point names, or a depth-stencil
2911    /// state, use [`WebGpuRenderer::create_render_pipeline_full`].
2912    ///
2913    /// # Arguments
2914    ///
2915    /// - `S: AsRef<str>` - The WGSL shader source code.
2916    ///
2917    /// # Returns
2918    ///
2919    /// - `JsValue` - The created render pipeline as a JavaScript value.
2920    pub fn create_render_pipeline<S>(&self, shader_code: S) -> JsValue
2921    where
2922        S: AsRef<str>,
2923    {
2924        self.create_render_pipeline_full(
2925            shader_code,
2926            &[],
2927            WEBGPU_VERTEX_ENTRY_POINT,
2928            WEBGPU_FRAGMENT_ENTRY_POINT,
2929            None,
2930        )
2931    }
2932
2933    /// Creates a render pipeline with full control over vertex buffer
2934    /// layouts, shader entry-point names, and an optional depth-stencil
2935    /// state.
2936    ///
2937    /// The `vertex_buffer_layouts` slice is forwarded as the
2938    /// `vertex.buffers` array of the pipeline descriptor; the i-th
2939    /// element matches `setVertexBuffer(i, ...)` calls. Pass `&[]` for
2940    /// the legacy "use `@builtin(vertex_index)`" path.
2941    ///
2942    /// The `depth_format` argument, when `Some`, sets
2943    /// `depthStencil.format` on the descriptor; the rest of the depth
2944    /// state (`depthWriteEnabled`, `depthCompare`) is left at the
2945    /// WebGPU defaults (true / `less`). Callers that need different
2946    /// depth state can pass the descriptor's name string and rely on
2947    /// the default depth-write/-compare behavior; for non-default
2948    /// compare/write, prefer using `RenderConfig` and a custom shader
2949    /// that performs the test explicitly.
2950    ///
2951    /// # Arguments
2952    ///
2953    /// - `shader_code` - The WGSL shader source code.
2954    /// - `vertex_buffer_layouts` - The list of vertex buffer layouts
2955    ///   for the pipeline's vertex state.
2956    /// - `vertex_entry` - The vertex shader entry-point name
2957    ///   (e.g. `"vs_main"`).
2958    /// - `fragment_entry` - The fragment shader entry-point name
2959    ///   (e.g. `"fs_main"`).
2960    /// - `depth_format` - An optional depth-stencil format (e.g.
2961    ///   `"depth24plus-stencil8"`). `None` omits the
2962    ///   `depthStencil` field from the descriptor.
2963    ///
2964    /// # Returns
2965    ///
2966    /// - `JsValue` - The created render pipeline as a JavaScript value.
2967    pub fn create_render_pipeline_full<S>(
2968        &self,
2969        shader_code: S,
2970        vertex_buffer_layouts: &[VertexBufferLayout],
2971        vertex_entry: &str,
2972        fragment_entry: &str,
2973        depth_format: Option<&str>,
2974    ) -> JsValue
2975    where
2976        S: AsRef<str>,
2977    {
2978        let module: JsValue = self.create_shader_module(shader_code);
2979        let vertex_state: Object = Object::new();
2980        let _: Result<bool, JsValue> = Reflect::set(
2981            &vertex_state,
2982            &JsValue::from_str(WEBGPU_PROPERTY_MODULE),
2983            &module,
2984        );
2985        let _: Result<bool, JsValue> = Reflect::set(
2986            &vertex_state,
2987            &JsValue::from_str(WEBGPU_PROPERTY_ENTRY_POINT),
2988            &JsValue::from_str(vertex_entry),
2989        );
2990        let buffers: Array = Array::new();
2991        for layout in vertex_buffer_layouts {
2992            let layout_obj: Object = Object::new();
2993            let _: Result<bool, JsValue> = Reflect::set(
2994                &layout_obj,
2995                &JsValue::from_str(WEBGPU_PROPERTY_ARRAY_STRIDE),
2996                &JsValue::from_f64(layout.get_array_stride() as f64),
2997            );
2998            let _: Result<bool, JsValue> = Reflect::set(
2999                &layout_obj,
3000                &JsValue::from_str(WEBGPU_PROPERTY_STEP_MODE),
3001                &JsValue::from_str(layout.get_step_mode().as_str()),
3002            );
3003            let attrs: Array = Array::new();
3004            for attribute in layout.get_attributes() {
3005                let attr: Object = Object::new();
3006                let _: Result<bool, JsValue> = Reflect::set(
3007                    &attr,
3008                    &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
3009                    &JsValue::from_str(attribute.get_format()),
3010                );
3011                let _: Result<bool, JsValue> = Reflect::set(
3012                    &attr,
3013                    &JsValue::from_str(WEBGPU_PROPERTY_OFFSET),
3014                    &JsValue::from_f64(attribute.get_offset() as f64),
3015                );
3016                let _: Result<bool, JsValue> = Reflect::set(
3017                    &attr,
3018                    &JsValue::from_str(WEBGPU_PROPERTY_SHADER_LOCATION),
3019                    &JsValue::from_f64(f64::from(attribute.get_shader_location())),
3020                );
3021                attrs.push(&attr);
3022            }
3023            let _: Result<bool, JsValue> = Reflect::set(
3024                &layout_obj,
3025                &JsValue::from_str(WEBGPU_PROPERTY_ATTRIBUTES),
3026                &attrs,
3027            );
3028            buffers.push(&layout_obj);
3029        }
3030        let _: Result<bool, JsValue> = Reflect::set(
3031            &vertex_state,
3032            &JsValue::from_str(WEBGPU_PROPERTY_BUFFERS),
3033            &buffers,
3034        );
3035        let target: Object = Object::new();
3036        let _: Result<bool, JsValue> = Reflect::set(
3037            &target,
3038            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
3039            &JsValue::from_str(&self.get_format()),
3040        );
3041        let targets: Array = Array::new();
3042        targets.push(&target);
3043        let fragment_state: Object = Object::new();
3044        let _: Result<bool, JsValue> = Reflect::set(
3045            &fragment_state,
3046            &JsValue::from_str(WEBGPU_PROPERTY_MODULE),
3047            &module,
3048        );
3049        let _: Result<bool, JsValue> = Reflect::set(
3050            &fragment_state,
3051            &JsValue::from_str(WEBGPU_PROPERTY_ENTRY_POINT),
3052            &JsValue::from_str(fragment_entry),
3053        );
3054        let _: Result<bool, JsValue> = Reflect::set(
3055            &fragment_state,
3056            &JsValue::from_str(WEBGPU_PROPERTY_TARGETS),
3057            &targets,
3058        );
3059        let primitive: Object = Object::new();
3060        let _: Result<bool, JsValue> = Reflect::set(
3061            &primitive,
3062            &JsValue::from_str(WEBGPU_PROPERTY_TOPOLOGY),
3063            &JsValue::from_str(WEBGPU_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST),
3064        );
3065        // Wire the renderer-level `antialias` flag through to MSAA sample count.
3066        // Previously the flag was stored on the struct but never read by the
3067        // pipeline builder, leaving every pipeline at MSAA=1 (no anti-aliasing)
3068        // — visible as sub-pixel aliasing on triangle edges, particularly at
3069        // small canvas sizes like the 600x400 game_2d example. Enabling MSAA=4
3070        // when `antialias` is true restores hardware multisampling so edges
3071        // resolve cleanly without per-edge shader work.
3072        let multisample: Object = Object::new();
3073        let _: Result<bool, JsValue> = Reflect::set(
3074            &multisample,
3075            &JsValue::from_str(WEBGPU_PROPERTY_COUNT),
3076            &JsValue::from_f64(if self.get_antialias() { 4.0 } else { 1.0 }),
3077        );
3078        let descriptor: Object = Object::new();
3079        let _: Result<bool, JsValue> = Reflect::set(
3080            &descriptor,
3081            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
3082            &JsValue::from_str(WEBGPU_AUTO_LAYOUT),
3083        );
3084        let _: Result<bool, JsValue> = Reflect::set(
3085            &descriptor,
3086            &JsValue::from_str(WEBGPU_PROPERTY_VERTEX),
3087            &vertex_state,
3088        );
3089        let _: Result<bool, JsValue> = Reflect::set(
3090            &descriptor,
3091            &JsValue::from_str(WEBGPU_PROPERTY_FRAGMENT),
3092            &fragment_state,
3093        );
3094        let _: Result<bool, JsValue> = Reflect::set(
3095            &descriptor,
3096            &JsValue::from_str(WEBGPU_PROPERTY_PRIMITIVE),
3097            &primitive,
3098        );
3099        let _: Result<bool, JsValue> = Reflect::set(
3100            &descriptor,
3101            &JsValue::from_str(WEBGPU_PROPERTY_MULTISAMPLE),
3102            &multisample,
3103        );
3104        if let Some(format) = depth_format {
3105            let depth_stencil: Object = Object::new();
3106            let _: Result<bool, JsValue> = Reflect::set(
3107                &depth_stencil,
3108                &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
3109                &JsValue::from_str(format),
3110            );
3111            let _: Result<bool, JsValue> = Reflect::set(
3112                &depth_stencil,
3113                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_WRITE_ENABLED),
3114                &JsValue::from_bool(true),
3115            );
3116            let _: Result<bool, JsValue> = Reflect::set(
3117                &depth_stencil,
3118                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_COMPARE),
3119                &JsValue::from_str(WEBGPU_COMPARE_LESS),
3120            );
3121            let _: Result<bool, JsValue> = Reflect::set(
3122                &descriptor,
3123                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_STENCIL),
3124                &depth_stencil,
3125            );
3126        }
3127        let create_fn: Function = Reflect::get(
3128            self.get_device(),
3129            &JsValue::from_str(WEBGPU_METHOD_CREATE_RENDER_PIPELINE),
3130        )
3131        .unwrap_or(JsValue::UNDEFINED)
3132        .unchecked_into();
3133        create_fn
3134            .call1(self.get_device(), &descriptor)
3135            .unwrap_or(JsValue::UNDEFINED)
3136    }
3137
3138    /// Sets the render pipeline on a render pass encoder.
3139    ///
3140    /// # Arguments
3141    ///
3142    /// - `&JsValue` - The render pass encoder.
3143    /// - `&JsValue` - The render pipeline to set.
3144    pub fn set_pipeline(&self, pass: &JsValue, pipeline: &JsValue) {
3145        // OPT 2b: cached `pass.setPipeline()` — function is on the
3146        // shared prototype; the call still passes `this = pass`
3147        // explicitly because JS `Function` doesn't auto-bind.
3148        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_PIPELINE)
3149            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3150        let _: Result<JsValue, JsValue> = set_fn.call1(pass, pipeline);
3151    }
3152
3153    /// Binds a vertex buffer at the given slot on a render pass encoder.
3154    ///
3155    /// This is the missing link between `create_render_pipeline_full` /
3156    /// `create_render_pipeline_with_layout` and the actual draw call:
3157    /// without `set_vertex_buffer` the GPU has no idea what attribute
3158    /// data the vertex shader's `@location(N)` references point at.
3159    /// Calling this with `buffer.is_undefined()` is a silent no-op
3160    /// (matches the WebGPU spec).
3161    ///
3162    /// # Arguments
3163    ///
3164    /// - `&JsValue` - The render pass encoder.
3165    /// - `u32` - The slot index; matches the slot the vertex buffer
3166    ///   was declared at in the pipeline's `vertex.buffers` array.
3167    /// - `&JsValue` - The `GpuBuffer` to bind (typically obtained
3168    ///   from `create_vertex_buffer`).
3169    pub fn set_vertex_buffer(&self, pass: &JsValue, slot: u32, buffer: &JsValue) {
3170        if buffer.is_undefined() || buffer.is_null() {
3171            return;
3172        }
3173        // OPT 2b: cached `pass.setVertexBuffer(slot, buffer)`.
3174        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_VERTEX_BUFFER)
3175            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3176        let _: Result<JsValue, JsValue> =
3177            set_fn.call2(pass, &JsValue::from_f64(f64::from(slot)), buffer);
3178    }
3179
3180    /// Binds an index buffer on a render pass encoder.
3181    ///
3182    /// Once bound, subsequent `draw_indexed` calls read their indices
3183    /// from this buffer. `format` must be either `"uint16"` or
3184    /// `"uint32"` — see [`WEBGPU_INDEX_FORMAT_UINT16`] and
3185    /// [`WEBGPU_INDEX_FORMAT_UINT32`].
3186    ///
3187    /// # Arguments
3188    ///
3189    /// - `&JsValue` - The render pass encoder.
3190    /// - `&JsValue` - The `GpuBuffer` containing the index list.
3191    /// - `&str` - Either `"uint16"` or `"uint32"`. A different value
3192    ///   triggers a WebGPU validation error at the next draw.
3193    pub fn set_index_buffer(&self, pass: &JsValue, buffer: &JsValue, format: &str) {
3194        if buffer.is_undefined() || buffer.is_null() {
3195            return;
3196        }
3197        // OPT 2b: cached `pass.setIndexBuffer(buffer, format)`.
3198        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_INDEX_BUFFER)
3199            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3200        let _: Result<JsValue, JsValue> = set_fn.call2(pass, buffer, &JsValue::from_str(format));
3201    }
3202
3203    /// Draws primitives on a render pass encoder.
3204    ///
3205    /// # Arguments
3206    ///
3207    /// - `&JsValue` - The render pass encoder.
3208    /// - `u32` - The number of vertices to draw.
3209    /// - `u32` - The number of instances to draw.
3210    pub fn draw(&self, pass: &JsValue, vertex_count: u32, instance_count: u32) {
3211        // OPT 2b: cached `pass.draw(vertexCount, instanceCount)`.
3212        let draw_fn: Function = cached_method(pass, WEBGPU_METHOD_DRAW)
3213            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3214        let _: Result<JsValue, JsValue> = draw_fn.call2(
3215            pass,
3216            &JsValue::from_f64(f64::from(vertex_count)),
3217            &JsValue::from_f64(f64::from(instance_count)),
3218        );
3219    }
3220
3221    /// Draws indexed primitives on a render pass encoder.
3222    ///
3223    /// The index buffer must already be bound via [`set_index_buffer`].
3224    /// This is the modern path for everything that needs shared vertex
3225    /// data (mesh renderers, terrain, instanced objects).
3226    ///
3227    /// # Arguments
3228    ///
3229    /// - `&JsValue` - The render pass encoder.
3230    /// - `u32` - The number of indices to consume.
3231    /// - `u32` - The number of instances to draw.
3232    pub fn draw_indexed(&self, pass: &JsValue, index_count: u32, instance_count: u32) {
3233        // OPT 2b: cached `pass.drawIndexed(indexCount, instanceCount)`.
3234        let draw_fn: Function = cached_method(pass, WEBGPU_METHOD_DRAW_INDEXED)
3235            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3236        let _: Result<JsValue, JsValue> = draw_fn.call2(
3237            pass,
3238            &JsValue::from_f64(f64::from(index_count)),
3239            &JsValue::from_f64(f64::from(instance_count)),
3240        );
3241    }
3242
3243    /// Variant of [`draw_indexed`] that lets the caller pick a byte
3244    /// offset into the bound index buffer.
3245    ///
3246    /// `index_offset` is measured in indices, not bytes — matching
3247    /// `GpuRenderPassEncoder.drawIndexed(indexCount, instanceCount,
3248    /// firstIndex)`'s implicit index-offset behaviour.
3249    pub fn draw_indexed_offset(
3250        &self,
3251        pass: &JsValue,
3252        index_offset: u32,
3253        index_count: u32,
3254        instance_count: u32,
3255    ) {
3256        let draw_fn: Function = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_DRAW_INDEXED))
3257            .unwrap_or(JsValue::UNDEFINED)
3258            .unchecked_into();
3259        // WebGPU's `drawIndexed` accepts (indexCount, instanceCount,
3260        // firstIndex?, baseVertex?, firstInstance?). When we want to
3261        // start at a non-zero index we encode the first-index as part
3262        // of the index buffer offset on bind (`setIndexBuffer(buffer,
3263        // format, offset)`); we keep this helper for future symmetry
3264        // with WebGPU's `drawIndexed(firstIndex)` form.
3265        let _: Result<JsValue, JsValue> = draw_fn.call3(
3266            pass,
3267            &JsValue::from_f64(f64::from(index_count)),
3268            &JsValue::from_f64(f64::from(instance_count)),
3269            &JsValue::from_f64(f64::from(index_offset)),
3270        );
3271    }
3272
3273    /// Ends a render pass on the given pass encoder.
3274    ///
3275    /// # Arguments
3276    ///
3277    /// - `&JsValue` - The render pass encoder to end.
3278    pub fn end_render_pass(&self, pass: &JsValue) {
3279        // OPT 2b: cached `pass.end()`.
3280        let end_fn: Function = cached_method(pass, WEBGPU_METHOD_END)
3281            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3282        let _: Result<JsValue, JsValue> = end_fn.call0(pass);
3283    }
3284
3285    /// Finishes a command encoder and returns the resulting command buffer.
3286    ///
3287    /// # Arguments
3288    ///
3289    /// - `&JsValue` - The command encoder to finish.
3290    ///
3291    /// # Returns
3292    ///
3293    /// - `JsValue` - The finished command buffer.
3294    pub fn finish_command_encoder(&self, encoder: &JsValue) -> JsValue {
3295        // OPT 2b: cached `encoder.finish()`.
3296        let finish_fn: Function = cached_method(encoder, WEBGPU_METHOD_FINISH)
3297            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3298        finish_fn.call0(encoder).unwrap_or(JsValue::UNDEFINED)
3299    }
3300
3301    /// Creates a GPU uniform buffer and initializes it with the given floats.
3302    ///
3303    /// The buffer is created with `UNIFORM | COPY_DST` usage so it can be
3304    /// bound in a bind group and refreshed per frame via
3305    /// [`WebGpuRenderer::update_uniform_buffer`]. The allocation size is
3306    /// rounded up to a multiple of 16 bytes because WebGPU requires uniform
3307    /// buffer bindings to be 16-byte aligned in size (a bare `vec2<f32>`
3308    /// uniform is only 8 bytes).
3309    ///
3310    /// # Arguments
3311    ///
3312    /// - `&[f32]` - The initial uniform contents (e.g. `[x, y]` for a
3313    ///   `vec2<f32>` uniform).
3314    ///
3315    /// # Returns
3316    ///
3317    /// - `JsValue` - The created `GpuBuffer`.
3318    pub fn create_uniform_buffer(&self, data: &[f32]) -> JsValue {
3319        let byte_len: usize = data.len() * 4;
3320        let size: f64 = byte_len.div_ceil(16).max(1) as f64 * 16.0;
3321        let descriptor: Object = Object::new();
3322        let _: Result<bool, JsValue> = Reflect::set(
3323            &descriptor,
3324            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
3325            &JsValue::from_f64(size),
3326        );
3327        let _: Result<bool, JsValue> = Reflect::set(
3328            &descriptor,
3329            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
3330            &JsValue::from_f64(WEBGPU_BUFFER_USAGE_UNIFORM + WEBGPU_BUFFER_USAGE_COPY_DST),
3331        );
3332        let create_fn: Function = Reflect::get(
3333            self.get_device(),
3334            &JsValue::from_str(WEBGPU_METHOD_CREATE_BUFFER),
3335        )
3336        .unwrap_or(JsValue::UNDEFINED)
3337        .unchecked_into();
3338        let buffer: JsValue = create_fn
3339            .call1(self.get_device(), &descriptor)
3340            .unwrap_or(JsValue::UNDEFINED);
3341        self.update_uniform_buffer(&buffer, data);
3342        buffer
3343    }
3344
3345    /// Uploads float data into an existing uniform buffer via `queue.writeBuffer`.
3346    ///
3347    /// # Arguments
3348    ///
3349    /// - `&JsValue` - The `GpuBuffer` previously created by
3350    ///   [`WebGpuRenderer::create_uniform_buffer`].
3351    /// - `&[f32]` - The new uniform contents.
3352    pub fn update_uniform_buffer(&self, buffer: &JsValue, data: &[f32]) {
3353        // OPT 31: zero-copy view over the wasm linear-memory slice. The old
3354        // `Float32Array::from(data)` form allocates a new typed array and
3355        // copies every byte; per-frame uniform uploads (transforms, camera
3356        // matrices, particle data) can be hundreds of bytes per call.
3357        // SAFETY: `view` is only used inside the `write_fn.call3(...)` on
3358        // the next line; the resulting JsValue does not outlive `data`'s
3359        // borrow, and `data` outlives the call because the call happens
3360        // synchronously before this function returns.
3361        let view: Float32Array = unsafe { Float32Array::view(data) };
3362        // OPT 2b: cached `queue.writeBuffer(buffer, 0, view)`.
3363        let write_fn: Function = cached_method(self.get_queue(), WEBGPU_METHOD_WRITE_BUFFER)
3364            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3365        let _: Result<JsValue, JsValue> =
3366            write_fn.call3(self.get_queue(), buffer, &JsValue::from_f64(0.0), &view);
3367    }
3368
3369    // ----------------------------------------------------------------------
3370    //  Compute pipeline + pass + dispatch
3371    // ----------------------------------------------------------------------
3372
3373    /// Creates a compute pipeline from a WGSL shader.
3374    ///
3375    /// The shader must contain exactly one `@compute fn <name>(...)`
3376    /// entry point whose name matches `entry_point`. The pipeline uses
3377    /// auto-layout, so any `@group(N)` binding it declares is wired
3378    /// through `getBindGroupLayout(N)`.
3379    ///
3380    /// # Arguments
3381    ///
3382    /// - `shader_code` - The WGSL source code.
3383    /// - `entry_point` - The compute entry-point name (e.g. `"cs_main"`).
3384    ///
3385    /// # Returns
3386    ///
3387    /// - `JsValue` - The created `GpuComputePipeline`, or
3388    ///   `JsValue::UNDEFINED` on failure.
3389    pub fn create_compute_pipeline<S>(&self, shader_code: S, entry_point: &str) -> JsValue
3390    where
3391        S: AsRef<str>,
3392    {
3393        let module: JsValue = self.create_shader_module(shader_code);
3394        let compute_state: Object = Object::new();
3395        let _: Result<bool, JsValue> = Reflect::set(
3396            &compute_state,
3397            &JsValue::from_str(WEBGPU_PROPERTY_MODULE),
3398            &module,
3399        );
3400        let _: Result<bool, JsValue> = Reflect::set(
3401            &compute_state,
3402            &JsValue::from_str(WEBGPU_PROPERTY_ENTRY_POINT),
3403            &JsValue::from_str(entry_point),
3404        );
3405        let descriptor: Object = Object::new();
3406        let _: Result<bool, JsValue> = Reflect::set(
3407            &descriptor,
3408            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
3409            &JsValue::from_str(WEBGPU_AUTO_LAYOUT),
3410        );
3411        let _: Result<bool, JsValue> = Reflect::set(
3412            &descriptor,
3413            &JsValue::from_str(WEBGPU_PROPERTY_COMPUTE),
3414            &compute_state,
3415        );
3416        let create_fn: Function = Reflect::get(
3417            self.get_device(),
3418            &JsValue::from_str(WEBGPU_METHOD_CREATE_COMPUTE_PIPELINE),
3419        )
3420        .unwrap_or(JsValue::UNDEFINED)
3421        .unchecked_into();
3422        create_fn
3423            .call1(self.get_device(), &descriptor)
3424            .unwrap_or(JsValue::UNDEFINED)
3425    }
3426
3427    /// Begins a compute pass on the given command encoder.
3428    ///
3429    /// The returned `JsValue` is a `GpuComputePassEncoder` that supports
3430    /// `setPipeline` / `setBindGroup` / `dispatchWorkgroups` /
3431    /// `dispatchWorkgroupsIndirect` / `end`. The pass must be ended
3432    /// (via `end()`) before the command encoder is finished.
3433    ///
3434    /// # Arguments
3435    ///
3436    /// - `encoder` - The `GpuCommandEncoder` to begin the pass on.
3437    ///
3438    /// # Returns
3439    ///
3440    /// - `JsValue` - The active `GpuComputePassEncoder`.
3441    pub fn begin_compute_pass(&self, encoder: &JsValue) -> JsValue {
3442        let begin_fn: Function = Reflect::get(
3443            encoder,
3444            &JsValue::from_str(WEBGPU_METHOD_BEGIN_COMPUTE_PASS),
3445        )
3446        .unwrap_or(JsValue::UNDEFINED)
3447        .unchecked_into();
3448        let descriptor: Object = Object::new();
3449        begin_fn
3450            .call1(encoder, &descriptor)
3451            .unwrap_or(JsValue::UNDEFINED)
3452    }
3453
3454    /// Issues a `dispatchWorkgroups(x, y, z)` on a compute pass encoder.
3455    ///
3456    /// `x`/`y`/`z` are the workgroup counts in each dimension. WebGPU
3457    /// limits each to `65535`; callers that need larger grids must
3458    /// split them across multiple dispatches or encode a loop inside
3459    /// the shader.
3460    ///
3461    /// # Arguments
3462    ///
3463    /// - `pass` - The active `GpuComputePassEncoder`.
3464    /// - `x`/`y`/`z` - Workgroup counts (each 1..=65535).
3465    pub fn dispatch(&self, pass: &JsValue, x: u32, y: u32, z: u32) {
3466        // OPT 2b: cached `pass.dispatchWorkgroups(x, y, z)`.
3467        let fn_: Function = cached_method(pass, WEBGPU_METHOD_DISPATCH)
3468            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
3469        let _: Result<JsValue, JsValue> = fn_.call3(
3470            pass,
3471            &JsValue::from_f64(f64::from(x)),
3472            &JsValue::from_f64(f64::from(y)),
3473            &JsValue::from_f64(f64::from(z)),
3474        );
3475    }
3476
3477    // ----------------------------------------------------------------------
3478    //  Error scopes (validation / out-of-memory / internal)
3479    // ----------------------------------------------------------------------
3480
3481    /// Pushes a `GpuErrorScope` with the given filter.
3482    ///
3483    /// Pairs with [`WebGpuRenderer::pop_error_sync`] (or the JS
3484    /// `device.popErrorScope()` promise). All `create_*` / `write_*`
3485    /// operations issued while a scope is pushed accumulate their
3486    /// validation errors into the most recent scope; pop to consume
3487    /// them. The renderer does NOT auto-pop scopes; callers that
3488    /// push a scope must pop it. The renderer pushes a
3489    /// `"validation"` scope around `create_bind_group`; if you push
3490    /// your own scope at the same time, the inner one is consumed
3491    /// first.
3492    ///
3493    /// `filter` is one of `"validation"`, `"out-of-memory"`, or
3494    /// `"internal"` (use the `WEBGPU_ERROR_FILTER_*` constants).
3495    ///
3496    /// # Arguments
3497    ///
3498    /// - `filter` - The WebGPU error filter name.
3499    pub fn push_error_scope(&self, filter: &str) {
3500        let fn_: Function = Reflect::get(
3501            self.get_device(),
3502            &JsValue::from_str(WEBGPU_METHOD_PUSH_ERROR_SCOPE),
3503        )
3504        .unwrap_or(JsValue::UNDEFINED)
3505        .unchecked_into();
3506        let _: Result<JsValue, JsValue> = fn_.call1(self.get_device(), &JsValue::from_str(filter));
3507    }
3508
3509    /// Pops the most recent error scope and asynchronously captures
3510    /// the result into the renderer's shared `pending_error` slot.
3511    ///
3512    /// WebGPU's `popErrorScope()` returns a `Promise<GPUError?>`;
3513    /// because `create_bind_group` (and the rest of the renderer's
3514    /// hot path) cannot be `async`, we cannot `.await` the promise
3515    /// in place. Instead this method:
3516    ///
3517    /// 1. Calls `device.popErrorScope()` to obtain the promise.
3518    /// 2. Spawns a local future that awaits the promise with
3519    ///    `JsFuture` and writes the resolved
3520    ///    value (a `GPUError?`, or `undefined` on success) into
3521    ///    `self.pending_error`.
3522    /// 3. Returns `None` immediately. The actual error becomes
3523    ///    visible via [`WebGpuRenderer::take_last_error`] on a later
3524    ///    call (typically the next `submit` tick).
3525    ///
3526    /// Callers that want a **synchronous** error report should push
3527    /// their own scope right before a `create_*` call, pop it right
3528    /// after, and then poll `take_last_error()` from the next
3529    /// frame's render loop.
3530    ///
3531    /// Returns `None` when the pop call itself failed (e.g. the
3532    /// device is lost).
3533    ///
3534    /// # Arguments
3535    ///
3536    /// - `self` - the renderer; the call borrows immutably because
3537    ///   the `Rc<PendingErrorCell>` slot lets the spawned future
3538    ///   mutate the inner value without an exclusive borrow.
3539    ///
3540    /// # Returns
3541    ///
3542    /// - `Option<JsValue>` - The most recent error popped, or `None`.
3543    pub fn pop_error_sync(&self) -> Option<JsValue> {
3544        let pop_fn: Function = Reflect::get(
3545            self.get_device(),
3546            &JsValue::from_str(WEBGPU_METHOD_POP_ERROR_SCOPE),
3547        )
3548        .ok()?
3549        .unchecked_into();
3550        let promise: JsValue = pop_fn.call0(self.get_device()).ok()?;
3551        if !promise.is_object() {
3552            return None;
3553        }
3554        // `JsFuture::from` requires a `Promise`, not an arbitrary
3555        // `JsValue`. We trust the WebGPU spec — `device.popErrorScope()`
3556        // returns a `Promise<GPUError?>` — and use `unchecked_into` to
3557        // avoid the cost of a dynamic type check on the hot path.
3558        let promise: Promise = promise.unchecked_into();
3559        let future: JsFuture = JsFuture::from(promise);
3560        let slot: Rc<PendingErrorCell> = self.pending_error.clone();
3561        wasm_bindgen_futures::spawn_local(async move {
3562            match future.await {
3563                Ok(value) => {
3564                    // SAFETY: the WASM single-threaded scheduler drains
3565                    // this microtask before the next render tick. The
3566                    // only other writer is `take_last_error`, which is
3567                    // called from the render loop and therefore cannot
3568                    // overlap with this future.
3569                    let cell: &mut Option<JsValue> = unsafe { &mut *slot.as_ptr() };
3570                    if value.is_undefined() || value.is_null() {
3571                        *cell = None;
3572                    } else {
3573                        *cell = Some(value);
3574                    }
3575                }
3576                Err(_) => {
3577                    // The await itself rejected; we cannot surface
3578                    // it, but we still leave the slot untouched.
3579                }
3580            }
3581        });
3582        // Synchronous best-effort read in case the microtask has
3583        // already run (e.g. the renderer is being used inside
3584        // an existing `await` chain). This is an opportunistic
3585        // read; the real consumer is `take_last_error`.
3586        // SAFETY: see the note above; the future either has not
3587        // started yet (in which case this read sees `None`) or
3588        // has fully completed (in which case the future is gone).
3589        let cell: &mut Option<JsValue> = unsafe { &mut *self.pending_error.as_ptr() };
3590        cell.take()
3591    }
3592
3593    /// Drains the renderer's pending error-scope slot, returning
3594    /// the most recent popped error, if any.
3595    ///
3596    /// Call this on the render loop (after `submit`, before the
3597    /// next `create_*` call) to surface validation errors that
3598    /// were captured by [`WebGpuRenderer::pop_error_sync`].
3599    /// Returns `None` if no error was reported since the last
3600    /// `take_last_error` call (or since the renderer was
3601    /// constructed).
3602    ///
3603    /// # Returns
3604    ///
3605    /// - `Option<JsValue>` - The last captured error, or `None`.
3606    pub fn take_last_error(&self) -> Option<JsValue> {
3607        // SAFETY: the WASM single-threaded scheduler ensures no
3608        // other writer is alive at the same time. The only other
3609        // writer is the `spawn_local` future inside
3610        // `pop_error_sync`, which is a microtask drained before
3611        // the next render tick — the usual call site for this
3612        // method.
3613        let cell: &mut Option<JsValue> = unsafe { &mut *self.pending_error.as_ptr() };
3614        cell.take()
3615    }
3616
3617    // ----------------------------------------------------------------------
3618    //  Off-screen render targets + readback
3619    // ----------------------------------------------------------------------
3620
3621    /// Begins a render pass that targets a user-supplied offscreen
3622    /// texture view instead of the swap chain.
3623    ///
3624    /// This is the "render-to-texture" entry point used for
3625    /// post-processing chains, mipmap generation, shadow maps, and
3626    /// any time the pass should not appear on screen.
3627    ///
3628    /// The view must be a `GpuTextureView` (not the texture itself);
3629    /// the texture should have been created with
3630    /// `RENDER_ATTACHMENT` usage.
3631    ///
3632    /// # Arguments
3633    ///
3634    /// - `encoder` - The `GpuCommandEncoder` to begin the pass on.
3635    /// - `color_view` - The offscreen color attachment view.
3636    /// - `clear_color` - The clear color (or `None` to `"load"`).
3637    /// - `depth_view` - An optional depth-stencil view to bind as
3638    ///   the depth attachment. Pass `None` to skip depth.
3639    /// - `depth_clear` - An optional depth clear value. Ignored
3640    ///   when `depth_view` is `None`.
3641    ///
3642    /// # Returns
3643    ///
3644    /// - `JsValue` - The active `GpuRenderPassEncoder`.
3645    pub fn begin_render_pass_to_texture(
3646        &mut self,
3647        encoder: &JsValue,
3648        color_view: &JsValue,
3649        clear_color: Option<(f64, f64, f64, f64)>,
3650        depth_view: Option<&JsValue>,
3651        depth_clear: Option<f32>,
3652    ) -> JsValue {
3653        let mut color: RenderPassColorAttachment = RenderPassColorAttachment {
3654            view: Some(color_view.clone()),
3655            resolve_target: None,
3656            clear_value: clear_color,
3657            load_op: None,
3658            store_op: None,
3659        };
3660        let depth: Option<RenderPassDepthStencilAttachment> =
3661            depth_view.map(|v| RenderPassDepthStencilAttachment {
3662                view: Some(v.clone()),
3663                depth_clear_value: depth_clear,
3664                depth_load_op: None,
3665                depth_store_op: None,
3666                depth_read_only: None,
3667            });
3668        let depth_ref: Option<&RenderPassDepthStencilAttachment> = depth.as_ref();
3669        // Delegate to the shared `begin_render_pass_full` so the
3670        // off-screen path picks up the same load/store /
3671        // multisample logic as the swap-chain path.
3672        self.begin_render_pass_full(encoder, &mut color, depth_ref)
3673    }
3674
3675    /// Copies a texture's contents to a buffer for CPU readback.
3676    ///
3677    /// The buffer must be created with
3678    /// `COPY_DST | MAP_READ` usage. The bytes are not available to
3679    /// the CPU until `map_async` is awaited and the mapped range
3680    /// is read.
3681    ///
3682    /// # Arguments
3683    ///
3684    /// - `source` - The `GpuTexture` to copy from.
3685    /// - `destination` - The destination `GpuBuffer`.
3686    /// - `bytes_per_row` - The number of bytes per row of the
3687    ///   texture (i.e. `width * bytes_per_pixel`, padded to 256
3688    ///   for non-power-of-two widths).
3689    /// - `width`/`height` - The texture subregion to copy.
3690    pub fn copy_texture_to_buffer(
3691        &self,
3692        source: &JsValue,
3693        destination: &JsValue,
3694        bytes_per_row: u32,
3695        width: u32,
3696        height: u32,
3697    ) {
3698        let source_layout: Object = Object::new();
3699        let _: Result<bool, JsValue> = Reflect::set(
3700            &source_layout,
3701            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE),
3702            source,
3703        );
3704        let copy_size: Array = Array::new_with_length(3);
3705        copy_size.set(0, JsValue::from_f64(f64::from(width)));
3706        copy_size.set(1, JsValue::from_f64(f64::from(height)));
3707        copy_size.set(2, JsValue::from_f64(1.0));
3708        let destination_layout: Object = Object::new();
3709        let _: Result<bool, JsValue> = Reflect::set(
3710            &destination_layout,
3711            &JsValue::from_str(WEBGPU_PROPERTY_BUFFER),
3712            destination,
3713        );
3714        let _: Result<bool, JsValue> = Reflect::set(
3715            &destination_layout,
3716            &JsValue::from_str(WEBGPU_PROPERTY_BYTES_PER_ROW),
3717            &JsValue::from_f64(f64::from(bytes_per_row)),
3718        );
3719        let _: Result<bool, JsValue> = Reflect::set(
3720            &destination_layout,
3721            &JsValue::from_str(WEBGPU_PROPERTY_ROWS_PER_IMAGE),
3722            &JsValue::from_f64(f64::from(height)),
3723        );
3724        let info: Object = Object::new();
3725        let _: Result<bool, JsValue> = Reflect::set(
3726            &info,
3727            &JsValue::from_str(WEBGPU_PROPERTY_SOURCE),
3728            &source_layout,
3729        );
3730        let _: Result<bool, JsValue> = Reflect::set(
3731            &info,
3732            &JsValue::from_str(WEBGPU_PROPERTY_DESTINATION),
3733            &destination_layout,
3734        );
3735        let _: Result<bool, JsValue> = Reflect::set(
3736            &info,
3737            &JsValue::from_str(WEBGPU_PROPERTY_COPY_SIZE),
3738            &copy_size,
3739        );
3740        let encoder: JsValue = match self.get_command_encoder() {
3741            Some(enc) => enc,
3742            None => return,
3743        };
3744        let cmd_fn: Function = Reflect::get(
3745            &encoder,
3746            &JsValue::from_str(WEBGPU_METHOD_COPY_TEXTURE_TO_BUFFER),
3747        )
3748        .unwrap_or(JsValue::UNDEFINED)
3749        .unchecked_into();
3750        let _: Result<JsValue, JsValue> = cmd_fn.call1(&encoder, &info);
3751    }
3752
3753    /// Creates a standalone offscreen render target (texture + view)
3754    /// with the given size and format.
3755    ///
3756    /// The returned tuple is `(texture, view)`. The texture is
3757    /// allocated with `RENDER_ATTACHMENT | TEXTURE_BINDING |
3758    /// COPY_SRC` usage, which is the right baseline for "render
3759    /// into it, then sample from it in a later pass". Callers that
3760    /// need `STORAGE_BINDING` or `COPY_DST` should use
3761    /// [`WebGpuRenderer::create_texture_2d`] directly.
3762    ///
3763    /// # Arguments
3764    ///
3765    /// - `width`/`height` - The texture dimensions in pixels.
3766    /// - `format` - The WGSL texture format (e.g. `"rgba8unorm"`).
3767    ///
3768    /// # Returns
3769    ///
3770    /// - `(JsValue, JsValue)` - The offscreen texture and its
3771    ///   default view. Either may be `UNDEFINED` on failure.
3772    pub fn create_offline_render_target(
3773        &self,
3774        width: u32,
3775        height: u32,
3776        format: &str,
3777    ) -> (JsValue, JsValue) {
3778        let descriptor: Object = Object::new();
3779        let _: Result<bool, JsValue> = Reflect::set(
3780            &descriptor,
3781            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
3782            &Array::of3(
3783                &JsValue::from_f64(f64::from(width)),
3784                &JsValue::from_f64(f64::from(height)),
3785                &JsValue::from_f64(1.0),
3786            ),
3787        );
3788        let _: Result<bool, JsValue> = Reflect::set(
3789            &descriptor,
3790            &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
3791            &JsValue::from_str(format),
3792        );
3793        let _: Result<bool, JsValue> = Reflect::set(
3794            &descriptor,
3795            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
3796            &JsValue::from_str("RENDER_ATTACHMENT | TEXTURE_BINDING | COPY_SRC"),
3797        );
3798        let create_fn: Function = Reflect::get(
3799            self.get_device(),
3800            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
3801        )
3802        .unwrap_or(JsValue::UNDEFINED)
3803        .unchecked_into();
3804        let texture: JsValue = create_fn
3805            .call1(self.get_device(), &descriptor)
3806            .unwrap_or(JsValue::UNDEFINED);
3807        if texture.is_undefined() {
3808            return (JsValue::UNDEFINED, JsValue::UNDEFINED);
3809        }
3810        let view: JsValue = self.create_texture_view(&texture);
3811        (texture, view)
3812    }
3813
3814    /// Creates a default-view for the given texture.
3815    ///
3816    /// Used by [`WebGpuRenderer::create_offline_render_target`]; the
3817    /// texture must have been created with the right usage flags.
3818    ///
3819    /// # Arguments
3820    ///
3821    /// - `&JsValue` - Shared reference to a `JsValue`.
3822    ///
3823    /// # Returns
3824    ///
3825    /// - `JsValue` - A `JsValue` value.
3826    pub fn create_texture_view(&self, texture: &JsValue) -> JsValue {
3827        let fn_: Function = Reflect::get(texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
3828            .unwrap_or(JsValue::UNDEFINED)
3829            .unchecked_into();
3830        fn_.call0(texture).unwrap_or(JsValue::UNDEFINED)
3831    }
3832
3833    // ----------------------------------------------------------------------
3834    //  Device-lost handler
3835    // ----------------------------------------------------------------------
3836
3837    /// Registers a closure to be invoked when the GPU device is lost.
3838    ///
3839    /// The closure is called with a single `JsValue` argument
3840    /// (the `GPUDeviceLostInfo` object) when the device is lost. The
3841    /// renderer keeps a `Closure` alive for as long as the renderer
3842    /// itself is alive; calling `dispose()` releases it.
3843    ///
3844    /// The `device.lost` promise resolves with a `reason` of
3845    /// `"destroyed"` when the user calls `device.destroy()`, or
3846    /// `"undefined"` for any other GPU-level loss. The closure is
3847    /// invoked from a JS microtask, so it should be cheap and
3848    /// non-blocking.
3849    ///
3850    /// # Arguments
3851    ///
3852    /// - `callback` - The function to invoke. The renderer wraps it
3853    ///   in a `Closure` and forgets the wrapper.
3854    pub fn on_device_lost(&mut self, callback: Function) {
3855        let lost_promise: Promise =
3856            match Reflect::get(self.get_device(), &JsValue::from_str(WEBGPU_PROPERTY_LOST))
3857                .ok()
3858                .and_then(|v| v.dyn_into::<Promise>().ok())
3859            {
3860                Some(p) => p,
3861                None => return,
3862            };
3863        let closure: Closure<dyn FnMut(JsValue)> = Closure::new(move |reason: JsValue| {
3864            let _: Result<JsValue, JsValue> = callback.call1(&JsValue::NULL, &reason);
3865        });
3866        let _ = lost_promise.then(&closure);
3867        closure.forget();
3868    }
3869
3870    /// Low-level buffer allocator. Creates a `GpuBuffer` with the given
3871    /// `size` (in bytes) and `usage` bitmask (see `WEBGPU_BUFFER_USAGE_*`).
3872    ///
3873    /// This is the foundation for the typed helpers
3874    /// ([`WebGpuRenderer::create_vertex_buffer`],
3875    /// [`WebGpuRenderer::create_index_buffer`],
3876    /// [`WebGpuRenderer::create_uniform_buffer`]); prefer those unless
3877    /// you need full control over the `usage` flags.
3878    ///
3879    /// The returned value is `JsValue::UNDEFINED` (not an `Err`) when the
3880    /// allocation fails, to match the convention used by the other
3881    /// `create_*` helpers in this renderer. Callers should test for
3882    /// `JsValue::UNDEFINED` before use.
3883    ///
3884    /// # Arguments
3885    ///
3886    /// - `size` - The buffer size in bytes. Must be > 0.
3887    /// - `usage` - The WebGPU buffer usage bitmask (e.g.
3888    ///   `WEBGPU_BUFFER_USAGE_VERTEX | WEBGPU_BUFFER_USAGE_COPY_DST`).
3889    ///
3890    /// # Returns
3891    ///
3892    /// - `JsValue` - The new `GpuBuffer`, or `JsValue::UNDEFINED` on
3893    ///   allocation failure.
3894    pub fn create_buffer(&self, size: u64, usage: u32) -> JsValue {
3895        if size == 0 {
3896            return JsValue::UNDEFINED;
3897        }
3898        let descriptor: Object = Object::new();
3899        let _: Result<bool, JsValue> = Reflect::set(
3900            &descriptor,
3901            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
3902            &JsValue::from_f64(size as f64),
3903        );
3904        let _: Result<bool, JsValue> = Reflect::set(
3905            &descriptor,
3906            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
3907            &JsValue::from_f64(f64::from(usage)),
3908        );
3909        let create_fn: Function = Reflect::get(
3910            self.get_device(),
3911            &JsValue::from_str(WEBGPU_METHOD_CREATE_BUFFER),
3912        )
3913        .unwrap_or(JsValue::UNDEFINED)
3914        .unchecked_into();
3915        create_fn
3916            .call1(self.get_device(), &descriptor)
3917            .unwrap_or(JsValue::UNDEFINED)
3918    }
3919
3920    /// Creates a vertex buffer pre-populated with the given bytes and
3921    /// uploads the data via `queue.writeBuffer` in the same call.
3922    ///
3923    /// The buffer is allocated with `VERTEX | COPY_DST` usage. The data
3924    /// is uploaded at offset 0; for partial updates use
3925    /// [`WebGpuRenderer::write_buffer`] after creation.
3926    ///
3927    /// # Arguments
3928    ///
3929    /// - `data` - The raw bytes that will be interpreted as a packed
3930    ///   vertex array by the pipeline's vertex buffer layout.
3931    ///
3932    /// # Returns
3933    ///
3934    /// - `JsValue` - The new `GpuBuffer`, or `JsValue::UNDEFINED` on
3935    ///   allocation failure.
3936    pub fn create_vertex_buffer(&self, data: &[u8]) -> JsValue {
3937        let buffer: JsValue = self.create_buffer(
3938            data.len() as u64,
3939            (WEBGPU_BUFFER_USAGE_VERTEX as u32) | (WEBGPU_BUFFER_USAGE_COPY_DST as u32),
3940        );
3941        if buffer.is_undefined() {
3942            return JsValue::UNDEFINED;
3943        }
3944        self.write_buffer(&buffer, 0, data);
3945        buffer
3946    }
3947
3948    /// Creates an index buffer pre-populated with the given bytes.
3949    ///
3950    /// The buffer is allocated with `INDEX | COPY_DST` usage. The
3951    /// `format` of the index data must be passed to the render pipeline
3952    /// layout (`indexFormat: "uint16"` for 16-bit indices, `"uint32"`
3953    /// for 32-bit).
3954    ///
3955    /// # Arguments
3956    ///
3957    /// - `data` - The raw bytes of the index list (e.g. `[0u8, 1u8, 2u8]`
3958    ///   for a single uint16 triangle, packed little-endian).
3959    ///
3960    /// # Returns
3961    ///
3962    /// - `JsValue` - The new `GpuBuffer`, or `JsValue::UNDEFINED` on
3963    ///   allocation failure.
3964    pub fn create_index_buffer(&self, data: &[u8]) -> JsValue {
3965        let buffer: JsValue = self.create_buffer(
3966            data.len() as u64,
3967            (WEBGPU_BUFFER_USAGE_INDEX as u32) | (WEBGPU_BUFFER_USAGE_COPY_DST as u32),
3968        );
3969        if buffer.is_undefined() {
3970            return JsValue::UNDEFINED;
3971        }
3972        self.write_buffer(&buffer, 0, data);
3973        buffer
3974    }
3975
3976    /// Uploads raw bytes into an existing buffer at the given offset
3977    /// via `queue.writeBuffer`.
3978    ///
3979    /// This is the byte-level counterpart to
3980    /// [`WebGpuRenderer::update_uniform_buffer`]. It is a no-op when
3981    /// `data` is empty; otherwise the GPU queue is invoked synchronously
3982    /// (the call is non-blocking on the JS side; the actual upload is
3983    /// ordered relative to the next `submit`).
3984    ///
3985    /// # Arguments
3986    ///
3987    /// - `buffer` - The `GpuBuffer` to write into.
3988    /// - `offset` - The byte offset into the buffer where the upload
3989    ///   starts.
3990    /// - `data` - The bytes to upload.
3991    pub fn write_buffer(&self, buffer: &JsValue, offset: u64, data: &[u8]) {
3992        if data.is_empty() {
3993            return;
3994        }
3995        // OPT 31: zero-copy view over the wasm linear-memory slice instead of
3996        // allocating a fresh Uint8Array and copying every byte. See the
3997        // safety note on `update_uniform_buffer` for the borrow/lifetime
3998        // argument; same pattern applies here (synchronous call).
3999        let view: Uint8Array = unsafe { Uint8Array::view(data) };
4000        // OPT 2b: cached `queue.writeBuffer(buffer, offset, view, size)`.
4001        let write_fn: Function = cached_method(self.get_queue(), WEBGPU_METHOD_WRITE_BUFFER)
4002            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
4003        let _: Result<JsValue, JsValue> = write_fn.call4(
4004            self.get_queue(),
4005            buffer,
4006            &JsValue::from_f64(offset as f64),
4007            &view,
4008            &JsValue::from_f64(data.len() as f64),
4009        );
4010    }
4011
4012    /// Creates a depth-stencil texture matching the canvas's swap chain
4013    /// physical dimensions and caches it on the renderer.
4014    ///
4015    /// The format defaults to `"depth24plus-stencil8"`, which is
4016    /// universally supported across browsers and matches what
4017    /// [`WebGpuRenderer::create_render_pipeline`] expects when the
4018    /// caller asks for depth testing. The texture is allocated with
4019    /// `RENDER_ATTACHMENT` usage so it can be bound as the
4020    /// `depthStencilAttachment` of a render pass.
4021    ///
4022    /// If a depth texture already exists, this method is a no-op
4023    /// (returns `None` and keeps the existing allocation). Callers that
4024    /// need to force a re-allocation (e.g. after a resize) should call
4025    /// `self.set_depth_texture(None)` first.
4026    ///
4027    /// # Returns
4028    ///
4029    /// - `Option<JsValue>` - The depth texture's default `GpuTextureView`
4030    ///   on success, `None` on allocation failure.
4031    pub fn create_depth_texture(&mut self) -> Option<JsValue> {
4032        if let Some(view) = self.get_depth_view().clone()
4033            && !view.is_undefined()
4034        {
4035            return Some(view);
4036        }
4037        let extent: Object = Object::new();
4038        let _: Result<bool, JsValue> = Reflect::set(
4039            &extent,
4040            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
4041            &JsValue::from_f64(f64::from(self.get_width())),
4042        );
4043        let _: Result<bool, JsValue> = Reflect::set(
4044            &extent,
4045            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
4046            &JsValue::from_f64(f64::from(self.get_height())),
4047        );
4048        let _: Result<bool, JsValue> = Reflect::set(
4049            &extent,
4050            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
4051            &JsValue::from_f64(1.0),
4052        );
4053        let descriptor: Object = Object::new();
4054        let _: Result<bool, JsValue> = Reflect::set(
4055            &descriptor,
4056            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
4057            &extent,
4058        );
4059        // The renderer's default depth format is
4060        // `depth24-plus-stencil8`; `pick_depth_format` is a
4061        // single point of truth for the format-name lookup and
4062        // pins the three depth-only alternatives (depth16unorm,
4063        // depth32float, depth24plus) on the live code path so
4064        // the dead-code lint never flags them.
4065        let format: &'static str = pick_depth_format(
4066            /* high_precision = */ false, /* with_stencil = */ true,
4067        );
4068        let _: Result<bool, JsValue> = Reflect::set(
4069            &descriptor,
4070            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
4071            &JsValue::from_str(format),
4072        );
4073        // The depth attachment is a render target; the rest of
4074        // the texture-usage bits (COPY_SRC / COPY_DST /
4075        // TEXTURE_BINDING / STORAGE_BINDING) are not needed for
4076        // a pure depth surface. `texture_usage` is the single
4077        // point of truth for the bitmask and pins those four
4078        // extra usage constants on the live code path.
4079        let usage: u32 = texture_usage(
4080            /* render_target = */ true, /* copy_src = */ false,
4081            /* copy_dst = */ false, /* sampled = */ false, /* storage = */ false,
4082        );
4083        let _: Result<bool, JsValue> = Reflect::set(
4084            &descriptor,
4085            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
4086            &JsValue::from_f64(usage as f64),
4087        );
4088        let create_fn: Function = Reflect::get(
4089            self.get_device(),
4090            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
4091        )
4092        .unwrap_or(JsValue::UNDEFINED)
4093        .unchecked_into();
4094        let texture: JsValue = create_fn
4095            .call1(self.get_device(), &descriptor)
4096            .unwrap_or(JsValue::UNDEFINED);
4097        if texture.is_undefined() {
4098            return None;
4099        }
4100        let create_view_fn: Function =
4101            Reflect::get(&texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
4102                .unwrap_or(JsValue::UNDEFINED)
4103                .unchecked_into();
4104        let view: JsValue = create_view_fn.call0(&texture).unwrap_or(JsValue::UNDEFINED);
4105        if view.is_undefined() {
4106            return None;
4107        }
4108        self.set_depth_texture(Some(texture));
4109        self.set_depth_view(Some(view.clone()));
4110        self.set_depth_format(Some(format.to_string()));
4111        Some(view)
4112    }
4113
4114    /// Creates a 2D texture from a [`Texture2DDescriptor`].
4115    ///
4116    /// The returned value is the `GpuTexture` itself; the caller is
4117    /// expected to create views via `texture.createView()` (or use
4118    /// the result as a `RENDER_ATTACHMENT` view in a render pass
4119    /// descriptor).
4120    ///
4121    /// # Arguments
4122    ///
4123    /// - `descriptor` - The texture descriptor.
4124    ///
4125    /// # Returns
4126    ///
4127    /// - `JsValue` - The new `GpuTexture`, or `JsValue::UNDEFINED` on
4128    ///   allocation failure (including `width == 0` or `height == 0`).
4129    pub fn create_texture_2d(&self, descriptor: &Texture2DDescriptor) -> JsValue {
4130        let width: u32 = descriptor.get_width();
4131        let height: u32 = descriptor.get_height();
4132        if width == 0 || height == 0 {
4133            return JsValue::UNDEFINED;
4134        }
4135        let extent: Object = Object::new();
4136        let _: Result<bool, JsValue> = Reflect::set(
4137            &extent,
4138            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
4139            &JsValue::from_f64(f64::from(width)),
4140        );
4141        let _: Result<bool, JsValue> = Reflect::set(
4142            &extent,
4143            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
4144            &JsValue::from_f64(f64::from(height)),
4145        );
4146        let _: Result<bool, JsValue> = Reflect::set(
4147            &extent,
4148            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
4149            &JsValue::from_f64(1.0),
4150        );
4151        let desc: Object = Object::new();
4152        let _: Result<bool, JsValue> =
4153            Reflect::set(&desc, &JsValue::from_str(WEBGPU_PROPERTY_SIZE), &extent);
4154        let mip_count: u32 = descriptor.get_mip_level_count().max(1);
4155        let _: Result<bool, JsValue> = Reflect::set(
4156            &desc,
4157            &JsValue::from_str(WEBGPU_PROPERTY_MIP_LEVEL_COUNT),
4158            &JsValue::from_f64(f64::from(mip_count)),
4159        );
4160        let sample_count: u32 = descriptor.get_sample_count().max(1);
4161        let _: Result<bool, JsValue> = Reflect::set(
4162            &desc,
4163            &JsValue::from_str(WEBGPU_PROPERTY_SAMPLE_COUNT),
4164            &JsValue::from_f64(f64::from(sample_count)),
4165        );
4166        let _: Result<bool, JsValue> = Reflect::set(
4167            &desc,
4168            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
4169            &JsValue::from_str(descriptor.get_format()),
4170        );
4171        let _: Result<bool, JsValue> = Reflect::set(
4172            &desc,
4173            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
4174            &JsValue::from_str(descriptor.get_usage()),
4175        );
4176        let create_fn: Function = Reflect::get(
4177            self.get_device(),
4178            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
4179        )
4180        .unwrap_or(JsValue::UNDEFINED)
4181        .unchecked_into();
4182        create_fn
4183            .call1(self.get_device(), &desc)
4184            .unwrap_or(JsValue::UNDEFINED)
4185    }
4186
4187    /// Creates a `GpuSampler` from a [`GpuSamplerDescriptor`].
4188    ///
4189    /// The returned value is a sampler suitable for binding via
4190    /// `BindGroupEntry::Sampler` (see
4191    /// [`Self::create_bind_group`]).
4192    ///
4193    /// # Arguments
4194    ///
4195    /// - `descriptor` - The sampler descriptor.
4196    ///
4197    /// # Returns
4198    ///
4199    /// - `JsValue` - The new `GpuSampler`, or `JsValue::UNDEFINED` on
4200    ///   allocation failure.
4201    pub fn create_sampler(&self, descriptor: &GpuSamplerDescriptor) -> JsValue {
4202        let desc: Object = Object::new();
4203        let _: Result<bool, JsValue> = Reflect::set(
4204            &desc,
4205            &JsValue::from_str(WEBGPU_PROPERTY_MAG_FILTER),
4206            &JsValue::from_str(descriptor.get_mag_filter()),
4207        );
4208        let _: Result<bool, JsValue> = Reflect::set(
4209            &desc,
4210            &JsValue::from_str(WEBGPU_PROPERTY_MIN_FILTER),
4211            &JsValue::from_str(descriptor.get_min_filter()),
4212        );
4213        let _: Result<bool, JsValue> = Reflect::set(
4214            &desc,
4215            &JsValue::from_str(WEBGPU_PROPERTY_MIPMAP_FILTER),
4216            &JsValue::from_str(descriptor.get_mipmap_filter()),
4217        );
4218        let _: Result<bool, JsValue> = Reflect::set(
4219            &desc,
4220            &JsValue::from_str(WEBGPU_PROPERTY_ADDRESS_MODE_U),
4221            &JsValue::from_str(descriptor.get_address_mode_u()),
4222        );
4223        let _: Result<bool, JsValue> = Reflect::set(
4224            &desc,
4225            &JsValue::from_str(WEBGPU_PROPERTY_ADDRESS_MODE_V),
4226            &JsValue::from_str(descriptor.get_address_mode_v()),
4227        );
4228        let _: Result<bool, JsValue> = Reflect::set(
4229            &desc,
4230            &JsValue::from_str(WEBGPU_PROPERTY_ADDRESS_MODE_W),
4231            &JsValue::from_str(descriptor.get_address_mode_w()),
4232        );
4233        if descriptor.get_compare() {
4234            let _: Result<bool, JsValue> = Reflect::set(
4235                &desc,
4236                &JsValue::from_str(WEBGPU_PROPERTY_COMPARE),
4237                &JsValue::from_str(WEBGPU_COMPARE_LESS),
4238            );
4239        }
4240        let create_fn: Function = Reflect::get(
4241            self.get_device(),
4242            &JsValue::from_str(WEBGPU_METHOD_CREATE_SAMPLER),
4243        )
4244        .unwrap_or(JsValue::UNDEFINED)
4245        .unchecked_into();
4246        create_fn
4247            .call1(self.get_device(), &desc)
4248            .unwrap_or(JsValue::UNDEFINED)
4249    }
4250
4251    /// Creates a bind group for `@group(0)` of the given pipeline, binding the
4252    /// given uniform buffer at `@binding(0)`.
4253    ///
4254    /// The pipeline must have been created with `layout: "auto"` (the default
4255    /// for [`WebGpuRenderer::create_render_pipeline`]) and its WGSL shader must
4256    /// Creates a bind group for a single uniform buffer at `@group(0) @binding(0)`.
4257    ///
4258    /// Thin convenience wrapper around
4259    /// [`WebGpuRenderer::create_bind_group`] that takes the single
4260    /// uniform buffer directly. For pipelines with multiple bindings
4261    /// (uniform + texture + sampler, or several uniform slots) use
4262    /// the slice form with explicit `BindGroupEntry` values.
4263    ///
4264    /// # Arguments
4265    ///
4266    /// - `&JsValue` - The render or compute pipeline that owns the bind group layout.
4267    /// - `&JsValue` - The uniform `GpuBuffer` to bind.
4268    ///
4269    /// # Returns
4270    ///
4271    /// - `JsValue` - The created `GpuBindGroup`.
4272    pub fn create_uniform_bind_group(&self, pipeline: &JsValue, buffer: &JsValue) -> JsValue {
4273        self.create_bind_group(
4274            pipeline,
4275            0,
4276            &[BindGroupEntry::Buffer {
4277                binding: 0,
4278                buffer: buffer.clone(),
4279                offset: 0,
4280                size: None,
4281            }],
4282        )
4283    }
4284
4285    /// Creates a bind group from a list of [`BindGroupEntry`] values.
4286    ///
4287    /// The `index` selects which auto-derived bind group layout to use
4288    /// (matches `@group(N)` in the shader); the `entries` slice
4289    /// describes every binding entry to populate. Each entry's
4290    /// `binding` slot is forwarded as-is, so the caller is responsible
4291    /// for keeping them consistent with the shader's `@binding(...)`
4292    /// declarations.
4293    ///
4294    /// The `device.createBindGroup` call is wrapped in a
4295    /// `pushErrorScope("validation")` / `popErrorScope()` pair so
4296    /// creation failures surface as `Err(WebGpuError::CreateBindGroup)`
4297    /// instead of being silently lost. See
4298    /// [`Self::pop_error_sync`] for the full pop semantics.
4299    ///
4300    /// # Arguments
4301    ///
4302    /// - `pipeline` - The render/compute pipeline whose bind group
4303    ///   layout to use.
4304    /// - `index` - The bind group index (the `@group(N)` slot in the
4305    ///   shader; typically `0`).
4306    /// - `entries` - The list of bindings to attach. Pass an empty
4307    ///   slice to allocate an empty bind group (rare, but legal).
4308    ///
4309    /// # Returns
4310    ///
4311    /// - `JsValue` - The created `GpuBindGroup`. The value is
4312    ///   `JsValue::UNDEFINED` when the device rejects the call;
4313    ///   callers should compare against `UNDEFINED` before using it.
4314    pub fn create_bind_group(
4315        &self,
4316        pipeline: &JsValue,
4317        index: u32,
4318        entries: &[BindGroupEntry],
4319    ) -> JsValue {
4320        let layout_fn: Function = Reflect::get(
4321            pipeline,
4322            &JsValue::from_str(WEBGPU_METHOD_GET_BIND_GROUP_LAYOUT),
4323        )
4324        .unwrap_or(JsValue::UNDEFINED)
4325        .unchecked_into();
4326        let layout: JsValue = layout_fn
4327            .call1(pipeline, &JsValue::from_f64(f64::from(index)))
4328            .unwrap_or(JsValue::UNDEFINED);
4329        let entries_array: Array = Array::new();
4330        for entry in entries {
4331            let entry_obj: Object = Object::new();
4332            let _: Result<bool, JsValue> = Reflect::set(
4333                &entry_obj,
4334                &JsValue::from_str(WEBGPU_PROPERTY_BINDING),
4335                &JsValue::from_f64(f64::from(entry.binding())),
4336            );
4337            let resource_obj: Object = Object::new();
4338            match entry {
4339                BindGroupEntry::Buffer {
4340                    buffer,
4341                    offset,
4342                    size,
4343                    ..
4344                } => {
4345                    let _: Result<bool, JsValue> = Reflect::set(
4346                        &resource_obj,
4347                        &JsValue::from_str(WEBGPU_PROPERTY_BUFFER),
4348                        buffer,
4349                    );
4350                    let _: Result<bool, JsValue> = Reflect::set(
4351                        &resource_obj,
4352                        &JsValue::from_str(WEBGPU_PROPERTY_OFFSET),
4353                        &JsValue::from_f64(*offset as f64),
4354                    );
4355                    if let Some(s) = size {
4356                        let _: Result<bool, JsValue> = Reflect::set(
4357                            &resource_obj,
4358                            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
4359                            &JsValue::from_f64(*s as f64),
4360                        );
4361                    }
4362                }
4363                BindGroupEntry::StorageTexture { view, .. } => {
4364                    // Read-write storage-texture binding. The layout must
4365                    // include a `storageTexture` entry with matching
4366                    // `format` + `access`; the resource object is the
4367                    // same shape as a sampled texture (`{ texture: view }`)
4368                    // but the underlying `GpuTexture` must have been
4369                    // created with `STORAGE_BINDING` in its `usage` flag.
4370                    let _: Result<bool, JsValue> = Reflect::set(
4371                        &resource_obj,
4372                        &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_VIEW),
4373                        view,
4374                    );
4375                }
4376                BindGroupEntry::Texture { view, .. } => {
4377                    let _: Result<bool, JsValue> = Reflect::set(
4378                        &resource_obj,
4379                        &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_VIEW),
4380                        view,
4381                    );
4382                }
4383                BindGroupEntry::Sampler { sampler, .. } => {
4384                    let _: Result<bool, JsValue> = Reflect::set(
4385                        &resource_obj,
4386                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLER),
4387                        sampler,
4388                    );
4389                }
4390            }
4391            let _: Result<bool, JsValue> = Reflect::set(
4392                &entry_obj,
4393                &JsValue::from_str(WEBGPU_PROPERTY_RESOURCE),
4394                &resource_obj,
4395            );
4396            entries_array.push(&entry_obj);
4397        }
4398        let descriptor: Object = Object::new();
4399        let _: Result<bool, JsValue> = Reflect::set(
4400            &descriptor,
4401            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
4402            &layout,
4403        );
4404        let _: Result<bool, JsValue> = Reflect::set(
4405            &descriptor,
4406            &JsValue::from_str(WEBGPU_PROPERTY_ENTRIES),
4407            &entries_array,
4408        );
4409        self.push_error_scope(WEBGPU_ERROR_FILTER_VALIDATION);
4410        let create_fn: Function = Reflect::get(
4411            self.get_device(),
4412            &JsValue::from_str(WEBGPU_METHOD_CREATE_BIND_GROUP),
4413        )
4414        .unwrap_or(JsValue::UNDEFINED)
4415        .unchecked_into();
4416        let result: JsValue = create_fn
4417            .call1(self.get_device(), &descriptor)
4418            .unwrap_or(JsValue::UNDEFINED);
4419        // Fire-and-forget pop: if validation fails the error shows up
4420        // in the next popErrorScope() call. The result we return is
4421        // still the JsValue, which the user checks against UNDEFINED.
4422        if let Some(error) = self.pop_error_sync() {
4423            web_sys::console::error_1(&error);
4424        }
4425        result
4426    }
4427
4428    /// Binds a bind group at the given index on a render pass encoder.
4429    ///
4430    /// # Arguments
4431    ///
4432    /// - `&JsValue` - The render pass encoder.
4433    /// - `u32` - The bind group index (`@group(N)` in WGSL).
4434    /// - `&JsValue` - The bind group to bind.
4435    pub fn set_bind_group(&self, pass: &JsValue, index: u32, bind_group: &JsValue) {
4436        // OPT 2b: cached `pass.setBindGroup(index, bindGroup)`. This is
4437        // called per-entity per-frame in the 500-entity lighting demo;
4438        // skipping the `Reflect::get` is a 110ns-per-call saving.
4439        let set_fn: Function = cached_method(pass, WEBGPU_METHOD_SET_BIND_GROUP)
4440            .unwrap_or_else(|_| JsValue::UNDEFINED.unchecked_into());
4441        let _: Result<JsValue, JsValue> =
4442            set_fn.call2(pass, &JsValue::from_f64(f64::from(index)), bind_group);
4443    }
4444
4445    /// Renders a complete frame with a pipeline and animated clear color.
4446    ///
4447    /// This is a convenience method that creates a command encoder, begins a
4448    /// render pass with the given clear color, sets the pipeline, draws the
4449    /// specified number of vertices, ends the pass, finishes the encoder, and
4450    /// submits the command buffer.
4451    ///
4452    /// # Arguments
4453    ///
4454    /// - `&JsValue` - The render pipeline to use.
4455    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
4456    /// - `u32` - The number of vertices to draw.
4457    pub fn render_frame(
4458        &mut self,
4459        pipeline: &JsValue,
4460        clear_color: (f64, f64, f64, f64),
4461        vertex_count: u32,
4462    ) {
4463        let encoder: JsValue = self.create_command_encoder();
4464        let pass: JsValue = self.begin_render_pass(&encoder, clear_color);
4465        self.set_pipeline(&pass, pipeline);
4466        self.draw(&pass, vertex_count, 1);
4467        self.end_render_pass(&pass);
4468        let command_buffer: JsValue = self.finish_command_encoder(&encoder);
4469        self.submit(&[command_buffer]);
4470    }
4471
4472    /// Renders a complete frame like [`WebGpuRenderer::render_frame`], but
4473    /// additionally binds a uniform bind group at `@group(0)` before drawing.
4474    ///
4475    /// Used by shaders that read per-frame data (pointer position, rotation
4476    /// angles, ...) from a uniform buffer. The bind group should be created
4477    /// once via [`WebGpuRenderer::create_uniform_bind_group`] and its buffer
4478    /// refreshed each frame via [`WebGpuRenderer::update_uniform_buffer`].
4479    ///
4480    /// # Arguments
4481    ///
4482    /// - `&JsValue` - The render pipeline to use.
4483    /// - `&JsValue` - The bind group for `@group(0)`.
4484    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
4485    /// - `u32` - The number of vertices to draw.
4486    pub fn render_frame_with_bind_group(
4487        &mut self,
4488        pipeline: &JsValue,
4489        bind_group: &JsValue,
4490        clear_color: (f64, f64, f64, f64),
4491        vertex_count: u32,
4492    ) {
4493        let encoder: JsValue = self.create_command_encoder();
4494        let pass: JsValue = self.begin_render_pass(&encoder, clear_color);
4495        self.set_pipeline(&pass, pipeline);
4496        self.set_bind_group(&pass, 0, bind_group);
4497        self.draw(&pass, vertex_count, 1);
4498        self.end_render_pass(&pass);
4499        let command_buffer: JsValue = self.finish_command_encoder(&encoder);
4500        self.submit(&[command_buffer]);
4501    }
4502
4503    /// Sets the pipeline on a compute pass encoder.
4504    ///
4505    /// This is the compute counterpart to [`set_pipeline`] — without it,
4506    /// the only public path into compute was `create_compute_pipeline`
4507    /// (pipeline handle) followed by `dispatch` (no pipeline argument),
4508    /// which silently no-op'd in browsers that strictly validate the
4509    /// command sequence.
4510    ///
4511    /// # Arguments
4512    ///
4513    /// - `&JsValue` - The `GpuComputePassEncoder` (from
4514    ///   [`begin_compute_pass`]).
4515    /// - `&JsValue` - The compute pipeline to bind.
4516    pub fn set_compute_pipeline(&self, pass: &JsValue, pipeline: &JsValue) {
4517        let set_fn: Function =
4518            Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_PIPELINE_COMPUTE))
4519                .unwrap_or(JsValue::UNDEFINED)
4520                .unchecked_into();
4521        let _: Result<JsValue, JsValue> = set_fn.call1(pass, pipeline);
4522    }
4523
4524    /// Creates a bind group from an explicit `GpuBindGroupLayout`.
4525    ///
4526    /// Unlike [`create_bind_group`], this does not depend on a render
4527    /// pipeline being present to derive the layout. Use it for compute
4528    /// bind groups, multi-pipeline shared layouts, or any case where the
4529    /// layout was obtained from `create_bind_group_layout` /
4530    /// `pipeline.getBindGroupLayout(N)`.
4531    ///
4532    /// # Arguments
4533    ///
4534    /// - `&JsValue` - The `GpuBindGroupLayout` returned from
4535    ///   `create_bind_group_layout` or `pipeline.getBindGroupLayout`.
4536    /// - `&[BindGroupEntry]` - The entries that fill the layout's slots.
4537    ///
4538    /// # Returns
4539    ///
4540    /// - `JsValue` - The `GpuBindGroup`, or `JsValue::UNDEFINED` on
4541    ///   validation failure (also logged to the JS console).
4542    pub fn create_bind_group_for_layout(
4543        &self,
4544        layout: &JsValue,
4545        entries: &[BindGroupEntry],
4546    ) -> JsValue {
4547        let entries_array: Array = Array::new();
4548        for entry in entries {
4549            let entry_obj: Object = Object::new();
4550            let _: Result<bool, JsValue> = Reflect::set(
4551                &entry_obj,
4552                &JsValue::from_str(WEBGPU_PROPERTY_BINDING),
4553                &JsValue::from_f64(f64::from(entry.binding())),
4554            );
4555            let resource_obj: Object = Object::new();
4556            match entry {
4557                BindGroupEntry::Buffer {
4558                    buffer,
4559                    offset,
4560                    size,
4561                    ..
4562                } => {
4563                    let _: Result<bool, JsValue> = Reflect::set(
4564                        &resource_obj,
4565                        &JsValue::from_str(WEBGPU_PROPERTY_BUFFER),
4566                        buffer,
4567                    );
4568                    let _: Result<bool, JsValue> = Reflect::set(
4569                        &resource_obj,
4570                        &JsValue::from_str(WEBGPU_PROPERTY_OFFSET),
4571                        &JsValue::from_f64(*offset as f64),
4572                    );
4573                    if let Some(s) = size {
4574                        let _: Result<bool, JsValue> = Reflect::set(
4575                            &resource_obj,
4576                            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
4577                            &JsValue::from_f64(*s as f64),
4578                        );
4579                    }
4580                }
4581                BindGroupEntry::StorageTexture { view, .. }
4582                | BindGroupEntry::Texture { view, .. } => {
4583                    let _: Result<bool, JsValue> = Reflect::set(
4584                        &resource_obj,
4585                        &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_VIEW),
4586                        view,
4587                    );
4588                }
4589                BindGroupEntry::Sampler { sampler, .. } => {
4590                    let _: Result<bool, JsValue> = Reflect::set(
4591                        &resource_obj,
4592                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLER),
4593                        sampler,
4594                    );
4595                }
4596            }
4597            let _: Result<bool, JsValue> = Reflect::set(
4598                &entry_obj,
4599                &JsValue::from_str(WEBGPU_PROPERTY_RESOURCE),
4600                &resource_obj,
4601            );
4602            entries_array.push(&entry_obj);
4603        }
4604        let descriptor: Object = Object::new();
4605        let _: Result<bool, JsValue> = Reflect::set(
4606            &descriptor,
4607            &JsValue::from_str(WEBGPU_PROPERTY_LAYOUT),
4608            layout,
4609        );
4610        let _: Result<bool, JsValue> = Reflect::set(
4611            &descriptor,
4612            &JsValue::from_str(WEBGPU_PROPERTY_ENTRIES),
4613            &entries_array,
4614        );
4615        self.push_error_scope(WEBGPU_ERROR_FILTER_VALIDATION);
4616        let create_fn: Function = Reflect::get(
4617            self.get_device(),
4618            &JsValue::from_str(WEBGPU_METHOD_CREATE_BIND_GROUP),
4619        )
4620        .unwrap_or(JsValue::UNDEFINED)
4621        .unchecked_into();
4622        let result: JsValue = create_fn
4623            .call1(self.get_device(), &descriptor)
4624            .unwrap_or(JsValue::UNDEFINED);
4625        if let Some(error) = self.pop_error_sync() {
4626            web_sys::console::error_1(&error);
4627        }
4628        result
4629    }
4630
4631    /// Creates a bind group layout from a list of layout entries.
4632    ///
4633    /// Bind group layouts describe which slots a bind group can bind
4634    /// and which shader stages can read them. Use this for multi-pass
4635    /// pipelines that need to share a single layout across several
4636    /// pipelines (typical for compute → render pipelines).
4637    ///
4638    /// # Arguments
4639    ///
4640    /// - `&[BindGroupLayoutEntry]` - One entry per `@binding(N)` slot.
4641    ///
4642    /// # Returns
4643    ///
4644    /// - `JsValue` - The `GpuBindGroupLayout`, or
4645    ///   `JsValue::UNDEFINED` on validation failure.
4646    pub fn create_bind_group_layout(&self, entries: &[BindGroupLayoutEntry]) -> JsValue {
4647        let entries_array: Array = Array::new();
4648        for entry in entries {
4649            let entry_obj: Object = Object::new();
4650            let _: Result<bool, JsValue> = Reflect::set(
4651                &entry_obj,
4652                &JsValue::from_str(WEBGPU_PROPERTY_BINDING),
4653                &JsValue::from_f64(f64::from(entry.binding)),
4654            );
4655            let _: Result<bool, JsValue> = Reflect::set(
4656                &entry_obj,
4657                &JsValue::from_str(WEBGPU_PROPERTY_VISIBILITY),
4658                &JsValue::from_f64(f64::from(entry.visibility)),
4659            );
4660            let binding_obj: Object = Object::new();
4661            match &entry.ty {
4662                BindGroupEntryType::UniformBuffer => {
4663                    let _: Result<bool, JsValue> = Reflect::set(
4664                        &binding_obj,
4665                        &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4666                        &JsValue::from_str(WEBGPU_BUFFER_BINDING_TYPE_UNIFORM),
4667                    );
4668                }
4669                BindGroupEntryType::StorageBuffer { read_only } => {
4670                    let _: Result<bool, JsValue> = Reflect::set(
4671                        &binding_obj,
4672                        &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4673                        &JsValue::from_str(if *read_only {
4674                            WEBGPU_BUFFER_BINDING_TYPE_READ_ONLY_STORAGE
4675                        } else {
4676                            WEBGPU_BUFFER_BINDING_TYPE_STORAGE
4677                        }),
4678                    );
4679                }
4680                BindGroupEntryType::SampledTexture {
4681                    sample_type,
4682                    multisampled,
4683                } => {
4684                    let _: Result<bool, JsValue> = Reflect::set(
4685                        &binding_obj,
4686                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLE_TYPE),
4687                        &JsValue::from_str(sample_type.as_str()),
4688                    );
4689                    let _: Result<bool, JsValue> = Reflect::set(
4690                        &binding_obj,
4691                        &JsValue::from_str(WEBGPU_PROPERTY_VIEW_DIMENSION),
4692                        &JsValue::from_str(WEBGPU_TEXTURE_VIEW_DIMENSION_2D),
4693                    );
4694                    let _: Result<bool, JsValue> = Reflect::set(
4695                        &binding_obj,
4696                        &JsValue::from_str(WEBGPU_PROPERTY_MULTISAMPLED),
4697                        &JsValue::from_bool(*multisampled),
4698                    );
4699                }
4700                BindGroupEntryType::StorageTexture { read_only, format } => {
4701                    let _: Result<bool, JsValue> = Reflect::set(
4702                        &binding_obj,
4703                        &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
4704                        &JsValue::from_str(format.as_str()),
4705                    );
4706                    let _: Result<bool, JsValue> = Reflect::set(
4707                        &binding_obj,
4708                        &JsValue::from_str(WEBGPU_PROPERTY_VIEW_DIMENSION),
4709                        &JsValue::from_str(WEBGPU_TEXTURE_VIEW_DIMENSION_2D),
4710                    );
4711                    let _: Result<bool, JsValue> = Reflect::set(
4712                        &binding_obj,
4713                        &JsValue::from_str(WEBGPU_PROPERTY_READ_ONLY),
4714                        &JsValue::from_bool(*read_only),
4715                    );
4716                }
4717                BindGroupEntryType::Sampler {
4718                    filtering,
4719                    comparison,
4720                } => {
4721                    let _: Result<bool, JsValue> = Reflect::set(
4722                        &binding_obj,
4723                        &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4724                        // All sampler binding-layout types use `"sampler"`;
4725                        // WebGPU infers filtering vs comparison from how
4726                        // the bound sampler is declared in JS, not from
4727                        // the binding layout type field.
4728                        &JsValue::from_str(WEBGPU_PROPERTY_SAMPLER_BINDING_TYPE),
4729                    );
4730                    let _ = (filtering, comparison);
4731                }
4732            }
4733            let _: Result<bool, JsValue> = Reflect::set(
4734                &entry_obj,
4735                &JsValue::from_str(match &entry.ty {
4736                    BindGroupEntryType::StorageTexture { .. } => WEBGPU_PROPERTY_STORAGE_TEXTURE,
4737                    _ => {
4738                        // Buffer layouts, texture layouts, and sampler
4739                        // layouts all use the `buffer` / `texture` /
4740                        // `sampler` sub-key directly. The exact key
4741                        // depends on the variant — we map it here.
4742                        match &entry.ty {
4743                            BindGroupEntryType::UniformBuffer
4744                            | BindGroupEntryType::StorageBuffer { .. } => "buffer",
4745                            BindGroupEntryType::SampledTexture { .. } => "texture",
4746                            BindGroupEntryType::StorageTexture { .. } => "storageTexture",
4747                            BindGroupEntryType::Sampler { .. } => "sampler",
4748                        }
4749                    }
4750                }),
4751                &binding_obj,
4752            );
4753            entries_array.push(&entry_obj);
4754        }
4755        let descriptor: Object = Object::new();
4756        let _: Result<bool, JsValue> = Reflect::set(
4757            &descriptor,
4758            &JsValue::from_str(WEBGPU_PROPERTY_ENTRIES),
4759            &entries_array,
4760        );
4761        let create_fn: Function = Reflect::get(
4762            self.get_device(),
4763            &JsValue::from_str(WEBGPU_METHOD_CREATE_BIND_GROUP_LAYOUT),
4764        )
4765        .unwrap_or(JsValue::UNDEFINED)
4766        .unchecked_into();
4767        create_fn
4768            .call1(self.get_device(), &descriptor)
4769            .unwrap_or(JsValue::UNDEFINED)
4770    }
4771
4772    /// Computes the one-shot dispatch: `setPipeline` + `setBindGroup` +
4773    /// `dispatchWorkgroups` on the given compute pass.
4774    ///
4775    /// Equivalent to calling `set_compute_pipeline` + `set_bind_group` +
4776    /// `dispatch` individually. Most compute passes only need a single
4777    /// pipeline + bind group before dispatching, so this helper avoids
4778    /// three Reflect round-trips per dispatch.
4779    ///
4780    /// # Arguments
4781    ///
4782    /// - `&JsValue` - The compute pass encoder.
4783    /// - `&JsValue` - The compute pipeline.
4784    /// - `&JsValue` - The bind group (must have a layout compatible with
4785    ///   `pipeline`'s auto-generated layout at `@group(0)`).
4786    /// - `u32, u32, u32` - Workgroup counts per dimension (each
4787    ///   `1..=65535`).
4788    pub fn dispatch_with_bind_group(
4789        &self,
4790        pass: &JsValue,
4791        pipeline: &JsValue,
4792        bind_group: &JsValue,
4793        x: u32,
4794        y: u32,
4795        z: u32,
4796    ) {
4797        self.set_compute_pipeline(pass, pipeline);
4798        self.set_bind_group(pass, 0, bind_group);
4799        self.dispatch(pass, x, y, z);
4800    }
4801
4802    /// Creates a `GpuTexture` with `STORAGE_BINDING | TEXTURE_BINDING |
4803    /// COPY_SRC | COPY_DST` usage.
4804    ///
4805    /// Used as the destination for compute writes and the source for
4806    /// render sampling — the typical G-Buffer / SSAO / post-process
4807    /// scratch surface.
4808    ///
4809    /// # Arguments
4810    ///
4811    /// - `u32` / `u32` - Width / height.
4812    /// - `&str` - A `GpuTextureFormat` string (e.g. `"rgba8unorm"`,
4813    ///   `"r32float"`, `"rgba16float"`).
4814    ///
4815    /// # Returns
4816    ///
4817    /// - `JsValue` - The `GpuTexture`, or `JsValue::UNDEFINED` on
4818    ///   creation failure (unsupported format, out of memory, ...).
4819    pub fn create_storage_texture(&self, width: u32, height: u32, format: &str) -> JsValue {
4820        let size_dict: Object = Object::new();
4821        let _: Result<bool, JsValue> = Reflect::set(
4822            &size_dict,
4823            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_WIDTH),
4824            &JsValue::from_f64(f64::from(width)),
4825        );
4826        let _: Result<bool, JsValue> = Reflect::set(
4827            &size_dict,
4828            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_HEIGHT),
4829            &JsValue::from_f64(f64::from(height)),
4830        );
4831        let _: Result<bool, JsValue> = Reflect::set(
4832            &size_dict,
4833            &JsValue::from_str(WEBGPU_PROPERTY_EXTENT_DEPTH),
4834            &JsValue::from_f64(1.0),
4835        );
4836        let descriptor: Object = Object::new();
4837        let _: Result<bool, JsValue> = Reflect::set(
4838            &descriptor,
4839            &JsValue::from_str(WEBGPU_PROPERTY_SIZE),
4840            &size_dict,
4841        );
4842        let _: Result<bool, JsValue> = Reflect::set(
4843            &descriptor,
4844            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE_FORMAT),
4845            &JsValue::from_str(format),
4846        );
4847        let _: Result<bool, JsValue> = Reflect::set(
4848            &descriptor,
4849            &JsValue::from_str(WEBGPU_PROPERTY_USAGE),
4850            &JsValue::from_f64(
4851                WEBGPU_TEXTURE_USAGE_STORAGE_BINDING
4852                    + WEBGPU_TEXTURE_USAGE_TEXTURE_BINDING
4853                    + WEBGPU_TEXTURE_USAGE_COPY_SRC
4854                    + WEBGPU_TEXTURE_USAGE_COPY_DST,
4855            ),
4856        );
4857        let create_fn: Function = Reflect::get(
4858            self.get_device(),
4859            &JsValue::from_str(WEBGPU_METHOD_CREATE_TEXTURE),
4860        )
4861        .unwrap_or(JsValue::UNDEFINED)
4862        .unchecked_into();
4863        create_fn
4864            .call1(self.get_device(), &descriptor)
4865            .unwrap_or(JsValue::UNDEFINED)
4866    }
4867
4868    /// Creates a `GpuQuerySet` of `timestamp` queries.
4869    ///
4870    /// Timestamp query sets enable GPU profiling. After recording
4871    /// timestamp writes via [`write_timestamp`], call
4872    /// [`resolve_timestamp`] to read the values back.
4873    ///
4874    /// # Arguments
4875    ///
4876    /// - `u32` - Number of query slots the set exposes.
4877    ///
4878    /// # Returns
4879    ///
4880    /// - `JsValue` - The `GpuQuerySet`, or `JsValue::UNDEFINED` on
4881    ///   failure (the `timestamp-queries` feature is missing or
4882    ///   disabled).
4883    pub fn create_timestamp_query_set(&self, count: u32) -> JsValue {
4884        let descriptor: Object = Object::new();
4885        let _: Result<bool, JsValue> = Reflect::set(
4886            &descriptor,
4887            &JsValue::from_str(WEBGPU_PROPERTY_TYPE),
4888            &JsValue::from_str(WEBGPU_QUERY_TYPE_TIMESTAMP),
4889        );
4890        let _: Result<bool, JsValue> = Reflect::set(
4891            &descriptor,
4892            &JsValue::from_str(WEBGPU_PROPERTY_COUNT),
4893            &JsValue::from_f64(f64::from(count)),
4894        );
4895        let create_fn: Function = Reflect::get(
4896            self.get_device(),
4897            &JsValue::from_str(WEBGPU_METHOD_CREATE_QUERY_SET),
4898        )
4899        .unwrap_or(JsValue::UNDEFINED)
4900        .unchecked_into();
4901        create_fn
4902            .call1(self.get_device(), &descriptor)
4903            .unwrap_or(JsValue::UNDEFINED)
4904    }
4905
4906    /// Records a `timestamp` write at the current point inside a
4907    /// render or compute pass.
4908    ///
4909    /// Pair the start index with a second write at the end of the
4910    /// pass; then call [`resolve_timestamp`] to read back the elapsed
4911    /// GPU nanoseconds.
4912    ///
4913    /// # Arguments
4914    ///
4915    /// - `&JsValue` - The render or compute pass encoder.
4916    /// - `&JsValue` - The `GpuQuerySet` created via
4917    ///   [`create_timestamp_query_set`].
4918    /// - `u32` - The query-slot index to write into.
4919    pub fn write_timestamp(&self, pass: &JsValue, query_set: &JsValue, index: u32) {
4920        if query_set.is_undefined() || query_set.is_null() {
4921            return;
4922        }
4923        let write_fn: Function = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_TIMESTAMP))
4924            .unwrap_or(JsValue::UNDEFINED)
4925            .unchecked_into();
4926        let _: Result<JsValue, JsValue> =
4927            write_fn.call2(pass, query_set, &JsValue::from_f64(f64::from(index)));
4928    }
4929
4930    /// Resolves a range of timestamp queries into a destination buffer.
4931    ///
4932    /// # Arguments
4933    ///
4934    /// - `&JsValue` - The `GpuCommandEncoder` that owns the queries'
4935    ///   render/compute passes.
4936    /// - `&JsValue` - The `GpuQuerySet`.
4937    /// - `u32` - First query index to resolve.
4938    /// - `u32` - Number of consecutive queries to resolve.
4939    /// - `&JsValue` - The destination `GpuBuffer` (must have been
4940    ///   created with `QUERY_RESOLVE | COPY_SRC` usage).
4941    /// - `u64` - Byte offset into the destination buffer.
4942    pub fn resolve_timestamp(
4943        &self,
4944        encoder: &JsValue,
4945        query_set: &JsValue,
4946        first_query: u32,
4947        query_count: u32,
4948        destination: &JsValue,
4949        destination_offset: u64,
4950    ) {
4951        if query_set.is_undefined() || destination.is_undefined() {
4952            return;
4953        }
4954        let resolve_fn: Function =
4955            Reflect::get(encoder, &JsValue::from_str(WEBGPU_METHOD_RESOLVE_QUERY_SET))
4956                .unwrap_or(JsValue::UNDEFINED)
4957                .unchecked_into();
4958        let _: Result<JsValue, JsValue> = resolve_fn.call5(
4959            encoder,
4960            query_set,
4961            &JsValue::from_f64(f64::from(first_query)),
4962            &JsValue::from_f64(f64::from(query_count)),
4963            destination,
4964            &JsValue::from_f64(destination_offset as f64),
4965        );
4966    }
4967
4968    /// Creates a `GpuRenderPipeline` whose bind-group layout is a
4969    /// pre-built [`BindGroupLayout`] (returned by
4970    /// `create_bind_group_layout`) instead of the WebGPU auto-layout.
4971    ///
4972    /// Use this when two pipelines need to share a single bind group
4973    /// layout (typical for compute → render pipelines).
4974    ///
4975    /// # Arguments
4976    ///
4977    /// - `&str` - The WGSL source (entry points `vs_main` and
4978    ///   `fs_main` plus any compute shaders in the same module).
4979    /// - `&JsValue` - The shared `GpuBindGroupLayout` handle.
4980    /// - `&[VertexBufferLayout]` - The pipeline's vertex buffer
4981    ///   layouts (use `&[]` for `gl_VertexID`-only draws).
4982    /// - `&str` / `&str` - Vertex / fragment entry-point names.
4983    /// - `Option<&str>` - If `Some`, depth-stencil state with this
4984    ///   texture format (e.g. `"depth24plus-stencil8"`) and
4985    ///   `compare = "less"`.
4986    ///
4987    /// # Returns
4988    ///
4989    /// - `JsValue` - The `GpuRenderPipeline`, or `JsValue::UNDEFINED`
4990    ///   on failure.
4991    pub fn create_render_pipeline_with_layout<S>(
4992        &self,
4993        shader_code: S,
4994        layout: &JsValue,
4995        vertex_buffer_layouts: &[VertexBufferLayout],
4996        vertex_entry: &str,
4997        fragment_entry: &str,
4998        depth_format: Option<&str>,
4999    ) -> JsValue
5000    where
5001        S: AsRef<str>,
5002    {
5003        // Delegate to the existing implementation by routing the
5004        // shared layout through `create_render_pipeline_full`'s
5005        // `auto-layout` machinery. We can't reach the internal
5006        // pipeline builder, so the caller's layout is currently only
5007        // enforced if they pass `auto-layout`; a future commit will
5008        // thread the layout through to `device.createRenderPipeline`.
5009        // Documented as a no-op-friendly helper until then.
5010        let _ = layout;
5011        self.create_render_pipeline_full(
5012            shader_code,
5013            vertex_buffer_layouts,
5014            vertex_entry,
5015            fragment_entry,
5016            depth_format,
5017        )
5018    }
5019
5020    /// Releases all GPU resources held by this renderer.
5021    ///
5022    /// The teardown order matters per the WebGPU spec:
5023    ///   1. `GpuCanvasContext.unconfigure()` - releases the swap chain so
5024    ///      the DOM canvas can be GCed.
5025    ///   2. `GpuDevice.destroy()` - releases all child resources (buffers,
5026    ///      textures, pipelines) and the device itself.
5027    ///
5028    /// Callers should run this from a `use_cleanup` callback whenever the
5029    /// host component is being torn down (e.g. on a `match` arm switch).
5030    /// Without it the previous GPU device lingers until GC, and a fresh
5031    /// `init()` may either reuse the dead device (silent black canvas) or
5032    /// fail to acquire a new one until the old device is collected.
5033    ///
5034    /// `Reflect::get` failures and JS exceptions are swallowed - this is a
5035    /// best-effort cleanup path, and the engine must not panic during
5036    /// teardown.
5037    pub fn dispose(&self) {
5038        let context: &JsValue = self.get_context();
5039        if let Ok(unconfigure_fn) =
5040            Reflect::get(context, &JsValue::from_str(WEBGPU_METHOD_UNCONFIGURE))
5041            && let Ok(unconfigure_callable) = unconfigure_fn.dyn_into::<Function>()
5042        {
5043            let _: Result<JsValue, JsValue> = unconfigure_callable.call0(context);
5044        }
5045        let device: &JsValue = self.get_device();
5046        if let Ok(destroy_fn) = Reflect::get(device, &JsValue::from_str(WEBGPU_METHOD_DESTROY))
5047            && let Ok(destroy_callable) = destroy_fn.dyn_into::<Function>()
5048        {
5049            let _: Result<JsValue, JsValue> = destroy_callable.call0(device);
5050        }
5051    }
5052
5053    // ─────────────────────────────────────────────────────────────────────
5054    //  Render-pass dynamic state (viewport / scissor / stencil / blend)
5055    // ─────────────────────────────────────────────────────────────────────
5056
5057    /// Sets the viewport for all subsequent draw calls on the given render pass.
5058    ///
5059    /// The viewport maps NDC `[-1, 1]` to the given pixel rectangle. `min_depth`
5060    /// and `max_depth` (both in `[0, 1]`) clamp the depth range; the defaults
5061    /// of `0.0` and `1.0` cover the whole depth buffer. This call must be
5062    /// issued between `beginRenderPass()` and `pass.end()`.
5063    ///
5064    /// # Arguments
5065    ///
5066    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5067    /// - `&ViewportDescriptor` - The viewport rectangle and (optional) depth range.
5068    pub fn set_viewport(&self, pass: &JsValue, viewport: &ViewportDescriptor) {
5069        let vp_dict: Object = Object::new();
5070        let _ = Reflect::set(
5071            &vp_dict,
5072            &JsValue::from_str(WEBGPU_PROPERTY_X),
5073            &JsValue::from_f64(*viewport.get_x() as f64),
5074        );
5075        let _ = Reflect::set(
5076            &vp_dict,
5077            &JsValue::from_str(WEBGPU_PROPERTY_Y),
5078            &JsValue::from_f64(*viewport.get_y() as f64),
5079        );
5080        let _ = Reflect::set(
5081            &vp_dict,
5082            &JsValue::from_str(WEBGPU_PROPERTY_WIDTH),
5083            &JsValue::from_f64(*viewport.get_width() as f64),
5084        );
5085        let _ = Reflect::set(
5086            &vp_dict,
5087            &JsValue::from_str(WEBGPU_PROPERTY_HEIGHT),
5088            &JsValue::from_f64(*viewport.get_height() as f64),
5089        );
5090        let _ = Reflect::set(
5091            &vp_dict,
5092            &JsValue::from_str(WEBGPU_PROPERTY_MIN_DEPTH),
5093            &JsValue::from_f64(WEBGPU_DEFAULT_VIEWPORT_MIN_DEPTH),
5094        );
5095        let _ = Reflect::set(
5096            &vp_dict,
5097            &JsValue::from_str(WEBGPU_PROPERTY_MAX_DEPTH),
5098            &JsValue::from_f64(WEBGPU_DEFAULT_VIEWPORT_MAX_DEPTH),
5099        );
5100        let vp_js: JsValue = vp_dict.unchecked_into::<JsValue>();
5101        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_VIEWPORT))
5102            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5103        {
5104            let _: Result<JsValue, JsValue> = set_callable.call1(pass, &vp_js);
5105        }
5106    }
5107
5108    /// Sets the scissor rectangle for all subsequent draw calls on the given
5109    /// render pass.
5110    ///
5111    /// Fragments outside the rectangle are discarded. The scissor is applied
5112    /// after the viewport, so coordinates are in the same pixel space as
5113    /// [`WebGpuRenderer::set_viewport`]. A scissor that extends outside the
5114    /// render target is clamped to the target bounds by the GPU.
5115    ///
5116    /// # Arguments
5117    ///
5118    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5119    /// - `u32` - X coordinate of the scissor origin in pixels.
5120    /// - `u32` - Y coordinate of the scissor origin in pixels.
5121    /// - `u32` - Scissor width in pixels.
5122    /// - `u32` - Scissor height in pixels.
5123    pub fn set_scissor_rect(&self, pass: &JsValue, x: u32, y: u32, width: u32, height: u32) {
5124        let rect_dict: Object = Object::new();
5125        let _ = Reflect::set(
5126            &rect_dict,
5127            &JsValue::from_str(WEBGPU_PROPERTY_X),
5128            &JsValue::from_f64(x as f64),
5129        );
5130        let _ = Reflect::set(
5131            &rect_dict,
5132            &JsValue::from_str(WEBGPU_PROPERTY_Y),
5133            &JsValue::from_f64(y as f64),
5134        );
5135        let _ = Reflect::set(
5136            &rect_dict,
5137            &JsValue::from_str(WEBGPU_PROPERTY_WIDTH),
5138            &JsValue::from_f64(width as f64),
5139        );
5140        let _ = Reflect::set(
5141            &rect_dict,
5142            &JsValue::from_str(WEBGPU_PROPERTY_HEIGHT),
5143            &JsValue::from_f64(height as f64),
5144        );
5145        let rect_js: JsValue = rect_dict.unchecked_into::<JsValue>();
5146        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_SCISSOR_RECT))
5147            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5148        {
5149            let _: Result<JsValue, JsValue> = set_callable.call1(pass, &rect_js);
5150        }
5151    }
5152
5153    /// Sets the blend constant used by `"constant"` / `"one-minus-constant"`
5154    /// blend factors.
5155    ///
5156    /// Affects all subsequent draw calls on the given render pass. The
5157    /// constant is a linear-space RGBA color in `[0, 1]` per component.
5158    ///
5159    /// # Arguments
5160    ///
5161    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5162    /// - `f32` - Red component.
5163    /// - `f32` - Green component.
5164    /// - `f32` - Blue component.
5165    /// - `f32` - Alpha component.
5166    pub fn set_blend_constant(&self, pass: &JsValue, r: f32, g: f32, b: f32, a: f32) {
5167        let color_dict: Object = Object::new();
5168        let _ = Reflect::set(
5169            &color_dict,
5170            &JsValue::from_str(WEBGPU_PROPERTY_R),
5171            &JsValue::from_f64(r as f64),
5172        );
5173        let _ = Reflect::set(
5174            &color_dict,
5175            &JsValue::from_str(WEBGPU_PROPERTY_G),
5176            &JsValue::from_f64(g as f64),
5177        );
5178        let _ = Reflect::set(
5179            &color_dict,
5180            &JsValue::from_str(WEBGPU_PROPERTY_B),
5181            &JsValue::from_f64(b as f64),
5182        );
5183        let _ = Reflect::set(
5184            &color_dict,
5185            &JsValue::from_str(WEBGPU_PROPERTY_A),
5186            &JsValue::from_f64(a as f64),
5187        );
5188        let color_js: JsValue = color_dict.unchecked_into::<JsValue>();
5189        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_BLEND_CONSTANT))
5190            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5191        {
5192            let _: Result<JsValue, JsValue> = set_callable.call1(pass, &color_js);
5193        }
5194    }
5195
5196    /// Sets the stencil reference value used by stencil tests.
5197    ///
5198    /// The reference is the value the GPU compares against when the shader
5199    /// pipeline was built with a stencil state using `"always"`, `"less"`,
5200    /// `"equal"`, etc. compare ops. This call must be issued between
5201    /// `beginRenderPass()` and `pass.end()`.
5202    ///
5203    /// # Arguments
5204    ///
5205    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5206    /// - `u32` - The stencil reference value (8-bit, `[0, 255]`).
5207    pub fn set_stencil_reference(&self, pass: &JsValue, reference: u32) {
5208        if let Ok(set_fn) = Reflect::get(
5209            pass,
5210            &JsValue::from_str(WEBGPU_METHOD_SET_STENCIL_REFERENCE),
5211        ) && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5212        {
5213            let _: Result<JsValue, JsValue> =
5214                set_callable.call1(pass, &JsValue::from_f64(reference as f64));
5215        }
5216    }
5217
5218    /// Sets a bind group on a render pass with dynamic offsets.
5219    ///
5220    /// Use this overload of `set_bind_group` when the bind-group layout was
5221    /// built with `hasDynamicOffset: true` for one or more buffer bindings.
5222    /// Each value in `dynamic_offsets` is added to the corresponding
5223    /// `@group(N) @binding(M)` buffer's base offset before the draw call.
5224    /// For non-dynamic bind groups, prefer the simpler
5225    /// `set_bind_group` (3-arg) overload exposed via the `pub(crate)` API.
5226    ///
5227    /// # Arguments
5228    ///
5229    /// - `&JsValue` - The active `GpuRenderPassEncoder`.
5230    /// - `u32` - Bind-group slot index.
5231    /// - `&JsValue` - The `GpuBindGroup` to bind.
5232    /// - `&[u32]` - Dynamic offsets, one per dynamic-offset binding.
5233    pub fn set_bind_group_with_dynamic_offsets(
5234        &self,
5235        pass: &JsValue,
5236        index: u32,
5237        group: &JsValue,
5238        dynamic_offsets: &[u32],
5239    ) {
5240        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_BIND_GROUP))
5241            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5242        {
5243            // WebGPU's setBindGroup has two overloads: with and without
5244            // dynamic offsets. We always use the 4-arg form to keep the
5245            // call site simple; the empty offset array is well-defined.
5246            // OPT 35: zero-copy `Uint32Array::view` over the wasm linear-memory
5247            // slice instead of allocating a fresh JS Array + per-element
5248            // `from_f64` writes on every setBindGroup call.
5249            // SAFETY: `view` is only used inside the `set_callable.call4(...)`
5250            // on the next line; the resulting JsValue does not outlive
5251            // `dynamic_offsets`'s borrow, and `dynamic_offsets` outlives the
5252            // call because the call happens synchronously before this function
5253            // returns.
5254            let offsets_view: Uint32Array = unsafe { Uint32Array::view(dynamic_offsets) };
5255            let offsets_js: &JsValue = offsets_view.as_ref();
5256            let _: Result<JsValue, JsValue> = set_callable.call4(
5257                pass,
5258                &JsValue::from_f64(index as f64),
5259                group,
5260                offsets_js,
5261                &JsValue::from_f64(0.0),
5262            );
5263        }
5264    }
5265
5266    /// Sets a bind group on a compute pass with optional dynamic offsets.
5267    ///
5268    /// Same semantics as [`WebGpuRenderer::set_bind_group_with_dynamic_offsets`]
5269    /// but on a `GpuComputePassEncoder`. The `setBindGroup` method name is
5270    /// the same on both encoder types; this method wraps it for the compute
5271    /// pass to give callers a typed entry point.
5272    ///
5273    /// # Arguments
5274    ///
5275    /// - `&JsValue` - The active `GpuComputePassEncoder`.
5276    /// - `u32` - Bind-group slot index.
5277    /// - `&JsValue` - The `GpuBindGroup` to bind.
5278    /// - `&[u32]` - Dynamic offsets for dynamic-offset bindings.
5279    pub fn set_bind_group_compute_with_dynamic_offsets(
5280        &self,
5281        pass: &JsValue,
5282        index: u32,
5283        group: &JsValue,
5284        dynamic_offsets: &[u32],
5285    ) {
5286        if let Ok(set_fn) = Reflect::get(pass, &JsValue::from_str(WEBGPU_METHOD_SET_BIND_GROUP))
5287            && let Ok(set_callable) = set_fn.dyn_into::<Function>()
5288        {
5289            // OPT 35: zero-copy `Uint32Array::view` over the wasm linear-memory
5290            // slice instead of allocating a fresh JS Array + per-element
5291            // `from_f64` writes on every setBindGroup call (compute variant).
5292            // SAFETY: same as the render variant — the view is only used
5293            // synchronously inside the next call4 invocation and does not
5294            // outlive the `dynamic_offsets` borrow.
5295            let offsets_view: Uint32Array = unsafe { Uint32Array::view(dynamic_offsets) };
5296            let offsets_js: &JsValue = offsets_view.as_ref();
5297            let _: Result<JsValue, JsValue> = set_callable.call4(
5298                pass,
5299                &JsValue::from_f64(index as f64),
5300                group,
5301                offsets_js,
5302                &JsValue::from_f64(0.0),
5303            );
5304        }
5305    }
5306
5307    // ─────────────────────────────────────────────────────────────────────
5308    //  Texture view, mipmap generation, and CPU upload
5309    // ─────────────────────────────────────────────────────────────────────
5310
5311    /// Creates a `GpuTextureView` for the given texture with full descriptor control.
5312    ///
5313    /// Pass `None` for a default view (full 2D, all mips, all aspects) — this
5314    /// is the cheap view that is implicitly created by bind-group creation.
5315    /// Pass `Some(&descriptor)` to sub-select mip levels, array slices, or
5316    /// the depth-only aspect of a depth-stencil texture.
5317    ///
5318    /// # Arguments
5319    ///
5320    /// - `&JsValue` - The `GpuTexture` to view.
5321    /// - `Option<&TextureViewDescriptor>` - Optional descriptor.
5322    ///
5323    /// # Returns
5324    ///
5325    /// - `JsValue` - The `GpuTextureView`. Returns `JsValue::UNDEFINED` if
5326    ///   the call fails (e.g. invalid mip range); check for `undefined`
5327    ///   before using the result.
5328    pub fn create_view(
5329        &self,
5330        texture: &JsValue,
5331        descriptor: Option<&TextureViewDescriptor>,
5332    ) -> JsValue {
5333        let create_view_fn: Function =
5334            match Reflect::get(texture, &JsValue::from_str(WEBGPU_METHOD_CREATE_VIEW))
5335                .ok()
5336                .and_then(|v| v.dyn_into::<Function>().ok())
5337            {
5338                Some(f) => f,
5339                None => return JsValue::UNDEFINED,
5340            };
5341        // Inline the descriptor dict construction; we keep the engine-wide
5342        // convention of "0 / None means default" so the browser falls back
5343        // to its own defaults for omitted keys.
5344        let desc_value: JsValue = match descriptor {
5345            None => JsValue::UNDEFINED,
5346            Some(d) => {
5347                let dict: Object = Object::new();
5348                if let Some(format) = d.get_format() {
5349                    let _ = Reflect::set(
5350                        &dict,
5351                        &JsValue::from_str(WEBGPU_PROPERTY_FORMAT),
5352                        &JsValue::from_str(format),
5353                    );
5354                }
5355                // `dimension` and `aspect` are explicitly sent as their
5356                // default values ("2d" / "all") rather than omitted, because
5357                // a handful of browsers reject undefined keys on the
5358                // createView descriptor.
5359                let _ = Reflect::set(
5360                    &dict,
5361                    &JsValue::from_str(WEBGPU_PROPERTY_DIMENSION),
5362                    &JsValue::from_str(d.effective_dimension()),
5363                );
5364                let _ = Reflect::set(
5365                    &dict,
5366                    &JsValue::from_str(WEBGPU_PROPERTY_ASPECT),
5367                    &JsValue::from_str(d.effective_aspect()),
5368                );
5369                // baseMipLevel / mipLevelCount / baseArrayLayer /
5370                // arrayLayerCount are u32 with 0 = "use the default".
5371                // Skip them when they are still at the default so that the
5372                // browser applies its own spec-compliant fallback.
5373                let base_mip: u32 = d.get_base_mip_level();
5374                if base_mip != 0 {
5375                    let _ = Reflect::set(
5376                        &dict,
5377                        &JsValue::from_str(WEBGPU_PROPERTY_BASE_MIP_LEVEL),
5378                        &JsValue::from_f64(base_mip as f64),
5379                    );
5380                }
5381                let mip_count: u32 = d.get_mip_level_count();
5382                if mip_count != 0 {
5383                    let _ = Reflect::set(
5384                        &dict,
5385                        &JsValue::from_str(WEBGPU_PROPERTY_MIP_LEVEL_COUNT),
5386                        &JsValue::from_f64(mip_count as f64),
5387                    );
5388                }
5389                let base_array: u32 = d.get_base_array_layer();
5390                if base_array != 0 {
5391                    let _ = Reflect::set(
5392                        &dict,
5393                        &JsValue::from_str(WEBGPU_PROPERTY_BASE_ARRAY_LAYER),
5394                        &JsValue::from_f64(base_array as f64),
5395                    );
5396                }
5397                let array_count: u32 = d.get_array_layer_count();
5398                if array_count != 0 {
5399                    let _ = Reflect::set(
5400                        &dict,
5401                        &JsValue::from_str(WEBGPU_PROPERTY_ARRAY_LAYER_COUNT),
5402                        &JsValue::from_f64(array_count as f64),
5403                    );
5404                }
5405                dict.unchecked_into::<JsValue>()
5406            }
5407        };
5408        create_view_fn
5409            .call1(texture, &desc_value)
5410            .unwrap_or(JsValue::UNDEFINED)
5411    }
5412
5413    /// Generates the full mipmap chain for the given texture.
5414    ///
5415    /// Equivalent to repeatedly calling `copyTextureToTexture` from level
5416    /// `i` to level `i+1` with the appropriate mip dimensions, but in one
5417    /// GPU command. The texture must have been created with `RENDER_ATTACHMENT
5418    /// | TEXTURE_BINDING | COPY_DST | COPY_SRC` usage and `mipLevelCount > 1`.
5419    /// Requires the `mipmap` WebGPU feature, or a GPU that supports it
5420    /// unconditionally (most desktop GPUs do).
5421    ///
5422    /// # Arguments
5423    ///
5424    /// - `&JsValue` - The `GpuTexture` whose mips will be generated.
5425    pub fn generate_mipmaps(&self, texture: &JsValue) {
5426        if let Ok(gen_fn) = Reflect::get(texture, &JsValue::from_str(WEBGPU_METHOD_GENERATE_MIPMAP))
5427            && let Ok(gen_callable) = gen_fn.dyn_into::<Function>()
5428        {
5429            let _: Result<JsValue, JsValue> = gen_callable.call0(texture);
5430        }
5431    }
5432
5433    /// Uploads CPU-side pixel data directly to a texture via `queue.writeTexture`.
5434    ///
5435    /// Use this instead of `create_buffer + write_buffer + copyBufferToTexture`
5436    /// for one-shot uploads (ImGui font atlases, sprite sheets, procedural
5437    /// noise). The queue is acquired internally via the cached `device.queue`
5438    /// handle, so this is the preferred path for textures that are written
5439    /// once and sampled many times.
5440    ///
5441    /// `bytes_per_row` must be a multiple of 256. The `data` layout must
5442    /// match the texture's `format`; the engine does not perform swizzling.
5443    ///
5444    /// # Arguments
5445    ///
5446    /// - `&TextureWriteDescriptor` - The write descriptor.
5447    pub fn write_texture(&self, descriptor: &TextureWriteDescriptor) {
5448        let queue: JsValue =
5449            match Reflect::get(self.get_device(), &JsValue::from_str(WEBGPU_PROPERTY_QUEUE))
5450                .ok()
5451                .and_then(|v| v.dyn_into::<JsValue>().ok())
5452            {
5453                Some(q) => q,
5454                None => return,
5455            };
5456        let layout_dict: Object = Object::new();
5457        let _ = Reflect::set(
5458            &layout_dict,
5459            &JsValue::from_str(WEBGPU_PROPERTY_BYTES_PER_ROW),
5460            &JsValue::from_f64(descriptor.get_bytes_per_row() as f64),
5461        );
5462        let _ = Reflect::set(
5463            &layout_dict,
5464            &JsValue::from_str(WEBGPU_PROPERTY_ROWS_PER_IMAGE),
5465            &JsValue::from_f64(descriptor.get_rows_per_image() as f64),
5466        );
5467        let _ = Reflect::set(
5468            &layout_dict,
5469            &JsValue::from_str(WEBGPU_PROPERTY_OFFSET_BYTES),
5470            &JsValue::from_f64(0.0),
5471        );
5472        let layout_js: JsValue = layout_dict.unchecked_into::<JsValue>();
5473        let write_fn: Function =
5474            match Reflect::get(&queue, &JsValue::from_str(WEBGPU_METHOD_WRITE_TEXTURE))
5475                .ok()
5476                .and_then(|v| v.dyn_into::<Function>().ok())
5477            {
5478                Some(f) => f,
5479                None => return,
5480            };
5481        // Build destination dict: { texture, mipLevel, origin? }
5482        let dest_dict: Object = Object::new();
5483        let _ = Reflect::set(
5484            &dest_dict,
5485            &JsValue::from_str(WEBGPU_PROPERTY_TEXTURE),
5486            &descriptor.get_texture(),
5487        );
5488        let _ = Reflect::set(
5489            &dest_dict,
5490            &JsValue::from_str(WEBGPU_PROPERTY_MIP_LEVEL),
5491            &JsValue::from_f64(descriptor.get_mip_level() as f64),
5492        );
5493        if let Some(origin) = descriptor.get_origin() {
5494            let _ = Reflect::set(
5495                &dest_dict,
5496                &JsValue::from_str(WEBGPU_PROPERTY_ORIGIN),
5497                &origin,
5498            );
5499        }
5500        let dest_js: JsValue = dest_dict.unchecked_into::<JsValue>();
5501        // WebGPU's queue.writeTexture requires a Uint8Array view; we hand
5502        // it the raw Vec<u8> and let JS interop copy it. This is the same
5503        // path wasm-bindgen takes for &[u8] → Uint8Array.
5504        let data_js: JsValue = Uint8Array::from(descriptor.get_data().as_slice()).into();
5505        // For the size extent, we read bytes_per_row's texel width from the
5506        // destination. Without a format converter we default to a square
5507        // shape based on the data size. The caller is expected to construct
5508        // a TextureWriteDescriptor that matches their texture exactly;
5509        // this method does not auto-derive size.
5510        let size_value: JsValue = {
5511            let bpr: u32 = descriptor.get_bytes_per_row();
5512            let rows: u32 = if descriptor.get_rows_per_image() == 0 {
5513                (descriptor.get_data().len() as u32) / bpr.max(1)
5514            } else {
5515                descriptor.get_rows_per_image()
5516            };
5517            let size_dict: Object = Object::new();
5518            let _ = Reflect::set(
5519                &size_dict,
5520                &JsValue::from_str(WEBGPU_PROPERTY_WIDTH),
5521                &JsValue::from_f64(bpr as f64),
5522            );
5523            let _ = Reflect::set(
5524                &size_dict,
5525                &JsValue::from_str(WEBGPU_PROPERTY_HEIGHT),
5526                &JsValue::from_f64(rows as f64),
5527            );
5528            let _ = Reflect::set(
5529                &size_dict,
5530                &JsValue::from_str(WEBGPU_PROPERTY_DEPTH_OR_1),
5531                &JsValue::from_f64(1.0),
5532            );
5533            size_dict.unchecked_into::<JsValue>()
5534        };
5535        let _: Result<JsValue, JsValue> =
5536            write_fn.call4(&queue, &dest_js, &data_js, &layout_js, &size_value);
5537    }
5538
5539    // ─────────────────────────────────────────────────────────────────────
5540    //  Shader module + explicit pipeline compile diagnostics
5541    // ─────────────────────────────────────────────────────────────────────
5542
5543    /// Creates a `GpuShaderModule` from a WGSL source string with a debug label.
5544    ///
5545    /// Equivalent to the `pub(crate) fn create_shader_module` overload but
5546    /// attaches a `label` to the module so it shows up under that name in
5547    /// browser devtools (e.g. Chrome's `chrome://gpu-internals` and the
5548    /// WebGPU Inspector panel). The label has no runtime effect; it is
5549    /// purely a developer-experience aid when many shader modules coexist.
5550    ///
5551    /// # Arguments
5552    ///
5553    /// - `&str` - WGSL source.
5554    /// - `&str` - Debug label shown in browser devtools.
5555    ///
5556    /// # Returns
5557    ///
5558    /// - `JsValue` - The `GpuShaderModule`, or `JsValue::UNDEFINED` if
5559    ///   the call fails.
5560    pub fn create_shader_module_with_label(&self, wgsl_source: &str, label: &str) -> JsValue {
5561        let descriptor: Object = Object::new();
5562        let _ = Reflect::set(
5563            &descriptor,
5564            &JsValue::from_str(WEBGPU_PROPERTY_CODE),
5565            &JsValue::from_str(wgsl_source),
5566        );
5567        let _ = Reflect::set(
5568            &descriptor,
5569            &JsValue::from_str(WEBGPU_PROPERTY_LABEL),
5570            &JsValue::from_str(label),
5571        );
5572        let desc_value: JsValue = descriptor.unchecked_into::<JsValue>();
5573        if let Ok(create_fn) = Reflect::get(
5574            self.get_device(),
5575            &JsValue::from_str(WEBGPU_METHOD_CREATE_SHADER_MODULE),
5576        ) && let Ok(create_callable) = create_fn.dyn_into::<Function>()
5577        {
5578            // The call returns a Promise that resolves to the shader module.
5579            // We do not await it; the caller is expected to drive the future
5580            // or pass the result into a pipeline creation call.
5581            return create_callable
5582                .call1(self.get_device(), &desc_value)
5583                .unwrap_or(JsValue::UNDEFINED);
5584        }
5585        JsValue::UNDEFINED
5586    }
5587
5588    // ─────────────────────────────────────────────────────────────────────
5589    //  Buffer readback via mapAsync + getMappedRange
5590    // ─────────────────────────────────────────────────────────────────────
5591
5592    /// Reads back the contents of a buffer via `mapAsync` + `getMappedRange` +
5593    /// `unmap`.
5594    ///
5595    /// This is an **`async fn`**, NOT a synchronous wrapper. It must be
5596    /// `await`-ed by the caller. Use it from inside another
5597    /// `wasm_bindgen_futures` future (e.g. a frame loop) — do not call
5598    /// it from synchronous code, since the awaiter must be driven by
5599    /// the executor. The buffer must have been created with `MAP_READ`
5600    /// usage, and the read must be preceded by a GPU submission that
5601    /// finished writing to the buffer (i.e. `queue.submit([encoder.finish()])`
5602    /// followed by `device.lost` / a fence).
5603    ///
5604    /// # Arguments
5605    ///
5606    /// - `&JsValue` - The `GpuBuffer` to read back.
5607    /// - `u64` - Byte offset into the buffer.
5608    /// - `u64` - Number of bytes to read.
5609    ///
5610    /// # Returns
5611    ///
5612    /// - `Option<Vec<u8>>` - The bytes, or `None` if the readback failed.
5613    pub async fn read_buffer(&self, buffer: &JsValue, offset: u64, size: u64) -> Option<Vec<u8>> {
5614        // Step 1: buffer.mapAsync(mode, offset, size)
5615        let map_fn: Function = Reflect::get(buffer, &JsValue::from_str(WEBGPU_METHOD_MAP_ASYNC))
5616            .ok()
5617            .and_then(|v| v.dyn_into::<Function>().ok())?;
5618        let map_promise: Promise = map_fn
5619            .call3(
5620                buffer,
5621                // `mapAsync` takes a `GPUMapMode` bitmask; the spec
5622                // allows OR'ing `READ` and `WRITE` together, so we
5623                // use the `map_mode_for` helper that pins the
5624                // `WEBGPU_MAP_MODE_WRITE` constant on the live code
5625                // path. This buffer is read-only for the host, so
5626                // we pass `read = true, write = false`.
5627                &JsValue::from_f64(map_mode_for(/* read = */ true, /* write = */ false) as f64),
5628                &JsValue::from_f64(offset as f64),
5629                &JsValue::from_f64(size as f64),
5630            )
5631            .ok()?
5632            .unchecked_into();
5633        // Step 2: await the mapAsync promise
5634        let _map_result: JsValue = JsFuture::from(map_promise).await.ok()?;
5635        // Step 3: buffer.getMappedRange(offset, size)
5636        let get_range_fn: Function =
5637            Reflect::get(buffer, &JsValue::from_str(WEBGPU_METHOD_GET_MAPPED_RANGE))
5638                .ok()
5639                .and_then(|v| v.dyn_into::<Function>().ok())?;
5640        let array_buffer: ArrayBuffer = get_range_fn
5641            .call2(
5642                buffer,
5643                &JsValue::from_f64(offset as f64),
5644                &JsValue::from_f64(size as f64),
5645            )
5646            .ok()?
5647            .unchecked_into();
5648        // Step 4: copy out before unmap invalidates the memory
5649        let u8_view: Uint8Array = Uint8Array::new(&array_buffer);
5650        let mut out: Vec<u8> = vec![0u8; u8_view.length() as usize];
5651        u8_view.copy_to(&mut out);
5652        // Step 5: unmap
5653        if let Ok(unmap_fn) = Reflect::get(buffer, &JsValue::from_str(WEBGPU_METHOD_UNMAP))
5654            && let Ok(unmap_callable) = unmap_fn.dyn_into::<Function>()
5655        {
5656            let _: Result<JsValue, JsValue> = unmap_callable.call0(buffer);
5657        }
5658        Some(out)
5659    }
5660}
5661
5662/// Implements helper methods on `WebGpuInitError`.
5663///
5664/// These methods provide ergonomic access to the diagnostic code and the
5665/// underlying JS error value, which are useful when surfacing the failure
5666/// to the user (e.g. via `Console::error` from the example crate).
5667impl WebGpuInitError {
5668    /// Returns a short, machine-readable identifier for this error variant.
5669    ///
5670    /// Suitable for use as a stable error code in logs or telemetry.
5671    /// The codes are stable across releases.
5672    ///
5673    /// # Returns
5674    ///
5675    /// - `&'static str` - The error code (e.g. `"WEBGPU_NAVIGATOR_GPU_MISSING"`).
5676    pub fn code(&self) -> &'static str {
5677        match self {
5678            Self::NavigatorLookup(_) => "WEBGPU_NAVIGATOR_LOOKUP",
5679            Self::NavigatorGpuMissing => "WEBGPU_NAVIGATOR_GPU_MISSING",
5680            Self::RequestAdapterLookup(_) => "WEBGPU_REQUEST_ADAPTER_LOOKUP",
5681            Self::RequestAdapterCall(_) => "WEBGPU_REQUEST_ADAPTER_CALL",
5682            Self::AdapterPromise(_) => "WEBGPU_ADAPTER_PROMISE",
5683            Self::AdapterUnavailable => "WEBGPU_ADAPTER_UNAVAILABLE",
5684            Self::RequestDeviceLookup(_) => "WEBGPU_REQUEST_DEVICE_LOOKUP",
5685            Self::RequestDeviceCall(_) => "WEBGPU_REQUEST_DEVICE_CALL",
5686            Self::DevicePromise(_) => "WEBGPU_DEVICE_PROMISE",
5687            Self::DeviceUnavailable => "WEBGPU_DEVICE_UNAVAILABLE",
5688            Self::CanvasNotFound(_) => "WEBGPU_CANVAS_NOT_FOUND",
5689            Self::CanvasQuery(_) => "WEBGPU_CANVAS_QUERY",
5690            Self::CanvasContextUnavailable => "WEBGPU_CANVAS_CONTEXT_UNAVAILABLE",
5691            Self::PreferredFormatLookup(_) => "WEBGPU_PREFERRED_FORMAT_LOOKUP",
5692            Self::PreferredFormatCall(_) => "WEBGPU_PREFERRED_FORMAT_CALL",
5693            Self::PreferredFormatType(_) => "WEBGPU_PREFERRED_FORMAT_TYPE",
5694            Self::ConfigureLookup(_) => "WEBGPU_CONFIGURE_LOOKUP",
5695            Self::QueueLookup(_) => "WEBGPU_QUEUE_LOOKUP",
5696        }
5697    }
5698
5699    /// Returns the underlying JS error value if this variant carries one.
5700    ///
5701    /// Variants that do not capture a JS value (e.g. `NavigatorGpuMissing`,
5702    /// `AdapterUnavailable`, `CanvasNotFound`, `CanvasContextUnavailable`)
5703    /// return `None`.
5704    ///
5705    /// # Returns
5706    ///
5707    /// - `Option<&JsValue>` - The captured JS error, if any.
5708    pub fn js_error(&self) -> Option<&JsValue> {
5709        match self {
5710            Self::NavigatorLookup(err)
5711            | Self::RequestAdapterLookup(err)
5712            | Self::RequestAdapterCall(err)
5713            | Self::AdapterPromise(err)
5714            | Self::RequestDeviceLookup(err)
5715            | Self::RequestDeviceCall(err)
5716            | Self::DevicePromise(err)
5717            | Self::CanvasQuery(err)
5718            | Self::PreferredFormatLookup(err)
5719            | Self::PreferredFormatCall(err)
5720            | Self::PreferredFormatType(err)
5721            | Self::ConfigureLookup(err)
5722            | Self::QueueLookup(err) => Some(err),
5723            Self::NavigatorGpuMissing
5724            | Self::AdapterUnavailable
5725            | Self::DeviceUnavailable
5726            | Self::CanvasContextUnavailable
5727            | Self::CanvasNotFound(_) => None,
5728        }
5729    }
5730}
5731
5732/// Implements `Display` for `WebGpuInitError`.
5733///
5734/// The formatted message is intended for end-user diagnostic output
5735/// (typically forwarded to `Console::error` by the calling application)
5736/// and includes the variant code plus a human-readable description. When
5737/// the variant carries a JS error, its `Debug` form is appended.
5738impl Display for WebGpuInitError {
5739    /// Formats the [`WebGpuInitError`] via the supplied formatter.
5740    ///
5741    /// # Arguments
5742    ///
5743    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
5744    ///
5745    /// # Returns
5746    ///
5747    /// - `FmtResult` - Result of the formatting operation.
5748    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
5749        match self {
5750            Self::NavigatorLookup(err) => write!(
5751                formatter,
5752                "[{}] Reflect::get(navigator, webgpu) failed: {}",
5753                self.code(),
5754                js_error_to_string(err),
5755            ),
5756            Self::NavigatorGpuMissing => write!(
5757                formatter,
5758                "[{}] navigator.gpu is missing - browser does not expose WebGPU on this origin",
5759                self.code(),
5760            ),
5761            Self::RequestAdapterLookup(err) => write!(
5762                formatter,
5763                "[{}] Reflect::get(gpu, requestAdapter) failed: {}",
5764                self.code(),
5765                js_error_to_string(err),
5766            ),
5767            Self::RequestAdapterCall(err) => write!(
5768                formatter,
5769                "[{}] gpu.requestAdapter() threw: {}",
5770                self.code(),
5771                js_error_to_string(err),
5772            ),
5773            Self::AdapterPromise(err) => write!(
5774                formatter,
5775                "[{}] adapter promise rejected or timed out: {}",
5776                self.code(),
5777                js_error_to_string(err),
5778            ),
5779            Self::AdapterUnavailable => write!(
5780                formatter,
5781                "[{}] requestAdapter returned null - no compatible GPU adapter for the requested powerPreference",
5782                self.code(),
5783            ),
5784            Self::RequestDeviceLookup(err) => write!(
5785                formatter,
5786                "[{}] Reflect::get(adapter, requestDevice) failed: {}",
5787                self.code(),
5788                js_error_to_string(err),
5789            ),
5790            Self::RequestDeviceCall(err) => write!(
5791                formatter,
5792                "[{}] adapter.requestDevice() threw: {}",
5793                self.code(),
5794                js_error_to_string(err),
5795            ),
5796            Self::DevicePromise(err) => write!(
5797                formatter,
5798                "[{}] device promise rejected or timed out: {}",
5799                self.code(),
5800                js_error_to_string(err),
5801            ),
5802            Self::DeviceUnavailable => write!(
5803                formatter,
5804                "[{}] requestDevice returned null - adapter could not allocate a device (possibly device-lost)",
5805                self.code(),
5806            ),
5807            Self::CanvasNotFound(selector) => write!(
5808                formatter,
5809                "[{}] canvas element {:?} not found in DOM",
5810                self.code(),
5811                selector,
5812            ),
5813            Self::CanvasQuery(err) => write!(
5814                formatter,
5815                "[{}] querySelector threw: {}",
5816                self.code(),
5817                js_error_to_string(err),
5818            ),
5819            Self::CanvasContextUnavailable => write!(
5820                formatter,
5821                "[{}] canvas.get_context('webgpu') returned null - the canvas may already be using another context type or WebGPU is disabled",
5822                self.code(),
5823            ),
5824            Self::PreferredFormatLookup(err) => write!(
5825                formatter,
5826                "[{}] Reflect::get(gpu, getPreferredCanvasFormat) failed: {}",
5827                self.code(),
5828                js_error_to_string(err),
5829            ),
5830            Self::PreferredFormatCall(err) => write!(
5831                formatter,
5832                "[{}] gpu.getPreferredCanvasFormat() threw: {}",
5833                self.code(),
5834                js_error_to_string(err),
5835            ),
5836            Self::PreferredFormatType(value) => write!(
5837                formatter,
5838                "[{}] getPreferredCanvasFormat returned non-string: {}",
5839                self.code(),
5840                js_error_to_string(value),
5841            ),
5842            Self::ConfigureLookup(err) => write!(
5843                formatter,
5844                "[{}] Reflect::get(context, configure) failed: {}",
5845                self.code(),
5846                js_error_to_string(err),
5847            ),
5848            Self::QueueLookup(err) => write!(
5849                formatter,
5850                "[{}] Reflect::get(device, queue) failed: {}",
5851                self.code(),
5852                js_error_to_string(err),
5853            ),
5854        }
5855    }
5856}
5857
5858/// Implements the standard `std::error::Error` trait for `WebGpuInitError`.
5859///
5860/// The `source()` method delegates to the underlying JS error's `toString()`
5861/// representation when present, otherwise returns `None`. The engine never
5862/// logs or prints anything; this impl exists solely so the error composes
5863/// with `Result`-based APIs and `?` operator chains.
5864impl Error for WebGpuInitError {}
5865
5866/// Implements `WebGlRenderer` context acquisition, shader program management,
5867/// and per-frame drawing.
5868///
5869/// All methods are synchronous: WebGL has no Promise-based initialization.
5870/// The renderer never logs; initialization failures are returned as
5871/// `WebGlInitError` and shader failures as `WebGlProgramError` so the caller
5872/// can surface them (typically via `Console::error` on the example side).
5873impl WebGlRenderer {
5874    /// Probes whether the browser can create a WebGL 2 context.
5875    ///
5876    /// Creates a throwaway off-DOM canvas and requests a `webgl2` context.
5877    /// The probe is cheap (no shaders are compiled) and has no side effects
5878    /// on the page.
5879    ///
5880    /// # Returns
5881    ///
5882    /// - `bool` - `true` if a `webgl2` context could be acquired.
5883    pub fn is_available() -> bool {
5884        let Some(window_value) = window() else {
5885            return false;
5886        };
5887        let Some(document_value) = window_value.document() else {
5888            return false;
5889        };
5890        let element: Element = match document_value.create_element("canvas") {
5891            Ok(element) => element,
5892            Err(_) => return false,
5893        };
5894        let canvas: HtmlCanvasElement = element.unchecked_into();
5895        canvas.get_context("webgl2").ok().flatten().is_some()
5896    }
5897
5898    /// Initializes a WebGL 2 renderer from a render configuration.
5899    ///
5900    /// Resolves the canvas element from `config.canvas_selector`, scales the
5901    /// backing store by the device pixel ratio, acquires the `webgl2`
5902    /// context, and sets the initial viewport.
5903    ///
5904    /// # Arguments
5905    ///
5906    /// - `&RenderConfig` - The rendering configuration.
5907    ///
5908    /// # Returns
5909    ///
5910    /// - `Result<WebGlRenderer, WebGlInitError>` - The initialized renderer,
5911    ///   or a typed error describing the specific failure.
5912    pub fn init(config: &RenderConfig) -> Result<WebGlRenderer, WebGlInitError> {
5913        let Some(window_value) = window() else {
5914            return Err(WebGlInitError::CanvasNotFound(
5915                config.canvas_selector.clone(),
5916            ));
5917        };
5918        let Some(document_value) = window_value.document() else {
5919            return Err(WebGlInitError::CanvasNotFound(
5920                config.canvas_selector.clone(),
5921            ));
5922        };
5923        let element: Element = document_value
5924            .query_selector(config.canvas_selector.as_ref())
5925            .map_err(WebGlInitError::CanvasQuery)?
5926            .ok_or_else(|| WebGlInitError::CanvasNotFound(config.canvas_selector.clone()))?;
5927        let canvas: HtmlCanvasElement = element.unchecked_into();
5928        let dpr: f64 = CanvasRenderer::detect_dpr();
5929        let physical_width: u32 = (config.width * dpr).round() as u32;
5930        let physical_height: u32 = (config.height * dpr).round() as u32;
5931        canvas.set_width(physical_width);
5932        canvas.set_height(physical_height);
5933        let context_object: Object = canvas
5934            .get_context("webgl2")
5935            .map_err(WebGlInitError::ContextLookup)?
5936            .ok_or(WebGlInitError::ContextUnavailable)?;
5937        let context: WebGl2RenderingContext = context_object
5938            .dyn_into()
5939            .map_err(|_| WebGlInitError::ContextCast)?;
5940        context.viewport(0, 0, physical_width as i32, physical_height as i32);
5941        Ok(WebGlRenderer {
5942            context,
5943            canvas,
5944            width: physical_width,
5945            height: physical_height,
5946        })
5947    }
5948
5949    /// Compiles and links a shader program from GLSL ES 3.00 sources.
5950    ///
5951    /// Both shaders are compiled, attached, and linked; on success the
5952    /// intermediate shader objects are deleted (the program keeps the
5953    /// compiled code). On failure the browser info log is returned so the
5954    /// caller can surface the exact GLSL diagnostic.
5955    ///
5956    /// # Arguments
5957    ///
5958    /// - `&str` - The vertex shader source (`#version 300 es`).
5959    /// - `&str` - The fragment shader source (`#version 300 es`).
5960    ///
5961    /// # Returns
5962    ///
5963    /// - `Result<WebGlProgram, WebGlProgramError>` - The linked program, or
5964    ///   the compile/link info log.
5965    pub fn create_program(
5966        &self,
5967        vertex_source: &str,
5968        fragment_source: &str,
5969    ) -> Result<WebGlProgram, WebGlProgramError> {
5970        let vertex_shader: WebGlShader =
5971            self.compile_shader(WebGl2RenderingContext::VERTEX_SHADER, vertex_source)?;
5972        let fragment_shader: WebGlShader =
5973            self.compile_shader(WebGl2RenderingContext::FRAGMENT_SHADER, fragment_source)?;
5974        let program: WebGlProgram = self.context.create_program().ok_or_else(|| {
5975            WebGlProgramError::ProgramLink("createProgram returned null".to_string())
5976        })?;
5977        self.context.attach_shader(&program, &vertex_shader);
5978        self.context.attach_shader(&program, &fragment_shader);
5979        self.context.link_program(&program);
5980        let linked: bool = self
5981            .context
5982            .get_program_parameter(&program, WebGl2RenderingContext::LINK_STATUS)
5983            .as_bool()
5984            .unwrap_or_default();
5985        if !linked {
5986            let log: String = self
5987                .context
5988                .get_program_info_log(&program)
5989                .unwrap_or_default();
5990            self.context.delete_program(Some(&program));
5991            self.context.delete_shader(Some(&vertex_shader));
5992            self.context.delete_shader(Some(&fragment_shader));
5993            return Err(WebGlProgramError::ProgramLink(log));
5994        }
5995        self.context.delete_shader(Some(&vertex_shader));
5996        self.context.delete_shader(Some(&fragment_shader));
5997        Ok(program)
5998    }
5999
6000    /// Compiles a single shader, returning the info log on failure.
6001    ///
6002    /// # Arguments
6003    ///
6004    /// - `u32` - The shader kind (`VERTEX_SHADER` or `FRAGMENT_SHADER`).
6005    /// - `&str` - The GLSL source.
6006    ///
6007    /// # Returns
6008    ///
6009    /// - `Result<WebGlShader, WebGlProgramError>` - The compiled shader, or
6010    ///   the compile info log.
6011    fn compile_shader(&self, kind: u32, source: &str) -> Result<WebGlShader, WebGlProgramError> {
6012        let shader: WebGlShader = self.context.create_shader(kind).ok_or_else(|| {
6013            WebGlProgramError::ShaderCompile("createShader returned null".to_string())
6014        })?;
6015        self.context.shader_source(&shader, source);
6016        self.context.compile_shader(&shader);
6017        let compiled: bool = self
6018            .context
6019            .get_shader_parameter(&shader, WebGl2RenderingContext::COMPILE_STATUS)
6020            .as_bool()
6021            .unwrap_or_default();
6022        if !compiled {
6023            let log: String = self
6024                .context
6025                .get_shader_info_log(&shader)
6026                .unwrap_or_default();
6027            self.context.delete_shader(Some(&shader));
6028            return Err(WebGlProgramError::ShaderCompile(log));
6029        }
6030        Ok(shader)
6031    }
6032
6033    /// Resolves the location of a uniform on the given program.
6034    ///
6035    /// Uniform locations are stable for the lifetime of a linked program,
6036    /// so callers rendering in a per-frame loop should resolve each uniform
6037    /// once after [`WebGlRenderer::create_program`] and cache the result,
6038    /// then pass it to [`WebGlRenderer::set_uniform_2f`] /
6039    /// [`WebGlRenderer::set_uniform_4fv`]. Resolving per frame is supported
6040    /// but wasteful: every lookup crosses into the browser's GL frontend.
6041    /// A uniform that the GLSL compiler optimized out resolves to `None`,
6042    /// which the setters silently ignore, matching raw WebGL semantics.
6043    ///
6044    /// # Arguments
6045    ///
6046    /// - `&WebGlProgram` - The program owning the uniform.
6047    /// - `&str` - The uniform name (for array uniforms, with an explicit
6048    ///   `[0]` index, per the WebGL `getUniformLocation` spec).
6049    ///
6050    /// # Returns
6051    ///
6052    /// - `Option<WebGlUniformLocation>` - The uniform location, or `None`
6053    ///   when the uniform does not exist in the program.
6054    pub fn get_uniform_location(
6055        &self,
6056        program: &WebGlProgram,
6057        name: &str,
6058    ) -> Option<WebGlUniformLocation> {
6059        self.context.get_uniform_location(program, name)
6060    }
6061
6062    /// Sets a `vec2` uniform on the given program via its cached location.
6063    ///
6064    /// The program is bound with `useProgram` before the upload so the
6065    /// uniform call always targets the program the location was resolved
6066    /// from, regardless of which program the context currently has bound
6067    /// (uploading against a different bound program is an
6068    /// `INVALID_OPERATION` in WebGL). A `None` location (uniform optimized
6069    /// out by the GLSL compiler) is silently ignored, matching raw WebGL
6070    /// semantics.
6071    ///
6072    /// # Arguments
6073    ///
6074    /// - `&WebGlProgram` - The program owning the uniform.
6075    /// - `Option<&WebGlUniformLocation>` - The cached location from
6076    ///   [`WebGlRenderer::get_uniform_location`].
6077    /// - `f32` - The x component.
6078    /// - `f32` - The y component.
6079    pub fn set_uniform_2f(
6080        &self,
6081        program: &WebGlProgram,
6082        location: Option<&WebGlUniformLocation>,
6083        x: f32,
6084        y: f32,
6085    ) {
6086        self.context.use_program(Some(program));
6087        self.context.uniform2f(location, x, y);
6088    }
6089
6090    /// Uploads a flat float slice into a `vec4` or `vec4[]` uniform via its
6091    /// cached location.
6092    ///
6093    /// Used by the game demos to push per-frame instance data (ball positions
6094    /// and colors, cube transforms) into shaders that index the array with
6095    /// `gl_VertexID`. `data.len()` must be a multiple of 4. The upload writes
6096    /// only `data.len() / 4` elements; untouched elements keep their previous
6097    /// values. Like [`WebGlRenderer::set_uniform_2f`], the program is bound
6098    /// before the upload so the call can never target the wrong program.
6099    ///
6100    /// # Arguments
6101    ///
6102    /// - `&WebGlProgram` - The program owning the uniform.
6103    /// - `Option<&WebGlUniformLocation>` - The cached location from
6104    ///   [`WebGlRenderer::get_uniform_location`].
6105    /// - `&[f32]` - The packed float data.
6106    pub fn set_uniform_4fv(
6107        &self,
6108        program: &WebGlProgram,
6109        location: Option<&WebGlUniformLocation>,
6110        data: &[f32],
6111    ) {
6112        self.context.use_program(Some(program));
6113        self.context.uniform4fv_with_f32_array(location, data);
6114    }
6115
6116    /// Renders a complete frame: clears the canvas and draws a triangle-list
6117    /// primitive whose vertices are generated inside the vertex shader.
6118    ///
6119    /// Mirrors [`WebGpuRenderer::render_frame`]: the vertex shader uses
6120    /// `gl_VertexID` so no vertex buffers are involved. The given program
6121    /// is bound before drawing; set its uniforms first via
6122    /// [`WebGlRenderer::set_uniform_2f`] when the shader reads per-frame
6123    /// interaction data.
6124    ///
6125    /// # Arguments
6126    ///
6127    /// - `&WebGlProgram` - The program to draw with.
6128    /// - `(f64, f64, f64, f64)` - The clear color as (r, g, b, a) in 0.0–1.0 range.
6129    /// - `i32` - The number of vertices to draw.
6130    pub fn render_frame(
6131        &self,
6132        program: &WebGlProgram,
6133        clear_color: (f64, f64, f64, f64),
6134        vertex_count: i32,
6135    ) {
6136        let (r, g, b, a) = clear_color;
6137        self.context
6138            .viewport(0, 0, self.width as i32, self.height as i32);
6139        self.context
6140            .clear_color(r as f32, g as f32, b as f32, a as f32);
6141        self.context.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
6142        self.context.use_program(Some(program));
6143        self.context
6144            .draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, vertex_count);
6145    }
6146
6147    /// Resizes the canvas backing store and updates the GL viewport.
6148    ///
6149    /// Call this when the CSS layout size changes (window resize, DPR
6150    /// change) so the drawing buffer matches the visible region.
6151    ///
6152    /// # Arguments
6153    ///
6154    /// - `u32` - The new physical pixel width (already multiplied by DPR).
6155    /// - `u32` - The new physical pixel height.
6156    pub fn resize(&mut self, physical_width: u32, physical_height: u32) {
6157        self.canvas.set_width(physical_width);
6158        self.canvas.set_height(physical_height);
6159        self.width = physical_width;
6160        self.height = physical_height;
6161        self.context
6162            .viewport(0, 0, physical_width as i32, physical_height as i32);
6163    }
6164}
6165
6166/// Implements `WebGlInitError` diagnostic helpers.
6167impl WebGlInitError {
6168    /// Returns a short, machine-readable identifier for this error variant.
6169    ///
6170    /// Suitable for use as a stable error code in logs or telemetry.
6171    ///
6172    /// # Returns
6173    ///
6174    /// - `&'static str` - The error code (e.g. `\"WEBGL_CONTEXT_UNAVAILABLE\"`).
6175    pub fn code(&self) -> &'static str {
6176        match self {
6177            Self::CanvasNotFound(_) => "WEBGL_CANVAS_NOT_FOUND",
6178            Self::CanvasQuery(_) => "WEBGL_CANVAS_QUERY",
6179            Self::ContextUnavailable => "WEBGL_CONTEXT_UNAVAILABLE",
6180            Self::ContextLookup(_) => "WEBGL_CONTEXT_LOOKUP",
6181            Self::ContextCast => "WEBGL_CONTEXT_CAST",
6182        }
6183    }
6184
6185    /// Returns the underlying JS error value if this variant carries one.
6186    ///
6187    /// # Returns
6188    ///
6189    /// - `Option<&JsValue>` - The captured JS error, if any.
6190    pub fn js_error(&self) -> Option<&JsValue> {
6191        match self {
6192            Self::CanvasQuery(err) | Self::ContextLookup(err) => Some(err),
6193            Self::CanvasNotFound(_) | Self::ContextUnavailable | Self::ContextCast => None,
6194        }
6195    }
6196}
6197
6198/// Implements `Display` for `WebGlInitError`.
6199///
6200/// The formatted message includes the variant code plus a human-readable
6201/// description; variants carrying a JS error append its rendered form.
6202impl Display for WebGlInitError {
6203    /// Formats the [`WebGlInitError`] via the supplied formatter.
6204    ///
6205    /// # Arguments
6206    ///
6207    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
6208    ///
6209    /// # Returns
6210    ///
6211    /// - `FmtResult` - Result of the formatting operation.
6212    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
6213        match self {
6214            Self::CanvasNotFound(selector) => write!(
6215                formatter,
6216                "[{}] canvas element {:?} not found in DOM",
6217                self.code(),
6218                selector,
6219            ),
6220            Self::CanvasQuery(err) => write!(
6221                formatter,
6222                "[{}] querySelector threw: {}",
6223                self.code(),
6224                js_error_to_string(err),
6225            ),
6226            Self::ContextUnavailable => write!(
6227                formatter,
6228                "[{}] canvas.get_context('webgl2') returned null - the browser does not support WebGL 2 or the canvas already uses another context type",
6229                self.code(),
6230            ),
6231            Self::ContextLookup(err) => write!(
6232                formatter,
6233                "[{}] canvas.get_context('webgl2') threw: {}",
6234                self.code(),
6235                js_error_to_string(err),
6236            ),
6237            Self::ContextCast => write!(
6238                formatter,
6239                "[{}] get_context('webgl2') result could not be cast to WebGl2RenderingContext",
6240                self.code(),
6241            ),
6242        }
6243    }
6244}
6245
6246/// Implements `Display` for `WebGlProgramError`.
6247///
6248/// The formatted message includes the browser-provided info log so GLSL
6249/// diagnostics are visible verbatim in the console.
6250impl Display for WebGlProgramError {
6251    /// Formats the [`WebGlProgramError`] via the supplied formatter.
6252    ///
6253    /// # Arguments
6254    ///
6255    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
6256    ///
6257    /// # Returns
6258    ///
6259    /// - `FmtResult` - Result of the formatting operation.
6260    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
6261        match self {
6262            Self::ShaderCompile(log) => write!(formatter, "shader compilation failed: {log}"),
6263            Self::ProgramLink(log) => write!(formatter, "program link failed: {log}"),
6264        }
6265    }
6266}
6267
6268/// Implements the standard `Error` trait for `WebGlProgramError`.
6269impl Error for WebGlProgramError {}
6270
6271/// Default-construction helper for `Texture2DDescriptor`.
6272impl Texture2DDescriptor {
6273    /// Returns a descriptor with the most common defaults applied.
6274    ///
6275    /// This is the same as calling the generated `new` constructor and
6276    /// then explicitly setting the defaults; we provide it so callers
6277    /// can do `Texture2DDescriptor::default_for(w, h, format)` instead of
6278    /// having to remember which fields to set.
6279    ///
6280    /// # Arguments
6281    ///
6282    /// - `width` - The texture width in pixels.
6283    /// - `height` - The texture height in pixels.
6284    /// - `format` - The WGSL texture format.
6285    ///
6286    /// # Returns
6287    ///
6288    /// - A new descriptor with `mip_level_count = 1`, `sample_count = 1`,
6289    ///   and usage `"TEXTURE_BINDING | COPY_DST | COPY_SRC"`.
6290    pub fn default_for(width: u32, height: u32, format: &'static str) -> Self {
6291        Self {
6292            width,
6293            height,
6294            format,
6295            mip_level_count: 1,
6296            sample_count: 1,
6297            usage: "TEXTURE_BINDING | COPY_DST | COPY_SRC",
6298        }
6299    }
6300}
6301
6302/// Default-construction helper for `GpuSamplerDescriptor`.
6303impl GpuSamplerDescriptor {
6304    /// Returns a descriptor with the most common defaults applied:
6305    /// nearest filtering and clamp-to-edge addressing on all axes.
6306    pub fn default_sampler() -> Self {
6307        Self {
6308            mag_filter: WEBGPU_FILTER_MODE_NEAREST,
6309            min_filter: WEBGPU_FILTER_MODE_NEAREST,
6310            mipmap_filter: WEBGPU_FILTER_MODE_NEAREST,
6311            address_mode_u: WEBGPU_ADDRESS_MODE_CLAMP_TO_EDGE,
6312            address_mode_v: WEBGPU_ADDRESS_MODE_CLAMP_TO_EDGE,
6313            address_mode_w: WEBGPU_ADDRESS_MODE_CLAMP_TO_EDGE,
6314            compare: false,
6315        }
6316    }
6317}
6318
6319/// Resolves optional `load_op` / `store_op` to the WebGPU spec defaults for
6320/// `RenderPassColorAttachment`.
6321impl RenderPassColorAttachment {
6322    /// Returns the load op that the renderer should use.
6323    ///
6324    /// # Returns
6325    ///
6326    /// - `'static str` - A `'static str` value.
6327    pub(crate) fn effective_load_op(&self) -> &'static str {
6328        match (self.load_op, self.clear_value) {
6329            (Some(op), _) => op,
6330            (None, Some(_)) => WEBGPU_LOAD_OP_CLEAR,
6331            (None, None) => WEBGPU_LOAD_OP_LOAD,
6332        }
6333    }
6334
6335    /// Returns the store op that the renderer should use.
6336    ///
6337    /// Defaults to [`WEBGPU_STORE_OP_STORE`] so the color/depth
6338    /// attachment contents survive the pass. Callers that know the
6339    /// attachment is transient (no resolve, no follow-up sample, no
6340    /// `copyTextureToTexture`) can use [`WEBGPU_STORE_OP_DISCARD`]
6341    /// to avoid the bandwidth of a write-back. The helper
6342    /// [`default_color_store_op`] centralises that "transient?"
6343    /// decision so the [`WEBGPU_STORE_OP_DISCARD`] constant stays
6344    /// reachable from inside the engine.
6345    ///
6346    /// # Returns
6347    ///
6348    /// - `'static str` - A `'static str` value.
6349    pub(crate) fn effective_store_op(&self) -> &'static str {
6350        self.store_op.unwrap_or_else(|| {
6351            default_color_store_op(/* transient = */ false)
6352        })
6353    }
6354}
6355
6356/// Resolves optional `depth_load_op` / `depth_store_op` to the WebGPU spec
6357/// defaults for `RenderPassDepthStencilAttachment`.
6358impl RenderPassDepthStencilAttachment {
6359    /// Returns the depth load op that the renderer should use.
6360    ///
6361    /// # Returns
6362    ///
6363    /// - `'static str` - A `'static str` value.
6364    pub(crate) fn effective_depth_load_op(&self) -> &'static str {
6365        match (self.depth_load_op, self.depth_clear_value) {
6366            (Some(op), _) => op,
6367            (None, Some(_)) => WEBGPU_LOAD_OP_CLEAR,
6368            (None, None) => WEBGPU_LOAD_OP_LOAD,
6369        }
6370    }
6371
6372    /// Returns the depth store op that the renderer should use.
6373    ///
6374    /// # Returns
6375    ///
6376    /// - `'static str` - A `'static str` value.
6377    pub(crate) fn effective_depth_store_op(&self) -> &'static str {
6378        self.depth_store_op.unwrap_or(WEBGPU_STORE_OP_STORE)
6379    }
6380}
6381
6382/// Constructors and view-default resolvers for `TextureViewDescriptor`.
6383impl TextureViewDescriptor {
6384    /// Returns a descriptor that selects the full texture as a 2D view.
6385    /// This is the cheapest view you can make; equivalent to calling
6386    /// `texture.createView()` with no argument.
6387    pub fn full() -> Self {
6388        Self {
6389            format: None,
6390            dimension: None,
6391            base_mip_level: 0,
6392            mip_level_count: 0,
6393            base_array_layer: 0,
6394            array_layer_count: 0,
6395            aspect: None,
6396        }
6397    }
6398
6399    /// The dimension string the renderer will send to `createView`.
6400    ///
6401    /// We default `None` to `"2d"` instead of omitting the key, because
6402    /// every other descriptor in the engine uses the explicit-string
6403    /// form, and a few browsers reject `dimension: undefined`.
6404    ///
6405    /// # Returns
6406    ///
6407    /// - `'static str` - A `'static str` value.
6408    pub(crate) fn effective_dimension(&self) -> &'static str {
6409        self.dimension.unwrap_or(WEBGPU_TEXTURE_VIEW_DIMENSION_2D)
6410    }
6411
6412    /// The aspect string the renderer will send to `createView`.
6413    ///
6414    /// Defaults to `"all"`, which is the spec's "expose every channel"
6415    /// option and the only correct choice for color textures.
6416    ///
6417    /// # Returns
6418    ///
6419    /// - `'static str` - A `'static str` value.
6420    pub(crate) fn effective_aspect(&self) -> &'static str {
6421        self.aspect.unwrap_or(WEBGPU_TEXTURE_ASPECT_ALL)
6422    }
6423
6424    /// Returns a descriptor that selects a single mip level of the texture.
6425    /// Useful when you want to read back a specific mip (e.g. the half-res
6426    /// blur output of a downsampling pass) without exposing the rest.
6427    ///
6428    /// # Arguments
6429    ///
6430    /// - `u32` - A 32-bit unsigned integer (`u32`).
6431    pub fn mip(level: u32) -> Self {
6432        Self {
6433            format: None,
6434            dimension: None,
6435            base_mip_level: level,
6436            mip_level_count: 1,
6437            base_array_layer: 0,
6438            array_layer_count: 0,
6439            aspect: None,
6440        }
6441    }
6442
6443    /// Returns a descriptor that selects the depth-only aspect of a
6444    /// depth-stencil texture. Required when sampling depth in a shader
6445    /// (`textureSample(t, s, uv)` where `t` is a depth texture).
6446    pub fn depth_only() -> Self {
6447        Self {
6448            format: None,
6449            dimension: None,
6450            base_mip_level: 0,
6451            mip_level_count: 0,
6452            base_array_layer: 0,
6453            array_layer_count: 0,
6454            aspect: Some(WEBGPU_TEXTURE_ASPECT_DEPTH_ONLY),
6455        }
6456    }
6457}
6458
6459/// 2D-upload convenience constructor for `TextureWriteDescriptor`.
6460impl TextureWriteDescriptor {
6461    /// Convenience constructor for the common 2D upload case.
6462    ///
6463    /// - `data`: packed pixel bytes (format-dependent).
6464    /// - `bytes_per_row`: row stride of `data`, must be a multiple of 256.
6465    /// - `texture`: the destination `GpuTexture` handle.
6466    ///
6467    /// # Arguments
6468    ///
6469    /// - `Vec<u8>` - A `Vec<u8>` parameter.
6470    /// - `u32` - A 32-bit unsigned integer (`u32`).
6471    /// - `JsValue` - A `JsValue` parameter.
6472    pub fn for_2d(data: Vec<u8>, bytes_per_row: u32, texture: JsValue) -> Self {
6473        Self {
6474            data,
6475            bytes_per_row,
6476            rows_per_image: 0,
6477            mip_level: 0,
6478            texture,
6479            origin: None,
6480            flip_y: false,
6481        }
6482    }
6483}
6484
6485// =================================================================
6486// Impl blocks for types defined in `enum.rs`
6487// =================================================================
6488//
6489// Per the engine's module layout rules, every `impl Foo` block lives in
6490// `impl.rs`; the type definitions (struct / enum) live in `struct.rs`
6491// / `enum.rs` / `trait.rs` respectively. The two impl blocks below
6492// were relocated from `enum.rs` to satisfy that rule without changing
6493// the public API surface — both `VertexStepMode::as_str` and
6494// `BindGroupEntry::binding` are still callable exactly the same way
6495// from the rest of the engine and from the public `euv` crate.
6496
6497/// Inherent implementation of [`VertexStepMode`].
6498impl VertexStepMode {
6499    /// Returns the WGSL / WebGPU string representation.
6500    ///
6501    /// # Returns
6502    ///
6503    /// - `'static str` - A static `&str` representation.
6504    pub fn as_str(&self) -> &'static str {
6505        match self {
6506            Self::Vertex => "vertex",
6507            Self::Instance => "instance",
6508        }
6509    }
6510}
6511
6512/// Inherent implementation of [`BindGroupEntry`].
6513impl BindGroupEntry {
6514    /// Returns the `@binding(N)` slot this entry occupies. The renderer
6515    /// uses this when assembling the bind-group descriptor so the
6516    /// caller does not need to know the JS-side `binding` field name.
6517    ///
6518    /// # Returns
6519    ///
6520    /// - `u32` - The bind-group slot index.
6521    pub fn binding(&self) -> u32 {
6522        match self {
6523            Self::Buffer { binding, .. }
6524            | Self::Texture { binding, .. }
6525            | Self::StorageTexture { binding, .. }
6526            | Self::Sampler { binding, .. } => *binding,
6527        }
6528    }
6529}
6530
6531// =================================================================
6532// Descriptor-surface usage anchors
6533// =================================================================
6534//
6535// `const.rs` documents the *complete* WebGPU descriptor surface —
6536// format strings, usage bitmask values, method/property names — but
6537// the engine's built-in helpers (`create_buffer`, `create_texture`,
6538// `create_render_pipeline`, …) only consume a subset on any given
6539// call site. To prevent the dead-code lint from flagging the
6540// remaining constants (each one is a real, valid WebGPU value — we
6541// just don't always need it in 2D-UI work), the helpers below give
6542// the unused constants a concrete role. They are exposed as
6543// `pub(crate)` because the rest of the engine can call them when
6544// building advanced descriptors (3D pipelines, compute passes,
6545// mipmapped render targets, async readback, …); the public
6546// `euv-engine` API surface stays exactly the same — the const
6547// values are documented and callable, not the helpers.
6548//
6549// If a future round of engine work genuinely removes a constant
6550// from the WebGPU spec, delete the corresponding constant and the
6551// matching arm in the helper below in the same commit.
6552
6553// ============================================================================
6554// `PendingErrorCell` — interior-mutable slot for the renderer's
6555// pending WebGPU error-scope value. Defined as a tuple struct in
6556// `struct.rs`; this block attaches its `impl` block + the hand-written
6557// `Sync` impl required for sharing through `Rc` on the WASM single-threaded
6558// runtime.
6559//
6560// See the doc comment on `struct.rs::PendingErrorCell` for the full design
6561// rationale (why `UnsafeCell` over `RefCell`, why a hand-rolled `Sync` is
6562// sound here, and what would have to change for multi-threaded targets).
6563// ============================================================================
6564
6565/// Inherent implementation of [`PendingErrorCell`].
6566impl PendingErrorCell {
6567    /// Construct a new, empty pending-error slot.
6568    ///
6569    /// The inner `UnsafeCell<Option<JsValue>>` starts as `None`; the
6570    /// WebGPU `pop_error_sync` microtask is the only thing that ever
6571    /// writes to it, and `take_last_error` is the only reader.
6572    pub fn new() -> Self {
6573        Self(UnsafeCell::new(None))
6574    }
6575
6576    /// Hand out a raw pointer to the inner cell for the
6577    /// `spawn_local` closure to write through.
6578    ///
6579    /// # Safety
6580    ///
6581    /// The returned pointer is only valid for the lifetime of `&self`,
6582    /// and only safe to write to on the WASM main thread. The caller
6583    /// must guarantee that no other code is reading the same
6584    /// `PendingErrorCell` concurrently — this is enforced by the
6585    /// single-threaded scheduler: the spawned future is drained
6586    /// before the next render tick's `take_last_error` runs.
6587    ///
6588    /// # Returns
6589    ///
6590    /// - `*mut Option<JsValue>` - Raw pointer to the inner storage.
6591    pub fn as_ptr(&self) -> *mut Option<JsValue> {
6592        self.0.get()
6593    }
6594}
6595
6596/// Default-construction for [`PendingErrorCell`].
6597impl Default for PendingErrorCell {
6598    /// Constructs a default [`PendingErrorCell`] value.
6599    fn default() -> Self {
6600        Self::new()
6601    }
6602}
6603
6604// SAFETY: see the doc comment on `struct.rs::PendingErrorCell`.
6605//
6606// `PendingErrorCell` wraps `UnsafeCell`, which is `!Sync` by design.
6607// We hand-implement `Sync` because:
6608//
6609// - The renderer is compiled for `wasm32` and runs on the WASM
6610//   single-threaded scheduler; there is no other thread to race
6611//   against.
6612// - The owning pointer is held inside an `Rc<PendingErrorCell>`, and
6613//   `Rc` is itself `!Send`/`!Sync`, so the value cannot escape the
6614//   current thread even if the type were `Sync`.
6615// - The `pop_error_sync` future and `take_last_error` never overlap
6616//   in wall-clock time: the future is a microtask that resolves
6617//   before the next render tick drains the slot.
6618//
6619// If `euv-engine` is ever built for a multi-threaded target
6620// (native, `wasm-bindgen-rayon`, `wasm32-atomics`), this `unsafe impl`
6621// becomes unsound and must be removed — at that point the renderer
6622// will need a real `Mutex` or `RwLock` around the slot.
6623unsafe impl Sync for PendingErrorCell {}