aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/model_materials.rs
blob: 8e44dde793797096dfc210280665c40b00d8da23 (plain) (blame)
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
//! Scene and instrument variants of a model's authored materials.

use super::{
    page_uv_transform, phase_texture_name, phase_uv_transforms_from_assets,
    prepared_texture_to_vulkan, solid_environment_texture, MaterialAnimationBinding,
    MaterialPhaseBinding, MaterialVariantSet, MissionAssets, PreparedTextureUsage, PreparedVisual,
    VulkanStaticMaterial, VulkanStaticMesh,
};
use fparkan_material::MaterialCoefficients;
use fparkan_render::cockpit_lighting::CAMERA_ADDITIVE;

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum ModelMaterialStyle {
    Scene,
    #[cfg(windows)]
    Instrument,
}

pub(super) fn apply_instrument_camera_color(coefficients: &mut MaterialCoefficients) {
    // Terrain+0x29b90 replaces the material's additive color and opacity.
    coefficients.additive_rgb = CAMERA_ADDITIVE;
    coefficients.opacity = 1.0;
}

pub(super) fn static_preview_component_materials(
    assets: &MissionAssets,
    visual: &PreparedVisual,
    mesh: &VulkanStaticMesh,
    static_material_phase: Option<u16>,
    materials: &mut Vec<VulkanStaticMaterial>,
    material_animations: &mut Vec<MaterialAnimationBinding>,
    style: ModelMaterialStyle,
) -> Result<Vec<(u16, u16)>, String> {
    let instrument = match style {
        ModelMaterialStyle::Scene => false,
        #[cfg(windows)]
        ModelMaterialStyle::Instrument => true,
    };
    let mut source_selectors = mesh
        .draw_ranges
        .iter()
        .map(|range| range.material_index)
        .collect::<Vec<_>>();
    source_selectors.sort_unstable();
    source_selectors.dedup();
    source_selectors
        .into_iter()
        .map(|source_selector| {
            let material_id = visual
                .material_ids
                .get(usize::from(source_selector))
                .ok_or_else(|| {
                    format!(
                        "static preview MSH batch selector {source_selector} has no prepared WEAR material"
                    )
                })?;
            let material = assets.material_by_id(*material_id).ok_or_else(|| {
                format!("static preview prepared material {source_selector} is unavailable")
            })?;
            let pipeline_category = if instrument {
                0
            } else {
                material.pipeline_category
            };
            let initial_phase_index = usize::from(static_material_phase.unwrap_or(0))
                .min(material.mat0.phases.len().saturating_sub(1));
            if material.mat0.phases.is_empty() {
                return Err(format!(
                    "static preview material {source_selector} has no MAT0 phases"
                ));
            }
            let mut phase_material_indices = Vec::with_capacity(material.mat0.phases.len());
            for phase in &material.mat0.phases {
                let texture_name = if instrument {
                    None
                } else {
                    phase_texture_name(phase)
                };
                let prepared_texture = texture_name.as_ref().and_then(|name| {
                    assets.textures.iter().find(|texture| {
                        texture.usage == PreparedTextureUsage::Diffuse
                            && texture.source.name == *name
                    })
                });
                // Empty MAT0 texture names remain valid untextured materials.
                let texture = prepared_texture
                    .map(|texture| {
                        prepared_texture_to_vulkan(texture, "static preview diffuse texture")
                    })
                    .transpose()?
                    .unwrap_or_else(|| solid_environment_texture([255, 255, 255, 255]));
                let mut coefficients = phase.coefficients();
                if instrument {
                    apply_instrument_camera_color(&mut coefficients);
                }
                let uv_transform = if let Some(texture) = prepared_texture {
                    page_uv_transform(
                        texture.texm.width(),
                        texture.texm.height(),
                        &texture.texm.page_rects(),
                        coefficients.page_index,
                    )?
                } else {
                    [0.0, 0.0, 1.0, 1.0]
                };
                let preview_selector = u16::try_from(materials.len()).map_err(|_| {
                    "static preview exceeds the available 16-bit material selector space"
                        .to_string()
                })?;
                materials.push(VulkanStaticMaterial {
                    material_index: preview_selector,
                    pipeline_category,
                    texture,
                    detail_texture: None,
                    overlay_texture: None,
                    overlay_detail_texture: None,
                    diffuse_alpha: coefficients.opacity,
                    overlay_diffuse_alpha: None,
                    directional_rgb: coefficients.directional_rgb,
                    additive_rgb: coefficients.additive_rgb,
                    uv_transform,
                    overlay_directional_rgb: None,
                    overlay_additive_rgb: None,
                    specular_rgb: coefficients.specular_rgb,
                    specular_power: coefficients.power,
                    overlay_specular_rgb: None,
                    overlay_specular_power: None,
                    detail_uv_transform: [0.0, 0.0, 1.0, 1.0],
                    overlay_uv_transform: None,
                    overlay_detail_uv_transform: None,
                    unlit: false,
                    sky_nebula_stars: false,
                    lightmap_mode: false,
                    sky_far_depth: false,
                    screen_tl: false,
                });
                phase_material_indices.push(usize::from(preview_selector));
            }
            let preview_selector = u16::try_from(
                *phase_material_indices
                    .get(initial_phase_index)
                    .ok_or_else(|| "MAT0 phase variant table is empty".to_string())?,
            )
            .map_err(|_| "MAT0 phase variant selector exceeds u16".to_string())?;
            material_animations.push(MaterialAnimationBinding {
                initial_phase_index,
                normalized_phase_override: None,
                ambient_fx_material_alpha: false,
                cockpit_instrument: instrument,
                variants: vec![MaterialVariantSet {
                    phase_material_indices,
                    range_indices: Vec::new(),
                    pipeline_category,
                }],
                base: MaterialPhaseBinding {
                    document: material.mat0.clone(),
                    animation_block_index: 0,
                    wear_row_start_ms: 0,
                    random_state: material_id.raw() as u32,
                    frozen_phase_index: static_material_phase.map(usize::from),
                    phase_uv_transforms: if instrument {
                        vec![[0.0, 0.0, 1.0, 1.0]; material.mat0.phases.len()]
                    } else {
                        phase_uv_transforms_from_assets(&material.mat0, assets)
                    },
                },
                detail: None,
                overlay: None,
                overlay_detail: None,
                stage_textures: None,
            });
            Ok((source_selector, preview_selector))
        })
        .collect()
}

#[cfg(test)]
#[test]
fn instrument_camera_replaces_the_base_color_and_opacity() {
    let phase = fparkan_material::MaterialPhase {
        parameters: [100; 18],
        texture_raw: [0; 16],
    };
    let original = phase.coefficients();
    let mut instrument = original;
    apply_instrument_camera_color(&mut instrument);
    assert_eq!(instrument.additive_rgb, [0.0, 0.5, 0.0]);
    assert_eq!(instrument.opacity, 1.0);
    assert_eq!(instrument.directional_rgb, original.directional_rgb);
    assert_eq!(instrument.specular_rgb, original.specular_rgb);
    assert_eq!(instrument.power, original.power);
}