nsh_gpu/lib.rs
1//! GPU views: a view's box drawn every frame by a renderer the app writes
2//! with [`wgpu`], composited by the platform under the view's children.
3//!
4//! A [`GpuRenderer`] is the app's own Rust code: it builds its pipelines and
5//! buffers once ([`GpuRenderer::prepare`]), takes the view's props
6//! ([`GpuRenderer::set_prop`], [`GpuRenderer::set_animated_number`]) and
7//! encodes a frame whenever the view needs one ([`GpuRenderer::render`]).
8//! NSH runs it on a render thread of the surface's, never on the main
9//! thread and never in JS: the main thread only asks for frames on the
10//! display's clock and shows the ones that are done, so a frame the GPU or
11//! the renderer is late with is skipped rather than waited for.
12//!
13//! An app's crate registers a renderer by name for TSX, from its
14//! `#[native_module]` function ([`GpuRegistry::gpu_renderer`]):
15//!
16//! ```ignore
17//! #[native_module("gallery/scenes")]
18//! fn scenes(registry: &mut Registry) {
19//! registry.gpu_renderer("gallery/gears", Gears::new);
20//! }
21//! ```
22//!
23//! and TSX makes a component of it with `gpuView` of `nsh`:
24//!
25//! ```tsx
26//! const Gears = gpuView<{ exposure: number }>("gallery/gears", { props: ["exposure"] });
27//! <Gears exposure={exposure} style={{ height: 320 }} />
28//! ```
29//!
30//! A Rust element gives the view its renderer itself
31//! ([`GpuViewExt::renderer`]): `gpu_view().renderer(Gears::new)`.
32//!
33//! # Frames
34//!
35//! The renderer draws into [`GpuFrame::target`], `GpuFrame::width` ×
36//! `GpuFrame::height` pixels of [`GpuFrame::format`] (8-bit unsigned
37//! normalized, RGBA or BGRA by platform; rebuild what depends on it if it
38//! changes), clearing it first. Colors are what the view shows: sRGB-encoded
39//! with premultiplied alpha, as CSS colors (a renderer lighting in linear
40//! space encodes its result to sRGB itself). A frame is rendered when one of
41//! the view's props, its size or its scale changed, and on every display
42//! frame while [`GpuRenderer::animating`] says so.
43//!
44//! The device is shared by the views of a surface: a high-performance
45//! adapter, with all of its features and limits (read them from
46//! [`GpuContext::device`]). Where no GPU answers, GPU views draw nothing of
47//! their own.
48
49use std::{sync::Arc, time::Duration};
50
51use nsh_core::{
52 JsonValue, Rgba,
53 element::{GpuView, Registry},
54 geometry::{Points, Size},
55 gpu::GpuSource,
56};
57pub use wgpu;
58
59/// What a GPU view draws: the app's own wgpu code, run on the surface's
60/// render thread.
61pub trait GpuRenderer: Send + 'static {
62 /// Called once the device is open, before the first frame: build the
63 /// pipelines, buffers and textures here.
64 fn prepare(&mut self, cx: &GpuContext<'_>) {
65 let _ = cx;
66 }
67
68 /// Prop `name` set to `value` (any JSON value; `None`: removed), before
69 /// the next frame. A frame follows.
70 fn set_prop(&mut self, name: &str, value: Option<&JsonValue>) {
71 let _ = (name, value);
72 }
73
74 /// Prop `name`, bound to an animated value, moved to `value` (on the
75 /// display frames it changes, without JS). By default, [`Self::set_prop`]
76 /// with a JSON number. A frame follows.
77 fn set_animated_number(&mut self, name: &str, value: f64) {
78 let json = serde_json::Number::from_f64(value).map_or(JsonValue::Null, JsonValue::Number);
79 self.set_prop(name, Some(&json));
80 }
81
82 /// Prop `name`, bound to an animated color, moved to `color`. By
83 /// default, [`Self::set_prop`] with the color as `#rrggbbaa`. A frame
84 /// follows.
85 fn set_animated_color(&mut self, name: &str, color: Rgba) {
86 let channel = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8;
87 let hex = format!(
88 "#{:02x}{:02x}{:02x}{:02x}",
89 channel(color.r),
90 channel(color.g),
91 channel(color.b),
92 channel(color.a)
93 );
94 self.set_prop(name, Some(&JsonValue::from(hex)));
95 }
96
97 /// Whether its frames change with time alone (an animation, a
98 /// simulation): it is then rendered on every display frame. By default,
99 /// only when something changed.
100 fn animating(&self) -> bool {
101 false
102 }
103
104 /// Encodes a frame into [`GpuFrame::target`].
105 fn render(&mut self, frame: &mut GpuFrame<'_>);
106}
107
108/// The device a renderer prepares with ([`GpuRenderer::prepare`]).
109#[non_exhaustive]
110pub struct GpuContext<'a> {
111 device: &'a wgpu::Device,
112 queue: &'a wgpu::Queue,
113}
114
115impl<'a> GpuContext<'a> {
116 /// The context of `device` and its `queue` (made by the runtime that
117 /// runs renderers: NSH's engine, a test).
118 pub fn new(device: &'a wgpu::Device, queue: &'a wgpu::Queue) -> Self {
119 Self { device, queue }
120 }
121
122 /// The device, shared by the GPU views of the surface.
123 pub fn device(&self) -> &wgpu::Device {
124 self.device
125 }
126
127 /// The device's queue.
128 pub fn queue(&self) -> &wgpu::Queue {
129 self.queue
130 }
131}
132
133/// An event a renderer emitted ([`GpuFrame::emit`]): its view's
134/// `on<Name>` handler gets `data`.
135#[derive(Debug, Clone, PartialEq)]
136#[non_exhaustive]
137pub struct GpuEvent {
138 /// Its name (`pick` reaches `onPick`).
139 pub name: Arc<str>,
140 /// What it carries.
141 pub data: JsonValue,
142}
143
144/// One frame of a GPU view, as its renderer encodes it.
145#[non_exhaustive]
146pub struct GpuFrame<'a> {
147 device: &'a wgpu::Device,
148 queue: &'a wgpu::Queue,
149 target: &'a wgpu::TextureView,
150 format: wgpu::TextureFormat,
151 width: u32,
152 height: u32,
153 scale: f32,
154 time: Duration,
155 encoder: &'a mut wgpu::CommandEncoder,
156 events: &'a mut Vec<GpuEvent>,
157}
158
159/// What a frame is made of ([`GpuFrame::new`]).
160#[non_exhaustive]
161pub struct GpuFrameParts<'a> {
162 /// The device.
163 pub device: &'a wgpu::Device,
164 /// Its queue.
165 pub queue: &'a wgpu::Queue,
166 /// Where the frame is drawn.
167 pub target: &'a wgpu::TextureView,
168 /// The target's format.
169 pub format: wgpu::TextureFormat,
170 /// The target's width in pixels.
171 pub width: u32,
172 /// The target's height in pixels.
173 pub height: u32,
174 /// Pixels per point.
175 pub scale: f32,
176 /// Since the renderer was made.
177 pub time: Duration,
178 /// What the frame is encoded with.
179 pub encoder: &'a mut wgpu::CommandEncoder,
180 /// Where its events go.
181 pub events: &'a mut Vec<GpuEvent>,
182}
183
184impl<'a> GpuFrameParts<'a> {
185 /// The parts of a frame of `width` × `height` pixels at `scale`.
186 #[allow(clippy::too_many_arguments)]
187 pub fn new(
188 device: &'a wgpu::Device,
189 queue: &'a wgpu::Queue,
190 target: &'a wgpu::TextureView,
191 format: wgpu::TextureFormat,
192 (width, height): (u32, u32),
193 scale: f32,
194 time: Duration,
195 encoder: &'a mut wgpu::CommandEncoder,
196 events: &'a mut Vec<GpuEvent>,
197 ) -> Self {
198 Self {
199 device,
200 queue,
201 target,
202 format,
203 width,
204 height,
205 scale,
206 time,
207 encoder,
208 events,
209 }
210 }
211}
212
213impl<'a> GpuFrame<'a> {
214 /// A frame of `parts` (made by the runtime that runs renderers).
215 pub fn new(parts: GpuFrameParts<'a>) -> Self {
216 let GpuFrameParts {
217 device,
218 queue,
219 target,
220 format,
221 width,
222 height,
223 scale,
224 time,
225 encoder,
226 events,
227 } = parts;
228 Self {
229 device,
230 queue,
231 target,
232 format,
233 width,
234 height,
235 scale,
236 time,
237 encoder,
238 events,
239 }
240 }
241
242 /// The device.
243 pub fn device(&self) -> &wgpu::Device {
244 self.device
245 }
246
247 /// The device's queue: buffer and texture writes made here land before
248 /// the frame's commands.
249 pub fn queue(&self) -> &wgpu::Queue {
250 self.queue
251 }
252
253 /// Where the frame is drawn: clear it first.
254 pub fn target(&self) -> &wgpu::TextureView {
255 self.target
256 }
257
258 /// The target's format: 8-bit unsigned normalized, RGBA or BGRA.
259 pub fn format(&self) -> wgpu::TextureFormat {
260 self.format
261 }
262
263 /// The target's width in pixels.
264 pub fn width(&self) -> u32 {
265 self.width
266 }
267
268 /// The target's height in pixels.
269 pub fn height(&self) -> u32 {
270 self.height
271 }
272
273 /// Pixels per point.
274 pub fn scale(&self) -> f32 {
275 self.scale
276 }
277
278 /// The view's size in points.
279 pub fn size(&self) -> Size<Points> {
280 let scale = self.scale.max(f32::MIN_POSITIVE);
281 Size {
282 width: Points(self.width as f32 / scale),
283 height: Points(self.height as f32 / scale),
284 }
285 }
286
287 /// Since the renderer was made: what an animation reads.
288 pub fn time(&self) -> Duration {
289 self.time
290 }
291
292 /// The encoder the frame's commands go to; NSH submits it.
293 pub fn encoder(&mut self) -> &mut wgpu::CommandEncoder {
294 self.encoder
295 }
296
297 /// Emits event `name` with `data`: the view's `on<Name>` handler (Rust:
298 /// `on_native_event`) gets it.
299 pub fn emit(&mut self, name: &str, data: JsonValue) {
300 self.events.push(GpuEvent {
301 name: name.into(),
302 data,
303 });
304 }
305}
306
307/// A renderer's factory, as [`GpuSource`]s carry it.
308type Make = Arc<dyn Fn() -> Box<dyn GpuRenderer> + Send + Sync>;
309
310/// The source of renderers `make` makes: a view mounted with it makes one.
311pub fn renderer_source<R: GpuRenderer>(make: impl Fn() -> R + Send + Sync + 'static) -> GpuSource {
312 let make: Make = Arc::new(move || Box::new(make()));
313 GpuSource::new(make)
314}
315
316/// A renderer of `source` ([`renderer_source`]); `None` for a source of
317/// something else.
318pub fn make_renderer(source: &GpuSource) -> Option<Box<dyn GpuRenderer>> {
319 source.downcast_ref::<Make>().map(|make| make())
320}
321
322/// GPU renderers on a UI set's registry: what an app's crate calls from
323/// its `#[native_module]` function.
324pub trait GpuRegistry {
325 /// Registers the renderers `make` makes as `name`, which TSX's
326 /// `gpuView(name, …)` and Rust's `gpu_view().renderer_named(name)` draw
327 /// with.
328 fn gpu_renderer<R: GpuRenderer>(
329 &mut self,
330 name: &'static str,
331 make: impl Fn() -> R + Send + Sync + 'static,
332 ) -> &mut Self;
333}
334
335impl GpuRegistry for Registry {
336 fn gpu_renderer<R: GpuRenderer>(
337 &mut self,
338 name: &'static str,
339 make: impl Fn() -> R + Send + Sync + 'static,
340 ) -> &mut Self {
341 self.gpu_renderer_source(name, renderer_source(make))
342 }
343}
344
345/// A GPU view's renderer, given by a Rust element.
346pub trait GpuViewExt {
347 /// Draws the view with the renderers `make` makes (one each time the
348 /// view is mounted).
349 fn renderer<R: GpuRenderer>(self, make: impl Fn() -> R + Send + Sync + 'static) -> Self;
350}
351
352impl GpuViewExt for GpuView {
353 fn renderer<R: GpuRenderer>(self, make: impl Fn() -> R + Send + Sync + 'static) -> Self {
354 self.source(renderer_source(make))
355 }
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 struct Clear;
363
364 impl GpuRenderer for Clear {
365 fn render(&mut self, _: &mut GpuFrame<'_>) {}
366 }
367
368 #[test]
369 fn a_source_makes_renderers_and_others_make_none() {
370 let source = renderer_source(|| Clear);
371 assert!(make_renderer(&source).is_some());
372 assert!(make_renderer(&GpuSource::new(7_u32)).is_none());
373 }
374
375 #[test]
376 fn a_registered_renderer_is_found_by_name() {
377 let mut registry = Registry::new();
378 registry.gpu_renderer("test/clear", || Clear);
379 let source = registry
380 .registered_gpu_renderer("test/clear")
381 .expect("registered");
382 assert!(make_renderer(source).is_some());
383 assert!(registry.registered_gpu_renderer("test/other").is_none());
384 }
385}