use std::sync::Arc;
use unityrs_core::limits::{Charge, Meter, MeteredVec};
use crate::error::{MeshError, StructError};
use crate::format::{Norm, StructCode};
#[derive(Debug)]
pub struct VertexArray {
dimension: usize,
values: Values,
_charge: Charge,
}
const _: () = crate::send_sync::<VertexArray>();
#[derive(Debug, PartialEq)]
#[non_exhaustive]
pub enum Values {
Float(Vec<f64>),
Int(Vec<i64>),
Mixed(Vec<Component>),
}
const _: () = crate::send_sync::<Values>();
impl VertexArray {
#[must_use]
pub fn from_components(dimension: usize, values: MeteredVec<Component>) -> Self {
let (values, charge) = values.into_parts();
Self::new(dimension, Values::Mixed(values), charge)
}
pub(crate) fn new(dimension: usize, values: Values, charge: Charge) -> Self {
Self {
dimension,
values,
_charge: charge,
}
}
#[must_use]
pub fn dimension(&self) -> usize {
self.dimension
}
fn values_len(&self) -> usize {
match &self.values {
Values::Float(v) => v.len(),
Values::Int(v) => v.len(),
Values::Mixed(v) => v.len(),
}
}
#[must_use]
pub fn len(&self) -> usize {
if self.dimension == 0 {
return 0;
}
self.values_len().div_ceil(self.dimension)
}
#[must_use]
pub fn tuple_len(&self, tuple: usize) -> Option<usize> {
if tuple >= self.len() {
return None;
}
let from = tuple.checked_mul(self.dimension)?;
Some((self.values_len() - from).min(self.dimension))
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
#[must_use]
pub fn values(&self) -> &Values {
&self.values
}
#[must_use]
pub fn component(&self, tuple: usize, component: usize) -> Option<Component> {
if component >= self.tuple_len(tuple)? {
return None;
}
let at = tuple.checked_mul(self.dimension)?.checked_add(component)?;
match &self.values {
Values::Float(v) => v.get(at).copied().map(Component::Float),
Values::Int(v) => v.get(at).copied().map(Component::Int),
Values::Mixed(v) => v.get(at).copied(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Component {
Float(f64),
Int(i64),
}
const _: () = crate::send_sync::<Component>();
impl Component {
#[must_use]
#[allow(clippy::cast_precision_loss)] pub fn as_f64(self) -> f64 {
match self {
Self::Float(f) => f,
Self::Int(i) => i as f64,
}
}
#[must_use]
pub fn is_truthy(self) -> bool {
match self {
Self::Float(f) => f != 0.0,
Self::Int(i) => i != 0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Gather {
pub component_byte_size: u32,
pub vertex_count: u32,
pub stream_offset: u32,
pub stream_stride: u32,
pub channel_offset: u32,
pub channel_dimension: u32,
pub swap: bool,
}
const _: () = crate::send_sync::<Gather>();
impl Gather {
fn check(&self, len: usize) -> Result<u64, MeshError> {
let cbs = self.component_byte_size;
let dim = self.channel_dimension;
let max_access = self
.vertex_count
.wrapping_sub(1)
.wrapping_mul(self.stream_stride)
.wrapping_add(self.channel_offset)
.wrapping_add(self.stream_offset)
.wrapping_add(cbs.wrapping_mul(dim.wrapping_sub(1)))
.wrapping_add(cbs);
if u64::from(max_access) > u64::try_from(len).unwrap_or(u64::MAX) {
return Err(MeshError::OutOfBounds);
}
let wrapped = self.vertex_count.wrapping_mul(dim).wrapping_mul(cbs);
let exact = u128::from(self.vertex_count) * u128::from(dim) * u128::from(cbs);
if exact != u128::from(wrapped) {
return Err(MeshError::WrappedAccess);
}
Ok(u64::from(wrapped))
}
fn offset(&self, v: u32, d: u32) -> u32 {
self.stream_offset
.wrapping_add(self.channel_offset)
.wrapping_add(self.stream_stride.wrapping_mul(v))
.wrapping_add(self.component_byte_size.wrapping_mul(d))
}
fn each(
&self,
data: &[u8],
mut visit: impl FnMut(&[u8]) -> Result<(), MeshError>,
) -> Result<(), MeshError> {
let cbs = usize::try_from(self.component_byte_size).unwrap_or(usize::MAX);
for v in 0..self.vertex_count {
for d in 0..self.channel_dimension {
let at = usize::try_from(self.offset(v, d)).unwrap_or(usize::MAX);
let src = at
.checked_add(cbs)
.and_then(|end| data.get(at..end))
.ok_or(MeshError::WrappedAccess)?;
visit(src)?;
}
}
Ok(())
}
}
#[derive(Debug)]
pub struct ComponentBytes {
bytes: Vec<u8>,
_charge: Charge,
}
const _: () = crate::send_sync::<ComponentBytes>();
impl ComponentBytes {
#[must_use]
pub fn as_slice(&self) -> &[u8] {
&self.bytes
}
}
pub fn unpack_vertexdata(
data: &[u8],
args: &Gather,
meter: &Arc<Meter>,
) -> Result<ComponentBytes, MeshError> {
let length = args.check(data.len())?;
let n = usize::try_from(length).map_err(|_| MeshError::WrappedAccess)?;
let mut out = MeteredVec::<u8>::with_capacity(meter, n)?;
meter.count_decode(length)?;
let swap = args.swap && matches!(args.component_byte_size, 2 | 4);
if length == 0 {
let (bytes, charge) = out.into_parts();
return Ok(ComponentBytes {
bytes,
_charge: charge,
});
}
args.each(data, |src| {
if swap {
for &b in src.iter().rev() {
out.push(b)?;
}
} else {
out.extend_from_slice(src)?;
}
Ok(())
})?;
let (bytes, charge) = out.into_parts();
Ok(ComponentBytes {
bytes,
_charge: charge,
})
}
pub(crate) fn unpack_channel(
data: &[u8],
args: &Gather,
code: StructCode,
norm: Option<Norm>,
meter: &Arc<Meter>,
) -> Result<VertexArray, MeshError> {
let length = args.check(data.len())?;
let dimension = usize::try_from(args.channel_dimension).unwrap_or(usize::MAX);
if dimension == 0 {
return Err(MeshError::Struct(StructError::ZeroLength));
}
let n = usize::try_from(u64::from(args.vertex_count) * u64::from(args.channel_dimension))
.map_err(|_| MeshError::WrappedAccess)?;
let little = args.swap;
if code.is_float() || norm.is_some() {
let mut out = MeteredVec::<f64>::with_capacity(meter, n)?;
meter.count_decode(length)?;
args.each(data, |src| {
out.push(match norm {
Some(rule) if !code.is_float() => rule.value(code, int(code, src, little)),
_ => float(code, src, little),
})?;
Ok(())
})?;
let (v, charge) = out.into_parts();
Ok(VertexArray::new(dimension, Values::Float(v), charge))
} else {
let mut out = MeteredVec::<i64>::with_capacity(meter, n)?;
meter.count_decode(length)?;
args.each(data, |src| {
out.push(int(code, src, little))?;
Ok(())
})?;
let (v, charge) = out.into_parts();
Ok(VertexArray::new(dimension, Values::Int(v), charge))
}
}
fn le(src: &[u8], little: bool) -> [u8; 4] {
let mut a = [0u8; 4];
if little {
a.iter_mut().zip(src).for_each(|(o, b)| *o = *b);
} else {
a.iter_mut()
.zip(src.iter().rev())
.for_each(|(o, b)| *o = *b);
}
a
}
fn int(code: StructCode, src: &[u8], little: bool) -> i64 {
let [a, b, c, d] = le(src, little);
match code {
StructCode::I8 => i64::from(i8::from_le_bytes([a])),
StructCode::U16 => i64::from(u16::from_le_bytes([a, b])),
StructCode::I16 => i64::from(i16::from_le_bytes([a, b])),
StructCode::U32 => i64::from(u32::from_le_bytes([a, b, c, d])),
StructCode::I32 => i64::from(i32::from_le_bytes([a, b, c, d])),
StructCode::U8 | StructCode::F16 | StructCode::F32 => i64::from(a),
}
}
fn float(code: StructCode, src: &[u8], little: bool) -> f64 {
let [a, b, c, d] = le(src, little);
match code {
StructCode::F16 => half(u16::from_le_bytes([a, b])),
_ => widen(u32::from_le_bytes([a, b, c, d])),
}
}
pub(crate) fn widen(bits: u32) -> f64 {
let f = f32::from_bits(bits);
if f.is_nan() {
let sign = u64::from(bits >> 31) << 63;
let payload = u64::from((bits & 0x007f_ffff) | 0x0040_0000);
f64::from_bits(sign | 0x7ff0_0000_0000_0000 | (payload << 29))
} else {
f64::from(f)
}
}
pub(crate) fn half(bits: u16) -> f64 {
let sign = u64::from(bits >> 15) << 63;
let exponent = u64::from((bits >> 10) & 0x1f);
let fraction = bits & 0x03ff;
let magnitude = match exponent {
0 => (f64::from(fraction) * 2f64.powi(-24)).to_bits(),
0x1f if fraction == 0 => f64::INFINITY.to_bits(),
0x1f => 0x7ff8_0000_0000_0000,
_ => ((exponent + 1023 - 15) << 52) | (u64::from(fraction) << 42),
};
f64::from_bits(sign | magnitude)
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use unityrs_core::limits::{Charge, Meter};
use super::{Component, Gather, Values, VertexArray, half, unpack_vertexdata, widen};
use crate::error::MeshError;
fn args(vc: u32, soff: u32, stride: u32, choff: u32, dim: u32, cbs: u32) -> Gather {
Gather {
component_byte_size: cbs,
vertex_count: vc,
stream_offset: soff,
stream_stride: stride,
channel_offset: choff,
channel_dimension: dim,
swap: true,
}
}
#[test]
fn halves_and_floats_widen_as_the_oracle_does() {
assert_eq!(half(0x7c00), f64::INFINITY);
assert_eq!(half(0x7c01).to_bits(), 0x7ff8_0000_0000_0000);
assert_eq!(half(0x7e00).to_bits(), 0x7ff8_0000_0000_0000);
assert_eq!(half(0xfc01).to_bits(), 0xfff8_0000_0000_0000);
assert_eq!(half(0x3c00), 1.0);
assert_eq!(half(0x0001), 2f64.powi(-24));
assert_eq!(half(0x8000).to_bits(), (-0.0f64).to_bits());
assert_eq!(widen(0x7f80_0001).to_bits(), 0x7ff8_0000_2000_0000);
assert_eq!(widen(0xffa0_0005).to_bits(), 0xfffc_0000_a000_0000);
assert_eq!(widen(0x7fc0_0000).to_bits(), 0x7ff8_0000_0000_0000);
}
#[test]
fn every_half_widens_to_its_value() {
for bits in 0..=u16::MAX {
let (e, f) = (i32::from((bits >> 10) & 0x1f), f64::from(bits & 0x3ff));
if e == 0x1f {
continue;
}
let x = if e == 0 {
f / 1024.0 * 2f64.powi(-14)
} else {
(1.0 + f / 1024.0) * 2f64.powi(e - 15)
};
let want = if bits & 0x8000 != 0 { -x } else { x };
assert_eq!(half(bits).to_bits(), want.to_bits(), "{bits:#06x}");
}
}
#[test]
fn a_backward_stride_reads_as_unitypyboost_reads_it() {
let data: Vec<u8> = (0..12).collect();
let a = args(3, 8, 0xFFFF_FFFC, 0, 1, 4);
let out = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap();
assert_eq!(out.as_slice(), &[11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
}
#[test]
fn a_wrapped_offset_past_the_data_is_refused() {
let data = [0u8; 16];
let a = args(8, 0xFFFF_FFF0, 4, 0, 1, 4);
let e = unpack_vertexdata(&data, &a, &Meter::unlimited()).unwrap_err();
assert!(matches!(e, MeshError::WrappedAccess), "{e:?}");
let a = args(8, 0, 4, 0, 1, 4);
let e = unpack_vertexdata(&data, &a, &Arc::clone(&Meter::unlimited())).unwrap_err();
assert!(matches!(e, MeshError::OutOfBounds), "{e:?}");
}
fn array(dimension: usize, values: Values) -> VertexArray {
VertexArray::new(dimension, values, Charge::zero(&Meter::unlimited()))
}
#[test]
fn a_component_is_a_python_float_or_int_by_the_form_that_holds_it() {
let floats = array(2, Values::Float(vec![0.5, -1.0, 2.0, 3.5]));
assert_eq!(floats.len(), 2);
assert_eq!(floats.component(0, 1), Some(Component::Float(-1.0)));
assert_eq!(floats.component(1, 0), Some(Component::Float(2.0)));
let ints = array(3, Values::Int(vec![1, -2, 3, i64::MAX, 0, -7]));
assert_eq!(ints.component(1, 0), Some(Component::Int(i64::MAX)));
assert_eq!(ints.component(0, 2), Some(Component::Int(3)));
assert_eq!(
Component::Int(i64::MAX).as_f64(),
9_223_372_036_854_775_808.0
);
assert_eq!(
Component::Int((1 << 53) + 1).as_f64(),
9_007_199_254_740_992.0
);
assert_eq!(Component::Float(-0.25).as_f64(), -0.25);
}
#[test]
fn a_component_past_the_tuples_or_its_tuple_is_none() {
let a = array(2, Values::Float(vec![1.0, 2.0, 3.0]));
assert_eq!(a.len(), 2);
assert_eq!(
(a.tuple_len(0), a.tuple_len(1), a.tuple_len(2)),
(Some(2), Some(1), None)
);
assert_eq!(a.component(0, 2), None);
assert_eq!(a.component(0, 1), Some(Component::Float(2.0)));
assert_eq!(a.component(1, 0), Some(Component::Float(3.0)));
assert_eq!(a.component(1, 1), None);
assert_eq!(a.component(2, 0), None);
assert_eq!(a.component(usize::MAX, 1), None);
assert_eq!(a.component(usize::MAX / 2 + 1, 0), None);
let empty = array(0, Values::Int(vec![1, 2]));
assert_eq!((empty.len(), empty.component(0, 0)), (0, None));
}
#[test]
fn truth_is_python_s() {
assert!(!Component::Float(0.0).is_truthy());
assert!(!Component::Float(-0.0).is_truthy());
assert!(Component::Float(f64::NAN).is_truthy());
assert!(Component::Float(f64::MIN_POSITIVE / 2.0).is_truthy());
assert!(!Component::Int(0).is_truthy());
assert!(Component::Int(-1).is_truthy());
}
}