-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
393 lines (337 loc) · 11.4 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#![warn(clippy::all, clippy::pedantic, clippy::multiple_crate_versions)]
// These are intentional
#![allow(
clippy::cast_possible_wrap,
clippy::cast_sign_loss,
clippy::cast_precision_loss
)]
mod binary_utils;
mod mdl;
mod vtx;
mod vvd;
use std::{
collections::BTreeMap,
fmt::{self, Display},
io,
mem::size_of,
result,
};
use mdl::Mdl;
pub use mdl::{AnimationData, AnimationDescFlags, BoneAnimationData};
pub use vtx::Face;
use vtx::Vtx;
use vvd::Vvd;
pub use vvd::{BoneWeight, Vertex};
use itertools::Itertools;
use thiserror::Error;
use plumber_fs::{GameFile, GamePathBuf, OpenFileSystem, Path, PathBuf};
#[derive(Debug, Clone, Error, Hash, PartialEq, Eq)]
pub enum Error {
#[error("io error reading `{path}`: {error}")]
Io { path: String, error: String },
#[error("not a {ty} file: invalid signature `{signature}`")]
InvalidSignature { ty: FileType, signature: String },
#[error("unsupported {ty} version {version}")]
UnsupportedVersion { ty: FileType, version: i32 },
#[error("{0} checksum doesn't match mdl checksum")]
ChecksumMismatch(FileType),
#[error("{ty} corrupted: {error}")]
Corrupted { ty: FileType, error: &'static str },
#[error("{ty} {feature} unsupported")]
Unsupported { ty: FileType, feature: &'static str },
}
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub enum FileType {
Mdl,
Vvd,
Vtx,
}
pub type Result<T> = result::Result<T, Error>;
impl Display for FileType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
FileType::Mdl => "mdl",
FileType::Vvd => "vvd",
FileType::Vtx => "vtx",
})
}
}
impl Error {
fn from_io(err: &io::Error, path: &impl ToString) -> Self {
Self::Io {
path: path.to_string(),
error: err.to_string(),
}
}
}
const VTX_EXTENSIONS: &[&str] = &["dx90.vtx", "dx80.vtx", "sw.vtx", "vtx"];
fn find_vtx<'a>(
mdl_path: Path,
file_system: &'a OpenFileSystem,
) -> Result<(PathBuf, GameFile<'a>)> {
for &extension in VTX_EXTENSIONS {
let path = mdl_path.with_extension(extension);
match file_system.open_file(&path) {
Ok(file) => return Ok((path, file)),
Err(err) => {
if err.kind() == io::ErrorKind::NotFound {
continue;
}
return Err(Error::from_io(&err, &path));
}
}
}
Err(Error::Io {
path: mdl_path.with_extension("*.vtx").to_string(),
error: "could not find a supported vtx file".to_owned(),
})
}
#[derive(Debug, Clone)]
pub struct Model {
mdl: Mdl,
vvd: Vvd,
vtx: Vtx,
}
impl Model {
/// # Errors
///
/// Returns `Err` if reading the mdl file fails or if reading an associated vvd or vtx file fails.
pub fn read<'a>(path: impl Into<Path<'a>>, file_system: &OpenFileSystem) -> Result<Self> {
let path = path.into();
let mdl_file = file_system
.open_file(path)
.map_err(|err| Error::from_io(&err, &path))?;
let mdl = Mdl::read(mdl_file).map_err(|err| Error::from_io(&err, &path))?;
let vvd_path = path.with_extension("vvd");
let vvd_file = file_system
.open_file(&vvd_path)
.map_err(|err| Error::from_io(&err, &vvd_path))?;
let vvd = Vvd::read(vvd_file).map_err(|err| Error::from_io(&err, &vvd_path))?;
let (vtx_path, vtx_file) = find_vtx(path, file_system)?;
let vtx = Vtx::read(vtx_file).map_err(|err| Error::from_io(&err, &vtx_path))?;
Ok(Model { mdl, vvd, vtx })
}
/// # Errors
///
/// Returns `Err` if a signature or header is invalid or a version is unsupported.
pub fn verify(&self) -> Result<Verified> {
self.mdl.check_signature()?;
self.mdl.check_version()?;
self.vvd.check_signature()?;
self.vvd.check_version()?;
self.vtx.check_version()?;
let mdl_header = self.mdl.header()?;
let vvd_header = self.vvd.header()?;
let vtx_header = self.vtx.header()?;
if vvd_header.checksum() != mdl_header.checksum() {
return Err(Error::ChecksumMismatch(FileType::Vvd));
}
if vtx_header.checksum() != mdl_header.checksum() {
return Err(Error::ChecksumMismatch(FileType::Vtx));
}
Ok(Verified {
mdl_header,
vvd_header,
vtx_header,
})
}
}
#[derive(Debug, Clone)]
pub struct Verified<'a> {
mdl_header: mdl::HeaderRef<'a>,
vvd_header: vvd::HeaderRef<'a>,
vtx_header: vtx::HeaderRef<'a>,
}
impl<'a> Verified<'a> {
#[must_use]
pub fn is_static_prop(&self) -> bool {
self.mdl_header
.flags()
.contains(mdl::HeaderFlags::STATIC_PROP)
}
/// # Errors
///
/// Returns `Err` if reading the name fails.
pub fn name(&self) -> Result<&str> {
self.mdl_header.name()
}
/// # Errors
///
/// Returns `Err` if reading the meshes fails.
pub fn meshes(&self) -> Result<Vec<Mesh>> {
let vertices = self.vvd_header.lod_vertices(0)?.ok_or(Error::Corrupted {
ty: FileType::Vvd,
error: "lod 0 doesn't exist",
})?;
let vtx_body_parts = self.vtx_header.iter_body_parts()?;
let mdl_body_parts = self.mdl_header.iter_body_parts()?;
let mut meshes = Vec::new();
for (vtx_body_part, mdl_body_part) in vtx_body_parts.zip(mdl_body_parts) {
let vtx_models = vtx_body_part.iter_models()?;
let mdl_models = mdl_body_part.iter_models()?;
let body_part_name = mdl_body_part.name()?;
meshes.reserve(vtx_models.len());
for (vtx_model, mdl_model) in vtx_models.zip(mdl_models) {
let name = mdl_model.name()?;
let vertex_offset: usize =
mdl_model
.vertex_offset
.try_into()
.map_err(|_| Error::Corrupted {
ty: FileType::Mdl,
error: "model vertex offset is negative",
})?;
let vertex_count: usize =
mdl_model
.vertex_count
.try_into()
.map_err(|_| Error::Corrupted {
ty: FileType::Mdl,
error: "model vertex count is negative",
})?;
if vertex_offset % size_of::<Vertex>() != 0 {
return Err(Error::Corrupted {
ty: FileType::Mdl,
error: "model vertex offset is misaligned",
});
}
let vertex_index = vertex_offset / size_of::<Vertex>();
let model_vertices = vertices
.get(vertex_index..vertex_index + vertex_count)
.ok_or(Error::Corrupted {
ty: FileType::Mdl,
error: "model vertex offset out of bounds",
})?;
let lods = vtx_model.lods()?;
let Some(lod_0) = lods.get(0) else {
continue;
};
let (vertice_indices, faces) = lod_0.merged_meshes(mdl_model)?;
let vertices: Vec<_> = vertice_indices
.into_iter()
.map(|i| {
model_vertices.get(i).copied().ok_or(Error::Corrupted {
ty: FileType::Vtx,
error: "vertice index out of bounds",
})
})
.try_collect()?;
meshes.push(Mesh {
body_part_name,
name,
vertices,
faces,
});
}
}
Ok(meshes)
}
/// # Errors
///
/// Returns `Err` if a material path reading fails or a material isn't found.
pub fn materials<'f>(
&self,
file_system: &'f OpenFileSystem,
) -> Result<impl Iterator<Item = Result<GamePathBuf>> + 'f>
where
'a: 'f,
{
let texture_paths = self.mdl_header.texture_paths()?;
Ok(self
.mdl_header
.iter_textures()?
.map(move |texture| find_material(texture, &texture_paths, file_system)))
}
/// # Errors
///
/// Returns `Err` if reading the bones fails due to corrupted mdl.
pub fn bones(&self) -> Result<Vec<Bone>> {
self.mdl_header
.iter_bones()?
.map(|bone| {
Ok(Bone {
name: bone.name()?,
surface_prop: bone.surface_prop()?,
parent_bone_index: bone.parent_bone_index.try_into().ok(),
position: bone.position,
rotation: bone.rotation,
pose_to_bone: bone.pose_to_bone,
})
})
.try_collect()
}
/// # Errors
///
/// Returns `Err` if reading the animations fails due to corrupted mdl.
pub fn animations(&self) -> Result<impl Iterator<Item = Result<Animation>>> {
Ok(self
.mdl_header
.iter_animation_descs()?
.map(|animation_desc| {
let flags = animation_desc.flags();
let name = animation_desc.name()?;
let fps = animation_desc.animation_desc.fps;
if animation_desc.iter_movements()?.count() > 0 {
return Err(Error::Unsupported {
ty: FileType::Mdl,
feature: "animation movements",
});
}
let data = animation_desc.data()?;
Ok(Animation {
name,
flags,
fps,
data,
})
}))
}
}
fn find_material(
texture: mdl::TextureRef,
texture_paths: &[&str],
file_system: &OpenFileSystem,
) -> Result<GamePathBuf> {
let name = GamePathBuf::from(texture.name()?);
for &path in texture_paths {
let mut candidate = GamePathBuf::from("materials");
candidate.push(GamePathBuf::from(path));
candidate.push(&name);
candidate.set_extension("vmt");
match file_system.open_file(&candidate) {
Ok(_) => return Ok(candidate),
Err(err) => {
if err.kind() != io::ErrorKind::NotFound {
return Err(Error::from_io(&err, &candidate));
}
}
}
}
Err(Error::Io {
path: name.with_extension("vmt").into_string(),
error: "could not find the material in any material paths".to_owned(),
})
}
#[derive(Debug, Clone)]
pub struct Mesh<'a> {
pub body_part_name: &'a str,
pub name: &'a str,
pub vertices: Vec<Vertex>,
pub faces: Vec<Face>,
}
#[derive(Debug, Clone, Copy)]
pub struct Bone<'a> {
pub name: &'a str,
pub surface_prop: Option<&'a str>,
pub parent_bone_index: Option<usize>,
pub position: [f32; 3],
pub rotation: [f32; 3],
pub pose_to_bone: [f32; 12],
}
#[derive(Debug, Clone)]
pub struct Animation<'a> {
pub name: &'a str,
pub flags: AnimationDescFlags,
pub fps: f32,
pub data: BTreeMap<usize, BoneAnimationData>,
}