use std::sync::Arc;
use unityrs_core::env::Environment;
use unityrs_core::limits::{Charge, Meter, MeteredVec};
use unityrs_core::{Bytes, Parsed, RawStr, SerializedFile};
use crate::compressed::decompress_compressed_mesh;
use crate::error::{MeshError, StructError, Unsupported};
use crate::triangles::{Triangles, get_triangles};
use crate::unpack::{Values, VertexArray, widen};
use crate::vertex::{Attributes, Streams, VertexData, field, get_streams, read_vertex_data};
use crate::{ProcessedOwned, Version};
use unityrs_core::Value;
use unityrs_core::objmode::{
BONE_WEIGHTS, CHANNEL_INFO, Ints, List, MESH, MESH_6000, Obj, SPRITE, SPRITE_RENDER_DATA,
STREAM_INFO, STREAMING_INFO, VERTEX_DATA,
};
pub trait Resources: Send + Sync {
fn resource(&self, path: &RawStr, offset: u64, size: u64)
-> Result<Bytes, unityrs_core::Error>;
}
const _: () = crate::send_sync::<dyn Resources>();
#[derive(Clone, Copy, Debug)]
pub struct FileResources<'a> {
pub env: &'a Environment,
pub file: &'a Arc<SerializedFile>,
}
const _: () = crate::send_sync::<FileResources<'static>>();
impl Resources for FileResources<'_> {
fn resource(
&self,
path: &RawStr,
offset: u64,
size: u64,
) -> Result<Bytes, unityrs_core::Error> {
self.env.resource(self.file, path, offset, size)
}
}
#[derive(Clone, Copy, Debug)]
pub struct Source<'a> {
parsed: &'a Parsed,
kind: Kind,
}
const _: () = crate::send_sync::<Source<'static>>();
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Mesh,
RenderData,
}
impl<'a> Source<'a> {
#[must_use]
pub const fn mesh(parsed: &'a Parsed) -> Self {
Self {
parsed,
kind: Kind::Mesh,
}
}
#[must_use]
pub const fn sprite(parsed: &'a Parsed) -> Self {
Self {
parsed,
kind: Kind::RenderData,
}
}
fn root<'m>(&self, meter: &'m Meter) -> Result<Obj<'m>, MeshError>
where
'a: 'm,
{
match self.kind {
Kind::Mesh => Ok(Obj::root(self.parsed, &MESH, meter)?),
Kind::RenderData => Obj::root(self.parsed, &SPRITE, meter)?
.class("m_RD", &SPRITE_RENDER_DATA)?
.ok_or(MeshError::NoAttribute("m_RD")),
}
}
fn upgrade<'m>(
&self,
obj: Obj<'m>,
version: Version,
meter: &'m Meter,
) -> Result<Obj<'m>, MeshError>
where
'a: 'm,
{
if self.kind == Kind::Mesh && !obj.built() && version.at_least(&[6000])? {
return Ok(Obj::root(self.parsed, &MESH_6000, meter)?);
}
Ok(obj)
}
fn is_mesh(&self, obj: &Obj<'_>) -> bool {
self.kind == Kind::Mesh && obj.built()
}
fn is_render_data(&self, obj: &Obj<'_>) -> bool {
self.kind == Kind::RenderData && obj.built()
}
}
#[derive(Clone, Copy, Debug)]
pub struct MeshHandler<'a> {
src: Source<'a>,
version: Version,
little: bool,
}
const _: () = crate::send_sync::<MeshHandler<'static>>();
impl<'a> MeshHandler<'a> {
#[must_use]
pub fn new(src: Source<'a>, version: Version) -> Self {
Self {
src,
version,
little: true,
}
}
#[must_use]
pub fn little_endian(mut self, little: bool) -> Self {
self.little = little;
self
}
pub fn process(
&self,
resources: Option<&dyn Resources>,
meter: &Arc<Meter>,
) -> Result<Processed<'a>, MeshError> {
let version = self.version;
let mesh = self.src.root(meter)?;
let vd = mesh
.class("m_VertexData", &VERTEX_DATA)?
.ok_or(MeshError::Assertion(""))?;
let mesh = self.src.upgrade(mesh, version, meter)?;
let (channels, streams) = channels_and_streams(version, &vd, meter)?;
let streamed = if self.src.is_mesh(&mesh) {
stream_data(&mesh, resources)?
} else {
None
};
let mut use_16bit = true;
let mut attrs = Attributes::default();
let index = if self.src.is_mesh(&mesh) {
if let Some(v) = mesh.int32("m_Use16BitIndices")? {
use_16bit = v != 0;
} else if version.at_least(&[2017, 4])?
|| (version.minor_is(2017, 3)?
&& field(&mesh, "m_MeshCompression", u64::from(u8::MAX))? == 0)
{
use_16bit = mesh.int32("m_IndexFormat")? == Some(0);
}
copy_from_mesh(&mesh, &mut attrs, meter)?
} else if self.src.is_render_data(&mesh) {
copy_from_spriterenderdata(&mesh, meter)?
} else {
return Err(MeshError::UnknownMeshType);
};
let mut index_buffer = match index {
Some(ints) => Some(unpack_indices(ints, use_16bit, meter)?),
None => None,
};
let mut vertex_count = 0;
if version.at_least(&[3, 5])? {
let data = VertexData {
obj: vd,
streamed: streamed.as_deref(),
};
let read = read_vertex_data(
version,
self.little,
self.src.is_mesh(&mesh),
data,
&channels,
&streams,
&mut attrs,
meter,
)?;
if let Some(n) = read {
vertex_count = n;
}
}
if self.src.is_mesh(&mesh) && version.at_least(&[2, 6])? {
let done = decompress_compressed_mesh(version, &mesh, &mut attrs, meter)?;
vertex_count = done.vertex_count;
if let Some((values, charge)) = done.triangles {
index_buffer = Some(IndexBuffer {
values,
_charge: charge,
});
}
}
if vertex_count == 0
&& let Some(v) = attrs.vertices.as_ref().filter(|v| !v.is_empty())
{
vertex_count = u64::try_from(v.len()).unwrap_or(u64::MAX);
}
Ok(Processed {
src: self.src,
version,
vertex_count,
use_16bit,
index_buffer,
attrs,
})
}
}
fn channels_and_streams<'a>(
version: Version,
vd: &Obj<'a>,
meter: &Arc<Meter>,
) -> Result<(List<'a>, Streams<'a>), MeshError> {
let major = version.major()?;
if major < 4 {
for name in [
"m_Streams_0_",
"m_Streams_1_",
"m_Streams_2_",
"m_Streams_3_",
] {
if vd.class(name, &STREAM_INFO)?.is_none() {
return Err(MeshError::Assertion(""));
}
}
return Err(MeshError::Unsupported(Unsupported::FixedChannels));
}
if major == 4 {
let streams = vd
.list("m_Streams", &STREAM_INFO)?
.ok_or(MeshError::Assertion(""))?;
let channels = vd
.list("m_Channels", &CHANNEL_INFO)?
.ok_or(MeshError::Assertion(""))?;
return Ok((channels, Streams::File(streams)));
}
let channels = vd
.list("m_Channels", &CHANNEL_INFO)?
.ok_or(MeshError::Assertion(""))?;
let count = field(vd, "m_VertexCount", u64::from(u32::MAX))?;
let streams = get_streams(version, &channels, count, meter)?;
Ok((channels, streams))
}
fn stream_data(
mesh: &Obj<'_>,
resources: Option<&dyn Resources>,
) -> Result<Option<Bytes>, MeshError> {
let Some(sd) = mesh.class("m_StreamData", &STREAMING_INFO)? else {
return Ok(None);
};
let path = sd.string("path")?.ok_or(MeshError::NoAttribute("path"))?;
if path.is_empty() {
return Ok(None);
}
let resources = resources.ok_or(MeshError::Assertion(
"No object reader assigned to the input Mesh!",
))?;
let offset = field(&sd, "offset", u64::MAX)?;
let size = field(&sd, "size", u64::MAX)?;
resources
.resource(path, offset, size)
.map(Some)
.map_err(MeshError::Resource)
}
fn list_len(v: &Value, name: &'static str, meter: &Meter) -> Result<usize, MeshError> {
match v {
Value::List(items) => Ok(items.len()),
Value::Tuple(items) => Ok(items.len()),
Value::Prims(p) => Ok(p.len()),
Value::Bytes(b) => Ok(b.len()),
_ => Err(MeshError::malformed(
format_args!("{name} is not a list"),
meter,
)),
}
}
fn copy_from_mesh<'a>(
mesh: &Obj<'a>,
attrs: &mut Attributes,
meter: &Arc<Meter>,
) -> Result<Option<Ints<'a>>, MeshError> {
let index = mesh.ints("m_IndexBuffer")?.filter(|i| !i.is_empty());
for name in [
"m_Vertices",
"m_Normals",
"m_Tangents",
"m_UV",
"m_UV1",
"m_Colors",
] {
if let Some((_, v)) = mesh.get(name)?
&& list_len(v, name, meter)? > 0
{
return Err(MeshError::Unsupported(Unsupported::MeshArray(name)));
}
}
if let Some(skin) = mesh.list("m_Skin", &BONE_WEIGHTS)?
&& !skin.is_empty()
{
let (indices, weights) = copy_skin(&skin, meter)?;
attrs.bone_indices = Some(indices);
attrs.bone_weights = Some(weights);
}
Ok(index)
}
fn copy_skin(skin: &List<'_>, meter: &Arc<Meter>) -> Result<(VertexArray, VertexArray), MeshError> {
const INDICES: [&str; 4] = [
"boneIndex_0_",
"boneIndex_1_",
"boneIndex_2_",
"boneIndex_3_",
];
const WEIGHTS: [&str; 4] = ["weight_0_", "weight_1_", "weight_2_", "weight_3_"];
let n = skin.len().saturating_mul(4);
let mut indices = MeteredVec::<i64>::with_capacity(meter, n)?;
let mut weights = MeteredVec::<f64>::with_capacity(meter, n)?;
meter.count_decode(u64::try_from(n).unwrap_or(u64::MAX).saturating_mul(2))?;
for bone in skin.iter() {
let bone = bone?;
for name in INDICES {
let (_, v) = bone.get(name)?.ok_or(MeshError::NoAttribute(name))?;
match v {
Value::Int(i) if i32::try_from(*i).is_ok() => indices.push(*i)?,
_ => {
return Err(MeshError::malformed(
format_args!("{name} is not an int"),
meter,
));
}
}
}
}
for bone in skin.iter() {
let bone = bone?;
for name in WEIGHTS {
let (_, v) = bone.get(name)?.ok_or(MeshError::NoAttribute(name))?;
match v {
Value::F32(bits) => weights.push(widen(*bits))?,
Value::F64(bits) => weights.push(f64::from_bits(*bits))?,
_ => {
return Err(MeshError::malformed(
format_args!("{name} is not a float"),
meter,
));
}
}
}
}
let (indices, c1) = indices.into_parts();
let (weights, c2) = weights.into_parts();
Ok((
VertexArray::new(4, Values::Int(indices), c1),
VertexArray::new(4, Values::Float(weights), c2),
))
}
fn copy_from_spriterenderdata<'a>(
rd: &Obj<'a>,
meter: &Meter,
) -> Result<Option<Ints<'a>>, MeshError> {
let mut index = rd.ints("m_IndexBuffer")?.filter(|i| !i.is_empty());
if index.is_none() {
index = rd.ints("indices")?.filter(|i| !i.is_empty());
}
if let Some((_, v)) = rd.get("vertices")?
&& list_len(v, "vertices", meter)? > 0
{
return Err(MeshError::Unsupported(Unsupported::SpriteVertices));
}
Ok(index)
}
fn unpack_indices(
ints: Ints<'_>,
use_16bit: bool,
meter: &Arc<Meter>,
) -> Result<IndexBuffer, MeshError> {
let len = ints.len();
let size = if use_16bit { 2 } else { 4 };
let count = len / size;
let mut out = MeteredVec::<u32>::with_capacity(meter, count)?;
meter.count_decode(u64::try_from(len).unwrap_or(u64::MAX).saturating_mul(2))?;
if ints.as_u8().is_none() {
for i in 0..len {
ints.byte(i)?;
}
}
if !len.is_multiple_of(size) {
let wanted = u64::try_from(count * size).unwrap_or(u64::MAX);
return Err(MeshError::Struct(StructError::UnpackSize(wanted)));
}
for k in 0..count {
let at = k * size;
let byte = |j: usize| ints.byte(at + j).map(u32::from);
let v = if use_16bit {
byte(0)? | byte(1)? << 8
} else {
byte(0)? | byte(1)? << 8 | byte(2)? << 16 | byte(3)? << 24
};
out.push(v)?;
}
let (values, charge) = out.into_parts();
Ok(IndexBuffer {
values,
_charge: charge,
})
}
#[derive(Debug)]
pub struct IndexBuffer {
values: Vec<u32>,
_charge: Charge,
}
const _: () = crate::send_sync::<IndexBuffer>();
impl IndexBuffer {
#[must_use]
pub fn as_slice(&self) -> &[u32] {
&self.values
}
}
#[derive(Debug)]
pub struct Processed<'a> {
src: Source<'a>,
version: Version,
vertex_count: u64,
use_16bit: bool,
index_buffer: Option<IndexBuffer>,
attrs: Attributes,
}
const _: () = crate::send_sync::<Processed<'static>>();
impl Processed<'_> {
#[must_use]
pub fn into_owned(self) -> ProcessedOwned {
ProcessedOwned {
vertex_count: self.vertex_count,
use_16bit: self.use_16bit,
index_buffer: self.index_buffer,
attrs: self.attrs,
}
}
#[must_use]
pub fn vertex_count(&self) -> u64 {
self.vertex_count
}
#[must_use]
pub fn use_16bit_indices(&self) -> bool {
self.use_16bit
}
#[must_use]
pub fn index_buffer(&self) -> Option<&IndexBuffer> {
self.index_buffer.as_ref()
}
#[must_use]
pub fn vertices(&self) -> Option<&VertexArray> {
self.attrs.vertices.as_ref()
}
#[must_use]
pub fn normals(&self) -> Option<&VertexArray> {
self.attrs.normals.as_ref()
}
#[must_use]
pub fn tangents(&self) -> Option<&VertexArray> {
self.attrs.tangents.as_ref()
}
#[must_use]
pub fn colors(&self) -> Option<&VertexArray> {
self.attrs.colors.as_ref()
}
#[must_use]
pub fn uv(&self, i: usize) -> Option<&VertexArray> {
self.attrs.uv.get(i).and_then(Option::as_ref)
}
#[must_use]
pub fn bone_weights(&self) -> Option<&VertexArray> {
self.attrs.bone_weights.as_ref()
}
#[must_use]
pub fn bone_indices(&self) -> Option<&VertexArray> {
self.attrs.bone_indices.as_ref()
}
#[must_use]
pub fn bind_pose(&self) -> Option<&VertexArray> {
self.attrs.bind_pose.as_ref()
}
pub fn get_triangles(&self, meter: &Arc<Meter>) -> Result<Triangles, MeshError> {
get_triangles(
&self
.src
.upgrade(self.src.root(meter)?, self.version, meter)?,
self.version,
self.use_16bit,
self.index_buffer.as_ref().map(IndexBuffer::as_slice),
meter,
)
}
}