use super::*;
#[must_use]
fn gltf_type_components(type_str: &str) -> usize {
match type_str {
ACC_TYPE_SCALAR => 1,
ACC_TYPE_VEC2 => 2,
ACC_TYPE_VEC3 => 3,
ACC_TYPE_VEC4 | ACC_TYPE_MAT2 => 4,
ACC_TYPE_MAT3 => 9,
ACC_TYPE_MAT4 => 16,
_ => 0,
}
}
#[must_use]
fn gltf_component_byte_size(comp_type: u32) -> usize {
match comp_type {
GLTF_COMP_I8 | GLTF_COMP_U8 => 1,
GLTF_COMP_I16 | GLTF_COMP_U16 => 2,
GLTF_COMP_U32 | GLTF_COMP_F32 => 4,
_ => 0,
}
}
fn read_gltf_scalar_f32(
bytes: &[u8],
offset: usize,
comp_type: u32,
normalized: bool,
) -> Result<f32, String> {
let size: usize = gltf_component_byte_size(comp_type);
if size == 0 || offset.saturating_add(size) > bytes.len() {
return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
}
let val: f32 = match comp_type {
GLTF_COMP_I8 => {
let raw: f32 = f32::from(bytes[offset] as i8);
if normalized {
(raw / 127.0).max(-1.0)
} else {
raw
}
}
GLTF_COMP_U8 => {
let raw: f32 = f32::from(bytes[offset]);
if normalized { raw / 255.0 } else { raw }
}
GLTF_COMP_I16 => {
let raw: f32 = f32::from(i16::from_le_bytes([bytes[offset], bytes[offset + 1]]));
if normalized {
(raw / 32_767.0).max(-1.0)
} else {
raw
}
}
GLTF_COMP_U16 => {
let raw: f32 = f32::from(u16::from_le_bytes([bytes[offset], bytes[offset + 1]]));
if normalized { raw / 65_535.0 } else { raw }
}
GLTF_COMP_U32 => u32::from_le_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
]) as f32,
GLTF_COMP_F32 => f32::from_le_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
]),
_ => return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string()),
};
Ok(val)
}
fn read_gltf_scalar_u32(bytes: &[u8], offset: usize, comp_type: u32) -> Result<u32, String> {
let size: usize = gltf_component_byte_size(comp_type);
if size == 0 || offset.saturating_add(size) > bytes.len() {
return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
}
match comp_type {
GLTF_COMP_U8 => Ok(u32::from(bytes[offset])),
GLTF_COMP_U16 => Ok(u32::from(u16::from_le_bytes([
bytes[offset],
bytes[offset + 1],
]))),
GLTF_COMP_U32 => Ok(u32::from_le_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
])),
GLTF_COMP_I16 => Ok(i16::from_le_bytes([bytes[offset], bytes[offset + 1]]).max(0) as u32),
GLTF_COMP_I8 => Ok((bytes[offset] as i8).max(0) as u32),
_ => Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string()),
}
}
fn resolve_buffer_view<'a>(
root: &Value,
buffers: &'a [Vec<u8>],
view_idx: usize,
) -> Result<(&'a [u8], Option<usize>), String> {
let view: &Value = root
.get(KEY_BUFFER_VIEWS)
.and_then(Value::as_array)
.and_then(|arr: &Vec<Value>| arr.get(view_idx))
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let buf_idx: usize = view
.get(KEY_BUFFER)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
let byte_offset: usize = view
.get(KEY_BYTE_OFFSET)
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let byte_length: usize = view
.get(KEY_BYTE_LENGTH)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
let byte_stride: Option<usize> = view
.get(KEY_BYTE_STRIDE)
.and_then(Value::as_u64)
.map(|val: u64| val as usize);
let buf: &[u8] = buffers
.get(buf_idx)
.map(Vec::as_slice)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let end: usize = byte_offset.saturating_add(byte_length);
if end > buf.len() {
return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
}
Ok((&buf[byte_offset..end], byte_stride))
}
fn decode_accessor_f32(
root: &Value,
buffers: &[Vec<u8>],
accessor_idx: usize,
) -> Result<(Vec<f32>, usize, usize), String> {
let acc: &Value = root
.get(KEY_ACCESSORS)
.and_then(Value::as_array)
.and_then(|arr: &Vec<Value>| arr.get(accessor_idx))
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let comp_type: u32 = acc
.get(KEY_COMPONENT_TYPE)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as u32;
let count: usize = acc
.get(KEY_COUNT)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
let type_str: &str = acc
.get(KEY_TYPE)
.and_then(Value::as_str)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let comps: usize = gltf_type_components(type_str);
let comp_size: usize = gltf_component_byte_size(comp_type);
if comps == 0 || comp_size == 0 {
return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
}
let normalized: bool = acc
.get(KEY_NORMALIZED)
.and_then(Value::as_bool)
.unwrap_or(false);
let mut out: Vec<f32> = vec![0.0; count.saturating_mul(comps)];
if let Some(view_idx) = acc.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
let (view_slice, stride_opt): (&[u8], Option<usize>) =
resolve_buffer_view(root, buffers, view_idx as usize)?;
let acc_off: usize = acc
.get(KEY_BYTE_OFFSET)
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let elem_bytes: usize = comps * comp_size;
let stride: usize = stride_opt.unwrap_or(elem_bytes).max(elem_bytes);
for elem_idx in 0..count {
let base: usize = acc_off.saturating_add(elem_idx.saturating_mul(stride));
for c_idx in 0..comps {
let off: usize = base.saturating_add(c_idx.saturating_mul(comp_size));
out[elem_idx * comps + c_idx] =
read_gltf_scalar_f32(view_slice, off, comp_type, normalized)?;
}
}
}
if let Some(sparse) = acc.get(KEY_SPARSE) {
let sparse_count: usize =
sparse.get(KEY_COUNT).and_then(Value::as_u64).unwrap_or(0) as usize;
if sparse_count > 0 {
let idx_obj: &Value = sparse
.get(KEY_INDICES)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let val_obj: &Value = sparse
.get(KEY_VALUES)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let idx_view_id: usize = idx_obj
.get(KEY_BUFFER_VIEW)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
as usize;
let idx_off: usize = idx_obj
.get(KEY_BYTE_OFFSET)
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let idx_comp_type: u32 = idx_obj
.get(KEY_COMPONENT_TYPE)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
as u32;
let idx_step: usize = gltf_component_byte_size(idx_comp_type);
let val_view_id: usize = val_obj
.get(KEY_BUFFER_VIEW)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?
as usize;
let val_off: usize = val_obj
.get(KEY_BYTE_OFFSET)
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let (idx_slice, _): (&[u8], Option<usize>) =
resolve_buffer_view(root, buffers, idx_view_id)?;
let (val_slice, _): (&[u8], Option<usize>) =
resolve_buffer_view(root, buffers, val_view_id)?;
let val_elem_bytes: usize = comps * comp_size;
for sparse_i in 0..sparse_count {
let target_idx: usize = read_gltf_scalar_u32(
idx_slice,
idx_off.saturating_add(sparse_i.saturating_mul(idx_step)),
idx_comp_type,
)? as usize;
if target_idx >= count {
return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
}
let src_base: usize =
val_off.saturating_add(sparse_i.saturating_mul(val_elem_bytes));
for c_idx in 0..comps {
let off: usize = src_base.saturating_add(c_idx.saturating_mul(comp_size));
out[target_idx * comps + c_idx] =
read_gltf_scalar_f32(val_slice, off, comp_type, normalized)?;
}
}
}
}
Ok((out, count, comps))
}
fn decode_accessor_u32(
root: &Value,
buffers: &[Vec<u8>],
accessor_idx: usize,
) -> Result<(Vec<u32>, usize, usize), String> {
let acc: &Value = root
.get(KEY_ACCESSORS)
.and_then(Value::as_array)
.and_then(|arr: &Vec<Value>| arr.get(accessor_idx))
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let comp_type: u32 = acc
.get(KEY_COMPONENT_TYPE)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as u32;
let count: usize = acc
.get(KEY_COUNT)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())? as usize;
let type_str: &str = acc
.get(KEY_TYPE)
.and_then(Value::as_str)
.ok_or_else(|| ERR_GLTF_ACCESSOR_BOUNDS.to_string())?;
let comps: usize = gltf_type_components(type_str);
let comp_size: usize = gltf_component_byte_size(comp_type);
if comps == 0 || comp_size == 0 {
return Err(ERR_GLTF_ACCESSOR_BOUNDS.to_string());
}
let mut out: Vec<u32> = vec![0u32; count.saturating_mul(comps)];
if let Some(view_idx) = acc.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
let (view_slice, stride_opt): (&[u8], Option<usize>) =
resolve_buffer_view(root, buffers, view_idx as usize)?;
let acc_off: usize = acc
.get(KEY_BYTE_OFFSET)
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let elem_bytes: usize = comps * comp_size;
let stride: usize = stride_opt.unwrap_or(elem_bytes).max(elem_bytes);
for elem_idx in 0..count {
let base: usize = acc_off.saturating_add(elem_idx.saturating_mul(stride));
for c_idx in 0..comps {
let off: usize = base.saturating_add(c_idx.saturating_mul(comp_size));
out[elem_idx * comps + c_idx] = read_gltf_scalar_u32(view_slice, off, comp_type)?;
}
}
}
Ok((out, count, comps))
}
fn decode_data_uri(uri: &str) -> Result<Vec<u8>, String> {
let marker_pos: usize = uri
.find(GLTF_BASE64_MARKER)
.ok_or_else(|| ERR_GLTF_URI_RESOLVE.to_string())?;
let b64_str: &str = &uri[(marker_pos + GLTF_BASE64_MARKER.len())..];
decode_base64(b64_str)
}
#[must_use]
fn json_f32_2(value: Option<&Value>, default: [f32; 2]) -> [f32; 2] {
let Some(arr) = value.and_then(Value::as_array) else {
return default;
};
if arr.len() < 2 {
return default;
}
[
arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
]
}
#[must_use]
fn json_f32_3(value: Option<&Value>, default: [f32; 3]) -> [f32; 3] {
let Some(arr) = value.and_then(Value::as_array) else {
return default;
};
if arr.len() < 3 {
return default;
}
[
arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
arr[2].as_f64().unwrap_or(f64::from(default[2])) as f32,
]
}
#[must_use]
fn json_f32_4(value: Option<&Value>, default: [f32; 4]) -> [f32; 4] {
let Some(arr) = value.and_then(Value::as_array) else {
return default;
};
if arr.len() < 4 {
return default;
}
[
arr[0].as_f64().unwrap_or(f64::from(default[0])) as f32,
arr[1].as_f64().unwrap_or(f64::from(default[1])) as f32,
arr[2].as_f64().unwrap_or(f64::from(default[2])) as f32,
arr[3].as_f64().unwrap_or(f64::from(default[3])) as f32,
]
}
#[must_use]
fn parse_texture_slot(info_opt: Option<&Value>) -> Option<TextureSlot3D> {
let info: &Value = info_opt?;
let tex_index: u32 = info.get(KEY_INDEX).and_then(Value::as_u64)? as u32;
let mut tex_coord: u8 = info.get(KEY_TEX_COORD).and_then(Value::as_u64).unwrap_or(0) as u8;
let mut transform: TextureTransform3D = TextureTransform3D::default();
if let Some(tt) = info
.get(KEY_EXTENSIONS)
.and_then(|ext: &Value| ext.get(GLTF_EXT_TEX_TRANSFORM))
{
let offset_arr: [f32; 2] = json_f32_2(tt.get(KEY_OFFSET), [0.0, 0.0]);
let rotation: f32 = tt.get(KEY_ROTATION).and_then(Value::as_f64).unwrap_or(0.0) as f32;
let scale_arr: [f32; 2] = json_f32_2(tt.get(KEY_SCALE), [1.0, 1.0]);
if let Some(override_uv) = tt.get(KEY_TEX_COORD).and_then(Value::as_u64) {
tex_coord = override_uv as u8;
}
transform = TextureTransform3D::from_trs(
Vec2::from_array(offset_arr),
rotation,
Vec2::from_array(scale_arr),
);
}
Some(TextureSlot3D {
texture_index: tex_index,
tex_coord,
transform,
})
}
#[must_use]
fn parse_principled_material(mat_val: &Value, mat_idx: usize) -> PrincipledMaterial3D {
let mut mat: PrincipledMaterial3D = PrincipledMaterial3D::default();
let name: String = mat_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("material_{mat_idx}"));
mat.set_name(name);
if let Some(pbr) = mat_val.get(KEY_PBR_MR) {
mat.set_base_color_factor(json_f32_4(
pbr.get(KEY_BASE_COLOR_FACTOR),
[1.0, 1.0, 1.0, 1.0],
));
mat.set_base_color_texture(parse_texture_slot(pbr.get(KEY_BASE_COLOR_TEX)));
let metallic: f32 = pbr
.get(KEY_METALLIC_FACTOR)
.and_then(Value::as_f64)
.unwrap_or(1.0) as f32;
let roughness: f32 = pbr
.get(KEY_ROUGHNESS_FACTOR)
.and_then(Value::as_f64)
.unwrap_or(1.0) as f32;
mat.set_metallic_factor(metallic.clamp(0.0, 1.0));
mat.set_roughness_factor(roughness.clamp(0.04, 1.0));
mat.set_metallic_roughness_texture(parse_texture_slot(pbr.get(KEY_MR_TEX)));
}
if let Some(norm_obj) = mat_val.get(KEY_NORMAL_TEX) {
mat.set_normal_texture(parse_texture_slot(Some(norm_obj)));
let scale: f32 = norm_obj
.get(KEY_SCALE)
.and_then(Value::as_f64)
.unwrap_or(1.0) as f32;
mat.set_normal_scale(scale);
}
if let Some(occ_obj) = mat_val.get(KEY_OCCLUSION_TEX) {
mat.set_occlusion_texture(parse_texture_slot(Some(occ_obj)));
let strength: f32 = occ_obj
.get(KEY_STRENGTH)
.and_then(Value::as_f64)
.unwrap_or(1.0) as f32;
mat.set_occlusion_strength(strength.clamp(0.0, 1.0));
}
mat.set_emissive_factor(json_f32_3(
mat_val.get(KEY_EMISSIVE_FACTOR),
[0.0, 0.0, 0.0],
));
mat.set_emissive_texture(parse_texture_slot(mat_val.get(KEY_EMISSIVE_TEX)));
if let Some(alpha_str) = mat_val.get(KEY_ALPHA_MODE).and_then(Value::as_str) {
let mode: AlphaMode3D = if alpha_str == ALPHA_MODE_MASK {
AlphaMode3D::Mask
} else if alpha_str == ALPHA_MODE_BLEND {
AlphaMode3D::Blend
} else {
AlphaMode3D::Opaque
};
mat.set_alpha_mode(mode);
}
if let Some(cutoff) = mat_val.get(KEY_ALPHA_CUTOFF).and_then(Value::as_f64) {
mat.set_alpha_cutoff(cutoff as f32);
}
if let Some(ds) = mat_val.get(KEY_DOUBLE_SIDED).and_then(Value::as_bool) {
mat.set_double_sided(ds);
}
if let Some(ext) = mat_val.get(KEY_EXTENSIONS) {
if let Some(em_ext) = ext.get(GLTF_EXT_EMISSIVE_STRENGTH)
&& let Some(val) = em_ext.get(KEY_EMISSIVE_STRENGTH).and_then(Value::as_f64)
{
mat.set_emissive_strength((val as f32).max(0.0));
}
if let Some(ior_ext) = ext.get(GLTF_EXT_IOR)
&& let Some(val) = ior_ext.get("ior").and_then(Value::as_f64)
{
mat.set_ior((val as f32).max(1.0));
}
if let Some(spec_ext) = ext.get(GLTF_EXT_SPECULAR) {
if let Some(sf) = spec_ext.get(KEY_SPECULAR_FACTOR).and_then(Value::as_f64) {
mat.set_specular_factor((sf as f32).clamp(0.0, 1.0));
}
mat.set_specular_color_factor(json_f32_3(
spec_ext.get(KEY_SPECULAR_COLOR_FACTOR),
[1.0, 1.0, 1.0],
));
mat.set_specular_texture(parse_texture_slot(spec_ext.get(KEY_SPECULAR_TEX)));
mat.set_specular_color_texture(parse_texture_slot(
spec_ext.get(KEY_SPECULAR_COLOR_TEX),
));
}
if let Some(cc_ext) = ext.get(GLTF_EXT_CLEARCOAT) {
if let Some(cf) = cc_ext.get(KEY_CLEARCOAT_FACTOR).and_then(Value::as_f64) {
mat.set_clearcoat_factor((cf as f32).clamp(0.0, 1.0));
}
if let Some(cr) = cc_ext.get(KEY_CLEARCOAT_ROUGHNESS).and_then(Value::as_f64) {
mat.set_clearcoat_roughness_factor((cr as f32).clamp(0.0, 1.0));
}
mat.set_clearcoat_texture(parse_texture_slot(cc_ext.get(KEY_CLEARCOAT_TEX)));
mat.set_clearcoat_roughness_texture(parse_texture_slot(
cc_ext.get(KEY_CLEARCOAT_ROUGH_TEX),
));
mat.set_clearcoat_normal_texture(parse_texture_slot(
cc_ext.get(KEY_CLEARCOAT_NORM_TEX),
));
}
if let Some(tr_ext) = ext.get(GLTF_EXT_TRANSMISSION) {
if let Some(tf) = tr_ext.get(KEY_TRANSMISSION_FACTOR).and_then(Value::as_f64) {
mat.set_transmission_factor((tf as f32).clamp(0.0, 1.0));
}
mat.set_transmission_texture(parse_texture_slot(tr_ext.get(KEY_TRANSMISSION_TEX)));
}
if let Some(vol_ext) = ext.get(GLTF_EXT_VOLUME) {
if let Some(th) = vol_ext.get(KEY_THICKNESS_FACTOR).and_then(Value::as_f64) {
mat.set_thickness_factor((th as f32).max(0.0));
}
if let Some(ad) = vol_ext.get(KEY_ATTENUATION_DIST).and_then(Value::as_f64) {
mat.set_attenuation_distance((ad as f32).max(1e-4));
}
mat.set_attenuation_color(json_f32_3(
vol_ext.get(KEY_ATTENUATION_COLOR),
[1.0, 1.0, 1.0],
));
}
if let Some(sh_ext) = ext.get(GLTF_EXT_SHEEN) {
mat.set_sheen_color_factor(json_f32_3(sh_ext.get(KEY_SHEEN_COLOR), [0.0, 0.0, 0.0]));
if let Some(sr) = sh_ext.get(KEY_SHEEN_ROUGHNESS).and_then(Value::as_f64) {
mat.set_sheen_roughness_factor((sr as f32).clamp(0.0, 1.0));
}
mat.set_sheen_color_texture(parse_texture_slot(sh_ext.get(KEY_SHEEN_COLOR_TEX)));
mat.set_sheen_roughness_texture(parse_texture_slot(sh_ext.get(KEY_SHEEN_ROUGH_TEX)));
}
if ext.get(GLTF_EXT_UNLIT).is_some() {
mat.set_unlit(true);
}
}
mat
}
#[must_use]
fn assemble_primitive_triangles(raw_indices: &[u32], mode: u32) -> Vec<[u32; 3]> {
let mut tris: Vec<[u32; 3]> = Vec::new();
match mode {
GLTF_MODE_TRIANGLE_STRIP => {
if raw_indices.len() >= 3 {
tris.reserve(raw_indices.len() - 2);
for idx in 0..(raw_indices.len() - 2) {
let i0: u32 = raw_indices[idx];
let i1: u32 = raw_indices[idx + 1];
let i2: u32 = raw_indices[idx + 2];
if i0 == i1 || i1 == i2 || i0 == i2 {
continue;
}
if (idx & 1) == 0 {
tris.push([i0, i1, i2]);
} else {
tris.push([i1, i0, i2]);
}
}
}
}
GLTF_MODE_TRIANGLE_FAN => {
if raw_indices.len() >= 3 {
tris.reserve(raw_indices.len() - 2);
let anchor: u32 = raw_indices[0];
for idx in 1..(raw_indices.len() - 1) {
tris.push([anchor, raw_indices[idx], raw_indices[idx + 1]]);
}
}
}
_ => {
tris.reserve(raw_indices.len() / 3);
for tri in raw_indices.as_chunks::<3>().0 {
tris.push(*tri);
}
}
}
tris
}
pub fn parse_gltf_document(
json_source: &str,
glb_bin_chunk: Option<&[u8]>,
resolver: Option<&dyn GltfBufferResolver>,
) -> Result<ImportedScene3D, String> {
let root: Value = from_str::<Value>(json_source)
.ok()
.ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
let generator: String = root
.get(KEY_ASSET)
.and_then(|asset: &Value| asset.get(KEY_GENERATOR))
.and_then(Value::as_str)
.unwrap_or(GLTF_DEFAULT_SCENE_NAME)
.to_string();
let default_scene_idx: usize =
root.get(KEY_SCENE).and_then(Value::as_u64).unwrap_or(0) as usize;
let scene_name: String = root
.get(KEY_SCENES)
.and_then(Value::as_array)
.and_then(|arr: &Vec<Value>| arr.get(default_scene_idx))
.and_then(|sc: &Value| sc.get(KEY_NAME))
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| generator.clone());
let mut buffers: Vec<Vec<u8>> = Vec::new();
if let Some(bufs_arr) = root.get(KEY_BUFFERS).and_then(Value::as_array) {
for (buf_idx, buf_val) in bufs_arr.iter().enumerate() {
if let Some(uri) = buf_val.get("uri").and_then(Value::as_str) {
if uri.starts_with(GLTF_DATA_URI_PREFIX) {
buffers.push(decode_data_uri(uri)?);
} else if let Some(res) = resolver {
buffers.push(res.resolve_buffer(uri)?);
} else {
return Err(ERR_GLTF_URI_RESOLVE.to_string());
}
} else if buf_idx == 0
&& let Some(bin) = glb_bin_chunk
{
buffers.push(bin.to_vec());
} else {
buffers.push(Vec::new());
}
}
} else if let Some(bin) = glb_bin_chunk {
buffers.push(bin.to_vec());
}
let mut materials: Vec<PrincipledMaterial3D> = Vec::new();
if let Some(mats_arr) = root.get(KEY_MATERIALS).and_then(Value::as_array) {
for (mat_idx, mat_val) in mats_arr.iter().enumerate() {
materials.push(parse_principled_material(mat_val, mat_idx));
}
}
let mut tex_spaces: HashMap<u32, TextureColorSpace> = HashMap::new();
for mat in materials.iter() {
if let Some(slot) = mat.try_get_base_color_texture() {
let _: Option<TextureColorSpace> =
tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
}
if let Some(slot) = mat.try_get_emissive_texture() {
let _: Option<TextureColorSpace> =
tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
}
if let Some(slot) = mat.try_get_sheen_color_texture() {
let _: Option<TextureColorSpace> =
tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::Srgb);
}
if let Some(slot) = mat.try_get_normal_texture() {
let _: Option<TextureColorSpace> =
tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::NormalTangent);
}
if let Some(slot) = mat.try_get_clearcoat_normal_texture() {
let _: Option<TextureColorSpace> =
tex_spaces.insert(slot.get_texture_index(), TextureColorSpace::NormalTangent);
}
for slot in [
mat.try_get_metallic_roughness_texture(),
mat.try_get_occlusion_texture(),
mat.try_get_clearcoat_texture(),
mat.try_get_clearcoat_roughness_texture(),
mat.try_get_transmission_texture(),
mat.try_get_specular_texture(),
mat.try_get_sheen_roughness_texture(),
]
.into_iter()
.flatten()
{
let _: &mut TextureColorSpace = tex_spaces
.entry(slot.get_texture_index())
.or_insert(TextureColorSpace::Linear);
}
}
let mut samplers: Vec<TextureSampler3D> = Vec::new();
if let Some(samps_arr) = root.get(KEY_SAMPLERS).and_then(Value::as_array) {
for samp_val in samps_arr.iter() {
let mag: TextureFilterMode = samp_val
.get(KEY_MAG_FILTER)
.and_then(Value::as_u64)
.map(|code: u64| TextureFilterMode::from_gltf_code(code as u32))
.unwrap_or(TextureFilterMode::Linear);
let min: TextureFilterMode = samp_val
.get(KEY_MIN_FILTER)
.and_then(Value::as_u64)
.map(|code: u64| TextureFilterMode::from_gltf_code(code as u32))
.unwrap_or(TextureFilterMode::LinearMipmapLinear);
let wrap_s: TextureWrapMode = samp_val
.get(KEY_WRAP_S)
.and_then(Value::as_u64)
.map(|code: u64| TextureWrapMode::from_gltf_code(code as u32))
.unwrap_or(TextureWrapMode::Repeat);
let wrap_t: TextureWrapMode = samp_val
.get(KEY_WRAP_T)
.and_then(Value::as_u64)
.map(|code: u64| TextureWrapMode::from_gltf_code(code as u32))
.unwrap_or(TextureWrapMode::Repeat);
samplers.push(TextureSampler3D::new(mag, min, wrap_s, wrap_t));
}
}
let mut raw_images: Vec<(String, Vec<u8>)> = Vec::new();
if let Some(imgs_arr) = root.get(KEY_IMAGES).and_then(Value::as_array) {
for (img_idx, img_val) in imgs_arr.iter().enumerate() {
let img_name: String = img_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("image_{img_idx}"));
let img_bytes: Vec<u8> =
if let Some(view_idx) = img_val.get(KEY_BUFFER_VIEW).and_then(Value::as_u64) {
let (slice, _): (&[u8], Option<usize>) =
resolve_buffer_view(&root, &buffers, view_idx as usize)?;
slice.to_vec()
} else if let Some(uri) = img_val.get("uri").and_then(Value::as_str) {
if uri.starts_with(GLTF_DATA_URI_PREFIX) {
decode_data_uri(uri)?
} else if let Some(res) = resolver {
res.resolve_image(uri)?
} else {
Vec::new()
}
} else {
Vec::new()
};
raw_images.push((img_name, img_bytes));
}
}
let mut textures: Vec<Texture2D3D> = Vec::new();
if let Some(texs_arr) = root.get(KEY_TEXTURES).and_then(Value::as_array) {
for (tex_idx, tex_val) in texs_arr.iter().enumerate() {
let color_space: TextureColorSpace = tex_spaces
.get(&(tex_idx as u32))
.copied()
.unwrap_or(TextureColorSpace::Srgb);
let sampler: TextureSampler3D = tex_val
.get(KEY_SAMPLER)
.and_then(Value::as_u64)
.and_then(|s_idx: u64| samplers.get(s_idx as usize).copied())
.unwrap_or_default();
let tex_name: String = tex_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("texture_{tex_idx}"));
let mut decoded_tex: Texture2D3D = if let Some(src_idx) =
tex_val.get(KEY_SOURCE).and_then(Value::as_u64)
&& let Some((img_name, img_bytes)) = raw_images.get(src_idx as usize)
&& !img_bytes.is_empty()
{
let label: &str = if tex_val.get(KEY_NAME).is_some() {
&tex_name
} else {
img_name
};
Texture2D3D::from_encoded_bytes(label, img_bytes, color_space, true)?
} else {
Texture2D3D::from_rgba8(
&tex_name,
1,
1,
vec![255, 255, 255, 255],
color_space,
false,
)?
};
decoded_tex.set_sampler(sampler);
textures.push(decoded_tex);
}
}
let mut meshes: Vec<Mesh3D> = Vec::new();
let mut gltf_mesh_to_first_prim: Vec<usize> = Vec::new();
if let Some(meshes_arr) = root.get(KEY_MESHES).and_then(Value::as_array) {
for (mesh_idx, mesh_val) in meshes_arr.iter().enumerate() {
gltf_mesh_to_first_prim.push(meshes.len());
let mesh_name: String = mesh_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("{scene_name}_mesh_{mesh_idx}"));
let target_names: Vec<String> = mesh_val
.get(KEY_EXTRAS)
.and_then(|ext: &Value| ext.get(KEY_TARGET_NAMES))
.and_then(Value::as_array)
.map(|arr: &Vec<Value>| {
arr.iter()
.filter_map(|item: &Value| item.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default();
let Some(prims) = mesh_val.get(KEY_PRIMITIVES).and_then(Value::as_array) else {
continue;
};
for (prim_idx, prim) in prims.iter().enumerate() {
let prim_name: String = if prims.len() == 1 {
mesh_name.clone()
} else {
format!("{mesh_name}_prim_{prim_idx}")
};
let mat_opt: Option<u32> = prim
.get(KEY_MATERIAL)
.and_then(Value::as_u64)
.map(|idx: u64| idx as u32);
let legacy_mat: PbrMaterial = mat_opt
.and_then(|idx: u32| materials.get(idx as usize))
.or_else(|| materials.first())
.map(PrincipledMaterial3D::to_legacy_pbr)
.unwrap_or_default();
if let Some(attrs) = prim.get(KEY_ATTRIBUTES).and_then(Value::as_object) {
let Some(pos_acc_idx) = attrs.get(ATTR_POSITION).and_then(Value::as_u64) else {
continue;
};
let (pos_floats, vert_count, pos_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, pos_acc_idx as usize)?;
if pos_comps < 3 || vert_count == 0 {
continue;
}
let mut vertices: Vec<Vertex3D> = Vec::with_capacity(vert_count);
for v_idx in 0..vert_count {
let base: usize = v_idx * pos_comps;
vertices.push(Vertex3D::new(
Vec3::new(pos_floats[base], pos_floats[base + 1], pos_floats[base + 2]),
Vec3::new(0.0, 1.0, 0.0),
));
}
let has_normals: bool = if let Some(n_acc) =
attrs.get(ATTR_NORMAL).and_then(Value::as_u64)
{
let (n_floats, n_count, n_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, n_acc as usize)?;
if n_comps >= 3 && n_count >= vert_count {
for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
{
let base: usize = v_idx * n_comps;
vertex.set_normal(
Vec3::new(
n_floats[base],
n_floats[base + 1],
n_floats[base + 2],
)
.normalize(),
);
}
true
} else {
false
}
} else {
false
};
let has_tangents: bool = if let Some(t_acc) =
attrs.get(ATTR_TANGENT).and_then(Value::as_u64)
{
let (t_floats, t_count, t_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, t_acc as usize)?;
if t_comps >= 4 && t_count >= vert_count {
for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
{
let base: usize = v_idx * t_comps;
vertex.set_tangent([
t_floats[base],
t_floats[base + 1],
t_floats[base + 2],
t_floats[base + 3],
]);
let next_flags: u32 = vertex.get_flags() | 4;
vertex.set_flags(next_flags);
}
true
} else {
false
}
} else {
false
};
if let Some(uv0_acc) = attrs.get(ATTR_TEXCOORD_0).and_then(Value::as_u64) {
let (uv_floats, uv_count, uv_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, uv0_acc as usize)?;
if uv_comps >= 2 && uv_count >= vert_count {
for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
{
let base: usize = v_idx * uv_comps;
vertex.set_uv0([uv_floats[base], uv_floats[base + 1]]);
let next_flags: u32 = vertex.get_flags() | 1;
vertex.set_flags(next_flags);
}
}
}
if let Some(uv1_acc) = attrs.get(ATTR_TEXCOORD_1).and_then(Value::as_u64) {
let (uv_floats, uv_count, uv_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, uv1_acc as usize)?;
if uv_comps >= 2 && uv_count >= vert_count {
for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
{
let base: usize = v_idx * uv_comps;
vertex.set_uv1([uv_floats[base], uv_floats[base + 1]]);
let next_flags: u32 = vertex.get_flags() | 2;
vertex.set_flags(next_flags);
}
}
}
if let Some(col_acc) = attrs.get(ATTR_COLOR_0).and_then(Value::as_u64) {
let (c_floats, c_count, c_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, col_acc as usize)?;
if c_comps >= 3 && c_count >= vert_count {
for (v_idx, vertex) in vertices.iter_mut().enumerate().take(vert_count)
{
let base: usize = v_idx * c_comps;
let r_u8: u8 =
(c_floats[base].clamp(0.0, 1.0) * 255.0).round() as u8;
let g_u8: u8 =
(c_floats[base + 1].clamp(0.0, 1.0) * 255.0).round() as u8;
let b_u8: u8 =
(c_floats[base + 2].clamp(0.0, 1.0) * 255.0).round() as u8;
let a_u8: u8 = if c_comps >= 4 {
(c_floats[base + 3].clamp(0.0, 1.0) * 255.0).round() as u8
} else {
255
};
vertex.set_color0([r_u8, g_u8, b_u8, a_u8]);
let next_flags: u32 = vertex.get_flags() | 8;
vertex.set_flags(next_flags);
}
}
}
let mut skin_influences: Vec<MeshSkinInfluence3D> = Vec::new();
if let Some(j0_acc) = attrs.get(ATTR_JOINTS_0).and_then(Value::as_u64)
&& let Some(w0_acc) = attrs.get(ATTR_WEIGHTS_0).and_then(Value::as_u64)
{
let (j0_vals, j0_cnt, j0_c): (Vec<u32>, usize, usize) =
decode_accessor_u32(&root, &buffers, j0_acc as usize)?;
let (w0_vals, w0_cnt, w0_c): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, w0_acc as usize)?;
let j1_data: Option<(Vec<u32>, usize, usize)> = attrs
.get(ATTR_JOINTS_1)
.and_then(Value::as_u64)
.and_then(|id: u64| {
decode_accessor_u32(&root, &buffers, id as usize).ok()
});
let w1_data: Option<(Vec<f32>, usize, usize)> =
attrs.get(ATTR_WEIGHTS_1).and_then(Value::as_u64).and_then(
|id: u64| decode_accessor_f32(&root, &buffers, id as usize).ok(),
);
if j0_c >= 4 && w0_c >= 4 && j0_cnt >= vert_count && w0_cnt >= vert_count {
skin_influences.reserve(vert_count);
for v_idx in 0..vert_count {
let jb: usize = v_idx * j0_c;
let wb: usize = v_idx * w0_c;
let joints_0: [u16; 4] = [
j0_vals[jb] as u16,
j0_vals[jb + 1] as u16,
j0_vals[jb + 2] as u16,
j0_vals[jb + 3] as u16,
];
let mut weights_0: [f32; 4] = [
w0_vals[wb].max(0.0),
w0_vals[wb + 1].max(0.0),
w0_vals[wb + 2].max(0.0),
w0_vals[wb + 3].max(0.0),
];
let mut joints_1: [u16; 4] = [0u16; 4];
let mut weights_1: [f32; 4] = [0.0; 4];
if let (Some((j1v, j1cnt, j1c)), Some((w1v, w1cnt, w1c))) =
(&j1_data, &w1_data)
&& *j1c >= 4
&& *w1c >= 4
&& *j1cnt >= vert_count
&& *w1cnt >= vert_count
{
let j1b: usize = v_idx * (*j1c);
let w1b: usize = v_idx * (*w1c);
joints_1 = [
j1v[j1b] as u16,
j1v[j1b + 1] as u16,
j1v[j1b + 2] as u16,
j1v[j1b + 3] as u16,
];
weights_1 = [
w1v[w1b].max(0.0),
w1v[w1b + 1].max(0.0),
w1v[w1b + 2].max(0.0),
w1v[w1b + 3].max(0.0),
];
}
let sum_w: f32 = weights_0[0]
+ weights_0[1]
+ weights_0[2]
+ weights_0[3]
+ weights_1[0]
+ weights_1[1]
+ weights_1[2]
+ weights_1[3];
if sum_w > 1e-6 {
let inv_w: f32 = 1.0 / sum_w;
for lane in 0..4usize {
weights_0[lane] *= inv_w;
weights_1[lane] *= inv_w;
}
}
skin_influences.push(MeshSkinInfluence3D::new(
joints_0, weights_0, joints_1, weights_1,
));
}
}
}
let mut morph_targets: Vec<MorphTarget3D> = Vec::new();
if let Some(targets_arr) = prim.get(KEY_TARGETS).and_then(Value::as_array) {
for (t_idx, target_val) in targets_arr.iter().enumerate() {
let target_name: String = target_names
.get(t_idx)
.cloned()
.unwrap_or_else(|| format!("shape_key_{t_idx}"));
let mut delta_positions: Vec<[f32; 3]> = Vec::new();
if let Some(dp_acc) =
target_val.get(ATTR_POSITION).and_then(Value::as_u64)
{
let (dp, cnt, comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, dp_acc as usize)?;
if comps >= 3 {
delta_positions.reserve(cnt);
for i in 0..cnt {
let b: usize = i * comps;
delta_positions.push([dp[b], dp[b + 1], dp[b + 2]]);
}
}
}
let mut delta_normals: Vec<[f32; 3]> = Vec::new();
if let Some(dn_acc) =
target_val.get(ATTR_NORMAL).and_then(Value::as_u64)
{
let (dn, cnt, comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, dn_acc as usize)?;
if comps >= 3 {
delta_normals.reserve(cnt);
for i in 0..cnt {
let b: usize = i * comps;
delta_normals.push([dn[b], dn[b + 1], dn[b + 2]]);
}
}
}
let mut delta_tangents: Vec<[f32; 3]> = Vec::new();
if let Some(dt_acc) =
target_val.get(ATTR_TANGENT).and_then(Value::as_u64)
{
let (dt, cnt, comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, dt_acc as usize)?;
if comps >= 3 {
delta_tangents.reserve(cnt);
for i in 0..cnt {
let b: usize = i * comps;
delta_tangents.push([dt[b], dt[b + 1], dt[b + 2]]);
}
}
}
morph_targets.push(MorphTarget3D {
name: target_name,
delta_positions,
delta_normals,
delta_tangents,
});
}
}
let raw_indices: Vec<u32> =
if let Some(idx_acc) = prim.get(KEY_INDICES).and_then(Value::as_u64) {
let (vals, _, _): (Vec<u32>, usize, usize) =
decode_accessor_u32(&root, &buffers, idx_acc as usize)?;
vals
} else {
(0..(vert_count as u32)).collect()
};
let mode: u32 = prim
.get(KEY_MODE)
.and_then(Value::as_u64)
.unwrap_or(u64::from(GLTF_MODE_TRIANGLES))
as u32;
let tris: Vec<[u32; 3]> = assemble_primitive_triangles(&raw_indices, mode);
if !tris.is_empty() {
let mut built: Mesh3D =
Mesh3D::from_parts(prim_name, vertices, tris, legacy_mat);
if !has_normals {
built.compute_smooth_normals();
}
if !has_tangents {
built.compute_lengyel_tangents();
}
built.set_skin_influences(skin_influences);
built.set_morph_targets(morph_targets);
built.set_material_index(mat_opt);
meshes.push(built);
}
} else {
let extras: &Value = prim.get(KEY_EXTRAS).unwrap_or(prim);
let pos_vals: Vec<f32> = extras
.get(KEY_LEGACY_POSITIONS)
.and_then(Value::as_array)
.map(|arr: &Vec<Value>| {
arr.iter()
.filter_map(|item: &Value| item.as_f64().map(|val: f64| val as f32))
.collect()
})
.unwrap_or_default();
let idx_vals: Vec<u32> = extras
.get(KEY_INDICES)
.and_then(Value::as_array)
.map(|arr: &Vec<Value>| {
arr.iter()
.filter_map(|item: &Value| item.as_u64().map(|val: u64| val as u32))
.collect()
})
.unwrap_or_default();
let raw_pts: Vec<Vec3> = pos_vals
.as_chunks::<3>()
.0
.iter()
.map(|chunk: &[f32; 3]| Vec3::new(chunk[0], chunk[1], chunk[2]))
.collect();
let mut verts: Vec<Vertex3D> = Vec::new();
let mut tris: Vec<[u32; 3]> = Vec::new();
for tri in idx_vals.as_chunks::<3>().0 {
let (i0, i1, i2): (usize, usize, usize) =
(tri[0] as usize, tri[1] as usize, tri[2] as usize);
if i0 < raw_pts.len() && i1 < raw_pts.len() && i2 < raw_pts.len() {
let p0: Vec3 = raw_pts[i0];
let p1: Vec3 = raw_pts[i1];
let p2: Vec3 = raw_pts[i2];
let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
let base: u32 = verts.len() as u32;
verts.push(Vertex3D::new(p0, face_n));
verts.push(Vertex3D::new(p1, face_n));
verts.push(Vertex3D::new(p2, face_n));
tris.push([base, base + 1, base + 2]);
}
}
if !tris.is_empty() {
let mut built: Mesh3D =
Mesh3D::from_parts(prim_name, verts, tris, legacy_mat);
built.set_material_index(mat_opt);
meshes.push(built);
}
}
}
}
}
let mut skins: Vec<ImportedSkin3D> = Vec::new();
if let Some(skins_arr) = root.get(KEY_SKINS).and_then(Value::as_array) {
for (skin_idx, skin_val) in skins_arr.iter().enumerate() {
let name: String = skin_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("skin_{skin_idx}"));
let joints: Vec<u32> = skin_val
.get(KEY_JOINTS)
.and_then(Value::as_array)
.map(|arr: &Vec<Value>| {
arr.iter()
.filter_map(|item: &Value| item.as_u64().map(|id: u64| id as u32))
.collect()
})
.unwrap_or_default();
let skeleton_root: Option<u32> = skin_val
.get(KEY_SKELETON)
.and_then(Value::as_u64)
.map(|id: u64| id as u32);
let mut inverse_bind_matrices: Vec<Mat4> = Vec::with_capacity(joints.len());
if let Some(ibm_acc) = skin_val.get(KEY_INV_BIND_MATRICES).and_then(Value::as_u64) {
let (floats, count, comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, ibm_acc as usize)?;
if comps == 16 {
for idx in 0..count {
let base: usize = idx * 16;
let mut elems: [f32; 16] = [0.0; 16];
elems.copy_from_slice(&floats[base..(base + 16)]);
inverse_bind_matrices.push(Mat4::from_cols_array(elems));
}
}
}
while inverse_bind_matrices.len() < joints.len() {
inverse_bind_matrices.push(Mat4::identity());
}
skins.push(ImportedSkin3D {
name,
joints,
skeleton_root,
inverse_bind_matrices,
});
}
}
let mut animations: Vec<ImportedAnimationClip3D> = Vec::new();
if let Some(anims_arr) = root.get(KEY_ANIMATIONS).and_then(Value::as_array) {
for (anim_idx, anim_val) in anims_arr.iter().enumerate() {
let name: String = anim_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("animation_{anim_idx}"));
let mut duration_secs: f32 = 0.0;
let mut parsed_samplers: Vec<ImportedAnimationSampler3D> = Vec::new();
if let Some(samps_arr) = anim_val.get(KEY_SAMPLERS).and_then(Value::as_array) {
for samp_val in samps_arr.iter() {
let Some(in_acc) = samp_val.get(KEY_INPUT).and_then(Value::as_u64) else {
parsed_samplers.push(ImportedAnimationSampler3D::default());
continue;
};
let Some(out_acc) = samp_val.get(KEY_OUTPUT).and_then(Value::as_u64) else {
parsed_samplers.push(ImportedAnimationSampler3D::default());
continue;
};
let (timestamps, t_cnt, _): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, in_acc as usize)?;
let (values, v_cnt, v_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, out_acc as usize)?;
for &ts in timestamps.iter() {
if ts > duration_secs {
duration_secs = ts;
}
}
let interp: GltfInterpolationMode =
match samp_val.get(KEY_INTERPOLATION).and_then(Value::as_str) {
Some(INTERP_STEP) => GltfInterpolationMode::Step,
Some(INTERP_CUBICSPLINE) => GltfInterpolationMode::CubicSpline,
_ => GltfInterpolationMode::Linear,
};
let per_key_mult: usize = if interp == GltfInterpolationMode::CubicSpline {
3
} else {
1
};
let denom: usize = t_cnt.saturating_mul(per_key_mult).max(1);
let value_stride: usize = ((v_cnt * v_comps) / denom).max(1);
parsed_samplers.push(ImportedAnimationSampler3D {
timestamps,
values,
value_stride,
interpolation: interp,
});
}
}
let mut parsed_channels: Vec<ImportedAnimationChannel3D> = Vec::new();
if let Some(ch_arr) = anim_val.get(KEY_CHANNELS).and_then(Value::as_array) {
for ch_val in ch_arr.iter() {
let Some(sampler_index) = ch_val.get(KEY_SAMPLER).and_then(Value::as_u64)
else {
continue;
};
let Some(target_obj) = ch_val.get(KEY_TARGET) else {
continue;
};
let Some(target_node) = target_obj.get(KEY_NODE).and_then(Value::as_u64) else {
continue;
};
let Some(path_str) = target_obj.get(KEY_PATH).and_then(Value::as_str) else {
continue;
};
let path: GltfAnimationPath = if path_str == KEY_TRANSLATION {
GltfAnimationPath::Translation
} else if path_str == KEY_ROTATION {
GltfAnimationPath::Rotation
} else if path_str == KEY_SCALE {
GltfAnimationPath::Scale
} else if path_str == KEY_WEIGHTS {
GltfAnimationPath::MorphWeights
} else {
continue;
};
parsed_channels.push(ImportedAnimationChannel3D::new(
target_node as u32,
path,
sampler_index as usize,
));
}
}
animations.push(ImportedAnimationClip3D {
name,
duration_secs,
samplers: parsed_samplers,
channels: parsed_channels,
});
}
}
let mut cameras: Vec<ImportedCamera3D> = Vec::new();
if let Some(cams_arr) = root.get(KEY_CAMERAS).and_then(Value::as_array) {
for (cam_idx, cam_val) in cams_arr.iter().enumerate() {
let name: String = cam_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("camera_{cam_idx}"));
if let Some(persp) = cam_val.get(KEY_PERSPECTIVE) {
let yfov_rad: f32 =
persp.get(KEY_YFOV).and_then(Value::as_f64).unwrap_or(0.8) as f32;
let aspect_ratio: Option<f32> = persp
.get(KEY_ASPECT_RATIO)
.and_then(Value::as_f64)
.map(|val: f64| val as f32);
let znear: f32 = persp.get(KEY_ZNEAR).and_then(Value::as_f64).unwrap_or(0.1) as f32;
let zfar: Option<f32> = persp
.get(KEY_ZFAR)
.and_then(Value::as_f64)
.map(|val: f64| val as f32);
cameras.push(ImportedCamera3D {
name,
projection: GltfCameraProjection::Perspective {
yfov_rad,
aspect_ratio,
znear,
zfar,
},
});
} else if let Some(ortho) = cam_val.get(KEY_ORTHOGRAPHIC) {
let xmag: f32 = ortho.get(KEY_XMAG).and_then(Value::as_f64).unwrap_or(1.0) as f32;
let ymag: f32 = ortho.get(KEY_YMAG).and_then(Value::as_f64).unwrap_or(1.0) as f32;
let znear: f32 = ortho.get(KEY_ZNEAR).and_then(Value::as_f64).unwrap_or(0.1) as f32;
let zfar: f32 = ortho.get(KEY_ZFAR).and_then(Value::as_f64).unwrap_or(100.0) as f32;
cameras.push(ImportedCamera3D {
name,
projection: GltfCameraProjection::Orthographic {
xmag,
ymag,
znear,
zfar,
},
});
}
}
}
let mut lights: Vec<ImportedLight3D> = Vec::new();
if let Some(lights_arr) = root
.get(KEY_EXTENSIONS)
.and_then(|ext: &Value| ext.get(GLTF_EXT_LIGHTS_PUNCTUAL))
.and_then(|lp: &Value| lp.get(KEY_LIGHTS))
.and_then(Value::as_array)
{
for (light_idx, light_val) in lights_arr.iter().enumerate() {
let name: String = light_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("light_{light_idx}"));
let color_arr: [f32; 3] = json_f32_3(light_val.get(KEY_COLOR), [1.0, 1.0, 1.0]);
let intensity: f32 = light_val
.get(KEY_INTENSITY)
.and_then(Value::as_f64)
.unwrap_or(1.0) as f32;
let range: Option<f32> = light_val
.get(KEY_RANGE)
.and_then(Value::as_f64)
.map(|val: f64| val as f32);
let light_type: &str = light_val
.get(KEY_TYPE)
.and_then(Value::as_str)
.unwrap_or(LIGHT_TYPE_POINT);
let kind: GltfLightKind = if light_type == LIGHT_TYPE_DIRECTIONAL {
GltfLightKind::Directional
} else if light_type == LIGHT_TYPE_SPOT {
let spot_obj: Option<&Value> = light_val.get(KEY_SPOT);
let inner_cone_angle: f32 = spot_obj
.and_then(|s: &Value| s.get(KEY_INNER_CONE))
.and_then(Value::as_f64)
.unwrap_or(0.0) as f32;
let outer_cone_angle: f32 = spot_obj
.and_then(|s: &Value| s.get(KEY_OUTER_CONE))
.and_then(Value::as_f64)
.map(|val: f64| val as f32)
.unwrap_or(FRAC_PI_2 * 0.5);
GltfLightKind::Spot {
range,
inner_cone_angle,
outer_cone_angle,
}
} else if light_type == LIGHT_TYPE_AREA {
GltfLightKind::Area {
width: 1.0,
height: 1.0,
}
} else {
GltfLightKind::Point { range }
};
lights.push(ImportedLight3D {
name,
color: Vec3::from_array(color_arr),
intensity,
kind,
});
}
}
let mut scene_graph: SceneGraph3D = SceneGraph3D::default();
if let Some(nodes_arr) = root.get(KEY_NODES).and_then(Value::as_array) {
let mut parent_of: Vec<Option<u32>> = vec![None; nodes_arr.len()];
for (parent_idx, node_val) in nodes_arr.iter().enumerate() {
if let Some(children) = node_val.get(KEY_CHILDREN).and_then(Value::as_array) {
for child_val in children.iter() {
if let Some(child_idx) = child_val.as_u64() {
let c_usize: usize = child_idx as usize;
if c_usize < parent_of.len() {
parent_of[c_usize] = Some(parent_idx as u32);
}
}
}
}
}
for (node_idx, node_val) in nodes_arr.iter().enumerate() {
let name: String = node_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("node_{node_idx}"));
let mut node: SceneNode3D = SceneNode3D::from_name(&name, parent_of[node_idx]);
if let Some(mat_arr) = node_val.get(KEY_MATRIX).and_then(Value::as_array)
&& mat_arr.len() == 16
{
let mut elems: [f32; 16] = [0.0; 16];
for i in 0..16usize {
elems[i] = mat_arr[i].as_f64().unwrap_or(0.0) as f32;
}
let (tr, rot, sc): (Vec3, Quat, Vec3) =
Mat4::from_cols_array(elems).decompose_trs();
node.set_local_translation(tr);
node.set_local_rotation(rot);
node.set_local_scale(sc);
} else {
let tr: [f32; 3] = json_f32_3(node_val.get(KEY_TRANSLATION), [0.0, 0.0, 0.0]);
let rot: [f32; 4] = json_f32_4(node_val.get(KEY_ROTATION), [0.0, 0.0, 0.0, 1.0]);
let sc: [f32; 3] = json_f32_3(node_val.get(KEY_SCALE), [1.0, 1.0, 1.0]);
node.set_local_translation(Vec3::from_array(tr));
node.set_local_rotation(Quat::from_array(rot).normalize());
node.set_local_scale(Vec3::from_array(sc));
}
if let Some(mesh_idx) = node_val.get(KEY_MESH).and_then(Value::as_u64)
&& let Some(&first_prim) = gltf_mesh_to_first_prim.get(mesh_idx as usize)
&& first_prim < meshes.len()
{
node.set_mesh_id(Some(first_prim as u32));
}
if let Some(skin_idx) = node_val.get(KEY_SKIN).and_then(Value::as_u64) {
node.set_skin_id(Some(skin_idx as u32));
}
if let Some(cam_idx) = node_val.get(KEY_CAMERA).and_then(Value::as_u64) {
node.set_camera_id(Some(cam_idx as u32));
}
if let Some(light_idx) = node_val
.get(KEY_EXTENSIONS)
.and_then(|ext: &Value| ext.get(GLTF_EXT_LIGHTS_PUNCTUAL))
.and_then(|lp: &Value| lp.get(KEY_LIGHT))
.and_then(Value::as_u64)
{
node.set_light_id(Some(light_idx as u32));
}
if let Some(extras_obj) = node_val.get(KEY_EXTRAS) {
let euv_obj: &Value = extras_obj.get("euv").unwrap_or(extras_obj);
if let Some(colls) = euv_obj
.get(KEY_EUV_COLLECTIONS)
.or_else(|| extras_obj.get(KEY_EUV_COLLECTIONS))
.and_then(Value::as_array)
{
let mut mask: u64 = 0;
for coll_val in colls.iter() {
if let Some(coll_name) = coll_val.as_str() {
mask |= scene_graph
.get_mut_collections()
.register_collection(coll_name);
}
}
if mask != 0 {
node.set_collection_mask(mask);
}
}
let mut tags: BlenderExtrasTags3D = BlenderExtrasTags3D::default();
if let Some(col_str) = euv_obj.get(KEY_EUV_COLLIDER).and_then(Value::as_str) {
let shape: SceneColliderShape3D = if col_str == COLLIDER_SPHERE {
SceneColliderShape3D::Sphere
} else if col_str == COLLIDER_CONVEX || col_str == COLLIDER_CONVEX_HULL {
SceneColliderShape3D::ConvexHull
} else if col_str == COLLIDER_MESH {
SceneColliderShape3D::Mesh
} else if col_str == "box" {
SceneColliderShape3D::Box
} else {
SceneColliderShape3D::None
};
tags.set_collider(shape);
}
if let Some(buoy) = euv_obj.get(KEY_EUV_BUOYANCY).and_then(Value::as_f64) {
tags.set_buoyancy_density(buoy as f32);
}
if let Some(trig) = euv_obj.get(KEY_EUV_TRIGGER).and_then(Value::as_bool) {
tags.set_is_trigger(trig);
}
if let Some(cast) = euv_obj.get(KEY_EUV_CAST_SHADOWS).and_then(Value::as_bool) {
tags.set_cast_shadows(cast);
}
if let Ok(raw_json) = to_string(extras_obj) {
tags.set_custom_json(Some(raw_json));
}
node.set_extras(tags);
}
let added_id: u32 = scene_graph.add_node(node);
if let Some(weights_arr) = node_val.get(KEY_WEIGHTS).and_then(Value::as_array) {
let w_vec: Vec<f32> = weights_arr
.iter()
.filter_map(|item: &Value| item.as_f64().map(|val: f64| val as f32))
.collect();
scene_graph.attach_morph_weights(added_id, &w_vec);
}
}
let _: usize = scene_graph.propagate_world_matrices();
}
Ok(ImportedScene3D {
name: scene_name,
generator,
scene_graph,
meshes,
materials,
textures,
skins,
animations,
cameras,
lights,
})
}
pub fn parse_glb_bytes(bytes: &[u8]) -> Result<ImportedScene3D, String> {
if bytes.len() < 20 {
return Err(ERR_GLB_INVALID.to_string());
}
let magic: u32 = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
let version: u32 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
let total_len: usize = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
if magic != GLB_MAGIC || version != GLB_VERSION_2 || total_len > bytes.len() || total_len < 20 {
return Err(ERR_GLB_INVALID.to_string());
}
let mut cursor: usize = 12;
let mut json_slice: Option<&[u8]> = None;
let mut bin_slice: Option<&[u8]> = None;
while cursor + 8 <= total_len {
let chunk_len: usize = u32::from_le_bytes([
bytes[cursor],
bytes[cursor + 1],
bytes[cursor + 2],
bytes[cursor + 3],
]) as usize;
let chunk_type: u32 = u32::from_le_bytes([
bytes[cursor + 4],
bytes[cursor + 5],
bytes[cursor + 6],
bytes[cursor + 7],
]);
let payload_start: usize = cursor + 8;
let payload_end: usize = payload_start.saturating_add(chunk_len);
if payload_end > total_len {
return Err(ERR_GLB_INVALID.to_string());
}
if chunk_type == GLB_CHUNK_JSON && json_slice.is_none() {
json_slice = Some(&bytes[payload_start..payload_end]);
} else if chunk_type == GLB_CHUNK_BIN && bin_slice.is_none() {
bin_slice = Some(&bytes[payload_start..payload_end]);
}
cursor = payload_end;
}
let raw_json: &[u8] = json_slice.ok_or_else(|| ERR_GLB_INVALID.to_string())?;
let json_text: &str = from_utf8(raw_json)
.ok()
.ok_or_else(|| ERR_GLB_INVALID.to_string())?;
parse_gltf_document(json_text, bin_slice, None)
}
pub fn parse_gltf_or_glb_bytes(
bytes: &[u8],
resolver: Option<&dyn GltfBufferResolver>,
) -> Result<ImportedScene3D, String> {
if bytes.len() >= 4 && u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) == GLB_MAGIC
{
return parse_glb_bytes(bytes);
}
let json_text: &str = from_utf8(bytes)
.ok()
.ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
parse_gltf_document(json_text, None, resolver)
}