aboutsummaryrefslogtreecommitdiff
path: root/apps
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-12-02 05:09:14 +0300
committerValentin Popov <valentin@popov.link>2026-12-02 05:09:14 +0300
commit0ad190894afd8e9592ef182e36e16ee7a61483f6 (patch)
treee9aacd5995bcad2024bee939d629f186c2667ef9 /apps
parent8e11cede8106e36aa1b91400318cff353c157986 (diff)
downloadfparkan-0ad190894afd8e9592ef182e36e16ee7a61483f6.tar.xz
fparkan-0ad190894afd8e9592ef182e36e16ee7a61483f6.zip
feat(ui): render assembled warbots in the designer
Diffstat (limited to 'apps')
-rw-r--r--apps/fparkan-game/src/designer_model.rs222
-rw-r--r--apps/fparkan-game/src/factory_menu.rs45
-rw-r--r--apps/fparkan-game/src/main.rs12
-rw-r--r--apps/fparkan-game/src/mission_overlay.rs4
-rw-r--r--apps/fparkan-game/src/robot_designer.rs49
5 files changed, 307 insertions, 25 deletions
diff --git a/apps/fparkan-game/src/designer_model.rs b/apps/fparkan-game/src/designer_model.rs
new file mode 100644
index 00000000..3639566f
--- /dev/null
+++ b/apps/fparkan-game/src/designer_model.rs
@@ -0,0 +1,222 @@
+use super::{
+ add3, clip_from_world_for_view, cross3, length3, normalize3, scale3, sub3, StaticPreviewScene,
+ VulkanSmokeRenderer, VulkanStaticCamera,
+};
+use fparkan_assets::designer_screen::MODEL_VIEWPORT;
+use fparkan_render_vulkan::VulkanModelPreview;
+use fparkan_runtime::{factory_project_root, Engine};
+use std::ops::Range;
+
+const SPIN_RADIANS_PER_MS: f32 = f32::from_bits(0x3a449ba6);
+const ELEVATION: f32 = 0.5;
+const HALF_FOV: f32 = std::f32::consts::FRAC_PI_6;
+
+pub(super) struct DesignerModels(Vec<Option<DesignerModel>>);
+
+struct DesignerModel {
+ draws: Range<usize>,
+ counts: Vec<u32>,
+ center: [f32; 3],
+ radius: f32,
+}
+
+impl DesignerModels {
+ pub(super) fn prepare(engine: &Engine, scene: &mut StaticPreviewScene) -> Result<Self, String> {
+ let mut models = Vec::new();
+ for root in (0..).map_while(|scheme| factory_project_root(engine, scheme)) {
+ models.push(DesignerModel::prepare(root, scene)?);
+ }
+ Ok(Self(models))
+ }
+
+ pub(super) fn ranges(&self) -> impl Iterator<Item = usize> + '_ {
+ self.0
+ .iter()
+ .flatten()
+ .flat_map(|model| model.draws.clone())
+ }
+
+ pub(super) fn draw(
+ &self,
+ renderer: &mut VulkanSmokeRenderer,
+ active: Option<(usize, u32)>,
+ viewport: [f32; 2],
+ ) -> Result<(), String> {
+ let preview = active.and_then(|(scheme, elapsed_ms)| {
+ self.0
+ .get(scheme)?
+ .as_ref()
+ .map(|model| model.view(elapsed_ms, viewport))
+ });
+ for (scheme, model) in self.0.iter().enumerate() {
+ let Some(model) = model else { continue };
+ let visible = active.is_some_and(|(selected, _)| selected == scheme);
+ for (index, count) in model.draws.clone().zip(&model.counts) {
+ renderer
+ .set_draw_range_index_count(index, if visible { *count } else { 0 })
+ .map_err(|error| error.to_string())?;
+ }
+ }
+ renderer
+ .set_model_preview(preview)
+ .map_err(|error| error.to_string())
+ }
+}
+
+impl DesignerModel {
+ fn prepare(root: usize, scene: &mut StaticPreviewScene) -> Result<Option<Self>, String> {
+ let source = scene.dynamic_component_geometry[root]
+ .iter()
+ .flatten()
+ .flat_map(|component| component.base_draws.clone())
+ .map(|index| scene.mesh.draw_ranges[index])
+ .filter(|range| range.index_count != 0)
+ .collect::<Vec<_>>();
+ let referenced = source.iter().flat_map(|range| {
+ let first = range.first_index as usize;
+ scene.mesh.indices[first..first + range.index_count as usize]
+ .iter()
+ .copied()
+ });
+ let Some(([min, max], [lo, hi])) = referenced.fold(None, |bounds, index| {
+ let position = scene.mesh.vertices[index as usize].position;
+ Some(bounds.map_or(
+ ([index; 2], [position; 2]),
+ |([min, max], [lo, hi]): Bounds| {
+ (
+ [min.min(index), max.max(index)],
+ [
+ std::array::from_fn(|axis| lo[axis].min(position[axis])),
+ std::array::from_fn(|axis| hi[axis].max(position[axis])),
+ ],
+ )
+ },
+ ))
+ }) else {
+ return Ok(None);
+ };
+ let sphere = scene
+ .dynamic_shadow_casters
+ .iter()
+ .find(|caster| caster.object_index == root)
+ .map(|caster| caster.initial_sphere);
+ let (center, radius) = sphere.map_or_else(
+ || {
+ (
+ scale3(add3(lo, hi), 0.5),
+ length3(sub3(hi, lo)).unwrap_or(0.0) * 0.5,
+ )
+ },
+ |sphere| (sphere.center, sphere.radius),
+ );
+ if !radius.is_finite() || radius <= f32::EPSILON {
+ return Ok(None);
+ }
+
+ // Keep the designer at its prepared pose even after the factory
+ // moves its first live unit out of the reserved world slot.
+ let vertex_start = u32::try_from(scene.mesh.vertices.len())
+ .map_err(|_| "designer vertex offset exceeds u32")?;
+ scene
+ .mesh
+ .vertices
+ .extend_from_within(min as usize..=max as usize);
+ let start = scene.mesh.draw_ranges.len();
+ let counts = source.iter().map(|range| range.index_count).collect();
+ for mut range in source {
+ let first = range.first_index as usize;
+ let next = scene.mesh.indices.len();
+ scene
+ .mesh
+ .indices
+ .extend_from_within(first..first + range.index_count as usize);
+ for index in &mut scene.mesh.indices[next..] {
+ *index = (*index - min)
+ .checked_add(vertex_start)
+ .ok_or("designer mesh index exceeds u32")?;
+ }
+ range.first_index =
+ u32::try_from(next).map_err(|_| "designer index offset exceeds u32")?;
+ range.owner_scope = 0;
+ scene.mesh.draw_ranges.push(range);
+ }
+ Ok(Some(Self {
+ draws: start..scene.mesh.draw_ranges.len(),
+ counts,
+ center,
+ radius,
+ }))
+ }
+
+ fn view(&self, elapsed_ms: u32, drawable: [f32; 2]) -> VulkanModelPreview {
+ let yaw = elapsed_ms as f64 * f64::from(SPIN_RADIANS_PER_MS);
+ let (sin_yaw, cos_yaw) = yaw.sin_cos();
+ let (sin_elevation, cos_elevation) = ELEVATION.sin_cos();
+ let outward = [
+ -cos_elevation * cos_yaw as f32,
+ cos_elevation * sin_yaw as f32,
+ sin_elevation,
+ ];
+ let radius = self.radius;
+ let near = 0.5;
+ let distance = (radius / HALF_FOV.sin()).max(radius + near);
+ let horizontal_half = (radius / distance).asin();
+ let eye = add3(self.center, scale3(outward, distance));
+ let forward = scale3(outward, -1.0);
+ let right = normalize3(cross3(forward, [0.0, 0.0, 1.0]))
+ .expect("designer elevation avoids the pole");
+ let up = cross3(right, forward);
+ let [l, t, r, b] = MODEL_VIEWPORT;
+ let viewport = [l / 640.0, t / 480.0, r / 640.0, b / 480.0];
+ let aspect = super::preview_aspect(
+ ((r - l) / 640.0 * drawable[0]) / ((b - t) / 480.0 * drawable[1]),
+ );
+ let vertical_fov = (horizontal_half.tan() / aspect).atan() * 2.0;
+ let far = 300.0_f32.max(distance + radius);
+ let camera = VulkanStaticCamera {
+ clip_from_world: clip_from_world_for_view(
+ eye,
+ forward,
+ right,
+ up,
+ vertical_fov,
+ near,
+ far,
+ aspect,
+ ),
+ };
+ VulkanModelPreview {
+ ranges: self.draws.clone(),
+ viewport,
+ camera,
+ eye,
+ }
+ }
+}
+
+type Bounds = ([u32; 2], [[f32; 3]; 2]);
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn designer_camera_orbits_the_same_project_center() {
+ let model = DesignerModel {
+ draws: 2..3,
+ counts: vec![3],
+ center: [8.0, -2.0, 5.0],
+ radius: 4.0,
+ };
+ let initial = model.view(0, [1280.0, 720.0]);
+ let later = model.view(1000, [1280.0, 720.0]);
+ let relative = sub3(initial.eye, model.center);
+ let rotated = sub3(later.eye, model.center);
+ assert!((relative[1]).abs() < 1.0e-5);
+ assert!((length3(relative).unwrap() - 8.0).abs() < 1.0e-5);
+ assert!((relative[2] - rotated[2]).abs() < 1.0e-5);
+ assert!((rotated[1].atan2(-rotated[0]) - 0.75).abs() < 1.0e-5);
+ assert_eq!(initial.viewport, later.viewport);
+ assert_ne!(initial.camera.clip_from_world, later.camera.clip_from_world);
+ }
+}
diff --git a/apps/fparkan-game/src/factory_menu.rs b/apps/fparkan-game/src/factory_menu.rs
index 743a438a..376b1723 100644
--- a/apps/fparkan-game/src/factory_menu.rs
+++ b/apps/fparkan-game/src/factory_menu.rs
@@ -39,6 +39,7 @@ pub(super) struct DesignerSession {
pub(super) first_part: usize,
pub(super) hover: Option<DesignerAction>,
pub(super) dirty: bool,
+ pub(super) model_started_ms: u32,
}
impl DesignerSession {
@@ -93,12 +94,13 @@ impl FactoryMenu {
first_part: 0,
hover: None,
dirty: true,
+ model_started_ms: 0,
};
designer.point(self.cursor);
self.designer = Some(designer);
}
- fn designer_action(&mut self, action: DesignerAction) {
+ fn designer_action(&mut self, action: DesignerAction, clock_ms: u32) {
let Some(designer) = &mut self.designer else {
return;
};
@@ -107,6 +109,7 @@ impl FactoryMenu {
designer.selected = Some(slot);
designer.first_part = 0;
designer.dirty = true;
+ designer.model_started_ms = clock_ms;
}
DesignerAction::Send => {
if let Some(slot) = designer.selected {
@@ -151,7 +154,11 @@ struct ProjectPicture {
}
impl FactoryProjectPanel {
- pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> {
+ pub(super) fn load(
+ root: &Path,
+ preview: &mut StaticPreviewScene,
+ engine: &Engine,
+ ) -> Result<Self, String> {
let images = FactoryProjectImages::load(&DirectoryVfs::new(root))?;
let range = append_picture(
preview,
@@ -164,12 +171,14 @@ impl FactoryProjectPanel {
],
)?;
#[cfg(windows)]
- let designer = RobotDesignerPanel::load(root, preview)
+ let designer = RobotDesignerPanel::load(root, preview, engine)
.map(Some)
.unwrap_or_else(|error| {
eprintln!("robot_designer_unavailable reason={error}");
None
});
+ #[cfg(not(windows))]
+ let _ = engine;
Ok(Self {
images,
range,
@@ -190,11 +199,11 @@ impl FactoryProjectPanel {
}
}
- pub(super) fn ranges(&self) -> impl Iterator<Item = usize> {
+ pub(super) fn ranges(&self) -> impl Iterator<Item = usize> + '_ {
#[cfg(windows)]
- let designer = self.designer.as_ref().map(RobotDesignerPanel::range_index);
+ let designer = self.designer.iter().flat_map(RobotDesignerPanel::ranges);
#[cfg(not(windows))]
- let designer = None;
+ let designer = std::iter::empty();
std::iter::once(self.range.range_index).chain(designer)
}
@@ -203,13 +212,15 @@ impl FactoryProjectPanel {
renderer: &mut VulkanSmokeRenderer,
mut menu: Option<&mut FactoryMenu>,
engine: Option<&Engine>,
+ viewport: [f32; 2],
+ clock_ms: u32,
) -> Result<(), String> {
#[cfg(windows)]
if let Some(designer) = &mut self.designer {
- designer.draw(renderer, menu.as_deref_mut(), engine)?;
+ designer.draw(renderer, menu.as_deref_mut(), engine, viewport, clock_ms)?;
}
#[cfg(not(windows))]
- let _ = (&mut menu, engine);
+ let _ = (&mut menu, engine, viewport, clock_ms);
if let Some(menu) = menu.filter(|menu| menu.designer.is_none()) {
let slots = menu.visible_slots();
let count = slots.len();
@@ -264,9 +275,11 @@ impl StaticVulkanApp {
if state == ElementState::Pressed && !repeat && !self.mission_paused {
if menu.designer.is_some() {
match code {
- KeyCode::Escape => menu.designer_action(DesignerAction::Exit),
+ KeyCode::Escape => {
+ menu.designer_action(DesignerAction::Exit, self.simulation_time_ms)
+ }
KeyCode::Enter | KeyCode::NumpadEnter => {
- menu.designer_action(DesignerAction::Send)
+ menu.designer_action(DesignerAction::Send, self.simulation_time_ms)
}
_ => {}
}
@@ -351,7 +364,7 @@ impl StaticVulkanApp {
{
if let Some(designer) = &menu.designer {
if let Some(action) = designer.hover {
- menu.designer_action(action);
+ menu.designer_action(action, self.simulation_time_ms);
self.update_mission_title();
}
return true;
@@ -451,15 +464,15 @@ mod tests {
.collect(),
);
menu.open_designer();
- menu.designer_action(DesignerAction::Send);
+ menu.designer_action(DesignerAction::Send, 0);
assert!(menu.designer.is_some());
- menu.designer_action(DesignerAction::Project(1));
- menu.designer_action(DesignerAction::Exit);
+ menu.designer_action(DesignerAction::Project(1), 0);
+ menu.designer_action(DesignerAction::Exit, 0);
assert_eq!(menu.selected().scheme, 0);
menu.open_designer();
- menu.designer_action(DesignerAction::Project(1));
- menu.designer_action(DesignerAction::Send);
+ menu.designer_action(DesignerAction::Project(1), 0);
+ menu.designer_action(DesignerAction::Send, 0);
assert!(menu.designer.is_none());
assert_eq!(menu.selected().scheme, 1);
}
diff --git a/apps/fparkan-game/src/main.rs b/apps/fparkan-game/src/main.rs
index 4b5734b0..8e372c9f 100644
--- a/apps/fparkan-game/src/main.rs
+++ b/apps/fparkan-game/src/main.rs
@@ -36,6 +36,8 @@ use fparkan_runtime::query_building_segment_world;
#[cfg(test)]
use player_collision::building_collision_nodes;
use player_collision::{building_collision_binding, BuildingCollisionBinding};
+#[cfg(windows)]
+mod designer_model;
mod player_fire;
mod player_footsteps;
mod player_service;
@@ -4846,6 +4848,8 @@ struct DynamicComponentGeometry {
parent_mount: Option<(usize, usize)>,
vertex_start: usize,
vertex_count: usize,
+ #[cfg(windows)]
+ base_draws: std::ops::Range<usize>,
damage_stages: Vec<fparkan_render_vulkan::DamageStageRanges>,
}
@@ -8604,6 +8608,8 @@ fn static_preview_mesh_and_materials(
parent_mount,
vertex_start,
vertex_count,
+ #[cfg(windows)]
+ base_draws: range_start..range_start + base_range_count,
damage_stages,
});
}
@@ -14501,6 +14507,8 @@ mod tests {
parent_mount: None,
vertex_start: 0,
vertex_count: parent_vertex_count,
+ #[cfg(windows)]
+ base_draws: 0..0,
damage_stages: Vec::new(),
}),
Some(DynamicComponentGeometry {
@@ -14511,6 +14519,8 @@ mod tests {
parent_mount: Some((0, 1)),
vertex_start: parent_vertex_count,
vertex_count: 3,
+ #[cfg(windows)]
+ base_draws: 0..0,
damage_stages: Vec::new(),
}),
]];
@@ -14854,6 +14864,8 @@ mod tests {
parent_mount,
vertex_start: 0,
vertex_count: mesh.vertices.len(),
+ #[cfg(windows)]
+ base_draws: 0..0,
damage_stages: Vec::new(),
}),
]];
diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs
index ee3c2425..0c3ad122 100644
--- a/apps/fparkan-game/src/mission_overlay.rs
+++ b/apps/fparkan-game/src/mission_overlay.rs
@@ -88,7 +88,7 @@ impl MissionOverlay {
})
});
let factory_projects = cockpit.and_then(|_| {
- FactoryProjectPanel::load(root, preview)
+ FactoryProjectPanel::load(root, preview, engine)
.map(Some)
.unwrap_or_else(|error| {
eprintln!("factory_project_panel_unavailable reason={error}");
@@ -236,6 +236,8 @@ impl StaticVulkanApp {
renderer,
self.factory_menu.as_mut(),
self.mission_engine.as_ref(),
+ frame.viewport,
+ frame.clock.time_ms,
)?;
}
Ok(())
diff --git a/apps/fparkan-game/src/robot_designer.rs b/apps/fparkan-game/src/robot_designer.rs
index 80005b89..6b48ca77 100644
--- a/apps/fparkan-game/src/robot_designer.rs
+++ b/apps/fparkan-game/src/robot_designer.rs
@@ -1,4 +1,5 @@
use super::{
+ designer_model::DesignerModels,
factory_menu::{append_picture, picture_texture, FactoryMenu},
DirectoryVfs, EnvironmentGpuRange, StaticPreviewScene, VulkanSmokeRenderer,
};
@@ -9,11 +10,17 @@ use std::path::Path;
pub(super) struct RobotDesignerPanel {
assets: DesignerScreen,
+ background: EnvironmentGpuRange,
+ models: DesignerModels,
range: EnvironmentGpuRange,
}
impl RobotDesignerPanel {
- pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result<Self, String> {
+ pub(super) fn load(
+ root: &Path,
+ preview: &mut StaticPreviewScene,
+ engine: &Engine,
+ ) -> Result<Self, String> {
let strings = StringResources::open(&root.join("iron3d.dll"))?;
let read = |id| {
strings
@@ -29,12 +36,24 @@ impl RobotDesignerPanel {
exit: read(0x615)?,
},
)?;
- let range = append_picture(preview, EXTENT, [0.0, 0.0, 640.0, 480.0])?;
- Ok(Self { assets, range })
+ let screen = [0.0, 0.0, 640.0, 480.0];
+ let background = append_picture(preview, EXTENT, screen)?;
+ preview.materials[background.material_index].texture =
+ picture_texture(EXTENT, assets.paint_background().rgba8);
+ let models = DesignerModels::prepare(engine, preview)?;
+ let range = append_picture(preview, EXTENT, screen)?;
+ Ok(Self {
+ assets,
+ background,
+ models,
+ range,
+ })
}
- pub(super) fn range_index(&self) -> usize {
- self.range.range_index
+ pub(super) fn ranges(&self) -> impl Iterator<Item = usize> + '_ {
+ [self.background.range_index, self.range.range_index]
+ .into_iter()
+ .chain(self.models.ranges())
}
pub(super) fn draw(
@@ -42,8 +61,19 @@ impl RobotDesignerPanel {
renderer: &mut VulkanSmokeRenderer,
menu: Option<&mut FactoryMenu>,
engine: Option<&Engine>,
+ viewport: [f32; 2],
+ clock_ms: u32,
) -> Result<(), String> {
let visible = menu.as_ref().is_some_and(|menu| menu.designer.is_some());
+ let active = menu.as_ref().and_then(|menu| {
+ let designer = menu.designer.as_ref()?;
+ let root = designer.slots.start + designer.selected?;
+ Some((
+ menu.choices[root].scheme,
+ clock_ms.saturating_sub(designer.model_started_ms),
+ ))
+ });
+ self.models.draw(renderer, active, viewport)?;
if let Some(menu) = menu {
if let Some(designer) = menu.designer.as_mut().filter(|view| view.dirty) {
let project = designer.selected.and_then(|slot| {
@@ -67,8 +97,11 @@ impl RobotDesignerPanel {
designer.dirty = false;
}
}
- renderer
- .set_draw_range_index_count(self.range.range_index, if visible { 6 } else { 0 })
- .map_err(|error| error.to_string())
+ for range in [self.background, self.range] {
+ renderer
+ .set_draw_range_index_count(range.range_index, if visible { 6 } else { 0 })
+ .map_err(|error| error.to_string())?;
+ }
+ Ok(())
}
}