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()),
}
}
#[must_use]
fn meshopt_unzigzag8(val: u8) -> u8 {
((val & 1).wrapping_neg()) ^ (val >> 1)
}
#[must_use]
fn meshopt_unzigzag32(val: u32) -> u32 {
((val & 1).wrapping_neg()) ^ (val >> 1)
}
fn meshopt_read_varint(data: &[u8], cursor: &mut usize) -> Result<u32, String> {
let mut acc: u32 = 0;
let mut shift: u32 = 0;
for _ in 0..5 {
if *cursor >= data.len() {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let byte_val: u8 = data[*cursor];
*cursor += 1;
acc |= u32::from(byte_val & 0x7f) << shift;
if (byte_val & 0x80) == 0 {
return Ok(acc);
}
shift += 7;
}
Err(ERR_GLTF_MESHOPT.to_string())
}
pub fn decode_meshopt_vertex_buffer(
data: &[u8],
count: usize,
stride: usize,
) -> Result<Vec<u8>, String> {
let bad_stride: bool = stride == 0 || stride > 256;
if bad_stride || !stride.is_multiple_of(4) {
return Err(ERR_GLTF_MESHOPT.to_string());
}
if count == 0 {
return Ok(Vec::new());
}
if data.len() < 1 + stride {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let header: u8 = data[0];
if (header & 0xf0) != 0xa0 || (header & 0x0f) > 1 {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let payload_end: usize = data.len() - stride;
let mut last_vertex: Vec<u8> = data[payload_end..].to_vec();
let mut cursor: usize = 1;
let raw_block: usize = (8192 / stride) & !15usize;
let block_size: usize = raw_block.clamp(16, 256);
let mut out: Vec<u8> = vec![0u8; count.saturating_mul(stride)];
let mut vertex_offset: usize = 0;
while vertex_offset < count {
let block_count: usize = (count - vertex_offset).min(block_size);
let group_count: usize = block_count.div_ceil(16);
let ctrl_bytes: usize = group_count.div_ceil(4);
for k in 0..stride {
if cursor + ctrl_bytes > payload_end {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let ctrl: &[u8] = &data[cursor..(cursor + ctrl_bytes)];
cursor += ctrl_bytes;
let mut last_byte: u8 = last_vertex[k];
let mut decoded_in_block: usize = 0;
for g in 0..group_count {
let bits: u8 = (ctrl[g >> 2] >> ((g & 3) * 2)) & 0x03;
let mut deltas: [u8; 16] = [0u8; 16];
match bits {
0 => {}
1 => {
if cursor + 4 > payload_end {
return Err(ERR_GLTF_MESHOPT.to_string());
}
for b_idx in 0..4 {
let packed: u8 = data[cursor + b_idx];
deltas[b_idx * 4] = (packed >> 6) & 0x03;
deltas[b_idx * 4 + 1] = (packed >> 4) & 0x03;
deltas[b_idx * 4 + 2] = (packed >> 2) & 0x03;
deltas[b_idx * 4 + 3] = packed & 0x03;
}
cursor += 4;
}
2 => {
if cursor + 8 > payload_end {
return Err(ERR_GLTF_MESHOPT.to_string());
}
for b_idx in 0..8 {
let packed: u8 = data[cursor + b_idx];
deltas[b_idx * 2] = packed >> 4;
deltas[b_idx * 2 + 1] = packed & 0x0f;
}
cursor += 8;
}
_ => {
if cursor + 16 > payload_end {
return Err(ERR_GLTF_MESHOPT.to_string());
}
deltas.copy_from_slice(&data[cursor..(cursor + 16)]);
cursor += 16;
}
}
let take_n: usize = (block_count - decoded_in_block).min(16);
for delta_val in deltas.iter().take(take_n) {
let next_byte: u8 = last_byte.wrapping_add(meshopt_unzigzag8(*delta_val));
out[(vertex_offset + decoded_in_block) * stride + k] = next_byte;
last_byte = next_byte;
decoded_in_block += 1;
}
}
last_vertex[k] = last_byte;
}
vertex_offset += block_count;
}
Ok(out)
}
pub fn decode_meshopt_index_buffer(
data: &[u8],
index_count: usize,
index_size: usize,
) -> Result<Vec<u8>, String> {
if !index_count.is_multiple_of(3) || (index_size != 2 && index_size != 4) {
return Err(ERR_GLTF_MESHOPT.to_string());
}
if index_count == 0 {
return Ok(Vec::new());
}
let tri_count: usize = index_count / 3;
if data.len() < 1 + tri_count + 16 {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let header: u8 = data[0];
if (header & 0xf0) != 0xe0 || (header & 0x0f) > 1 {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let code_stream: &[u8] = &data[1..(1 + tri_count)];
let data_end: usize = data.len() - 16;
let codeaux_table: &[u8] = &data[data_end..];
let mut cursor: usize = 1 + tri_count;
let mut edge_fifo: [(u32, u32); 16] = [(0, 0); 16];
let mut edge_off: usize = 0;
let mut vert_fifo: [u32; 16] = [0; 16];
let mut vert_off: usize = 0;
let mut next_vert: u32 = 0;
let mut last_vert: u32 = 0;
let mut out: Vec<u8> = Vec::with_capacity(index_count.saturating_mul(index_size));
let decode_idx: fn(&[u8], &mut usize, &mut u32, &mut u32) -> Result<u32, String> =
|buf: &[u8], pos: &mut usize, next: &mut u32, last: &mut u32| -> Result<u32, String> {
let v: u32 = meshopt_read_varint(buf, pos)?;
if v == 0 {
let res: u32 = *next;
*next = next.wrapping_add(1);
Ok(res)
} else {
let d: u32 = meshopt_unzigzag32(v - 1);
*last = last.wrapping_add(d);
Ok(*last)
}
};
for &code in code_stream.iter() {
let fea: usize = usize::from(code >> 4);
let fec: usize = usize::from(code & 0x0f);
let (a, b, c): (u32, u32, u32) = if fea < 15 {
let (ea, eb): (u32, u32) = edge_fifo[(edge_off.wrapping_sub(1 + fea)) & 15];
let cv: u32 = if fec == 0 {
let res: u32 = next_vert;
next_vert = next_vert.wrapping_add(1);
vert_fifo[vert_off] = res;
vert_off = (vert_off + 1) & 15;
res
} else if fec < 15 {
vert_fifo[(vert_off.wrapping_sub(fec)) & 15]
} else {
let res: u32 = decode_idx(
&data[..data_end],
&mut cursor,
&mut next_vert,
&mut last_vert,
)?;
vert_fifo[vert_off] = res;
vert_off = (vert_off + 1) & 15;
res
};
edge_fifo[edge_off] = (cv, eb);
edge_off = (edge_off + 1) & 15;
edge_fifo[edge_off] = (ea, cv);
edge_off = (edge_off + 1) & 15;
(ea, eb, cv)
} else {
let codeaux: u8 = if fec < 15 {
codeaux_table[fec]
} else {
if cursor >= data_end {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let raw: u8 = data[cursor];
cursor += 1;
raw
};
let (av, bv, cv): (u32, u32, u32) = if fec == 15 && codeaux == 0 {
let a0: u32 = decode_idx(
&data[..data_end],
&mut cursor,
&mut next_vert,
&mut last_vert,
)?;
let b0: u32 = decode_idx(
&data[..data_end],
&mut cursor,
&mut next_vert,
&mut last_vert,
)?;
let c0: u32 = decode_idx(
&data[..data_end],
&mut cursor,
&mut next_vert,
&mut last_vert,
)?;
(a0, b0, c0)
} else {
let feb: u32 = u32::from(codeaux >> 4);
let fec_lo: u32 = u32::from(codeaux & 0x0f);
let a0: u32 = next_vert;
next_vert = next_vert.wrapping_add(1);
let b0: u32 = if feb == 0 {
let res: u32 = next_vert;
next_vert = next_vert.wrapping_add(1);
res
} else if feb < 15 {
a0.wrapping_sub(feb)
} else {
decode_idx(
&data[..data_end],
&mut cursor,
&mut next_vert,
&mut last_vert,
)?
};
let c0: u32 = if fec_lo == 0 {
let res: u32 = next_vert;
next_vert = next_vert.wrapping_add(1);
res
} else if fec_lo < 15 {
a0.wrapping_sub(fec_lo)
} else {
decode_idx(
&data[..data_end],
&mut cursor,
&mut next_vert,
&mut last_vert,
)?
};
(a0, b0, c0)
};
vert_fifo[vert_off] = av;
vert_off = (vert_off + 1) & 15;
vert_fifo[vert_off] = bv;
vert_off = (vert_off + 1) & 15;
vert_fifo[vert_off] = cv;
vert_off = (vert_off + 1) & 15;
edge_fifo[edge_off] = (bv, av);
edge_off = (edge_off + 1) & 15;
edge_fifo[edge_off] = (cv, bv);
edge_off = (edge_off + 1) & 15;
edge_fifo[edge_off] = (av, cv);
edge_off = (edge_off + 1) & 15;
(av, bv, cv)
};
for idx_val in [a, b, c] {
if index_size == 2 {
out.extend_from_slice(&(idx_val as u16).to_le_bytes());
} else {
out.extend_from_slice(&idx_val.to_le_bytes());
}
}
}
Ok(out)
}
pub fn decode_meshopt_index_sequence(
data: &[u8],
index_count: usize,
index_size: usize,
) -> Result<Vec<u8>, String> {
if index_size != 2 && index_size != 4 {
return Err(ERR_GLTF_MESHOPT.to_string());
}
if index_count == 0 {
return Ok(Vec::new());
}
if data.len() < 5 {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let header: u8 = data[0];
if (header & 0xf0) != 0xd0 || (header & 0x0f) > 1 {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let payload_end: usize = data.len() - 4;
let baseline: u32 = u32::from_le_bytes([
data[payload_end],
data[payload_end + 1],
data[payload_end + 2],
data[payload_end + 3],
]);
let mut cursor: usize = 1;
let mut last: [u32; 2] = [baseline, baseline];
let mut out: Vec<u8> = Vec::with_capacity(index_count.saturating_mul(index_size));
for _ in 0..index_count {
let v: u32 = meshopt_read_varint(&data[..payload_end], &mut cursor)?;
let lane: usize = (v & 1) as usize;
let delta: u32 = meshopt_unzigzag32(v >> 1);
last[lane] = last[lane].wrapping_add(delta);
if index_size == 2 {
out.extend_from_slice(&(last[lane] as u16).to_le_bytes());
} else {
out.extend_from_slice(&last[lane].to_le_bytes());
}
}
Ok(out)
}
fn apply_meshopt_filter_octahedral(buf: &mut [u8], count: usize, stride: usize) {
if stride == 4 {
for idx in 0..count {
let base: usize = idx * 4;
if base + 4 > buf.len() {
break;
}
let x: f32 = f32::from(buf[base] as i8);
let y: f32 = f32::from(buf[base + 1] as i8);
let one: f32 = f32::from(buf[base + 2] as i8);
let z: f32 = one - x.abs() - y.abs();
let t: f32 = (-z).max(0.0);
let nx: f32 = x + if x >= 0.0 { -t } else { t };
let ny: f32 = y + if y >= 0.0 { -t } else { t };
let len: f32 = (nx * nx + ny * ny + z * z).sqrt().max(1e-6);
let scale: f32 = 127.0 / len;
buf[base] = (nx * scale).round().clamp(-127.0, 127.0) as i8 as u8;
buf[base + 1] = (ny * scale).round().clamp(-127.0, 127.0) as i8 as u8;
buf[base + 2] = (z * scale).round().clamp(-127.0, 127.0) as i8 as u8;
}
} else if stride == 8 {
for idx in 0..count {
let base: usize = idx * 8;
if base + 8 > buf.len() {
break;
}
let x: f32 = f32::from(i16::from_le_bytes([buf[base], buf[base + 1]]));
let y: f32 = f32::from(i16::from_le_bytes([buf[base + 2], buf[base + 3]]));
let one: f32 = f32::from(i16::from_le_bytes([buf[base + 4], buf[base + 5]]));
let z: f32 = one - x.abs() - y.abs();
let t: f32 = (-z).max(0.0);
let nx: f32 = x + if x >= 0.0 { -t } else { t };
let ny: f32 = y + if y >= 0.0 { -t } else { t };
let len: f32 = (nx * nx + ny * ny + z * z).sqrt().max(1e-6);
let scale: f32 = 32_767.0 / len;
let qx: i16 = (nx * scale).round().clamp(-32_767.0, 32_767.0) as i16;
let qy: i16 = (ny * scale).round().clamp(-32_767.0, 32_767.0) as i16;
let qz: i16 = (z * scale).round().clamp(-32_767.0, 32_767.0) as i16;
buf[base..(base + 2)].copy_from_slice(&qx.to_le_bytes());
buf[(base + 2)..(base + 4)].copy_from_slice(&qy.to_le_bytes());
buf[(base + 4)..(base + 6)].copy_from_slice(&qz.to_le_bytes());
}
}
}
fn apply_meshopt_filter_quaternion(buf: &mut [u8], count: usize) {
let inv_sqrt2: f32 = 1.0 / SQRT_2;
for idx in 0..count {
let base: usize = idx * 8;
if base + 8 > buf.len() {
break;
}
let i0: i16 = i16::from_le_bytes([buf[base], buf[base + 1]]);
let i1: i16 = i16::from_le_bytes([buf[base + 2], buf[base + 3]]);
let i2: i16 = i16::from_le_bytes([buf[base + 4], buf[base + 5]]);
let i3: i16 = i16::from_le_bytes([buf[base + 6], buf[base + 7]]);
let max_comp: usize = (i3 & 3) as usize;
let denom: f32 = f32::from((i3 >> 2).max(1));
let scale: f32 = inv_sqrt2 / denom;
let x: f32 = f32::from(i0) * scale;
let y: f32 = f32::from(i1) * scale;
let z: f32 = f32::from(i2) * scale;
let w: f32 = (1.0 - x * x - y * y - z * z).max(0.0).sqrt();
let vals: [f32; 4] = [x, y, z, w];
let mut out_q: [i16; 4] = [0; 4];
for (lane, slot) in out_q.iter_mut().enumerate() {
let src_idx: usize = (lane + 3 - max_comp) & 3;
*slot = (vals[src_idx] * 32_767.0)
.round()
.clamp(-32_767.0, 32_767.0) as i16;
}
for (lane, qv) in out_q.iter().enumerate() {
buf[(base + lane * 2)..(base + lane * 2 + 2)].copy_from_slice(&qv.to_le_bytes());
}
}
}
fn apply_meshopt_filter_exponential(buf: &mut [u8], count: usize, stride: usize) {
let lanes: usize = count.saturating_mul(stride / 4);
for idx in 0..lanes {
let base: usize = idx * 4;
if base + 4 > buf.len() {
break;
}
let packed: u32 =
u32::from_le_bytes([buf[base], buf[base + 1], buf[base + 2], buf[base + 3]]);
let exp: i32 = (packed as i32) >> 24;
let mantissa: i32 = ((packed << 8) as i32) >> 8;
let val: f32 = (mantissa as f32) * 2.0f32.powi(exp);
buf[base..(base + 4)].copy_from_slice(&val.to_le_bytes());
}
}
fn decode_meshopt_buffer_views(
root: &Value,
buffers: &[Cow<'_, [u8]>],
) -> Result<HashMap<usize, Vec<u8>>, String> {
let mut decoded: HashMap<usize, Vec<u8>> = HashMap::new();
let Some(views) = root.get(KEY_BUFFER_VIEWS).and_then(Value::as_array) else {
return Ok(decoded);
};
for (view_idx, view) in views.iter().enumerate() {
let Some(ext) = view
.get(KEY_EXTENSIONS)
.and_then(|e: &Value| e.get(GLTF_EXT_MESHOPT))
else {
continue;
};
let buf_idx: usize = ext
.get(KEY_BUFFER)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
let byte_offset: usize = ext
.get(KEY_BYTE_OFFSET)
.and_then(Value::as_u64)
.unwrap_or(0) as usize;
let byte_length: usize = ext
.get(KEY_BYTE_LENGTH)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
let byte_stride: usize = ext
.get(KEY_BYTE_STRIDE)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
let count: usize = ext
.get(KEY_COUNT)
.and_then(Value::as_u64)
.ok_or_else(|| ERR_GLTF_MESHOPT.to_string())? as usize;
let mode: &str = ext
.get(KEY_MODE)
.and_then(Value::as_str)
.ok_or_else(|| ERR_GLTF_MESHOPT.to_string())?;
let raw_buf: &[u8] = buffers
.get(buf_idx)
.map(Cow::as_ref)
.ok_or_else(|| ERR_GLTF_MESHOPT.to_string())?;
let end: usize = byte_offset.saturating_add(byte_length);
if end > raw_buf.len() {
return Err(ERR_GLTF_MESHOPT.to_string());
}
let compressed: &[u8] = &raw_buf[byte_offset..end];
let mut raw_out: Vec<u8> = match mode {
MESHOPT_MODE_ATTRIBUTES => {
decode_meshopt_vertex_buffer(compressed, count, byte_stride)?
}
MESHOPT_MODE_TRIANGLES => decode_meshopt_index_buffer(compressed, count, byte_stride)?,
MESHOPT_MODE_INDICES => decode_meshopt_index_sequence(compressed, count, byte_stride)?,
_ => return Err(ERR_GLTF_MESHOPT.to_string()),
};
if let Some(filter) = ext.get(KEY_FILTER).and_then(Value::as_str) {
match filter {
MESHOPT_FILTER_OCTAHEDRAL => {
apply_meshopt_filter_octahedral(&mut raw_out, count, byte_stride);
}
MESHOPT_FILTER_QUATERNION if byte_stride == 8 => {
apply_meshopt_filter_quaternion(&mut raw_out, count);
}
MESHOPT_FILTER_EXPONENTIAL if byte_stride.is_multiple_of(4) => {
apply_meshopt_filter_exponential(&mut raw_out, count, byte_stride);
}
_ => {}
}
}
let _: Option<Vec<u8>> = decoded.insert(view_idx, raw_out);
}
Ok(decoded)
}
fn resolve_buffer_view<'a>(
root: &Value,
buffers: &'a [Cow<'a, [u8]>],
meshopt_views: &'a HashMap<usize, 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 byte_stride: Option<usize> = view
.get(KEY_BYTE_STRIDE)
.and_then(Value::as_u64)
.map(|val: u64| val as usize);
if let Some(decoded_buf) = meshopt_views.get(&view_idx) {
return Ok((decoded_buf.as_slice(), byte_stride));
}
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 buf: &[u8] = buffers
.get(buf_idx)
.map(Cow::as_ref)
.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: &[Cow<'_, [u8]>],
meshopt_views: &HashMap<usize, 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, meshopt_views, 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, meshopt_views, idx_view_id)?;
let (val_slice, _): (&[u8], Option<usize>) =
resolve_buffer_view(root, buffers, meshopt_views, 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: &[Cow<'_, [u8]>],
meshopt_views: &HashMap<usize, 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, meshopt_views, 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);
}
if let Some(aniso_ext) = ext.get(GLTF_EXT_ANISOTROPY)
&& let Some(strength) = aniso_ext
.get(KEY_ANISOTROPY_STRENGTH)
.and_then(Value::as_f64)
{
let clamped: f32 = (strength as f32).clamp(0.0, 1.0);
if clamped > 0.0 && ext.get(GLTF_EXT_SPECULAR).is_none() {
mat.set_specular_factor(
(mat.get_specular_factor() + clamped * 0.25).clamp(0.0, 1.5),
);
}
}
if let Some(iri_ext) = ext.get(GLTF_EXT_IRIDESCENCE) {
let factor: f32 = iri_ext
.get(KEY_IRIDESCENCE_FACTOR)
.and_then(Value::as_f64)
.unwrap_or(0.0) as f32;
let iri_ior: f32 = iri_ext
.get(KEY_IRIDESCENCE_IOR)
.and_then(Value::as_f64)
.unwrap_or(1.3) as f32;
if factor > 0.0 {
if ext.get(GLTF_EXT_IOR).is_none() {
mat.set_ior(iri_ior.max(1.0));
}
if ext.get(GLTF_EXT_SHEEN).is_none() {
let clamped: f32 = factor.clamp(0.0, 1.0);
mat.set_sheen_color_factor([clamped * 0.65, clamped * 0.85, clamped]);
mat.set_sheen_roughness_factor(0.25);
}
}
}
}
mat
}
#[must_use]
fn parse_material_extension_record(mat_val: &Value, mat_idx: usize) -> GltfMaterialExtensionData {
let name: String = mat_val
.get(KEY_NAME)
.and_then(Value::as_str)
.map(str::to_string)
.unwrap_or_else(|| format!("material_{mat_idx}"));
let mut data: GltfMaterialExtensionData = GltfMaterialExtensionData {
name,
anisotropy_strength: 0.0,
anisotropy_rotation: 0.0,
anisotropy_texture: None,
iridescence_factor: 0.0,
iridescence_ior: 1.3,
iridescence_thickness_min: 100.0,
iridescence_thickness_max: 400.0,
iridescence_texture: None,
iridescence_thickness_texture: None,
};
if let Some(ext) = mat_val.get(KEY_EXTENSIONS) {
if let Some(aniso_ext) = ext.get(GLTF_EXT_ANISOTROPY) {
if let Some(s) = aniso_ext
.get(KEY_ANISOTROPY_STRENGTH)
.and_then(Value::as_f64)
{
data.set_anisotropy_strength((s as f32).clamp(0.0, 1.0));
}
if let Some(r) = aniso_ext
.get(KEY_ANISOTROPY_ROTATION)
.and_then(Value::as_f64)
{
data.set_anisotropy_rotation(r as f32);
}
data.set_anisotropy_texture(parse_texture_slot(aniso_ext.get(KEY_ANISOTROPY_TEX)));
}
if let Some(iri_ext) = ext.get(GLTF_EXT_IRIDESCENCE) {
if let Some(f) = iri_ext.get(KEY_IRIDESCENCE_FACTOR).and_then(Value::as_f64) {
data.set_iridescence_factor((f as f32).clamp(0.0, 1.0));
}
if let Some(ior) = iri_ext.get(KEY_IRIDESCENCE_IOR).and_then(Value::as_f64) {
data.set_iridescence_ior((ior as f32).max(1.0));
}
if let Some(tmin) = iri_ext
.get(KEY_IRIDESCENCE_THICK_MIN)
.and_then(Value::as_f64)
{
data.set_iridescence_thickness_min((tmin as f32).max(0.0));
}
if let Some(tmax) = iri_ext
.get(KEY_IRIDESCENCE_THICK_MAX)
.and_then(Value::as_f64)
{
data.set_iridescence_thickness_max((tmax as f32).max(0.0));
}
data.set_iridescence_texture(parse_texture_slot(iri_ext.get(KEY_IRIDESCENCE_TEX)));
data.set_iridescence_thickness_texture(parse_texture_slot(
iri_ext.get(KEY_IRIDESCENCE_THICK_TEX),
));
}
}
data
}
pub fn parse_gltf_material_extensions(
json_source: &str,
) -> Result<Vec<GltfMaterialExtensionData>, String> {
let root: Value = from_str::<Value>(json_source)
.ok()
.ok_or_else(|| ERR_GLTF_PARSE.to_string())?;
let mut out: Vec<GltfMaterialExtensionData> = Vec::new();
if let Some(mats_arr) = root.get(KEY_MATERIALS).and_then(Value::as_array) {
out.reserve(mats_arr.len());
for (mat_idx, mat_val) in mats_arr.iter().enumerate() {
out.push(parse_material_extension_record(mat_val, mat_idx));
}
}
Ok(out)
}
#[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<Cow<'_, [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(Cow::Owned(decode_data_uri(uri)?));
} else if let Some(res) = resolver {
buffers.push(Cow::Owned(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(Cow::Borrowed(bin));
} else {
buffers.push(Cow::Borrowed(&[]));
}
}
} else if let Some(bin) = glb_bin_chunk {
buffers.push(Cow::Borrowed(bin));
}
let meshopt_views: HashMap<usize, Vec<u8>> = decode_meshopt_buffer_views(&root, &buffers)?;
let mut materials: Vec<PrincipledMaterial3D> = Vec::new();
let mut mat_ext_records: Vec<GltfMaterialExtensionData> = 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));
mat_ext_records.push(parse_material_extension_record(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);
}
}
for ext_rec in mat_ext_records.iter() {
for slot in [
ext_rec.try_get_anisotropy_texture(),
ext_rec.try_get_iridescence_texture(),
ext_rec.try_get_iridescence_thickness_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, &meshopt_views, 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_prim_ranges: Vec<(usize, 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() {
let first_prim_idx: usize = 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 {
gltf_mesh_prim_ranges.push((first_prim_idx, 0));
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, &meshopt_views, 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, &meshopt_views, 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, &meshopt_views, 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, &meshopt_views, 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, &meshopt_views, 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, &meshopt_views, 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, &meshopt_views, j0_acc as usize)?;
let (w0_vals, w0_cnt, w0_c): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, &meshopt_views, 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, &meshopt_views, 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, &meshopt_views, 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,
&meshopt_views,
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,
&meshopt_views,
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,
&meshopt_views,
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, &meshopt_views, 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);
}
}
}
gltf_mesh_prim_ranges
.push((first_prim_idx, meshes.len().saturating_sub(first_prim_idx)));
}
}
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, &meshopt_views, 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, &meshopt_views, in_acc as usize)?;
let (values, v_cnt, v_comps): (Vec<f32>, usize, usize) =
decode_accessor_f32(&root, &buffers, &meshopt_views, 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);
}
}
}
}
}
let mut extra_prim_children: Vec<GltfExtraPrimChild> = Vec::new();
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));
}
let mut extra_prims: Option<(usize, usize)> = None;
if let Some(mesh_idx) = node_val.get(KEY_MESH).and_then(Value::as_u64)
&& let Some(&(first_prim, prim_count)) =
gltf_mesh_prim_ranges.get(mesh_idx as usize)
&& prim_count > 0
&& first_prim < meshes.len()
{
node.set_mesh_id(Some(first_prim as u32));
if prim_count > 1 {
extra_prims = Some((first_prim + 1, prim_count - 1));
}
}
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 node_skin: Option<u32> = node.try_get_skin_id();
let node_col_mask: u64 = node.get_collection_mask();
let node_extras: BlenderExtrasTags3D = node.get_extras().clone();
let added_id: u32 = scene_graph.add_node(node);
let mut node_weights: Vec<f32> = Vec::new();
if let Some(weights_arr) = node_val.get(KEY_WEIGHTS).and_then(Value::as_array) {
node_weights = weights_arr
.iter()
.filter_map(|item: &Value| item.as_f64().map(|val: f64| val as f32))
.collect();
scene_graph.attach_morph_weights(added_id, &node_weights);
}
if let Some((start_p, extra_cnt)) = extra_prims {
for offset in 0..extra_cnt {
let prim_mesh_id: u32 = (start_p + offset) as u32;
let child_name: String = format!("{name}_prim_{}", offset + 1);
extra_prim_children.push(GltfExtraPrimChild {
parent_id: added_id,
child_name,
prim_mesh_id,
skin_id: node_skin,
collection_mask: node_col_mask,
extras: node_extras.clone(),
morph_weights: node_weights.clone(),
});
}
}
}
for extra_child in extra_prim_children {
let mut child: SceneNode3D =
SceneNode3D::from_name(&extra_child.child_name, Some(extra_child.parent_id));
child.set_mesh_id(Some(extra_child.prim_mesh_id));
child.set_skin_id(extra_child.skin_id);
child.set_collection_mask(extra_child.collection_mask);
child.set_extras(extra_child.extras);
let child_id: u32 = scene_graph.add_node(child);
if !extra_child.morph_weights.is_empty() {
scene_graph.attach_morph_weights(child_id, &extra_child.morph_weights);
}
}
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)
}