Skip to main content

unpeel_surface_abi/
lib.rs

1#![no_std]
2
3pub const ABI_VERSION: u32 = 1;
4pub const COMMAND_BYTES: usize = 32;
5
6pub const GRADIENT: u32 = 1;
7pub const ROUND_RECT: u32 = 2;
8pub const CIRCLE: u32 = 3;
9pub const LINE: u32 = 4;
10pub const TEXT: u32 = 5;
11// Kind 6 is retired (was CELL_GRID, the fake-TUI-in-pixels bridge). Cell
12// UI belongs on the real terminal grid above the z=-1 placement; hosts
13// ignore unknown kinds, so the number stays reserved rather than reused.
14/// Bounded RGBA pixels copied into guest memory after an explicit host grant.
15/// `arg0` is the guest byte pointer and `arg1` packs source width/height.
16pub const IMAGE_RGBA: u32 = 7;
17/// A bounded native-rendered 3D scene packet. `arg0` is the guest byte
18/// pointer and `arg1` is its byte length. The command rectangle is the
19/// viewport. Ordinary 2D commands emitted before it show through transparent
20/// scene pixels; commands emitted afterward layer above it.
21pub const SCENE_3D: u32 = 8;
22/// Composite one host-owned mesh resource into a 3D viewport. `arg0` is an
23/// opaque handle granted by the host; model bytes never enter guest memory.
24/// The command rectangle is the destination viewport and `arg1` is reserved.
25pub const MODEL_3D: u32 = 9;
26/// One infinite 2D grid evaluated by the renderer. `x`/`y` are the projected
27/// world origin, `w` is screen-space spacing, `h` is line thickness, `color`
28/// is the minor grid color, `arg0` is the major-axis color, and `arg1` is the
29/// horizontal edge-fade width as `f32::to_bits()`.
30pub const CANVAS_GRID: u32 = 10;
31/// A finite, dense canvas field evaluated in O(pixels), not O(items). `x`/`y`
32/// are the projected origin, `w`/`h` are projected item spacing, `arg0` packs
33/// columns/rows as two `u16`s, and `arg1` is a deterministic visual seed.
34/// Individual high-detail items can be layered above this persistent field.
35pub const CANVAS_TILE_FIELD: u32 = 11;
36// Kind 12 is a retired host-lowered content command. The value stays reserved
37// so retained scenes and native pre-lowering kinds never collide. Hosts feed
38// cached pixels through HOST_CACHED_RGBA instead.
39/// Host-lowered cached RGBA content. Guests must never emit this directly;
40/// a native host lowers its own payload commands into these draws and
41/// uploads the backing pixels via the renderer's `upload_pixel_atlas`.
42/// `arg0` is a byte offset in that host-owned atlas and `arg1` packs the
43/// source dimensions. It intentionally shares IMAGE_RGBA's sampling contract.
44pub const HOST_CACHED_RGBA: u32 = 13;
45/// Multiply the already-composited canvas alpha by an edge mask. Default
46/// (`arg0 == 0`): horizontal, `w` is the fade width at both side edges.
47/// `arg0 == 1`: a vertical band — alpha ramps in over `w` px from `y` and,
48/// when `h > 0`, ramps out over `w` px approaching `y + h`, hiding content
49/// scrolled toward the top or bottom. Fixed overlays emitted after this
50/// command remain unaffected.
51pub const CANVAS_EDGE_FADE: u32 = 14;
52/// Host-lowered antialiased text run. Guests must never emit this directly;
53/// they emit `TEXT`, and the host lowers it against its glyph atlas before
54/// upload. `arg0` is the first glyph-entry index, `arg1` the entry count, and
55/// `x/y/w/h` become the run's culling bounds in pixels.
56pub const GLYPH_RUN: u32 = 15;
57/// A dot-matrix ring gauge evaluated in O(pixels), like the grid and tile
58/// field. `x`/`y` are the center, `w` the ring radius, `h` the dot radius,
59/// `color` the base dot color, `arg0` the accent color, and `arg1` the fill
60/// fraction in [0, 1] as `f32::to_bits()` — accent dots sweep clockwise from
61/// 12 o'clock up to the fraction.
62pub const DOT_RING: u32 = 16;
63/// Dot-matrix text: the built-in 5x7 font rendered as round dots on a
64/// lattice (flip-dot/LED style), with faint "off" dots filling each glyph
65/// cell. `x`/`y` are the top-left, `w` the dot pitch in pixels, `h` the dot
66/// radius, `color` the lit dot color; `arg0`/`arg1` address UTF-8 bytes in
67/// the scene text buffer exactly like `TEXT`. Advance is 6 dots per glyph.
68pub const DOT_TEXT: u32 = 17;
69/// Guest-owned RGBA pixels revealed through a deterministic animated noise
70/// mask. Payload and destination geometry are identical to [`IMAGE_RGBA`].
71/// `color` packs effect state as `reveal:u8 | frame:u8 | seed:u16` from most
72/// to least significant bits. Hosts evaluate the mask while sampling, so a
73/// guest can keep one stable image buffer instead of rebuilding dithered
74/// pixels every frame.
75pub const IMAGE_RGBA_REVEAL: u32 = 18;
76/// Declare a portable, renderer-owned view gesture for the current scene.
77/// This command draws no pixels. `arg0` is one of the `VIEW_GESTURE_*`
78/// modes. A connected presenter may preview that gesture against its retained
79/// scene locally, then send one endpoint-equivalent commit to the
80/// authoritative app when the pointer is released.
81///
82/// For [`VIEW_GESTURE_ORBIT_3D`] and [`VIEW_GESTURE_ORBIT_3D_SCOPED`], `x`
83/// and `y` are yaw/pitch radians per logical pointer pixel and `w`/`h` are the
84/// inclusive pitch limits. The 2D pan modes follow pointer pixels exactly and
85/// ignore those fields.
86pub const VIEW_GESTURE: u32 = 19;
87/// Restrict a scoped view gesture to one screen-space rectangle.
88///
89/// This command draws no pixels. `arg0` associates the rectangle with one of
90/// the scoped `VIEW_GESTURE_*` modes, while `x`/`y`/`w`/`h` describe a
91/// logical-pixel hit region. `arg1` is [`VIEW_GESTURE_REGION_INCLUDE`] or
92/// [`VIEW_GESTURE_REGION_EXCLUDE`]. Presenters accept only finite origins and
93/// finite, positive extents. Ownership requires at least one matching include
94/// and excludes every matching exclusion.
95///
96/// Legacy gesture modes deliberately ignore regions. Apps that need terminal
97/// chrome and local GPU gestures in the same scene must use a `*_SCOPED` mode,
98/// which claims no input unless pointer-down is inside a valid matching region.
99pub const VIEW_GESTURE_REGION: u32 = 20;
100/// Region contributes to the gesture's allowed area.
101pub const VIEW_GESTURE_REGION_INCLUDE: u32 = 0;
102/// Region subtracts terminal chrome or another overlay from the allowed area.
103pub const VIEW_GESTURE_REGION_EXCLUDE: u32 = 1;
104
105pub const VIEW_GESTURE_NONE: u32 = 0;
106/// Backward-compatible whole-viewport 2D pan.
107pub const VIEW_GESTURE_PAN_2D: u32 = 1;
108/// Backward-compatible whole-viewport analytic 3D orbit.
109pub const VIEW_GESTURE_ORBIT_3D: u32 = 2;
110/// 2D pan restricted by matching [`VIEW_GESTURE_REGION`] commands.
111pub const VIEW_GESTURE_PAN_2D_SCOPED: u32 = 3;
112/// Analytic 3D orbit restricted by matching [`VIEW_GESTURE_REGION`] commands.
113pub const VIEW_GESTURE_ORBIT_3D_SCOPED: u32 = 4;
114
115/// Pack the effect state consumed by [`IMAGE_RGBA_REVEAL`].
116pub const fn image_reveal_state(reveal: u8, frame: u8, seed: u16) -> u32 {
117    ((reveal as u32) << 24) | ((frame as u32) << 16) | seed as u32
118}
119
120pub const PRIMITIVE_3D_SPHERE: u32 = 1;
121pub const PRIMITIVE_3D_BOX: u32 = 2;
122pub const PRIMITIVE_3D_SELECTED: u32 = 1 << 0;
123pub const MAX_SCENE_3D_PRIMITIVES: usize = 32;
124pub const SCENE_3D_HEADER_BYTES: usize = 64;
125pub const PRIMITIVE_3D_BYTES: usize = 80;
126
127// Input events use the existing three-i32 `surface_event` export. Pointer
128// events carry pixel x/y. Key events carry modifier bits in x and zero in y.
129// Keeping this additive lets the original ABI v1 guests ignore richer input.
130pub const EVENT_POINTER_DOWN: i32 = 1;
131pub const EVENT_ACTION: i32 = 2;
132pub const EVENT_POINTER_MOVE: i32 = 3;
133pub const EVENT_POINTER_DRAG: i32 = 4;
134pub const EVENT_POINTER_UP: i32 = 5;
135pub const EVENT_SCROLL_UP: i32 = 6;
136pub const EVENT_SCROLL_DOWN: i32 = 7;
137pub const EVENT_POINTER_DOUBLE: i32 = 8;
138pub const EVENT_POINTER_TRIPLE: i32 = 9;
139pub const EVENT_KEY_UP: i32 = 10;
140pub const EVENT_KEY_DOWN: i32 = 11;
141pub const EVENT_KEY_PAGE_UP: i32 = 12;
142pub const EVENT_KEY_PAGE_DOWN: i32 = 13;
143pub const EVENT_KEY_HOME: i32 = 14;
144pub const EVENT_KEY_END: i32 = 15;
145pub const EVENT_SELECT_ALL: i32 = 16;
146pub const EVENT_COPIED: i32 = 17;
147/// Horizontal viewport navigation, usually emitted by a trackpad or by
148/// Shift+wheel. Pointer x/y remain available to the guest.
149pub const EVENT_SCROLL_LEFT: i32 = 18;
150pub const EVENT_SCROLL_RIGHT: i32 = 19;
151/// Pointer-anchored canvas zoom, normally mapped from Cmd/Ctrl+wheel.
152pub const EVENT_ZOOM_IN: i32 = 20;
153pub const EVENT_ZOOM_OUT: i32 = 21;
154/// The terminal's color scheme, sent after the host queries the real
155/// background (OSC 11) at startup. `x` is 1 for a light background and 0
156/// for dark; `y` packs the background as `0xRRGGBB`. Guests that ignore it
157/// keep their dark-scheme defaults.
158pub const EVENT_THEME: i32 = 22;
159/// Jump the canvas zoom to an absolute level, anchored at the viewport
160/// center. `x` is the percent (100 = 1:1); `x <= 0` requests fit-all. Hosts
161/// send it from chrome such as the terminal-cell zoom dropdown; guests that
162/// expose `surface_zoom_percent` should handle it.
163pub const EVENT_ZOOM_SET: i32 = 23;
164/// Wall-clock anchor, sent once at startup in interactive mode: `x` is the
165/// host's local seconds since midnight when the surface started, `y` is
166/// reserved. A clock guest shows `(x + time_ms / 1000) % 86400`. Headless
167/// runs never send it, so renders stay deterministic; guests keep a fixed
168/// demo time as the fallback.
169pub const EVENT_CLOCK: i32 = 24;
170/// Activate one named layer from host chrome: `x` is the layer index from the
171/// guest's `surface_layers_ptr` list. The guest decides how activation changes
172/// its application state or view.
173pub const EVENT_LAYER_FOCUS: i32 = 25;
174/// Native renderer capabilities, sent once before the first frame. `x` is a
175/// bitset of `RENDER_CAPABILITY_*` values and `y` is reserved. Guests must
176/// retain a portable fallback because older hosts do not send this event.
177pub const EVENT_RENDER_CAPABILITIES: i32 = 26;
178/// Toggle one row of the guest's cell list (host-rendered terminal-cell
179/// rows over the surface): `x` is the row index from `surface_list_ptr`,
180/// `y` packs the toggled control's logical-pixel center as `(x << 16) | y`
181/// so the guest can anchor pixel effects (sparkles) to the cell the user
182/// clicked. Input UI is cells; the surface below draws only effects.
183pub const EVENT_LIST_TOGGLE: i32 = 27;
184/// Submit the host-collected input string as a new list entry. The host's
185/// terminal-cell input field owns all editing; on Enter it writes the final
186/// UTF-8 string through `surface_input_ptr`/`surface_input_set` and sends
187/// this event with `x` = byte length. Hosts never deliver per-keystroke
188/// composer state.
189pub const EVENT_LIST_SUBMIT: i32 = 28;
190
191/// The active renderer evaluates analytic `SCENE_3D` packets.
192pub const RENDER_CAPABILITY_SPATIAL_3D: i32 = 1 << 0;
193
194pub const MODIFIER_SHIFT: i32 = 1 << 0;
195pub const MODIFIER_CONTROL: i32 = 1 << 1;
196pub const MODIFIER_ALT: i32 = 1 << 2;
197pub const MODIFIER_SUPER: i32 = 1 << 3;
198
199/// A deliberately tiny retained-scene command shared by the WASM guest and
200/// native host. All fields are little-endian in guest linear memory.
201#[repr(C)]
202#[derive(Clone, Copy, Debug, PartialEq)]
203pub struct Command {
204    pub kind: u32,
205    pub color: u32,
206    pub x: f32,
207    pub y: f32,
208    pub w: f32,
209    pub h: f32,
210    pub arg0: u32,
211    pub arg1: u32,
212}
213
214impl Command {
215    pub const ZERO: Self = Self {
216        kind: 0,
217        color: 0,
218        x: 0.0,
219        y: 0.0,
220        w: 0.0,
221        h: 0.0,
222        arg0: 0,
223        arg1: 0,
224    };
225
226    #[allow(clippy::too_many_arguments)]
227    pub const fn new(
228        kind: u32,
229        color: u32,
230        x: f32,
231        y: f32,
232        w: f32,
233        h: f32,
234        arg0: u32,
235        arg1: u32,
236    ) -> Self {
237        Self {
238            kind,
239            color,
240            x,
241            y,
242            w,
243            h,
244            arg0,
245            arg1,
246        }
247    }
248
249    /// Construct a non-drawing hit region for a scoped view gesture mode.
250    pub const fn view_gesture_region(mode: u32, x: f32, y: f32, w: f32, h: f32) -> Self {
251        Self::new(
252            VIEW_GESTURE_REGION,
253            0,
254            x,
255            y,
256            w,
257            h,
258            mode,
259            VIEW_GESTURE_REGION_INCLUDE,
260        )
261    }
262
263    /// Construct a non-drawing exclusion from a scoped view gesture mode.
264    pub const fn view_gesture_exclusion(mode: u32, x: f32, y: f32, w: f32, h: f32) -> Self {
265        Self::new(
266            VIEW_GESTURE_REGION,
267            0,
268            x,
269            y,
270            w,
271            h,
272            mode,
273            VIEW_GESTURE_REGION_EXCLUDE,
274        )
275    }
276
277    pub fn decode(bytes: &[u8]) -> Option<Self> {
278        if bytes.len() < COMMAND_BYTES {
279            return None;
280        }
281        let word = |offset: usize| {
282            u32::from_le_bytes(bytes[offset..offset + 4].try_into().expect("four bytes"))
283        };
284        Some(Self {
285            kind: word(0),
286            color: word(4),
287            x: f32::from_bits(word(8)),
288            y: f32::from_bits(word(12)),
289            w: f32::from_bits(word(16)),
290            h: f32::from_bits(word(20)),
291            arg0: word(24),
292            arg1: word(28),
293        })
294    }
295
296    /// Encode this command into the protocol's canonical little-endian
297    /// 32-byte representation. Network presenters use this rather than a
298    /// native pointer cast, so desktop and Apple clients share an explicit
299    /// wire format even if their host endianness ever differs.
300    pub fn encode(self) -> [u8; COMMAND_BYTES] {
301        let words = [
302            self.kind,
303            self.color,
304            self.x.to_bits(),
305            self.y.to_bits(),
306            self.w.to_bits(),
307            self.h.to_bits(),
308            self.arg0,
309            self.arg1,
310        ];
311        let mut bytes = [0; COMMAND_BYTES];
312        for (index, word) in words.into_iter().enumerate() {
313            let start = index * 4;
314            bytes[start..start + 4].copy_from_slice(&word.to_le_bytes());
315        }
316        bytes
317    }
318}
319
320/// Camera, environment, and packet metadata for one 3D viewport.
321///
322/// All members are four-byte aligned so this layout is identical in Rust,
323/// wasm32 linear memory, and Metal. Quaternions below use `(x, y, z, w)`.
324#[repr(C)]
325#[derive(Clone, Copy, Debug, PartialEq)]
326pub struct Scene3DHeader {
327    /// World-space camera xyz and vertical field of view in radians.
328    pub camera_position_fov: [f32; 4],
329    /// Camera target xyz and ground-plane y.
330    pub camera_target_ground: [f32; 4],
331    /// Direction from a surface toward the key light, plus ambient strength.
332    pub light_direction_ambient: [f32; 4],
333    pub sky_top: u32,
334    pub sky_bottom: u32,
335    /// Ground-plane RGB and fill alpha. Metal renders the grid lines with
336    /// separate translucent coverage, including when this alpha is zero.
337    pub ground_color: u32,
338    pub primitive_count: u32,
339}
340
341impl Scene3DHeader {
342    pub const ZERO: Self = Self {
343        camera_position_fov: [0.0; 4],
344        camera_target_ground: [0.0; 4],
345        light_direction_ambient: [0.0; 4],
346        sky_top: 0,
347        sky_bottom: 0,
348        ground_color: 0,
349        primitive_count: 0,
350    };
351
352    pub fn decode(bytes: &[u8]) -> Option<Self> {
353        if bytes.len() < SCENE_3D_HEADER_BYTES {
354            return None;
355        }
356        Some(Self {
357            camera_position_fov: decode_f32x4(bytes, 0),
358            camera_target_ground: decode_f32x4(bytes, 16),
359            light_direction_ambient: decode_f32x4(bytes, 32),
360            sky_top: decode_u32(bytes, 48),
361            sky_bottom: decode_u32(bytes, 52),
362            ground_color: decode_u32(bytes, 56),
363            primitive_count: decode_u32(bytes, 60),
364        })
365    }
366}
367
368/// One analytic primitive owned by a 3D scene packet. The first example uses
369/// spheres and oriented boxes; later mesh handles can be additive kinds.
370#[repr(C)]
371#[derive(Clone, Copy, Debug, PartialEq)]
372pub struct Primitive3D {
373    pub kind: u32,
374    pub color: u32,
375    pub id: u32,
376    pub flags: u32,
377    /// Center xyz; sphere radius in w.
378    pub position_radius: [f32; 4],
379    /// Unit quaternion `(x, y, z, w)`.
380    pub rotation: [f32; 4],
381    /// Box half-extents xyz; material roughness in w.
382    pub half_extents_roughness: [f32; 4],
383    /// Emissive rgb; metallic amount in w.
384    pub emissive_metallic: [f32; 4],
385}
386
387impl Primitive3D {
388    pub const ZERO: Self = Self {
389        kind: 0,
390        color: 0,
391        id: 0,
392        flags: 0,
393        position_radius: [0.0; 4],
394        rotation: [0.0, 0.0, 0.0, 1.0],
395        half_extents_roughness: [0.0; 4],
396        emissive_metallic: [0.0; 4],
397    };
398
399    pub fn decode(bytes: &[u8]) -> Option<Self> {
400        if bytes.len() < PRIMITIVE_3D_BYTES {
401            return None;
402        }
403        Some(Self {
404            kind: decode_u32(bytes, 0),
405            color: decode_u32(bytes, 4),
406            id: decode_u32(bytes, 8),
407            flags: decode_u32(bytes, 12),
408            position_radius: decode_f32x4(bytes, 16),
409            rotation: decode_f32x4(bytes, 32),
410            half_extents_roughness: decode_f32x4(bytes, 48),
411            emissive_metallic: decode_f32x4(bytes, 64),
412        })
413    }
414}
415
416fn decode_u32(bytes: &[u8], offset: usize) -> u32 {
417    u32::from_le_bytes(
418        bytes[offset..offset + 4]
419            .try_into()
420            .expect("four-byte ABI word"),
421    )
422}
423
424fn decode_f32x4(bytes: &[u8], offset: usize) -> [f32; 4] {
425    [
426        f32::from_bits(decode_u32(bytes, offset)),
427        f32::from_bits(decode_u32(bytes, offset + 4)),
428        f32::from_bits(decode_u32(bytes, offset + 8)),
429        f32::from_bits(decode_u32(bytes, offset + 12)),
430    ]
431}
432
433pub const fn rgba(red: u8, green: u8, blue: u8, alpha: u8) -> u32 {
434    ((red as u32) << 24) | ((green as u32) << 16) | ((blue as u32) << 8) | alpha as u32
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn spatial_packet_layout_is_stable_across_targets() {
443        assert_eq!(core::mem::size_of::<Scene3DHeader>(), SCENE_3D_HEADER_BYTES);
444        assert_eq!(core::mem::size_of::<Primitive3D>(), PRIMITIVE_3D_BYTES);
445        assert_eq!(core::mem::align_of::<Scene3DHeader>(), 4);
446        assert_eq!(core::mem::align_of::<Primitive3D>(), 4);
447    }
448
449    #[test]
450    fn spatial_packet_decodes_without_native_pointer_casts() {
451        let header = Scene3DHeader {
452            camera_position_fov: [1.0, 2.0, 3.0, 0.9],
453            camera_target_ground: [0.0, 0.5, 0.0, -1.0],
454            light_direction_ambient: [0.2, 0.8, 0.4, 0.15],
455            sky_top: rgba(1, 2, 3, 255),
456            sky_bottom: rgba(4, 5, 6, 255),
457            ground_color: rgba(7, 8, 9, 255),
458            primitive_count: 3,
459        };
460        let bytes = unsafe {
461            core::slice::from_raw_parts(
462                (&header as *const Scene3DHeader).cast::<u8>(),
463                SCENE_3D_HEADER_BYTES,
464            )
465        };
466        assert_eq!(Scene3DHeader::decode(bytes), Some(header));
467    }
468
469    #[test]
470    fn command_wire_encoding_is_explicit_little_endian() {
471        let command = Command::new(
472            0x0102_0304,
473            0x1122_3344,
474            1.25,
475            -2.5,
476            3.75,
477            4.5,
478            0x5566_7788,
479            0x99aa_bbcc,
480        );
481        let bytes = command.encode();
482        assert_eq!(&bytes[..4], &[4, 3, 2, 1]);
483        assert_eq!(Command::decode(&bytes), Some(command));
484    }
485}