Skip to main content

euv_engine/renderer/
impl.rs

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