noesis_runtime 0.12.1

Rust bindings for the Noesis GUI Native SDK: load XAML UI, drive the view and renderer, and write custom controls in Rust. Renderer-agnostic; Bevy integration lives in noesis_bevy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! `extern "C"` trampolines that bridge the C++ `RustRenderDevice` subclass
//! to a Rust-side [`RenderDevice`] trait object, plus the [`register`] entry
//! point that owns the boxed impl and the C++ device handle.
//!
//! Userdata convention: every trampoline receives a `*mut c_void` whose
//! actual type is `*mut Box<dyn RenderDevice>`. The double-`Box` gives us a
//! stable thin pointer (the inner `Box<dyn ...>` is a fat pointer).

#![allow(unsafe_op_in_unsafe_fn)] // FFI sea-of-unsafe; explicit blocks add noise.

use core::num::NonZeroU64;
use core::ptr::NonNull;
use core::slice;
use std::borrow::Cow;
use std::ffi::CStr;
use std::os::raw::{c_char, c_void};

use crate::render_device::device::{
    RenderDevice, RenderTargetDesc, RenderTargetHandle, TextureDesc, TextureHandle, TextureRect,
};
use crate::render_device::ffi::{
    RenderDeviceVTable, RenderTargetBindingFfi, TextureBindingFfi, noesis_render_device_create,
    noesis_render_device_destroy, noesis_render_device_get_glyph_cache_height,
    noesis_render_device_get_glyph_cache_width,
    noesis_render_device_get_offscreen_default_num_surfaces,
    noesis_render_device_get_offscreen_height, noesis_render_device_get_offscreen_max_num_surfaces,
    noesis_render_device_get_offscreen_sample_count, noesis_render_device_get_offscreen_width,
    noesis_render_device_set_glyph_cache_height, noesis_render_device_set_glyph_cache_width,
    noesis_render_device_set_offscreen_default_num_surfaces,
    noesis_render_device_set_offscreen_height, noesis_render_device_set_offscreen_max_num_surfaces,
    noesis_render_device_set_offscreen_sample_count, noesis_render_device_set_offscreen_width,
};
use crate::render_device::types::{Batch, DeviceCaps, TextureFormat, Tile};

/// Decode a C `*const c_char` into a string. Empty on null. Noesis labels are
/// ASCII debug strings; decode lossily so odd input can't panic across the C
/// ABI (this runs on the render thread).
unsafe fn cstr_to_str<'a>(p: *const c_char) -> Cow<'a, str> {
    if p.is_null() {
        Cow::Borrowed("")
    } else {
        CStr::from_ptr(p).to_string_lossy()
    }
}

/// Decode a `Noesis::TextureFormat::Enum` ordinal. Returns `None` for an
/// unrecognized ordinal rather than panicking: `raw` is engine-supplied and
/// reaches this on the render-thread hot path, so an unknown value is treated
/// as a contained failure by the call sites (no panic across the C ABI).
fn texture_format_from_raw(raw: u32) -> Option<TextureFormat> {
    match raw {
        0 => Some(TextureFormat::Rgba8),
        1 => Some(TextureFormat::Rgbx8),
        2 => Some(TextureFormat::R8),
        _ => None,
    }
}

const fn bytes_per_pixel(format: TextureFormat) -> u32 {
    match format {
        TextureFormat::Rgba8 | TextureFormat::Rgbx8 => 4,
        TextureFormat::R8 => 1,
    }
}

fn level_byte_count(format: TextureFormat, base_w: u32, base_h: u32, level: u32) -> usize {
    let w = (base_w >> level).max(1) as usize;
    let h = (base_h >> level).max(1) as usize;
    w * h * bytes_per_pixel(format) as usize
}

fn texture_handle(raw: u64) -> TextureHandle {
    TextureHandle(NonZeroU64::new(raw).expect("RenderDevice impl returned a zero TextureHandle"))
}

fn render_target_handle(raw: u64) -> RenderTargetHandle {
    RenderTargetHandle(
        NonZeroU64::new(raw).expect("RenderDevice impl returned a zero RenderTargetHandle"),
    )
}

/// SAFETY: the caller must guarantee `userdata` was produced by `register()`
/// and is still alive (i.e. the [`Registered`] guard hasn't been dropped).
unsafe fn device<'a>(userdata: *mut c_void) -> &'a mut Box<dyn RenderDevice> {
    &mut *userdata.cast::<Box<dyn RenderDevice>>()
}

unsafe extern "C" fn t_get_caps(userdata: *mut c_void, out: *mut DeviceCaps) {
    crate::panic_guard::guard(|| {
        let caps = device(userdata).caps();
        out.write(caps);
    })
}

unsafe extern "C" fn t_create_texture(
    userdata: *mut c_void,
    label: *const c_char,
    width: u32,
    height: u32,
    num_levels: u32,
    format_raw: u32,
    data: *const *const c_void,
    out: *mut TextureBindingFfi,
) {
    crate::panic_guard::guard(|| {
        let dev = device(userdata);
        let label = cstr_to_str(label);
        // Unknown engine-supplied format ordinal: contained failure, leave `out`
        // unwritten. As on the panic path, the C shim then wraps the zero-init
        // `out` as an inert handle-0 texture that forwards no update/drop
        // callbacks back into this impl.
        let Some(format) = texture_format_from_raw(format_raw) else {
            return;
        };

        let slices: Vec<&[u8]> = if data.is_null() {
            Vec::new()
        } else {
            let ptrs = slice::from_raw_parts(data, num_levels as usize);
            ptrs.iter()
                .enumerate()
                .map(|(lvl, &p)| {
                    let len = level_byte_count(format, width, height, lvl as u32);
                    slice::from_raw_parts(p.cast::<u8>(), len)
                })
                .collect()
        };

        let desc = TextureDesc {
            label: &label,
            width,
            height,
            num_levels,
            format,
            data: if data.is_null() {
                None
            } else {
                Some(slices.as_slice())
            },
        };
        let binding = dev.create_texture(desc);
        out.write(TextureBindingFfi::from(binding));
    })
}

unsafe extern "C" fn t_update_texture(
    userdata: *mut c_void,
    handle: u64,
    level: u32,
    x: u32,
    y: u32,
    width: u32,
    height: u32,
    format_raw: u32,
    data: *const c_void,
) {
    crate::panic_guard::guard(|| {
        let dev = device(userdata);
        // Unknown engine-supplied format ordinal: contained failure, skip the
        // update (same as the panic path).
        let Some(format) = texture_format_from_raw(format_raw) else {
            return;
        };
        let len = (width as usize) * (height as usize) * bytes_per_pixel(format) as usize;
        let bytes = slice::from_raw_parts(data.cast::<u8>(), len);
        dev.update_texture(
            texture_handle(handle),
            level,
            TextureRect {
                x,
                y,
                width,
                height,
            },
            bytes,
        );
    })
}

unsafe extern "C" fn t_end_updating_textures(
    userdata: *mut c_void,
    handles: *const u64,
    count: u32,
) {
    crate::panic_guard::guard(|| {
        let dev = device(userdata);
        let raws = slice::from_raw_parts(handles, count as usize);
        let typed: Vec<TextureHandle> = raws.iter().copied().map(texture_handle).collect();
        dev.end_updating_textures(&typed);
    })
}

unsafe extern "C" fn t_drop_texture(userdata: *mut c_void, handle: u64) {
    crate::panic_guard::guard(|| {
        device(userdata).drop_texture(texture_handle(handle));
    })
}

unsafe extern "C" fn t_create_render_target(
    userdata: *mut c_void,
    label: *const c_char,
    width: u32,
    height: u32,
    sample_count: u32,
    needs_stencil: bool,
    out: *mut RenderTargetBindingFfi,
) {
    crate::panic_guard::guard(|| {
        let dev = device(userdata);
        let label = cstr_to_str(label);
        let desc = RenderTargetDesc {
            label: &label,
            width,
            height,
            sample_count,
            needs_stencil,
        };
        let binding = dev.create_render_target(desc);
        out.write(RenderTargetBindingFfi {
            handle: binding.handle.0.get(),
            resolve_texture: binding.resolve_texture.into(),
        });
    })
}

unsafe extern "C" fn t_clone_render_target(
    userdata: *mut c_void,
    label: *const c_char,
    src_handle: u64,
    out: *mut RenderTargetBindingFfi,
) {
    crate::panic_guard::guard(|| {
        let dev = device(userdata);
        let label = cstr_to_str(label);
        let binding = dev.clone_render_target(&label, render_target_handle(src_handle));
        out.write(RenderTargetBindingFfi {
            handle: binding.handle.0.get(),
            resolve_texture: binding.resolve_texture.into(),
        });
    })
}

unsafe extern "C" fn t_drop_render_target(userdata: *mut c_void, handle: u64) {
    crate::panic_guard::guard(|| {
        device(userdata).drop_render_target(render_target_handle(handle));
    })
}

unsafe extern "C" fn t_begin_offscreen_render(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        device(userdata).begin_offscreen_render();
    })
}
unsafe extern "C" fn t_end_offscreen_render(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        device(userdata).end_offscreen_render();
    })
}
unsafe extern "C" fn t_begin_onscreen_render(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        device(userdata).begin_onscreen_render();
    })
}
unsafe extern "C" fn t_end_onscreen_render(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        device(userdata).end_onscreen_render();
    })
}

unsafe extern "C" fn t_set_render_target(userdata: *mut c_void, handle: u64) {
    crate::panic_guard::guard(|| {
        device(userdata).set_render_target(render_target_handle(handle));
    })
}

unsafe extern "C" fn t_begin_tile(userdata: *mut c_void, handle: u64, tile: *const Tile) {
    crate::panic_guard::guard(|| {
        device(userdata).begin_tile(render_target_handle(handle), *tile);
    })
}

unsafe extern "C" fn t_end_tile(userdata: *mut c_void, handle: u64) {
    crate::panic_guard::guard(|| {
        device(userdata).end_tile(render_target_handle(handle));
    })
}

unsafe extern "C" fn t_resolve_render_target(
    userdata: *mut c_void,
    handle: u64,
    tiles: *const Tile,
    count: u32,
) {
    crate::panic_guard::guard(|| {
        let dev = device(userdata);
        let tiles_slice = slice::from_raw_parts(tiles, count as usize);
        dev.resolve_render_target(render_target_handle(handle), tiles_slice);
    })
}

unsafe extern "C" fn t_map_vertices(userdata: *mut c_void, bytes: u32) -> *mut c_void {
    // A panic here yields null; Noesis tolerates a failed map far better than an
    // unwind across the render-thread C ABI.
    crate::panic_guard::guard_or(core::ptr::null_mut(), || {
        device(userdata).map_vertices(bytes).as_mut_ptr().cast()
    })
}
unsafe extern "C" fn t_unmap_vertices(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        device(userdata).unmap_vertices();
    })
}
unsafe extern "C" fn t_map_indices(userdata: *mut c_void, bytes: u32) -> *mut c_void {
    crate::panic_guard::guard_or(core::ptr::null_mut(), || {
        device(userdata).map_indices(bytes).as_mut_ptr().cast()
    })
}
unsafe extern "C" fn t_unmap_indices(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        device(userdata).unmap_indices();
    })
}

unsafe extern "C" fn t_draw_batch(userdata: *mut c_void, batch: *const Batch) {
    crate::panic_guard::guard(|| {
        device(userdata).draw_batch(&*batch);
    })
}

// Frees the `Box<Box<dyn RenderDevice>>` that `register` leaked, at the device's
// true end-of-life. Guarded: a panic in the impl's `Drop` must not unwind across
// the C++ destructor.
unsafe extern "C" fn t_drop_userdata(userdata: *mut c_void) {
    crate::panic_guard::guard(|| {
        drop(Box::from_raw(userdata.cast::<Box<dyn RenderDevice>>()));
    })
}

// Static vtable, populated once with the trampoline addresses.
static VTABLE: RenderDeviceVTable = RenderDeviceVTable {
    get_caps: t_get_caps,
    create_texture: t_create_texture,
    update_texture: t_update_texture,
    end_updating_textures: t_end_updating_textures,
    drop_texture: t_drop_texture,
    create_render_target: t_create_render_target,
    clone_render_target: t_clone_render_target,
    drop_render_target: t_drop_render_target,
    begin_offscreen_render: t_begin_offscreen_render,
    end_offscreen_render: t_end_offscreen_render,
    begin_onscreen_render: t_begin_onscreen_render,
    end_onscreen_render: t_end_onscreen_render,
    set_render_target: t_set_render_target,
    begin_tile: t_begin_tile,
    end_tile: t_end_tile,
    resolve_render_target: t_resolve_render_target,
    map_vertices: t_map_vertices,
    unmap_vertices: t_unmap_vertices,
    map_indices: t_map_indices,
    unmap_indices: t_unmap_indices,
    draw_batch: t_draw_batch,
    drop_userdata: t_drop_userdata,
};

/// Owns a Rust [`RenderDevice`] impl together with its C++ `RustRenderDevice`
/// instance. Dropping releases the `_create` reference; the boxed impl is freed
/// by the `drop_userdata` callback from `~RustRenderDevice` once Noesis drops
/// its last reference, so every callback (including any issued after this guard
/// drops) sees a live trait object.
#[must_use = "dropping the guard immediately clears the registration"]
pub struct Registered {
    handle: NonNull<c_void>,
    userdata: NonNull<Box<dyn RenderDevice>>,
}

// SAFETY: Send-only (NOT Sync); see the crate-level "Thread affinity" docs.
unsafe impl Send for Registered {}

impl Registered {
    /// Raw `Noesis::RenderDevice*` for handing to other Noesis APIs that take
    /// a render device (e.g. `IView::SetRenderer`). Borrowed for the lifetime
    /// of this `Registered`.
    #[must_use]
    pub fn raw(&self) -> *mut c_void {
        self.handle.as_ptr()
    }

    /// Mutable access to the concrete [`RenderDevice`] impl behind the
    /// registration. Use when a system needs to mutate driver state between
    /// Noesis calls (e.g. swapping the onscreen target view each frame
    /// before driving the renderer).
    ///
    /// The type parameter `D` must match the concrete type passed to
    /// [`register`]; enforced at runtime via `dyn Any` downcast.
    ///
    /// # Panics
    ///
    /// Panics if `D` is not the concrete type `register` was called with.
    pub fn device_mut<D: RenderDevice>(&mut self) -> &mut D {
        // SAFETY: userdata points at the live Box<dyn RenderDevice> produced
        // by register(); the borrow lives only as long as &mut self.
        let boxed: &mut Box<dyn RenderDevice> = unsafe { self.userdata.as_mut() };
        (**boxed)
            .as_any_mut()
            .downcast_mut::<D>()
            .expect("Registered::device_mut: type does not match the one given to register")
    }

    /// Width of offscreen render-target textures, in pixels. `0` (the default)
    /// selects automatic sizing. Set this (and the sibling offscreen /
    /// glyph-cache knobs) before the renderer draws its first frame.
    pub fn set_offscreen_width(&mut self, width: u32) {
        // SAFETY: handle is a live Noesis::RenderDevice* until this guard drops.
        unsafe { noesis_render_device_set_offscreen_width(self.handle.as_ptr(), width) }
    }

    /// Height of offscreen render-target textures, in pixels. `0` (the default)
    /// selects automatic sizing.
    pub fn set_offscreen_height(&mut self, height: u32) {
        // SAFETY: handle is a live Noesis::RenderDevice* until this guard drops.
        unsafe { noesis_render_device_set_offscreen_height(self.handle.as_ptr(), height) }
    }

    /// Multisample count for offscreen textures. Default is `1` (no MSAA).
    pub fn set_offscreen_sample_count(&mut self, count: u32) {
        // SAFETY: handle is a live Noesis::RenderDevice* until this guard drops.
        unsafe { noesis_render_device_set_offscreen_sample_count(self.handle.as_ptr(), count) }
    }

    /// Number of offscreen textures created up-front at startup. Default is `0`.
    pub fn set_offscreen_default_num_surfaces(&mut self, num: u32) {
        // SAFETY: handle is a live Noesis::RenderDevice* until this guard drops.
        unsafe {
            noesis_render_device_set_offscreen_default_num_surfaces(self.handle.as_ptr(), num)
        }
    }

    /// Maximum number of offscreen textures. `0` (the default) means unlimited.
    pub fn set_offscreen_max_num_surfaces(&mut self, num: u32) {
        // SAFETY: handle is a live Noesis::RenderDevice* until this guard drops.
        unsafe { noesis_render_device_set_offscreen_max_num_surfaces(self.handle.as_ptr(), num) }
    }

    /// Width of the glyph-cache texture, in pixels. The default is
    /// build-dependent, so read it back with [`Self::glyph_cache_width`] rather
    /// than assuming a value.
    pub fn set_glyph_cache_width(&mut self, width: u32) {
        // SAFETY: handle is a live Noesis::RenderDevice* until this guard drops.
        unsafe { noesis_render_device_set_glyph_cache_width(self.handle.as_ptr(), width) }
    }

    /// Height of the glyph-cache texture, in pixels. The default is
    /// build-dependent, so read it back with [`Self::glyph_cache_height`] rather
    /// than assuming a value.
    pub fn set_glyph_cache_height(&mut self, height: u32) {
        // SAFETY: handle is a live Noesis::RenderDevice* until this guard drops.
        unsafe { noesis_render_device_set_glyph_cache_height(self.handle.as_ptr(), height) }
    }

    /// Configured offscreen texture width. `0` means automatic. Companion to
    /// [`Self::set_offscreen_width`].
    #[must_use]
    pub fn offscreen_width(&self) -> u32 {
        // SAFETY: handle is a live Noesis::RenderDevice*; const accessor.
        unsafe { noesis_render_device_get_offscreen_width(self.handle.as_ptr()) }
    }

    /// Configured offscreen texture height. `0` means automatic. Companion to
    /// [`Self::set_offscreen_height`].
    #[must_use]
    pub fn offscreen_height(&self) -> u32 {
        // SAFETY: handle is a live Noesis::RenderDevice*; const accessor.
        unsafe { noesis_render_device_get_offscreen_height(self.handle.as_ptr()) }
    }

    /// Configured offscreen multisample count. Companion to
    /// [`Self::set_offscreen_sample_count`].
    #[must_use]
    pub fn offscreen_sample_count(&self) -> u32 {
        // SAFETY: handle is a live Noesis::RenderDevice*; const accessor.
        unsafe { noesis_render_device_get_offscreen_sample_count(self.handle.as_ptr()) }
    }

    /// Configured startup offscreen-surface count. Companion to
    /// [`Self::set_offscreen_default_num_surfaces`].
    #[must_use]
    pub fn offscreen_default_num_surfaces(&self) -> u32 {
        // SAFETY: handle is a live Noesis::RenderDevice*; const accessor.
        unsafe { noesis_render_device_get_offscreen_default_num_surfaces(self.handle.as_ptr()) }
    }

    /// Configured maximum offscreen-surface count. `0` means unlimited.
    /// Companion to [`Self::set_offscreen_max_num_surfaces`].
    #[must_use]
    pub fn offscreen_max_num_surfaces(&self) -> u32 {
        // SAFETY: handle is a live Noesis::RenderDevice*; const accessor.
        unsafe { noesis_render_device_get_offscreen_max_num_surfaces(self.handle.as_ptr()) }
    }

    /// Configured glyph-cache texture width. Build-dependent default. Companion
    /// to [`Self::set_glyph_cache_width`].
    #[must_use]
    pub fn glyph_cache_width(&self) -> u32 {
        // SAFETY: handle is a live Noesis::RenderDevice*; const accessor.
        unsafe { noesis_render_device_get_glyph_cache_width(self.handle.as_ptr()) }
    }

    /// Configured glyph-cache texture height. Build-dependent default. Companion
    /// to [`Self::set_glyph_cache_height`].
    #[must_use]
    pub fn glyph_cache_height(&self) -> u32 {
        // SAFETY: handle is a live Noesis::RenderDevice*; const accessor.
        unsafe { noesis_render_device_get_glyph_cache_height(self.handle.as_ptr()) }
    }
}

impl Drop for Registered {
    fn drop(&mut self) {
        // SAFETY: `handle` came from `register`. This releases only the +1
        // `_create` ref; Noesis may keep its own Ptr<> and call back against
        // `userdata` afterward, so the box is freed by `drop_userdata` from
        // `~RustRenderDevice`, not here. Freeing here is a use-after-free — an
        // intermittent MapIndices-on-freed-device SIGSEGV under SDK 3.2.13.
        unsafe {
            noesis_render_device_destroy(self.handle.as_ptr());
        }
    }
}

/// Construct a C++ `RustRenderDevice` backed by the given Rust impl. Returns
/// a [`Registered`] guard that owns both halves; drop it to tear everything
/// down.
///
/// # Panics
///
/// Panics if the C++ factory returns null (only possible on internal logic
/// errors).
pub fn register<D: RenderDevice + 'static>(device: D) -> Registered {
    // Box<dyn ...> is a fat pointer; wrap in another Box to get a stable thin
    // pointer we can pass through the C ABI as userdata.
    let outer: Box<Box<dyn RenderDevice>> = Box::new(Box::new(device));
    let userdata = Box::into_raw(outer);
    // SAFETY: VTABLE is a 'static and userdata is a freshly leaked Box.
    let handle = unsafe { noesis_render_device_create(&raw const VTABLE, userdata.cast()) };

    Registered {
        handle: NonNull::new(handle).expect("noesis_render_device_create returned null"),
        userdata: NonNull::new(userdata).expect("Box::into_raw returned null"),
    }
}