1#![cfg_attr(target_arch = "mips", feature(asm_experimental_arch))]
3#![no_std]
41#![deny(unsafe_op_in_unsafe_fn)]
42#![warn(missing_docs)]
43
44pub mod hma1;
45pub mod hmd8;
46pub mod tracks;
47
48use psx_gte::math::{Vec3I16, Vec3I32};
49
50const MESH_VERSION_U8_INDICES: u16 = 1;
51const MESH_U8_INDEX_STRIDE: usize = 3;
52const MESH_U16_INDEX_STRIDE: usize = 6;
53
54pub mod world_topology {
56 pub use psxed_format::world::topology::{
57 horizontal_triangle_at_local, split_triangle, split_triangles, triangle_contains_corner,
58 wall_shape_for_dropped_corner, wall_shape_triangle, wall_shape_triangle_corners,
59 SplitTriangles, TriangleCorners, HORIZONTAL_NE_SW_TRIANGLES, HORIZONTAL_NW_SE_TRIANGLES,
60 SPLIT_ONE_THREE_TRIANGLES, SPLIT_ZERO_TWO_TRIANGLES, WHOLE_QUAD_TRIANGLE_INDEX,
61 };
62}
63
64pub const WORLD_SPLIT_NORTH_WEST_SOUTH_EAST: u8 = psxed_format::world::split::NORTH_WEST_SOUTH_EAST;
66
67pub const WORLD_SPLIT_NORTH_EAST_SOUTH_WEST: u8 = psxed_format::world::split::NORTH_EAST_SOUTH_WEST;
69
70pub const WORLD_WALL_SHAPE_QUAD: u16 = psxed_format::world::wall_shape::QUAD;
72
73pub const WORLD_WALL_SHAPE_DROP_BOTTOM_LEFT: u16 =
75 psxed_format::world::wall_shape::DROP_BOTTOM_LEFT;
76
77pub const WORLD_WALL_SHAPE_DROP_BOTTOM_RIGHT: u16 =
79 psxed_format::world::wall_shape::DROP_BOTTOM_RIGHT;
80
81pub const WORLD_WALL_SHAPE_DROP_TOP_RIGHT: u16 = psxed_format::world::wall_shape::DROP_TOP_RIGHT;
83
84pub const WORLD_WALL_SHAPE_DROP_TOP_LEFT: u16 = psxed_format::world::wall_shape::DROP_TOP_LEFT;
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum ParseError {
90 Truncated,
92 WrongMagic,
94 UnsupportedVersion(u16),
96 InvalidPayloadLen {
98 declared: u32,
100 actual: usize,
102 },
103 TableOverflow,
105 InvalidWorldLayout,
107 InvalidModelLayout,
109 InvalidAnimationLayout,
111 InvalidAudioLayout,
113}
114
115#[derive(Copy, Clone, Debug)]
121pub struct Mesh<'a> {
122 verts: &'a [u8],
123 indices: &'a [u8],
124 face_colors: Option<&'a [u8]>,
125 vertex_normals: Option<&'a [u8]>,
126 index_stride: u8,
127 vert_count: u16,
128 face_count: u16,
129 flags: u16,
130}
131
132impl<'a> Mesh<'a> {
133 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
136 if bytes.len() < psxed_format::AssetHeader::SIZE {
138 return Err(ParseError::Truncated);
139 }
140 let magic: [u8; 4] = [bytes[0], bytes[1], bytes[2], bytes[3]];
141 if magic != psxed_format::mesh::MAGIC {
142 return Err(ParseError::WrongMagic);
143 }
144 let version = u16::from_le_bytes([bytes[4], bytes[5]]);
145 let index_stride = match version {
146 MESH_VERSION_U8_INDICES => MESH_U8_INDEX_STRIDE,
147 psxed_format::mesh::VERSION => MESH_U16_INDEX_STRIDE,
148 _ => return Err(ParseError::UnsupportedVersion(version)),
149 };
150 let flags = u16::from_le_bytes([bytes[6], bytes[7]]);
151 let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
152 let payload_start = psxed_format::AssetHeader::SIZE;
153 let actual_payload = bytes.len().saturating_sub(payload_start);
154 if (payload_len as usize) != actual_payload {
155 return Err(ParseError::InvalidPayloadLen {
156 declared: payload_len,
157 actual: actual_payload,
158 });
159 }
160
161 if actual_payload < psxed_format::mesh::MeshHeader::SIZE {
163 return Err(ParseError::Truncated);
164 }
165 let mh = &bytes[payload_start..];
166 let vert_count = u16::from_le_bytes([mh[0], mh[1]]);
167 let face_count = u16::from_le_bytes([mh[2], mh[3]]);
168 let mut off = payload_start + psxed_format::mesh::MeshHeader::SIZE;
172 let vert_bytes = (vert_count as usize) * 6;
173 if off + vert_bytes > bytes.len() {
174 return Err(ParseError::TableOverflow);
175 }
176 let verts = &bytes[off..off + vert_bytes];
177 off += vert_bytes;
178
179 let index_bytes = (face_count as usize) * index_stride;
180 if off + index_bytes > bytes.len() {
181 return Err(ParseError::TableOverflow);
182 }
183 let indices = &bytes[off..off + index_bytes];
184 off += index_bytes;
185
186 let face_colors = if flags & psxed_format::mesh::flags::HAS_FACE_COLORS != 0 {
187 let color_bytes = (face_count as usize) * 3;
188 if off + color_bytes > bytes.len() {
189 return Err(ParseError::TableOverflow);
190 }
191 let slice = &bytes[off..off + color_bytes];
192 off += color_bytes;
193 Some(slice)
194 } else {
195 None
196 };
197
198 let vertex_normals = if flags & psxed_format::mesh::flags::HAS_NORMALS != 0 {
199 let normal_bytes = (vert_count as usize) * 6;
200 if off + normal_bytes > bytes.len() {
201 return Err(ParseError::TableOverflow);
202 }
203 let slice = &bytes[off..off + normal_bytes];
204 Some(slice)
205 } else {
206 None
207 };
208
209 Ok(Self {
210 verts,
211 indices,
212 face_colors,
213 vertex_normals,
214 index_stride: index_stride as u8,
215 vert_count,
216 face_count,
217 flags,
218 })
219 }
220
221 #[inline]
223 pub fn vertex_count(&self) -> u16 {
224 self.vert_count
225 }
226
227 #[deprecated(note = "renamed to `vertex_count`")]
229 #[inline(always)]
230 pub fn vert_count(&self) -> u16 {
231 self.vertex_count()
232 }
233
234 #[inline]
236 pub fn face_count(&self) -> u16 {
237 self.face_count
238 }
239
240 #[inline]
242 pub fn flags(&self) -> u16 {
243 self.flags
244 }
245
246 #[inline]
248 pub fn has_face_colors(&self) -> bool {
249 self.flags & psxed_format::mesh::flags::HAS_FACE_COLORS != 0
250 }
251
252 #[inline]
255 pub fn has_normals(&self) -> bool {
256 self.flags & psxed_format::mesh::flags::HAS_NORMALS != 0
257 }
258
259 #[inline]
264 pub fn vertex(&self, i: u16) -> Vec3I16 {
265 let idx = i as usize;
266 if idx >= self.vert_count as usize {
267 return Vec3I16::ZERO;
268 }
269 let base = idx * 6;
270 let x = i16::from_le_bytes([self.verts[base], self.verts[base + 1]]);
271 let y = i16::from_le_bytes([self.verts[base + 2], self.verts[base + 3]]);
272 let z = i16::from_le_bytes([self.verts[base + 4], self.verts[base + 5]]);
273 Vec3I16::new(x, y, z)
274 }
275
276 #[inline]
279 pub fn face(&self, i: u16) -> (u16, u16, u16) {
280 let idx = i as usize;
281 if idx >= self.face_count as usize {
282 return (0, 0, 0);
283 }
284 let base = idx * self.index_stride as usize;
285 if self.index_stride as usize == MESH_U16_INDEX_STRIDE {
286 (
287 u16::from_le_bytes([self.indices[base], self.indices[base + 1]]),
288 u16::from_le_bytes([self.indices[base + 2], self.indices[base + 3]]),
289 u16::from_le_bytes([self.indices[base + 4], self.indices[base + 5]]),
290 )
291 } else {
292 (
293 self.indices[base] as u16,
294 self.indices[base + 1] as u16,
295 self.indices[base + 2] as u16,
296 )
297 }
298 }
299
300 #[inline]
303 pub fn face_color(&self, i: u16) -> Option<(u8, u8, u8)> {
304 let colors = self.face_colors?;
305 let idx = i as usize;
306 if idx >= self.face_count as usize {
307 return None;
308 }
309 let base = idx * 3;
310 Some((colors[base], colors[base + 1], colors[base + 2]))
311 }
312
313 #[inline]
319 pub fn vertex_normal(&self, i: u16) -> Option<Vec3I16> {
320 let normals = self.vertex_normals?;
321 let idx = i as usize;
322 if idx >= self.vert_count as usize {
323 return None;
324 }
325 let base = idx * 6;
326 let x = i16::from_le_bytes([normals[base], normals[base + 1]]);
327 let y = i16::from_le_bytes([normals[base + 2], normals[base + 3]]);
328 let z = i16::from_le_bytes([normals[base + 4], normals[base + 5]]);
329 Some(Vec3I16::new(x, y, z))
330 }
331}
332
333#[derive(Copy, Clone, Debug)]
341pub struct Model<'a> {
342 joints: &'a [u8],
343 materials: &'a [u8],
344 parts: &'a [u8],
345 vertices: &'a [u8],
346 faces: &'a [u8],
347 face_palette_banks: Option<&'a [u8]>,
348 joint_count: u16,
349 material_count: u16,
350 part_count: u16,
351 vertex_count: u16,
352 face_count: u16,
353 texture_width: u16,
354 texture_height: u16,
355 local_to_world_q12: u16,
356 flags: u16,
357}
358
359impl<'a> Model<'a> {
360 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
362 use psxed_format::model::{
363 JointRecord, MaterialRecord, ModelHeader, PartRecord, FACE_RECORD_SIZE, LEGACY_VERSION,
364 MAGIC, VERSION, VERTEX_RECORD_SIZE,
365 };
366
367 if bytes.len() < psxed_format::AssetHeader::SIZE {
368 return Err(ParseError::Truncated);
369 }
370 let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
371 if magic != MAGIC {
372 return Err(ParseError::WrongMagic);
373 }
374 let version = read_u16(bytes, 4);
375 if version != LEGACY_VERSION && version != VERSION {
376 return Err(ParseError::UnsupportedVersion(version));
377 }
378 let flags = read_u16(bytes, 6);
379 let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
380 let payload_start = psxed_format::AssetHeader::SIZE;
381 let actual_payload = bytes.len().saturating_sub(payload_start);
382 if payload_len as usize != actual_payload {
383 return Err(ParseError::InvalidPayloadLen {
384 declared: payload_len,
385 actual: actual_payload,
386 });
387 }
388 if actual_payload < ModelHeader::SIZE {
389 return Err(ParseError::Truncated);
390 }
391
392 let mh = &bytes[payload_start..payload_start + ModelHeader::SIZE];
393 let joint_count = read_u16(mh, 0);
394 let part_count = read_u16(mh, 2);
395 let vertex_count = read_u16(mh, 4);
396 let face_count = read_u16(mh, 6);
397 let material_count = read_u16(mh, 8);
398 let texture_width = read_u16(mh, 10);
399 let texture_height = read_u16(mh, 12);
400 let local_to_world_q12 = read_u16(mh, 14);
401
402 let mut off = payload_start + ModelHeader::SIZE;
403
404 let joint_bytes = checked_table_bytes(joint_count, JointRecord::SIZE)?;
405 let joints = take_table(bytes, &mut off, joint_bytes)?;
406
407 let material_bytes = checked_table_bytes(material_count, MaterialRecord::SIZE)?;
408 let materials = take_table(bytes, &mut off, material_bytes)?;
409
410 let part_bytes = checked_table_bytes(part_count, PartRecord::SIZE)?;
411 let parts = take_table(bytes, &mut off, part_bytes)?;
412
413 let vertex_bytes = checked_table_bytes(vertex_count, VERTEX_RECORD_SIZE)?;
414 let vertices = take_table(bytes, &mut off, vertex_bytes)?;
415
416 let face_bytes = checked_table_bytes(face_count, FACE_RECORD_SIZE)?;
417 let faces = take_table(bytes, &mut off, face_bytes)?;
418
419 let has_face_palette_banks = flags & psxed_format::model::flags::FACE_PALETTE_BANKS != 0;
420 if version == LEGACY_VERSION && has_face_palette_banks {
421 return Err(ParseError::InvalidModelLayout);
422 }
423 let face_palette_banks = if has_face_palette_banks {
424 let bytes_needed = psxed_format::model::face_palette_bank_bytes(face_count);
425 Some(take_table(bytes, &mut off, bytes_needed)?)
426 } else {
427 None
428 };
429
430 if off != bytes.len() {
431 return Err(ParseError::InvalidModelLayout);
432 }
433 validate_model_parts(parts, joint_count, material_count, vertex_count, face_count)?;
434 validate_model_faces(faces, vertex_count)?;
435
436 Ok(Self {
437 joints,
438 materials,
439 parts,
440 vertices,
441 faces,
442 face_palette_banks,
443 joint_count,
444 material_count,
445 part_count,
446 vertex_count,
447 face_count,
448 texture_width,
449 texture_height,
450 local_to_world_q12,
451 flags,
452 })
453 }
454
455 #[inline]
457 pub fn flags(&self) -> u16 {
458 self.flags
459 }
460
461 #[inline]
464 pub fn is_double_sided(&self) -> bool {
465 self.flags & psxed_format::model::flags::DOUBLE_SIDED != 0
466 }
467
468 #[inline]
470 pub fn joint_count(&self) -> u16 {
471 self.joint_count
472 }
473
474 #[inline]
476 pub fn material_count(&self) -> u16 {
477 self.material_count
478 }
479
480 #[inline]
482 pub fn part_count(&self) -> u16 {
483 self.part_count
484 }
485
486 #[inline]
488 pub fn vertex_count(&self) -> u16 {
489 self.vertex_count
490 }
491
492 #[inline]
494 pub fn face_count(&self) -> u16 {
495 self.face_count
496 }
497
498 #[inline]
500 pub fn texture_width(&self) -> u16 {
501 self.texture_width
502 }
503
504 #[inline]
506 pub fn texture_height(&self) -> u16 {
507 self.texture_height
508 }
509
510 pub fn bind_pose_floor_lift(&self) -> i32 {
520 let mut lowest = i32::MAX;
521 let mut i = 0u16;
522 while i < self.vertex_count() {
523 if let Some(vertex) = self.vertex(i) {
524 lowest = lowest.min(vertex.position.y as i32);
525 }
526 i = i.wrapping_add(1);
527 if i == 0 {
528 break;
529 }
530 }
531 if lowest == i32::MAX || lowest >= 0 {
532 return 0;
533 }
534 -lowest
535 }
536
537 #[inline]
542 pub fn local_to_world_q12(&self) -> u16 {
543 if self.local_to_world_q12 == 0 {
544 psxed_format::model::DEFAULT_LOCAL_TO_WORLD_Q12
545 } else {
546 self.local_to_world_q12
547 }
548 }
549
550 #[inline]
552 pub fn joint(&self, index: u16) -> Option<ModelJoint> {
553 if index >= self.joint_count {
554 return None;
555 }
556 let base = index as usize * psxed_format::model::JointRecord::SIZE;
557 let bytes = self
558 .joints
559 .get(base..base + psxed_format::model::JointRecord::SIZE)?;
560 Some(ModelJoint {
561 parent: read_u16(bytes, 0),
562 })
563 }
564
565 #[inline]
567 pub fn material(&self, index: u16) -> Option<ModelMaterial> {
568 if index >= self.material_count {
569 return None;
570 }
571 let base = index as usize * psxed_format::model::MaterialRecord::SIZE;
572 let bytes = self
573 .materials
574 .get(base..base + psxed_format::model::MaterialRecord::SIZE)?;
575 Some(ModelMaterial {
576 texture_index: read_u16(bytes, 0),
577 flags: read_u16(bytes, 2),
578 base_color: [bytes[4], bytes[5], bytes[6], bytes[7]],
579 })
580 }
581
582 #[inline]
584 pub fn part(&self, index: u16) -> Option<ModelPart> {
585 if index >= self.part_count {
586 return None;
587 }
588 let base = index as usize * psxed_format::model::PartRecord::SIZE;
589 let bytes = self
590 .parts
591 .get(base..base + psxed_format::model::PartRecord::SIZE)?;
592 Some(ModelPart {
593 joint_index: read_u16(bytes, 0),
594 first_vertex: read_u16(bytes, 2),
595 vertex_count: read_u16(bytes, 4),
596 first_face: read_u16(bytes, 6),
597 face_count: read_u16(bytes, 8),
598 material_index: read_u16(bytes, 10),
599 })
600 }
601
602 #[inline]
604 pub fn vertex(&self, index: u16) -> Option<ModelVertex> {
605 if index >= self.vertex_count {
606 return None;
607 }
608 let base = index as usize * psxed_format::model::VERTEX_RECORD_SIZE;
609 let bytes = self
610 .vertices
611 .get(base..base + psxed_format::model::VERTEX_RECORD_SIZE)?;
612 Some(ModelVertex {
613 position: Vec3I16::new(read_i16(bytes, 0), read_i16(bytes, 2), read_i16(bytes, 4)),
614 joint1: bytes[6],
615 blend: bytes[7],
616 })
617 }
618
619 #[inline]
621 pub fn face(&self, index: u16) -> Option<ModelFace> {
622 if index >= self.face_count {
623 return None;
624 }
625 let base = index as usize * psxed_format::model::FACE_RECORD_SIZE;
626 let bytes = self
627 .faces
628 .get(base..base + psxed_format::model::FACE_RECORD_SIZE)?;
629 Some(ModelFace {
630 corners: [
631 ModelFaceCorner {
632 vertex_index: read_u16(bytes, 0),
633 uv: (bytes[2], bytes[3]),
634 },
635 ModelFaceCorner {
636 vertex_index: read_u16(bytes, 4),
637 uv: (bytes[6], bytes[7]),
638 },
639 ModelFaceCorner {
640 vertex_index: read_u16(bytes, 8),
641 uv: (bytes[10], bytes[11]),
642 },
643 ],
644 })
645 }
646
647 #[inline]
652 pub fn face_palette_bank(&self, index: u16) -> Option<u8> {
653 if index >= self.face_count {
654 return None;
655 }
656 let Some(packed) = self.face_palette_banks else {
657 return Some(0);
658 };
659 let byte = *packed.get(index as usize / 4)?;
660 Some((byte >> ((index as usize & 3) * 2)) & 3)
661 }
662
663 pub fn palette_bank_count(&self) -> u8 {
665 let mut highest = 0u8;
666 let mut index = 0u16;
667 while index < self.face_count {
668 highest = highest.max(self.face_palette_bank(index).unwrap_or(0));
669 index += 1;
670 }
671 highest + 1
672 }
673}
674
675#[derive(Copy, Clone, Debug, PartialEq, Eq)]
677pub struct ModelJoint {
678 parent: u16,
679}
680
681impl ModelJoint {
682 #[inline]
684 pub fn parent(&self) -> Option<u16> {
685 if self.parent == psxed_format::model::NO_JOINT {
686 None
687 } else {
688 Some(self.parent)
689 }
690 }
691}
692
693#[derive(Copy, Clone, Debug, PartialEq, Eq)]
695pub struct ModelMaterial {
696 texture_index: u16,
697 flags: u16,
698 base_color: [u8; 4],
699}
700
701impl ModelMaterial {
702 #[inline]
704 pub fn texture_index(&self) -> u16 {
705 self.texture_index
706 }
707
708 #[inline]
710 pub fn flags(&self) -> u16 {
711 self.flags
712 }
713
714 #[inline]
716 pub fn base_color(&self) -> [u8; 4] {
717 self.base_color
718 }
719}
720
721#[derive(Copy, Clone, Debug, PartialEq, Eq)]
723pub struct ModelPart {
724 joint_index: u16,
725 first_vertex: u16,
726 vertex_count: u16,
727 first_face: u16,
728 face_count: u16,
729 material_index: u16,
730}
731
732impl ModelPart {
733 pub const ZERO: Self = Self {
735 joint_index: 0,
736 first_vertex: 0,
737 vertex_count: 0,
738 first_face: 0,
739 face_count: 0,
740 material_index: 0,
741 };
742
743 #[inline]
745 pub fn joint_index(&self) -> u16 {
746 self.joint_index
747 }
748
749 #[inline]
751 pub fn first_vertex(&self) -> u16 {
752 self.first_vertex
753 }
754
755 #[inline]
757 pub fn vertex_count(&self) -> u16 {
758 self.vertex_count
759 }
760
761 #[inline]
763 pub fn first_face(&self) -> u16 {
764 self.first_face
765 }
766
767 #[inline]
769 pub fn face_count(&self) -> u16 {
770 self.face_count
771 }
772
773 #[inline]
775 pub fn material_index(&self) -> u16 {
776 self.material_index
777 }
778}
779
780pub const NO_JOINT8: u8 = psxed_format::model::NO_JOINT8;
784
785#[repr(C, align(4))]
789#[derive(Copy, Clone, Debug, PartialEq, Eq)]
790pub struct ModelVertex {
791 pub position: Vec3I16,
795 pub joint1: u8,
798 pub blend: u8,
801}
802
803const _: () = assert!(core::mem::size_of::<ModelVertex>() == 8);
805
806impl ModelVertex {
807 pub const ZERO: Self = Self {
809 position: Vec3I16::ZERO,
810 joint1: NO_JOINT8,
811 blend: 0,
812 };
813
814 #[inline]
816 pub fn is_blend(&self) -> bool {
817 self.blend != 0 && self.joint1 != NO_JOINT8
818 }
819}
820
821#[derive(Copy, Clone, Debug, PartialEq, Eq)]
823pub struct ModelFaceCorner {
824 pub vertex_index: u16,
826 pub uv: (u8, u8),
828}
829
830#[derive(Copy, Clone, Debug, PartialEq, Eq)]
832pub struct ModelFace {
833 pub corners: [ModelFaceCorner; 3],
835}
836
837#[derive(Copy, Clone, Debug)]
840pub struct Animation<'a> {
841 pose_indices: &'a [u8],
842 poses: &'a [u8],
844 joint_count: u16,
845 frame_count: u16,
846 sample_rate_hz: u16,
847 pose_record_size: usize,
849 translation_shift: u8,
850 tracks: Option<tracks::Tracks>,
851}
852
853const TRACKS_MARK: usize = 0;
855
856impl<'a> Animation<'a> {
857 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
859 use psxed_format::animation::{
860 AnimationHeader, MAGIC, POSE_RECORD_SIZE, POSE_RECORD_SIZE_V1, POSE_RECORD_SIZE_V3,
861 POSE_RECORD_SIZE_V4, VERSION, VERSION_V1, VERSION_V3, VERSION_V4, VERSION_V5,
862 VERSION_V6,
863 };
864
865 if bytes.len() < psxed_format::AssetHeader::SIZE {
866 return Err(ParseError::Truncated);
867 }
868 let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
869 if magic != MAGIC {
870 return Err(ParseError::WrongMagic);
871 }
872 let version = read_u16(bytes, 4);
873 let pose_record_size = match version {
874 VERSION => POSE_RECORD_SIZE,
875 VERSION_V1 => POSE_RECORD_SIZE_V1,
876 VERSION_V3 => POSE_RECORD_SIZE_V3,
877 VERSION_V4 | VERSION_V5 => POSE_RECORD_SIZE_V4,
878 VERSION_V6 => TRACKS_MARK,
879 _ => {
880 return Err(ParseError::UnsupportedVersion(version));
881 }
882 };
883 let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
884 let payload_start = psxed_format::AssetHeader::SIZE;
885 let actual_payload = bytes.len().saturating_sub(payload_start);
886 if payload_len as usize != actual_payload {
887 return Err(ParseError::InvalidPayloadLen {
888 declared: payload_len,
889 actual: actual_payload,
890 });
891 }
892 if actual_payload < AnimationHeader::SIZE {
893 return Err(ParseError::Truncated);
894 }
895
896 let ah = &bytes[payload_start..payload_start + AnimationHeader::SIZE];
897 let joint_count = read_u16(ah, 0);
898 let frame_count = read_u16(ah, 2);
899 let sample_rate_hz = read_u16(ah, 4);
900 let translation_shift = if version == VERSION
901 || version == VERSION_V3
902 || version == VERSION_V4
903 || version == VERSION_V5
904 || version == VERSION_V6
905 {
906 let shift = read_u16(ah, 6);
907 if shift > 15 {
908 return Err(ParseError::InvalidAnimationLayout);
909 }
910 shift as u8
911 } else {
912 0
913 };
914 if joint_count == 0 || frame_count == 0 || sample_rate_hz == 0 {
915 return Err(ParseError::InvalidAnimationLayout);
916 }
917
918 if version == VERSION_V6 {
919 let tracks = tracks::validate(bytes, joint_count, frame_count, translation_shift)?;
920 return Ok(Self {
921 pose_indices: &[],
922 poses: bytes,
923 joint_count,
924 frame_count,
925 sample_rate_hz,
926 pose_record_size: TRACKS_MARK,
927 translation_shift,
928 tracks: Some(tracks),
929 });
930 }
931
932 let mut off = payload_start + AnimationHeader::SIZE;
933 let pose_count = (joint_count as usize)
934 .checked_mul(frame_count as usize)
935 .ok_or(ParseError::TableOverflow)?;
936 let (pose_indices, poses) = if version == VERSION_V5 {
937 let index_bytes = pose_count.checked_mul(2).ok_or(ParseError::TableOverflow)?;
938 let indices = take_table(bytes, &mut off, index_bytes)?;
939 off = (off + 3) & !3;
940 let poses = bytes.get(off..).ok_or(ParseError::Truncated)?;
941 if poses.is_empty() || poses.len() % POSE_RECORD_SIZE_V4 != 0 {
942 return Err(ParseError::InvalidAnimationLayout);
943 }
944 let records = poses.len() / POSE_RECORD_SIZE_V4;
945 for index in indices.chunks_exact(2) {
946 if read_u16(index, 0) as usize >= records {
947 return Err(ParseError::InvalidAnimationLayout);
948 }
949 }
950 (indices, poses)
951 } else {
952 let pose_bytes = pose_count
953 .checked_mul(pose_record_size)
954 .ok_or(ParseError::TableOverflow)?;
955 let poses = take_table(bytes, &mut off, pose_bytes)?;
956 if off != bytes.len() {
957 return Err(ParseError::InvalidAnimationLayout);
958 }
959 (&[][..], poses)
960 };
961
962 Ok(Self {
963 pose_indices,
964 poses,
965 joint_count,
966 frame_count,
967 sample_rate_hz,
968 pose_record_size,
969 translation_shift,
970 tracks: None,
971 })
972 }
973
974 #[inline]
976 pub fn is_keyed_tracks(&self) -> bool {
977 self.tracks.is_some()
978 }
979
980 #[inline]
982 pub fn joint_count(&self) -> u16 {
983 self.joint_count
984 }
985
986 #[inline]
988 pub fn frame_count(&self) -> u16 {
989 self.frame_count
990 }
991
992 #[inline]
994 pub fn sample_rate_hz(&self) -> u16 {
995 self.sample_rate_hz
996 }
997
998 #[inline]
1000 pub fn pose_record_size(&self) -> usize {
1001 self.pose_record_size
1002 }
1003
1004 #[inline]
1006 pub fn translation_shift(&self) -> u8 {
1007 self.translation_shift
1008 }
1009
1010 #[inline]
1016 pub fn phase_step_q12(&self, playback_hz: u16) -> u32 {
1017 ((self.sample_rate_hz as u32) << 12) / playback_hz.max(1) as u32
1018 }
1019
1020 #[inline]
1026 pub fn phase_at_tick_q12(&self, playback_tick: u32, playback_hz: u16) -> u32 {
1027 playback_tick.wrapping_mul(self.phase_step_q12(playback_hz))
1028 }
1029
1030 #[inline]
1035 pub fn phase_at_tick_scaled_q12(
1036 &self,
1037 playback_tick: u32,
1038 playback_hz: u16,
1039 speed_q8: u16,
1040 ) -> u32 {
1041 let step = self.phase_step_q12(playback_hz);
1046 let speed = u32::from(speed_q8);
1047 let scaled_step = (step >> 8)
1048 .wrapping_mul(speed)
1049 .wrapping_add(((step & 0xff) * speed) >> 8);
1050 playback_tick.wrapping_mul(scaled_step)
1051 }
1052
1053 pub fn pose(&self, frame_index: u16, joint_index: u16) -> Option<JointPose> {
1055 if frame_index >= self.frame_count || joint_index >= self.joint_count {
1056 return None;
1057 }
1058 if let Some(tracks) = &self.tracks {
1059 let pos = tracks::track_pos(self.poses, u32::from(frame_index) << 8);
1060 return Some(unsafe { tracks::joint_pose(tracks, joint_index as usize, &pos) });
1063 }
1064 let base = frame_index as usize * self.joint_count as usize * self.pose_record_size;
1065 Some(unsafe { self.pose_at_frame_offset_unchecked(base, joint_index) })
1068 }
1069
1070 #[inline]
1071 fn record_offset(&self, logical_offset: usize) -> usize {
1072 if self.pose_indices.is_empty() {
1073 logical_offset
1074 } else {
1075 usize::from(read_u16(self.pose_indices, logical_offset >> 3)) << 4
1078 }
1079 }
1080
1081 #[inline]
1090 unsafe fn pose_at_frame_offset_unchecked(
1091 &self,
1092 frame_offset: usize,
1093 joint_index: u16,
1094 ) -> JointPose {
1095 let base = self.record_offset(frame_offset + joint_index as usize * self.pose_record_size);
1096 if self.poses.as_ptr() as usize & 1 != 0 {
1097 return unsafe { self.pose_at_byte_offset_unaligned(base) };
1100 }
1101 if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4 {
1102 return unsafe { self.pose_v4_unchecked(base) };
1106 }
1107 if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V3 {
1108 return unsafe { self.pose_v3_unchecked(base) };
1112 }
1113 let matrix = unsafe { read_pose_matrix_aligned_unchecked(self.poses, base) };
1120 let off = 18;
1121 let translation = if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE {
1122 Vec3I32::new(
1126 decode_packed_translation(
1127 unsafe { read_i16_aligned_unchecked(self.poses, base + off) },
1129 self.translation_shift,
1130 ),
1131 decode_packed_translation(
1132 unsafe { read_i16_aligned_unchecked(self.poses, base + off + 2) },
1134 self.translation_shift,
1135 ),
1136 decode_packed_translation(
1137 unsafe { read_i16_aligned_unchecked(self.poses, base + off + 4) },
1139 self.translation_shift,
1140 ),
1141 )
1142 } else {
1143 Vec3I32::new(
1146 unsafe { read_i32_unchecked(self.poses, base + off) },
1148 unsafe { read_i32_unchecked(self.poses, base + off + 4) },
1150 unsafe { read_i32_unchecked(self.poses, base + off + 8) },
1152 )
1153 };
1154 JointPose {
1155 matrix,
1156 translation,
1157 }
1158 }
1159
1160 unsafe fn pose_v3_unchecked(&self, base: usize) -> JointPose {
1171 let record = unsafe { self.poses.as_ptr().add(base) };
1174 let (matrix, packed_translation) = if record as usize & 3 == 0 {
1175 unsafe { read_pose_v3_word_aligned_unchecked(self.poses, base) }
1178 } else {
1179 let matrix = unsafe { read_pose_matrix_q11_unchecked(self.poses, base) };
1181 let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V3;
1182 let translation = Vec3I16::new(
1183 unsafe { read_i16_unchecked(self.poses, base + off) },
1185 unsafe { read_i16_unchecked(self.poses, base + off + 2) },
1187 unsafe { read_i16_unchecked(self.poses, base + off + 4) },
1189 );
1190 (matrix, translation)
1191 };
1192 let translation = Vec3I32::new(
1193 decode_packed_translation(packed_translation.x, self.translation_shift),
1194 decode_packed_translation(packed_translation.y, self.translation_shift),
1195 decode_packed_translation(packed_translation.z, self.translation_shift),
1196 );
1197 JointPose {
1198 matrix,
1199 translation,
1200 }
1201 }
1202
1203 unsafe fn pose_v4_unchecked(&self, base: usize) -> JointPose {
1209 let record = unsafe { self.poses.as_ptr().add(base) };
1212 let (matrix, packed_translation) = if record as usize & 3 == 0 {
1213 unsafe { read_pose_v4_word_aligned_unchecked(self.poses, base) }
1216 } else {
1217 let matrix = unsafe { read_pose_matrix_q11_cross_unchecked(self.poses, base) };
1219 let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V4;
1220 let translation = Vec3I16::new(
1221 unsafe { read_i16_unchecked(self.poses, base + off) },
1223 unsafe { read_i16_unchecked(self.poses, base + off + 2) },
1225 unsafe { read_i16_unchecked(self.poses, base + off + 4) },
1227 );
1228 (matrix, translation)
1229 };
1230 JointPose {
1231 matrix,
1232 translation: Vec3I32::new(
1233 decode_packed_translation(packed_translation.x, self.translation_shift),
1234 decode_packed_translation(packed_translation.y, self.translation_shift),
1235 decode_packed_translation(packed_translation.z, self.translation_shift),
1236 ),
1237 }
1238 }
1239
1240 #[inline(never)]
1247 unsafe fn pose_at_byte_offset_unaligned(&self, base: usize) -> JointPose {
1248 if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4 {
1249 return unsafe { self.pose_v4_unchecked(base) };
1251 }
1252 if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V3 {
1253 return unsafe { self.pose_v3_unchecked(base) };
1255 }
1256 let matrix = unsafe { read_pose_matrix_unchecked(self.poses, base) };
1260 let off = 18;
1261 let translation = if self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE {
1262 Vec3I32::new(
1263 decode_packed_translation(
1264 unsafe { read_i16_unchecked(self.poses, base + off) },
1266 self.translation_shift,
1267 ),
1268 decode_packed_translation(
1269 unsafe { read_i16_unchecked(self.poses, base + off + 2) },
1271 self.translation_shift,
1272 ),
1273 decode_packed_translation(
1274 unsafe { read_i16_unchecked(self.poses, base + off + 4) },
1276 self.translation_shift,
1277 ),
1278 )
1279 } else {
1280 Vec3I32::new(
1281 unsafe { read_i32_unchecked(self.poses, base + off) },
1283 unsafe { read_i32_unchecked(self.poses, base + off + 4) },
1285 unsafe { read_i32_unchecked(self.poses, base + off + 8) },
1287 )
1288 };
1289 JointPose {
1290 matrix,
1291 translation,
1292 }
1293 }
1294
1295 #[inline]
1296 fn packed_pose_at_frame_offset(
1297 &self,
1298 frame_offset: usize,
1299 joint_index: u16,
1300 ) -> Option<GteJointPose> {
1301 let v3 = self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V3;
1302 let v4 = self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4;
1303 if joint_index >= self.joint_count
1304 || !(v3 || v4 || self.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE)
1305 {
1306 return None;
1307 }
1308 let base = frame_offset.checked_add(joint_index as usize * self.pose_record_size)?;
1309 let base = self.record_offset(base);
1310 let bytes = self.poses.get(base..base + self.pose_record_size)?;
1311 if v4 {
1312 let (matrix, translation) = if bytes.as_ptr() as usize & 3 == 0 {
1313 unsafe { read_pose_v4_word_aligned_unchecked(bytes, 0) }
1316 } else {
1317 let matrix = unsafe { read_pose_matrix_q11_cross_unchecked(bytes, 0) };
1319 let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V4;
1320 let translation = Vec3I16::new(
1321 read_i16(bytes, off),
1322 read_i16(bytes, off + 2),
1323 read_i16(bytes, off + 4),
1324 );
1325 (matrix, translation)
1326 };
1327 return Some(GteJointPose {
1328 matrix,
1329 translation,
1330 translation_shift: self.translation_shift,
1331 });
1332 }
1333 if v3 {
1334 let (matrix, translation) = if bytes.as_ptr() as usize & 3 == 0 {
1338 unsafe { read_pose_v3_word_aligned_unchecked(bytes, 0) }
1340 } else {
1341 let matrix = unsafe { read_pose_matrix_q11_unchecked(bytes, 0) };
1343 let off = psxed_format::animation::POSE_ROTATION_BLOCK_SIZE_V3;
1344 let translation = Vec3I16::new(
1345 read_i16(bytes, off),
1346 read_i16(bytes, off + 2),
1347 read_i16(bytes, off + 4),
1348 );
1349 (matrix, translation)
1350 };
1351 return Some(GteJointPose {
1352 matrix,
1353 translation,
1354 translation_shift: self.translation_shift,
1355 });
1356 }
1357 Some(GteJointPose {
1358 matrix: read_pose_matrix(bytes),
1359 translation: Vec3I16::new(
1360 read_i16(bytes, 18),
1361 read_i16(bytes, 20),
1362 read_i16(bytes, 22),
1363 ),
1364 translation_shift: self.translation_shift,
1365 })
1366 }
1367
1368 pub fn pose_looped_q12(&self, frame_q12: u32, joint_index: u16) -> Option<JointPose> {
1377 self.looped_pose_sample_q12(frame_q12)?.pose(joint_index)
1378 }
1379
1380 pub fn looped_pose_sample_q12(&self, frame_q12: u32) -> Option<AnimationPoseSample<'a>> {
1387 if self.frame_count == 0 {
1388 return None;
1389 }
1390
1391 let cycle_frames = self.frame_count.saturating_sub(1).max(1);
1392 let base_frame = ((frame_q12 >> 12) % cycle_frames as u32) as u16;
1393 let next_frame = if cycle_frames <= 1 || base_frame + 1 >= cycle_frames {
1394 0
1395 } else {
1396 base_frame + 1
1397 };
1398 let alpha_q12 = (frame_q12 & 0x0fff) as u16;
1399 let track_pos = if self.tracks.is_some() {
1400 tracks::track_pos(
1401 self.poses,
1402 (u32::from(base_frame) << 8) | u32::from(alpha_q12 >> 4),
1403 )
1404 } else {
1405 tracks::TrackPos::ZERO
1406 };
1407 Some(AnimationPoseSample {
1408 animation: *self,
1409 base_frame,
1410 next_frame,
1411 base_frame_offset: base_frame as usize
1412 * self.joint_count as usize
1413 * self.pose_record_size,
1414 next_frame_offset: next_frame as usize
1415 * self.joint_count as usize
1416 * self.pose_record_size,
1417 alpha_q12,
1418 track_pos,
1419 })
1420 }
1421}
1422
1423#[derive(Copy, Clone, Debug)]
1425pub struct AnimationPoseSample<'a> {
1426 animation: Animation<'a>,
1427 base_frame: u16,
1428 next_frame: u16,
1429 base_frame_offset: usize,
1430 next_frame_offset: usize,
1431 alpha_q12: u16,
1432 track_pos: tracks::TrackPos,
1434}
1435
1436impl AnimationPoseSample<'_> {
1437 #[inline]
1439 pub fn pose(&self, joint_index: u16) -> Option<JointPose> {
1440 if joint_index >= self.animation.joint_count {
1441 return None;
1442 }
1443 if let Some(tracks) = &self.animation.tracks {
1444 return Some(unsafe {
1447 tracks::joint_pose(tracks, joint_index as usize, &self.track_pos)
1448 });
1449 }
1450 if self.alpha_q12 == 0 || self.base_frame == self.next_frame {
1451 return Some(unsafe {
1454 self.animation
1455 .pose_at_frame_offset_unchecked(self.base_frame_offset, joint_index)
1456 });
1457 }
1458
1459 if self.animation.pose_record_size == psxed_format::animation::POSE_RECORD_SIZE_V4 {
1471 let pool = self.animation.poses.as_ptr();
1472 if pool as usize & 3 == 0 {
1473 let joint_offset =
1474 joint_index as usize * psxed_format::animation::POSE_RECORD_SIZE_V4;
1475 return Some(unsafe {
1480 lerp_v4_pair_word_aligned(
1481 pool.add(
1482 self.animation
1483 .record_offset(self.base_frame_offset + joint_offset),
1484 ),
1485 pool.add(
1486 self.animation
1487 .record_offset(self.next_frame_offset + joint_offset),
1488 ),
1489 self.animation.translation_shift,
1490 self.alpha_q12,
1491 )
1492 });
1493 }
1494 }
1495
1496 let a = unsafe {
1499 self.animation
1500 .pose_at_frame_offset_unchecked(self.base_frame_offset, joint_index)
1501 };
1502 let b = unsafe {
1505 self.animation
1506 .pose_at_frame_offset_unchecked(self.next_frame_offset, joint_index)
1507 };
1508 Some(lerp_pose_q12(a, b, self.alpha_q12))
1509 }
1510
1511 #[inline]
1516 pub fn gte_pose(&self, joint_index: u16) -> Option<GteJointPose> {
1517 if self.alpha_q12 == 0 || self.base_frame == self.next_frame {
1518 return self
1519 .animation
1520 .packed_pose_at_frame_offset(self.base_frame_offset, joint_index);
1521 }
1522
1523 let a = self
1524 .animation
1525 .packed_pose_at_frame_offset(self.base_frame_offset, joint_index)?;
1526 let b = self
1527 .animation
1528 .packed_pose_at_frame_offset(self.next_frame_offset, joint_index)?;
1529 Some(lerp_gte_pose_q12(a, b, self.alpha_q12))
1530 }
1531}
1532
1533#[derive(Copy, Clone, Debug)]
1546pub struct ModelPoseBlend<'a> {
1547 pub sample: AnimationPoseSample<'a>,
1549 pub alpha_q12: u16,
1551}
1552
1553impl ModelPoseBlend<'_> {
1554 #[inline]
1559 pub fn blend_toward(&self, primary: JointPose, joint_index: u16) -> JointPose {
1560 if self.alpha_q12 >= 1 << 12 {
1561 return primary;
1562 }
1563 match self.sample.pose(joint_index) {
1564 Some(from) => lerp_pose_q12(from, primary, self.alpha_q12),
1565 None => primary,
1566 }
1567 }
1568}
1569
1570#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1572pub struct JointPose {
1573 pub matrix: [[i16; 3]; 3],
1575 pub translation: Vec3I32,
1577}
1578
1579#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1581pub struct GteJointPose {
1582 pub matrix: [[i16; 3]; 3],
1584 pub translation: Vec3I16,
1586 pub translation_shift: u8,
1588}
1589
1590#[derive(Copy, Clone, Debug)]
1592pub struct Audio<'a> {
1593 adpcm: &'a [u8],
1594 flags: u16,
1595 sample_rate_hz: u32,
1596 sample_count: u32,
1597 adpcm_block_count: u32,
1598 loop_start_block: u32,
1599}
1600
1601impl<'a> Audio<'a> {
1602 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
1604 use psxed_format::audio::{self, AudioHeader};
1605
1606 if bytes.len() < psxed_format::AssetHeader::SIZE {
1607 return Err(ParseError::Truncated);
1608 }
1609 let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
1610 if magic != audio::MAGIC {
1611 return Err(ParseError::WrongMagic);
1612 }
1613 let version = read_u16(bytes, 4);
1614 if version != audio::VERSION {
1615 return Err(ParseError::UnsupportedVersion(version));
1616 }
1617 let flags = read_u16(bytes, 6);
1618 let payload_len = read_u32(bytes, 8);
1619 let payload_start = psxed_format::AssetHeader::SIZE;
1620 let actual_payload = bytes.len().saturating_sub(payload_start);
1621 if payload_len as usize != actual_payload {
1622 return Err(ParseError::InvalidPayloadLen {
1623 declared: payload_len,
1624 actual: actual_payload,
1625 });
1626 }
1627 if actual_payload < AudioHeader::SIZE {
1628 return Err(ParseError::Truncated);
1629 }
1630
1631 let ah = &bytes[payload_start..payload_start + AudioHeader::SIZE];
1632 let codec = ah[0];
1633 let channel_count = ah[1];
1634 let sample_rate_hz = read_u32(ah, 4);
1635 let sample_count = read_u32(ah, 8);
1636 let adpcm_block_count = read_u32(ah, 12);
1637 let loop_start_block = read_u32(ah, 16);
1638 let decoded_capacity = adpcm_block_count
1639 .checked_mul(28)
1640 .ok_or(ParseError::TableOverflow)?;
1641 let min_samples_for_blocks = adpcm_block_count.saturating_sub(1) * 28 + 1;
1642 if codec != audio::CODEC_SPU_ADPCM
1643 || channel_count != 1
1644 || flags & audio::flags::MONO == 0
1645 || flags & audio::flags::ONE_SHOT == 0
1646 || sample_rate_hz == 0
1647 || sample_count == 0
1648 || adpcm_block_count == 0
1649 || sample_count > decoded_capacity
1650 || sample_count < min_samples_for_blocks
1651 || loop_start_block != AudioHeader::NO_LOOP
1652 {
1653 return Err(ParseError::InvalidAudioLayout);
1654 }
1655
1656 let adpcm_bytes = (adpcm_block_count as usize)
1657 .checked_mul(16)
1658 .ok_or(ParseError::TableOverflow)?;
1659 let adpcm_start = payload_start + AudioHeader::SIZE;
1660 let adpcm_end = adpcm_start
1661 .checked_add(adpcm_bytes)
1662 .ok_or(ParseError::TableOverflow)?;
1663 if adpcm_end != bytes.len() {
1664 return Err(ParseError::InvalidAudioLayout);
1665 }
1666
1667 Ok(Self {
1668 adpcm: &bytes[adpcm_start..adpcm_end],
1669 flags,
1670 sample_rate_hz,
1671 sample_count,
1672 adpcm_block_count,
1673 loop_start_block,
1674 })
1675 }
1676
1677 #[inline]
1679 pub fn sample_rate_hz(&self) -> u32 {
1680 self.sample_rate_hz
1681 }
1682
1683 #[inline]
1685 pub fn sample_count(&self) -> u32 {
1686 self.sample_count
1687 }
1688
1689 #[inline]
1691 pub fn adpcm_block_count(&self) -> u32 {
1692 self.adpcm_block_count
1693 }
1694
1695 #[inline]
1697 pub fn loop_start_block(&self) -> Option<u32> {
1698 if self.loop_start_block == psxed_format::audio::AudioHeader::NO_LOOP {
1699 None
1700 } else {
1701 Some(self.loop_start_block)
1702 }
1703 }
1704
1705 #[inline]
1707 pub fn adpcm_bytes(&self) -> &'a [u8] {
1708 self.adpcm
1709 }
1710
1711 #[inline]
1713 pub fn is_one_shot(&self) -> bool {
1714 self.flags & psxed_format::audio::flags::ONE_SHOT != 0
1715 }
1716}
1717
1718#[inline]
1719fn lerp_pose_q12(a: JointPose, b: JointPose, alpha_q12: u16) -> JointPose {
1720 let mut matrix = [[0i16; 3]; 3];
1721 let mut col = 0;
1722 while col < 3 {
1723 let mut row = 0;
1724 while row < 3 {
1725 matrix[col][row] = lerp_i16_q12(a.matrix[col][row], b.matrix[col][row], alpha_q12);
1726 row += 1;
1727 }
1728 col += 1;
1729 }
1730
1731 JointPose {
1732 matrix,
1733 translation: Vec3I32::new(
1734 lerp_i32_q12(a.translation.x, b.translation.x, alpha_q12),
1735 lerp_i32_q12(a.translation.y, b.translation.y, alpha_q12),
1736 lerp_i32_q12(a.translation.z, b.translation.z, alpha_q12),
1737 ),
1738 }
1739}
1740
1741#[inline]
1742fn lerp_gte_pose_q12(a: GteJointPose, b: GteJointPose, alpha_q12: u16) -> GteJointPose {
1743 let mut matrix = [[0i16; 3]; 3];
1744 let mut col = 0;
1745 while col < 3 {
1746 let mut row = 0;
1747 while row < 3 {
1748 matrix[col][row] = lerp_i16_q12(a.matrix[col][row], b.matrix[col][row], alpha_q12);
1749 row += 1;
1750 }
1751 col += 1;
1752 }
1753
1754 GteJointPose {
1755 matrix,
1756 translation: Vec3I16::new(
1757 lerp_i16_q12(a.translation.x, b.translation.x, alpha_q12),
1758 lerp_i16_q12(a.translation.y, b.translation.y, alpha_q12),
1759 lerp_i16_q12(a.translation.z, b.translation.z, alpha_q12),
1760 ),
1761 translation_shift: a.translation_shift,
1762 }
1763}
1764
1765#[inline(always)]
1773fn decode_q11_element(raw: u16) -> i16 {
1774 decode_q11_element_wide(raw) as i16
1775}
1776
1777#[inline(always)]
1784fn decode_q11_element_wide(raw: u16) -> i32 {
1785 #[cfg(target_arch = "mips")]
1786 {
1787 let decoded: u32;
1788 unsafe {
1795 core::arch::asm!(
1796 ".set push",
1797 ".set noat",
1798 "xori {scratch}, {decoded}, 0x07ff",
1799 "sltiu {scratch}, {scratch}, 1",
1800 "sll {decoded}, {decoded}, 20",
1801 "sra {decoded}, {decoded}, 19",
1802 "sll {scratch}, {scratch}, 1",
1803 "addu {decoded}, {decoded}, {scratch}",
1804 ".set pop",
1805 decoded = inlateout(reg) raw as u32 => decoded,
1806 scratch = lateout(reg) _,
1807 options(nomem, nostack, preserves_flags),
1808 );
1809 }
1810 decoded as i32
1811 }
1812
1813 #[cfg(not(target_arch = "mips"))]
1814 {
1815 let signed = ((raw << 4) as i16) >> 4;
1816 signed
1817 .wrapping_shl(1)
1818 .wrapping_add((((raw & 0x0fff) == 0x07ff) as i16) << 1) as i32
1819 }
1820}
1821
1822#[inline]
1831unsafe fn read_pose_matrix_q11_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
1832 let mut flat = [0i16; 9];
1833 let mut pair = 0;
1834 while pair < 4 {
1835 let o = offset + pair * 3;
1836 let packed = unsafe {
1840 (bytes.as_ptr().add(o).read() as u32)
1841 | ((bytes.as_ptr().add(o + 1).read() as u32) << 8)
1842 | ((bytes.as_ptr().add(o + 2).read() as u32) << 16)
1843 };
1844 flat[pair * 2] = decode_q11_element((packed & 0x0fff) as u16);
1845 flat[pair * 2 + 1] = decode_q11_element(((packed >> 12) & 0x0fff) as u16);
1846 pair += 1;
1847 }
1848 let last = unsafe {
1851 (bytes.as_ptr().add(offset + 12).read() as u16)
1852 | ((bytes.as_ptr().add(offset + 13).read() as u16) << 8)
1853 };
1854 flat[8] = decode_q11_element(last & 0x0fff);
1855 [
1856 [flat[0], flat[1], flat[2]],
1857 [flat[3], flat[4], flat[5]],
1858 [flat[6], flat[7], flat[8]],
1859 ]
1860}
1861
1862const V4_CROSS_LIMIT: i32 = 2 * 4096 * 4096;
1870
1871#[inline(always)]
1877fn cross_round_q12(value: i32) -> i32 {
1878 debug_assert!((-V4_CROSS_LIMIT..=V4_CROSS_LIMIT).contains(&value));
1879 if value >= 0 {
1880 (value + (1 << 11)) >> 12
1881 } else {
1882 -((-value + (1 << 11)) >> 12)
1883 }
1884}
1885
1886#[inline(always)]
1904fn v4_third_basis_q12(first: [i32; 3], second: [i32; 3], correction_byte: u8) -> [i32; 3] {
1905 let ([f0, f1, f2], [s0, s1, s2]) = (first, second);
1906 let x = cross_round_q12(f1 * s2 - f2 * s1);
1907 let y = cross_round_q12(f2 * s0 - f0 * s2);
1908 let z = cross_round_q12(f0 * s1 - f1 * s0);
1909 let correction = ((((correction_byte >> 2) << 2) as i8) >> 2) as i32;
1910 let (x, y, z) = match correction_byte & 0x03 {
1913 0 => (x + correction, y, z),
1914 1 => (x, y + correction, z),
1915 2 => (x, y, z + correction),
1916 _ => (x, y, z),
1917 };
1918 [
1919 x.clamp(-4096, 4096),
1920 y.clamp(-4096, 4096),
1921 z.clamp(-4096, 4096),
1922 ]
1923}
1924
1925#[inline]
1931unsafe fn read_pose_matrix_q11_cross_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
1932 let mut flat = [0i32; 6];
1933 let mut pair = 0usize;
1934 while pair < 3 {
1935 let o = offset + pair * 3;
1936 let packed = unsafe {
1939 (bytes.as_ptr().add(o).read() as u32)
1940 | ((bytes.as_ptr().add(o + 1).read() as u32) << 8)
1941 | ((bytes.as_ptr().add(o + 2).read() as u32) << 16)
1942 };
1943 flat[pair * 2] = decode_q11_element_wide((packed & 0x0fff) as u16);
1944 flat[pair * 2 + 1] = decode_q11_element_wide(((packed >> 12) & 0x0fff) as u16);
1945 pair += 1;
1946 }
1947 let first = [flat[0], flat[1], flat[2]];
1948 let second = [flat[3], flat[4], flat[5]];
1949 let correction = unsafe { bytes.as_ptr().add(offset + 9).read() };
1951 let third = v4_third_basis_q12(first, second, correction);
1952 [
1953 narrow_q12_row(first),
1954 narrow_q12_row(second),
1955 narrow_q12_row(third),
1956 ]
1957}
1958
1959#[inline]
1964unsafe fn read_pose_v4_word_aligned_unchecked(
1965 bytes: &[u8],
1966 offset: usize,
1967) -> ([[i16; 3]; 3], Vec3I16) {
1968 unsafe { read_pose_v4_word_aligned_ptr(bytes.as_ptr().add(offset)) }
1971}
1972
1973#[inline(always)]
1980unsafe fn read_pose_v4_word_aligned_ptr(record: *const u8) -> ([[i16; 3]; 3], Vec3I16) {
1981 let (rows, translation) = unsafe { read_pose_v4_rows_word_aligned(record) };
1983 (
1984 [
1985 narrow_q12_row(rows[0]),
1986 narrow_q12_row(rows[1]),
1987 narrow_q12_row(rows[2]),
1988 ],
1989 translation,
1990 )
1991}
1992
1993#[inline(always)]
1996fn narrow_q12_row(row: [i32; 3]) -> [i16; 3] {
1997 [row[0] as i16, row[1] as i16, row[2] as i16]
1998}
1999
2000#[inline(always)]
2012unsafe fn read_pose_v4_rows_word_aligned(record: *const u8) -> ([[i32; 3]; 3], Vec3I16) {
2013 debug_assert_eq!(record as usize & 3, 0);
2014 let words = record.cast::<u32>();
2015 let w0 = u32::from_le(unsafe { words.add(0).read() });
2019 let w1 = u32::from_le(unsafe { words.add(1).read() });
2021 let w2 = u32::from_le(unsafe { words.add(2).read() });
2023 let w3 = u32::from_le(unsafe { words.add(3).read() });
2025
2026 let p0 = w0 & 0x00ff_ffff;
2027 let p1 = (w0 >> 24) | ((w1 & 0x0000_ffff) << 8);
2028 let p2 = (w1 >> 16) | ((w2 & 0x0000_00ff) << 16);
2029 let first = [
2030 decode_q11_element_wide((p0 & 0x0fff) as u16),
2031 decode_q11_element_wide(((p0 >> 12) & 0x0fff) as u16),
2032 decode_q11_element_wide((p1 & 0x0fff) as u16),
2033 ];
2034 let second = [
2035 decode_q11_element_wide(((p1 >> 12) & 0x0fff) as u16),
2036 decode_q11_element_wide((p2 & 0x0fff) as u16),
2037 decode_q11_element_wide(((p2 >> 12) & 0x0fff) as u16),
2038 ];
2039 let third = v4_third_basis_q12(first, second, ((w2 >> 8) & 0xff) as u8);
2040 let translation = Vec3I16::new(
2041 (w2 >> 16) as u16 as i16,
2042 w3 as u16 as i16,
2043 (w3 >> 16) as u16 as i16,
2044 );
2045 ([first, second, third], translation)
2046}
2047
2048#[inline]
2060unsafe fn lerp_v4_pair_word_aligned(
2061 a_record: *const u8,
2062 b_record: *const u8,
2063 translation_shift: u8,
2064 alpha_q12: u16,
2065) -> JointPose {
2066 let (a_rows, a_packed) = unsafe { read_pose_v4_rows_word_aligned(a_record) };
2069 let (b_rows, b_packed) = unsafe { read_pose_v4_rows_word_aligned(b_record) };
2071
2072 let mut matrix = [[0i16; 3]; 3];
2073 let mut col = 0;
2074 while col < 3 {
2075 let mut row = 0;
2076 while row < 3 {
2077 matrix[col][row] = lerp_q12_wide_to_i16(a_rows[col][row], b_rows[col][row], alpha_q12);
2078 row += 1;
2079 }
2080 col += 1;
2081 }
2082
2083 JointPose {
2084 matrix,
2085 translation: Vec3I32::new(
2086 lerp_packed_translation_q12(a_packed.x, b_packed.x, translation_shift, alpha_q12),
2087 lerp_packed_translation_q12(a_packed.y, b_packed.y, translation_shift, alpha_q12),
2088 lerp_packed_translation_q12(a_packed.z, b_packed.z, translation_shift, alpha_q12),
2089 ),
2090 }
2091}
2092
2093#[inline(always)]
2108fn lerp_packed_translation_q12(a: i16, b: i16, shift: u8, alpha_q12: u16) -> i32 {
2109 debug_assert!(shift <= 15);
2110 debug_assert!(alpha_q12 < 4096);
2111 let base = (a as i32) << shift;
2112 let delta = ((b as i32) << shift) - base;
2113 let alpha = alpha_q12 as i32;
2116 let whole = delta >> 12;
2117 let frac = delta - (whole << 12);
2118 base + whole * alpha + ((frac * alpha) >> 12)
2119}
2120
2121#[inline]
2133unsafe fn read_pose_v3_word_aligned_unchecked(
2134 bytes: &[u8],
2135 offset: usize,
2136) -> ([[i16; 3]; 3], Vec3I16) {
2137 let record = unsafe { bytes.as_ptr().add(offset) };
2140 debug_assert_eq!(record as usize & 3, 0);
2141 let words = record.cast::<u32>();
2142 let w0 = u32::from_le(unsafe { words.add(0).read() });
2146 let w1 = u32::from_le(unsafe { words.add(1).read() });
2148 let w2 = u32::from_le(unsafe { words.add(2).read() });
2150 let w3 = u32::from_le(unsafe { words.add(3).read() });
2152 let w4 = u32::from_le(unsafe { words.add(4).read() });
2154
2155 let p0 = w0 & 0x00ff_ffff;
2156 let p1 = (w0 >> 24) | ((w1 & 0x0000_ffff) << 8);
2157 let p2 = (w1 >> 16) | ((w2 & 0x0000_00ff) << 16);
2158 let p3 = (w2 >> 8) & 0x00ff_ffff;
2159 let matrix = [
2160 [
2161 decode_q11_element((p0 & 0x0fff) as u16),
2162 decode_q11_element(((p0 >> 12) & 0x0fff) as u16),
2163 decode_q11_element((p1 & 0x0fff) as u16),
2164 ],
2165 [
2166 decode_q11_element(((p1 >> 12) & 0x0fff) as u16),
2167 decode_q11_element((p2 & 0x0fff) as u16),
2168 decode_q11_element(((p2 >> 12) & 0x0fff) as u16),
2169 ],
2170 [
2171 decode_q11_element((p3 & 0x0fff) as u16),
2172 decode_q11_element(((p3 >> 12) & 0x0fff) as u16),
2173 decode_q11_element((w3 & 0x0fff) as u16),
2174 ],
2175 ];
2176 let translation = Vec3I16::new(
2177 (w3 >> 16) as u16 as i16,
2178 w4 as u16 as i16,
2179 (w4 >> 16) as u16 as i16,
2180 );
2181 (matrix, translation)
2182}
2183
2184fn read_pose_matrix(bytes: &[u8]) -> [[i16; 3]; 3] {
2185 [
2186 [read_i16(bytes, 0), read_i16(bytes, 2), read_i16(bytes, 4)],
2187 [read_i16(bytes, 6), read_i16(bytes, 8), read_i16(bytes, 10)],
2188 [
2189 read_i16(bytes, 12),
2190 read_i16(bytes, 14),
2191 read_i16(bytes, 16),
2192 ],
2193 ]
2194}
2195
2196#[inline]
2201unsafe fn read_pose_matrix_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
2202 [
2203 [
2204 unsafe { read_i16_unchecked(bytes, offset) },
2206 unsafe { read_i16_unchecked(bytes, offset + 2) },
2208 unsafe { read_i16_unchecked(bytes, offset + 4) },
2210 ],
2211 [
2212 unsafe { read_i16_unchecked(bytes, offset + 6) },
2214 unsafe { read_i16_unchecked(bytes, offset + 8) },
2216 unsafe { read_i16_unchecked(bytes, offset + 10) },
2218 ],
2219 [
2220 unsafe { read_i16_unchecked(bytes, offset + 12) },
2222 unsafe { read_i16_unchecked(bytes, offset + 14) },
2224 unsafe { read_i16_unchecked(bytes, offset + 16) },
2226 ],
2227 ]
2228}
2229
2230#[inline]
2236unsafe fn read_pose_matrix_aligned_unchecked(bytes: &[u8], offset: usize) -> [[i16; 3]; 3] {
2237 [
2238 [
2239 unsafe { read_i16_aligned_unchecked(bytes, offset) },
2241 unsafe { read_i16_aligned_unchecked(bytes, offset + 2) },
2243 unsafe { read_i16_aligned_unchecked(bytes, offset + 4) },
2245 ],
2246 [
2247 unsafe { read_i16_aligned_unchecked(bytes, offset + 6) },
2249 unsafe { read_i16_aligned_unchecked(bytes, offset + 8) },
2251 unsafe { read_i16_aligned_unchecked(bytes, offset + 10) },
2253 ],
2254 [
2255 unsafe { read_i16_aligned_unchecked(bytes, offset + 12) },
2257 unsafe { read_i16_aligned_unchecked(bytes, offset + 14) },
2259 unsafe { read_i16_aligned_unchecked(bytes, offset + 16) },
2261 ],
2262 ]
2263}
2264
2265#[inline]
2266fn decode_packed_translation(value: i16, shift: u8) -> i32 {
2267 debug_assert!(shift <= 15);
2268 (value as i32) * (1i32 << shift)
2269}
2270
2271#[inline(always)]
2277fn lerp_q12_wide_to_i16(a: i32, b: i32, alpha_q12: u16) -> i16 {
2278 debug_assert!(alpha_q12 < 4096);
2279 (a + (((b - a) * alpha_q12 as i32) >> 12)) as i16
2280}
2281
2282#[inline]
2283fn lerp_i16_q12(a: i16, b: i16, alpha_q12: u16) -> i16 {
2284 debug_assert!(alpha_q12 < 4096);
2285 let value = a as i32 + (((b as i32 - a as i32) * alpha_q12 as i32) >> 12);
2286 value as i16
2287}
2288
2289#[inline]
2290fn lerp_i32_q12(a: i32, b: i32, alpha_q12: u16) -> i32 {
2291 let delta = b.saturating_sub(a);
2292 a.saturating_add(scale_i32_q12(delta, alpha_q12 as i32))
2293}
2294
2295#[inline]
2296fn scale_i32_q12(value: i32, scale_q12: i32) -> i32 {
2297 let whole = value >> 12;
2298 let frac = value - (whole << 12);
2299 whole.saturating_mul(scale_q12) + ((frac * scale_q12) >> 12)
2300}
2301
2302#[derive(Copy, Clone, Debug)]
2311pub struct Texture<'a> {
2312 pixel_data: &'a [u8],
2315 clut_data: &'a [u8],
2317 width_px: u16,
2318 height_px: u16,
2319 depth: psxed_format::texture::Depth,
2320 clut_entries: u16,
2321 flags: u16,
2322}
2323
2324impl<'a> Texture<'a> {
2325 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
2329 use psxed_format::texture::{Depth, TextureHeader, MAGIC, VERSION};
2330
2331 if bytes.len() < psxed_format::AssetHeader::SIZE {
2333 return Err(ParseError::Truncated);
2334 }
2335 let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
2336 if magic != MAGIC {
2337 return Err(ParseError::WrongMagic);
2338 }
2339 let version = u16::from_le_bytes([bytes[4], bytes[5]]);
2340 if version != VERSION {
2341 return Err(ParseError::UnsupportedVersion(version));
2342 }
2343 let flags = u16::from_le_bytes([bytes[6], bytes[7]]);
2344 let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
2345 let payload_start = psxed_format::AssetHeader::SIZE;
2346 let actual_payload = bytes.len().saturating_sub(payload_start);
2347 if (payload_len as usize) != actual_payload {
2348 return Err(ParseError::InvalidPayloadLen {
2349 declared: payload_len,
2350 actual: actual_payload,
2351 });
2352 }
2353
2354 if actual_payload < TextureHeader::SIZE {
2356 return Err(ParseError::Truncated);
2357 }
2358 let th = &bytes[payload_start..];
2359 let depth = Depth::from_byte(th[0]).ok_or(ParseError::TableOverflow)?;
2360 let width_px = u16::from_le_bytes([th[2], th[3]]);
2362 let height_px = u16::from_le_bytes([th[4], th[5]]);
2363 let clut_entries = u16::from_le_bytes([th[6], th[7]]);
2364 let pixel_bytes = u32::from_le_bytes([th[8], th[9], th[10], th[11]]) as usize;
2365 let clut_bytes = u32::from_le_bytes([th[12], th[13], th[14], th[15]]) as usize;
2366
2367 let mut off = payload_start + TextureHeader::SIZE;
2371 let pixel_data = take_table(bytes, &mut off, pixel_bytes)?;
2372 let clut_data = take_table(bytes, &mut off, clut_bytes)?;
2373
2374 Ok(Self {
2375 pixel_data,
2376 clut_data,
2377 width_px,
2378 height_px,
2379 depth,
2380 clut_entries,
2381 flags,
2382 })
2383 }
2384
2385 #[inline]
2387 pub fn width(&self) -> u16 {
2388 self.width_px
2389 }
2390
2391 #[inline]
2393 pub fn height(&self) -> u16 {
2394 self.height_px
2395 }
2396
2397 #[inline]
2399 pub fn depth(&self) -> psxed_format::texture::Depth {
2400 self.depth
2401 }
2402
2403 #[inline]
2407 pub fn clut_entries(&self) -> u16 {
2408 self.clut_entries
2409 }
2410
2411 #[inline]
2413 pub fn flags(&self) -> u16 {
2414 self.flags
2415 }
2416
2417 #[inline]
2419 pub fn is_index_zero_transparent(&self) -> bool {
2420 self.flags & psxed_format::texture::flags::INDEX_ZERO_TRANSPARENT != 0
2421 }
2422
2423 #[inline]
2427 pub fn pixel_bytes(&self) -> &'a [u8] {
2428 self.pixel_data
2429 }
2430
2431 #[inline]
2433 pub fn clut_bytes(&self) -> &'a [u8] {
2434 self.clut_data
2435 }
2436
2437 #[inline]
2442 pub fn halfwords_per_row(&self) -> u16 {
2443 psxed_format::texture::TextureHeader::halfwords_per_row(self.depth, self.width_px)
2444 }
2445}
2446
2447#[derive(Copy, Clone, Debug)]
2453pub struct World<'a> {
2454 sectors: &'a [u8],
2455 walls: &'a [u8],
2456 horizontal_overrides: &'a [u8],
2457 surface_lights: &'a [u8],
2458 sector_record_size: usize,
2459 wall_record_size: usize,
2460 horizontal_override_record_size: usize,
2461 width: u16,
2462 depth: u16,
2463 sector_size: i32,
2464 material_count: u16,
2465 wall_count: u16,
2466 horizontal_override_count: u16,
2467 surface_light_count: u16,
2468 ambient_color: [u8; 3],
2469 flags: u8,
2470 static_vertex_lighting: bool,
2471}
2472
2473#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2475pub struct WorldQuadUvs {
2476 corners: [(u8, u8); 4],
2477}
2478
2479impl WorldQuadUvs {
2480 pub const fn new(corners: [(u8, u8); 4]) -> Self {
2482 Self { corners }
2483 }
2484
2485 pub const fn corners(self) -> [(u8, u8); 4] {
2487 self.corners
2488 }
2489}
2490
2491#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2493pub struct WorldSurfaceLight {
2494 vertex_rgb: [[u8; 3]; 4],
2495}
2496
2497impl WorldSurfaceLight {
2498 pub const fn white() -> Self {
2500 Self {
2501 vertex_rgb: [[255, 255, 255]; 4],
2502 }
2503 }
2504
2505 pub const fn new(vertex_rgb: [[u8; 3]; 4]) -> Self {
2507 Self { vertex_rgb }
2508 }
2509
2510 pub const fn vertex_rgb(self) -> [[u8; 3]; 4] {
2512 self.vertex_rgb
2513 }
2514}
2515
2516const WORLD_V1_SECTOR_RECORD_SIZE: usize = 44;
2517const WORLD_V1_WALL_RECORD_SIZE: usize = 24;
2518const WORLD_V2_SECTOR_RECORD_SIZE: usize = 60;
2519const WORLD_V2_WALL_RECORD_SIZE: usize = 32;
2520const WORLD_V3_HEADER_SIZE: usize = 20;
2521const WORLD_V3_SECTOR_RECORD_SIZE: usize = 60;
2522const WORLD_V3_WALL_RECORD_SIZE: usize = 32;
2523const WORLD_V4_HORIZONTAL_OVERRIDE_RECORD_SIZE: usize = 24;
2524
2525impl<'a> World<'a> {
2526 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
2528 use psxed_format::world::{
2529 WorldHeader, MAGIC, VERSION, VERSION_V1, VERSION_V2, VERSION_V3, VERSION_V4,
2530 };
2531
2532 if bytes.len() < psxed_format::AssetHeader::SIZE {
2533 return Err(ParseError::Truncated);
2534 }
2535 let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
2536 if magic != MAGIC {
2537 return Err(ParseError::WrongMagic);
2538 }
2539 let version = u16::from_le_bytes([bytes[4], bytes[5]]);
2540 if version != VERSION
2541 && version != VERSION_V3
2542 && version != VERSION_V4
2543 && version != VERSION_V2
2544 && version != VERSION_V1
2545 {
2546 return Err(ParseError::UnsupportedVersion(version));
2547 }
2548 let (world_header_size, sector_record_size, wall_record_size) = match version {
2549 VERSION_V1 => (
2550 WORLD_V3_HEADER_SIZE,
2551 WORLD_V1_SECTOR_RECORD_SIZE,
2552 WORLD_V1_WALL_RECORD_SIZE,
2553 ),
2554 VERSION_V2 => (
2555 WORLD_V3_HEADER_SIZE,
2556 WORLD_V2_SECTOR_RECORD_SIZE,
2557 WORLD_V2_WALL_RECORD_SIZE,
2558 ),
2559 VERSION_V3 => (
2560 WORLD_V3_HEADER_SIZE,
2561 WORLD_V3_SECTOR_RECORD_SIZE,
2562 WORLD_V3_WALL_RECORD_SIZE,
2563 ),
2564 VERSION_V4 => (
2565 WorldHeader::SIZE,
2566 psxed_format::world::SectorRecord::SIZE,
2567 psxed_format::world::WallRecord::SIZE,
2568 ),
2569 _ => (
2570 WorldHeader::SIZE,
2571 psxed_format::world::SectorRecord::SIZE,
2572 psxed_format::world::WallRecord::SIZE,
2573 ),
2574 };
2575 let payload_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
2576 let payload_start = psxed_format::AssetHeader::SIZE;
2577 let actual_payload = bytes.len().saturating_sub(payload_start);
2578 if payload_len as usize != actual_payload {
2579 return Err(ParseError::InvalidPayloadLen {
2580 declared: payload_len,
2581 actual: actual_payload,
2582 });
2583 }
2584 if actual_payload < world_header_size {
2585 return Err(ParseError::Truncated);
2586 }
2587
2588 let wh = &bytes[payload_start..payload_start + world_header_size];
2589 let width = read_u16(wh, 0);
2590 let depth = read_u16(wh, 2);
2591 let sector_size = read_i32(wh, 4);
2592 let sector_count = read_u16(wh, 8);
2593 let material_count = read_u16(wh, 10);
2594 let wall_count = read_u16(wh, 12);
2595 let ambient_color = [wh[14], wh[15], wh[16]];
2596 let flags = wh[17];
2597 let surface_light_count =
2598 if version == VERSION || version == VERSION_V4 || version == VERSION_V3 {
2599 read_u16(wh, 18)
2600 } else {
2601 0
2602 };
2603 let horizontal_override_count = if version == VERSION || version == VERSION_V4 {
2604 read_u16(wh, 20)
2605 } else {
2606 0
2607 };
2608 let static_vertex_lighting =
2609 (version == VERSION || version == VERSION_V4 || version == VERSION_V3)
2610 && flags & psxed_format::world::world_flags::STATIC_VERTEX_LIGHTING != 0;
2611
2612 let expected_sectors = (width as usize)
2613 .checked_mul(depth as usize)
2614 .ok_or(ParseError::InvalidWorldLayout)?;
2615 if sector_count as usize != expected_sectors {
2616 return Err(ParseError::InvalidWorldLayout);
2617 }
2618 if static_vertex_lighting {
2619 let expected_surface_lights = sector_count
2620 .checked_mul(2)
2621 .and_then(|count| count.checked_add(wall_count))
2622 .ok_or(ParseError::InvalidWorldLayout)?;
2623 if surface_light_count != expected_surface_lights {
2624 return Err(ParseError::InvalidWorldLayout);
2625 }
2626 } else if surface_light_count != 0 {
2627 return Err(ParseError::InvalidWorldLayout);
2628 }
2629
2630 let mut off = payload_start + world_header_size;
2631 let sector_bytes = (sector_count as usize)
2632 .checked_mul(sector_record_size)
2633 .ok_or(ParseError::TableOverflow)?;
2634 if off + sector_bytes > bytes.len() {
2635 return Err(ParseError::TableOverflow);
2636 }
2637 let sectors = &bytes[off..off + sector_bytes];
2638 off += sector_bytes;
2639
2640 let wall_bytes = (wall_count as usize)
2641 .checked_mul(wall_record_size)
2642 .ok_or(ParseError::TableOverflow)?;
2643 if off + wall_bytes > bytes.len() {
2644 return Err(ParseError::TableOverflow);
2645 }
2646 let walls = &bytes[off..off + wall_bytes];
2647 off += wall_bytes;
2648 let horizontal_override_record_size = if version == VERSION_V4 {
2649 WORLD_V4_HORIZONTAL_OVERRIDE_RECORD_SIZE
2650 } else {
2651 psxed_format::world::HorizontalOverrideRecord::SIZE
2652 };
2653 let horizontal_override_bytes = (horizontal_override_count as usize)
2654 .checked_mul(horizontal_override_record_size)
2655 .ok_or(ParseError::TableOverflow)?;
2656 if off + horizontal_override_bytes > bytes.len() {
2657 return Err(ParseError::TableOverflow);
2658 }
2659 let horizontal_overrides = &bytes[off..off + horizontal_override_bytes];
2660 off += horizontal_override_bytes;
2661 let surface_light_bytes = (surface_light_count as usize)
2662 .checked_mul(psxed_format::world::SurfaceLightRecord::SIZE)
2663 .ok_or(ParseError::TableOverflow)?;
2664 if off + surface_light_bytes > bytes.len() {
2665 return Err(ParseError::TableOverflow);
2666 }
2667 let surface_lights = &bytes[off..off + surface_light_bytes];
2668 off += surface_light_bytes;
2669 if off != bytes.len() {
2670 return Err(ParseError::InvalidWorldLayout);
2671 }
2672
2673 validate_sector_wall_ranges(sectors, sector_record_size, wall_count)?;
2674 validate_horizontal_overrides(
2675 horizontal_overrides,
2676 horizontal_override_count,
2677 sector_count,
2678 horizontal_override_record_size,
2679 )?;
2680
2681 Ok(Self {
2682 sectors,
2683 walls,
2684 horizontal_overrides,
2685 surface_lights,
2686 sector_record_size,
2687 wall_record_size,
2688 horizontal_override_record_size,
2689 width,
2690 depth,
2691 sector_size,
2692 material_count,
2693 wall_count,
2694 horizontal_override_count,
2695 surface_light_count,
2696 ambient_color,
2697 flags,
2698 static_vertex_lighting,
2699 })
2700 }
2701
2702 #[inline]
2704 pub fn width(&self) -> u16 {
2705 self.width
2706 }
2707
2708 #[inline]
2710 pub fn depth(&self) -> u16 {
2711 self.depth
2712 }
2713
2714 #[inline]
2716 pub fn sector_size(&self) -> i32 {
2717 self.sector_size
2718 }
2719
2720 #[inline]
2722 pub fn material_count(&self) -> u16 {
2723 self.material_count
2724 }
2725
2726 #[inline]
2728 pub fn wall_count(&self) -> u16 {
2729 self.wall_count
2730 }
2731
2732 #[inline]
2734 pub fn horizontal_override_count(&self) -> u16 {
2735 self.horizontal_override_count
2736 }
2737
2738 #[inline]
2740 pub fn surface_light_count(&self) -> u16 {
2741 self.surface_light_count
2742 }
2743
2744 #[inline]
2746 pub fn ambient_color(&self) -> [u8; 3] {
2747 self.ambient_color
2748 }
2749
2750 #[inline]
2752 pub fn is_fog_enabled(&self) -> bool {
2753 self.flags & psxed_format::world::world_flags::FOG_ENABLED != 0
2754 }
2755
2756 #[inline]
2758 pub fn has_static_vertex_lighting(&self) -> bool {
2759 self.static_vertex_lighting
2760 }
2761
2762 pub fn sector(&self, x: u16, z: u16) -> Option<WorldSector> {
2764 if x >= self.width || z >= self.depth {
2765 return None;
2766 }
2767 let index = x as usize * self.depth as usize + z as usize;
2768 let sector = self.sector_record(index)?;
2769 if sector.has_geometry() {
2770 Some(sector)
2771 } else {
2772 None
2773 }
2774 }
2775
2776 pub fn sector_without_horizontal_overrides(&self, x: u16, z: u16) -> Option<WorldSector> {
2780 if x >= self.width || z >= self.depth {
2781 return None;
2782 }
2783 let index = x as usize * self.depth as usize + z as usize;
2784 let sector = self.sector_record_without_horizontal_overrides(index)?;
2785 if sector.has_geometry() {
2786 Some(sector)
2787 } else {
2788 None
2789 }
2790 }
2791
2792 pub fn sector_collision_probe(&self, x: u16, z: u16) -> Option<WorldSectorCollisionProbe> {
2796 if x >= self.width || z >= self.depth {
2797 return None;
2798 }
2799 let index = x as usize * self.depth as usize + z as usize;
2800 let sector = self.sector_collision_probe_record(index)?;
2801 if sector.has_geometry() {
2802 Some(sector)
2803 } else {
2804 None
2805 }
2806 }
2807
2808 pub fn sector_floor_collision(
2813 &self,
2814 x: u16,
2815 z: u16,
2816 local_x: i32,
2817 local_z: i32,
2818 sector_size: i32,
2819 ) -> Option<WorldSectorFloorCollision> {
2820 if x >= self.width || z >= self.depth || sector_size <= 0 {
2821 return None;
2822 }
2823 let index = x as usize * self.depth as usize + z as usize;
2824 let size = self.sector_record_size;
2825 let base = index.checked_mul(size)?;
2826 let end = base.checked_add(size)?;
2827 let bytes = self.sectors.get(base..end)?;
2828 let flags = bytes[0];
2829 if flags & psxed_format::world::sector_flags::HAS_FLOOR == 0 {
2830 return None;
2831 }
2832
2833 let split = bytes[1];
2834 let triangle =
2835 world_topology::horizontal_triangle_at_local(split, local_x, local_z, sector_size);
2836 let default_flags = default_horizontal_flags(
2837 true,
2838 flags & psxed_format::world::sector_flags::FLOOR_WALKABLE != 0,
2839 );
2840 let sector_index = u16::try_from(index).ok()?;
2841 let (triangle_flags, override_heights) = self
2842 .horizontal_collision_override(
2843 sector_index,
2844 psxed_format::world::horizontal_surface::FLOOR,
2845 triangle,
2846 )
2847 .unwrap_or((default_flags, None));
2848 if !horizontal_triangle_present(triangle_flags, triangle) {
2849 return None;
2850 }
2851
2852 let floor_heights = read_i32x4(bytes, 12);
2853 let triangle_heights = override_heights
2854 .unwrap_or_else(|| horizontal_triangle_heights(floor_heights, split, triangle));
2855 Some(WorldSectorFloorCollision {
2856 split,
2857 triangle: triangle as u8,
2858 walkable: horizontal_triangle_walkable(triangle_flags, triangle),
2859 floor_heights,
2860 triangle_heights,
2861 })
2862 }
2863
2864 pub fn sector_record(&self, index: usize) -> Option<WorldSector> {
2866 let size = self.sector_record_size;
2867 let base = index.checked_mul(size)?;
2868 let end = base.checked_add(size)?;
2869 let bytes = self.sectors.get(base..end)?;
2870 let sector_index = if index <= u16::MAX as usize {
2871 index as u16
2872 } else {
2873 return None;
2874 };
2875 let floor_override =
2876 self.horizontal_override(sector_index, psxed_format::world::horizontal_surface::FLOOR);
2877 let ceiling_override = self.horizontal_override(
2878 sector_index,
2879 psxed_format::world::horizontal_surface::CEILING,
2880 );
2881 Some(WorldSector::decode(bytes, floor_override, ceiling_override))
2882 }
2883
2884 fn sector_record_without_horizontal_overrides(&self, index: usize) -> Option<WorldSector> {
2885 let size = self.sector_record_size;
2886 let base = index.checked_mul(size)?;
2887 let end = base.checked_add(size)?;
2888 let bytes = self.sectors.get(base..end)?;
2889 if index > u16::MAX as usize {
2890 return None;
2891 }
2892 Some(WorldSector::decode(bytes, None, None))
2893 }
2894
2895 fn sector_collision_probe_record(&self, index: usize) -> Option<WorldSectorCollisionProbe> {
2896 let size = self.sector_record_size;
2897 let base = index.checked_mul(size)?;
2898 let end = base.checked_add(size)?;
2899 let bytes = self.sectors.get(base..end)?;
2900 if index > u16::MAX as usize {
2901 return None;
2902 }
2903 Some(WorldSectorCollisionProbe {
2904 flags: bytes[0],
2905 first_wall: read_u16(bytes, 8),
2906 wall_count: read_u16(bytes, 10),
2907 })
2908 }
2909
2910 pub fn wall(&self, index: u16) -> Option<WorldWall> {
2912 if index >= self.wall_count {
2913 return None;
2914 }
2915 let size = self.wall_record_size;
2916 let base = index as usize * size;
2917 let end = base.checked_add(size)?;
2918 let bytes = self.walls.get(base..end)?;
2919 Some(WorldWall::decode(bytes))
2920 }
2921
2922 pub fn sector_wall(&self, sector: WorldSector, local_index: u16) -> Option<WorldWall> {
2924 if local_index >= sector.wall_count {
2925 return None;
2926 }
2927 self.wall(sector.first_wall.checked_add(local_index)?)
2928 }
2929
2930 pub fn surface_light(&self, index: u16) -> Option<WorldSurfaceLight> {
2932 if !self.static_vertex_lighting || index >= self.surface_light_count {
2933 return None;
2934 }
2935 let size = psxed_format::world::SurfaceLightRecord::SIZE;
2936 let base = index as usize * size;
2937 let end = base.checked_add(size)?;
2938 let bytes = self.surface_lights.get(base..end)?;
2939 Some(read_world_surface_light(bytes, 0))
2940 }
2941
2942 fn horizontal_override(
2943 &self,
2944 sector_index: u16,
2945 surface: u8,
2946 ) -> Option<WorldHorizontalOverride> {
2947 let size = self.horizontal_override_record_size;
2948 let mut index = 0usize;
2949 while index < self.horizontal_override_count as usize {
2950 let base = index.checked_mul(size)?;
2951 let bytes = self.horizontal_overrides.get(base..base + size)?;
2952 if read_u16(bytes, 0) == sector_index && bytes[2] == surface {
2953 return Some(read_world_horizontal_override(bytes));
2954 }
2955 index += 1;
2956 }
2957 None
2958 }
2959
2960 fn horizontal_collision_override(
2961 &self,
2962 sector_index: u16,
2963 surface: u8,
2964 triangle: usize,
2965 ) -> Option<(u8, Option<[i32; 3]>)> {
2966 let size = self.horizontal_override_record_size;
2967 let mut index = 0usize;
2968 while index < self.horizontal_override_count as usize {
2969 let base = index.checked_mul(size)?;
2970 let bytes = self.horizontal_overrides.get(base..base + size)?;
2971 if read_u16(bytes, 0) == sector_index && bytes[2] == surface {
2972 let heights = (bytes.len() >= psxed_format::world::HorizontalOverrideRecord::SIZE)
2973 .then(|| {
2974 let offset = 24 + triangle.min(1) * 12;
2975 [
2976 read_i32(bytes, offset),
2977 read_i32(bytes, offset + 4),
2978 read_i32(bytes, offset + 8),
2979 ]
2980 });
2981 return Some((bytes[3], heights));
2982 }
2983 index += 1;
2984 }
2985 None
2986 }
2987}
2988
2989#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2990struct WorldHorizontalOverride {
2991 flags: u8,
2992 materials: [u16; 2],
2993 uvs: [WorldQuadUvs; 2],
2994 heights: Option<[[i32; 3]; 2]>,
2995}
2996
2997#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2999pub struct WorldSectorCollisionProbe {
3000 flags: u8,
3001 first_wall: u16,
3002 wall_count: u16,
3003}
3004
3005#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3007pub struct WorldSectorFloorCollision {
3008 split: u8,
3009 triangle: u8,
3010 walkable: bool,
3011 floor_heights: [i32; 4],
3012 triangle_heights: [i32; 3],
3013}
3014
3015impl WorldSectorFloorCollision {
3016 #[inline]
3018 pub fn split(self) -> u8 {
3019 self.split
3020 }
3021
3022 #[inline]
3024 pub fn triangle(self) -> usize {
3025 self.triangle as usize
3026 }
3027
3028 #[inline]
3030 pub fn is_walkable(self) -> bool {
3031 self.walkable
3032 }
3033
3034 #[deprecated(note = "renamed to `is_walkable`")]
3036 #[inline(always)]
3037 pub fn walkable(self) -> bool {
3038 self.is_walkable()
3039 }
3040
3041 #[inline]
3043 pub fn floor_heights(self) -> [i32; 4] {
3044 self.floor_heights
3045 }
3046
3047 #[inline]
3049 pub fn triangle_heights(self) -> [i32; 3] {
3050 self.triangle_heights
3051 }
3052}
3053
3054impl WorldSectorCollisionProbe {
3055 #[inline]
3057 pub fn has_geometry(self) -> bool {
3058 self.has_floor() || self.has_ceiling() || self.wall_count != 0
3059 }
3060
3061 #[inline]
3063 pub fn has_floor(self) -> bool {
3064 self.flags & psxed_format::world::sector_flags::HAS_FLOOR != 0
3065 }
3066
3067 #[inline]
3069 pub fn has_ceiling(self) -> bool {
3070 self.flags & psxed_format::world::sector_flags::HAS_CEILING != 0
3071 }
3072
3073 #[inline]
3075 pub fn first_wall(self) -> u16 {
3076 self.first_wall
3077 }
3078
3079 #[inline]
3081 pub fn wall_count(self) -> u16 {
3082 self.wall_count
3083 }
3084}
3085
3086#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3088pub struct WorldSector {
3089 flags: u8,
3090 floor_split: u8,
3091 ceiling_split: u8,
3092 floor_material: u16,
3093 ceiling_material: u16,
3094 floor_triangle_flags: u8,
3095 ceiling_triangle_flags: u8,
3096 floor_triangle_materials: [u16; 2],
3097 ceiling_triangle_materials: [u16; 2],
3098 floor_triangle_heights: [[i32; 3]; 2],
3099 ceiling_triangle_heights: [[i32; 3]; 2],
3100 first_wall: u16,
3101 wall_count: u16,
3102 floor_heights: [i32; 4],
3103 ceiling_heights: [i32; 4],
3104 floor_uvs: WorldQuadUvs,
3105 ceiling_uvs: WorldQuadUvs,
3106 floor_triangle_uvs: [WorldQuadUvs; 2],
3107 ceiling_triangle_uvs: [WorldQuadUvs; 2],
3108}
3109
3110impl WorldSector {
3111 fn decode(
3112 bytes: &[u8],
3113 floor_override: Option<WorldHorizontalOverride>,
3114 ceiling_override: Option<WorldHorizontalOverride>,
3115 ) -> Self {
3116 let has_v2_uvs = bytes.len() >= WORLD_V2_SECTOR_RECORD_SIZE;
3117 let flags = bytes[0];
3118 let floor_material = read_u16(bytes, 4);
3119 let ceiling_material = read_u16(bytes, 6);
3120 let floor_heights = read_i32x4(bytes, 12);
3121 let ceiling_heights = read_i32x4(bytes, 28);
3122 let floor_uvs = if has_v2_uvs {
3123 read_world_uvs(bytes, 44)
3124 } else {
3125 WorldQuadUvs::new(psxed_format::world::FLOOR_UVS)
3126 };
3127 let ceiling_uvs = if has_v2_uvs {
3128 read_world_uvs(bytes, 52)
3129 } else {
3130 WorldQuadUvs::new(psxed_format::world::FLOOR_UVS)
3131 };
3132 let floor_default_flags = default_horizontal_flags(
3133 flags & psxed_format::world::sector_flags::HAS_FLOOR != 0,
3134 flags & psxed_format::world::sector_flags::FLOOR_WALKABLE != 0,
3135 );
3136 let ceiling_default_flags = default_horizontal_flags(
3137 flags & psxed_format::world::sector_flags::HAS_CEILING != 0,
3138 flags & psxed_format::world::sector_flags::CEILING_WALKABLE != 0,
3139 );
3140 let floor_triangle_flags =
3141 floor_override.map_or(floor_default_flags, |override_data| override_data.flags);
3142 let ceiling_triangle_flags =
3143 ceiling_override.map_or(ceiling_default_flags, |override_data| override_data.flags);
3144 let floor_triangle_materials = floor_override
3145 .map_or([floor_material, floor_material], |override_data| {
3146 override_data.materials
3147 });
3148 let ceiling_triangle_materials = ceiling_override
3149 .map_or([ceiling_material, ceiling_material], |override_data| {
3150 override_data.materials
3151 });
3152 let floor_triangle_uvs =
3153 floor_override.map_or([floor_uvs, floor_uvs], |override_data| override_data.uvs);
3154 let ceiling_triangle_uvs = ceiling_override
3155 .map_or([ceiling_uvs, ceiling_uvs], |override_data| {
3156 override_data.uvs
3157 });
3158 let floor_triangle_heights = floor_override
3159 .and_then(|override_data| override_data.heights)
3160 .unwrap_or_else(|| {
3161 [
3162 horizontal_triangle_heights(floor_heights, bytes[1], 0),
3163 horizontal_triangle_heights(floor_heights, bytes[1], 1),
3164 ]
3165 });
3166 let ceiling_triangle_heights = ceiling_override
3167 .and_then(|override_data| override_data.heights)
3168 .unwrap_or_else(|| {
3169 [
3170 horizontal_triangle_heights(ceiling_heights, bytes[2], 0),
3171 horizontal_triangle_heights(ceiling_heights, bytes[2], 1),
3172 ]
3173 });
3174 Self {
3175 flags,
3176 floor_split: bytes[1],
3177 ceiling_split: bytes[2],
3178 floor_material,
3179 ceiling_material,
3180 floor_triangle_flags,
3181 ceiling_triangle_flags,
3182 floor_triangle_materials,
3183 ceiling_triangle_materials,
3184 floor_triangle_heights,
3185 ceiling_triangle_heights,
3186 first_wall: read_u16(bytes, 8),
3187 wall_count: read_u16(bytes, 10),
3188 floor_heights,
3189 ceiling_heights,
3190 floor_uvs,
3191 ceiling_uvs,
3192 floor_triangle_uvs,
3193 ceiling_triangle_uvs,
3194 }
3195 }
3196
3197 #[inline]
3199 pub fn has_geometry(&self) -> bool {
3200 self.has_floor() || self.has_ceiling() || self.wall_count != 0
3201 }
3202
3203 #[inline]
3205 pub fn has_floor(&self) -> bool {
3206 self.flags & psxed_format::world::sector_flags::HAS_FLOOR != 0
3207 && (self.has_floor_triangle(0) || self.has_floor_triangle(1))
3208 }
3209
3210 #[inline]
3212 pub fn has_ceiling(&self) -> bool {
3213 self.flags & psxed_format::world::sector_flags::HAS_CEILING != 0
3214 && (self.has_ceiling_triangle(0) || self.has_ceiling_triangle(1))
3215 }
3216
3217 #[inline]
3219 pub fn is_floor_walkable(&self) -> bool {
3220 self.is_floor_triangle_walkable(0) || self.is_floor_triangle_walkable(1)
3221 }
3222
3223 #[deprecated(note = "renamed to `is_floor_walkable`")]
3225 #[inline(always)]
3226 pub fn floor_walkable(&self) -> bool {
3227 self.is_floor_walkable()
3228 }
3229
3230 #[inline]
3232 pub fn floor_split(&self) -> u8 {
3233 self.floor_split
3234 }
3235
3236 #[inline]
3238 pub fn floor_material(&self) -> Option<u16> {
3239 self.floor_triangle_material(0)
3240 .or_else(|| self.floor_triangle_material(1))
3241 .or_else(|| material_or_none(self.floor_material))
3242 }
3243
3244 #[inline]
3246 pub fn floor_heights(&self) -> [i32; 4] {
3247 self.floor_heights
3248 }
3249
3250 #[inline]
3252 pub fn floor_uvs(&self) -> WorldQuadUvs {
3253 self.floor_uvs
3254 }
3255
3256 #[inline]
3258 pub fn has_floor_triangle(&self, index: usize) -> bool {
3259 horizontal_triangle_present(self.floor_triangle_flags, index)
3260 }
3261
3262 #[deprecated(note = "renamed to `has_floor_triangle`")]
3264 #[inline(always)]
3265 pub fn floor_triangle_present(&self, index: usize) -> bool {
3266 self.has_floor_triangle(index)
3267 }
3268
3269 #[inline]
3271 pub fn floor_triangle_material(&self, index: usize) -> Option<u16> {
3272 if self.has_floor_triangle(index) {
3273 material_or_none(self.floor_triangle_materials[index.min(1)])
3274 } else {
3275 None
3276 }
3277 }
3278
3279 #[inline]
3281 pub fn floor_triangle_uvs(&self, index: usize) -> WorldQuadUvs {
3282 self.floor_triangle_uvs[index.min(1)]
3283 }
3284
3285 #[inline]
3287 pub fn floor_triangle_heights(&self, index: usize) -> [i32; 3] {
3288 self.floor_triangle_heights[index.min(1)]
3289 }
3290
3291 #[inline]
3293 pub fn is_floor_triangle_walkable(&self, index: usize) -> bool {
3294 self.has_floor_triangle(index)
3295 && horizontal_triangle_walkable(self.floor_triangle_flags, index)
3296 }
3297
3298 #[deprecated(note = "renamed to `is_floor_triangle_walkable`")]
3300 #[inline(always)]
3301 pub fn floor_triangle_walkable(&self, index: usize) -> bool {
3302 self.is_floor_triangle_walkable(index)
3303 }
3304
3305 #[inline]
3307 pub fn ceiling_split(&self) -> u8 {
3308 self.ceiling_split
3309 }
3310
3311 #[inline]
3313 pub fn ceiling_material(&self) -> Option<u16> {
3314 self.ceiling_triangle_material(0)
3315 .or_else(|| self.ceiling_triangle_material(1))
3316 .or_else(|| material_or_none(self.ceiling_material))
3317 }
3318
3319 #[inline]
3321 pub fn ceiling_heights(&self) -> [i32; 4] {
3322 self.ceiling_heights
3323 }
3324
3325 #[inline]
3327 pub fn ceiling_uvs(&self) -> WorldQuadUvs {
3328 self.ceiling_uvs
3329 }
3330
3331 #[inline]
3333 pub fn has_ceiling_triangle(&self, index: usize) -> bool {
3334 horizontal_triangle_present(self.ceiling_triangle_flags, index)
3335 }
3336
3337 #[deprecated(note = "renamed to `has_ceiling_triangle`")]
3339 #[inline(always)]
3340 pub fn ceiling_triangle_present(&self, index: usize) -> bool {
3341 self.has_ceiling_triangle(index)
3342 }
3343
3344 #[inline]
3346 pub fn ceiling_triangle_material(&self, index: usize) -> Option<u16> {
3347 if self.has_ceiling_triangle(index) {
3348 material_or_none(self.ceiling_triangle_materials[index.min(1)])
3349 } else {
3350 None
3351 }
3352 }
3353
3354 #[inline]
3356 pub fn ceiling_triangle_uvs(&self, index: usize) -> WorldQuadUvs {
3357 self.ceiling_triangle_uvs[index.min(1)]
3358 }
3359
3360 #[inline]
3362 pub fn ceiling_triangle_heights(&self, index: usize) -> [i32; 3] {
3363 self.ceiling_triangle_heights[index.min(1)]
3364 }
3365
3366 #[inline]
3368 pub fn is_ceiling_triangle_walkable(&self, index: usize) -> bool {
3369 self.has_ceiling_triangle(index)
3370 && horizontal_triangle_walkable(self.ceiling_triangle_flags, index)
3371 }
3372
3373 #[inline]
3375 pub fn first_wall(&self) -> u16 {
3376 self.first_wall
3377 }
3378
3379 #[inline]
3381 pub fn wall_count(&self) -> u16 {
3382 self.wall_count
3383 }
3384}
3385
3386#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3388pub struct WorldWall {
3389 direction: u8,
3390 flags: u8,
3391 material: u16,
3392 shape: u16,
3393 heights: [i32; 4],
3394 uvs: WorldQuadUvs,
3395}
3396
3397impl WorldWall {
3398 fn decode(bytes: &[u8]) -> Self {
3399 let has_v2_uvs = bytes.len() >= WORLD_V2_WALL_RECORD_SIZE;
3400 Self {
3401 direction: bytes[0],
3402 flags: bytes[1],
3403 material: read_u16(bytes, 4),
3404 shape: if has_v2_uvs {
3405 read_u16(bytes, 6)
3406 } else {
3407 psxed_format::world::wall_shape::QUAD
3408 },
3409 heights: read_i32x4(bytes, 8),
3410 uvs: if has_v2_uvs {
3411 read_world_uvs(bytes, 24)
3412 } else {
3413 WorldQuadUvs::new(psxed_format::world::WALL_UVS)
3414 },
3415 }
3416 }
3417
3418 #[inline]
3420 pub fn direction(&self) -> u8 {
3421 self.direction
3422 }
3423
3424 #[inline]
3426 pub fn is_solid(&self) -> bool {
3427 self.flags & psxed_format::world::wall_flags::SOLID != 0
3428 }
3429
3430 #[inline]
3432 pub fn material(&self) -> u16 {
3433 self.material
3434 }
3435
3436 #[inline]
3438 pub fn shape(&self) -> u16 {
3439 self.shape
3440 }
3441
3442 #[inline]
3444 pub fn heights(&self) -> [i32; 4] {
3445 self.heights
3446 }
3447
3448 #[inline]
3450 pub fn uvs(&self) -> WorldQuadUvs {
3451 self.uvs
3452 }
3453}
3454
3455#[inline]
3456fn material_or_none(material: u16) -> Option<u16> {
3457 if material == psxed_format::world::NO_MATERIAL {
3458 None
3459 } else {
3460 Some(material)
3461 }
3462}
3463
3464const fn default_horizontal_flags(present: bool, walkable: bool) -> u8 {
3465 if !present {
3466 0
3467 } else {
3468 let mut flags = psxed_format::world::horizontal_flags::TRI_A_PRESENT
3469 | psxed_format::world::horizontal_flags::TRI_B_PRESENT;
3470 if walkable {
3471 flags |= psxed_format::world::horizontal_flags::TRI_A_WALKABLE
3472 | psxed_format::world::horizontal_flags::TRI_B_WALKABLE;
3473 }
3474 flags
3475 }
3476}
3477
3478const fn horizontal_triangle_present(flags: u8, index: usize) -> bool {
3479 let bit = if index == 0 {
3480 psxed_format::world::horizontal_flags::TRI_A_PRESENT
3481 } else {
3482 psxed_format::world::horizontal_flags::TRI_B_PRESENT
3483 };
3484 flags & bit != 0
3485}
3486
3487const fn horizontal_triangle_walkable(flags: u8, index: usize) -> bool {
3488 let bit = if index == 0 {
3489 psxed_format::world::horizontal_flags::TRI_A_WALKABLE
3490 } else {
3491 psxed_format::world::horizontal_flags::TRI_B_WALKABLE
3492 };
3493 flags & bit != 0
3494}
3495
3496fn horizontal_triangle_heights(heights: [i32; 4], split: u8, index: usize) -> [i32; 3] {
3497 let corners = psxed_format::world::topology::split_triangle(split, index);
3498 [
3499 heights[corners[0]],
3500 heights[corners[1]],
3501 heights[corners[2]],
3502 ]
3503}
3504
3505fn checked_table_bytes(count: u16, stride: usize) -> Result<usize, ParseError> {
3506 (count as usize)
3507 .checked_mul(stride)
3508 .ok_or(ParseError::TableOverflow)
3509}
3510
3511fn take_table<'a>(bytes: &'a [u8], offset: &mut usize, len: usize) -> Result<&'a [u8], ParseError> {
3512 let end = offset.checked_add(len).ok_or(ParseError::TableOverflow)?;
3513 if end > bytes.len() {
3514 return Err(ParseError::TableOverflow);
3515 }
3516 let table = &bytes[*offset..end];
3517 *offset = end;
3518 Ok(table)
3519}
3520
3521fn validate_model_parts(
3522 parts: &[u8],
3523 joint_count: u16,
3524 material_count: u16,
3525 vertex_count: u16,
3526 face_count: u16,
3527) -> Result<(), ParseError> {
3528 let size = psxed_format::model::PartRecord::SIZE;
3529 let count = parts.len() / size;
3530 for index in 0..count {
3531 let base = index * size;
3532 let joint_index = read_u16(parts, base);
3533 let first_vertex = read_u16(parts, base + 2);
3534 let part_vertex_count = read_u16(parts, base + 4);
3535 let first_face = read_u16(parts, base + 6);
3536 let part_face_count = read_u16(parts, base + 8);
3537 let material_index = read_u16(parts, base + 10);
3538
3539 if joint_index != psxed_format::model::NO_JOINT && joint_index >= joint_count {
3540 return Err(ParseError::InvalidModelLayout);
3541 }
3542 if material_index >= material_count {
3543 return Err(ParseError::InvalidModelLayout);
3544 }
3545 let Some(vertex_end) = first_vertex.checked_add(part_vertex_count) else {
3546 return Err(ParseError::InvalidModelLayout);
3547 };
3548 if vertex_end > vertex_count {
3549 return Err(ParseError::InvalidModelLayout);
3550 }
3551 let Some(face_end) = first_face.checked_add(part_face_count) else {
3552 return Err(ParseError::InvalidModelLayout);
3553 };
3554 if face_end > face_count {
3555 return Err(ParseError::InvalidModelLayout);
3556 }
3557 }
3558 Ok(())
3559}
3560
3561fn validate_model_faces(faces: &[u8], vertex_count: u16) -> Result<(), ParseError> {
3562 let size = psxed_format::model::FACE_RECORD_SIZE;
3563 let count = faces.len() / size;
3564 for index in 0..count {
3565 let base = index * size;
3566 let a = read_u16(faces, base);
3567 let b = read_u16(faces, base + 4);
3568 let c = read_u16(faces, base + 8);
3569 if a >= vertex_count || b >= vertex_count || c >= vertex_count {
3570 return Err(ParseError::InvalidModelLayout);
3571 }
3572 }
3573 Ok(())
3574}
3575
3576#[inline]
3577fn read_u16(bytes: &[u8], offset: usize) -> u16 {
3578 u16::from_le_bytes([bytes[offset], bytes[offset + 1]])
3579}
3580
3581#[inline]
3582fn read_u32(bytes: &[u8], offset: usize) -> u32 {
3583 u32::from_le_bytes([
3584 bytes[offset],
3585 bytes[offset + 1],
3586 bytes[offset + 2],
3587 bytes[offset + 3],
3588 ])
3589}
3590
3591#[inline]
3592fn read_i16(bytes: &[u8], offset: usize) -> i16 {
3593 i16::from_le_bytes([bytes[offset], bytes[offset + 1]])
3594}
3595
3596#[inline]
3601unsafe fn read_i16_unchecked(bytes: &[u8], offset: usize) -> i16 {
3602 let lo = unsafe { *bytes.get_unchecked(offset) };
3605 let hi = unsafe { *bytes.get_unchecked(offset + 1) };
3607 i16::from_le_bytes([lo, hi])
3608}
3609
3610#[inline]
3616unsafe fn read_i16_aligned_unchecked(bytes: &[u8], offset: usize) -> i16 {
3617 debug_assert_eq!((unsafe { bytes.as_ptr().add(offset) } as usize) & 1, 0);
3620 i16::from_le(unsafe { bytes.as_ptr().add(offset).cast::<i16>().read() })
3623}
3624
3625#[inline]
3626fn read_i32(bytes: &[u8], offset: usize) -> i32 {
3627 i32::from_le_bytes([
3628 bytes[offset],
3629 bytes[offset + 1],
3630 bytes[offset + 2],
3631 bytes[offset + 3],
3632 ])
3633}
3634
3635#[inline]
3640unsafe fn read_i32_unchecked(bytes: &[u8], offset: usize) -> i32 {
3641 i32::from_le_bytes([
3642 unsafe { *bytes.get_unchecked(offset) },
3644 unsafe { *bytes.get_unchecked(offset + 1) },
3646 unsafe { *bytes.get_unchecked(offset + 2) },
3648 unsafe { *bytes.get_unchecked(offset + 3) },
3650 ])
3651}
3652
3653#[inline]
3654fn read_i32x4(bytes: &[u8], offset: usize) -> [i32; 4] {
3655 [
3656 read_i32(bytes, offset),
3657 read_i32(bytes, offset + 4),
3658 read_i32(bytes, offset + 8),
3659 read_i32(bytes, offset + 12),
3660 ]
3661}
3662
3663#[inline]
3664fn read_world_uvs(bytes: &[u8], offset: usize) -> WorldQuadUvs {
3665 WorldQuadUvs::new([
3666 (bytes[offset], bytes[offset + 1]),
3667 (bytes[offset + 2], bytes[offset + 3]),
3668 (bytes[offset + 4], bytes[offset + 5]),
3669 (bytes[offset + 6], bytes[offset + 7]),
3670 ])
3671}
3672
3673#[inline]
3674fn read_world_horizontal_override(bytes: &[u8]) -> WorldHorizontalOverride {
3675 WorldHorizontalOverride {
3676 flags: bytes[3],
3677 materials: [read_u16(bytes, 4), read_u16(bytes, 6)],
3678 uvs: [read_world_uvs(bytes, 8), read_world_uvs(bytes, 16)],
3679 heights: (bytes.len() >= psxed_format::world::HorizontalOverrideRecord::SIZE).then(|| {
3680 [
3681 [
3682 read_i32(bytes, 24),
3683 read_i32(bytes, 28),
3684 read_i32(bytes, 32),
3685 ],
3686 [
3687 read_i32(bytes, 36),
3688 read_i32(bytes, 40),
3689 read_i32(bytes, 44),
3690 ],
3691 ]
3692 }),
3693 }
3694}
3695
3696#[inline]
3697fn read_world_surface_light(bytes: &[u8], offset: usize) -> WorldSurfaceLight {
3698 WorldSurfaceLight::new([
3699 [bytes[offset], bytes[offset + 1], bytes[offset + 2]],
3700 [bytes[offset + 3], bytes[offset + 4], bytes[offset + 5]],
3701 [bytes[offset + 6], bytes[offset + 7], bytes[offset + 8]],
3702 [bytes[offset + 9], bytes[offset + 10], bytes[offset + 11]],
3703 ])
3704}
3705
3706fn validate_horizontal_overrides(
3707 overrides: &[u8],
3708 override_count: u16,
3709 sector_count: u16,
3710 record_size: usize,
3711) -> Result<(), ParseError> {
3712 let size = record_size;
3713 if overrides.len() != override_count as usize * size {
3714 return Err(ParseError::InvalidWorldLayout);
3715 }
3716 for index in 0..override_count as usize {
3717 let base = index * size;
3718 let sector_index = read_u16(overrides, base);
3719 let surface = overrides[base + 2];
3720 if sector_index >= sector_count {
3721 return Err(ParseError::InvalidWorldLayout);
3722 }
3723 if surface != psxed_format::world::horizontal_surface::FLOOR
3724 && surface != psxed_format::world::horizontal_surface::CEILING
3725 {
3726 return Err(ParseError::InvalidWorldLayout);
3727 }
3728 }
3729 Ok(())
3730}
3731
3732fn validate_sector_wall_ranges(
3733 sectors: &[u8],
3734 sector_record_size: usize,
3735 wall_count: u16,
3736) -> Result<(), ParseError> {
3737 let size = sector_record_size;
3738 let count = sectors.len() / size;
3739 for index in 0..count {
3740 let base = index * size;
3741 let first_wall = read_u16(sectors, base + 8);
3742 let sector_wall_count = read_u16(sectors, base + 10);
3743 let Some(end) = first_wall.checked_add(sector_wall_count) else {
3744 return Err(ParseError::InvalidWorldLayout);
3745 };
3746 if end > wall_count {
3747 return Err(ParseError::InvalidWorldLayout);
3748 }
3749 }
3750 Ok(())
3751}
3752
3753#[cfg(test)]
3754extern crate std;
3755
3756#[cfg(test)]
3757mod tests;