use std::sync::Arc;
use unityrs_core::limits::{Charge, Meter, MeteredVec};
use crate::Version;
use crate::error::{IndexKind, MeshError};
use crate::format::{FormatTable, get_channel_dtype};
use crate::unpack::{Gather, VertexArray, unpack_channel};
use unityrs_core::objmode::{List, Obj};
const MAX_STREAMS: usize = 256;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct DerivedStream {
pub(crate) offset: u128,
pub(crate) stride: u64,
}
#[derive(Debug)]
pub(crate) enum Streams<'a> {
Derived {
streams: Vec<DerivedStream>,
_charge: Charge,
},
File(List<'a>),
}
#[derive(Debug, Default)]
pub(crate) struct Attributes {
pub(crate) vertices: Option<VertexArray>,
pub(crate) normals: Option<VertexArray>,
pub(crate) tangents: Option<VertexArray>,
pub(crate) colors: Option<VertexArray>,
pub(crate) uv: [Option<VertexArray>; 8],
pub(crate) bone_weights: Option<VertexArray>,
pub(crate) bone_indices: Option<VertexArray>,
pub(crate) bind_pose: Option<VertexArray>,
}
pub(crate) fn field(obj: &Obj<'_>, name: &'static str, max: u64) -> Result<u64, MeshError> {
obj.uint(name, max)?.ok_or(MeshError::NoAttribute(name))
}
pub(crate) fn get_streams(
version: Version,
channels: &List<'_>,
vertex_count: u64,
meter: &Arc<Meter>,
) -> Result<Streams<'static>, MeshError> {
meter.count_decode(u64::try_from(channels.len()).unwrap_or(u64::MAX))?;
let mut highest: Option<u64> = None;
for ch in channels.iter() {
let s = field(&ch?, "stream", 255)?;
highest = Some(highest.map_or(s, |h| h.max(s)));
}
let count = usize::try_from(highest.ok_or(MeshError::NoChannels)?).unwrap_or(0) + 1;
let mut strides = [0u64; MAX_STREAMS];
let mut first: Option<(u64, MeshError)> = None;
for ch in channels.iter() {
let ch = ch?;
let s = field(&ch, "stream", 255)?;
let stride = (|| {
let dim = field(&ch, "dimension", 255)?;
if dim == 0 {
return Ok(0);
}
let format = u8::try_from(field(&ch, "format", 255)?).unwrap_or(u8::MAX);
let size = get_channel_dtype(version, format)?.size();
Ok((dim & 0xF) * u64::from(size))
})();
match stride {
Ok(add) => {
if let Some(slot) = usize::try_from(s).ok().and_then(|i| strides.get_mut(i)) {
*slot = slot.saturating_add(add);
}
}
Err(e) => {
if first.as_ref().is_none_or(|(at, _)| s < *at) {
first = Some((s, e));
}
}
}
}
if let Some((_, e)) = first {
return Err(e);
}
let mut streams = MeteredVec::<DerivedStream>::with_capacity(meter, count)?;
let mut offset: u128 = 0;
for &stride in strides.get(..count).unwrap_or(&[]) {
streams.push(DerivedStream { offset, stride })?;
offset = offset.saturating_add(u128::from(vertex_count) * u128::from(stride));
offset = offset.saturating_add(15) & !15;
}
let (streams, charge) = streams.into_parts();
Ok(Streams::Derived {
streams,
_charge: charge,
})
}
pub(crate) fn mask_bit(mask: u64, chn: usize) -> Result<bool, MeshError> {
let bits = usize::try_from(mask.bit_width()).unwrap_or(0).max(1);
if chn >= bits + 2 {
return Err(MeshError::Index(IndexKind::Str));
}
Ok(chn < bits && (mask >> chn) & 1 == 1)
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct VertexData<'a> {
pub(crate) obj: Obj<'a>,
pub(crate) streamed: Option<&'a [u8]>,
}
#[allow(clippy::too_many_arguments)] pub(crate) fn read_vertex_data(
version: Version,
little: bool,
normalise: bool,
vertex_data: VertexData<'_>,
channels: &List<'_>,
streams: &Streams<'_>,
attrs: &mut Attributes,
meter: &Arc<Meter>,
) -> Result<Option<u64>, MeshError> {
let vd = vertex_data.obj;
let count = field(&vd, "m_VertexCount", u64::from(u32::MAX))?;
if count == 0 {
return Ok(None);
}
let data = match vertex_data.streamed {
Some(b) => b,
None => vd
.bytes("m_DataSize")?
.ok_or(MeshError::NoAttribute("m_DataSize"))?,
};
if data.is_empty() {
return Ok(None);
}
let vertex_count = u32::try_from(count).unwrap_or(u32::MAX);
meter.count_decode(u64::try_from(channels.len()).unwrap_or(u64::MAX))?;
for (chn, ch) in channels.iter().enumerate() {
let ch = ch?;
if field(&ch, "dimension", 255)? == 0 {
continue;
}
let stream = field(&ch, "stream", 255)?;
let stream = usize::try_from(stream).unwrap_or(usize::MAX);
let file_stream = match streams {
Streams::Derived { .. } => None,
Streams::File(list) => {
let s = list
.get(stream)
.ok_or(MeshError::Index(IndexKind::List))??;
let mask = field(&s, "channelMask", u64::from(u32::MAX))?;
if !mask_bit(mask, chn)? {
continue;
}
Some(s)
}
};
let colour = version.major()? < 2018 && chn == 2 && field(&ch, "format", 255)? == 2;
let (dimension, format) = if colour {
field(&ch, "offset", 255)?;
(4, 2)
} else {
(field(&ch, "dimension", 255)?, field(&ch, "format", 255)?)
};
let format = u8::try_from(format).unwrap_or(u8::MAX);
let code = get_channel_dtype(version, format)?;
let major = version.major()?;
let norm = if normalise && !is_blend_indices(major, chn) {
FormatTable::for_major(major).norm(format)
} else {
None
};
let size = code.size();
let swap = little && size > 1;
let channel_dimension = u32::try_from(dimension & 0xF).unwrap_or(0);
let (stream_offset, stream_stride) = match (file_stream, streams) {
(Some(s), _) => (
field(&s, "offset", u64::from(u32::MAX))?,
field(&s, "stride", u64::from(u32::MAX))?,
),
(None, Streams::Derived { streams: v, .. }) => {
let s = v.get(stream).copied().unwrap_or_default();
(low32(s.offset), low32(u128::from(s.stride)))
}
(None, Streams::File(_)) => (0, 0),
};
let channel_offset = field(&ch, "offset", 255)?;
let args = Gather {
component_byte_size: size,
vertex_count,
stream_offset: u32::try_from(stream_offset).unwrap_or(0),
stream_stride: u32::try_from(stream_stride).unwrap_or(0),
channel_offset: u32::try_from(channel_offset).unwrap_or(0),
channel_dimension,
swap,
};
let array = unpack_channel(data, &args, code, norm, meter)?;
assign(version, chn, array, attrs)?;
}
Ok(Some(count))
}
fn is_blend_indices(major: u16, chn: usize) -> bool {
major >= 2018 && chn == 13
}
fn low32(v: u128) -> u64 {
u64::try_from(v & 0xFFFF_FFFF).unwrap_or(0)
}
pub(crate) fn assign(
version: Version,
channel: usize,
data: VertexArray,
attrs: &mut Attributes,
) -> Result<(), MeshError> {
let major = version.major()?;
let slot = if major >= 2018 {
match channel {
0 => &mut attrs.vertices,
1 => &mut attrs.normals,
2 => &mut attrs.tangents,
3 => &mut attrs.colors,
4..=11 => uv(attrs, channel - 4),
12 => &mut attrs.bone_weights,
13 => &mut attrs.bone_indices,
_ => return Err(unknown(channel)),
}
} else {
match channel {
0 => &mut attrs.vertices,
1 => &mut attrs.normals,
2 => &mut attrs.colors,
3 => uv(attrs, 0),
4 => uv(attrs, 1),
5 if major >= 5 => uv(attrs, 2),
5 | 7 => &mut attrs.tangents,
6 => uv(attrs, 3),
_ => return Err(unknown(channel)),
}
};
*slot = Some(data);
Ok(())
}
fn uv(attrs: &mut Attributes, i: usize) -> &mut Option<VertexArray> {
let [u0, u1, u2, u3, u4, u5, u6, u7] = &mut attrs.uv;
match i {
0 => u0,
1 => u1,
2 => u2,
3 => u3,
4 => u4,
5 => u5,
6 => u6,
_ => u7,
}
}
fn unknown(channel: usize) -> MeshError {
MeshError::UnknownChannel(u64::try_from(channel).unwrap_or(u64::MAX))
}
#[cfg(test)]
mod tests {
use super::mask_bit;
use crate::error::{IndexKind, MeshError};
#[test]
fn the_mask_is_read_as_its_reversed_binary_string() {
assert!(mask_bit(0b101, 0).unwrap());
assert!(!mask_bit(0b101, 1).unwrap());
assert!(mask_bit(0b101, 2).unwrap());
assert!(!mask_bit(0b101, 3).unwrap());
assert!(!mask_bit(0b101, 4).unwrap());
assert!(matches!(
mask_bit(0b101, 5),
Err(MeshError::Index(IndexKind::Str))
));
assert!(!mask_bit(0, 0).unwrap());
assert!(!mask_bit(0, 2).unwrap());
assert!(mask_bit(0, 3).is_err());
assert!(mask_bit(u64::from(u32::MAX), 31).unwrap());
assert!(!mask_bit(u64::from(u32::MAX), 33).unwrap());
assert!(mask_bit(u64::from(u32::MAX), 34).is_err());
}
}