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