euv-core 0.52.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Detects outer compression magic on raw `.blend` bytes without decompressing.
///
/// # Arguments
///
/// - `&[u8]` - Raw input bytes read from a `.blend` file.
///
/// # Returns
///
/// - `BlendCompression` - Detected compression container (`None`, `Gzip`, or `Zstd`).
#[must_use]
pub fn detect_blend_compression(bytes: &[u8]) -> BlendCompression {
    if bytes.len() >= 2 && bytes[0..2] == BLEND_GZIP_MAGIC {
        BlendCompression::Gzip
    } else if bytes.len() >= 4 && bytes[0..4] == BLEND_ZSTD_MAGIC {
        BlendCompression::Zstd
    } else {
        BlendCompression::None
    }
}

/// Parses a fixed-width ASCII unsigned decimal integer from `digits`.
///
/// # Arguments
///
/// - `&[u8]` - ASCII digit slice.
///
/// # Returns
///
/// - `Option<u16>` - Parsed decimal integer if every byte is `'0'..='9'`.
#[must_use]
pub(crate) fn parse_ascii_u16(digits: &[u8]) -> Option<u16> {
    if digits.is_empty() {
        return None;
    }
    let mut acc: u16 = 0;
    for &b in digits {
        if !b.is_ascii_digit() {
            return None;
        }
        acc = acc.checked_mul(10)?.checked_add(u16::from(b - b'0'))?;
    }
    Some(acc)
}

/// Reads an endian-aware `u16` from `bytes` at `offset`.
///
/// # Arguments
///
/// - `&[u8]` - Source buffer.
/// - `usize` - Starting byte offset.
/// - `bool` - `true` for little-endian, `false` for big-endian.
///
/// # Returns
///
/// - `Option<u16>` - Decoded 16-bit integer if in bounds.
#[must_use]
pub(crate) fn read_endian_u16(bytes: &[u8], offset: usize, is_le: bool) -> Option<u16> {
    if offset + 2 > bytes.len() {
        return None;
    }
    let arr: [u8; 2] = [bytes[offset], bytes[offset + 1]];
    if is_le {
        Some(u16::from_le_bytes(arr))
    } else {
        Some(u16::from_be_bytes(arr))
    }
}

/// Reads an endian-aware `u32` from `bytes` at `offset`.
///
/// # Arguments
///
/// - `&[u8]` - Source buffer.
/// - `usize` - Starting byte offset.
/// - `bool` - `true` for little-endian, `false` for big-endian.
///
/// # Returns
///
/// - `Option<u32>` - Decoded 32-bit integer if in bounds.
#[must_use]
pub(crate) fn read_endian_u32(bytes: &[u8], offset: usize, is_le: bool) -> Option<u32> {
    if offset + 4 > bytes.len() {
        return None;
    }
    let arr: [u8; 4] = [
        bytes[offset],
        bytes[offset + 1],
        bytes[offset + 2],
        bytes[offset + 3],
    ];
    if is_le {
        Some(u32::from_le_bytes(arr))
    } else {
        Some(u32::from_be_bytes(arr))
    }
}

/// Reads an endian-aware `i64` from `bytes` at `offset`.
///
/// # Arguments
///
/// - `&[u8]` - Source buffer.
/// - `usize` - Starting byte offset.
/// - `bool` - `true` for little-endian, `false` for big-endian.
///
/// # Returns
///
/// - `Option<i64>` - Decoded signed 64-bit integer if in bounds.
#[must_use]
pub(crate) fn read_endian_i64(bytes: &[u8], offset: usize, is_le: bool) -> Option<i64> {
    if offset + 8 > bytes.len() {
        return None;
    }
    let arr: [u8; 8] = [
        bytes[offset],
        bytes[offset + 1],
        bytes[offset + 2],
        bytes[offset + 3],
        bytes[offset + 4],
        bytes[offset + 5],
        bytes[offset + 6],
        bytes[offset + 7],
    ];
    if is_le {
        Some(i64::from_le_bytes(arr))
    } else {
        Some(i64::from_be_bytes(arr))
    }
}

/// Rounds `offset` upward to the next 4-byte boundary.
///
/// # Arguments
///
/// - `usize` - Input offset.
///
/// # Returns
///
/// - `usize` - 4-byte-aligned offset.
#[must_use]
pub(crate) fn align_up_4(offset: usize) -> usize {
    (offset + 3) & !3
}

/// Classifies a 4-byte Blender `BHead::code` into a semantic `BlendBlockKind`.
///
/// # Arguments
///
/// - `[u8; 4]` - Raw 4-byte block code.
///
/// # Returns
///
/// - `BlendBlockKind` - Classified Blender block kind.
#[must_use]
pub(crate) fn classify_blend_code(code: [u8; 4]) -> BlendBlockKind {
    if code == BLEND_CODE_DNA1 {
        return BlendBlockKind::DnaSchema;
    }
    if code == BLEND_CODE_ENDB {
        return BlendBlockKind::EndOfFile;
    }
    match [code[0], code[1]] {
        [b'S', b'C'] if code[2] == 0 => BlendBlockKind::Scene,
        [b'G', b'R'] if code[2] == 0 => BlendBlockKind::Collection,
        [b'O', b'B'] if code[2] == 0 => BlendBlockKind::Object,
        [b'M', b'E'] if code[2] == 0 => BlendBlockKind::Mesh,
        [b'M', b'A'] if code[2] == 0 => BlendBlockKind::Material,
        [b'C', b'A'] if code[2] == 0 => BlendBlockKind::Camera,
        [b'L', b'A'] if code[2] == 0 => BlendBlockKind::Light,
        [b'A', b'R'] if code[2] == 0 => BlendBlockKind::Armature,
        [b'A', b'C'] if code[2] == 0 => BlendBlockKind::Action,
        [b'I', b'M'] if code[2] == 0 => BlendBlockKind::Image,
        [b'N', b'T'] if code[2] == 0 => BlendBlockKind::NodeTree,
        _ => BlendBlockKind::Other,
    }
}

/// Parses a Blender 2.x-4.x (12-byte) or Blender 5.0+ (17-byte large) `.blend` header.
///
/// # Arguments
///
/// - `&[u8]` - Uncompressed `.blend` byte buffer starting with `BLENDER`.
///
/// # Returns
///
/// - `Result<BlendHeader, String>` - Parsed header metadata or format error.
pub fn parse_blend_header(bytes: &[u8]) -> Result<BlendHeader, String> {
    if bytes.len() < BLEND_CLASSIC_HEADER_BYTES {
        return Err(ERR_BLEND_TOO_SHORT.to_string());
    }
    if &bytes[0..7] != BLEND_MAGIC {
        return Err(ERR_BLEND_BAD_MAGIC.to_string());
    }
    if bytes[7].is_ascii_digit() {
        if bytes.len() < BLEND_LARGE_HEADER_BYTES {
            return Err(ERR_BLEND_TOO_SHORT.to_string());
        }
        let header_size: usize = usize::from(
            parse_ascii_u16(&bytes[7..9]).ok_or_else(|| ERR_BLEND_MALFORMED_HEADER.to_string())?,
        );
        if header_size < BLEND_LARGE_HEADER_BYTES || header_size > bytes.len() {
            return Err(ERR_BLEND_MALFORMED_HEADER.to_string());
        }
        let pointer_size_bytes: u8 = match bytes[9] {
            b'-' => 8,
            b'_' => 4,
            _ => return Err(ERR_BLEND_MALFORMED_HEADER.to_string()),
        };
        let format_version: u16 = parse_ascii_u16(&bytes[10..12])
            .ok_or_else(|| ERR_BLEND_MALFORMED_HEADER.to_string())?;
        let is_little_endian: bool = match bytes[12] {
            b'v' => true,
            b'V' => false,
            _ => return Err(ERR_BLEND_MALFORMED_HEADER.to_string()),
        };
        let version_num: u16 = parse_ascii_u16(&bytes[13..17])
            .ok_or_else(|| ERR_BLEND_MALFORMED_HEADER.to_string())?;
        let version_major: u16 = version_num / 100;
        let version_minor: u16 = version_num % 100;
        Ok(BlendHeader {
            version_major,
            version_minor,
            pointer_size_bytes,
            is_little_endian,
            is_large_header_v5: true,
            header_size_bytes: header_size,
            format_version,
        })
    } else {
        let pointer_size_bytes: u8 = match bytes[7] {
            b'-' => 8,
            b'_' => 4,
            _ => return Err(ERR_BLEND_MALFORMED_HEADER.to_string()),
        };
        let is_little_endian: bool = match bytes[8] {
            b'v' => true,
            b'V' => false,
            _ => return Err(ERR_BLEND_MALFORMED_HEADER.to_string()),
        };
        let version_num: u16 =
            parse_ascii_u16(&bytes[9..12]).ok_or_else(|| ERR_BLEND_MALFORMED_HEADER.to_string())?;
        let version_major: u16 = version_num / 100;
        let version_minor: u16 = version_num % 100;
        Ok(BlendHeader {
            version_major,
            version_minor,
            pointer_size_bytes,
            is_little_endian,
            is_large_header_v5: false,
            header_size_bytes: BLEND_CLASSIC_HEADER_BYTES,
            format_version: 0,
        })
    }
}

/// Computes the byte footprint of an SDNA C field declaration given its base type size and pointer size.
///
/// # Arguments
///
/// - `&str` - SDNA field name string (e.g., `*next`, `name[66]`, `mat[4][4]`).
/// - `usize` - Base C type byte length from `TLEN`.
/// - `usize` - Pointer width in bytes (`4` or `8`).
///
/// # Returns
///
/// - `usize` - Total field size in bytes.
#[must_use]
pub(crate) fn sdna_field_byte_size(
    field_name: &str,
    base_type_size: usize,
    ptr_size: usize,
) -> usize {
    let elem_size: usize = if field_name.starts_with('*') || field_name.starts_with("(*") {
        ptr_size
    } else {
        base_type_size
    };
    let mut array_mult: usize = 1;
    let bytes: &[u8] = field_name.as_bytes();
    let mut idx: usize = 0;
    while idx < bytes.len() {
        if bytes[idx] == b'[' {
            let start: usize = idx + 1;
            let mut end: usize = start;
            while end < bytes.len() && bytes[end] != b']' {
                end += 1;
            }
            if end > start
                && let Some(dim) = parse_ascii_u16(&bytes[start..end])
            {
                array_mult = array_mult.saturating_mul(usize::from(dim));
            }
            idx = end + 1;
        } else {
            idx += 1;
        }
    }
    elem_size.saturating_mul(array_mult)
}

/// Parses a `DNA1` SDNA schema block (`SDNA`/`NAME`/`TYPE`/`TLEN`/`STRC`) and resolves `ID.name` layout.
///
/// # Arguments
///
/// - `&[u8]` - Raw `DNA1` payload bytes.
/// - `bool` - `true` for little-endian, `false` for big-endian.
/// - `usize` - Pointer width in bytes (`4` or `8`).
///
/// # Returns
///
/// - `Option<BlendDnaSchemaSummary>` - Parsed SDNA table summary or `None` if malformed.
#[must_use]
pub fn parse_blend_dna1(
    payload: &[u8],
    is_le: bool,
    ptr_size: usize,
) -> Option<BlendDnaSchemaSummary> {
    if payload.len() < 12 || payload[0..4] != BLEND_SDNA_MAGIC || payload[4..8] != BLEND_SDNA_NAME {
        return None;
    }
    let name_count: usize = read_endian_u32(payload, 8, is_le)? as usize;
    let mut cursor: usize = 12;
    let mut names: Vec<&str> = Vec::with_capacity(name_count.min(65_536));
    for _ in 0..name_count {
        let start: usize = cursor;
        while cursor < payload.len() && payload[cursor] != 0 {
            cursor += 1;
        }
        if cursor >= payload.len() {
            return None;
        }
        names.push(from_utf8(&payload[start..cursor]).unwrap_or(""));
        cursor += 1;
    }
    cursor = align_up_4(cursor);
    if cursor + 8 > payload.len() || payload[cursor..cursor + 4] != BLEND_SDNA_TYPE {
        return None;
    }
    let type_count: usize = read_endian_u32(payload, cursor + 4, is_le)? as usize;
    cursor += 8;
    let mut types: Vec<&str> = Vec::with_capacity(type_count.min(65_536));
    for _ in 0..type_count {
        let start: usize = cursor;
        while cursor < payload.len() && payload[cursor] != 0 {
            cursor += 1;
        }
        if cursor >= payload.len() {
            return None;
        }
        types.push(from_utf8(&payload[start..cursor]).unwrap_or(""));
        cursor += 1;
    }
    cursor = align_up_4(cursor);
    if cursor + 4 > payload.len() || payload[cursor..cursor + 4] != BLEND_SDNA_TLEN {
        return None;
    }
    cursor += 4;
    let mut tlens: Vec<u16> = Vec::with_capacity(type_count.min(65_536));
    for _ in 0..type_count {
        tlens.push(read_endian_u16(payload, cursor, is_le)?);
        cursor += 2;
    }
    cursor = align_up_4(cursor);
    if cursor + 8 > payload.len() || payload[cursor..cursor + 4] != BLEND_SDNA_STRC {
        return None;
    }
    let struct_count: usize = read_endian_u32(payload, cursor + 4, is_le)? as usize;
    cursor += 8;
    let mut id_name_offset: Option<usize> = None;
    let mut id_name_max_len: Option<usize> = None;
    for _ in 0..struct_count {
        let struct_type_idx: usize = usize::from(read_endian_u16(payload, cursor, is_le)?);
        let field_count: usize = usize::from(read_endian_u16(payload, cursor + 2, is_le)?);
        cursor += 4;
        let is_id_struct: bool = types.get(struct_type_idx).copied() == Some("ID");
        let mut field_offset: usize = 0;
        for _ in 0..field_count {
            let f_type_idx: usize = usize::from(read_endian_u16(payload, cursor, is_le)?);
            let f_name_idx: usize = usize::from(read_endian_u16(payload, cursor + 2, is_le)?);
            cursor += 4;
            if is_id_struct && id_name_offset.is_none() {
                let f_name: &str = names.get(f_name_idx).copied().unwrap_or("");
                let base_size: usize = usize::from(tlens.get(f_type_idx).copied().unwrap_or(0));
                let f_size: usize = sdna_field_byte_size(f_name, base_size, ptr_size);
                if f_name.starts_with(BLEND_SDNA_FIELD_NAME_PREFIX) {
                    id_name_offset = Some(field_offset);
                    id_name_max_len = Some(f_size.max(2));
                }
                field_offset = field_offset.saturating_add(f_size);
            }
        }
    }
    Some(BlendDnaSchemaSummary {
        name_count,
        type_count,
        struct_count,
        id_name_offset,
        id_name_max_len,
    })
}

/// Extracts a clean UTF-8 Blender ID name from an ID block payload, stripping the 2-byte Blender type prefix (`OB`, `ME`, `MA`, etc.).
///
/// # Arguments
///
/// - `&[u8]` - Block payload slice.
/// - `[u8; 4]` - Owning block 4-byte code.
/// - `usize` - Byte offset of `ID.name` inside the payload.
/// - `usize` - Maximum byte length of `ID.name`.
///
/// # Returns
///
/// - `Option<String>` - Extracted non-empty Blender ID name.
#[must_use]
pub(crate) fn extract_blend_id_name(
    payload: &[u8],
    code: [u8; 4],
    name_offset: usize,
    max_len: usize,
) -> Option<String> {
    if name_offset >= payload.len() {
        return None;
    }
    let slice_end: usize = (name_offset + max_len).min(payload.len());
    let raw: &[u8] = &payload[name_offset..slice_end];
    let nul_pos: usize = raw.iter().position(|b: &u8| *b == 0).unwrap_or(raw.len());
    let valid: &[u8] = &raw[..nul_pos];
    if valid.is_empty() {
        return None;
    }
    let stripped: &[u8] = if valid.len() >= 2 && valid[0] == code[0] && valid[1] == code[1] {
        &valid[2..]
    } else {
        valid
    };
    let text: &str = from_utf8(stripped).ok()?.trim();
    if text.is_empty() {
        None
    } else {
        Some(text.to_string())
    }
}

/// Inspects raw (uncompressed or gzip-compressed) `.blend` 4.x/5.x bytes without invoking an external Blender binary.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.blend` file bytes.
///
/// # Returns
///
/// - `Result<BlendInspectionReport, String>` - Complete `.blend` version, SDNA, and ID block inventory report.
pub fn inspect_blend_bytes(bytes: &[u8]) -> Result<BlendInspectionReport, String> {
    BlendInspector::inspect_bytes(bytes)
}