Skip to main content

euv_core/game/engine3d/blend/scene/
fn.rs

1use super::*;
2
3/// Decodes a minimal uncompressed or RLE-compressed Truevision TGA image into RGBA8 pixels.
4///
5/// # Arguments
6///
7/// - `&[u8]` - Raw TGA byte slice.
8///
9/// # Returns
10///
11/// - `Result<(u32, u32, Vec<u8>), String>` - Decoded `(width, height, rgba8)` tuple or format error.
12fn decode_tga_rgba(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), String> {
13    if bytes.len() < 18 {
14        return Err(ERR_BLEND_TGA_INVALID.to_string());
15    }
16    let id_len: usize = usize::from(bytes[0]);
17    let color_map_type: u8 = bytes[1];
18    let image_type: u8 = bytes[2];
19    let width: usize = usize::from(u16::from_le_bytes([bytes[12], bytes[13]]));
20    let height: usize = usize::from(u16::from_le_bytes([bytes[14], bytes[15]]));
21    let bpp: usize = usize::from(bytes[16]);
22    let descriptor: u8 = bytes[17];
23    let zero_dims: bool = width == 0 || height == 0;
24    let huge_dims: bool = width > 16_384 || height > 16_384;
25    let bad_dims: bool = zero_dims || huge_dims;
26    if color_map_type != 0 || bad_dims {
27        return Err(ERR_BLEND_TGA_INVALID.to_string());
28    }
29    let bytes_per_pixel: usize = match bpp {
30        8 => 1,
31        24 => 3,
32        32 => 4,
33        _ => return Err(ERR_BLEND_TGA_INVALID.to_string()),
34    };
35    let is_rle: bool = match image_type {
36        2 | 3 => false,
37        10 | 11 => true,
38        _ => return Err(ERR_BLEND_TGA_INVALID.to_string()),
39    };
40    let mut cursor: usize = 18 + id_len;
41    if cursor > bytes.len() {
42        return Err(ERR_BLEND_TGA_INVALID.to_string());
43    }
44    let total_pixels: usize = width.saturating_mul(height);
45    let mut raw_rgba: Vec<u8> = Vec::with_capacity(total_pixels.saturating_mul(4));
46    let push_pixel: fn(&mut Vec<u8>, &[u8], usize) =
47        |dst: &mut Vec<u8>, src: &[u8], bpp_bytes: usize| match bpp_bytes {
48            1 => dst.extend_from_slice(&[src[0], src[0], src[0], 255]),
49            3 => dst.extend_from_slice(&[src[2], src[1], src[0], 255]),
50            _ => dst.extend_from_slice(&[src[2], src[1], src[0], src[3]]),
51        };
52    if !is_rle {
53        let needed: usize = total_pixels.saturating_mul(bytes_per_pixel);
54        if cursor.saturating_add(needed) > bytes.len() {
55            return Err(ERR_BLEND_TGA_INVALID.to_string());
56        }
57        for p_idx in 0..total_pixels {
58            let off: usize = cursor + p_idx * bytes_per_pixel;
59            push_pixel(
60                &mut raw_rgba,
61                &bytes[off..(off + bytes_per_pixel)],
62                bytes_per_pixel,
63            );
64        }
65    } else {
66        let mut decoded_pixels: usize = 0;
67        while decoded_pixels < total_pixels {
68            if cursor >= bytes.len() {
69                return Err(ERR_BLEND_TGA_INVALID.to_string());
70            }
71            let packet: u8 = bytes[cursor];
72            cursor += 1;
73            let run_len: usize = usize::from(packet & 0x7f) + 1;
74            if (packet & 0x80) != 0 {
75                if cursor + bytes_per_pixel > bytes.len() {
76                    return Err(ERR_BLEND_TGA_INVALID.to_string());
77                }
78                let px: &[u8] = &bytes[cursor..(cursor + bytes_per_pixel)];
79                cursor += bytes_per_pixel;
80                for _ in 0..run_len.min(total_pixels - decoded_pixels) {
81                    push_pixel(&mut raw_rgba, px, bytes_per_pixel);
82                    decoded_pixels += 1;
83                }
84            } else {
85                for _ in 0..run_len.min(total_pixels - decoded_pixels) {
86                    if cursor + bytes_per_pixel > bytes.len() {
87                        return Err(ERR_BLEND_TGA_INVALID.to_string());
88                    }
89                    push_pixel(
90                        &mut raw_rgba,
91                        &bytes[cursor..(cursor + bytes_per_pixel)],
92                        bytes_per_pixel,
93                    );
94                    cursor += bytes_per_pixel;
95                    decoded_pixels += 1;
96                }
97            }
98        }
99    }
100    let top_origin: bool = (descriptor & 0x20) != 0;
101    if !top_origin {
102        let row_bytes: usize = width * 4;
103        let mut flipped: Vec<u8> = vec![0u8; raw_rgba.len()];
104        for row in 0..height {
105            let src_off: usize = (height - 1 - row) * row_bytes;
106            let dst_off: usize = row * row_bytes;
107            flipped[dst_off..(dst_off + row_bytes)]
108                .copy_from_slice(&raw_rgba[src_off..(src_off + row_bytes)]);
109        }
110        return Ok((width as u32, height as u32, flipped));
111    }
112    Ok((width as u32, height as u32, raw_rgba))
113}
114
115/// Converts a Blender Z-up 4x4 column-major matrix into Engine Y-up space via similarity transform `C * M * C^-1`.
116///
117/// # Arguments
118///
119/// - `Mat4` - Matrix in Blender Z-up coordinates.
120///
121/// # Returns
122///
123/// - `Mat4` - Equivalent matrix in Engine Y-up coordinates.
124#[must_use]
125fn blend_mat4_to_y_up(mat_blend: Mat4) -> Mat4 {
126    let c_to_y: Mat4 = Mat4::blender_z_up_to_y_up();
127    let c_to_z: Mat4 = Mat4::y_up_to_blender_z_up();
128    c_to_y.mul(mat_blend).mul(c_to_z)
129}
130
131/// Converts a Blender Z-up XYZ Euler rotation triple (radians) into a Blender Z-up unit quaternion.
132///
133/// # Arguments
134///
135/// - `[f32; 3]` - Euler XYZ angles `(rx, ry, rz)` in radians.
136///
137/// # Returns
138///
139/// - `Quat` - Equivalent unit quaternion in Blender Z-up space.
140#[must_use]
141fn blend_euler_xyz_to_quat(rot: [f32; 3]) -> Quat {
142    let qx: Quat = Quat::from_axis_angle(Vec3::new(1.0, 0.0, 0.0), rot[0]);
143    let qy: Quat = Quat::from_axis_angle(Vec3::new(0.0, 1.0, 0.0), rot[1]);
144    let qz: Quat = Quat::from_axis_angle(Vec3::new(0.0, 0.0, 1.0), rot[2]);
145    qz.mul_quat(qy).mul_quat(qx).normalize()
146}
147
148/// Reads a column-major 4x4 matrix from an inline `float[4][4]` SDNA field.
149///
150/// # Arguments
151///
152/// - `&BlendStructView<'_>` - Struct view owning the matrix field.
153/// - `&str` - Clean field name (`"obmat"`, `"arm_mat"`, etc.).
154///
155/// # Returns
156///
157/// - `Option<Mat4>` - Non-zero parsed 4x4 matrix, or `None` if missing or all-zero.
158#[must_use]
159fn read_blend_mat4(view: &BlendStructView<'_>, field_name: &str) -> Option<Mat4> {
160    let vals: Vec<f32> = view.read_f32_array(field_name)?;
161    if vals.len() < 16 {
162        return None;
163    }
164    let mut sum_abs: f32 = 0.0;
165    let mut arr: [f32; 16] = [0.0; 16];
166    for idx in 0..16 {
167        arr[idx] = vals[idx];
168        sum_abs += vals[idx].abs();
169    }
170    if sum_abs < 1e-6 {
171        return None;
172    }
173    Some(Mat4::from_cols_array(arr))
174}
175
176/// Extracts all packed `Image` (`IM`) blocks into `Texture2D3D` entries and maps `image_old_addr -> texture_index`.
177///
178/// # Arguments
179///
180/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
181///
182/// # Returns
183///
184/// - `(Vec<Texture2D3D>, HashMap<u64, u32>)` - Decoded textures and pointer-to-index map.
185fn extract_blend_images(archive: &BlendArchiveView<'_>) -> (Vec<Texture2D3D>, HashMap<u64, u32>) {
186    let mut textures: Vec<Texture2D3D> = Vec::new();
187    let mut addr_to_tex: HashMap<u64, u32> = HashMap::new();
188    for block in archive.get_blocks().iter() {
189        if block.get_kind() != BlendBlockKind::Image {
190            continue;
191        }
192        let Some(img_view) = archive.block_struct_view(block, None, 0) else {
193            continue;
194        };
195        let tex_name: String = img_view
196            .id_name()
197            .unwrap_or_else(|| format!("blend_image_{}", textures.len()));
198        let mut packed_view: Option<BlendStructView<'_>> =
199            img_view.follow_ptr(FLD_PACKEDFILE, Some(TYPE_PACKED_FILE));
200        if packed_view.is_none() {
201            let packed_items: Vec<BlendStructView<'_>> =
202                img_view.follow_list_base(FLD_PACKEDFILES, Some(TYPE_IMAGE_PACKED_FILE));
203            if let Some(first_ipf) = packed_items.first() {
204                packed_view = first_ipf.follow_ptr(FLD_PACKEDFILE, Some(TYPE_PACKED_FILE));
205            }
206        }
207        let Some(pf_view) = packed_view else {
208            continue;
209        };
210        let declared_size: usize = pf_view.read_i32(FLD_SIZE).unwrap_or(0).max(0) as usize;
211        let data_ptr: u64 = pf_view.read_ptr(FLD_DATA).unwrap_or(0);
212        let Some(data_block) = archive.block_by_address(data_ptr) else {
213            continue;
214        };
215        let raw_payload: &[u8] = archive.block_payload(data_block);
216        let img_bytes: &[u8] = if declared_size > 0 && declared_size <= raw_payload.len() {
217            &raw_payload[..declared_size]
218        } else {
219            raw_payload
220        };
221        let decoded: Option<Texture2D3D> =
222            Texture2D3D::from_encoded_bytes(&tex_name, img_bytes, TextureColorSpace::Srgb, true)
223                .ok()
224                .or_else(|| {
225                    decode_tga_rgba(img_bytes).ok().and_then(
226                        |(w, h, pixels): (u32, u32, Vec<u8>)| {
227                            Texture2D3D::from_rgba8(
228                                &tex_name,
229                                w,
230                                h,
231                                pixels,
232                                TextureColorSpace::Srgb,
233                                true,
234                            )
235                            .ok()
236                        },
237                    )
238                });
239        if let Some(tex) = decoded {
240            let tex_idx: u32 = textures.len() as u32;
241            textures.push(tex);
242            let _: Option<u32> = addr_to_tex.insert(block.get_old_address(), tex_idx);
243        }
244    }
245    (textures, addr_to_tex)
246}
247
248/// Reads a scalar float default value from a `bNodeSocket`'s `default_value` pointer (`bNodeSocketValueFloat`).
249///
250/// # Arguments
251///
252/// - `&BlendStructView<'_>` - Socket struct view (`bNodeSocket`).
253///
254/// # Returns
255///
256/// - `Option<f32>` - Decoded scalar float default value.
257#[must_use]
258fn read_socket_float(sock: &BlendStructView<'_>) -> Option<f32> {
259    let val_view: BlendStructView<'_> =
260        sock.follow_ptr(FLD_DEFAULT_VALUE, Some(TYPE_SOCK_VAL_FLOAT))?;
261    val_view.read_f32(FLD_VALUE)
262}
263
264/// Reads an RGBA float4 default value from a `bNodeSocket`'s `default_value` pointer (`bNodeSocketValueRGBA`).
265///
266/// # Arguments
267///
268/// - `&BlendStructView<'_>` - Socket struct view (`bNodeSocket`).
269///
270/// # Returns
271///
272/// - `Option<[f32; 4]>` - Decoded RGBA color tuple.
273#[must_use]
274fn read_socket_rgba(sock: &BlendStructView<'_>) -> Option<[f32; 4]> {
275    let val_view: BlendStructView<'_> =
276        sock.follow_ptr(FLD_DEFAULT_VALUE, Some(TYPE_SOCK_VAL_RGBA))?;
277    let arr: Vec<f32> = val_view.read_f32_array(FLD_VALUE)?;
278    if arr.len() >= 4 {
279        Some([arr[0], arr[1], arr[2], arr[3]])
280    } else if arr.len() == 3 {
281        Some([arr[0], arr[1], arr[2], 1.0])
282    } else {
283        None
284    }
285}
286
287/// Resolves an image texture index linked to a `ShaderNodeTexImage` node view.
288///
289/// # Arguments
290///
291/// - `&BlendStructView<'_>` - Source `bNode` view.
292/// - `&HashMap<u64, u32>` - Map from `Image` `old_address` to texture index.
293///
294/// # Returns
295///
296/// - `Option<u32>` - Texture index if the node is an Image Texture with a resolved packed image.
297#[must_use]
298fn resolve_tex_image_node(
299    node: &BlendStructView<'_>,
300    image_to_tex: &HashMap<u64, u32>,
301) -> Option<u32> {
302    let idname: String = node.read_cstr(FLD_IDNAME).unwrap_or_default();
303    let ntype: i32 = node.read_i32(FLD_TYPE).unwrap_or(-1);
304    if idname != BLEND_NODE_ID_TEX_IMAGE && ntype != BLEND_NODE_TYPE_TEX_IMAGE {
305        return None;
306    }
307    let img_ptr: u64 = node.read_ptr(SDNA_FIELD_ID)?;
308    image_to_tex.get(&img_ptr).copied()
309}
310
311/// Resolves the `old_address` of the block owning a `BlendStructView` by locating its payload start inside the archive.
312///
313/// # Arguments
314///
315/// - `&BlendStructView<'_>` - Struct view referencing a block payload.
316/// - `&HashMap<usize, u64>` - Precomputed map from payload start offset to `old_address`.
317///
318/// # Returns
319///
320/// - `u64` - Matching `old_address` or `0` if not a block root.
321#[must_use]
322fn resolve_view_address(view: &BlendStructView<'_>, offset_to_addr: &HashMap<usize, u64>) -> u64 {
323    let base_ptr: usize = view.get_archive().get_data().as_ptr() as usize;
324    let slice_ptr: usize = view.get_bytes().as_ptr() as usize;
325    let rel_off: usize = slice_ptr.saturating_sub(base_ptr);
326    offset_to_addr.get(&rel_off).copied().unwrap_or(0)
327}
328
329/// Extracts `Material` (`MA`) blocks and their `bNodeTree` Principled BSDF shader graphs into `PrincipledMaterial3D`s.
330///
331/// # Arguments
332///
333/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
334/// - `&HashMap<usize, u64>` - Payload offset to `old_address` lookup map.
335/// - `&HashMap<u64, u32>` - Image `old_address` to texture index map.
336/// - `&mut [Texture2D3D]` - Mutable texture table to update color space tags (`Linear`/`NormalTangent`).
337///
338/// # Returns
339///
340/// - `(Vec<PrincipledMaterial3D>, HashMap<u64, u32>)` - Extracted materials and pointer-to-index map.
341fn extract_blend_materials(
342    archive: &BlendArchiveView<'_>,
343    offset_to_addr: &HashMap<usize, u64>,
344    image_to_tex: &HashMap<u64, u32>,
345    textures: &mut [Texture2D3D],
346) -> (Vec<PrincipledMaterial3D>, HashMap<u64, u32>) {
347    let mut materials: Vec<PrincipledMaterial3D> = Vec::new();
348    let mut addr_to_mat: HashMap<u64, u32> = HashMap::new();
349    for block in archive.get_blocks().iter() {
350        if block.get_kind() != BlendBlockKind::Material {
351            continue;
352        }
353        let Some(mat_view) = archive.block_struct_view(block, None, 0) else {
354            continue;
355        };
356        let mat_name: String = mat_view
357            .id_name()
358            .unwrap_or_else(|| format!("Material_{}", materials.len()));
359        let mut mat: PrincipledMaterial3D = PrincipledMaterial3D::default();
360        mat.set_name(mat_name);
361        let legacy_r: f32 = mat_view.read_f32("r").unwrap_or(0.8);
362        let legacy_g: f32 = mat_view.read_f32("g").unwrap_or(0.8);
363        let legacy_b: f32 = mat_view.read_f32("b").unwrap_or(0.8);
364        let legacy_a: f32 = mat_view.read_f32("a").unwrap_or(1.0);
365        mat.set_base_color_factor([legacy_r, legacy_g, legacy_b, legacy_a]);
366        if let Some(metal) = mat_view.read_f32(FLD_METALLIC) {
367            mat.set_metallic_factor(metal.clamp(0.0, 1.0));
368        }
369        if let Some(rough) = mat_view.read_f32(FLD_ROUGHNESS) {
370            mat.set_roughness_factor(rough.clamp(0.04, 1.0));
371        }
372        if legacy_a < 0.999 {
373            mat.set_alpha_mode(AlphaMode3D::Blend);
374        }
375        let ntree_opt: Option<BlendStructView<'_>> = mat_view
376            .follow_ptr(FLD_NODETREE, Some(TYPE_BNODE_TREE))
377            .or_else(|| mat_view.read_embedded(FLD_NODETREE));
378        if let Some(ntree) = ntree_opt {
379            let nodes: Vec<BlendStructView<'_>> =
380                ntree.follow_list_base(FLD_NODES, Some(TYPE_BNODE));
381            let links: Vec<BlendStructView<'_>> =
382                ntree.follow_list_base(FLD_LINKS, Some(TYPE_BNODE_LINK));
383            let mut to_sock_to_from_node: HashMap<u64, u64> = HashMap::new();
384            for link in links.iter() {
385                let to_sock: u64 = link.read_ptr(FLD_TOSOCK).unwrap_or(0);
386                let from_node: u64 = link.read_ptr(FLD_FROMNODE).unwrap_or(0);
387                if to_sock != 0 && from_node != 0 {
388                    let _: Option<u64> = to_sock_to_from_node.insert(to_sock, from_node);
389                }
390            }
391            let mut addr_to_node: HashMap<u64, BlendStructView<'_>> = HashMap::new();
392            let mut principled_node: Option<BlendStructView<'_>> = None;
393            for node in nodes.iter() {
394                let node_addr: u64 = resolve_view_address(node, offset_to_addr);
395                if node_addr != 0 {
396                    let _: Option<BlendStructView<'_>> = addr_to_node.insert(node_addr, *node);
397                }
398                let idname: String = node.read_cstr(FLD_IDNAME).unwrap_or_default();
399                let ntype: i32 = node.read_i32(FLD_TYPE).unwrap_or(-1);
400                if idname == BLEND_NODE_ID_PRINCIPLED || ntype == BLEND_NODE_TYPE_PRINCIPLED {
401                    principled_node = Some(*node);
402                }
403            }
404            if let Some(bsdf) = principled_node {
405                let sockets: Vec<BlendStructView<'_>> =
406                    bsdf.follow_list_base(FLD_INPUTS, Some(TYPE_BNODE_SOCKET));
407                for sock in sockets.iter() {
408                    let sock_name: String = sock.read_cstr(SDNA_FIELD_NAME).unwrap_or_default();
409                    let sock_addr: u64 = resolve_view_address(sock, offset_to_addr);
410                    let linked_node: Option<BlendStructView<'_>> = to_sock_to_from_node
411                        .get(&sock_addr)
412                        .and_then(|from_addr: &u64| addr_to_node.get(from_addr).copied());
413                    let linked_tex: Option<u32> =
414                        linked_node.as_ref().and_then(|node: &BlendStructView<'_>| {
415                            resolve_tex_image_node(node, image_to_tex)
416                        });
417                    match sock_name.as_str() {
418                        SOCK_BASE_COLOR => {
419                            if let Some(rgba) = read_socket_rgba(sock) {
420                                mat.set_base_color_factor(rgba);
421                            }
422                            if let Some(t_idx) = linked_tex {
423                                mat.set_base_color_texture(Some(TextureSlot3D::from_index(
424                                    t_idx, 0,
425                                )));
426                            }
427                        }
428                        SOCK_METALLIC => {
429                            if let Some(val) = read_socket_float(sock) {
430                                mat.set_metallic_factor(val.clamp(0.0, 1.0));
431                            }
432                            if let Some(t_idx) = linked_tex {
433                                if let Some(tex) = textures.get_mut(t_idx as usize) {
434                                    tex.set_color_space(TextureColorSpace::Linear);
435                                }
436                                mat.set_metallic_roughness_texture(Some(
437                                    TextureSlot3D::from_index(t_idx, 0),
438                                ));
439                            }
440                        }
441                        SOCK_ROUGHNESS => {
442                            if let Some(val) = read_socket_float(sock) {
443                                mat.set_roughness_factor(val.clamp(0.04, 1.0));
444                            }
445                            if let Some(t_idx) = linked_tex {
446                                if let Some(tex) = textures.get_mut(t_idx as usize) {
447                                    tex.set_color_space(TextureColorSpace::Linear);
448                                }
449                                mat.set_metallic_roughness_texture(Some(
450                                    TextureSlot3D::from_index(t_idx, 0),
451                                ));
452                            }
453                        }
454                        "IOR" => {
455                            if let Some(val) = read_socket_float(sock) {
456                                mat.set_ior(val.max(1.0));
457                            }
458                        }
459                        SOCK_ALPHA => {
460                            if let Some(val) = read_socket_float(sock) {
461                                let mut bc: [f32; 4] = mat.get_base_color_factor();
462                                bc[3] = val.clamp(0.0, 1.0);
463                                mat.set_base_color_factor(bc);
464                                if bc[3] < 0.999 {
465                                    mat.set_alpha_mode(AlphaMode3D::Blend);
466                                }
467                            }
468                        }
469                        SOCK_EMISSION_3X | SOCK_EMISSION_COLOR => {
470                            if let Some(rgba) = read_socket_rgba(sock) {
471                                mat.set_emissive_factor([rgba[0], rgba[1], rgba[2]]);
472                            }
473                            if let Some(t_idx) = linked_tex {
474                                mat.set_emissive_texture(Some(TextureSlot3D::from_index(t_idx, 0)));
475                            }
476                        }
477                        SOCK_EMISSION_STRENGTH => {
478                            if let Some(val) = read_socket_float(sock) {
479                                mat.set_emissive_strength(val.max(0.0));
480                            }
481                        }
482                        SOCK_CLEARCOAT_3X | SOCK_COAT_WEIGHT => {
483                            if let Some(val) = read_socket_float(sock) {
484                                mat.set_clearcoat_factor(val.clamp(0.0, 1.0));
485                            }
486                            if let Some(t_idx) = linked_tex {
487                                if let Some(tex) = textures.get_mut(t_idx as usize) {
488                                    tex.set_color_space(TextureColorSpace::Linear);
489                                }
490                                mat.set_clearcoat_texture(Some(TextureSlot3D::from_index(
491                                    t_idx, 0,
492                                )));
493                            }
494                        }
495                        SOCK_CLEARCOAT_ROUGH_3X | SOCK_COAT_ROUGHNESS => {
496                            if let Some(val) = read_socket_float(sock) {
497                                mat.set_clearcoat_roughness_factor(val.clamp(0.0, 1.0));
498                            }
499                            if let Some(t_idx) = linked_tex {
500                                if let Some(tex) = textures.get_mut(t_idx as usize) {
501                                    tex.set_color_space(TextureColorSpace::Linear);
502                                }
503                                mat.set_clearcoat_roughness_texture(Some(
504                                    TextureSlot3D::from_index(t_idx, 0),
505                                ));
506                            }
507                        }
508                        SOCK_SHEEN_3X | SOCK_SHEEN_WEIGHT => {
509                            if let Some(val) = read_socket_float(sock) {
510                                let clamped: f32 = val.clamp(0.0, 1.0);
511                                if clamped > 0.0 {
512                                    mat.set_sheen_color_factor([clamped, clamped, clamped]);
513                                }
514                            }
515                        }
516                        SOCK_SHEEN_TINT => {
517                            if let Some(rgba) = read_socket_rgba(sock) {
518                                mat.set_sheen_color_factor([rgba[0], rgba[1], rgba[2]]);
519                            }
520                        }
521                        SOCK_SHEEN_ROUGHNESS => {
522                            if let Some(val) = read_socket_float(sock) {
523                                mat.set_sheen_roughness_factor(val.clamp(0.0, 1.0));
524                            }
525                        }
526                        SOCK_SPECULAR_3X | SOCK_SPECULAR_IOR_LEVEL => {
527                            if let Some(val) = read_socket_float(sock) {
528                                mat.set_specular_factor((val * 2.0).clamp(0.0, 2.0));
529                            }
530                        }
531                        SOCK_TRANSMISSION_3X | SOCK_TRANSMISSION_WEIGHT => {
532                            if let Some(val) = read_socket_float(sock) {
533                                mat.set_transmission_factor(val.clamp(0.0, 1.0));
534                            }
535                            if let Some(t_idx) = linked_tex {
536                                if let Some(tex) = textures.get_mut(t_idx as usize) {
537                                    tex.set_color_space(TextureColorSpace::Linear);
538                                }
539                                mat.set_transmission_texture(Some(TextureSlot3D::from_index(
540                                    t_idx, 0,
541                                )));
542                            }
543                        }
544                        SOCK_NORMAL => {
545                            if let Some(src_node) = linked_node {
546                                let src_id: String =
547                                    src_node.read_cstr(FLD_IDNAME).unwrap_or_default();
548                                let src_ty: i32 = src_node.read_i32(FLD_TYPE).unwrap_or(-1);
549                                if src_id == BLEND_NODE_ID_NORMAL_MAP
550                                    || src_ty == BLEND_NODE_TYPE_NORMAL_MAP
551                                {
552                                    let nm_socks: Vec<BlendStructView<'_>> = src_node
553                                        .follow_list_base(FLD_INPUTS, Some(TYPE_BNODE_SOCKET));
554                                    for nm_sock in nm_socks.iter() {
555                                        let nm_name: String =
556                                            nm_sock.read_cstr(SDNA_FIELD_NAME).unwrap_or_default();
557                                        if nm_name == SOCK_STRENGTH
558                                            && let Some(str_val) = read_socket_float(nm_sock)
559                                        {
560                                            mat.set_normal_scale(str_val.max(0.0));
561                                        }
562                                        if nm_name == SOCK_COLOR {
563                                            let nm_addr: u64 =
564                                                resolve_view_address(nm_sock, offset_to_addr);
565                                            if let Some(tex_node) = to_sock_to_from_node
566                                                .get(&nm_addr)
567                                                .and_then(|a: &u64| addr_to_node.get(a))
568                                                && let Some(t_idx) =
569                                                    resolve_tex_image_node(tex_node, image_to_tex)
570                                            {
571                                                if let Some(tex) = textures.get_mut(t_idx as usize)
572                                                {
573                                                    tex.set_color_space(
574                                                        TextureColorSpace::NormalTangent,
575                                                    );
576                                                }
577                                                mat.set_normal_texture(Some(
578                                                    TextureSlot3D::from_index(t_idx, 0),
579                                                ));
580                                            }
581                                        }
582                                    }
583                                } else if let Some(t_idx) = linked_tex {
584                                    if let Some(tex) = textures.get_mut(t_idx as usize) {
585                                        tex.set_color_space(TextureColorSpace::NormalTangent);
586                                    }
587                                    mat.set_normal_texture(Some(TextureSlot3D::from_index(
588                                        t_idx, 0,
589                                    )));
590                                }
591                            }
592                        }
593                        _ => {}
594                    }
595                }
596            }
597        }
598        let mat_idx: u32 = materials.len() as u32;
599        materials.push(mat);
600        let _: Option<u32> = addr_to_mat.insert(block.get_old_address(), mat_idx);
601    }
602    (materials, addr_to_mat)
603}
604
605/// Extracts `Camera` (`CA`) blocks into `ImportedCamera3D` entries and maps `camera_old_addr -> camera_index`.
606///
607/// # Arguments
608///
609/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
610///
611/// # Returns
612///
613/// - `(Vec<ImportedCamera3D>, HashMap<u64, u32>)` - Extracted cameras and pointer-to-index map.
614fn extract_blend_cameras(
615    archive: &BlendArchiveView<'_>,
616) -> (Vec<ImportedCamera3D>, HashMap<u64, u32>) {
617    let mut cameras: Vec<ImportedCamera3D> = Vec::new();
618    let mut addr_to_cam: HashMap<u64, u32> = HashMap::new();
619    for block in archive.get_blocks().iter() {
620        if block.get_kind() != BlendBlockKind::Camera {
621            continue;
622        }
623        let Some(cam_view) = archive.block_struct_view(block, None, 0) else {
624            continue;
625        };
626        let name: String = cam_view
627            .id_name()
628            .unwrap_or_else(|| format!("Camera_{}", cameras.len()));
629        let cam_type: i32 = cam_view.read_i32(FLD_TYPE).unwrap_or(0);
630        let znear: f32 = cam_view
631            .read_f32(FLD_CLIP_START)
632            .or_else(|| cam_view.read_f32(FLD_CLIPSTA))
633            .unwrap_or(BLEND_DEFAULT_CLIP_START)
634            .max(1e-4);
635        let zfar: f32 = cam_view
636            .read_f32(FLD_CLIP_END)
637            .or_else(|| cam_view.read_f32(FLD_CLIPEND))
638            .unwrap_or(BLEND_DEFAULT_CLIP_END)
639            .max(znear + 0.1);
640        let projection: GltfCameraProjection = if cam_type == 1 {
641            let ortho_scale: f32 = cam_view
642                .read_f32(FLD_ORTHO_SCALE)
643                .unwrap_or(BLEND_DEFAULT_ORTHO_SCALE)
644                .max(1e-3);
645            GltfCameraProjection::Orthographic {
646                xmag: ortho_scale * 0.5,
647                ymag: ortho_scale * 0.5,
648                znear,
649                zfar,
650            }
651        } else {
652            let lens: f32 = cam_view
653                .read_f32(FLD_LENS)
654                .unwrap_or(BLEND_DEFAULT_CAMERA_LENS_MM)
655                .max(1.0);
656            let sensor_x: f32 = cam_view
657                .read_f32(FLD_SENSOR_X)
658                .unwrap_or(BLEND_DEFAULT_SENSOR_X_MM)
659                .max(1.0);
660            let sensor_y: f32 = cam_view
661                .read_f32(FLD_SENSOR_Y)
662                .unwrap_or(BLEND_DEFAULT_SENSOR_Y_MM)
663                .max(1.0);
664            let yfov_rad: f32 = 2.0 * ((sensor_y * 0.5) / lens).atan();
665            GltfCameraProjection::Perspective {
666                yfov_rad: yfov_rad.clamp(0.05, PI - 0.05),
667                aspect_ratio: Some((sensor_x / sensor_y).max(0.1)),
668                znear,
669                zfar: Some(zfar),
670            }
671        };
672        let cam_idx: u32 = cameras.len() as u32;
673        cameras.push(ImportedCamera3D { name, projection });
674        let _: Option<u32> = addr_to_cam.insert(block.get_old_address(), cam_idx);
675    }
676    (cameras, addr_to_cam)
677}
678
679/// Extracts `Light`/`Lamp` (`LA`) blocks into `ImportedLight3D` entries and maps `light_old_addr -> light_index`.
680///
681/// # Arguments
682///
683/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
684///
685/// # Returns
686///
687/// - `(Vec<ImportedLight3D>, HashMap<u64, u32>)` - Extracted lights and pointer-to-index map.
688fn extract_blend_lights(
689    archive: &BlendArchiveView<'_>,
690) -> (Vec<ImportedLight3D>, HashMap<u64, u32>) {
691    let mut lights: Vec<ImportedLight3D> = Vec::new();
692    let mut addr_to_light: HashMap<u64, u32> = HashMap::new();
693    for block in archive.get_blocks().iter() {
694        if block.get_kind() != BlendBlockKind::Light {
695            continue;
696        }
697        let Some(light_view) = archive.block_struct_view(block, None, 0) else {
698            continue;
699        };
700        let name: String = light_view
701            .id_name()
702            .unwrap_or_else(|| format!("Light_{}", lights.len()));
703        let ltype: i32 = light_view.read_i32(FLD_TYPE).unwrap_or(BLEND_LIGHT_POINT);
704        let color: Vec3 = Vec3::new(
705            light_view.read_f32("r").unwrap_or(1.0).max(0.0),
706            light_view.read_f32("g").unwrap_or(1.0).max(0.0),
707            light_view.read_f32("b").unwrap_or(1.0).max(0.0),
708        );
709        let intensity: f32 = light_view.read_f32(FLD_ENERGY).unwrap_or(10.0).max(0.0);
710        let range: Option<f32> = light_view
711            .read_f32(FLD_CUTOFF_DISTANCE)
712            .or_else(|| light_view.read_f32(FLD_DIST))
713            .filter(|v: &f32| *v > 0.0 && v.is_finite());
714        let kind: GltfLightKind = match ltype {
715            BLEND_LIGHT_SUN => GltfLightKind::Directional,
716            BLEND_LIGHT_SPOT => {
717                let outer_cone: f32 = (light_view.read_f32(FLD_SPOTSIZE).unwrap_or(FRAC_PI_3)
718                    * 0.5)
719                    .clamp(0.01, FRAC_PI_2);
720                let blend: f32 = light_view
721                    .read_f32(FLD_SPOTBLEND)
722                    .unwrap_or(0.15)
723                    .clamp(0.0, 1.0);
724                let inner_cone: f32 = (outer_cone * (1.0 - blend)).max(0.0);
725                GltfLightKind::Spot {
726                    range,
727                    inner_cone_angle: inner_cone,
728                    outer_cone_angle: outer_cone,
729                }
730            }
731            BLEND_LIGHT_AREA => {
732                let width: f32 = light_view.read_f32(FLD_AREA_SIZE).unwrap_or(1.0).max(0.01);
733                let height: f32 = light_view
734                    .read_f32(FLD_AREA_SIZEY)
735                    .filter(|v: &f32| *v > 0.0)
736                    .unwrap_or(width);
737                GltfLightKind::Area { width, height }
738            }
739            _ => GltfLightKind::Point { range },
740        };
741        let light_idx: u32 = lights.len() as u32;
742        lights.push(ImportedLight3D {
743            name,
744            color,
745            intensity,
746            kind,
747        });
748        let _: Option<u32> = addr_to_light.insert(block.get_old_address(), light_idx);
749    }
750    (lights, addr_to_light)
751}
752
753/// Reads the `CustomDataLayer` array descriptors from an embedded Blender `CustomData` struct (`vdata`, `ldata`, `pdata`).
754///
755/// # Arguments
756///
757/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
758/// - `&BlendStructView<'_>` - Owning `Mesh` struct view.
759/// - `&str` - Embedded `CustomData` field name (`vdata`, `ldata`, or `pdata`).
760///
761/// # Returns
762///
763/// - `Vec<(i32, String, u64)>` - Tuples `(layer_type, layer_name, data_old_address)`.
764fn read_custom_data_layers(
765    archive: &BlendArchiveView<'_>,
766    mesh_view: &BlendStructView<'_>,
767    cdata_field: &str,
768) -> Vec<(i32, String, u64)> {
769    let Some(cd_view) = mesh_view.read_embedded(cdata_field) else {
770        return Vec::new();
771    };
772    let totlayer: usize = cd_view.read_i32(FLD_TOTLAYER).unwrap_or(0).max(0) as usize;
773    let layers_ptr: u64 = cd_view.read_ptr(FLD_LAYERS).unwrap_or(0);
774    let Some(layers_block) = archive.block_by_address(layers_ptr) else {
775        return Vec::new();
776    };
777    let count: usize = if totlayer > 0 {
778        totlayer.min(layers_block.get_count().max(totlayer))
779    } else {
780        layers_block.get_count()
781    };
782    let mut out: Vec<(i32, String, u64)> = Vec::with_capacity(count);
783    for idx in 0..count {
784        let Some(layer) =
785            archive.block_struct_view(layers_block, Some(TYPE_CUSTOM_DATA_LAYER), idx)
786        else {
787            break;
788        };
789        let layer_type: i32 = layer.read_i32(FLD_TYPE).unwrap_or(-1);
790        let layer_name: String = layer.read_cstr(SDNA_FIELD_NAME).unwrap_or_default();
791        let data_ptr: u64 = layer.read_ptr(FLD_DATA).unwrap_or(0);
792        if data_ptr != 0 {
793            out.push((layer_type, layer_name, data_ptr));
794        }
795    }
796    out
797}
798
799/// Extracts `MDeformVert` / `MDeformWeight` per-vertex bone influence lists from a `DATA` block at `dvert_ptr`.
800///
801/// # Arguments
802///
803/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
804/// - `u64` - Serialized pointer to the `MDeformVert` array block.
805/// - `usize` - Number of vertices.
806///
807/// # Returns
808///
809/// - `Vec<Vec<(u32, f32)>>` - Per-vertex `(def_nr, weight)` influence pairs.
810fn read_deform_weights(
811    archive: &BlendArchiveView<'_>,
812    dvert_ptr: u64,
813    vert_count: usize,
814) -> Vec<Vec<(u32, f32)>> {
815    let Some(dv_block) = archive.block_by_address(dvert_ptr) else {
816        return Vec::new();
817    };
818    let count: usize = vert_count.min(dv_block.get_count().max(vert_count));
819    let mut out: Vec<Vec<(u32, f32)>> = Vec::with_capacity(count);
820    for v_idx in 0..count {
821        let Some(dv_view) = archive.block_struct_view(dv_block, Some(TYPE_MDEFORMVERT), v_idx)
822        else {
823            out.push(Vec::new());
824            continue;
825        };
826        let totweight: usize = dv_view.read_i32(FLD_TOTWEIGHT).unwrap_or(0).max(0) as usize;
827        let dw_ptr: u64 = dv_view.read_ptr("dw").unwrap_or(0);
828        let mut pairs: Vec<(u32, f32)> = Vec::with_capacity(totweight);
829        if totweight > 0
830            && let Some(dw_block) = archive.block_by_address(dw_ptr)
831        {
832            for w_idx in 0..totweight {
833                if let Some(dw_view) =
834                    archive.block_struct_view(dw_block, Some(TYPE_MDEFORMWEIGHT), w_idx)
835                {
836                    let def_nr: u32 = dw_view.read_i32(FLD_DEF_NR).unwrap_or(0).max(0) as u32;
837                    let weight: f32 = dw_view.read_f32(FLD_WEIGHT).unwrap_or(0.0).max(0.0);
838                    if weight > 0.0 {
839                        pairs.push((def_nr, weight));
840                    }
841                }
842            }
843        }
844        out.push(pairs);
845    }
846    out
847}
848
849/// Extracts `Mesh` (`ME`) blocks supporting both Blender 3.x (`MVert`/`MPoly`/`MLoop`) and 4.x/5.x (`CustomData` + `face_offset_indices`) plus Shape Keys.
850///
851/// # Arguments
852///
853/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
854/// - `&[PrincipledMaterial3D]` - Extracted scene materials.
855/// - `&HashMap<u64, u32>` - Material `old_address` to material index map.
856///
857/// # Returns
858///
859/// - `(Vec<BlendExtractedMesh>, HashMap<u64, u32>)` - Extracted meshes and pointer-to-index map.
860fn extract_blend_meshes(
861    archive: &BlendArchiveView<'_>,
862    materials: &[PrincipledMaterial3D],
863    mat_addr_map: &HashMap<u64, u32>,
864) -> (Vec<BlendExtractedMesh>, HashMap<u64, u32>) {
865    let mut extracted: Vec<BlendExtractedMesh> = Vec::new();
866    let mut addr_to_mesh: HashMap<u64, u32> = HashMap::new();
867    let is_le: bool = archive.get_header().get_is_little_endian();
868    for block in archive.get_blocks().iter() {
869        if block.get_kind() != BlendBlockKind::Mesh {
870            continue;
871        }
872        let Some(mesh_view) = archive.block_struct_view(block, None, 0) else {
873            continue;
874        };
875        let mesh_name: String = mesh_view
876            .id_name()
877            .unwrap_or_else(|| format!("Mesh_{}", extracted.len()));
878        let vdata_layers: Vec<(i32, String, u64)> =
879            read_custom_data_layers(archive, &mesh_view, FLD_VDATA);
880        let ldata_layers: Vec<(i32, String, u64)> =
881            read_custom_data_layers(archive, &mesh_view, FLD_LDATA);
882        let pdata_layers: Vec<(i32, String, u64)> =
883            read_custom_data_layers(archive, &mesh_view, FLD_PDATA);
884        let declared_verts: usize = mesh_view
885            .read_i32(FLD_TOTVERT)
886            .or_else(|| mesh_view.read_i32(FLD_VERTS_NUM))
887            .unwrap_or(0)
888            .max(0) as usize;
889        let declared_faces: usize = mesh_view
890            .read_i32(FLD_TOTPOLY)
891            .or_else(|| mesh_view.read_i32(FLD_FACES_NUM))
892            .unwrap_or(0)
893            .max(0) as usize;
894        let declared_loops: usize = mesh_view
895            .read_i32(FLD_TOTLOOP)
896            .or_else(|| mesh_view.read_i32(FLD_CORNERS_NUM))
897            .unwrap_or(0)
898            .max(0) as usize;
899        let mut src_positions: Vec<Vec3> = Vec::new();
900        let mut src_normals: Vec<Vec3> = Vec::new();
901        let pos_layer_ptr: Option<u64> = vdata_layers
902            .iter()
903            .find(|(ty, nm, _): &&(i32, String, u64)| {
904                *ty == BLEND_CD_PROP_FLOAT3 && nm == BLEND_LAYER_POSITION
905            })
906            .map(|(_, _, ptr): &(i32, String, u64)| *ptr);
907        if let Some(pos_ptr) = pos_layer_ptr {
908            let floats: Vec<f32> = archive.read_f32_array_at(
909                pos_ptr,
910                if declared_verts > 0 {
911                    declared_verts.saturating_mul(3)
912                } else {
913                    usize::MAX
914                },
915            );
916            let v_cnt: usize = floats.len() / 3;
917            src_positions.reserve(v_cnt);
918            for v_idx in 0..v_cnt {
919                let base: usize = v_idx * 3;
920                src_positions.push(
921                    Vec3::new(floats[base], floats[base + 1], floats[base + 2])
922                        .blender_z_up_to_y_up(),
923                );
924            }
925        } else {
926            let mvert_ptr: u64 = mesh_view
927                .read_ptr(FLD_MVERT)
928                .filter(|p: &u64| *p != 0)
929                .or_else(|| {
930                    vdata_layers
931                        .iter()
932                        .find(|(ty, _, _): &&(i32, String, u64)| *ty == BLEND_CD_MVERT)
933                        .map(|(_, _, ptr): &(i32, String, u64)| *ptr)
934                })
935                .unwrap_or(0);
936            if let Some(mv_block) = archive.block_by_address(mvert_ptr) {
937                let st_idx: Option<usize> = archive
938                    .get_sdna()
939                    .struct_index_by_name(TYPE_MVERT)
940                    .or(Some(mv_block.get_sdna_index() as usize));
941                if let Some(mv_st) =
942                    st_idx.and_then(|i: usize| archive.get_sdna().struct_by_index(i))
943                {
944                    let stride: usize = mv_st.get_byte_size();
945                    let co_off: usize = mv_st
946                        .field("co")
947                        .map(BlendSdnaField::get_offset)
948                        .unwrap_or(0);
949                    let no_off_opt: Option<usize> =
950                        mv_st.field("no").map(BlendSdnaField::get_offset);
951                    let payload: &[u8] = archive.block_payload(mv_block);
952                    let v_cnt: usize =
953                        payload.len().checked_div(stride).map_or(0, |avail: usize| {
954                            if declared_verts > 0 {
955                                declared_verts.min(avail)
956                            } else {
957                                avail
958                            }
959                        });
960                    src_positions.reserve(v_cnt);
961                    let mut any_nonzero_normal: bool = false;
962                    let mut tmp_normals: Vec<Vec3> = Vec::with_capacity(v_cnt);
963                    for v_idx in 0..v_cnt {
964                        let base: usize = v_idx * stride + co_off;
965                        let x: f32 = sdna_read_f32(payload, base, is_le).unwrap_or(0.0);
966                        let y: f32 = sdna_read_f32(payload, base + 4, is_le).unwrap_or(0.0);
967                        let z: f32 = sdna_read_f32(payload, base + 8, is_le).unwrap_or(0.0);
968                        src_positions.push(Vec3::new(x, y, z).blender_z_up_to_y_up());
969                        if let Some(no_off) = no_off_opt {
970                            let nb: usize = v_idx * stride + no_off;
971                            let nx: i16 = sdna_read_i16(payload, nb, is_le).unwrap_or(0);
972                            let ny: i16 = sdna_read_i16(payload, nb + 2, is_le).unwrap_or(0);
973                            let nz: i16 = sdna_read_i16(payload, nb + 4, is_le).unwrap_or(0);
974                            if nx != 0 || ny != 0 || nz != 0 {
975                                any_nonzero_normal = true;
976                            }
977                            tmp_normals.push(
978                                Vec3::new(
979                                    f32::from(nx) / 32_767.0,
980                                    f32::from(ny) / 32_767.0,
981                                    f32::from(nz) / 32_767.0,
982                                )
983                                .blender_z_up_to_y_up()
984                                .normalize(),
985                            );
986                        }
987                    }
988                    if any_nonzero_normal && tmp_normals.len() == src_positions.len() {
989                        src_normals = tmp_normals;
990                    }
991                }
992            }
993        }
994        if src_positions.is_empty() {
995            continue;
996        }
997        let mut corner_verts: Vec<u32> = Vec::new();
998        let corner_layer_ptr: Option<u64> = ldata_layers
999            .iter()
1000            .find(|(ty, nm, _): &&(i32, String, u64)| {
1001                *ty == BLEND_CD_PROP_INT32 && nm == BLEND_LAYER_CORNER_VERT
1002            })
1003            .map(|(_, _, ptr): &(i32, String, u64)| *ptr);
1004        if let Some(cv_ptr) = corner_layer_ptr {
1005            let ints: Vec<i32> = archive.read_i32_array_at(
1006                cv_ptr,
1007                if declared_loops > 0 {
1008                    declared_loops
1009                } else {
1010                    usize::MAX
1011                },
1012            );
1013            corner_verts = ints.into_iter().map(|v: i32| v.max(0) as u32).collect();
1014        } else {
1015            let mloop_ptr: u64 = mesh_view
1016                .read_ptr(FLD_MLOOP)
1017                .filter(|p: &u64| *p != 0)
1018                .or_else(|| {
1019                    ldata_layers
1020                        .iter()
1021                        .find(|(ty, _, _): &&(i32, String, u64)| *ty == BLEND_CD_MLOOP)
1022                        .map(|(_, _, ptr): &(i32, String, u64)| *ptr)
1023                })
1024                .unwrap_or(0);
1025            if let Some(ml_block) = archive.block_by_address(mloop_ptr)
1026                && let Some(ml_st) = archive
1027                    .get_sdna()
1028                    .struct_index_by_name(TYPE_MLOOP)
1029                    .or(Some(ml_block.get_sdna_index() as usize))
1030                    .and_then(|i: usize| archive.get_sdna().struct_by_index(i))
1031            {
1032                let stride: usize = ml_st.get_byte_size();
1033                let v_off: usize = ml_st
1034                    .field("v")
1035                    .map(BlendSdnaField::get_offset)
1036                    .unwrap_or(0);
1037                let payload: &[u8] = archive.block_payload(ml_block);
1038                let l_cnt: usize = payload.len().checked_div(stride).map_or(0, |avail: usize| {
1039                    if declared_loops > 0 {
1040                        declared_loops.min(avail)
1041                    } else {
1042                        avail
1043                    }
1044                });
1045                corner_verts.reserve(l_cnt);
1046                for l_idx in 0..l_cnt {
1047                    let v_id: u32 =
1048                        read_endian_u32(payload, l_idx * stride + v_off, is_le).unwrap_or(0);
1049                    corner_verts.push(v_id);
1050                }
1051            }
1052        }
1053        let mut face_ranges: Vec<(usize, usize, u16)> = Vec::new();
1054        let face_offsets_ptr: u64 = mesh_view.read_ptr(FLD_FACE_OFFSETS).unwrap_or(0);
1055        if face_offsets_ptr != 0 {
1056            let offsets: Vec<i32> = archive.read_i32_array_at(
1057                face_offsets_ptr,
1058                if declared_faces > 0 {
1059                    declared_faces + 1
1060                } else {
1061                    usize::MAX
1062                },
1063            );
1064            let mat_idx_layer: Vec<i32> = pdata_layers
1065                .iter()
1066                .find(|(ty, nm, _): &&(i32, String, u64)| {
1067                    *ty == BLEND_CD_PROP_INT32 && nm == BLEND_LAYER_MATERIAL_INDEX
1068                })
1069                .map(|(_, _, ptr): &(i32, String, u64)| {
1070                    archive.read_i32_array_at(*ptr, offsets.len())
1071                })
1072                .unwrap_or_default();
1073            if offsets.len() >= 2 {
1074                face_ranges.reserve(offsets.len() - 1);
1075                for f_idx in 0..(offsets.len() - 1) {
1076                    let start: usize = offsets[f_idx].max(0) as usize;
1077                    let end: usize = offsets[f_idx + 1].max(0) as usize;
1078                    let mat_nr: u16 = mat_idx_layer
1079                        .get(f_idx)
1080                        .copied()
1081                        .unwrap_or(0)
1082                        .clamp(0, i32::from(u16::MAX)) as u16;
1083                    if end > start {
1084                        face_ranges.push((start, end - start, mat_nr));
1085                    }
1086                }
1087            }
1088        } else {
1089            let mpoly_ptr: u64 = mesh_view
1090                .read_ptr(FLD_MPOLY)
1091                .filter(|p: &u64| *p != 0)
1092                .or_else(|| {
1093                    pdata_layers
1094                        .iter()
1095                        .find(|(ty, _, _): &&(i32, String, u64)| *ty == BLEND_CD_MPOLY)
1096                        .map(|(_, _, ptr): &(i32, String, u64)| *ptr)
1097                })
1098                .unwrap_or(0);
1099            if let Some(mp_block) = archive.block_by_address(mpoly_ptr)
1100                && let Some(mp_st) = archive
1101                    .get_sdna()
1102                    .struct_index_by_name(TYPE_MPOLY)
1103                    .or(Some(mp_block.get_sdna_index() as usize))
1104                    .and_then(|i: usize| archive.get_sdna().struct_by_index(i))
1105            {
1106                let stride: usize = mp_st.get_byte_size();
1107                let ls_off: usize = mp_st
1108                    .field(FLD_LOOPSTART)
1109                    .map(BlendSdnaField::get_offset)
1110                    .unwrap_or(0);
1111                let tl_off: usize = mp_st
1112                    .field(FLD_TOTLOOP)
1113                    .map(BlendSdnaField::get_offset)
1114                    .unwrap_or(4);
1115                let mn_off_opt: Option<usize> =
1116                    mp_st.field(FLD_MAT_NR).map(BlendSdnaField::get_offset);
1117                let payload: &[u8] = archive.block_payload(mp_block);
1118                let f_cnt: usize = payload.len().checked_div(stride).map_or(0, |avail: usize| {
1119                    if declared_faces > 0 {
1120                        declared_faces.min(avail)
1121                    } else {
1122                        avail
1123                    }
1124                });
1125                face_ranges.reserve(f_cnt);
1126                for f_idx in 0..f_cnt {
1127                    let base: usize = f_idx * stride;
1128                    let loopstart: usize = sdna_read_i32(payload, base + ls_off, is_le)
1129                        .unwrap_or(0)
1130                        .max(0) as usize;
1131                    let totloop: usize = sdna_read_i32(payload, base + tl_off, is_le)
1132                        .unwrap_or(0)
1133                        .max(0) as usize;
1134                    let mat_nr: u16 = mn_off_opt
1135                        .and_then(|off: usize| sdna_read_i16(payload, base + off, is_le))
1136                        .unwrap_or(0)
1137                        .max(0) as u16;
1138                    if totloop >= 3 {
1139                        face_ranges.push((loopstart, totloop, mat_nr));
1140                    }
1141                }
1142            }
1143        }
1144        if face_ranges.is_empty() || corner_verts.is_empty() {
1145            continue;
1146        }
1147        let mut uv_layers: Vec<Vec<[f32; 2]>> = Vec::new();
1148        for (ty, _, ptr) in ldata_layers.iter() {
1149            if uv_layers.len() >= 2 {
1150                break;
1151            }
1152            if *ty == BLEND_CD_PROP_FLOAT2 {
1153                let floats: Vec<f32> = archive.read_f32_array_at(*ptr, corner_verts.len() * 2);
1154                if floats.len() >= corner_verts.len() * 2 {
1155                    let mut uvs: Vec<[f32; 2]> = Vec::with_capacity(corner_verts.len());
1156                    for idx in 0..corner_verts.len() {
1157                        uvs.push([floats[idx * 2], 1.0 - floats[idx * 2 + 1]]);
1158                    }
1159                    uv_layers.push(uvs);
1160                }
1161            } else if *ty == BLEND_CD_MLOOPUV
1162                && let Some(uv_block) = archive.block_by_address(*ptr)
1163                && let Some(uv_st) = archive
1164                    .get_sdna()
1165                    .struct_index_by_name(TYPE_MLOOPUV)
1166                    .or(Some(uv_block.get_sdna_index() as usize))
1167                    .and_then(|i: usize| archive.get_sdna().struct_by_index(i))
1168            {
1169                let stride: usize = uv_st.get_byte_size();
1170                let uv_off: usize = uv_st
1171                    .field("uv")
1172                    .map(BlendSdnaField::get_offset)
1173                    .unwrap_or(0);
1174                let payload: &[u8] = archive.block_payload(uv_block);
1175                if stride > 0 && payload.len() >= corner_verts.len() * stride {
1176                    let mut uvs: Vec<[f32; 2]> = Vec::with_capacity(corner_verts.len());
1177                    for idx in 0..corner_verts.len() {
1178                        let b: usize = idx * stride + uv_off;
1179                        let u: f32 = sdna_read_f32(payload, b, is_le).unwrap_or(0.0);
1180                        let v: f32 = sdna_read_f32(payload, b + 4, is_le).unwrap_or(0.0);
1181                        uvs.push([u, 1.0 - v]);
1182                    }
1183                    uv_layers.push(uvs);
1184                }
1185            }
1186        }
1187        if uv_layers.is_empty()
1188            && let Some(uv_ptr) = mesh_view.read_ptr(FLD_MLOOPUV).filter(|p: &u64| *p != 0)
1189            && let Some(uv_block) = archive.block_by_address(uv_ptr)
1190            && let Some(uv_st) = archive
1191                .get_sdna()
1192                .struct_index_by_name(TYPE_MLOOPUV)
1193                .or(Some(uv_block.get_sdna_index() as usize))
1194                .and_then(|i: usize| archive.get_sdna().struct_by_index(i))
1195        {
1196            let stride: usize = uv_st.get_byte_size();
1197            let uv_off: usize = uv_st
1198                .field("uv")
1199                .map(BlendSdnaField::get_offset)
1200                .unwrap_or(0);
1201            let payload: &[u8] = archive.block_payload(uv_block);
1202            if stride > 0 && payload.len() >= corner_verts.len() * stride {
1203                let mut uvs: Vec<[f32; 2]> = Vec::with_capacity(corner_verts.len());
1204                for idx in 0..corner_verts.len() {
1205                    let b: usize = idx * stride + uv_off;
1206                    let u: f32 = sdna_read_f32(payload, b, is_le).unwrap_or(0.0);
1207                    let v: f32 = sdna_read_f32(payload, b + 4, is_le).unwrap_or(0.0);
1208                    uvs.push([u, 1.0 - v]);
1209                }
1210                uv_layers.push(uvs);
1211            }
1212        }
1213        let mut corner_colors: Vec<[u8; 4]> = Vec::new();
1214        for (ty, _, ptr) in ldata_layers.iter() {
1215            if *ty == BLEND_CD_PROP_BYTE_COLOR || *ty == BLEND_CD_MLOOPCOL {
1216                if let Some(col_block) = archive.block_by_address(*ptr) {
1217                    let payload: &[u8] = archive.block_payload(col_block);
1218                    if payload.len() >= corner_verts.len() * 4 {
1219                        corner_colors.reserve(corner_verts.len());
1220                        for idx in 0..corner_verts.len() {
1221                            let b: usize = idx * 4;
1222                            corner_colors.push([
1223                                payload[b],
1224                                payload[b + 1],
1225                                payload[b + 2],
1226                                payload[b + 3],
1227                            ]);
1228                        }
1229                        break;
1230                    }
1231                }
1232            } else if *ty == BLEND_CD_PROP_COLOR {
1233                let floats: Vec<f32> = archive.read_f32_array_at(*ptr, corner_verts.len() * 4);
1234                if floats.len() >= corner_verts.len() * 4 {
1235                    corner_colors.reserve(corner_verts.len());
1236                    for idx in 0..corner_verts.len() {
1237                        let b: usize = idx * 4;
1238                        corner_colors.push([
1239                            (floats[b].clamp(0.0, 1.0) * 255.0).round() as u8,
1240                            (floats[b + 1].clamp(0.0, 1.0) * 255.0).round() as u8,
1241                            (floats[b + 2].clamp(0.0, 1.0) * 255.0).round() as u8,
1242                            (floats[b + 3].clamp(0.0, 1.0) * 255.0).round() as u8,
1243                        ]);
1244                    }
1245                    break;
1246                }
1247            }
1248        }
1249        if corner_colors.is_empty()
1250            && let Some(col_ptr) = mesh_view.read_ptr(FLD_MLOOPCOL).filter(|p: &u64| *p != 0)
1251            && let Some(col_block) = archive.block_by_address(col_ptr)
1252        {
1253            let payload: &[u8] = archive.block_payload(col_block);
1254            if payload.len() >= corner_verts.len() * 4 {
1255                corner_colors.reserve(corner_verts.len());
1256                for idx in 0..corner_verts.len() {
1257                    let b: usize = idx * 4;
1258                    corner_colors.push([
1259                        payload[b],
1260                        payload[b + 1],
1261                        payload[b + 2],
1262                        payload[b + 3],
1263                    ]);
1264                }
1265            }
1266        }
1267        let has_uv0: bool = !uv_layers.is_empty();
1268        let has_uv1: bool = uv_layers.len() >= 2;
1269        let has_col: bool = !corner_colors.is_empty();
1270        let has_src_normals: bool = src_normals.len() == src_positions.len();
1271        let mut vertices: Vec<Vertex3D> = Vec::new();
1272        let mut corner_to_src_vert: Vec<u32> = Vec::new();
1273        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(face_ranges.len().saturating_mul(2));
1274        let mut tri_materials: Vec<u16> = Vec::new();
1275        let mut any_nonzero_mat_nr: bool = false;
1276        if !has_uv0 && !has_col {
1277            vertices.reserve(src_positions.len());
1278            corner_to_src_vert.reserve(src_positions.len());
1279            for (v_idx, &pos) in src_positions.iter().enumerate() {
1280                let norm: Vec3 = if has_src_normals {
1281                    src_normals[v_idx]
1282                } else {
1283                    Vec3::new(0.0, 1.0, 0.0)
1284                };
1285                vertices.push(Vertex3D::new(pos, norm));
1286                corner_to_src_vert.push(v_idx as u32);
1287            }
1288            for &(loopstart, totloop, mat_nr) in face_ranges.iter() {
1289                if totloop < 3 || loopstart + totloop > corner_verts.len() {
1290                    continue;
1291                }
1292                let v0: u32 = corner_verts[loopstart];
1293                if (v0 as usize) >= src_positions.len() {
1294                    continue;
1295                }
1296                for step in 1..(totloop - 1) {
1297                    let v1: u32 = corner_verts[loopstart + step];
1298                    let v2: u32 = corner_verts[loopstart + step + 1];
1299                    if (v1 as usize) < src_positions.len() && (v2 as usize) < src_positions.len() {
1300                        indices.push([v0, v1, v2]);
1301                        tri_materials.push(mat_nr);
1302                        if mat_nr != 0 {
1303                            any_nonzero_mat_nr = true;
1304                        }
1305                    }
1306                }
1307            }
1308        } else {
1309            let mut first_emit_for_vert: Vec<u32> = vec![u32::MAX; src_positions.len()];
1310            vertices.reserve(src_positions.len());
1311            corner_to_src_vert.reserve(src_positions.len());
1312            let mut corner_remap: Vec<u32> = vec![u32::MAX; corner_verts.len()];
1313            for (c_idx, &v_id) in corner_verts.iter().enumerate() {
1314                let v_usize: usize = v_id as usize;
1315                if v_usize >= src_positions.len() {
1316                    continue;
1317                }
1318                let uv0: [f32; 2] = if has_uv0 {
1319                    uv_layers[0][c_idx]
1320                } else {
1321                    [0.0, 0.0]
1322                };
1323                let uv1: [f32; 2] = if has_uv1 {
1324                    uv_layers[1][c_idx]
1325                } else {
1326                    [0.0, 0.0]
1327                };
1328                let col: [u8; 4] = if has_col {
1329                    corner_colors[c_idx]
1330                } else {
1331                    [255, 255, 255, 255]
1332                };
1333                let existing: u32 = first_emit_for_vert[v_usize];
1334                let can_reuse: bool = if existing != u32::MAX {
1335                    let prev: &Vertex3D = &vertices[existing as usize];
1336                    let prev_uv0: [f32; 2] = prev.get_uv0();
1337                    let prev_uv1: [f32; 2] = prev.get_uv1();
1338                    (prev_uv0[0] - uv0[0]).abs() < 1e-5
1339                        && (prev_uv0[1] - uv0[1]).abs() < 1e-5
1340                        && (prev_uv1[0] - uv1[0]).abs() < 1e-5
1341                        && (prev_uv1[1] - uv1[1]).abs() < 1e-5
1342                        && prev.get_color0() == col
1343                } else {
1344                    false
1345                };
1346                if can_reuse {
1347                    corner_remap[c_idx] = existing;
1348                } else {
1349                    let norm: Vec3 = if has_src_normals {
1350                        src_normals[v_usize]
1351                    } else {
1352                        Vec3::new(0.0, 1.0, 0.0)
1353                    };
1354                    let mut vert: Vertex3D = Vertex3D::new(src_positions[v_usize], norm);
1355                    let mut flags: u32 = 0;
1356                    if has_uv0 {
1357                        vert.set_uv0(uv0);
1358                        flags |= 1;
1359                    }
1360                    if has_uv1 {
1361                        vert.set_uv1(uv1);
1362                        flags |= 2;
1363                    }
1364                    if has_col {
1365                        vert.set_color0(col);
1366                        flags |= 8;
1367                    }
1368                    vert.set_flags(flags);
1369                    let new_idx: u32 = vertices.len() as u32;
1370                    vertices.push(vert);
1371                    corner_to_src_vert.push(v_id);
1372                    if existing == u32::MAX {
1373                        first_emit_for_vert[v_usize] = new_idx;
1374                    }
1375                    corner_remap[c_idx] = new_idx;
1376                }
1377            }
1378            for &(loopstart, totloop, mat_nr) in face_ranges.iter() {
1379                if totloop < 3 || loopstart + totloop > corner_remap.len() {
1380                    continue;
1381                }
1382                let i0: u32 = corner_remap[loopstart];
1383                if i0 == u32::MAX {
1384                    continue;
1385                }
1386                for step in 1..(totloop - 1) {
1387                    let i1: u32 = corner_remap[loopstart + step];
1388                    let i2: u32 = corner_remap[loopstart + step + 1];
1389                    if i1 != u32::MAX && i2 != u32::MAX {
1390                        indices.push([i0, i1, i2]);
1391                        tri_materials.push(mat_nr);
1392                        if mat_nr != 0 {
1393                            any_nonzero_mat_nr = true;
1394                        }
1395                    }
1396                }
1397            }
1398        }
1399        if indices.is_empty() {
1400            continue;
1401        }
1402        let totcol: usize = mesh_view.read_i32(FLD_TOTCOL).unwrap_or(0).max(0) as usize;
1403        let mat_ptrs: Vec<u64> = if totcol > 0
1404            && let Some(mat_arr_ptr) = mesh_view.read_ptr("mat").filter(|p: &u64| *p != 0)
1405        {
1406            archive.read_ptr_array_at(mat_arr_ptr, totcol)
1407        } else {
1408            Vec::new()
1409        };
1410        let slot_mat_indices: Vec<Option<u32>> = mat_ptrs
1411            .iter()
1412            .map(|ptr: &u64| mat_addr_map.get(ptr).copied())
1413            .collect();
1414        let primary_mat_idx: Option<u32> = slot_mat_indices.first().copied().flatten();
1415        let primary_pbr: PbrMaterial = primary_mat_idx
1416            .and_then(|idx: u32| materials.get(idx as usize))
1417            .map(PrincipledMaterial3D::to_legacy_pbr)
1418            .unwrap_or_default();
1419        let mut built: Mesh3D = Mesh3D::from_parts(mesh_name, vertices, indices, primary_pbr);
1420        if !has_src_normals {
1421            built.compute_smooth_normals();
1422        }
1423        built.compute_lengyel_tangents();
1424        built.set_material_index(primary_mat_idx);
1425        if any_nonzero_mat_nr && slot_mat_indices.len() > 1 {
1426            let sub_mats: Vec<PbrMaterial> = slot_mat_indices
1427                .iter()
1428                .skip(1)
1429                .map(|idx_opt: &Option<u32>| {
1430                    idx_opt
1431                        .and_then(|idx: u32| materials.get(idx as usize))
1432                        .map(PrincipledMaterial3D::to_legacy_pbr)
1433                        .unwrap_or(primary_pbr)
1434                })
1435                .collect();
1436            built.set_sub_materials(sub_mats);
1437            built.set_tri_materials(tri_materials);
1438        }
1439        let mut shape_key_names: Vec<String> = Vec::new();
1440        let mut shape_key_weights: Vec<f32> = Vec::new();
1441        if let Some(key_view) = mesh_view.follow_ptr("key", None) {
1442            let key_blocks: Vec<BlendStructView<'_>> =
1443                key_view.follow_list_base(FLD_BLOCK, Some(TYPE_KEYBLOCK));
1444            if key_blocks.len() >= 2 {
1445                let basis_ptr: u64 = key_blocks[0].read_ptr(FLD_DATA).unwrap_or(0);
1446                let basis_floats: Vec<f32> =
1447                    archive.read_f32_array_at(basis_ptr, src_positions.len() * 3);
1448                let mut morph_targets: Vec<MorphTarget3D> =
1449                    Vec::with_capacity(key_blocks.len() - 1);
1450                for kb in key_blocks.iter().skip(1) {
1451                    let kb_name: String = kb
1452                        .read_cstr(SDNA_FIELD_NAME)
1453                        .filter(|s: &String| !s.is_empty())
1454                        .unwrap_or_else(|| format!("ShapeKey_{}", morph_targets.len()));
1455                    let kb_curval: f32 = kb.read_f32(FLD_CURVAL).unwrap_or(0.0);
1456                    let kb_elems: usize = kb
1457                        .read_i32(FLD_TOTELEM)
1458                        .unwrap_or(src_positions.len() as i32)
1459                        .max(0) as usize;
1460                    let kb_ptr: u64 = kb.read_ptr(FLD_DATA).unwrap_or(0);
1461                    let kb_floats: Vec<f32> = archive.read_f32_array_at(kb_ptr, kb_elems * 3);
1462                    if kb_floats.len() >= 3 {
1463                        let mut delta_positions: Vec<[f32; 3]> =
1464                            Vec::with_capacity(corner_to_src_vert.len());
1465                        for &src_v in corner_to_src_vert.iter() {
1466                            let idx: usize = (src_v as usize) * 3;
1467                            if idx + 2 < kb_floats.len() {
1468                                let target_pos: Vec3 = Vec3::new(
1469                                    kb_floats[idx],
1470                                    kb_floats[idx + 1],
1471                                    kb_floats[idx + 2],
1472                                )
1473                                .blender_z_up_to_y_up();
1474                                let base_pos: Vec3 = if idx + 2 < basis_floats.len() {
1475                                    Vec3::new(
1476                                        basis_floats[idx],
1477                                        basis_floats[idx + 1],
1478                                        basis_floats[idx + 2],
1479                                    )
1480                                    .blender_z_up_to_y_up()
1481                                } else {
1482                                    src_positions[src_v as usize]
1483                                };
1484                                delta_positions.push(target_pos.sub(base_pos).to_array());
1485                            } else {
1486                                delta_positions.push([0.0, 0.0, 0.0]);
1487                            }
1488                        }
1489                        shape_key_names.push(kb_name.clone());
1490                        shape_key_weights.push(kb_curval);
1491                        morph_targets.push(MorphTarget3D {
1492                            name: kb_name,
1493                            delta_positions,
1494                            delta_normals: Vec::new(),
1495                            delta_tangents: Vec::new(),
1496                        });
1497                    }
1498                }
1499                built.set_morph_targets(morph_targets);
1500            }
1501        }
1502        let dvert_ptr: u64 = mesh_view
1503            .read_ptr(FLD_DVERT)
1504            .filter(|p: &u64| *p != 0)
1505            .or_else(|| {
1506                vdata_layers
1507                    .iter()
1508                    .find(|(ty, _, _): &&(i32, String, u64)| *ty == BLEND_CD_MDEFORMVERT)
1509                    .map(|(_, _, ptr): &(i32, String, u64)| *ptr)
1510            })
1511            .unwrap_or(0);
1512        let raw_deform_weights: Vec<Vec<(u32, f32)>> = if dvert_ptr != 0 {
1513            read_deform_weights(archive, dvert_ptr, src_positions.len())
1514        } else {
1515            Vec::new()
1516        };
1517        let mesh_idx: u32 = extracted.len() as u32;
1518        extracted.push(BlendExtractedMesh {
1519            mesh: built,
1520            corner_to_src_vert,
1521            raw_deform_weights,
1522            shape_key_names,
1523            shape_key_weights,
1524        });
1525        let _: Option<u32> = addr_to_mesh.insert(block.get_old_address(), mesh_idx);
1526    }
1527    (extracted, addr_to_mesh)
1528}
1529
1530/// Recursively registers a Blender `Bone` and its `childbase` descendants as joint nodes in `scene_graph`.
1531///
1532/// # Arguments
1533///
1534/// - `&BlendStructView<'_>` - Current Blender `Bone` view.
1535/// - `Option<u32>` - Parent joint node index in `scene_graph`.
1536/// - `Mat4` - Parent bone world matrix in Engine Y-up space.
1537/// - `&mut SceneGraph3D` - Target scene graph receiving bone nodes.
1538/// - `&mut BlendArmatureAccumulator` - Mutable accumulator for joints, IBMs, and name maps.
1539fn walk_blend_bone(
1540    bone_view: &BlendStructView<'_>,
1541    parent_node: Option<u32>,
1542    parent_mat_euv: Mat4,
1543    scene_graph: &mut SceneGraph3D,
1544    acc: &mut BlendArmatureAccumulator,
1545) {
1546    let bone_name: String = bone_view
1547        .read_cstr(SDNA_FIELD_NAME)
1548        .filter(|s: &String| !s.is_empty())
1549        .unwrap_or_else(|| format!("Bone_{}", acc.joints.len()));
1550    let arm_mat_blend: Mat4 = read_blend_mat4(bone_view, FLD_ARM_MAT).unwrap_or_else(|| {
1551        let head: Vec<f32> = bone_view
1552            .read_f32_array(FLD_ARM_HEAD)
1553            .unwrap_or_else(|| vec![0.0, 0.0, 0.0]);
1554        let h_vec: Vec3 = if head.len() >= 3 {
1555            Vec3::new(head[0], head[1], head[2])
1556        } else {
1557            Vec3::zero()
1558        };
1559        Mat4::from_trs_quat(h_vec, Quat::identity(), Vec3::splat(1.0))
1560    });
1561    let bone_mat_euv: Mat4 = blend_mat4_to_y_up(arm_mat_blend);
1562    let local_mat: Mat4 = parent_mat_euv
1563        .inverse()
1564        .map(|inv_p: Mat4| inv_p.mul(bone_mat_euv))
1565        .unwrap_or(bone_mat_euv);
1566    let (local_t, local_r, local_s): (Vec3, Quat, Vec3) = local_mat.decompose_trs();
1567    let mut node: SceneNode3D = SceneNode3D::from_name(&bone_name, parent_node);
1568    node.set_local_translation(local_t);
1569    node.set_local_rotation(local_r);
1570    node.set_local_scale(local_s);
1571    let node_id: u32 = scene_graph.add_node(node);
1572    let joint_idx: u16 = acc.joints.len() as u16;
1573    acc.joints.push(node_id);
1574    let ibm: Mat4 = bone_mat_euv.inverse().unwrap_or_else(Mat4::identity);
1575    acc.inverse_bind_matrices.push(ibm);
1576    let _: Option<u16> = acc.bone_name_to_joint.insert(bone_name.clone(), joint_idx);
1577    let _: Option<u32> = acc.bone_name_to_node.insert(bone_name, node_id);
1578    let children: Vec<BlendStructView<'_>> =
1579        bone_view.follow_list_base(FLD_CHILDBASE, Some(TYPE_BONE));
1580    for child in children.iter() {
1581        walk_blend_bone(child, Some(node_id), bone_mat_euv, scene_graph, acc);
1582    }
1583}
1584
1585/// Recursively walks Blender `Collection` children and objects to populate `CollectionRegistry3D` and object visibility masks.
1586///
1587/// # Arguments
1588///
1589/// - `&BlendStructView<'_>` - Current Blender `Collection` view.
1590/// - `u64` - Inherited collection bitmask.
1591/// - `&mut HashSet<u64>` - Cycle guard over visited collection addresses.
1592/// - `&HashMap<usize, u64>` - Payload offset to `old_address` map.
1593/// - `&mut CollectionRegistry3D` - Destination collection registry.
1594/// - `&mut HashMap<u64, u64>` - Map from `Object` `old_address` to combined collection bitmask.
1595fn walk_blend_collection(
1596    col_view: &BlendStructView<'_>,
1597    inherited_mask: u64,
1598    visited: &mut HashSet<u64>,
1599    offset_to_addr: &HashMap<usize, u64>,
1600    registry: &mut CollectionRegistry3D,
1601    obj_masks: &mut HashMap<u64, u64>,
1602) {
1603    let col_addr: u64 = resolve_view_address(col_view, offset_to_addr);
1604    if col_addr != 0 && !visited.insert(col_addr) {
1605        return;
1606    }
1607    let col_name: String = col_view
1608        .id_name()
1609        .unwrap_or_else(|| DEFAULT_BLEND_SCENE_NAME.to_string());
1610    let bit_mask: u64 = registry.register_collection(&col_name);
1611    let combined_mask: u64 = inherited_mask | bit_mask;
1612    let gobjs: Vec<BlendStructView<'_>> =
1613        col_view.follow_list_base(FLD_GOBJECT, Some(TYPE_COLLECTION_OBJECT));
1614    for gobj in gobjs.iter() {
1615        let ob_ptr: u64 = gobj.read_ptr("ob").unwrap_or(0);
1616        if ob_ptr != 0 {
1617            let entry: &mut u64 = obj_masks.entry(ob_ptr).or_insert(1u64);
1618            *entry |= combined_mask;
1619        }
1620    }
1621    let children: Vec<BlendStructView<'_>> =
1622        col_view.follow_list_base(FLD_CHILDREN, Some(TYPE_COLLECTION_CHILD));
1623    for child in children.iter() {
1624        if let Some(child_col) = child.follow_ptr(FLD_COLLECTION, Some(TYPE_COLLECTION)) {
1625            walk_blend_collection(
1626                &child_col,
1627                combined_mask,
1628                visited,
1629                offset_to_addr,
1630                registry,
1631                obj_masks,
1632            );
1633        }
1634    }
1635}
1636
1637/// Remaps raw Blender `(def_nr, weight)` lists onto normalized 8-influence `MeshSkinInfluence3D` records.
1638///
1639/// # Arguments
1640///
1641/// - `&BlendExtractedMesh` - Extracted mesh with corner-to-source-vertex mapping and raw weights.
1642/// - `&[String]` - Ordered Blender vertex group names (`Object.defbase`).
1643/// - `&HashMap<String, u16>` - Armature bone name to joint index lookup.
1644///
1645/// # Returns
1646///
1647/// - `Vec<MeshSkinInfluence3D>` - Normalized per-vertex skin influences aligned with `mesh.vertices`.
1648fn build_skin_influences(
1649    extracted: &BlendExtractedMesh,
1650    vertex_groups: &[String],
1651    bone_name_to_joint: &HashMap<String, u16>,
1652) -> Vec<MeshSkinInfluence3D> {
1653    let raw_weights: &[Vec<(u32, f32)>] = extracted.get_raw_deform_weights();
1654    if raw_weights.is_empty() {
1655        return Vec::new();
1656    }
1657    let corners: &[u32] = extracted.get_corner_to_src_vert();
1658    let mut out: Vec<MeshSkinInfluence3D> = Vec::with_capacity(corners.len());
1659    for &src_v in corners.iter() {
1660        let mut mapped: Vec<(u16, f32)> = Vec::new();
1661        if let Some(pairs) = raw_weights.get(src_v as usize) {
1662            for &(def_nr, weight) in pairs.iter() {
1663                let fallback_joint: Option<u16> =
1664                    if vertex_groups.is_empty() && (def_nr as usize) < bone_name_to_joint.len() {
1665                        Some(def_nr as u16)
1666                    } else {
1667                        None
1668                    };
1669                let joint_opt: Option<u16> = vertex_groups
1670                    .get(def_nr as usize)
1671                    .and_then(|vg: &String| bone_name_to_joint.get(vg).copied())
1672                    .or(fallback_joint);
1673                if let Some(j_idx) = joint_opt
1674                    && weight > 0.0
1675                {
1676                    mapped.push((j_idx, weight));
1677                }
1678            }
1679        }
1680        mapped.sort_by(|a: &(u16, f32), b: &(u16, f32)| b.1.total_cmp(&a.1));
1681        mapped.truncate(8);
1682        let mut joints_0: [u16; 4] = [0; 4];
1683        let mut weights_0: [f32; 4] = [0.0; 4];
1684        let mut joints_1: [u16; 4] = [0; 4];
1685        let mut weights_1: [f32; 4] = [0.0; 4];
1686        let mut sum_w: f32 = 0.0;
1687        for (slot, &(j_idx, w_val)) in mapped.iter().enumerate() {
1688            sum_w += w_val;
1689            if slot < 4 {
1690                joints_0[slot] = j_idx;
1691                weights_0[slot] = w_val;
1692            } else {
1693                joints_1[slot - 4] = j_idx;
1694                weights_1[slot - 4] = w_val;
1695            }
1696        }
1697        if sum_w > 1e-6 {
1698            let inv_w: f32 = 1.0 / sum_w;
1699            for lane in 0..4 {
1700                weights_0[lane] *= inv_w;
1701                weights_1[lane] *= inv_w;
1702            }
1703        } else {
1704            weights_0[0] = 1.0;
1705        }
1706        out.push(MeshSkinInfluence3D::new(
1707            joints_0, weights_0, joints_1, weights_1,
1708        ));
1709    }
1710    out
1711}
1712
1713/// Parses one Blender `FCurve` view into a `BlendParsedFCurve` converting frame numbers to seconds.
1714///
1715/// # Arguments
1716///
1717/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
1718/// - `&BlendStructView<'_>` - `FCurve` struct view.
1719/// - `f32` - Scene frames-per-second rate.
1720///
1721/// # Returns
1722///
1723/// - `Option<BlendParsedFCurve>` - Parsed FCurve if non-empty with valid RNA path.
1724fn parse_single_fcurve(
1725    archive: &BlendArchiveView<'_>,
1726    fc_view: &BlendStructView<'_>,
1727    fps: f32,
1728) -> Option<BlendParsedFCurve> {
1729    let rna_path: String = fc_view.read_cstr(FLD_RNA_PATH)?;
1730    if rna_path.is_empty() {
1731        return None;
1732    }
1733    let array_index: usize = fc_view.read_i32(FLD_ARRAY_INDEX).unwrap_or(0).max(0) as usize;
1734    let totvert: usize = fc_view.read_i32(FLD_TOTVERT).unwrap_or(0).max(0) as usize;
1735    let bezt_ptr: u64 = fc_view.read_ptr(FLD_BEZT).unwrap_or(0);
1736    let bezt_block: &BlendFileBlock = archive.block_by_address(bezt_ptr)?;
1737    let count: usize = if totvert > 0 {
1738        totvert.min(bezt_block.get_count().max(totvert))
1739    } else {
1740        bezt_block.get_count()
1741    };
1742    let mut keyframes: Vec<(f32, f32)> = Vec::with_capacity(count);
1743    let inv_fps: f32 = 1.0 / fps.max(1.0);
1744    for idx in 0..count {
1745        let Some(bt_view) = archive.block_struct_view(bezt_block, Some(TYPE_BEZ_TRIPLE), idx)
1746        else {
1747            break;
1748        };
1749        if let Some(vec_vals) = bt_view.read_f32_array("vec")
1750            && vec_vals.len() >= 6
1751        {
1752            let frame: f32 = vec_vals[3];
1753            let value: f32 = vec_vals[4];
1754            keyframes.push((frame * inv_fps, value));
1755        }
1756    }
1757    if keyframes.is_empty() {
1758        return None;
1759    }
1760    keyframes.sort_by(|a: &(f32, f32), b: &(f32, f32)| a.0.total_cmp(&b.0));
1761    Some(BlendParsedFCurve {
1762        rna_path,
1763        array_index,
1764        keyframes,
1765    })
1766}
1767
1768/// Samples a sorted keyframe slice `(time, value)` linearly at `time_sec`.
1769///
1770/// # Arguments
1771///
1772/// - `&[(f32, f32)]` - Sorted `(time_sec, value)` keyframes.
1773/// - `f32` - Query timestamp in seconds.
1774/// - `f32` - Default fallback value when slice is empty.
1775///
1776/// # Returns
1777///
1778/// - `f32` - Sampled scalar value.
1779#[must_use]
1780fn sample_fcurve_linear(kfs: &[(f32, f32)], time_sec: f32, default_val: f32) -> f32 {
1781    if kfs.is_empty() {
1782        return default_val;
1783    }
1784    if time_sec <= kfs[0].0 || kfs.len() == 1 {
1785        return kfs[0].1;
1786    }
1787    let last_idx: usize = kfs.len() - 1;
1788    if time_sec >= kfs[last_idx].0 {
1789        return kfs[last_idx].1;
1790    }
1791    for idx in 0..last_idx {
1792        let (t0, v0): (f32, f32) = kfs[idx];
1793        let (t1, v1): (f32, f32) = kfs[idx + 1];
1794        if time_sec >= t0 && time_sec <= t1 {
1795            let span: f32 = (t1 - t0).max(1e-6);
1796            let alpha: f32 = ((time_sec - t0) / span).clamp(0.0, 1.0);
1797            return v0 + (v1 - v0) * alpha;
1798        }
1799    }
1800    kfs[last_idx].1
1801}
1802
1803/// Looks up `lane_idx` in a grouped list of `BlendLaneTrack` items and samples it linearly at `time_sec`.
1804///
1805/// # Arguments
1806///
1807/// - `&[BlendLaneTrack]` - Grouped FCurve channel tracks.
1808/// - `usize` - Target array lane index (`0..=3`).
1809/// - `f32` - Query timestamp in seconds.
1810/// - `f32` - Fallback value when the lane is absent.
1811///
1812/// # Returns
1813///
1814/// - `f32` - Sampled scalar lane value.
1815#[must_use]
1816fn sample_fcurve_lane(
1817    lanes: &[BlendLaneTrack],
1818    lane_idx: usize,
1819    time_sec: f32,
1820    default_val: f32,
1821) -> f32 {
1822    lanes
1823        .iter()
1824        .find(|track: &&BlendLaneTrack| track.lane == lane_idx)
1825        .map(|track: &BlendLaneTrack| sample_fcurve_linear(&track.keyframes, time_sec, default_val))
1826        .unwrap_or(default_val)
1827}
1828
1829/// Collects all `FCurve`s from both legacy `bAction.curves` and Blender 4.4+/5.x Layered Action channelbags.
1830///
1831/// # Arguments
1832///
1833/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
1834/// - `&BlendStructView<'_>` - `bAction` struct view.
1835/// - `f32` - Scene frames-per-second rate.
1836///
1837/// # Returns
1838///
1839/// - `Vec<BlendParsedFCurve>` - All extracted FCurves belonging to this action.
1840fn collect_action_fcurves(
1841    archive: &BlendArchiveView<'_>,
1842    action_view: &BlendStructView<'_>,
1843    fps: f32,
1844) -> Vec<BlendParsedFCurve> {
1845    let mut parsed: Vec<BlendParsedFCurve> = Vec::new();
1846    let legacy_curves: Vec<BlendStructView<'_>> =
1847        action_view.follow_list_base(FLD_CURVES, Some(TYPE_FCURVE));
1848    for fc in legacy_curves.iter() {
1849        if let Some(curve) = parse_single_fcurve(archive, fc, fps) {
1850            parsed.push(curve);
1851        }
1852    }
1853    let layer_num: usize = action_view
1854        .read_i32(FLD_LAYER_ARRAY_NUM)
1855        .unwrap_or(0)
1856        .max(0) as usize;
1857    let layers_ptr: u64 = action_view.read_ptr(FLD_LAYERS).unwrap_or(0);
1858    if layer_num > 0 && layers_ptr != 0 {
1859        let layer_ptrs: Vec<u64> = archive.read_ptr_array_at(layers_ptr, layer_num);
1860        for l_ptr in layer_ptrs {
1861            let Some(layer_view) = archive.resolve_struct_at(l_ptr, Some(TYPE_ACTION_LAYER)) else {
1862                continue;
1863            };
1864            let strip_num: usize =
1865                layer_view.read_i32(FLD_STRIP_ARRAY_NUM).unwrap_or(0).max(0) as usize;
1866            let strips_ptr: u64 = layer_view.read_ptr(FLD_STRIPS).unwrap_or(0);
1867            let strip_ptrs: Vec<u64> = archive.read_ptr_array_at(strips_ptr, strip_num);
1868            for s_ptr in strip_ptrs {
1869                let Some(strip_view) = archive.resolve_struct_at(s_ptr, Some(TYPE_ACTION_STRIP))
1870                else {
1871                    continue;
1872                };
1873                let cb_num: usize = strip_view
1874                    .read_i32(FLD_CHANNELBAG_ARRAY_NUM)
1875                    .unwrap_or(0)
1876                    .max(0) as usize;
1877                let cbs_ptr: u64 = strip_view.read_ptr(FLD_CHANNELBAGS).unwrap_or(0);
1878                let cb_ptrs: Vec<u64> = archive.read_ptr_array_at(cbs_ptr, cb_num);
1879                for cb_ptr in cb_ptrs {
1880                    let Some(cb_view) =
1881                        archive.resolve_struct_at(cb_ptr, Some(TYPE_ACTION_CHANNELBAG))
1882                    else {
1883                        continue;
1884                    };
1885                    let fc_num: usize =
1886                        cb_view.read_i32(FLD_FCURVE_ARRAY_NUM).unwrap_or(0).max(0) as usize;
1887                    let fcs_ptr: u64 = cb_view.read_ptr(FLD_FCURVES).unwrap_or(0);
1888                    let fc_ptrs: Vec<u64> = archive.read_ptr_array_at(fcs_ptr, fc_num);
1889                    for fc_ptr in fc_ptrs {
1890                        if let Some(fc_view) = archive.resolve_struct_at(fc_ptr, Some(TYPE_FCURVE))
1891                            && let Some(curve) = parse_single_fcurve(archive, &fc_view, fps)
1892                        {
1893                            parsed.push(curve);
1894                        }
1895                    }
1896                }
1897            }
1898        }
1899    }
1900    parsed
1901}
1902
1903/// Extracts `bAction` (`AC`) animation clips (legacy FCurves and 4.4+/5.x Layered Actions) bound to scene objects, bones, and shape keys.
1904///
1905/// # Arguments
1906///
1907/// - `&BlendArchiveView<'_>` - Indexed `.blend` archive view.
1908/// - `f32` - Scene FPS.
1909/// - `&HashMap<u64, u32>` - Map from `Action` `old_address` to owning object node index.
1910/// - `&HashMap<String, u32>` - Global map from bone name to joint node index.
1911/// - `&HashMap<String, (u32, usize, usize)>` - Map from shape key name to `(node_id, morph_index, total_morphs)`.
1912/// - `u32` - Fallback target node index when an action is unlinked.
1913///
1914/// # Returns
1915///
1916/// - `Vec<ImportedAnimationClip3D>` - Converted animation clips in Engine Y-up space.
1917fn extract_blend_animations(
1918    archive: &BlendArchiveView<'_>,
1919    fps: f32,
1920    action_to_node: &HashMap<u64, u32>,
1921    all_bones_to_node: &HashMap<String, u32>,
1922    shape_key_to_target: &HashMap<String, (u32, usize, usize)>,
1923    fallback_node: u32,
1924) -> Vec<ImportedAnimationClip3D> {
1925    let mut clips: Vec<ImportedAnimationClip3D> = Vec::new();
1926    for block in archive.get_blocks().iter() {
1927        if block.get_kind() != BlendBlockKind::Action {
1928            continue;
1929        }
1930        let Some(action_view) = archive.block_struct_view(block, None, 0) else {
1931            continue;
1932        };
1933        let clip_name: String = action_view
1934            .id_name()
1935            .unwrap_or_else(|| format!("Action_{}", clips.len()));
1936        let fcurves: Vec<BlendParsedFCurve> = collect_action_fcurves(archive, &action_view, fps);
1937        if fcurves.is_empty() {
1938            continue;
1939        }
1940        let owner_node: u32 = action_to_node
1941            .get(&block.get_old_address())
1942            .copied()
1943            .unwrap_or(fallback_node);
1944        let mut grouped: HashMap<(u32, u8), Vec<BlendLaneTrack>> = HashMap::new();
1945        let mut morph_grouped: HashMap<(u32, usize), Vec<BlendLaneTrack>> = HashMap::new();
1946        for fc in fcurves {
1947            let path: &str = fc.get_rna_path();
1948            if let Some(after_bone) = path.strip_prefix(RNA_POSE_BONES_PREFIX)
1949                && let Some(split_pos) = after_bone.find(RNA_BRACKET_DOT)
1950            {
1951                let bone_name: &str = &after_bone[..split_pos];
1952                let prop: &str = &after_bone[(split_pos + RNA_BRACKET_DOT.len())..];
1953                if let Some(&bone_node) = all_bones_to_node.get(bone_name) {
1954                    let kind_tag: Option<u8> = match prop {
1955                        RNA_LOCATION => Some(0),
1956                        RNA_ROTATION_QUAT => Some(1),
1957                        RNA_ROTATION_EULER => Some(2),
1958                        RNA_SCALE => Some(3),
1959                        _ => None,
1960                    };
1961                    if let Some(tag) = kind_tag {
1962                        grouped
1963                            .entry((bone_node, tag))
1964                            .or_default()
1965                            .push(BlendLaneTrack {
1966                                lane: fc.get_array_index(),
1967                                keyframes: fc.get_keyframes().clone(),
1968                            });
1969                    }
1970                }
1971            } else if let Some(after_kb) = path.strip_prefix(RNA_KEY_BLOCKS_PREFIX)
1972                && let Some(split_pos) = after_kb.find(RNA_BRACKET_DOT)
1973            {
1974                let kb_name: &str = &after_kb[..split_pos];
1975                if let Some(&(target_node, morph_idx, total_morphs)) =
1976                    shape_key_to_target.get(kb_name)
1977                {
1978                    morph_grouped
1979                        .entry((target_node, total_morphs))
1980                        .or_default()
1981                        .push(BlendLaneTrack {
1982                            lane: morph_idx,
1983                            keyframes: fc.get_keyframes().clone(),
1984                        });
1985                }
1986            } else {
1987                let kind_tag: Option<u8> = match path {
1988                    RNA_LOCATION => Some(0),
1989                    RNA_ROTATION_QUAT => Some(1),
1990                    RNA_ROTATION_EULER => Some(2),
1991                    RNA_SCALE => Some(3),
1992                    _ => None,
1993                };
1994                if let Some(tag) = kind_tag {
1995                    grouped
1996                        .entry((owner_node, tag))
1997                        .or_default()
1998                        .push(BlendLaneTrack {
1999                            lane: fc.get_array_index(),
2000                            keyframes: fc.get_keyframes().clone(),
2001                        });
2002                }
2003            }
2004        }
2005        let mut samplers: Vec<ImportedAnimationSampler3D> = Vec::new();
2006        let mut channels: Vec<ImportedAnimationChannel3D> = Vec::new();
2007        let mut duration_secs: f32 = 0.0;
2008        let mut sorted_keys: Vec<(u32, u8)> = grouped.keys().copied().collect();
2009        sorted_keys.sort();
2010        for key in sorted_keys {
2011            let (target_node, tag): (u32, u8) = key;
2012            let Some(lanes) = grouped.get(&key) else {
2013                continue;
2014            };
2015            let mut times: Vec<f32> = Vec::new();
2016            for track in lanes.iter() {
2017                for &(t, _) in track.keyframes.iter() {
2018                    times.push(t);
2019                    if t > duration_secs {
2020                        duration_secs = t;
2021                    }
2022                }
2023            }
2024            times.sort_by(|a: &f32, b: &f32| a.total_cmp(b));
2025            times.dedup_by(|a: &mut f32, b: &mut f32| (*a - *b).abs() < 1e-5);
2026            if times.is_empty() {
2027                continue;
2028            }
2029            let (anim_path, stride, values): (GltfAnimationPath, usize, Vec<f32>) = match tag {
2030                0 => {
2031                    let mut vals: Vec<f32> = Vec::with_capacity(times.len() * 3);
2032                    for &t in times.iter() {
2033                        let v: Vec3 = Vec3::new(
2034                            sample_fcurve_lane(lanes, 0, t, 0.0),
2035                            sample_fcurve_lane(lanes, 1, t, 0.0),
2036                            sample_fcurve_lane(lanes, 2, t, 0.0),
2037                        )
2038                        .blender_z_up_to_y_up();
2039                        vals.extend_from_slice(&v.to_array());
2040                    }
2041                    (GltfAnimationPath::Translation, 3, vals)
2042                }
2043                1 => {
2044                    let mut vals: Vec<f32> = Vec::with_capacity(times.len() * 4);
2045                    for &t in times.iter() {
2046                        let qw: f32 = sample_fcurve_lane(lanes, 0, t, 1.0);
2047                        let qx: f32 = sample_fcurve_lane(lanes, 1, t, 0.0);
2048                        let qy: f32 = sample_fcurve_lane(lanes, 2, t, 0.0);
2049                        let qz: f32 = sample_fcurve_lane(lanes, 3, t, 0.0);
2050                        let q_euv: Quat = Quat::from_xyzw(qx, qy, qz, qw)
2051                            .normalize()
2052                            .blender_z_up_to_y_up();
2053                        vals.extend_from_slice(&q_euv.to_array());
2054                    }
2055                    (GltfAnimationPath::Rotation, 4, vals)
2056                }
2057                2 => {
2058                    let mut vals: Vec<f32> = Vec::with_capacity(times.len() * 4);
2059                    for &t in times.iter() {
2060                        let q_blend: Quat = blend_euler_xyz_to_quat([
2061                            sample_fcurve_lane(lanes, 0, t, 0.0),
2062                            sample_fcurve_lane(lanes, 1, t, 0.0),
2063                            sample_fcurve_lane(lanes, 2, t, 0.0),
2064                        ]);
2065                        let q_euv: Quat = q_blend.blender_z_up_to_y_up();
2066                        vals.extend_from_slice(&q_euv.to_array());
2067                    }
2068                    (GltfAnimationPath::Rotation, 4, vals)
2069                }
2070                _ => {
2071                    let mut vals: Vec<f32> = Vec::with_capacity(times.len() * 3);
2072                    for &t in times.iter() {
2073                        let sx: f32 = sample_fcurve_lane(lanes, 0, t, 1.0);
2074                        let sy: f32 = sample_fcurve_lane(lanes, 1, t, 1.0);
2075                        let sz: f32 = sample_fcurve_lane(lanes, 2, t, 1.0);
2076                        vals.extend_from_slice(&[sx, sz, sy]);
2077                    }
2078                    (GltfAnimationPath::Scale, 3, vals)
2079                }
2080            };
2081            let sampler_index: usize = samplers.len();
2082            samplers.push(ImportedAnimationSampler3D {
2083                timestamps: times,
2084                values,
2085                value_stride: stride,
2086                interpolation: GltfInterpolationMode::Linear,
2087            });
2088            channels.push(ImportedAnimationChannel3D::new(
2089                target_node,
2090                anim_path,
2091                sampler_index,
2092            ));
2093        }
2094        let mut sorted_morph_keys: Vec<(u32, usize)> = morph_grouped.keys().copied().collect();
2095        sorted_morph_keys.sort();
2096        for key in sorted_morph_keys {
2097            let (target_node, total_morphs): (u32, usize) = key;
2098            let Some(lanes) = morph_grouped.get(&key) else {
2099                continue;
2100            };
2101            let mut times: Vec<f32> = Vec::new();
2102            for track in lanes.iter() {
2103                for &(t, _) in track.keyframes.iter() {
2104                    times.push(t);
2105                    if t > duration_secs {
2106                        duration_secs = t;
2107                    }
2108                }
2109            }
2110            times.sort_by(|a: &f32, b: &f32| a.total_cmp(b));
2111            times.dedup_by(|a: &mut f32, b: &mut f32| (*a - *b).abs() < 1e-5);
2112            if times.is_empty() || total_morphs == 0 {
2113                continue;
2114            }
2115            let mut vals: Vec<f32> = Vec::with_capacity(times.len() * total_morphs);
2116            for &t in times.iter() {
2117                for m_idx in 0..total_morphs {
2118                    let w: f32 = sample_fcurve_lane(lanes, m_idx, t, 0.0);
2119                    vals.push(w);
2120                }
2121            }
2122            let sampler_index: usize = samplers.len();
2123            samplers.push(ImportedAnimationSampler3D {
2124                timestamps: times,
2125                values: vals,
2126                value_stride: total_morphs,
2127                interpolation: GltfInterpolationMode::Linear,
2128            });
2129            channels.push(ImportedAnimationChannel3D::new(
2130                target_node,
2131                GltfAnimationPath::MorphWeights,
2132                sampler_index,
2133            ));
2134        }
2135        if !channels.is_empty() {
2136            clips.push(ImportedAnimationClip3D {
2137                name: clip_name,
2138                duration_secs,
2139                samplers,
2140                channels,
2141            });
2142        }
2143    }
2144    clips
2145}
2146
2147/// Parses a pure-Rust Blender 3.x/4.x/5.x `.blend` buffer directly into an `ImportedScene3D` without invoking an external Blender binary.
2148///
2149/// # Arguments
2150///
2151/// - `&[u8]` - Raw `.blend` binary buffer (uncompressed, gzip, or Zstd single/multi-frame archive).
2152///
2153/// # Returns
2154///
2155/// - `Result<ImportedScene3D, String>` - Imported 3D scene bundle or structured `.blend` parse error.
2156pub fn parse_blend_bytes(bytes: &[u8]) -> Result<ImportedScene3D, String> {
2157    if bytes.is_empty() {
2158        return Err(ERR_BLEND_SCENE_EMPTY.to_string());
2159    }
2160    let compression: BlendCompression = detect_blend_compression(bytes);
2161    let owned_decompressed: Vec<u8>;
2162    let data: &[u8] = match compression {
2163        BlendCompression::None => bytes,
2164        BlendCompression::Gzip => {
2165            owned_decompressed = inflate_gzip(bytes)?;
2166            &owned_decompressed
2167        }
2168        BlendCompression::Zstd => {
2169            owned_decompressed = decompress_zstd_frame(bytes)?;
2170            &owned_decompressed
2171        }
2172    };
2173    let archive: BlendArchiveView<'_> = BlendArchiveView::parse(data)?;
2174    let hdr: BlendHeader = archive.get_header();
2175    let generator: String = format!(
2176        "Blender {}.{}",
2177        hdr.get_version_major(),
2178        hdr.get_version_minor()
2179    );
2180    let mut offset_to_addr: HashMap<usize, u64> =
2181        HashMap::with_capacity(archive.get_blocks().len());
2182    for block in archive.get_blocks().iter() {
2183        if block.get_old_address() != 0 {
2184            let _: Option<u64> =
2185                offset_to_addr.insert(block.get_payload_start(), block.get_old_address());
2186        }
2187    }
2188    let (mut textures, image_to_tex): (Vec<Texture2D3D>, HashMap<u64, u32>) =
2189        extract_blend_images(&archive);
2190    let (materials, mat_addr_map): (Vec<PrincipledMaterial3D>, HashMap<u64, u32>) =
2191        extract_blend_materials(&archive, &offset_to_addr, &image_to_tex, &mut textures);
2192    let (cameras, cam_addr_map): (Vec<ImportedCamera3D>, HashMap<u64, u32>) =
2193        extract_blend_cameras(&archive);
2194    let (lights, light_addr_map): (Vec<ImportedLight3D>, HashMap<u64, u32>) =
2195        extract_blend_lights(&archive);
2196    let (mut extracted_meshes, mesh_addr_map): (Vec<BlendExtractedMesh>, HashMap<u64, u32>) =
2197        extract_blend_meshes(&archive, &materials, &mat_addr_map);
2198    let mut scene_name: String = DEFAULT_BLEND_SCENE_NAME.to_string();
2199    let mut fps: f32 = BLEND_DEFAULT_FPS;
2200    let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
2201    let mut obj_collection_masks: HashMap<u64, u64> = HashMap::new();
2202    let mut visited_cols: HashSet<u64> = HashSet::new();
2203    for block in archive.get_blocks().iter() {
2204        if block.get_kind() == BlendBlockKind::Scene
2205            && let Some(sc_view) = archive.block_struct_view(block, None, 0)
2206        {
2207            if let Some(name) = sc_view.id_name() {
2208                scene_name = name;
2209            }
2210            if let Some(render_data) = sc_view.read_embedded("r") {
2211                let frs: i32 = render_data
2212                    .read_i32("frs")
2213                    .or_else(|| render_data.read_i32(FLD_FRS_SEC))
2214                    .unwrap_or(24);
2215                if frs > 0 {
2216                    fps = frs as f32;
2217                }
2218            }
2219            if let Some(master_col) =
2220                sc_view.follow_ptr(FLD_MASTER_COLLECTION, Some(TYPE_COLLECTION))
2221            {
2222                walk_blend_collection(
2223                    &master_col,
2224                    1u64,
2225                    &mut visited_cols,
2226                    &offset_to_addr,
2227                    scene_graph.get_mut_collections(),
2228                    &mut obj_collection_masks,
2229                );
2230            }
2231        }
2232    }
2233    for block in archive.get_blocks().iter() {
2234        if block.get_kind() == BlendBlockKind::Collection
2235            && !visited_cols.contains(&block.get_old_address())
2236            && let Some(col_view) = archive.block_struct_view(block, None, 0)
2237        {
2238            walk_blend_collection(
2239                &col_view,
2240                1u64,
2241                &mut visited_cols,
2242                &offset_to_addr,
2243                scene_graph.get_mut_collections(),
2244                &mut obj_collection_masks,
2245            );
2246        }
2247    }
2248    let mut objects: Vec<BlendObjectStage> = Vec::new();
2249    let mut ob_addr_to_stage: HashMap<u64, usize> = HashMap::new();
2250    for block in archive.get_blocks().iter() {
2251        if block.get_kind() != BlendBlockKind::Object {
2252            continue;
2253        }
2254        let Some(ob_view) = archive.block_struct_view(block, None, 0) else {
2255            continue;
2256        };
2257        let ob_name: String = ob_view
2258            .id_name()
2259            .unwrap_or_else(|| format!("Object_{}", objects.len()));
2260        let ob_type: i32 = ob_view.read_i32(FLD_TYPE).unwrap_or(0);
2261        let parent_addr: u64 = ob_view.read_ptr(FLD_PARENT).unwrap_or(0);
2262        let data_addr: u64 = ob_view.read_ptr(FLD_DATA).unwrap_or(0);
2263        let world_mat_blend: Mat4 = read_blend_mat4(&ob_view, FLD_OBMAT).unwrap_or_else(|| {
2264            let loc: Vec<f32> = ob_view
2265                .read_f32_array("loc")
2266                .unwrap_or_else(|| vec![0.0, 0.0, 0.0]);
2267            let rot: Vec<f32> = ob_view
2268                .read_f32_array("rot")
2269                .unwrap_or_else(|| vec![0.0, 0.0, 0.0]);
2270            let scale: Vec<f32> = ob_view
2271                .read_f32_array(FLD_SCALE)
2272                .or_else(|| ob_view.read_f32_array(FLD_SIZE))
2273                .unwrap_or_else(|| vec![1.0, 1.0, 1.0]);
2274            let quat_arr: Option<Vec<f32>> = ob_view.read_f32_array(FLD_QUAT);
2275            let t_vec: Vec3 = if loc.len() >= 3 {
2276                Vec3::new(loc[0], loc[1], loc[2])
2277            } else {
2278                Vec3::zero()
2279            };
2280            let s_vec: Vec3 = if scale.len() >= 3 {
2281                let sx: f32 = if scale[0].abs() < 1e-6 { 1.0 } else { scale[0] };
2282                let sy: f32 = if scale[1].abs() < 1e-6 { 1.0 } else { scale[1] };
2283                let sz: f32 = if scale[2].abs() < 1e-6 { 1.0 } else { scale[2] };
2284                Vec3::new(sx, sy, sz)
2285            } else {
2286                Vec3::splat(1.0)
2287            };
2288            let q_rot: Quat = if let Some(qa) = quat_arr
2289                && qa.len() >= 4
2290                && (qa[0] * qa[0] + qa[1] * qa[1] + qa[2] * qa[2] + qa[3] * qa[3]) > 0.01
2291                && (rot.len() < 3 || (rot[0].abs() + rot[1].abs() + rot[2].abs()) < 1e-6)
2292            {
2293                Quat::from_xyzw(qa[1], qa[2], qa[3], qa[0]).normalize()
2294            } else if rot.len() >= 3 {
2295                blend_euler_xyz_to_quat([rot[0], rot[1], rot[2]])
2296            } else {
2297                Quat::identity()
2298            };
2299            Mat4::from_trs_quat(t_vec, q_rot, s_vec)
2300        });
2301        let restrict_flag: i32 = ob_view.read_i32(FLD_RESTRICTFLAG).unwrap_or(0);
2302        let vis_flag: i32 = ob_view.read_i32(FLD_VISIBILITY_FLAG).unwrap_or(0);
2303        let visible: bool = (restrict_flag & 1) == 0 && (vis_flag & 1) == 0;
2304        let mut vertex_groups: Vec<String> = ob_view
2305            .follow_list_base(FLD_DEFBASE, Some(TYPE_DEFORM_GROUP))
2306            .iter()
2307            .filter_map(|dg: &BlendStructView<'_>| dg.read_cstr(SDNA_FIELD_NAME))
2308            .collect();
2309        if vertex_groups.is_empty()
2310            && data_addr != 0
2311            && let Some(data_view) = archive.resolve_struct_at(data_addr, None)
2312        {
2313            vertex_groups = data_view
2314                .follow_list_base(FLD_VGROUP_NAMES, Some(TYPE_DEFORM_GROUP))
2315                .iter()
2316                .filter_map(|dg: &BlendStructView<'_>| dg.read_cstr(SDNA_FIELD_NAME))
2317                .collect();
2318        }
2319        let action_addr: u64 = ob_view
2320            .follow_ptr("adt", Some(TYPE_ANIM_DATA))
2321            .and_then(|adt: BlendStructView<'_>| adt.read_ptr(FLD_ACTION))
2322            .unwrap_or(0);
2323        let stage_idx: usize = objects.len();
2324        let _: Option<usize> = ob_addr_to_stage.insert(block.get_old_address(), stage_idx);
2325        objects.push(BlendObjectStage {
2326            old_address: block.get_old_address(),
2327            name: ob_name,
2328            ob_type,
2329            parent_addr,
2330            data_addr,
2331            world_mat_blend,
2332            visible,
2333            vertex_groups,
2334            action_addr,
2335        });
2336    }
2337    let mut ob_addr_to_node: HashMap<u64, u32> = HashMap::with_capacity(objects.len());
2338    for stage in objects.iter() {
2339        let mut node: SceneNode3D = SceneNode3D::from_name(stage.get_name(), None);
2340        node.set_visible(stage.get_visible());
2341        let col_mask: u64 = obj_collection_masks
2342            .get(&stage.get_old_address())
2343            .copied()
2344            .unwrap_or(1u64);
2345        node.set_collection_mask(col_mask);
2346        let node_id: u32 = scene_graph.add_node(node);
2347        let _: Option<u32> = ob_addr_to_node.insert(stage.get_old_address(), node_id);
2348    }
2349    let mut skins: Vec<ImportedSkin3D> = Vec::new();
2350    let mut armature_addr_to_extracted: HashMap<u64, BlendExtractedArmature> = HashMap::new();
2351    let mut all_bones_to_node: HashMap<String, u32> = HashMap::new();
2352    for block in archive.get_blocks().iter() {
2353        if block.get_kind() != BlendBlockKind::Armature {
2354            continue;
2355        }
2356        let Some(arm_view) = archive.block_struct_view(block, None, 0) else {
2357            continue;
2358        };
2359        let arm_name: String = arm_view
2360            .id_name()
2361            .unwrap_or_else(|| format!("Armature_{}", skins.len()));
2362        let owner_node: Option<u32> = objects
2363            .iter()
2364            .find(|st: &&BlendObjectStage| st.get_data_addr() == block.get_old_address())
2365            .and_then(|st: &BlendObjectStage| ob_addr_to_node.get(&st.get_old_address()).copied());
2366        let mut acc: BlendArmatureAccumulator = BlendArmatureAccumulator::default();
2367        let root_bones: Vec<BlendStructView<'_>> =
2368            arm_view.follow_list_base(FLD_BONEBASE, Some(TYPE_BONE));
2369        for root_bone in root_bones.iter() {
2370            walk_blend_bone(
2371                root_bone,
2372                owner_node,
2373                Mat4::identity(),
2374                &mut scene_graph,
2375                &mut acc,
2376            );
2377        }
2378        if !acc.joints.is_empty() {
2379            for (b_name, &b_node) in acc.bone_name_to_node.iter() {
2380                let _: Option<u32> = all_bones_to_node.insert(b_name.clone(), b_node);
2381            }
2382            let skin_index: u32 = skins.len() as u32;
2383            let skeleton_root: Option<u32> = owner_node.or_else(|| acc.joints.first().copied());
2384            skins.push(ImportedSkin3D {
2385                name: arm_name,
2386                joints: acc.joints,
2387                skeleton_root,
2388                inverse_bind_matrices: acc.inverse_bind_matrices,
2389            });
2390            let _: Option<BlendExtractedArmature> = armature_addr_to_extracted.insert(
2391                block.get_old_address(),
2392                BlendExtractedArmature {
2393                    skin_index,
2394                    bone_name_to_joint: acc.bone_name_to_joint,
2395                },
2396            );
2397        }
2398    }
2399    let mut action_to_node: HashMap<u64, u32> = HashMap::new();
2400    let mut shape_key_to_target: HashMap<String, (u32, usize, usize)> = HashMap::new();
2401    let c_to_y: Mat4 = Mat4::blender_z_up_to_y_up();
2402    for stage in objects.iter() {
2403        let Some(&node_id) = ob_addr_to_node.get(&stage.get_old_address()) else {
2404            continue;
2405        };
2406        if stage.get_action_addr() != 0 {
2407            let _: Option<u32> = action_to_node.insert(stage.get_action_addr(), node_id);
2408        }
2409        let parent_node: Option<u32> = ob_addr_to_node.get(&stage.get_parent_addr()).copied();
2410        let is_cam_or_light: bool = stage.get_ob_type() == BLEND_OB_TYPE_CAMERA
2411            || stage.get_ob_type() == BLEND_OB_TYPE_LAMP
2412            || cam_addr_map.contains_key(&stage.get_data_addr())
2413            || light_addr_map.contains_key(&stage.get_data_addr());
2414        let world_euv: Mat4 = if is_cam_or_light {
2415            c_to_y.mul(stage.get_world_mat_blend())
2416        } else {
2417            blend_mat4_to_y_up(stage.get_world_mat_blend())
2418        };
2419        let local_euv: Mat4 = if let Some(&p_stage_idx) =
2420            ob_addr_to_stage.get(&stage.get_parent_addr())
2421        {
2422            let p_world_euv: Mat4 = blend_mat4_to_y_up(objects[p_stage_idx].get_world_mat_blend());
2423            p_world_euv
2424                .inverse()
2425                .map(|inv_p: Mat4| inv_p.mul(world_euv))
2426                .unwrap_or(world_euv)
2427        } else {
2428            world_euv
2429        };
2430        let (local_t, local_r, local_s): (Vec3, Quat, Vec3) = local_euv.decompose_trs();
2431        let mesh_id: Option<u32> = mesh_addr_map.get(&stage.get_data_addr()).copied();
2432        let camera_id: Option<u32> = cam_addr_map.get(&stage.get_data_addr()).copied();
2433        let light_id: Option<u32> = light_addr_map.get(&stage.get_data_addr()).copied();
2434        let mut skin_id: Option<u32> = None;
2435        if let Some(m_idx) = mesh_id {
2436            let parent_arm: Option<&BlendExtractedArmature> = ob_addr_to_stage
2437                .get(&stage.get_parent_addr())
2438                .and_then(|&p_idx: &usize| {
2439                    armature_addr_to_extracted.get(&objects[p_idx].get_data_addr())
2440                })
2441                .or_else(|| {
2442                    if armature_addr_to_extracted.len() == 1
2443                        && !extracted_meshes[m_idx as usize]
2444                            .get_raw_deform_weights()
2445                            .is_empty()
2446                    {
2447                        armature_addr_to_extracted.values().next()
2448                    } else {
2449                        None
2450                    }
2451                });
2452            if let Some(arm_info) = parent_arm {
2453                let influences: Vec<MeshSkinInfluence3D> = build_skin_influences(
2454                    &extracted_meshes[m_idx as usize],
2455                    stage.get_vertex_groups(),
2456                    arm_info.get_bone_name_to_joint(),
2457                );
2458                if !influences.is_empty() {
2459                    let mut updated_mesh: Mesh3D =
2460                        extracted_meshes[m_idx as usize].get_mesh().clone();
2461                    updated_mesh.set_skin_influences(influences);
2462                    let _: &mut BlendExtractedMesh =
2463                        extracted_meshes[m_idx as usize].set_mesh(updated_mesh);
2464                    skin_id = Some(arm_info.get_skin_index());
2465                }
2466            }
2467            let sk_names: Vec<String> = extracted_meshes[m_idx as usize]
2468                .get_shape_key_names()
2469                .clone();
2470            let sk_weights: Vec<f32> = extracted_meshes[m_idx as usize]
2471                .get_shape_key_weights()
2472                .clone();
2473            let total_morphs: usize = sk_names.len();
2474            for (k_i, k_name) in sk_names.into_iter().enumerate() {
2475                let _: Option<(u32, usize, usize)> =
2476                    shape_key_to_target.insert(k_name, (node_id, k_i, total_morphs));
2477            }
2478            if !sk_weights.is_empty() {
2479                scene_graph.attach_morph_weights(node_id, &sk_weights);
2480            }
2481        }
2482        if let Some(node) = scene_graph.get_mut_nodes().get_mut(node_id as usize) {
2483            node.set_parent(parent_node);
2484            node.set_local_translation(local_t);
2485            node.set_local_rotation(local_r);
2486            node.set_local_scale(local_s);
2487            node.set_mesh_id(mesh_id);
2488            node.set_skin_id(skin_id);
2489            node.set_camera_id(camera_id);
2490            node.set_light_id(light_id);
2491        }
2492        scene_graph.set_topology_dirty(true);
2493    }
2494    if objects.is_empty() && !extracted_meshes.is_empty() {
2495        for (m_idx, ext_mesh) in extracted_meshes.iter().enumerate() {
2496            let mut node: SceneNode3D =
2497                SceneNode3D::from_name(ext_mesh.get_mesh().get_name(), None);
2498            node.set_mesh_id(Some(m_idx as u32));
2499            let _: u32 = scene_graph.add_node(node);
2500        }
2501    }
2502    let _: usize = scene_graph.propagate_world_matrices();
2503    let fallback_node: u32 = 0;
2504    let animations: Vec<ImportedAnimationClip3D> = extract_blend_animations(
2505        &archive,
2506        fps,
2507        &action_to_node,
2508        &all_bones_to_node,
2509        &shape_key_to_target,
2510        fallback_node,
2511    );
2512    let meshes: Vec<Mesh3D> = extracted_meshes
2513        .into_iter()
2514        .map(|ext: BlendExtractedMesh| ext.mesh)
2515        .collect();
2516    Ok(ImportedScene3D {
2517        name: scene_name,
2518        generator,
2519        scene_graph,
2520        meshes,
2521        materials,
2522        textures,
2523        skins,
2524        animations,
2525        cameras,
2526        lights,
2527    })
2528}