Skip to main content

gltforge_unity/
unity_image.rs

1use crate::unity_gltf::UnityGltf;
2
3// ─── FFI ────────────────────────────────────────────────────────────────────
4
5/// Return the number of images.
6///
7/// # Safety
8/// `ptr` must be a valid, non-null handle.
9#[unsafe(no_mangle)]
10pub unsafe extern "C" fn gltforge_image_count(ptr: *const UnityGltf) -> u32 {
11    unsafe { &*ptr }.images.len() as u32
12}
13
14/// Return a pointer to the UTF-8 name bytes for image `image_idx`.
15/// `out_len` receives the byte length. Returns null if `image_idx` is out of range.
16///
17/// # Safety
18/// `ptr` must be a valid, non-null handle. `out_len` may be null.
19#[unsafe(no_mangle)]
20pub unsafe extern "C" fn gltforge_image_name(
21    ptr: *const UnityGltf,
22    image_idx: u32,
23    out_len: *mut u32,
24) -> *const u8 {
25    unsafe { crate::write_name({ &*ptr }.images.get(&image_idx).map(|i| &i.name), out_len) }
26}
27
28/// Return a pointer to the UTF-8 URI bytes for image `image_idx`.
29/// `out_len` receives the byte length.
30/// Returns null if `image_idx` is out of range or the image is buffer-view-embedded.
31///
32/// # Safety
33/// `ptr` must be a valid, non-null handle. `out_len` may be null.
34#[unsafe(no_mangle)]
35pub unsafe extern "C" fn gltforge_image_uri(
36    ptr: *const UnityGltf,
37    image_idx: u32,
38    out_len: *mut u32,
39) -> *const u8 {
40    unsafe {
41        crate::write_name(
42            { &*ptr }
43                .images
44                .get(&image_idx)
45                .and_then(|i| i.uri.as_ref()),
46            out_len,
47        )
48    }
49}
50
51/// Return a pointer to the raw encoded image bytes (PNG, JPEG, …) for a
52/// buffer-view-embedded image. `out_len` receives the byte count.
53/// Returns null if `image_idx` is out of range or the image is URI-based.
54///
55/// # Safety
56/// `ptr` must be a valid, non-null handle. `out_len` may be null.
57/// The returned pointer is valid for the lifetime of the [`UnityGltf`] handle.
58#[unsafe(no_mangle)]
59pub unsafe extern "C" fn gltforge_image_bytes(
60    ptr: *const UnityGltf,
61    image_idx: u32,
62    out_len: *mut u32,
63) -> *const u8 {
64    let image = unsafe { &*ptr }.images.get(&image_idx);
65    match image.and_then(|i| i.bytes.as_ref()) {
66        Some(bytes) => {
67            if !out_len.is_null() {
68                unsafe { *out_len = bytes.len() as u32 };
69            }
70            bytes.as_ptr()
71        }
72        None => {
73            if !out_len.is_null() {
74                unsafe { *out_len = 0 };
75            }
76            std::ptr::null()
77        }
78    }
79}