rpfm_lib/files/rigidmodel/materials/mod.rs
1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! Material system for RigidModel files.
12//!
13//! # Overview
14//!
15//! Materials define how meshes are rendered in Total War games. Each material type
16//! has specific properties that control textures, shaders, vertex formats, and
17//! rendering behavior. The material system supports 40+ different material types
18//! for various rendering scenarios.
19//!
20//! # Material Types
21//!
22//! Materials are categorized by their rendering purpose:
23//!
24//! ## Standard Rendering
25//! - **DefaultMaterial (68)**: Full-featured material for most meshes
26//! - **Decal (71)**: Applied decals on surfaces
27//! - **Tree (74)**, **TreeLeaf (75)**: Vegetation rendering
28//! - **Grass (69)**: Grass
29//! - **Water (83)**: Water surfaces
30//! - **Unlit (84)**: No lighting calculations
31//!
32//! ## Skeletal Animation (Weighted)
33//! - **WeightedSkin (70)**: Character skin with bone weights
34//! - **WeightedCloth (58)**, **Cloth (60)**: Cloth simulation
35//! - **Weighted (65)**: Generic weighted material
36//!
37//! ## Terrain
38//! - **RsTerrain (66)**: Terrain block of the tiles' meshes (and, up to version 6, WeightedTextureBlend (96) and ProjectedDecalV4 (97))
39//! - **CustomTerrain (49)**, **GlobalTerrain (98)**: Terrain variants
40//! - **WeightedTextureBlend (96)**, **TerrainBlend (86)**: Texture blending
41//! - **TiledDirtmap (63)**: Tiled dirt textures
42//!
43//! ## Special Effects
44//! - **Collision (61)**, **CollisionShape (62)**: Collision meshes (invisible)
45//! - **DebugGeometry (46)**: Debug visualization
46//! - **PointLight (38)**, **StaticPointLight (45)**: Light sources
47//! - **Rope (93)**: Rope rendering
48//!
49//! ## Projected Decals
50//! - **ProjectedDecal (67)**, **ProjectedDecalV2 (87)**, **ProjectedDecalV3 (95)**, **ProjectedDecalV4 (97, from version 7)**
51//!
52//! # Material Data Structure
53//!
54//! Materials contain:
55//! - **Vertex format**: Determines vertex data layout
56//! - **Textures**: Diffuse, normal, specular, masks, etc.
57//! - **Transformation matrices**: 3x4 matrices for positioning/attachment
58//! - **Attachment points**: Named locations for effects/weapons
59//! - **Shader parameters**: Strings, floats, integers, vectors
60//! - **Cloth-specific data**: Physics simulation parameters (cloth materials only)
61//!
62//! # Texture Types
63//!
64//! Materials reference textures by type:
65//! - **Diffuse (0)**: Base color texture
66//! - **Normal (1)**: Normal mapping for surface detail
67//! - **Specular (11)**, **GlossMap (12)**: Reflectivity
68//! - **Mask (3)**: Alpha/transparency mask
69//! - **AmbientOcclusion (5)**: Baked ambient lighting
70//! - **Decal variants**: Special decal textures
71//!
72//! # Implementation Details
73//!
74//! Different material types have different data structures:
75//! - **Default materials**: Full data (textures, params, attachment points)
76//! - **RsTerrain**: Minimal (name + 5 unknown u32 fields)
77//! - **WeightedTextureBlend**: Name + 6 unknown u32 fields
78//! - **AlphaBlend**: Name only
79//! - **Cloth**: Default data + cloth simulation sections (cloth_links, cloth_triangle_counts, cloth_triangles)
80//!
81//! See individual material variant modules for format-specific details.
82
83use std::io::Cursor;
84
85use getset::{Getters, MutGetters, Setters};
86use nalgebra::{Matrix3x4, Vector3, Vector4};
87use serde::{Deserialize, Serialize};
88
89use crate::binary::{ReadBytes, WriteBytes};
90use crate::error::{Result, RLibError};
91
92use super::vertices::VertexFormat;
93use super::{PADDED_SIZE_32, PADDED_SIZE_256};
94
95mod alpha_blend;
96mod cloth;
97mod collision_shape;
98mod custom_terrain;
99mod default;
100mod rs_terrain;
101mod rope;
102mod rs_river;
103mod static_point_light;
104mod texture_combo;
105mod uk_27;
106mod uk_54;
107mod weighted_cloth;
108mod projected_decal;
109mod projected_decal_v4;
110mod weighted_texture_blend;
111
112#[cfg(test)] mod materials_test;
113
114//---------------------------------------------------------------------------//
115// Enum & Structs
116//---------------------------------------------------------------------------//
117
118/// Material type identifier determining rendering behavior and data structure.
119///
120/// Each material type corresponds to a specific shader and vertex format combination.
121/// The numeric value is stored in the RigidModel file format as a u16.
122///
123/// # Categories
124///
125/// - **22-46**: Effects and special materials (BowWave, PointLight, DebugGeometry)
126/// - **49-64**: Terrain and campaign materials
127/// - **65-82**: Weighted (skeletal) materials and variants
128/// - **83-100**: Water, unlit, terrain blends, projected decals
129#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
130#[repr(u16)]
131pub enum MaterialType {
132 /// Boat bow wave effect (water displacement).
133 BowWave = 22,
134 /// Non-rendered material (collision, occlusion, etc.).
135 NonRenderable = 26,
136 /// Unknown material, seen in an old test skybox.
137 Uk27 = 27,
138 /// Texture combo with vertex-based wind animation.
139 TextureComboVertexWind = 29,
140 /// Combined texture material.
141 TextureCombo = 30,
142 /// Waterfall decal effect.
143 DecalWaterfall = 31,
144 /// Simplified standard material.
145 StandardSimple = 32,
146 /// Campaign map tree rendering.
147 CampaignTrees = 34,
148 /// Dynamic point light source.
149 PointLight = 38,
150 /// Static baked point light.
151 StaticPointLight = 45,
152 /// Debug visualization geometry (wireframe, normals, etc.).
153 DebugGeometry = 46,
154 /// The older river block of the tiles' meshes, inner and outfield alike (the engine's `RS_RIVER_depreciated` in Rome 2, Attila
155 /// and Warhammer III): Rome 2's rivers and Attila's older tiles'.
156 RsRiverDeprecated = 48,
157 /// Unknown material, seen in some statues. Has no vertex format.
158 Uk54 = 54,
159 /// Unknown material, seen in the burning variant of some buildings. Has no vertex data, only indices into the vertices of another mesh.
160 Uk56 = 56,
161 /// Unknown material, seen in the rain variant of some buildings. Has no vertex data, only indices into the vertices of another mesh.
162 Uk57 = 57,
163 /// Custom terrain material variant.
164 CustomTerrain = 49,
165 /// Cloth material with skeletal weights and physics.
166 WeightedCloth = 58,
167 /// Cloth material with physics simulation.
168 Cloth = 60,
169 /// Collision mesh (invisible, physics only).
170 Collision = 61,
171 /// Collision shape variant.
172 CollisionShape = 62,
173 /// Tiled dirt texture mapping.
174 TiledDirtmap = 63,
175 /// Ship ambient mapping (possibly incorrect identification).
176 ShipAmbientmap = 64,
177 /// Generic weighted material (skeletal animation).
178 Weighted = 65,
179 /// Terrain block of the tiles' meshes (the engine's `RS_TERRAIN` in Rome 2, `RS_TERRAIN_depreciated` from Attila on).
180 RsTerrain = 66,
181 /// Projected decal (first version).
182 ProjectedDecal = 67,
183 /// Default full-featured material (most common).
184 #[default]
185 DefaultMaterial = 68,
186 /// Grass and vegetation material.
187 Grass = 69,
188 /// Weighted skin material (characters with bone weights).
189 WeightedSkin = 70,
190 /// Surface decal material.
191 Decal = 71,
192 /// Decal with dirt mapping.
193 DecalDirtmap = 72,
194 /// Dirt map material.
195 Dirtmap = 73,
196 /// Tree trunk/branch material.
197 Tree = 74,
198 /// Tree leaf material (alpha transparency).
199 TreeLeaf = 75,
200 /// Weighted decal (animated decals on characters).
201 WeightedDecal = 77,
202 /// Weighted decal with dirt mapping.
203 WeightedDecalDirtmap = 78,
204 /// Weighted dirt mapping.
205 WeightedDirtmap = 79,
206 /// Weighted skin with decal overlay.
207 WeightedSkinDecal = 80,
208 /// Weighted skin with decal and dirt mapping.
209 WeightedSkinDecalDirtmap = 81,
210 /// Weighted skin with dirt mapping.
211 WeightedSkinDirtmap = 82,
212 /// Water surface material.
213 Water = 83,
214 /// Unlit material (no lighting calculations, full bright).
215 Unlit = 84,
216 /// Weighted unlit material.
217 WeightedUnlit = 85,
218 /// Terrain texture blending material.
219 TerrainBlend = 86,
220 /// Projected decal version 2.
221 ProjectedDecalV2 = 87,
222 /// Ignored/placeholder material.
223 Ignore = 88,
224 /// Billboard-style tree material (always faces camera).
225 TreeBillboardMaterial = 89,
226 /// River block of the tiles' meshes (the engine's `RS_RIVER`): Attila's rivers.
227 RsRiver = 90,
228 /// Water displacement volume (physics interaction).
229 WaterDisplaceVolume = 91,
230 /// Rope rendering material.
231 Rope = 93,
232 /// Campaign map vegetation.
233 CampaignVegetation = 94,
234 /// Projected decal version 3.
235 ProjectedDecalV3 = 95,
236 /// Weighted texture blending (the engine's `weighted_texture_blend` in Warhammer III). Up to version 6 (Attila, Thrones of
237 /// Britannia) this id is a terrain block of the tiles' meshes instead, the engine's `RS_TERRAIN_depreciated2`, laid out as
238 /// RsTerrain's.
239 WeightedTextureBlend = 96,
240 /// Projected decal version 4 (the engine's `projected_decal_v4` in Warhammer III). Up to version 6 (Attila, Thrones of Britannia)
241 /// this id is the terrain block of the tiles' meshes instead, the engine's `RS_TERRAIN`, as BOB writes them: RsTerrain's layout
242 /// with the block's index count.
243 ProjectedDecalV4 = 97,
244 /// Global terrain material.
245 GlobalTerrain = 98,
246 /// Overlay decal material.
247 DecalOverlay = 99,
248 /// Alpha-blended material.
249 AlphaBlend = 100,
250}
251
252/// Complete material definition with textures, transforms, and shader parameters.
253///
254/// Materials contain all rendering data except geometry. The exact fields present
255/// depend on the material type - some types use only a subset of these fields.
256///
257/// # Field Organization
258///
259/// - **Identification**: `vertex_format`, `name`
260/// - **Unknown fields**: `uk_1` through `uk_6` (only in certain material types)
261/// - **Textures**: `texture_directory`, `textures` list
262/// - **Transforms**: `v_pivot`, `matrix1/2/3`, matrix indices
263/// - **Attachments**: `attachment_points` for effects/weapons
264/// - **Shader params**: `params_string`, `params_f32`, `params_i32`, `params_vector4df32`
265/// - **Cloth physics**: `cloth_links`, `cloth_triangle_counts`, `cloth_triangles` (cloth materials only)
266///
267/// # Matrix Storage
268///
269/// 3x4 matrices are stored in the same format as skeleton bind pose matrices.
270/// The implicit fourth row `[0, 0, 0, 1]` must be added when converting to 4x4.
271#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
272#[getset(get = "pub", get_mut = "pub", set = "pub")]
273pub struct Material {
274 /// Vertex format determining vertex data layout.
275 vertex_format: VertexFormat,
276
277 /// Material name (human-readable identifier).
278 name: String,
279
280 /// Second name, only in materials of types 56 and 57: the name of the mesh followed by a suffix, like `burning` or `rain`.
281 name2: String,
282
283 /// Bytes found after the end of `name` in its padded field, usually leftovers of the program that wrote the file.
284 /// They're kept so the file is written back as it was.
285 name_padding: Vec<u8>,
286
287 /// Terrain blocks (RsTerrain, and up to version 6 ProjectedDecalV4): the tile's size in metres along x.
288 /// Projected decals, WeightedTextureBlend: unknown. WeightedCloth, CollisionShape: 0 in every Attila file.
289 uk_1: u32,
290 /// Terrain blocks: the tile's size in metres along z. ProjectedDecalV2/V3, WeightedTextureBlend: unknown.
291 uk_2: u32,
292 /// Terrain blocks: the height samples per row (the size along x plus 1). ProjectedDecalV2/V3, WeightedTextureBlend: unknown.
293 uk_3: u32,
294 /// Terrain blocks: 1 in every file. ProjectedDecalV3: the decal box's turn about y in radians, an f32 stored as its bits
295 /// (`f32::from_bits`). WeightedTextureBlend: unknown.
296 uk_4: u32,
297 /// Terrain blocks: 16 in every file. WeightedTextureBlend: unknown.
298 uk_5: u32,
299 /// ProjectedDecalV4 up to version 6 (a terrain block): the block's index count (BOB counts the indices of its surface triangles).
300 /// WeightedTextureBlend: unknown.
301 uk_6: u32,
302
303 /// Directory path for texture files (relative to game data directory).
304 texture_directory: String,
305
306 /// Filter settings (NOT part of file format, runtime-only).
307 filters: String,
308
309 /// Padding byte 0 (alignment/reserved).
310 padding_byte0: u8,
311 /// Padding byte 1 (alignment/reserved).
312 padding_byte1: u8,
313
314 /// Pivot point for transformations.
315 v_pivot: Vector3<f32>,
316
317 /// Center of the box a projected decal is projected in.
318 decal_center: Vector3<f32>,
319
320 /// Size of the box a projected decal is projected in.
321 decal_size: Vector3<f32>,
322
323 /// Center of the sphere around a collision shape.
324 sphere_center: Vector3<f32>,
325
326 /// Radius of the sphere around a collision shape.
327 sphere_radius: f32,
328
329 /// Bones of the cloth simulation of weighted cloth materials.
330 cloth_bones: Vec<ClothBone>,
331
332 /// Simulation data of rope materials.
333 rope: Rope,
334
335 /// Transform matrix 1 (3x4, implicit 4th row: [0, 0, 0, 1]).
336 matrix1: Matrix3x4<f32>,
337 /// Transform matrix 2 (3x4, implicit 4th row: [0, 0, 0, 1]).
338 matrix2: Matrix3x4<f32>,
339 /// Transform matrix 3 (3x4, implicit 4th row: [0, 0, 0, 1]).
340 matrix3: Matrix3x4<f32>,
341
342 /// Matrix index in hierarchy.
343 i_matrix_index: i32,
344 /// Parent matrix index for hierarchical transforms.
345 i_parent_matrix_index: i32,
346
347 /// Additional padding bytes (variable length).
348 sz_padding: Vec<u8>,
349
350 /// Named attachment points for weapons, effects, banners, etc.
351 attachment_points: Vec<AttachmentPointEntry>,
352
353 /// Texture list with type and path for each texture.
354 textures: Vec<Texture>,
355
356 /// String shader parameters (index, value pairs).
357 params_string: Vec<(i32, String)>,
358 /// Float shader parameters (index, value pairs).
359 params_f32: Vec<(i32, f32)>,
360 /// Integer shader parameters (index, value pairs).
361 params_i32: Vec<(i32, i32)>,
362 /// Vector4 shader parameters (index, value pairs).
363 params_vector4df32: Vec<(i32, Vector4<f32>)>,
364
365 /// Cloth materials: the simulation's distance constraints over the particles (the mesh's first `cloth_triangle_counts.len()`
366 /// vertices), every triangle edge plus one bend link per pair of adjacent triangles, solved in this order.
367 cloth_links: Vec<ClothLink>,
368 /// Cloth materials: per particle, the number of triangles touching it. Its length is the particle count.
369 cloth_triangle_counts: Vec<ClothTriangleCount>,
370 /// Cloth materials: the triangles touching each particle, particle after particle (`cloth_triangle_counts` of them each). Used for
371 /// the particles' normals and frames, not for the dynamics.
372 cloth_triangles: Vec<ClothTriangle>,
373}
374
375/// Named attachment point for visual effects, weapons, or equipment.
376///
377/// Attachment points define locations on a model where other objects can be attached,
378/// such as weapon hardpoints, banner poles, or particle effect emitters.
379#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
380#[getset(get = "pub", get_mut = "pub", set = "pub")]
381pub struct AttachmentPointEntry {
382 /// Attachment point name (e.g., "weapon_1", "engine_exhaust").
383 name: String,
384
385 /// 3x4 transform matrix positioning the attachment point (implicit 4th row: [0, 0, 0, 1]).
386 matrix: Matrix3x4<f32>,
387
388 /// Bone ID for skeletal attachment (0 for non-skeletal).
389 bone_id: u32,
390}
391
392/// Texture reference with type and file path.
393/// The simulation data of a rope material: a chain of nodes joined by links.
394#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
395#[getset(get = "pub", get_mut = "pub", set = "pub")]
396pub struct Rope {
397
398 /// Unknown indices, or -1. Likely what the rope is attached to.
399 attachments: Vector4<i32>,
400
401 /// Half the width of the drawn rope ribbon, in model units (around 0.03). The simulation doesn't read it.
402 half_width: f32,
403
404 /// Probably the node released when the rope breaks under ship damage (0, 3, 8, 16, 32 or 64): the game frees this node and
405 /// detaches the rope entry with it. Not checked in game.
406 break_node: u32,
407
408 /// Nodes of the rope, from one end to the other.
409 nodes: Vec<RopeNode>,
410
411 /// Links between consecutive nodes. There's always one fewer than nodes.
412 links: Vec<RopeLink>,
413}
414
415/// A node of a rope.
416#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
417#[getset(get = "pub", get_mut = "pub", set = "pub")]
418pub struct RopeNode {
419
420 /// Position of the node.
421 position: Vector3<f32>,
422
423 /// Weight of the node in the simulation: 0 for the pinned ends, 1 for the rest.
424 weight: f32,
425
426 /// Texture coordinate v of the node along the rope, decreasing from one end to the other. The simulation doesn't read it.
427 texture_v: f32,
428}
429
430/// A link between two nodes of a rope.
431#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
432#[getset(get = "pub", get_mut = "pub", set = "pub")]
433pub struct RopeLink {
434
435 /// Index of the first node.
436 node_a: u32,
437
438 /// Index of the second node.
439 node_b: u32,
440
441 /// Length of the link.
442 length: f32,
443}
444
445/// A bone of the cloth simulation of a weighted cloth material, attached to a vertex of its mesh.
446#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
447#[getset(get = "pub", get_mut = "pub", set = "pub")]
448pub struct ClothBone {
449
450 /// Name of the bone.
451 name: String,
452
453 /// Bytes found after the end of `name` in its padded field, usually leftovers of the program that wrote the file.
454 /// They're kept so the file is written back as it was.
455 name_padding: Vec<u8>,
456
457 /// Unknown values. (100, 200, 400) in every Attila file.
458 uk_1: Vector3<f32>,
459
460 /// Unknown value. 12 in every Attila file.
461 uk_2: u32,
462
463 /// Unknown value. 64 in every Attila file.
464 uk_3: u32,
465
466 /// Unknown value, the same for all the bones of a mesh: likely a pointer the exporter left behind.
467 uk_4: u32,
468
469 /// Unknown value. 24 or 25.
470 uk_5: u32,
471
472 /// Unknown value. 24 or 25.
473 uk_6: u32,
474
475 /// 1 when the bone's particle is free, 0 when it's pinned: a copy of the pin state of its simulation vertex.
476 free: f32,
477
478 /// Transform of the bone.
479 matrix: Matrix3x4<f32>,
480
481 /// Index of the parent bone, or -1.
482 parent_index: i32,
483
484 /// Index of the vertex of the mesh the bone is attached to.
485 vertex_index: u32,
486}
487
488#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
489#[getset(get = "pub", get_mut = "pub", set = "pub")]
490pub struct Texture {
491 /// Texture type/slot (diffuse, normal, specular, etc.).
492 tex_type: TextureType,
493
494 /// Relative path to texture file (from `texture_directory`).
495 path: String,
496}
497
498/// Texture type identifier for shader texture slots.
499///
500/// Determines which shader texture slot this texture is bound to during rendering.
501/// The numeric value is stored as an i32 in the file format.
502#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
503#[repr(i32)]
504pub enum TextureType {
505 /// Base color/albedo texture.
506 #[default]
507 Diffuse = 0,
508 /// Normal map for surface detail (tangent space).
509 Normal = 1,
510 /// Alpha/transparency mask.
511 Mask = 3,
512 /// Material map of older games, like Rome II and Attila.
513 LegacyMaterialMap = 4,
514 /// Baked ambient occlusion.
515 AmbientOcclusion = 5,
516 /// Tessellation displacement map (red channel: the offset along the normal), bound as `t_tesselation_displacement_map` by the
517 /// Rome II / Attila / Thrones of Britannia engine when tessellation is enabled.
518 Displacement = 6,
519 /// Tiling dirt texture (UV set 2).
520 TilingDirtUV2 = 7,
521 /// Dirt alpha mask.
522 DirtAlphaMask = 8,
523 /// Skin mask texture.
524 SkinMask = 10,
525 /// Specular reflectivity map.
526 Specular = 11,
527 /// Gloss/smoothness map (specular roughness).
528 GlossMap = 12,
529 /// Decal dirt map.
530 DecalDirtmap = 13,
531 /// Decal dirt mask.
532 DecalDirtmask = 14,
533 /// Decal alpha mask.
534 DecalMask = 15,
535 /// Damaged diffuse texture variant.
536 DiffuseDamage = 17,
537 /// PBR base color.
538 BaseColor = 27,
539 /// PBR material properties (metallic/roughness/AO packed).
540 MaterialMap = 29,
541}
542
543/// A distance constraint of a cloth simulation between two of its particles.
544#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
545#[getset(get = "pub", get_mut = "pub", set = "pub")]
546pub struct ClothLink {
547 /// Index of the first particle.
548 particle_a: i32,
549 /// Index of the second particle.
550 particle_b: i32,
551 /// Rest length of the link: the particles' distance at rest.
552 rest_length: f32,
553}
554
555/// The number of triangles of a cloth simulation touching one of its particles.
556#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
557#[getset(get = "pub", get_mut = "pub", set = "pub")]
558pub struct ClothTriangleCount {
559 /// Number of triangles touching the particle.
560 count: i32,
561}
562
563/// A triangle of a cloth simulation, by the indices of its three particles.
564#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
565#[getset(get = "pub", get_mut = "pub", set = "pub")]
566pub struct ClothTriangle {
567 /// Index of the first particle.
568 index_0: i32,
569 /// Index of the second particle.
570 index_1: i32,
571 /// Index of the third particle.
572 index_2: i32,
573}
574
575//---------------------------------------------------------------------------//
576// Implementation
577//---------------------------------------------------------------------------//
578
579
580impl Material {
581
582 /// Reads a material from binary data based on the material type.
583 ///
584 /// Different material types have different binary layouts, which may change between
585 /// versions of the RigidModel format. This function dispatches to the appropriate reader.
586 ///
587 /// # Errors
588 ///
589 /// Returns [`RLibError::DecodingRigidModelUnsupportedMaterialType`] if the
590 /// material type is not supported.
591 pub fn read<R: ReadBytes>(data: &mut R, version: u32, mtype: MaterialType) -> Result<Self> {
592 Ok(match mtype {
593 MaterialType::RsTerrain => Self::read_rs_terrain(data, version)?,
594 MaterialType::BowWave |
595 MaterialType::DebugGeometry |
596 MaterialType::RsRiverDeprecated |
597 MaterialType::RsRiver => Self::read_rs_river(data, version)?,
598 MaterialType::WeightedTextureBlend => Self::read_weighted_texture_blend(data, version)?,
599 MaterialType::ProjectedDecalV4 if version <= 6 => Self::read_projected_decal_v4(data, version)?,
600 MaterialType::ProjectedDecal |
601 MaterialType::ProjectedDecalV2 |
602 MaterialType::ProjectedDecalV3 => Self::read_projected_decal(data, version, mtype)?,
603 MaterialType::CustomTerrain => Self::read_custom_terrain(data, version)?,
604 MaterialType::CollisionShape => Self::read_collision_shape(data, version)?,
605 MaterialType::WeightedCloth if version <= 6 => Self::read_weighted_cloth(data, version)?,
606 MaterialType::Rope if version <= 6 => Self::read_rope(data, version)?,
607 MaterialType::TextureCombo |
608 MaterialType::TextureComboVertexWind => Self::read_texture_combo(data, version)?,
609 MaterialType::StaticPointLight => Self::read_static_point_light(data, version)?,
610 MaterialType::Uk27 => Self::read_uk_27(data, version)?,
611 MaterialType::Uk54 |
612 MaterialType::Uk56 |
613 MaterialType::Uk57 => Self::read_uk_54(data, version, mtype)?,
614 MaterialType::AlphaBlend => Self::read_alpha_blend(data, version)?,
615 MaterialType::Cloth => Self::read_cloth(data, version)?,
616 MaterialType::ProjectedDecalV4 |
617 MaterialType::Water |
618 MaterialType::TiledDirtmap |
619 MaterialType::ShipAmbientmap |
620 MaterialType::TerrainBlend |
621 MaterialType::Weighted |
622 MaterialType::Grass |
623 MaterialType::WeightedSkin |
624 MaterialType::Decal |
625 MaterialType::DecalDirtmap |
626 MaterialType::Dirtmap |
627 MaterialType::Tree |
628 MaterialType::TreeLeaf |
629 MaterialType::WeightedDecal |
630 MaterialType::WeightedDecalDirtmap |
631 MaterialType::WeightedDirtmap |
632 MaterialType::WeightedSkinDirtmap |
633 MaterialType::Unlit |
634 MaterialType::TreeBillboardMaterial |
635 MaterialType::WaterDisplaceVolume |
636 MaterialType::CampaignVegetation |
637 MaterialType::DefaultMaterial => Self::read_default(data, version)?,
638 _ => return Err(RLibError::DecodingRigidModelUnsupportedMaterialType(mtype.into()))
639 })
640 }
641
642 /// Writes a material to binary data based on the material type.
643 ///
644 /// Different material types have different binary layouts, which may change between
645 /// versions of the RigidModel format. This function dispatches to the appropriate writer.
646 ///
647 /// # Errors
648 ///
649 /// Returns [`RLibError::DecodingRigidModelUnsupportedMaterialType`] if the
650 /// material type is not supported.
651 pub fn write<W: WriteBytes>(&self, buffer: &mut W, version: u32, mtype: MaterialType) -> Result<()> {
652 match mtype {
653 MaterialType::RsTerrain => self.write_rs_terrain(buffer, version)?,
654 MaterialType::BowWave |
655 MaterialType::DebugGeometry |
656 MaterialType::RsRiverDeprecated |
657 MaterialType::RsRiver => self.write_rs_river(buffer, version)?,
658 MaterialType::WeightedTextureBlend => self.write_weighted_texture_blend(buffer, version)?,
659 MaterialType::ProjectedDecalV4 if version <= 6 => self.write_projected_decal_v4(buffer, version)?,
660 MaterialType::ProjectedDecal |
661 MaterialType::ProjectedDecalV2 |
662 MaterialType::ProjectedDecalV3 => self.write_projected_decal(buffer, version, mtype)?,
663 MaterialType::CustomTerrain => self.write_custom_terrain(buffer, version)?,
664 MaterialType::CollisionShape => self.write_collision_shape(buffer, version)?,
665 MaterialType::WeightedCloth if version <= 6 => self.write_weighted_cloth(buffer, version)?,
666 MaterialType::Rope if version <= 6 => self.write_rope(buffer, version)?,
667 MaterialType::TextureCombo |
668 MaterialType::TextureComboVertexWind => self.write_texture_combo(buffer, version)?,
669 MaterialType::StaticPointLight => self.write_static_point_light(buffer, version)?,
670 MaterialType::Uk27 => self.write_uk_27(buffer, version)?,
671 MaterialType::Uk54 |
672 MaterialType::Uk56 |
673 MaterialType::Uk57 => self.write_uk_54(buffer, version, mtype)?,
674 MaterialType::AlphaBlend => self.write_alpha_blend(buffer, version)?,
675 MaterialType::Cloth => self.write_cloth(buffer, version)?,
676 MaterialType::ProjectedDecalV4 |
677 MaterialType::Water |
678 MaterialType::TiledDirtmap |
679 MaterialType::ShipAmbientmap |
680 MaterialType::TerrainBlend |
681 MaterialType::Weighted |
682 MaterialType::Grass |
683 MaterialType::WeightedSkin |
684 MaterialType::Decal |
685 MaterialType::DecalDirtmap |
686 MaterialType::Dirtmap |
687 MaterialType::Tree |
688 MaterialType::TreeLeaf |
689 MaterialType::WeightedDecal |
690 MaterialType::WeightedDecalDirtmap |
691 MaterialType::WeightedDirtmap |
692 MaterialType::WeightedSkinDirtmap |
693 MaterialType::Unlit |
694 MaterialType::TreeBillboardMaterial |
695 MaterialType::WaterDisplaceVolume |
696 MaterialType::CampaignVegetation |
697 MaterialType::DefaultMaterial => self.write_default(buffer, version)?,
698 _ => return Err(RLibError::DecodingRigidModelUnsupportedMaterialType(mtype.into()))
699 }
700
701 Ok(())
702 }
703}
704
705impl TryFrom<u16> for MaterialType {
706 type Error = RLibError;
707 fn try_from(value: u16) -> Result<Self> {
708 match value {
709 _ if value == Self::BowWave as u16 => Ok(Self::BowWave),
710 _ if value == Self::NonRenderable as u16 => Ok(Self::NonRenderable),
711 _ if value == Self::Uk27 as u16 => Ok(Self::Uk27),
712 _ if value == Self::TextureComboVertexWind as u16 => Ok(Self::TextureComboVertexWind),
713 _ if value == Self::TextureCombo as u16 => Ok(Self::TextureCombo),
714 _ if value == Self::DecalWaterfall as u16 => Ok(Self::DecalWaterfall),
715 _ if value == Self::StandardSimple as u16 => Ok(Self::StandardSimple),
716 _ if value == Self::CampaignTrees as u16 => Ok(Self::CampaignTrees),
717 _ if value == Self::PointLight as u16 => Ok(Self::PointLight),
718 _ if value == Self::StaticPointLight as u16 => Ok(Self::StaticPointLight),
719 _ if value == Self::DebugGeometry as u16 => Ok(Self::DebugGeometry),
720 _ if value == Self::RsRiverDeprecated as u16 => Ok(Self::RsRiverDeprecated),
721 _ if value == Self::Uk54 as u16 => Ok(Self::Uk54),
722 _ if value == Self::Uk56 as u16 => Ok(Self::Uk56),
723 _ if value == Self::Uk57 as u16 => Ok(Self::Uk57),
724 _ if value == Self::CustomTerrain as u16 => Ok(Self::CustomTerrain),
725 _ if value == Self::WeightedCloth as u16 => Ok(Self::WeightedCloth),
726 _ if value == Self::Cloth as u16 => Ok(Self::Cloth),
727 _ if value == Self::Collision as u16 => Ok(Self::Collision),
728 _ if value == Self::CollisionShape as u16 => Ok(Self::CollisionShape),
729 _ if value == Self::TiledDirtmap as u16 => Ok(Self::TiledDirtmap),
730 _ if value == Self::ShipAmbientmap as u16 => Ok(Self::ShipAmbientmap),
731 _ if value == Self::Weighted as u16 => Ok(Self::Weighted),
732 _ if value == Self::RsTerrain as u16 => Ok(Self::RsTerrain),
733 _ if value == Self::ProjectedDecal as u16 => Ok(Self::ProjectedDecal),
734 _ if value == Self::DefaultMaterial as u16 => Ok(Self::DefaultMaterial),
735 _ if value == Self::Grass as u16 => Ok(Self::Grass),
736 _ if value == Self::WeightedSkin as u16 => Ok(Self::WeightedSkin),
737 _ if value == Self::Decal as u16 => Ok(Self::Decal),
738 _ if value == Self::DecalDirtmap as u16 => Ok(Self::DecalDirtmap),
739 _ if value == Self::Dirtmap as u16 => Ok(Self::Dirtmap),
740 _ if value == Self::Tree as u16 => Ok(Self::Tree),
741 _ if value == Self::TreeLeaf as u16 => Ok(Self::TreeLeaf),
742 _ if value == Self::WeightedDecal as u16 => Ok(Self::WeightedDecal),
743 _ if value == Self::WeightedDecalDirtmap as u16 => Ok(Self::WeightedDecalDirtmap),
744 _ if value == Self::WeightedDirtmap as u16 => Ok(Self::WeightedDirtmap),
745 _ if value == Self::WeightedSkinDecal as u16 => Ok(Self::WeightedSkinDecal),
746 _ if value == Self::WeightedSkinDecalDirtmap as u16 => Ok(Self::WeightedSkinDecalDirtmap),
747 _ if value == Self::WeightedSkinDirtmap as u16 => Ok(Self::WeightedSkinDirtmap),
748 _ if value == Self::Water as u16 => Ok(Self::Water),
749 _ if value == Self::Unlit as u16 => Ok(Self::Unlit),
750 _ if value == Self::WeightedUnlit as u16 => Ok(Self::WeightedUnlit),
751 _ if value == Self::TerrainBlend as u16 => Ok(Self::TerrainBlend),
752 _ if value == Self::ProjectedDecalV2 as u16 => Ok(Self::ProjectedDecalV2),
753 _ if value == Self::Ignore as u16 => Ok(Self::Ignore),
754 _ if value == Self::TreeBillboardMaterial as u16 => Ok(Self::TreeBillboardMaterial),
755 _ if value == Self::RsRiver as u16 => Ok(Self::RsRiver),
756 _ if value == Self::WaterDisplaceVolume as u16 => Ok(Self::WaterDisplaceVolume),
757 _ if value == Self::Rope as u16 => Ok(Self::Rope),
758 _ if value == Self::CampaignVegetation as u16 => Ok(Self::CampaignVegetation),
759 _ if value == Self::ProjectedDecalV3 as u16 => Ok(Self::ProjectedDecalV3),
760 _ if value == Self::WeightedTextureBlend as u16 => Ok(Self::WeightedTextureBlend),
761 _ if value == Self::ProjectedDecalV4 as u16 => Ok(Self::ProjectedDecalV4),
762 _ if value == Self::GlobalTerrain as u16 => Ok(Self::GlobalTerrain),
763 _ if value == Self::DecalOverlay as u16 => Ok(Self::DecalOverlay),
764 _ if value == Self::AlphaBlend as u16 => Ok(Self::AlphaBlend),
765 _ => Err(RLibError::DecodingRigidModelUnsupportedMaterialType(value))
766 }
767 }
768}
769
770impl From<MaterialType> for u16 {
771 fn from(value: MaterialType) -> u16 {
772 value as u16
773 }
774}
775
776impl TryFrom<i32> for TextureType {
777 type Error = RLibError;
778 fn try_from(value: i32) -> Result<Self> {
779 match value {
780 _ if value == Self::Diffuse as i32 => Ok(Self::Diffuse),
781 _ if value == Self::Normal as i32 => Ok(Self::Normal),
782 _ if value == Self::Mask as i32 => Ok(Self::Mask),
783 _ if value == Self::LegacyMaterialMap as i32 => Ok(Self::LegacyMaterialMap),
784 _ if value == Self::AmbientOcclusion as i32 => Ok(Self::AmbientOcclusion),
785 _ if value == Self::Displacement as i32 => Ok(Self::Displacement),
786 _ if value == Self::TilingDirtUV2 as i32 => Ok(Self::TilingDirtUV2),
787 _ if value == Self::DirtAlphaMask as i32 => Ok(Self::DirtAlphaMask),
788 _ if value == Self::SkinMask as i32 => Ok(Self::SkinMask),
789 _ if value == Self::Specular as i32 => Ok(Self::Specular),
790 _ if value == Self::GlossMap as i32 => Ok(Self::GlossMap),
791 _ if value == Self::DecalDirtmap as i32 => Ok(Self::DecalDirtmap),
792 _ if value == Self::DecalDirtmask as i32 => Ok(Self::DecalDirtmask),
793 _ if value == Self::DecalMask as i32 => Ok(Self::DecalMask),
794 _ if value == Self::DiffuseDamage as i32 => Ok(Self::DiffuseDamage),
795 _ if value == Self::BaseColor as i32 => Ok(Self::BaseColor),
796 _ if value == Self::MaterialMap as i32 => Ok(Self::MaterialMap),
797 _ => Err(RLibError::DecodingRigidModelUnknownTextureType(value))
798 }
799 }
800}
801
802impl TryFrom<TextureType> for i32 {
803 type Error = RLibError;
804 fn try_from(value: TextureType) -> Result<i32> {
805 Ok(value as i32)
806 }
807}
808
809/// Reads a 0-padded string of `size` bytes, also returning the bytes after its NUL up to the last non-zero one.
810///
811/// The string is UTF-8, or UTF-16 if `utf16` is set.
812fn read_string_0padded_with_tail<R: ReadBytes>(data: &mut R, size: usize, utf16: bool) -> Result<(String, Vec<u8>)> {
813 let bytes = data.read_slice(size, false)?;
814 let char_size = if utf16 { 2 } else { 1 };
815 let len = bytes.chunks_exact(char_size).position(|char| char.iter().all(|x| *x == 0)).map_or(size, |chars| chars * char_size);
816 let tail_end = bytes.iter().rposition(|x| *x != 0).map_or(0, |last| last + 1);
817 let tail = if tail_end > len + char_size { bytes[len + char_size..tail_end].to_vec() } else { vec![] };
818
819 let string = if utf16 { Cursor::new(&bytes[..len]).read_string_u16(len)? } else { String::from_utf8(bytes[..len].to_vec())? };
820 Ok((string, tail))
821}
822
823/// Writes a 0-padded string of `size` bytes, with `tail` right after its NUL.
824///
825/// The string is UTF-8, or UTF-16 if `utf16` is set.
826fn write_string_0padded_with_tail<W: WriteBytes>(data: &mut W, string: &str, tail: &[u8], size: usize, utf16: bool) -> Result<()> {
827 let char_size = if utf16 { 2 } else { 1 };
828 let string_size = if utf16 { string.encode_utf16().count() * 2 } else { string.len() };
829 let used = string_size + if tail.is_empty() { 0 } else { char_size + tail.len() };
830 if used > size {
831 return Err(RLibError::EncodingPaddedStringError("0-Padded String".to_owned(), string.to_owned(), used, size));
832 }
833
834 if utf16 {
835 data.write_string_u16(string)?;
836 } else {
837 data.write_string_u8(string)?;
838 }
839
840 if !tail.is_empty() {
841 data.write_all(&vec![0; char_size])?;
842 data.write_all(tail)?;
843 }
844
845 data.write_all(&vec![0; size - used]).map_err(From::from)
846}
847
848/// Reads a 0-padded string of `size` characters: one byte each, or two in version 5 RigidModels, which use UTF-16.
849fn read_padded_string<R: ReadBytes>(data: &mut R, version: u32, size: usize) -> Result<String> {
850 if version <= 5 {
851 data.read_string_u16_0padded(size * 2)
852 } else {
853 data.read_string_u8_0padded(size)
854 }
855}
856
857/// Writes a 0-padded string of `size` characters: one byte each, or two in version 5 RigidModels, which use UTF-16.
858fn write_padded_string<W: WriteBytes>(data: &mut W, version: u32, string: &str, size: usize) -> Result<()> {
859 if version <= 5 {
860 data.write_string_u16_0padded(string, size * 2, true)
861 } else {
862 data.write_string_u8_0padded(string, size, true)
863 }
864}