Skip to main content

euv_engine/renderer/
struct.rs

1use super::*;
2
3/// A 2D camera that defines the viewport into the game world.
4#[derive(Clone, Copy, Data, Debug, New, PartialEq, PartialOrd)]
5pub struct Camera2D {
6    /// The world-space position of the camera center.
7    #[get(type(copy))]
8    pub(crate) position: Vector2D,
9    /// The zoom factor (1.0 = no zoom, 2.0 = 2x magnification).
10    #[get(type(copy))]
11    pub(crate) zoom: f64,
12    /// The rotation angle in radians.
13    #[get(type(copy))]
14    pub(crate) rotation: f64,
15    /// The viewport width in screen pixels.
16    #[get(type(copy))]
17    pub(crate) viewport_width: f64,
18    /// The viewport height in screen pixels.
19    #[get(type(copy))]
20    pub(crate) viewport_height: f64,
21}
22
23/// A 3D camera that defines the viewport into a 3D world using perspective
24/// or orthographic projection.
25#[derive(Clone, Copy, Data, Debug, New, PartialEq, PartialOrd)]
26pub struct Camera3D {
27    /// The world-space position of the camera (eye).
28    #[get(type(copy))]
29    pub(crate) position: Vector3D,
30    /// The point the camera is looking at (target).
31    #[get(type(copy))]
32    pub(crate) target: Vector3D,
33    /// The up direction for the camera.
34    #[get(type(copy))]
35    #[new(skip)]
36    pub(crate) up: Vector3D,
37    /// The vertical field of view in radians.
38    #[get(type(copy))]
39    #[new(skip)]
40    pub(crate) fov: f64,
41    /// The near clipping plane distance.
42    #[get(type(copy))]
43    #[new(skip)]
44    pub(crate) near: f64,
45    /// The far clipping plane distance.
46    #[get(type(copy))]
47    #[new(skip)]
48    pub(crate) far: f64,
49    /// The viewport width in pixels.
50    #[get(type(copy))]
51    pub(crate) viewport_width: f64,
52    /// The viewport height in pixels.
53    #[get(type(copy))]
54    pub(crate) viewport_height: f64,
55}
56
57/// A wrapper around `CanvasRenderingContext2d` providing convenience
58/// drawing methods and camera management for the game engine.
59#[derive(Clone, Data, New)]
60pub struct CanvasRenderer {
61    /// The underlying canvas 2D rendering context.
62    pub(crate) context: CanvasRenderingContext2d,
63    /// The active camera controlling the viewport.
64    #[get(type(copy))]
65    pub(crate) camera: Camera2D,
66    /// The active rendering quality preset.
67    ///
68    /// Controls `imageSmoothingEnabled`, `imageSmoothingQuality`, and
69    /// `textRendering` on the underlying context. Defaults to `Medium`.
70    #[get(type(copy))]
71    pub(crate) quality: RenderQuality,
72}
73
74/// A linear gradient defined by two endpoints and a list of color stops.
75///
76/// Used to create smooth color transitions along a straight line
77/// for fill or stroke operations on the canvas.
78#[derive(Clone, Data, Debug, New, PartialEq)]
79pub struct LinearGradient {
80    /// The starting point of the gradient in world space.
81    #[get(type(copy))]
82    pub(crate) start: Vector2D,
83    /// The ending point of the gradient in world space.
84    #[get(type(copy))]
85    pub(crate) end: Vector2D,
86    /// The ordered list of color stops, each containing a position (0.0 to 1.0) and a CSS color string.
87    pub(crate) stops: Vec<(f64, String)>,
88}
89
90/// A radial gradient defined by inner and outer circles and a list of color stops.
91///
92/// Used to create smooth color transitions radiating outward from a center point
93/// for fill or stroke operations on the canvas.
94#[derive(Clone, Data, Debug, New, PartialEq)]
95pub struct RadialGradient {
96    /// The center of the inner circle of the gradient.
97    #[get(type(copy))]
98    pub(crate) inner_center: Vector2D,
99    /// The radius of the inner circle.
100    #[get(type(copy))]
101    pub(crate) inner_radius: f64,
102    /// The center of the outer circle of the gradient.
103    #[get(type(copy))]
104    pub(crate) outer_center: Vector2D,
105    /// The radius of the outer circle.
106    #[get(type(copy))]
107    pub(crate) outer_radius: f64,
108    /// The ordered list of color stops, each containing a position (0.0 to 1.0) and a CSS color string.
109    pub(crate) stops: Vec<(f64, String)>,
110}
111
112/// Shadow rendering configuration for drop shadow effects on canvas primitives.
113///
114/// When applied, all subsequent fill, stroke, and draw operations will cast
115/// a shadow with the specified color, blur radius, and offset.
116#[derive(Clone, Data, Debug, New, PartialEq, PartialOrd)]
117pub struct ShadowConfig {
118    /// The CSS color string of the shadow (e.g., `"rgba(0,0,0,0.5)"`).
119    #[get(type(clone))]
120    pub(crate) color: String,
121    /// The blur radius of the shadow in pixels.
122    #[get(type(copy))]
123    pub(crate) blur: f64,
124    /// The horizontal offset of the shadow in pixels.
125    #[get(type(copy))]
126    pub(crate) offset_x: f64,
127    /// The vertical offset of the shadow in pixels.
128    #[get(type(copy))]
129    pub(crate) offset_y: f64,
130}
131
132/// Represents the rendering priority layer for draw call ordering.
133///
134/// Higher z-index values are drawn on top of lower values,
135/// enabling correct visual layering of game objects.
136#[derive(Clone, Copy, Data, Debug, Default, Eq, Hash, New, Ord, PartialEq, PartialOrd)]
137pub struct RenderLayer {
138    /// The z-index determining draw order. Higher values draw later (on top).
139    #[get(type(copy))]
140    pub(crate) z_index: i32,
141    /// Whether objects in this layer should be rendered.
142    #[get(type(copy))]
143    pub(crate) visible: bool,
144}
145
146/// An ordered buffer of deferred draw commands recorded during a frame.
147///
148/// Scenes and components push `DrawCommand`s into the list during `on_render`
149/// instead of drawing immediately. The engine then replays the whole list once
150/// per frame via `CanvasRenderer::replay`, which batches consecutive same-style
151/// shapes into a single path and skips redundant canvas state changes. The
152/// backing `Vec` is reused across frames via `clear()` to avoid reallocation.
153#[derive(Clone, Data, Debug, Default, New)]
154pub struct DrawList {
155    /// The recorded draw commands for the current frame.
156    #[get(pub(crate))]
157    #[get_mut(pub(crate))]
158    #[set(pub(crate))]
159    pub(crate) commands: Vec<DrawCommand>,
160}
161
162/// A supersampling anti-aliasing (SSAA) canvas wrapper that renders at a higher
163/// resolution on an offscreen canvas and downscales to the display canvas for
164/// smoother polygon edges in software-rendered 3D scenes.
165///
166/// The offscreen context is scaled by `scale_factor` so that all drawing
167/// code can use logical pixel coordinates without modification. After
168/// rendering, call `present()` to draw the high-resolution buffer onto the
169/// visible canvas with high-quality image smoothing.
170#[derive(Clone, Data, New)]
171pub struct SsaaCanvas {
172    /// The display canvas element visible to the user.
173    pub(crate) display_canvas: HtmlCanvasElement,
174    /// The 2D rendering context of the display canvas used for final presentation.
175    pub(crate) display_context: CanvasRenderingContext2d,
176    /// The offscreen canvas used for high-resolution rendering.
177    pub(crate) offscreen_canvas: HtmlCanvasElement,
178    /// The 2D rendering context of the offscreen canvas, pre-scaled by `scale_factor`.
179    pub(crate) offscreen_context: CanvasRenderingContext2d,
180    /// The supersampling scale factor (e.g., 2.0 means 4x SSAA).
181    #[get(type(copy))]
182    pub(crate) scale_factor: f64,
183    /// The rendering quality preset for the downscaling present step.
184    ///
185    /// Controls the smoothing strategy when the offscreen buffer is
186    /// downscaled onto the display canvas. Defaults to `Medium`.
187    #[new(skip)]
188    #[get(type(copy))]
189    pub(crate) quality: RenderQuality,
190    /// The logical display width in CSS pixels.
191    #[get(type(copy))]
192    pub(crate) width: f64,
193    /// The logical display height in CSS pixels.
194    #[get(type(copy))]
195    pub(crate) height: f64,
196}
197
198/// A WebGPU rendering backend wrapping the GPU device, queue, and canvas context
199/// for GPU-accelerated rendering on the web.
200///
201/// Created asynchronously via `WebGpuRenderer::init` because adapter and
202/// device acquisition returns JavaScript Promises that must be awaited.
203/// Once initialized, the renderer provides methods to create GPU resources
204/// (buffers, shader modules, command encoders) and execute render passes.
205///
206/// WebGPU types are stored as `JsValue` to avoid feature-gated import issues
207/// with `web_sys`. Method calls are performed via `Reflect` and `JsCast`.
208#[derive(Clone, Data)]
209pub struct WebGpuRenderer {
210    /// The WebGPU device (`GpuDevice`) used to create GPU resources.
211    pub(crate) device: JsValue,
212    /// The device's command queue (`GpuQueue`) for submitting command buffers.
213    pub(crate) queue: JsValue,
214    /// The WebGPU canvas rendering context (`GpuCanvasContext`).
215    pub(crate) context: JsValue,
216    /// The HTML canvas element backing the WebGPU context.
217    pub(crate) canvas: HtmlCanvasElement,
218    /// The texture format string used by the canvas's swap chain (e.g., `"bgra8unorm"`).
219    #[get(type(clone))]
220    pub(crate) format: String,
221    /// The physical pixel width of the canvas backing store.
222    #[get(type(copy))]
223    pub(crate) width: u32,
224    /// The physical pixel height of the canvas backing store.
225    #[get(type(copy))]
226    pub(crate) height: u32,
227    /// Whether MSAA anti-aliasing is enabled for render pipelines.
228    ///
229    /// When `true`, the renderer allocates a multisampled intermediate texture
230    /// (`sampleCount: 4`) and resolves into the swap chain each frame; when
231    /// `false`, render passes attach directly to the swap chain view at
232    /// `sampleCount: 1`.
233    #[get(type(copy))]
234    pub(crate) antialias: bool,
235    /// The multisampled color texture used when `antialias` is `true`.
236    ///
237    /// `None` when MSAA is disabled. Rebuilt on every resize because the
238    /// `width`/`height` are immutable for a given `GpuTexture`.
239    #[get(type(clone))]
240    pub(crate) multisample_texture: Option<JsValue>,
241    /// The default `GpuTextureView` into `multisample_texture`.
242    ///
243    /// Cached at texture-create time so `begin_render_pass` does not have to
244    /// recreate the view each frame. `None` when MSAA is disabled.
245    #[get(type(clone))]
246    pub(crate) multisample_view: Option<JsValue>,
247    /// The depth-stencil texture used for depth-tested passes.
248    ///
249    /// Created lazily on the first call to [`WebGpuRenderer::begin_render_pass`]
250    /// that includes a `depthStencil` attachment. Rebuilt on every resize
251    /// because the dimensions are immutable for a given `GpuTexture`. The
252    /// matching default view is cached in `depth_view`.
253    ///
254    /// `None` until the first depth-tested render pass is opened.
255    #[get(type(clone))]
256    pub(crate) depth_texture: Option<JsValue>,
257    /// The default `GpuTextureView` into `depth_texture`.
258    ///
259    /// `None` when no depth texture has been allocated.
260    #[get(type(clone))]
261    pub(crate) depth_view: Option<JsValue>,
262    /// The depth-stencil format used for `depth_texture`.
263    ///
264    /// Stored so subsequent render-pass openers can pass the same format
265    /// to the pipeline layout without having to remember it externally.
266    /// `None` until the first depth texture is allocated.
267    #[get(type(clone))]
268    pub(crate) depth_format: Option<String>,
269    /// User-supplied closure fired when the underlying `GpuDevice` enters
270    /// the `lost` state (browser-initiated context loss, OS driver crash,
271    /// `device.destroy()`, ...).
272    ///
273    /// `None` until the caller calls [`WebGpuRenderer::on_device_lost`].
274    /// The renderer also stores a separate `device_lost_handle` that
275    /// forwards the `GPUDeviceLostInfo` JS value into this callback.
276    #[get(type(clone))]
277    pub(crate) device_lost_callback: Option<js_sys::Function>,
278    /// Whether the device is currently in the `lost` state.
279    ///
280    /// Once flipped to `true`, every GPU operation returns
281    /// `Err(WebGpuError::RendererDisposed)` until the caller destroys the
282    /// renderer and creates a new one (WebGPU has no "recover from lost
283    /// device" API).
284    #[get(type(copy))]
285    pub(crate) device_lost: bool,
286    /// Shared slot for the most recent popped error-scope value.
287    ///
288    /// `device.popErrorScope()` returns a `Promise<GPUError?>`; we
289    /// cannot `.await` it from a sync call site. Instead, every
290    /// `push_error_scope` + `pop_error_scope` pair registers a
291    /// microtask via `wasm_bindgen_futures::spawn_local` that stores
292    /// the resolved value here. Callers that want the error
293    /// synchronously call [`WebGpuRenderer::take_last_error`] to
294    /// drain the slot.
295    ///
296    /// Holding a `Rc<PendingErrorCell>` lets the spawn_local future
297    /// own its own handle independently of `&self`, so the
298    /// renderer's borrow checker stays happy. The slot is empty
299    /// (`None`) by default and after each successful take.
300    ///
301    /// The cell is intentionally `PendingErrorCell` (a `Sync`
302    /// `UnsafeCell` newtype, see [`crate::renderer::static`]) rather
303    /// than `Rc<RefCell<...>>`: the WASM single-threaded scheduler
304    /// makes the runtime borrow check `RefCell` provides unreachable
305    /// in practice, so we trade it for a raw `UnsafeCell` deref
306    /// confined to two call sites. This mirrors how euv-core
307    /// implements its global registries
308    /// (`core/src/renderer/registry/struct.rs:62`).
309    pub(crate) pending_error: Rc<PendingErrorCell>,
310    /// The currently-open `GpuCommandEncoder`, if any.
311    ///
312    /// WebGPU expects the application to encode all work for a
313    /// frame (clear, render passes, compute passes, copy ops) into
314    /// a single command encoder, then call `encoder.finish()` to
315    /// produce a `GpuCommandBuffer` and submit it to the queue.
316    /// The encoder is `None` after `submit()` finishes and must
317    /// be re-acquired via `device.createCommandEncoder()` before
318    /// the next frame.
319    #[get(type(clone))]
320    pub(crate) command_encoder: Option<JsValue>,
321}
322
323/// A WebGL 2 rendering backend wrapping the `WebGl2RenderingContext`.
324///
325/// Unlike `WebGpuRenderer`, which stores all GPU handles as opaque `JsValue`s,
326/// WebGL exposes concrete `web_sys` types, so the context and canvas are kept
327/// as strongly typed values. Shader programs created via
328/// [`WebGlRenderer::create_program`] are managed by the caller.
329///
330/// Construct via [`WebGlRenderer::init`], which resolves the canvas from the
331/// [`RenderConfig`], applies device-pixel-ratio scaling to the backing store,
332/// and acquires the `webgl2` context.
333#[derive(Clone, Data)]
334pub struct WebGlRenderer {
335    /// The WebGL 2 rendering context used for all GL calls.
336    pub(crate) context: WebGl2RenderingContext,
337    /// The HTML canvas element backing the WebGL context.
338    pub(crate) canvas: HtmlCanvasElement,
339    /// The physical pixel width of the canvas backing store.
340    #[get(type(copy))]
341    pub(crate) width: u32,
342    /// The physical pixel height of the canvas backing store.
343    #[get(type(copy))]
344    pub(crate) height: u32,
345}
346
347// =====================================================================
348// WebGPU: descriptor & data structs (consumed by the WebGpuRenderer API)
349// =====================================================================
350
351/// A single vertex attribute within a vertex buffer layout.
352///
353/// Mirrors the fields of `GPUVertexAttribute` exactly. The shader location
354/// is the `@location(N)` qualifier in the WGSL source. The offset is in
355/// bytes from the start of the vertex, and `format` is one of the
356/// WGSL vertex format strings (e.g. `"float32x4"`, `"unorm8x4"`).
357#[derive(Clone, Copy, Debug, New, PartialEq, Eq, Hash, Getter)]
358pub struct VertexAttribute {
359    /// The shader location the attribute maps to.
360    #[get(type(copy))]
361    pub(crate) shader_location: u32,
362    /// The byte offset from the start of the vertex.
363    #[get(type(copy))]
364    pub(crate) offset: u64,
365    /// The WGSL vertex format (e.g. `"float32x4"`).
366    #[get(type(clone))]
367    pub(crate) format: &'static str,
368}
369
370/// The layout of a single vertex buffer, expressed as an array stride plus
371/// a list of attributes.
372///
373/// Mirrors `GPUVertexBufferLayout` from the WebGPU spec. The renderer
374/// passes the assembled descriptor straight to `createRenderPipeline` via
375/// `Reflect`.
376#[derive(Clone, Debug, New, Getter)]
377pub struct VertexBufferLayout {
378    /// The byte stride of one vertex in the buffer.
379    #[get(type(copy))]
380    pub(crate) array_stride: u64,
381    /// Whether the buffer should be advanced per-instance (`true`) or
382    /// per-vertex (`false`).
383    #[get(type(copy))]
384    pub(crate) step_mode: VertexStepMode,
385    /// The attributes that describe how to interpret the bytes of one
386    /// vertex.
387    pub(crate) attributes: Vec<VertexAttribute>,
388}
389
390/// A 2D texture descriptor for `create_texture_2d`.
391///
392/// Defaults produce a 1x1 RGBA8 texture with `TEXTURE_BINDING | COPY_DST
393/// | COPY_SRC` usage, which is the right baseline for a sampled color
394/// texture that is uploaded to via `queue.writeTexture`. Override fields
395/// after constructing to set `mip_level_count`, `sample_count`, or
396/// different `usage` flags.
397#[derive(Clone, Debug, New, Getter)]
398pub struct Texture2DDescriptor {
399    /// The texture width in pixels. Must be > 0.
400    #[get(type(copy))]
401    pub(crate) width: u32,
402    /// The texture height in pixels. Must be > 0.
403    #[get(type(copy))]
404    pub(crate) height: u32,
405    /// The WGSL texture format (e.g. `"rgba8unorm"`, `"bgra8unorm"`,
406    /// `"rgba16float"`, `"depth24plus-stencil8"`).
407    #[get(type(clone))]
408    pub(crate) format: &'static str,
409    /// The number of mip levels. `0` is treated as `1`.
410    #[get(type(copy))]
411    #[new(skip)]
412    pub(crate) mip_level_count: u32,
413    /// The number of samples per texel (`1` for non-MSAA, `4` for MSAA).
414    #[get(type(copy))]
415    #[new(skip)]
416    pub(crate) sample_count: u32,
417    /// The WGSL usage flags (e.g. `"RENDER_ATTACHMENT | TEXTURE_BINDING |
418    /// COPY_DST | COPY_SRC"`).
419    #[get(type(clone))]
420    #[new(skip)]
421    pub(crate) usage: &'static str,
422}
423
424/// A sampler descriptor for `create_sampler`.
425///
426/// Defaults produce a non-filtering clamp-to-edge sampler. Override
427/// fields after constructing to enable linear filtering, repeat
428/// addressing, or depth comparison.
429#[derive(Clone, Debug, New, Getter)]
430pub struct GpuSamplerDescriptor {
431    /// Minification filter.
432    #[get(type(clone))]
433    #[new(skip)]
434    pub(crate) mag_filter: &'static str,
435    /// Magnification filter.
436    #[get(type(clone))]
437    #[new(skip)]
438    pub(crate) min_filter: &'static str,
439    /// Mipmap filter.
440    #[get(type(clone))]
441    #[new(skip)]
442    pub(crate) mipmap_filter: &'static str,
443    /// U address mode.
444    #[get(type(clone))]
445    #[new(skip)]
446    pub(crate) address_mode_u: &'static str,
447    /// V address mode.
448    #[get(type(clone))]
449    #[new(skip)]
450    pub(crate) address_mode_v: &'static str,
451    /// W address mode.
452    #[get(type(clone))]
453    #[new(skip)]
454    pub(crate) address_mode_w: &'static str,
455    /// Whether the sampler is a comparison sampler.
456    #[get(type(copy))]
457    #[new(skip)]
458    pub(crate) compare: bool,
459}
460
461/// The descriptor for a single (color or depth-stencil) render pass
462/// attachment, used as input to `begin_render_pass` / `begin_render_pass_to_texture`.
463#[derive(Clone, Debug)]
464pub struct RenderPassColorAttachment {
465    /// The texture view to draw into.
466    ///
467    /// When `None`, the renderer uses the swap-chain view (or the MSAA
468    /// intermediate view if `antialias == true`).
469    pub(crate) view: Option<JsValue>,
470    /// An optional resolve target for MSAA.
471    ///
472    /// `None` when MSAA is disabled. The renderer fills in the default
473    /// resolve target (the swap-chain view) when MSAA is enabled and the
474    /// caller leaves this as `None`.
475    pub(crate) resolve_target: Option<JsValue>,
476    /// The clear color as `(r, g, b, a)` in `0.0..=1.0`. `None` means
477    /// `"load"` (keep the previous contents).
478    pub(crate) clear_value: Option<(f64, f64, f64, f64)>,
479    /// The load operation. `None` → `"clear"` when `clear_value` is
480    /// `Some`, otherwise `"load"`.
481    pub(crate) load_op: Option<&'static str>,
482    /// The store operation. `None` → `"store"`.
483    pub(crate) store_op: Option<&'static str>,
484}
485
486/// The depth-stencil portion of a `RenderPassDescriptor`, used as input to
487/// `begin_render_pass` / `begin_render_pass_to_texture`.
488#[derive(Clone, Debug)]
489pub struct RenderPassDepthStencilAttachment {
490    /// The depth-stencil texture view to use.
491    ///
492    /// When `None`, the renderer uses the default view into its
493    /// `depth_texture` field, allocating the depth texture lazily if
494    /// needed.
495    pub(crate) view: Option<JsValue>,
496    /// The depth clear value in `0.0..=1.0`. `None` means
497    /// `"load"` (keep previous depth).
498    pub(crate) depth_clear_value: Option<f32>,
499    /// The depth load op. `None` → `"clear"` when
500    /// `depth_clear_value` is `Some`, otherwise `"load"`.
501    pub(crate) depth_load_op: Option<&'static str>,
502    /// The depth store op. `None` → `"store"`.
503    pub(crate) depth_store_op: Option<&'static str>,
504    /// Whether depth reads should be enabled. `None` → `false`.
505    pub(crate) depth_read_only: Option<bool>,
506}
507
508/// Descriptor for `GpuTexture.createView(descriptor)`.
509///
510/// Sub-selects a single cube face / mip / array slice / depth-aspect of a
511/// texture. When you need the full texture as a 2D view (the common case),
512/// just call `create_view` without a descriptor; the new method accepts an
513/// `Option<&TextureViewDescriptor>` for callers that need the full
514/// flexibility of the WebGPU spec.
515#[derive(Clone, Debug, New, Getter)]
516pub struct TextureViewDescriptor {
517    /// View format override, or `None` to use the texture's own format.
518    #[get(type(clone))]
519    #[new(value = "None")]
520    pub(crate) format: Option<&'static str>,
521    /// View dimension (`"2d"`, `"2d-array"`, `"cube"`, `"cube-array"`, ...).
522    /// `None` means the dimension is inferred from the texture.
523    #[get(type(clone))]
524    #[new(value = "None")]
525    pub(crate) dimension: Option<&'static str>,
526    /// Most significant mip level (inclusive). `None` → `0`.
527    #[get(type(copy))]
528    #[new(value = "0")]
529    pub(crate) base_mip_level: u32,
530    /// Number of mip levels in the view. `0` → all the way to the top.
531    #[get(type(copy))]
532    #[new(value = "0")]
533    pub(crate) mip_level_count: u32,
534    /// First array layer (inclusive). `None` → `0`. Only meaningful for
535    /// `2d-array` / `cube` / `cube-array` views.
536    #[get(type(copy))]
537    #[new(value = "0")]
538    pub(crate) base_array_layer: u32,
539    /// Number of array layers. `0` → all remaining layers.
540    #[get(type(copy))]
541    #[new(value = "0")]
542    pub(crate) array_layer_count: u32,
543    /// Which aspect of the texture to expose. One of:
544    /// `"all"`, `"depth-only"`, `"stencil-only"`. `None` → `"all"`.
545    #[get(type(clone))]
546    #[new(value = "None")]
547    pub(crate) aspect: Option<&'static str>,
548}
549
550/// Descriptor for `queue.writeTexture(destination, data, dataLayout, size)`.
551///
552/// WebGPU's `writeTexture` lets you upload CPU-side pixel data directly to a
553/// texture without staging through a buffer. Use it for: ImGui font atlases,
554/// procedural noise textures, sprite sheets, `ImageBitmap` pixels, etc.
555#[derive(Clone, Debug, New, Getter)]
556pub struct TextureWriteDescriptor {
557    /// The pixel data to upload. Bytes are laid out according to
558    /// `bytes_per_row` / `rows_per_image`.
559    #[get(type(clone))]
560    pub(crate) data: Vec<u8>,
561    /// Bytes per row of the source data. Must be a multiple of 256.
562    #[get(type(copy))]
563    pub(crate) bytes_per_row: u32,
564    /// Number of rows per image. `0` for 2D textures without mip chains.
565    #[get(type(copy))]
566    pub(crate) rows_per_image: u32,
567    /// Destination mip level to write into.
568    #[get(type(copy))]
569    pub(crate) mip_level: u32,
570    /// Destination texture to write into.
571    #[get(type(clone))]
572    pub(crate) texture: JsValue,
573    /// Origin within the destination texture. `None` → `(0, 0, 0)`.
574    #[get(type(clone))]
575    #[new(value = "None")]
576    pub(crate) origin: Option<JsValue>,
577    /// Whether to flip the source data vertically before writing.
578    /// `true` is essential when uploading from `<img>` / `<canvas>` whose
579    /// rows are top-to-bottom but WebGPU textures are bottom-to-top.
580    #[get(type(copy))]
581    #[new(value = "false")]
582    pub(crate) flip_y: bool,
583}
584
585/// Interior-mutable slot for the renderer's pending error-scope value.
586///
587/// This is the `euv-engine` analog of euv-core's `HandlerRegistryCell`
588/// (`core/src/renderer/registry/struct.rs:62`): a single-element
589/// `Sync` wrapper that holds an `Option<JsValue>` behind an
590/// `UnsafeCell`.
591///
592/// # Why this type exists
593///
594/// `WebGpuRenderer::pending_error` needs interior mutability
595/// because:
596///
597/// 1. `pop_error_sync` takes `&self` (the WebGPU hot path cannot
598///    be `async`), but the spawned `wasm_bindgen_futures::spawn_local`
599///    future must mutate the slot to store the resolved
600///    `Promise<GPUError?>` value.
601/// 2. `take_last_error` also takes `&self` and drains the slot
602///    on the next render tick.
603///
604/// The first implementation used `Rc<RefCell<Option<JsValue>>>`,
605/// which works but pays for:
606///
607/// - a `RefCell::borrow_mut` runtime borrow check on every
608///   write (the panic path is unreachable in practice — only
609///   the spawn_local future and `take_last_error` ever touch
610///   the slot, and they never overlap because the future is
611///   a microtask drained before the next render tick).
612/// - a heap allocation for the `RefCell`'s borrow state.
613///
614/// The newtype keeps the interior-mutability primitive (`Rc`),
615/// because the spawn_local future needs its own owning handle,
616/// but swaps the inner cell from `RefCell` to `UnsafeCell`:
617///
618/// - zero runtime borrow check (the WASM single-threaded
619///   scheduler makes the borrow impossible to violate).
620/// - zero allocation (the cell is just a `*mut Option<JsValue>`
621///   sitting inside the `Rc`-managed box).
622///
623/// # Sync safety
624///
625/// `PendingErrorCell` is **not** `Sync` by default (`UnsafeCell`
626/// explicitly opts out). We hand-implement `Sync` for it because
627/// the renderer is only ever used in the WASM single-threaded
628/// runtime; the `Rc` ensures the same instance is never shared
629/// across threads (it is not `Send`/`Sync` either), and the
630/// WASM main thread is the only place that ever touches the
631/// slot. This matches euv-core's pattern
632/// (`unsafe impl Sync for HandlerRegistryCell {}`).
633///
634/// If the engine is ever compiled for a multi-threaded target
635/// (native, `wasm-bindgen-rayon`), this `unsafe impl Sync` is
636/// unsound and must be removed.
637pub struct PendingErrorCell(
638    /// Interior-mutable storage for the optional `JsValue`.
639    ///
640    /// Marked `pub(crate)` (not just `pub`) because the field is
641    /// only meant to be touched from inside the renderer module —
642    /// specifically from the `impl PendingErrorCell` block in
643    /// `impl.rs`. The struct itself stays `pub` so external code
644    /// can name the type, but the raw `UnsafeCell` is an
645    /// implementation detail.
646    pub(crate) UnsafeCell<Option<JsValue>>,
647);