From 8e11cede8106e36aa1b91400318cff353c157986 Mon Sep 17 00:00:00 2001 From: Valentin Popov Date: Wed, 2 Dec 2026 05:53:53 +0400 Subject: feat(ui): open and transfer recent factory designs --- apps/fparkan-game/src/factory_menu.rs | 254 ++++++++++++++++++++++---- apps/fparkan-game/src/main.rs | 10 +- apps/fparkan-game/src/mission_overlay.rs | 12 +- apps/fparkan-game/src/robot_designer.rs | 74 ++++++++ crates/fparkan-assets/src/designer_screen.rs | 251 +++++++++++++++++++++++++ crates/fparkan-assets/src/factory_projects.rs | 33 +++- crates/fparkan-assets/src/lib.rs | 1 + crates/fparkan-assets/src/ui_sprite.rs | 47 ++--- crates/fparkan-runtime/src/lib.rs | 4 +- crates/fparkan-runtime/src/production.rs | 15 ++ docs/tomes/06-behavior.md | 15 +- 11 files changed, 647 insertions(+), 69 deletions(-) create mode 100644 apps/fparkan-game/src/robot_designer.rs create mode 100644 crates/fparkan-assets/src/designer_screen.rs diff --git a/apps/fparkan-game/src/factory_menu.rs b/apps/fparkan-game/src/factory_menu.rs index 8f307cfc..743a438a 100644 --- a/apps/fparkan-game/src/factory_menu.rs +++ b/apps/fparkan-game/src/factory_menu.rs @@ -1,16 +1,20 @@ +#[cfg(windows)] +use super::robot_designer::RobotDesignerPanel; use super::{ append_environment_gradient_material, append_environment_range, quad_indices, screen_tl_quad_vertices_pixels, world_pipeline_state, DirectoryVfs, EnvironmentGpuRange, LegacyBlendMode, LegacyDepthMode, StaticPreviewScene, StaticVulkanApp, VulkanSmokeRenderer, VulkanStaticTexture, }; +use fparkan_assets::designer_screen::{self, DesignerAction, PART_ROWS}; use fparkan_assets::factory_projects::{ hit_test, FactoryProjectAction, FactoryProjectImages, EXTENT, ORIGIN, PROJECT_SLOTS, }; +use fparkan_runtime::{factory_project_components, Engine}; use fparkan_world::ObjectHandle; use std::{ops::Range, path::Path}; use winit::{ - event::{ElementState, MouseButton, WindowEvent}, + event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent}, keyboard::KeyCode, }; @@ -22,10 +26,27 @@ pub(super) struct FactoryChoice { } pub(super) struct FactoryMenu { - choices: Vec, + pub(super) choices: Vec, selected: usize, cursor: [f32; 2], pressed: Option, + pub(super) designer: Option, +} + +pub(super) struct DesignerSession { + pub(super) slots: Range, + pub(super) selected: Option, + pub(super) first_part: usize, + pub(super) hover: Option, + pub(super) dirty: bool, +} + +impl DesignerSession { + fn point(&mut self, cursor: [f32; 2]) { + let next = designer_screen::hit_test(cursor, self.slots.len(), self.selected.is_some()); + self.dirty |= next != self.hover; + self.hover = next; + } } impl FactoryMenu { @@ -36,6 +57,7 @@ impl FactoryMenu { selected: 0, cursor: [f32::NAN; 2], pressed: None, + designer: None, } } @@ -64,6 +86,39 @@ impl FactoryMenu { start..start + count } + fn open_designer(&mut self) { + let mut designer = DesignerSession { + slots: self.visible_slots(), + selected: None, + first_part: 0, + hover: None, + dirty: true, + }; + designer.point(self.cursor); + self.designer = Some(designer); + } + + fn designer_action(&mut self, action: DesignerAction) { + let Some(designer) = &mut self.designer else { + return; + }; + match action { + DesignerAction::Project(slot) if slot < designer.slots.len() => { + designer.selected = Some(slot); + designer.first_part = 0; + designer.dirty = true; + } + DesignerAction::Send => { + if let Some(slot) = designer.selected { + self.selected = designer.slots.start + slot; + self.designer = None; + } + } + DesignerAction::Exit => self.designer = None, + _ => {} + } + } + pub(super) fn title(&self) -> String { let choice = self.selected(); let factory = choice.factory.map_or_else( @@ -83,6 +138,8 @@ pub(super) struct FactoryProjectPanel { images: FactoryProjectImages, range: EnvironmentGpuRange, displayed: Option, + #[cfg(windows)] + designer: Option, } #[derive(PartialEq, Eq)] @@ -96,45 +153,64 @@ struct ProjectPicture { impl FactoryProjectPanel { pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result { let images = FactoryProjectImages::load(&DirectoryVfs::new(root))?; - let material = append_environment_gradient_material(&mut preview.materials)?; - preview.materials[material].screen_tl = true; - preview.materials[material].sky_far_depth = false; - preview.materials[material].texture = - texture(vec![0; (EXTENT[0] * EXTENT[1] * 4) as usize]); - let half = EXTENT.map(|dimension| dimension as f32 * 0.5); - let vertices = screen_tl_quad_vertices_pixels( - [ORIGIN[0] as f32 + half[0], ORIGIN[1] as f32 + half[1]], - half[0], - half[1], - [640.0, 480.0], - [1.0; 3], - 1.0, - [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], - ); - let range = append_environment_range( - &mut preview.mesh, - material, - vertices.to_vec(), - quad_indices(1)?, - world_pipeline_state(LegacyBlendMode::SourceAlpha, LegacyDepthMode::Disabled), + let range = append_picture( + preview, + EXTENT, + [ + ORIGIN[0] as f32, + ORIGIN[1] as f32, + EXTENT[0] as f32, + EXTENT[1] as f32, + ], )?; + #[cfg(windows)] + let designer = RobotDesignerPanel::load(root, preview) + .map(Some) + .unwrap_or_else(|error| { + eprintln!("robot_designer_unavailable reason={error}"); + None + }); Ok(Self { images, range, displayed: None, + #[cfg(windows)] + designer, }) } - pub(super) fn range_index(&self) -> usize { - self.range.range_index + pub(super) fn designer_available(&self) -> bool { + #[cfg(windows)] + { + self.designer.is_some() + } + #[cfg(not(windows))] + { + false + } + } + + pub(super) fn ranges(&self) -> impl Iterator { + #[cfg(windows)] + let designer = self.designer.as_ref().map(RobotDesignerPanel::range_index); + #[cfg(not(windows))] + let designer = None; + std::iter::once(self.range.range_index).chain(designer) } pub(super) fn draw( &mut self, renderer: &mut VulkanSmokeRenderer, - menu: Option<&mut FactoryMenu>, + mut menu: Option<&mut FactoryMenu>, + engine: Option<&Engine>, ) -> Result<(), String> { - if let Some(menu) = menu { + #[cfg(windows)] + if let Some(designer) = &mut self.designer { + designer.draw(renderer, menu.as_deref_mut(), engine)?; + } + #[cfg(not(windows))] + let _ = (&mut menu, engine); + if let Some(menu) = menu.filter(|menu| menu.designer.is_none()) { let slots = menu.visible_slots(); let count = slots.len(); let selected = menu.selected - slots.start; @@ -147,9 +223,15 @@ impl FactoryProjectPanel { && picture.name == *name }); if !unchanged { - let image = self.images.paint(count, selected, pressed, name)?; + let image = + self.images + .paint(count, selected, pressed, name, self.designer_available())?; renderer - .update_material_texture(self.range.material_index, 0, &texture(image.rgba8)) + .update_material_texture( + self.range.material_index, + 0, + &picture_texture(EXTENT, image.rgba8), + ) .map_err(|error| error.to_string())?; self.displayed = Some(ProjectPicture { count, @@ -180,6 +262,17 @@ impl StaticVulkanApp { return false; }; if state == ElementState::Pressed && !repeat && !self.mission_paused { + if menu.designer.is_some() { + match code { + KeyCode::Escape => menu.designer_action(DesignerAction::Exit), + KeyCode::Enter | KeyCode::NumpadEnter => { + menu.designer_action(DesignerAction::Send) + } + _ => {} + } + self.update_mission_title(); + return true; + } match code { KeyCode::ArrowUp => menu.navigate(true), KeyCode::ArrowDown => menu.navigate(false), @@ -198,6 +291,11 @@ impl StaticVulkanApp { } pub(super) fn handle_factory_pointer(&mut self, event: &WindowEvent) -> bool { + let designer_available = self + .overlay + .factory_projects + .as_ref() + .is_some_and(FactoryProjectPanel::designer_available); let Some(menu) = &mut self.factory_menu else { return false; }; @@ -210,19 +308,54 @@ impl StaticVulkanApp { position.x as f32 * 640.0 / size.width as f32, position.y as f32 * 480.0 / size.height as f32, ]; + if let Some(designer) = &mut menu.designer { + designer.point(menu.cursor); + } } } true } WindowEvent::CursorLeft { .. } | WindowEvent::Focused(false) => { menu.cursor = [f32::NAN; 2]; + if let Some(designer) = &mut menu.designer { + designer.point(menu.cursor); + } false } + WindowEvent::MouseWheel { delta, .. } if menu.designer.is_some() => { + let designer = menu.designer.as_mut().expect("the designer is open"); + if let Some(parts) = designer.selected.and_then(|slot| { + let choice = &menu.choices[designer.slots.start + slot]; + factory_project_components(self.mission_engine.as_ref()?, choice.scheme) + }) { + let y = match delta { + MouseScrollDelta::LineDelta(_, y) => *y, + MouseScrollDelta::PixelDelta(point) => point.y as f32, + }; + if y == 0.0 { + return true; + } + let first_part = designer + .first_part + .saturating_add_signed(-y.signum() as isize) + .min(parts.len().saturating_sub(PART_ROWS)); + designer.dirty |= designer.first_part != first_part; + designer.first_part = first_part; + } + true + } WindowEvent::MouseInput { state, button, .. } => { if *state == ElementState::Pressed && *button == MouseButton::Left && !self.mission_paused { + if let Some(designer) = &menu.designer { + if let Some(action) = designer.hover { + menu.designer_action(action); + self.update_mission_title(); + } + return true; + } let slots = menu.visible_slots(); match hit_test(menu.cursor, slots.len()) { Some(FactoryProjectAction::Select(index)) => { @@ -231,6 +364,10 @@ impl StaticVulkanApp { self.update_mission_title(); } Some(FactoryProjectAction::Build) => self.player_build_pressed = true, + Some(FactoryProjectAction::Designer) if designer_available => { + menu.open_designer() + } + Some(FactoryProjectAction::Designer) => {} None => {} } } @@ -241,10 +378,38 @@ impl StaticVulkanApp { } } -fn texture(rgba8: Vec) -> VulkanStaticTexture { +pub(super) fn append_picture( + preview: &mut StaticPreviewScene, + extent: [u32; 2], + [x, y, width, height]: [f32; 4], +) -> Result { + let material = append_environment_gradient_material(&mut preview.materials)?; + preview.materials[material].screen_tl = true; + preview.materials[material].sky_far_depth = false; + preview.materials[material].texture = + picture_texture(extent, vec![0; (extent[0] * extent[1] * 4) as usize]); + let vertices = screen_tl_quad_vertices_pixels( + [x + width * 0.5, y + height * 0.5], + width * 0.5, + height * 0.5, + [640.0, 480.0], + [1.0; 3], + 1.0, + [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], + ); + append_environment_range( + &mut preview.mesh, + material, + vertices.to_vec(), + quad_indices(1)?, + world_pipeline_state(LegacyBlendMode::SourceAlpha, LegacyDepthMode::Disabled), + ) +} + +pub(super) fn picture_texture([width, height]: [u32; 2], rgba8: Vec) -> VulkanStaticTexture { VulkanStaticTexture { - width: EXTENT[0], - height: EXTENT[1], + width, + height, rgba8, mip_levels: Vec::new(), } @@ -273,4 +438,29 @@ mod tests { menu.navigate(false); assert_eq!(menu.visible_slots(), 6..8); } + + #[test] + fn previewing_a_project_changes_the_factory_selection_only_on_transfer() { + let mut menu = FactoryMenu::new( + (0..2) + .map(|scheme| FactoryChoice { + factory: None, + scheme, + name: format!("{scheme}.dat"), + }) + .collect(), + ); + menu.open_designer(); + menu.designer_action(DesignerAction::Send); + assert!(menu.designer.is_some()); + menu.designer_action(DesignerAction::Project(1)); + menu.designer_action(DesignerAction::Exit); + assert_eq!(menu.selected().scheme, 0); + + menu.open_designer(); + menu.designer_action(DesignerAction::Project(1)); + menu.designer_action(DesignerAction::Send); + 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 65f8bc59..4b5734b0 100644 --- a/apps/fparkan-game/src/main.rs +++ b/apps/fparkan-game/src/main.rs @@ -42,6 +42,8 @@ mod player_service; mod projectile_render; mod projectile_sound; mod projectile_trail; +#[cfg(windows)] +mod robot_designer; mod shield_effects; mod shot_sound; use mission_loading::{MissionLoading, Stage as LoadingStage}; @@ -10830,7 +10832,13 @@ impl StaticVulkanApp { Some("Завод — нет подходящих схем".into()); None } - 1 if !remote => choices.pop(), + 1 if !remote + && !self.overlay.factory_projects.as_ref().is_some_and( + factory_menu::FactoryProjectPanel::designer_available, + ) => + { + choices.pop() + } _ => { self.factory_menu = Some(FactoryMenu::new(choices)); self.pressed_keys.clear(); diff --git a/apps/fparkan-game/src/mission_overlay.rs b/apps/fparkan-game/src/mission_overlay.rs index d6c0a242..ee3c2425 100644 --- a/apps/fparkan-game/src/mission_overlay.rs +++ b/apps/fparkan-game/src/mission_overlay.rs @@ -18,7 +18,7 @@ pub(super) use fparkan_assets::ui_sprite::source_over; pub(super) struct MissionOverlay { pub(super) satellite_map: Option, dial: Option, - factory_projects: Option, + pub(super) factory_projects: Option, pub(super) radar: Option, #[cfg(windows)] pub(super) hints: Option, @@ -138,7 +138,9 @@ impl MissionOverlay { } } if let Some(panel) = &self.factory_projects { - remove(panel.range_index(), ranges, counts); + for range in panel.ranges() { + remove(range, ranges, counts); + } } #[cfg(windows)] if let Some(hints) = &self.hints { @@ -230,7 +232,11 @@ impl StaticVulkanApp { help.draw(renderer, &mut self.mesh, frame.viewport)?; } if let Some(panel) = &mut self.overlay.factory_projects { - panel.draw(renderer, self.factory_menu.as_mut())?; + panel.draw( + renderer, + self.factory_menu.as_mut(), + self.mission_engine.as_ref(), + )?; } Ok(()) } diff --git a/apps/fparkan-game/src/robot_designer.rs b/apps/fparkan-game/src/robot_designer.rs new file mode 100644 index 00000000..80005b89 --- /dev/null +++ b/apps/fparkan-game/src/robot_designer.rs @@ -0,0 +1,74 @@ +use super::{ + factory_menu::{append_picture, picture_texture, FactoryMenu}, + DirectoryVfs, EnvironmentGpuRange, StaticPreviewScene, VulkanSmokeRenderer, +}; +use fparkan_assets::designer_screen::{DesignerLabels, DesignerPicture, DesignerScreen, EXTENT}; +use fparkan_platform_winit::text::StringResources; +use fparkan_runtime::{factory_project_components, Engine}; +use std::path::Path; + +pub(super) struct RobotDesignerPanel { + assets: DesignerScreen, + range: EnvironmentGpuRange, +} + +impl RobotDesignerPanel { + pub(super) fn load(root: &Path, preview: &mut StaticPreviewScene) -> Result { + let strings = StringResources::open(&root.join("iron3d.dll"))?; + let read = |id| { + strings + .get(id) + .ok_or_else(|| format!("missing designer label {id:#06x}")) + }; + let assets = DesignerScreen::load( + &DirectoryVfs::new(root), + DesignerLabels { + title: read(0x5e7)?, + recent: read(0x616)?, + send: read(0x184e)?, + exit: read(0x615)?, + }, + )?; + let range = append_picture(preview, EXTENT, [0.0, 0.0, 640.0, 480.0])?; + Ok(Self { assets, range }) + } + + pub(super) fn range_index(&self) -> usize { + self.range.range_index + } + + pub(super) fn draw( + &mut self, + renderer: &mut VulkanSmokeRenderer, + menu: Option<&mut FactoryMenu>, + engine: Option<&Engine>, + ) -> Result<(), String> { + let visible = menu.as_ref().is_some_and(|menu| menu.designer.is_some()); + if let Some(menu) = menu { + if let Some(designer) = menu.designer.as_mut().filter(|view| view.dirty) { + let project = designer.selected.and_then(|slot| { + let choice = &menu.choices[designer.slots.start + slot]; + let parts = factory_project_components(engine?, choice.scheme)?; + Some((slot, choice.name.as_str(), parts)) + }); + let image = self.assets.paint(DesignerPicture { + count: designer.slots.len(), + project, + first_part: designer.first_part, + hover: designer.hover, + })?; + renderer + .update_material_texture( + self.range.material_index, + 0, + &picture_texture(EXTENT, image.rgba8), + ) + .map_err(|error| error.to_string())?; + designer.dirty = false; + } + } + renderer + .set_draw_range_index_count(self.range.range_index, if visible { 6 } else { 0 }) + .map_err(|error| error.to_string()) + } +} diff --git a/crates/fparkan-assets/src/designer_screen.rs b/crates/fparkan-assets/src/designer_screen.rs new file mode 100644 index 00000000..fea9eef9 --- /dev/null +++ b/crates/fparkan-assets/src/designer_screen.rs @@ -0,0 +1,251 @@ +//! Project selection and the installed parts of the selected Unit DAT. + +use crate::{ + factory_projects::PROJECT_SLOTS, + game_font::{load_game_font, BitmapFont}, + mission_pager::{copy_sprite, scale, UiFrame}, + object_descriptions::ObjectDescriptions, + ui_sprite::{atlas_region, load_ui_page}, + RgbaImage, +}; +use encoding_rs::WINDOWS_1251; +use fparkan_prototype::{unit_component_tree, UnitComponentRecord}; +use fparkan_vfs::Vfs; + +const SEND: [u32; 4] = [194, 437, 229, 480]; +const EXIT: [u32; 4] = [405, 437, 446, 480]; +/// Extent of the designer's original font profile. +pub const EXTENT: [u32; 2] = [800, 600]; +/// Number of part rows in the project viewport. +pub const PART_ROWS: usize = 18; + +/// Controls in logical 640×480 coordinates. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DesignerAction { + /// Restore a recent project in the designer. + Project(usize), + /// Assign the currently open project to the factory. + Send, + /// Return to the factory panel. + Exit, +} + +/// Original strings that label the currently supported designer actions. +pub struct DesignerLabels { + /// Constructor title. + pub title: String, + /// Recent project list. + pub recent: String, + /// Transfer to the connected factory. + pub send: String, + /// Close the designer. + pub exit: String, +} + +/// Original UI resources required by the project view of the designer. +pub struct DesignerScreen { + font: BitmapFont, + frame: UiFrame, + descriptions: ObjectDescriptions, + recent: RgbaImage, + send: RgbaImage, + send_frame: RgbaImage, + exit: RgbaImage, + exit_frame: RgbaImage, + labels: DesignerLabels, +} + +/// Selection and scroll state to compose on the screen. +pub struct DesignerPicture<'a> { + /// Number of populated history slots. + pub count: usize, + /// Previewed project name and parts, when a slot has been opened. + pub project: Option<(usize, &'a str, &'a [UnitComponentRecord])>, + /// First component row in the pane. + pub first_part: usize, + /// Action whose original tooltip is shown. + pub hover: Option, +} + +impl DesignerScreen { + /// Reads the original sheets, display font and prototype descriptions. + pub fn load(vfs: &dyn Vfs, labels: DesignerLabels) -> Result { + let icons = load_ui_page(vfs, "icons")?; + let frames = load_ui_page(vfs, "page4")?; + let sprite = |page: &RgbaImage, [x, y, width, height]: [u32; 4]| { + atlas_region(page, [x, y, width, height]) + .ok_or_else(|| format!("designer sprite outside its page at {x},{y}")) + }; + Ok(Self { + font: load_game_font(vfs)?, + frame: UiFrame::load(vfs)?, + descriptions: ObjectDescriptions::load(vfs)?, + recent: sprite(&icons, [216, 96, 24, 24])?, + send: sprite(&icons, [176, 231, 24, 24])?, + send_frame: sprite(&frames, [84, 169, 35, 43])?, + exit: sprite(&icons, [192, 72, 24, 24])?, + exit_frame: sprite(&frames, [141, 213, 41, 43])?, + labels, + }) + } + + /// Paints the active project and every installed mount in Unit DAT order. + pub fn paint(&self, view: DesignerPicture<'_>) -> Result { + let [width, height] = EXTENT; + let mut image = RgbaImage { + width, + height, + rgba8: vec![0; (width * height * 4) as usize], + }; + for pixel in image.rgba8.chunks_exact_mut(4) { + pixel[3] = 255; + } + self.frame + .paint(&mut image, [185, 2, 455, 480], [0, 48, 0, 255]); + self.text(&mut image, &self.labels.title, [194, 10, 446, 26], [255; 3])?; + self.text( + &mut image, + &self.labels.recent, + [199, 250, 350, 268], + [100, 255, 100], + )?; + let selected = view.project.map(|(index, _, _)| index); + for index in 0..view.count.min(PROJECT_SLOTS) { + let tint = if selected == Some(index) { + [255; 3] + } else { + [160; 3] + }; + sprite(&mut image, &self.recent, recent_slot(index), tint); + } + if let Some((_, name, records)) = view.project { + self.text(&mut image, name, [194, 27, 446, 42], [255, 255, 100])?; + self.paint_parts(&mut image, records, view.first_part)?; + sprite(&mut image, &self.send_frame, SEND, [255; 3]); + sprite(&mut image, &self.send, [201, 450, 225, 474], [255; 3]); + } + sprite(&mut image, &self.exit_frame, EXIT, [255; 3]); + sprite(&mut image, &self.exit, [413, 450, 437, 474], [255; 3]); + let hint = match view.hover { + Some(DesignerAction::Send) => &self.labels.send, + Some(DesignerAction::Exit) => &self.labels.exit, + _ => return Ok(image), + }; + self.text(&mut image, hint, [194, 418, 446, 436], [255; 3])?; + Ok(image) + } + + fn paint_parts( + &self, + image: &mut RgbaImage, + records: &[UnitComponentRecord], + first: usize, + ) -> Result<(), String> { + let tree = unit_component_tree(records).map_err(|error| error.to_string())?; + let mut depth = Vec::with_capacity(tree.len()); + for node in tree { + depth.push(node.parent_index.map_or(0_u32, |parent| depth[parent] + 1)); + } + for (row, record) in records.iter().skip(first).take(PART_ROWS).enumerate() { + let key = field(&record.resource_raw); + let description = self + .descriptions + .short_name(key) + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| field(&record.description_raw)); + let text = if description.is_empty() { + key + } else { + description + }; + let [width, glyph_height] = self.font.line_metrics_bytes(text)?; + if width == 0 { + continue; + } + let left = scale(196 + depth[first + row].min(8) * 7); + let top = scale(46 + 10 * row as u32); + let width = width.min((scale(446) - left) as u16); + let glyphs = self.font.centered_line_bytes(text, width, glyph_height)?; + copy_sprite( + image, + &glyphs, + [ + left, + top, + left + u32::from(width), + top + u32::from(glyph_height), + ], + [false; 2], + [255; 3], + ); + } + Ok(()) + } + + fn text( + &self, + image: &mut RgbaImage, + text: &str, + bounds: [u32; 4], + tint: [u8; 3], + ) -> Result<(), String> { + let [l, t, r, b] = bounds.map(scale); + let (bytes, _, _) = WINDOWS_1251.encode(text); + let labels = self + .font + .centered_line_bytes(&bytes, (r - l) as u16, (b - t) as u16)?; + copy_sprite(image, &labels, [l, t, r, b], [false; 2], tint); + Ok(()) + } +} + +/// Maps pointer input to a populated history slot or available command. +pub fn hit_test([x, y]: [f32; 2], count: usize, has_project: bool) -> Option { + let hit = + |[l, t, r, b]: [u32; 4]| x >= l as f32 && x < r as f32 && y >= t as f32 && y < b as f32; + if hit(EXIT) { + return Some(DesignerAction::Exit); + } + if has_project && hit(SEND) { + return Some(DesignerAction::Send); + } + (0..count.min(PROJECT_SLOTS)) + .find(|&index| hit(recent_slot(index))) + .map(DesignerAction::Project) +} + +fn recent_slot(index: usize) -> [u32; 4] { + let left = 200 + 30 * index as u32; + [left, 270, left + 24, 294] +} + +fn field(raw: &[u8; 32]) -> &[u8] { + raw.split(|&byte| byte == 0).next().unwrap_or_default() +} + +fn sprite(image: &mut RgbaImage, source: &RgbaImage, rect: [u32; 4], tint: [u8; 3]) { + copy_sprite(image, source, rect.map(scale), [false; 2], tint); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn project_picker_uses_populated_slots_and_needs_a_project_to_send() { + assert_eq!( + hit_test([240.0, 278.0], 2, false), + Some(DesignerAction::Project(1)) + ); + assert_eq!(hit_test([240.0, 278.0], 1, false), None); + assert_eq!(hit_test([201.0, 455.0], 2, false), None); + assert_eq!( + hit_test([201.0, 455.0], 2, true), + Some(DesignerAction::Send) + ); + assert_eq!( + hit_test([420.0, 455.0], 0, false), + Some(DesignerAction::Exit) + ); + } +} diff --git a/crates/fparkan-assets/src/factory_projects.rs b/crates/fparkan-assets/src/factory_projects.rs index 94973b22..ca77137a 100644 --- a/crates/fparkan-assets/src/factory_projects.rs +++ b/crates/fparkan-assets/src/factory_projects.rs @@ -16,6 +16,7 @@ pub const ORIGIN: [u32; 2] = [50, 122]; // A transparent texel on each side keeps repeat sampling from bleeding buttons across the quad. pub const EXTENT: [u32; 2] = [328, 48]; const BUILD: [u32; 4] = [277, 28, 327, 47]; +const CONSTRUCTOR: [u32; 4] = [20, 28, 70, 47]; /// A command selected with the pointer. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -24,6 +25,8 @@ pub enum FactoryProjectAction { Select(usize), /// Queue the selected project at this factory. Build, + /// Open the active factory's model designer. + Designer, } /// Original button frames, icons and game font for the project controls. @@ -32,13 +35,14 @@ pub struct FactoryProjectImages { project: RgbaImage, build_frame: RgbaImage, build_icon: RgbaImage, + constructor_icon: RgbaImage, font: BitmapFont, } impl FactoryProjectImages { /// Resolves factory sprites and text through the installed game's catalogs. pub fn load(vfs: &dyn Vfs) -> Result { - let [idle, pressed, project, build_icon] = load_ui_sprites( + let [idle, pressed, project, build_icon, constructor_icon] = load_ui_sprites( vfs, "ui/hq.cfg", [ @@ -46,6 +50,7 @@ impl FactoryProjectImages { "short_button_frame_on", "project_icon", "build_icon", + "constructor_icon", ], )?; let [build_frame] = load_ui_sprites(vfs, "ui/compaund.cfg", ["ccres_long_button_normal"])?; @@ -53,6 +58,7 @@ impl FactoryProjectImages { frames: [idle, pressed], project, build_icon, + constructor_icon, build_frame, font: load_layout_font(vfs)?, }) @@ -65,6 +71,7 @@ impl FactoryProjectImages { selected: usize, pressed: Option, name: &str, + designer_available: bool, ) -> Result { let mut image = RgbaImage { width: EXTENT[0], @@ -92,18 +99,25 @@ impl FactoryProjectImages { }, ); } - copy_sprite(&mut image, &self.build_frame, BUILD, [false; 2], [255; 3]); - let [left, top, _, _] = BUILD; + self.paint_button(&mut image, BUILD, &self.build_icon); + if designer_available { + self.paint_button(&mut image, CONSTRUCTOR, &self.constructor_icon); + } + let label = self.font.centered_line(name, 150, 16)?; + copy_sprite(&mut image, &label, [125, 17, 275, 33], [false; 2], [255; 3]); + Ok(image) + } + + fn paint_button(&self, image: &mut RgbaImage, rect: [u32; 4], icon: &RgbaImage) { + copy_sprite(image, &self.build_frame, rect, [false; 2], [255; 3]); + let [left, top, _, _] = rect; copy_sprite( - &mut image, - &self.build_icon, + image, + icon, [left + 10, top + 2, left + 40, top + 17], [false; 2], [240; 3], ); - let label = self.font.centered_line(name, 150, 16)?; - copy_sprite(&mut image, &label, [1, 22, 151, 38], [false; 2], [255; 3]); - Ok(image) } } @@ -118,6 +132,9 @@ pub fn hit_test(position: [f32; 2], count: usize) -> Option( let [x, y, width, height] = ["OFFSET_X", "OFFSET_Y", "WIDTH", "HEIGHT"].map(|key| number(®ion, key)); let [x, y, width, height] = [x?, y?, width?, height?]; - if width == 0 - || height == 0 - || x.checked_add(width).is_none_or(|right| right > image.width) - || y.checked_add(height) - .is_none_or(|bottom| bottom > image.height) - { - return Err(format!("UI sprite {name} is outside atlas page {page}")); - } - let rgba8 = (y..y + height) - .flat_map(|row| { - let start = (row as usize * image.width as usize + x as usize) * 4; - image.rgba8[start..start + width as usize * 4] - .iter() - .copied() - }) - .collect(); - let image = RgbaImage { - width, - height, - rgba8, - }; + let image = atlas_region(image, [x, y, width, height]) + .ok_or_else(|| format!("UI sprite {name} is outside atlas page {page}"))?; let angle = if region.contains_key("ROTATE") { number(®ion, "ROTATE")? } else { @@ -75,6 +56,30 @@ pub fn load_ui_sprites( .expect("one rectangle per UI sprite name")) } +pub(crate) fn atlas_region( + image: &RgbaImage, + [x, y, width, height]: [u32; 4], +) -> Option { + let right = x.checked_add(width)?; + let bottom = y.checked_add(height)?; + if width == 0 || height == 0 || right > image.width || bottom > image.height { + return None; + } + let rgba8 = (y..bottom) + .flat_map(|row| { + let start = (row as usize * image.width as usize + x as usize) * 4; + image.rgba8[start..start + width as usize * 4] + .iter() + .copied() + }) + .collect(); + Some(RgbaImage { + width, + height, + rgba8, + }) +} + fn rotate(image: RgbaImage, angle: u32) -> Result { let (w, h) = (image.width, image.height); let (width, height) = match angle { diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index c5794e55..b5527a4a 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -197,8 +197,8 @@ pub use player_weapon::{ WeaponIndicator, WeaponLamp, }; pub use production::{ - clan_factory_schemes, factory_schemes, order_clan_factory_scheme, order_factory_robot, - order_factory_scheme, + clan_factory_schemes, factory_project_components, factory_schemes, order_clan_factory_scheme, + order_factory_robot, order_factory_scheme, }; pub use projectile::{ apply_projectile_contact, apply_projectile_hit, apply_projectile_impact, diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs index 3d3eb159..9f6846f8 100644 --- a/crates/fparkan-runtime/src/production.rs +++ b/crates/fparkan-runtime/src/production.rs @@ -387,6 +387,21 @@ pub fn clan_factory_schemes( .collect()) } +/// Components of a prepared player project, in the original Unit DAT order. +pub fn factory_project_components( + engine: &Engine, + scheme: usize, +) -> Option<&[UnitComponentRecord]> { + let (mission, production) = loaded_production(engine).ok()?; + if scheme >= production.player_scheme_count { + return None; + } + mission + .object_drafts + .get(production.reserve_start + scheme * RESERVE_SLOTS) + .map(|draft| draft.unit_components.as_slice()) +} + fn schemes_for_plant<'a>( mission: &'a LoadedMissionState, production: &'a Production, diff --git a/docs/tomes/06-behavior.md b/docs/tomes/06-behavior.md index 73bb4bea..92d1ebd3 100644 --- a/docs/tomes/06-behavior.md +++ b/docs/tomes/06-behavior.md @@ -3750,8 +3750,19 @@ RVA `0x10abc` он задаёт диапазон случайного смеще Выбранный значок белый, остальные получают светло-зелёный оттенок. В FParkan под строкой показано имя текущего файла схемы игровым шрифтом. -На коммуникаторе B показывает схемы этого -завода или сразу заказывает единственную подходящую. При запуске можно +Кнопка конструктора находится слева от кнопки сборки. В оригинале +нажатие по RVA `0x97fe0` передаёт завод режиму конструктора через +RVA `0x56090`. Внутри пять ячеек «Последние проекты» идут с X=200 +с шагом 30, на Y=270. Щелчок по ячейке загружает соответствующее дерево +компонентов. В FParkan читаются данные подготовленной схемы и подписи +компонентов из `objects.dlb` или поля описания Unit DAT. У разных +креплений одной детали сохраняются отдельные строки. +Команда «Передать модель на завод» возвращает выбранный проект в панель +завода. Сборка начинается отдельным заказом. Выход из конструктора +сохраняет прежний выбор завода. Подписи команд читаются из `iron3d.dll`, +значки ячеек и команд — из листа `icons`, рамки кнопок — из `page4`. + +На коммуникаторе B показывает схемы этого завода. При запуске можно указать одну схему через `--build-scheme`. Повторяемый параметр `--build-part СТАРАЯ=НОВАЯ` заменяет внутренние детали этой схемы. Например, `i_pws_b_02=i_pws_b_01` ставит другой аккумулятор в тот же -- cgit v1.2.3