Skip to main content

unbanished_formats/
types.rs

1//! Decoders for individual resource classes.
2
3mod animation;
4mod image;
5mod mesh;
6mod sound;
7pub use animation::{AnimationBlend, AnimationClip, AnimationEvent, AnimationGroup};
8pub use image::{ImageBuffer, ImageFormat};
9pub use mesh::{
10    Bone, DrawRange, GraphicsMesh, MeshPart, POSITION_SCALE, SKINNED_STRIDE, STATIC_STRIDE,
11};
12pub use sound::{SoundBuffer, WaveFormat};
13
14use crate::crc::type_id;
15use crate::crs::{self, Reader};
16use crate::error::{format_err, Error, Result};
17
18// ---------------------------------------------------------------- MaterialInstance
19
20/// A material instance: a base material, and its named textures and values.
21#[derive(Debug, Clone)]
22pub struct MaterialInstance {
23    /// The base material, which selects the shader.
24    pub material: Option<String>,
25    /// The textures by slot name, for example `diffuse`.
26    pub textures: Vec<(String, Option<String>)>,
27    /// The named values (four floats each).
28    pub vectors: Vec<(String, [f32; 4])>,
29}
30
31impl MaterialInstance {
32    /// The resource class name.
33    pub const CLASS: &'static str = "MaterialInstance";
34
35    /// Original: `Graphics::MaterialInstance::Serialize`, Runtime `0x180106300`.
36    pub fn read(r: &mut Reader) -> Result<Self> {
37        r.block(|r, _| {
38            let material = r.external_ref()?;
39            let textures = (0..r.count()?)
40                .map(|_| Ok((r.string()?, r.external_ref()?)))
41                .collect::<Result<_>>()?;
42            let vectors = (0..r.count()?)
43                .map(|_| Ok((r.string()?, r.f32s()?)))
44                .collect::<Result<_>>()?;
45            Ok(MaterialInstance {
46                material,
47                textures,
48                vectors,
49            })
50        })
51    }
52
53    /// The texture in a named slot, for example `diffuse`.
54    pub fn texture(&self, slot: &str) -> Option<&str> {
55        self.textures
56            .iter()
57            .find(|(s, _)| s == slot)
58            .and_then(|(_, t)| t.as_deref())
59    }
60}
61
62// ---------------------------------------------------------------- VertexLayout
63
64/// One attribute of a vertex layout.
65#[derive(Debug, Clone)]
66pub struct VertexElement {
67    /// The semantic, for example `POSITION`.
68    pub semantic: String,
69    /// The vertex stream.
70    pub stream: i32,
71    /// The offset in the vertex, in bytes.
72    pub offset: i32,
73    /// The usage.
74    pub usage: i32,
75    /// The usage index.
76    pub usage_index: i32,
77    /// 0 float4, 1 float3, 2 float2, 3 float1, 4 sint16x4, 5 sint16x2,
78    /// 6 bgra8unorm, 7 uint8x4, 8 unorm8x4 (VideoDX11 DXGI table).
79    pub format: i32,
80}
81
82/// A vertex layout: its attributes, and the Direct3D 11 input signature.
83#[derive(Debug, Clone)]
84pub struct VertexLayout {
85    /// The attributes.
86    pub elements: Vec<VertexElement>,
87    /// The Direct3D 11 input signature.
88    pub dxbc_signature: Vec<u8>,
89}
90
91impl VertexLayout {
92    /// The resource class name.
93    pub const CLASS: &'static str = "VertexLayout";
94
95    /// Original: `Video::VertexLayout::Serialize`, Runtime `0x1800f86c0`.
96    pub fn read(r: &mut Reader) -> Result<Self> {
97        r.block(|r, _| {
98            let elements = (0..r.count()?)
99                .map(|_| {
100                    Ok(VertexElement {
101                        semantic: r.string()?,
102                        stream: r.i32()?,
103                        offset: r.i32()?,
104                        usage: r.i32()?,
105                        usage_index: r.i32()?,
106                        format: r.i32()?,
107                    })
108                })
109                .collect::<Result<_>>()?;
110            let n = r.count()?;
111            Ok(VertexLayout {
112                elements,
113                dxbc_signature: r.bytes(n)?.to_vec(),
114            })
115        })
116    }
117}
118
119// ---------------------------------------------------------------- dispatch
120
121/// Decode a resource whose class is known statically; checks the type id.
122pub fn decode<T>(data: &[u8], class: &str, read: fn(&mut Reader) -> Result<T>) -> Result<T> {
123    let (_, value) = crs::parse(data, |r, h| {
124        if h.type_id != type_id(class) {
125            return format_err(format!(
126                "expected {class}, found type id {:#010x}",
127                h.type_id
128            ));
129        }
130        read(r)
131    })?;
132    Ok(value)
133}
134
135macro_rules! decode_fn {
136    ($name:ident, $ty:ty) => {
137        #[doc = concat!("Read a [`", stringify!($ty), "`] from the bytes of its resource.")]
138        pub fn $name(data: &[u8]) -> Result<$ty> {
139            decode(data, <$ty>::CLASS, <$ty>::read)
140        }
141    };
142}
143
144decode_fn!(image_buffer, ImageBuffer);
145decode_fn!(graphics_mesh, GraphicsMesh);
146decode_fn!(animation_group, AnimationGroup);
147decode_fn!(material_instance, MaterialInstance);
148decode_fn!(vertex_layout, VertexLayout);
149
150decode_fn!(sound_buffer, SoundBuffer);