aboutsummaryrefslogtreecommitdiff
path: root/apps/fparkan-game/src/object_render.rs
blob: 2655bc21d9cc20aee19cb6cd8e839d1c934cfc4e (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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Build mission object batches from the same AniMesh and Control inputs at startup and during play.

use super::*;

#[derive(Default)]
pub(super) struct ObjectRenderParts {
    pub(super) native_handedness_by_range: HashMap<usize, i8>,
    pub(super) type16_present_ranges: HashSet<usize>,
    pub(super) ambient_effect_slots: Vec<AmbientEffectGpuSlot>,
    pub(super) control_point_light_slots: Vec<ControlEffectSlot>,
    pub(super) control_sound_slots: Vec<ControlSoundSlot>,
    pub(super) unsupported_control_sounds: usize,
    pub(super) component_pose_buffers_by_object: Vec<Vec<Option<NodePoseBuffer>>>,
    pub(super) component_mount_poses_by_object: Vec<Vec<Option<VulkanNodePose>>>,
    pub(super) dynamic_component_geometry_by_object: Vec<Vec<Option<DynamicComponentGeometry>>>,
    pub(super) building_collision_bindings: Vec<BuildingCollisionBinding>,
    pub(super) control_animation_instances_by_object: Vec<Vec<Option<ControlAnimationInstance>>>,
    pub(super) dynamic_shadow_casters: Vec<DynamicShadowCaster>,
    pub(super) sun_occlusion_range_indices: Vec<usize>,
    pub(super) shadow_casters: Vec<ShadowCaster>,
    pub(super) mesh_components: usize,
}

pub(super) struct ObjectRenderBuilder<'a> {
    pub(super) parts: ObjectRenderParts,
    mesh: &'a mut VulkanStaticMesh,
    materials: &'a mut Vec<VulkanStaticMaterial>,
    material_animations: &'a mut Vec<MaterialAnimationBinding>,
    effect_documents: HashMap<String, FxDocument>,
    effect_materials: EffectMaterials,
    shared_models: HashMap<fparkan_assets::AssetId<PreparedModel>, Arc<ModelAsset>>,
    caster_start: usize,
}

impl<'a> ObjectRenderBuilder<'a> {
    pub(super) fn new(
        root: &Path,
        mesh: &'a mut VulkanStaticMesh,
        materials: &'a mut Vec<VulkanStaticMaterial>,
        material_animations: &'a mut Vec<MaterialAnimationBinding>,
        caster_start: usize,
    ) -> Self {
        Self {
            parts: ObjectRenderParts::default(),
            mesh,
            materials,
            material_animations,
            effect_documents: HashMap::new(),
            effect_materials: EffectMaterials::new(root),
            shared_models: HashMap::new(),
            caster_start,
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn append(
        &mut self,
        root: &Path,
        assets: &MissionAssets,
        object_index: usize,
        asset_row: usize,
        mission_root: &MissionObjectDraft,
        static_animation_frame: Option<u16>,
        static_material_phase: Option<u16>,
        live_roots: bool,
        cockpit: Option<StartingCockpit>,
        build_collision: bool,
    ) -> Result<(), String> {
        let visual_ids = assets.visuals_for_object(asset_row);
        let records = &mission_root.unit_components;
        let tree = if records.is_empty() {
            None
        } else {
            Some(unit_component_tree(records).map_err(|error| {
                format!("decode unit component tree for mission object {object_index}: {error}")
            })?)
        };
        if let Some(tree) = tree.as_ref() {
            if tree.len() != visual_ids.len() {
                return Err(format!(
                    "mission object {object_index} unit tree has {} records but {} visuals",
                    tree.len(),
                    visual_ids.len()
                ));
            }
        }
        let component_refs = visual_ids
            .iter()
            .map(|visual_id| {
                let visual = assets.visual_by_id(*visual_id).ok_or_else(|| {
                    format!(
                        "static preview root {object_index} references unknown visual {visual_id:?}"
                    )
                })?;
                let model = visual
                    .model_id
                    .map(|model_id| {
                        assets.model_by_id(model_id).ok_or_else(|| {
                            format!(
                                "static preview visual {visual_id:?} references unknown model {model_id:?}"
                            )
                        })
                    })
                    .transpose()?;
                Ok((visual, model))
            })
            .collect::<Result<Vec<_>, String>>()?;
        let component_controls = assets.object_component_controls.get(asset_row);
        if component_controls.is_some_and(|controls| controls.len() != component_refs.len()) {
            return Err(format!(
                "mission object {object_index} has {} visuals but {} component controls",
                component_refs.len(),
                component_controls.map_or(0, Vec::len)
            ));
        }
        let root_native_kind = component_refs
            .first()
            .and_then(|(visual, _)| native_shadow_kind(visual.source_type));
        let root_sun_eligible = native_sun_object_kind_eligible(
            component_refs
                .first()
                .and_then(|(visual, _)| visual.source_type),
        );
        let mut root_shadow_triangles = Vec::new();
        let mut root_shadow_spheres = Vec::new();
        let mut root_shadow_sphere_sources = Vec::new();
        let mut root_shadow_draw_range_indices = Vec::new();
        let mut component_mount_poses = vec![None; component_refs.len()];
        let mut component_pose_buffers = vec![None; component_refs.len()];
        let mut dynamic_component_geometry = vec![None; component_refs.len()];
        let mut control_animation_instances = vec![None; component_refs.len()];
        for (component_index, (visual, model)) in component_refs.iter().enumerate() {
            let should_render = tree.as_ref().map_or(true, |_| {
                unit_component_is_visible(component_index, visual.source_type)
            });
            let control = component_controls
                .and_then(|controls| controls.get(component_index))
                .and_then(Option::as_ref);
            let Some(model) = *model else {
                if build_collision && root_native_kind == Some(3) && should_render {
                    return Err(format!(
                        "building collision object {object_index} component {component_index} has no model"
                    ));
                }
                if component_index == 0 {
                    if let Some(control) = control {
                        append_initial_control_effect_slots(
                            root,
                            mission_root,
                            object_index,
                            component_index,
                            control,
                            None,
                            None,
                            self.mesh,
                            self.materials,
                            self.material_animations,
                            &mut self.effect_documents,
                            &mut self.effect_materials,
                            &mut self.parts.ambient_effect_slots,
                            &mut self.parts.control_point_light_slots,
                            &mut self.parts.control_sound_slots,
                            &mut self.parts.unsupported_control_sounds,
                        )?;
                    }
                }
                continue;
            };
            let component_bindings = component_controls
                .and_then(|controls| controls.get(component_index))
                .and_then(Option::as_ref)
                .map_or(&[][..], |control| control.bindings.as_slice());
            if static_animation_frame.is_none() {
                if let Some(control) = control {
                    control_animation_instances[component_index] = Some(ControlAnimationInstance {
                        control: control.clone(),
                        model: model.validated.clone(),
                        gate_values: initial_control_gate_values(control),
                        state: ControlInstanceState::default(),
                        last_sampled_node_times: Vec::new(),
                        reported_unsupported_fallback: false,
                        door_blends: Vec::new(),
                        walk: None,
                        wheels: if component_index == 0
                            && mission_root
                                .unit_dat_header_flags
                                .is_some_and(|class| class & 0x0100_0000 != 0)
                        {
                            fparkan_runtime::WheelAnimation::prepare(control, &model.validated)
                        } else {
                            None
                        },
                    });
                }
            }
            component_pose_buffers[component_index] = static_preview_component_pose_buffer(
                &model.validated,
                component_bindings,
                static_animation_frame,
            )?;
            let wheel_root = control_animation_instances[0]
                .as_ref()
                .is_some_and(|instance| instance.wheels.is_some());
            let timeline_moves_component = static_animation_frame.is_none()
                && (wheel_root
                    || control_tree_chain_animates(
                        component_index,
                        tree.as_deref(),
                        component_controls.map_or(&[][..], |controls| controls.as_slice()),
                        cockpit
                            .filter(|cockpit| cockpit.object_index == object_index)
                            .map(|cockpit| cockpit.component_index),
                        live_roots
                            && mission_root
                                .unit_dat_header_flags
                                .is_some_and(|class| class & 0x0100_0000 != 0),
                    ));
            // Native AniMesh only resolves global MSH node sockets for EXTO
            // geometry. Internal INTO components use controller/equipment
            // slots, whose `parent_or_link` values are not MSH node indices.
            // Do not ask the MSH hierarchy to resolve hidden internal parts.
            let mount_pose = match tree.as_deref().filter(|_| should_render) {
                Some(tree) => model_mounts::initial_mount(
                    component_index,
                    records,
                    tree,
                    &component_refs,
                    &component_pose_buffers,
                    &component_mount_poses,
                    static_animation_frame,
                )?,
                None => None,
            };
            if let Some(mount_pose) = mount_pose {
                component_mount_poses[component_index] = Some(mount_pose);
            }
            // External tree components have a recovered mount pose; flat
            // mission components and the root use the mission pose. Hidden
            // INTO slots use controller links rather than MSH sockets, so
            // their Control owner transform remains unresolved here.
            let owner_pose_available =
                component_index == 0 || tree.is_none() || mount_pose.is_some();
            if owner_pose_available {
                if let Some(control) = control {
                    append_initial_control_effect_slots(
                        root,
                        mission_root,
                        object_index,
                        component_index,
                        control,
                        component_pose_buffers[component_index].as_ref(),
                        mount_pose,
                        self.mesh,
                        self.materials,
                        self.material_animations,
                        &mut self.effect_documents,
                        &mut self.effect_materials,
                        &mut self.parts.ambient_effect_slots,
                        &mut self.parts.control_point_light_slots,
                        &mut self.parts.control_sound_slots,
                        &mut self.parts.unsupported_control_sounds,
                    )?;
                }
            }

            let transform = LegacyIron3dEulerTransform {
                translation: mission_root.position,
                orientation_radians: mission_root.orientation_raw,
            };
            if build_collision && root_native_kind == Some(3) && should_render {
                let shared_model = self
                    .shared_models
                    .entry(model.id)
                    .or_insert_with(|| Arc::new(model.validated.clone()))
                    .clone();
                self.parts
                    .building_collision_bindings
                    .push(building_collision_binding(
                        object_index,
                        component_index,
                        format!("{:?}", model.source),
                        shared_model,
                        transform,
                        mission_root.scale,
                        mount_pose.is_some(),
                    )?);
            }
            if should_render {
                let pose_buffer = component_pose_buffers[component_index].as_ref();
                let mut component = match (pose_buffer, mount_pose, static_animation_frame) {
                    (Some(poses), Some(mount), _) => {
                        project_msh_to_static_mesh_in_world_space_with_node_pose_buffer_and_mount(
                            &model.validated,
                            transform,
                            mission_root.scale,
                            poses,
                            mount,
                        )
                    }
                    (Some(poses), None, _) => {
                        project_msh_to_static_mesh_in_world_space_with_node_pose_buffer(
                            &model.validated,
                            transform,
                            mission_root.scale,
                            poses,
                        )
                    }
                    (None, Some(mount), Some(frame)) => {
                        project_msh_to_static_mesh_in_world_space_with_node_sampled_poses_and_mount(
                            &model.validated,
                            transform,
                            mission_root.scale,
                            frame,
                            mount,
                        )
                    }
                    (None, Some(mount), None) => {
                        project_msh_to_static_mesh_in_world_space_with_node_fallback_poses_and_mount(
                            &model.validated,
                            transform,
                            mission_root.scale,
                            mount,
                        )
                    }
                    (None, None, Some(frame)) => {
                        project_msh_to_static_mesh_in_world_space_with_node_sampled_poses(
                            &model.validated,
                            transform,
                            mission_root.scale,
                            frame,
                        )
                    }
                    (None, None, None) => {
                        project_msh_to_static_mesh_in_world_space_with_node_fallback_poses(
                            &model.validated,
                            transform,
                            mission_root.scale,
                        )
                    }
                }
                .map_err(|err| format!("project mission MSH for Vulkan: {err}"))?;
                let base_range_count = component.draw_ranges.len();
                let component_shadow_triangles = static_mesh_shadow_triangles(&component);
                let mut damage_stages = if live_roots && root_native_kind == Some(3) {
                    fparkan_render_vulkan::append_msh_damage_stages(
                        &mut component, &model.validated, transform, mission_root.scale, pose_buffer, mount_pose,
                    )
                    .map_err(|error| format!("project building damage stages {object_index}:{component_index}: {error}"))?
                } else {
                    Vec::new()
                };
                let component_handedness = native_msh_handedness(transform, mission_root.scale);
                for range in &mut component.draw_ranges {
                    range.owner_scope = u32::try_from(object_index)
                        .ok()
                        .and_then(|index| index.checked_add(1))
                        .ok_or_else(|| "MSH light owner exceeds GPU scope range".to_string())?;
                    range.pipeline_state.cull =
                        native_msh_cull_mode(range.batch_flags, component_handedness);
                }
                if root_native_kind.is_some() {
                    root_shadow_triangles.extend(component_shadow_triangles);
                    let node1_pose = mount_pose.and_then(|_| match pose_buffer {
                        Some(poses) => node38_pose_relative_to_root_from_hierarchy(poses, 1),
                        None => node38_pose_relative_to_root(
                            &model.validated,
                            static_animation_frame,
                            1,
                        ),
                    });
                    if let Some(sphere) = mounted_shadow_sphere(
                        model.validated.bounding_sphere_center,
                        model.validated.bounding_sphere_radius,
                        mount_pose,
                        node1_pose,
                    ) {
                        root_shadow_spheres.push(sphere);
                        root_shadow_sphere_sources.push(DynamicShadowSphereSource {
                            component_index,
                            center: model.validated.bounding_sphere_center,
                            radius: model.validated.bounding_sphere_radius,
                            mounted: mount_pose.is_some(),
                        });
                    }
                }
                let selector_remap = static_preview_component_materials(
                    assets,
                    visual,
                    &component,
                    static_material_phase,
                    self.materials,
                    self.material_animations,
                )?;
                let lightmap_textures = static_preview_lightmap_textures(assets, visual)?;
                let range_start = self.mesh.draw_ranges.len();
                for stage in &mut damage_stages {
                    stage.ranges.start += range_start;
                    stage.ranges.end += range_start;
                }
                let vertex_start = self.mesh.vertices.len();
                let vertex_count = component.vertices.len();
                append_static_preview_component_with_lightmaps(
                    self.mesh,
                    component,
                    &selector_remap,
                    Some(self.materials),
                    &lightmap_textures,
                    Some(self.material_animations),
                )?;
                for range_index in range_start..self.mesh.draw_ranges.len() {
                    self.parts
                        .native_handedness_by_range
                        .insert(range_index, component_handedness);
                    if model.validated.type16_present {
                        self.parts.type16_present_ranges.insert(range_index);
                    }
                }
                if root_native_kind.is_some() {
                    root_shadow_draw_range_indices
                        .extend(range_start..range_start + base_range_count);
                }
                if live_roots || timeline_moves_component {
                    let parent_mount = tree
                        .as_ref()
                        .filter(|_| mount_pose.is_some())
                        .and_then(|nodes| nodes.get(component_index))
                        .and_then(|node| node.parent_index)
                        .filter(|parent_index| {
                            component_mount_poses[*parent_index].is_some()
                                || component_refs.get(*parent_index).is_some_and(
                                    |(parent_visual, _)| {
                                        unit_component_is_visible(
                                            *parent_index,
                                            parent_visual.source_type,
                                        )
                                    },
                                )
                        })
                        .map(|parent_index| {
                            let socket = usize::try_from(records[component_index].parent_or_link)
                                .expect("mount socket was validated above");
                            (parent_index, socket)
                        });
                    dynamic_component_geometry[component_index] = Some(DynamicComponentGeometry {
                        model: self
                            .shared_models
                            .entry(model.id)
                            .or_insert_with(|| Arc::new(model.validated.clone()))
                            .clone(),
                        animated: timeline_moves_component,
                        root_transform: transform,
                        owner_scale: mission_root.scale,
                        parent_mount,
                        vertex_start,
                        vertex_count,
                        #[cfg(windows)]
                        base_draws: range_start..range_start + base_range_count,
                        damage_stages,
                    });
                }
                if root_sun_eligible {
                    self.parts
                        .sun_occlusion_range_indices
                        .extend(range_start..self.mesh.draw_ranges.len());
                }
                self.parts.mesh_components += 1;
            }
        }
        if let Some(native_kind) =
            root_native_kind.filter(|kind| native_shadow_caster_enabled(*kind))
        {
            let caster_id = u32::try_from(self.caster_start + self.parts.shadow_casters.len())
                .map_err(|_| "shadow caster id exceeds u32".to_string())?;
            let root_transform = LegacyIron3dEulerTransform {
                translation: mission_root.position,
                orientation_radians: mission_root.orientation_raw,
            };
            if let Some(caster) = aggregate_shadow_caster(
                caster_id,
                native_kind,
                root_transform,
                mission_root.scale,
                root_shadow_triangles,
                &root_shadow_spheres,
            ) {
                let animated = dynamic_component_geometry
                    .iter()
                    .flatten()
                    .any(|c| c.animated);
                if live_roots || animated {
                    let component_draw_range_indices = root_shadow_draw_range_indices
                        .into_iter()
                        .filter(|range_index| {
                            self.mesh
                                .draw_ranges
                                .get(*range_index)
                                .is_some_and(|range| range.index_count != 0)
                        })
                        .collect::<Vec<_>>();
                    if !component_draw_range_indices.is_empty() {
                        self.parts.dynamic_shadow_casters.push(DynamicShadowCaster {
                            caster_index: self.caster_start + self.parts.shadow_casters.len(),
                            object_index,
                            animated,
                            root_transform,
                            owner_scale: mission_root.scale,
                            initial_sphere: caster.sphere,
                            component_draw_range_indices,
                            component_spheres: root_shadow_sphere_sources.clone(),
                        });
                    }
                }
                self.parts.shadow_casters.push(caster);
            }
        }
        self.parts
            .component_pose_buffers_by_object
            .push(component_pose_buffers);
        self.parts
            .component_mount_poses_by_object
            .push(component_mount_poses);
        self.parts
            .dynamic_component_geometry_by_object
            .push(dynamic_component_geometry);
        self.parts
            .control_animation_instances_by_object
            .push(control_animation_instances);
        Ok(())
    }
}