1use std::sync::Arc;
53
54use unityrs_core::env::Environment;
55use unityrs_core::limits::{Charge, Meter, MeteredVec};
56use unityrs_core::{Bytes, Parsed, RawStr, SerializedFile};
57
58use crate::compressed::decompress_compressed_mesh;
59use crate::error::{MeshError, StructError, Unsupported};
60use crate::triangles::{Triangles, get_triangles};
61use crate::unpack::{Values, VertexArray, widen};
62use crate::vertex::{Attributes, Streams, VertexData, field, get_streams, read_vertex_data};
63use crate::{ProcessedOwned, Version};
64use unityrs_core::Value;
65use unityrs_core::objmode::{
66 BONE_WEIGHTS, CHANNEL_INFO, Ints, List, MESH, MESH_6000, Obj, SPRITE, SPRITE_RENDER_DATA,
67 STREAM_INFO, STREAMING_INFO, VERTEX_DATA,
68};
69
70pub trait Resources: Send + Sync {
74 fn resource(&self, path: &RawStr, offset: u64, size: u64)
76 -> Result<Bytes, unityrs_core::Error>;
77}
78
79const _: () = crate::send_sync::<dyn Resources>();
80
81#[derive(Clone, Copy, Debug)]
84pub struct FileResources<'a> {
85 pub env: &'a Environment,
87 pub file: &'a Arc<SerializedFile>,
89}
90
91const _: () = crate::send_sync::<FileResources<'static>>();
92
93impl Resources for FileResources<'_> {
94 fn resource(
95 &self,
96 path: &RawStr,
97 offset: u64,
98 size: u64,
99 ) -> Result<Bytes, unityrs_core::Error> {
100 self.env.resource(self.file, path, offset, size)
101 }
102}
103
104#[derive(Clone, Copy, Debug)]
107pub struct Source<'a> {
108 parsed: &'a Parsed,
109 kind: Kind,
110}
111
112const _: () = crate::send_sync::<Source<'static>>();
113
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115enum Kind {
116 Mesh,
117 RenderData,
118}
119
120impl<'a> Source<'a> {
121 #[must_use]
124 pub const fn mesh(parsed: &'a Parsed) -> Self {
125 Self {
126 parsed,
127 kind: Kind::Mesh,
128 }
129 }
130
131 #[must_use]
136 pub const fn sprite(parsed: &'a Parsed) -> Self {
137 Self {
138 parsed,
139 kind: Kind::RenderData,
140 }
141 }
142
143 fn root<'m>(&self, meter: &'m Meter) -> Result<Obj<'m>, MeshError>
146 where
147 'a: 'm,
148 {
149 match self.kind {
150 Kind::Mesh => Ok(Obj::root(self.parsed, &MESH, meter)?),
151 Kind::RenderData => Obj::root(self.parsed, &SPRITE, meter)?
152 .class("m_RD", &SPRITE_RENDER_DATA)?
153 .ok_or(MeshError::NoAttribute("m_RD")),
154 }
155 }
156
157 fn upgrade<'m>(
163 &self,
164 obj: Obj<'m>,
165 version: Version,
166 meter: &'m Meter,
167 ) -> Result<Obj<'m>, MeshError>
168 where
169 'a: 'm,
170 {
171 if self.kind == Kind::Mesh && !obj.built() && version.at_least(&[6000])? {
172 return Ok(Obj::root(self.parsed, &MESH_6000, meter)?);
173 }
174 Ok(obj)
175 }
176
177 fn is_mesh(&self, obj: &Obj<'_>) -> bool {
179 self.kind == Kind::Mesh && obj.built()
180 }
181
182 fn is_render_data(&self, obj: &Obj<'_>) -> bool {
184 self.kind == Kind::RenderData && obj.built()
185 }
186}
187
188#[derive(Clone, Copy, Debug)]
190pub struct MeshHandler<'a> {
191 src: Source<'a>,
192 version: Version,
193 little: bool,
194}
195
196const _: () = crate::send_sync::<MeshHandler<'static>>();
197
198impl<'a> MeshHandler<'a> {
199 #[must_use]
202 pub fn new(src: Source<'a>, version: Version) -> Self {
203 Self {
204 src,
205 version,
206 little: true,
207 }
208 }
209
210 #[must_use]
214 pub fn little_endian(mut self, little: bool) -> Self {
215 self.little = little;
216 self
217 }
218
219 pub fn process(
225 &self,
226 resources: Option<&dyn Resources>,
227 meter: &Arc<Meter>,
228 ) -> Result<Processed<'a>, MeshError> {
229 let version = self.version;
230 let mesh = self.src.root(meter)?;
231 let vd = mesh
233 .class("m_VertexData", &VERTEX_DATA)?
234 .ok_or(MeshError::Assertion(""))?;
235 let mesh = self.src.upgrade(mesh, version, meter)?;
236 let (channels, streams) = channels_and_streams(version, &vd, meter)?;
237
238 let streamed = if self.src.is_mesh(&mesh) {
240 stream_data(&mesh, resources)?
241 } else {
242 None
243 };
244
245 let mut use_16bit = true;
246 let mut attrs = Attributes::default();
247 let index = if self.src.is_mesh(&mesh) {
248 if let Some(v) = mesh.int32("m_Use16BitIndices")? {
250 use_16bit = v != 0;
251 } else if version.at_least(&[2017, 4])?
252 || (version.minor_is(2017, 3)?
253 && field(&mesh, "m_MeshCompression", u64::from(u8::MAX))? == 0)
254 {
255 use_16bit = mesh.int32("m_IndexFormat")? == Some(0);
256 }
257 copy_from_mesh(&mesh, &mut attrs, meter)?
258 } else if self.src.is_render_data(&mesh) {
259 copy_from_spriterenderdata(&mesh, meter)?
260 } else {
261 return Err(MeshError::UnknownMeshType);
262 };
263
264 let mut index_buffer = match index {
266 Some(ints) => Some(unpack_indices(ints, use_16bit, meter)?),
267 None => None,
268 };
269
270 let mut vertex_count = 0;
272 if version.at_least(&[3, 5])? {
273 let data = VertexData {
274 obj: vd,
275 streamed: streamed.as_deref(),
276 };
277 let read = read_vertex_data(
278 version,
279 self.little,
280 self.src.is_mesh(&mesh),
281 data,
282 &channels,
283 &streams,
284 &mut attrs,
285 meter,
286 )?;
287 if let Some(n) = read {
288 vertex_count = n;
289 }
290 }
291
292 if self.src.is_mesh(&mesh) && version.at_least(&[2, 6])? {
294 let done = decompress_compressed_mesh(version, &mesh, &mut attrs, meter)?;
295 vertex_count = done.vertex_count;
296 if let Some((values, charge)) = done.triangles {
297 index_buffer = Some(IndexBuffer {
298 values,
299 _charge: charge,
300 });
301 }
302 }
303
304 if vertex_count == 0
306 && let Some(v) = attrs.vertices.as_ref().filter(|v| !v.is_empty())
307 {
308 vertex_count = u64::try_from(v.len()).unwrap_or(u64::MAX);
309 }
310
311 Ok(Processed {
312 src: self.src,
313 version,
314 vertex_count,
315 use_16bit,
316 index_buffer,
317 attrs,
318 })
319 }
320}
321
322fn channels_and_streams<'a>(
324 version: Version,
325 vd: &Obj<'a>,
326 meter: &Arc<Meter>,
327) -> Result<(List<'a>, Streams<'a>), MeshError> {
328 let major = version.major()?;
329 if major < 4 {
330 for name in [
332 "m_Streams_0_",
333 "m_Streams_1_",
334 "m_Streams_2_",
335 "m_Streams_3_",
336 ] {
337 if vd.class(name, &STREAM_INFO)?.is_none() {
338 return Err(MeshError::Assertion(""));
339 }
340 }
341 return Err(MeshError::Unsupported(Unsupported::FixedChannels));
343 }
344 if major == 4 {
345 let streams = vd
347 .list("m_Streams", &STREAM_INFO)?
348 .ok_or(MeshError::Assertion(""))?;
349 let channels = vd
350 .list("m_Channels", &CHANNEL_INFO)?
351 .ok_or(MeshError::Assertion(""))?;
352 return Ok((channels, Streams::File(streams)));
353 }
354 let channels = vd
356 .list("m_Channels", &CHANNEL_INFO)?
357 .ok_or(MeshError::Assertion(""))?;
358 let count = field(vd, "m_VertexCount", u64::from(u32::MAX))?;
359 let streams = get_streams(version, &channels, count, meter)?;
360 Ok((channels, streams))
361}
362
363fn stream_data(
366 mesh: &Obj<'_>,
367 resources: Option<&dyn Resources>,
368) -> Result<Option<Bytes>, MeshError> {
369 let Some(sd) = mesh.class("m_StreamData", &STREAMING_INFO)? else {
370 return Ok(None);
371 };
372 let path = sd.string("path")?.ok_or(MeshError::NoAttribute("path"))?;
373 if path.is_empty() {
374 return Ok(None);
375 }
376 let resources = resources.ok_or(MeshError::Assertion(
377 "No object reader assigned to the input Mesh!",
378 ))?;
379 let offset = field(&sd, "offset", u64::MAX)?;
380 let size = field(&sd, "size", u64::MAX)?;
381 resources
382 .resource(path, offset, size)
383 .map(Some)
384 .map_err(MeshError::Resource)
385}
386
387fn list_len(v: &Value, name: &'static str, meter: &Meter) -> Result<usize, MeshError> {
389 match v {
390 Value::List(items) => Ok(items.len()),
391 Value::Tuple(items) => Ok(items.len()),
392 Value::Prims(p) => Ok(p.len()),
393 Value::Bytes(b) => Ok(b.len()),
394 _ => Err(MeshError::malformed(
395 format_args!("{name} is not a list"),
396 meter,
397 )),
398 }
399}
400
401fn copy_from_mesh<'a>(
404 mesh: &Obj<'a>,
405 attrs: &mut Attributes,
406 meter: &Arc<Meter>,
407) -> Result<Option<Ints<'a>>, MeshError> {
408 let index = mesh.ints("m_IndexBuffer")?.filter(|i| !i.is_empty());
410 for name in [
412 "m_Vertices",
413 "m_Normals",
414 "m_Tangents",
415 "m_UV",
416 "m_UV1",
417 "m_Colors",
418 ] {
419 if let Some((_, v)) = mesh.get(name)?
420 && list_len(v, name, meter)? > 0
421 {
422 return Err(MeshError::Unsupported(Unsupported::MeshArray(name)));
423 }
424 }
425 if let Some(skin) = mesh.list("m_Skin", &BONE_WEIGHTS)?
427 && !skin.is_empty()
428 {
429 let (indices, weights) = copy_skin(&skin, meter)?;
430 attrs.bone_indices = Some(indices);
431 attrs.bone_weights = Some(weights);
432 }
433 Ok(index)
434}
435
436fn copy_skin(skin: &List<'_>, meter: &Arc<Meter>) -> Result<(VertexArray, VertexArray), MeshError> {
439 const INDICES: [&str; 4] = [
440 "boneIndex_0_",
441 "boneIndex_1_",
442 "boneIndex_2_",
443 "boneIndex_3_",
444 ];
445 const WEIGHTS: [&str; 4] = ["weight_0_", "weight_1_", "weight_2_", "weight_3_"];
446 let n = skin.len().saturating_mul(4);
447 let mut indices = MeteredVec::<i64>::with_capacity(meter, n)?;
450 let mut weights = MeteredVec::<f64>::with_capacity(meter, n)?;
451 meter.count_decode(u64::try_from(n).unwrap_or(u64::MAX).saturating_mul(2))?;
452 for bone in skin.iter() {
453 let bone = bone?;
454 for name in INDICES {
455 let (_, v) = bone.get(name)?.ok_or(MeshError::NoAttribute(name))?;
456 match v {
457 Value::Int(i) if i32::try_from(*i).is_ok() => indices.push(*i)?,
458 _ => {
459 return Err(MeshError::malformed(
460 format_args!("{name} is not an int"),
461 meter,
462 ));
463 }
464 }
465 }
466 }
467 for bone in skin.iter() {
468 let bone = bone?;
469 for name in WEIGHTS {
470 let (_, v) = bone.get(name)?.ok_or(MeshError::NoAttribute(name))?;
471 match v {
472 Value::F32(bits) => weights.push(widen(*bits))?,
473 Value::F64(bits) => weights.push(f64::from_bits(*bits))?,
474 _ => {
475 return Err(MeshError::malformed(
476 format_args!("{name} is not a float"),
477 meter,
478 ));
479 }
480 }
481 }
482 }
483 let (indices, c1) = indices.into_parts();
484 let (weights, c2) = weights.into_parts();
485 Ok((
486 VertexArray::new(4, Values::Int(indices), c1),
487 VertexArray::new(4, Values::Float(weights), c2),
488 ))
489}
490
491fn copy_from_spriterenderdata<'a>(
494 rd: &Obj<'a>,
495 meter: &Meter,
496) -> Result<Option<Ints<'a>>, MeshError> {
497 let mut index = rd.ints("m_IndexBuffer")?.filter(|i| !i.is_empty());
499 if index.is_none() {
500 index = rd.ints("indices")?.filter(|i| !i.is_empty());
501 }
502 if let Some((_, v)) = rd.get("vertices")?
504 && list_len(v, "vertices", meter)? > 0
505 {
506 return Err(MeshError::Unsupported(Unsupported::SpriteVertices));
507 }
508 Ok(index)
509}
510
511fn unpack_indices(
514 ints: Ints<'_>,
515 use_16bit: bool,
516 meter: &Arc<Meter>,
517) -> Result<IndexBuffer, MeshError> {
518 let len = ints.len();
519 let size = if use_16bit { 2 } else { 4 };
520 let count = len / size;
521 let mut out = MeteredVec::<u32>::with_capacity(meter, count)?;
523 meter.count_decode(u64::try_from(len).unwrap_or(u64::MAX).saturating_mul(2))?;
524 if ints.as_u8().is_none() {
526 for i in 0..len {
527 ints.byte(i)?;
528 }
529 }
530 if !len.is_multiple_of(size) {
531 let wanted = u64::try_from(count * size).unwrap_or(u64::MAX);
532 return Err(MeshError::Struct(StructError::UnpackSize(wanted)));
533 }
534 for k in 0..count {
535 let at = k * size;
536 let byte = |j: usize| ints.byte(at + j).map(u32::from);
537 let v = if use_16bit {
538 byte(0)? | byte(1)? << 8
539 } else {
540 byte(0)? | byte(1)? << 8 | byte(2)? << 16 | byte(3)? << 24
541 };
542 out.push(v)?;
543 }
544 let (values, charge) = out.into_parts();
545 Ok(IndexBuffer {
546 values,
547 _charge: charge,
548 })
549}
550
551#[derive(Debug)]
553pub struct IndexBuffer {
554 values: Vec<u32>,
555 _charge: Charge,
557}
558
559const _: () = crate::send_sync::<IndexBuffer>();
560
561impl IndexBuffer {
562 #[must_use]
564 pub fn as_slice(&self) -> &[u32] {
565 &self.values
566 }
567}
568
569#[derive(Debug)]
572pub struct Processed<'a> {
573 src: Source<'a>,
574 version: Version,
575 vertex_count: u64,
576 use_16bit: bool,
577 index_buffer: Option<IndexBuffer>,
578 attrs: Attributes,
579}
580
581const _: () = crate::send_sync::<Processed<'static>>();
582
583impl Processed<'_> {
584 #[must_use]
587 pub fn into_owned(self) -> ProcessedOwned {
588 ProcessedOwned {
589 vertex_count: self.vertex_count,
590 use_16bit: self.use_16bit,
591 index_buffer: self.index_buffer,
592 attrs: self.attrs,
593 }
594 }
595
596 #[must_use]
598 pub fn vertex_count(&self) -> u64 {
599 self.vertex_count
600 }
601
602 #[must_use]
604 pub fn use_16bit_indices(&self) -> bool {
605 self.use_16bit
606 }
607
608 #[must_use]
610 pub fn index_buffer(&self) -> Option<&IndexBuffer> {
611 self.index_buffer.as_ref()
612 }
613
614 #[must_use]
616 pub fn vertices(&self) -> Option<&VertexArray> {
617 self.attrs.vertices.as_ref()
618 }
619
620 #[must_use]
622 pub fn normals(&self) -> Option<&VertexArray> {
623 self.attrs.normals.as_ref()
624 }
625
626 #[must_use]
628 pub fn tangents(&self) -> Option<&VertexArray> {
629 self.attrs.tangents.as_ref()
630 }
631
632 #[must_use]
634 pub fn colors(&self) -> Option<&VertexArray> {
635 self.attrs.colors.as_ref()
636 }
637
638 #[must_use]
640 pub fn uv(&self, i: usize) -> Option<&VertexArray> {
641 self.attrs.uv.get(i).and_then(Option::as_ref)
642 }
643
644 #[must_use]
646 pub fn bone_weights(&self) -> Option<&VertexArray> {
647 self.attrs.bone_weights.as_ref()
648 }
649
650 #[must_use]
652 pub fn bone_indices(&self) -> Option<&VertexArray> {
653 self.attrs.bone_indices.as_ref()
654 }
655
656 #[must_use]
662 pub fn bind_pose(&self) -> Option<&VertexArray> {
663 self.attrs.bind_pose.as_ref()
664 }
665
666 pub fn get_triangles(&self, meter: &Arc<Meter>) -> Result<Triangles, MeshError> {
672 get_triangles(
673 &self
674 .src
675 .upgrade(self.src.root(meter)?, self.version, meter)?,
676 self.version,
677 self.use_16bit,
678 self.index_buffer.as_ref().map(IndexBuffer::as_slice),
679 meter,
680 )
681 }
682}