aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorValentin Popov <valentin@popov.link>2026-11-14 10:04:55 +0300
committerValentin Popov <valentin@popov.link>2026-11-14 10:04:55 +0300
commite8e55549d6bd984a01c09eb49882bf3f70090633 (patch)
treef266a985b5a6fe0c75a4818d9d8b257d052bb9a7 /crates
parente116199498486545a188582a44942c02786aab07 (diff)
downloadfparkan-e8e55549d6bd984a01c09eb49882bf3f70090633.tar.xz
fparkan-e8e55549d6bd984a01c09eb49882bf3f70090633.zip
feat(runtime): build a free robot at a captured factory
Diffstat (limited to 'crates')
-rw-r--r--crates/fparkan-runtime/src/autodemo.rs93
-rw-r--r--crates/fparkan-runtime/src/lib.rs123
-rw-r--r--crates/fparkan-runtime/src/mission_events.rs2
-rw-r--r--crates/fparkan-runtime/src/production.rs215
4 files changed, 388 insertions, 45 deletions
diff --git a/crates/fparkan-runtime/src/autodemo.rs b/crates/fparkan-runtime/src/autodemo.rs
index cd9b14cb..15338b0f 100644
--- a/crates/fparkan-runtime/src/autodemo.rs
+++ b/crates/fparkan-runtime/src/autodemo.rs
@@ -16,7 +16,7 @@ use std::sync::Arc;
const PITCH: f32 = 1.25;
const YAW: f32 = std::f32::consts::FRAC_PI_2;
const FOLLOW_DISTANCE: f32 = 30.0;
-const PLANT_CLASS: u32 = 0x8000_0010;
+pub(super) const PLANT_CLASS: u32 = 0x8000_0010;
pub(super) const MOBILE_UNIT: u32 = 0x0100_0000;
pub(super) fn read_config(
@@ -49,7 +49,7 @@ pub(super) struct LiveReinforcements {
/// A reserve model activated with a newly registered world object.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub struct AutoDemoReinforcement {
+pub struct SpawnedUnit {
/// Prepared scene object index.
pub object_index: usize,
/// New world handle.
@@ -58,6 +58,9 @@ pub struct AutoDemoReinforcement {
pub clan: u16,
}
+/// A unit created by AutoDemo's replacement policy.
+pub type AutoDemoReinforcement = SpawnedUnit;
+
impl LiveReinforcements {
pub(super) fn new(
plan: Reinforcements,
@@ -157,42 +160,14 @@ impl LiveReinforcements {
&mission.terrain,
&mut self.rng,
)?;
- let draft = &mission.object_drafts[index];
- let handle = construct_replacement(
+ let handle = spawn_prepared_unit(
world,
- ObjectDraft {
- original_id: draft.original_id,
- },
+ mission,
+ index,
+ clan,
+ position,
+ self.controls[index - self.reserve_start].clone(),
)?;
- let pose = TransformState {
- position: position.map(f32::to_bits),
- orientation: draft.orientation_raw.map(f32::to_bits),
- scale: draft.scale.map(f32::to_bits),
- };
- if let Err(error) = set_transform(world, handle, pose)
- .and_then(|()| set_owner(world, handle, Some(OwnerId(clan))))
- .and_then(|()| register_object(world, handle))
- {
- fparkan_world::request_delete(world, handle)?;
- return Err(error.into());
- }
- mission
- .control_device_tables
- .retain(|table| transform_state(world, table.handle).is_ok());
- mission
- .behavior_control_groupings
- .retain(|group| transform_state(world, group.handle).is_ok());
- let mut table = self.controls[index - self.reserve_start].clone();
- table.handle = handle;
- mission
- .behavior_control_groupings
- .push(super::project_mission_behavior_control_grouping(&table));
- mission.control_device_tables.push(table);
- mission.mission_events.register_unit(
- world,
- handle,
- draft.unit_dat_header_flags.expect("mobile reserve"),
- );
if let Some(patrol) = &mut mission.unit_patrol {
patrol.activate(world, handle);
}
@@ -200,6 +175,52 @@ impl LiveReinforcements {
}
}
+pub(super) fn spawn_prepared_unit(
+ world: &mut World,
+ mission: &mut super::LoadedMissionState,
+ index: usize,
+ clan: u16,
+ position: [f32; 3],
+ mut table: MissionControlDeviceTableState,
+) -> Result<ObjectHandle, EngineError> {
+ let draft = &mission.object_drafts[index];
+ let handle = construct_replacement(
+ world,
+ ObjectDraft {
+ original_id: draft.original_id,
+ },
+ )?;
+ let pose = TransformState {
+ position: position.map(f32::to_bits),
+ orientation: draft.orientation_raw.map(f32::to_bits),
+ scale: draft.scale.map(f32::to_bits),
+ };
+ if let Err(error) = set_transform(world, handle, pose)
+ .and_then(|()| set_owner(world, handle, Some(OwnerId(clan))))
+ .and_then(|()| register_object(world, handle))
+ {
+ fparkan_world::request_delete(world, handle)?;
+ return Err(error.into());
+ }
+ mission
+ .control_device_tables
+ .retain(|table| transform_state(world, table.handle).is_ok());
+ mission
+ .behavior_control_groupings
+ .retain(|group| transform_state(world, group.handle).is_ok());
+ table.handle = handle;
+ mission
+ .behavior_control_groupings
+ .push(super::project_mission_behavior_control_grouping(&table));
+ mission.control_device_tables.push(table);
+ mission.mission_events.register_unit(
+ world,
+ handle,
+ draft.unit_dat_header_flags.expect("mobile reserve"),
+ );
+ Ok(handle)
+}
+
pub(super) fn plan_reinforcements(
vfs: &Arc<dyn Vfs>,
mission: &super::MissionDocument,
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 94e61948..af069b33 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -47,10 +47,13 @@ mod mesh_collision;
mod mission_events;
mod player_motion;
mod player_weapon;
+mod production;
mod projectile;
mod unit_patrol;
-pub use autodemo::{autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView};
+pub use autodemo::{
+ autodemo_camera, AutoDemoCamera, AutoDemoReinforcement, AutoDemoView, SpawnedUnit,
+};
pub use autodemo_combat::{AutoDemoCombatEvent, AutoDemoProjectileType};
pub use fparkan_assets::MissionAssets;
pub use mesh_collision::{query_building_segment_world, BuildingMeshHit, BuildingMeshNode};
@@ -61,6 +64,7 @@ pub use mission_events::{
};
pub use player_motion::{plan_player_motion, PlayerMotion, PlayerMotionStep};
pub use player_weapon::{starting_player_weapons, PlayerWeapons};
+pub use production::order_factory_robot;
pub use projectile::{
apply_projectile_hit, load_player_projectile, projectile_terrain_hit, projectile_unit_hit,
PlayerProjectile, ProjectileAssets, ProjectileContact,
@@ -1289,6 +1293,10 @@ pub struct FrameResult {
pub autodemo_reinforcements: Vec<AutoDemoReinforcement>,
/// Failed replacement attempts.
pub autodemo_reinforcement_unavailable: usize,
+ /// Robot completed by a player factory order on this tick.
+ pub produced_unit: Option<SpawnedUnit>,
+ /// Diagnostic for a production order whose unit could not be created.
+ pub production_failure: Option<String>,
}
/// Engine.
@@ -1299,6 +1307,7 @@ pub struct Engine {
behavior_rng_state: u32,
autodemo_combat: Option<autodemo_combat::AutoDemoCombat>,
autodemo_reinforcements: Option<autodemo::LiveReinforcements>,
+ production: Option<production::Production>,
}
struct LoadedMissionState {
@@ -1474,6 +1483,8 @@ pub enum EngineError {
World(fparkan_world::WorldError),
/// Reference movement input or terrain query failed.
Movement(String),
+ /// Invalid or unavailable player construction order.
+ Production(String),
/// Staged mission world was torn down after a registration-phase failure.
RegistrationTeardown {
/// Registered objects before the forced failure.
@@ -1621,6 +1632,7 @@ impl std::fmt::Display for EngineError {
} => write!(f, "Behavior resource tick for clan {clan_index}: {message}"),
Self::World(source) => write!(f, "{source}"),
Self::Movement(message) => write!(f, "reference movement: {message}"),
+ Self::Production(message) => write!(f, "factory: {message}"),
Self::RegistrationTeardown {
registered_objects,
released_objects,
@@ -1653,6 +1665,7 @@ impl std::error::Error for EngineError {
| Self::ScriptRuntime { .. }
| Self::MissionAiRecordSlots { .. }
| Self::Movement(_)
+ | Self::Production(_)
| Self::ResearchTrfPath { .. }
| Self::PrototypeGraph { .. }
| Self::BehaviorProfile { .. }
@@ -1671,6 +1684,7 @@ pub fn create(services: EngineServices) -> Result<Engine, EngineError> {
behavior_rng_state: INITIAL_BEHAVIOR_RNG_STATE,
autodemo_combat: None,
autodemo_reinforcements: None,
+ production: None,
})
}
@@ -1700,6 +1714,7 @@ pub fn load_mission(
request,
MissionLoadOptions::default(),
Some(startup_input),
+ None,
)
}
@@ -1715,6 +1730,28 @@ pub fn load_mission_with_init_stubs(
request: MissionRequest,
startup_input: MissionStartupInput,
) -> Result<LoadedMission, EngineError> {
+ load_gameplay_mission(engine, request, startup_input, None)
+}
+
+/// Loads the gameplay world and prepares the player's optional Unit DAT design.
+///
+/// # Errors
+///
+/// Returns an error if the mission or selected design cannot be loaded.
+pub fn load_gameplay_mission(
+ engine: &mut Engine,
+ request: MissionRequest,
+ startup_input: MissionStartupInput,
+ build_scheme: Option<&str>,
+) -> Result<LoadedMission, EngineError> {
+ if build_scheme.is_some() && request.mode != MissionMode::SingleMission {
+ return Err(EngineError::Production(
+ "build schemes require a player mission".into(),
+ ));
+ }
+ let build_scheme = build_scheme
+ .map(|path| normalize_engine_path("factory Unit DAT", path))
+ .transpose()?;
load_mission_with_options(
engine,
request,
@@ -1724,6 +1761,7 @@ pub fn load_mission_with_init_stubs(
..MissionLoadOptions::default()
},
Some(startup_input),
+ build_scheme.as_ref(),
)
}
@@ -1751,6 +1789,7 @@ pub fn load_mission_static_preview(
..MissionLoadOptions::default()
},
None,
+ None,
)
}
@@ -1775,6 +1814,7 @@ pub fn load_mission_static_preview_roots(
..MissionLoadOptions::default()
},
None,
+ None,
)
}
@@ -1783,6 +1823,7 @@ fn load_mission_with_options(
request: MissionRequest,
options: MissionLoadOptions,
startup_input: Option<MissionStartupInput>,
+ build_scheme: Option<&NormalizedPath>,
) -> Result<LoadedMission, EngineError> {
let vfs = engine.services.vfs.clone().ok_or(EngineError::MissingVfs)?;
let mission_path = normalize_engine_path("mission", &request.key)?;
@@ -1870,6 +1911,7 @@ fn load_mission_with_options(
.take(plan.reserve_per_scheme)
}));
}
+ graph_roots.extend(build_scheme.map(|scheme| resource_name(scheme.as_str().as_bytes())));
let scoped_graph_roots = match options.asset_scope {
MissionAssetScope::Full => graph_roots.as_slice(),
MissionAssetScope::FirstMeshPreview => graph_roots.get(..1).unwrap_or_default(),
@@ -2337,15 +2379,37 @@ fn load_mission_with_options(
for &handle in &handles[reserve_start..] {
fparkan_world::request_delete(&mut new_runtime_world, handle)?;
}
- let autodemo_reinforcements = reinforcements.map(|plan| {
- let controls = control_device_tables.split_off(reserve_start);
+ let reserve_controls = if graph_roots.len() > reserve_start {
behavior_control_groupings.truncate(reserve_start);
- autodemo::LiveReinforcements::new(plan, reserve_start, spawn_rng, controls)
- });
+ control_device_tables.split_off(reserve_start)
+ } else {
+ Vec::new()
+ };
+ let (autodemo_reinforcements, production) = if build_scheme.is_some() {
+ let control = reserve_controls.into_iter().next().ok_or_else(|| {
+ EngineError::Production("missing Control table for build scheme".into())
+ })?;
+ (
+ None,
+ Some(production::Production::new(
+ reserve_start,
+ control,
+ &object_drafts,
+ )?),
+ )
+ } else {
+ (
+ reinforcements.map(|plan| {
+ autodemo::LiveReinforcements::new(plan, reserve_start, spawn_rng, reserve_controls)
+ }),
+ None,
+ )
+ };
engine.world = new_runtime_world;
engine.behavior_rng_state = next_behavior_rng_state;
engine.autodemo_combat = autodemo_combat;
engine.autodemo_reinforcements = autodemo_reinforcements;
+ engine.production = production;
engine.loaded = Some(LoadedMissionState {
summary: summary.clone(),
mission,
@@ -2463,7 +2527,17 @@ pub fn step_headless(
combat.activate(&engine.world, event.object_index, event.handle);
}
}
- if !autodemo_reinforcements.is_empty()
+ let (produced_unit, production_failure) =
+ if let (Some(production), Some(mission)) = (&mut engine.production, &mut engine.loaded) {
+ match production.tick(&mut engine.world, mission, queue_time_ms) {
+ Ok(unit) => (unit, None),
+ Err(error) => (None, Some(error.to_string())),
+ }
+ } else {
+ (None, None)
+ };
+ if produced_unit.is_some()
+ || !autodemo_reinforcements.is_empty()
|| autodemo_combat_events
.iter()
.any(|event| matches!(event, AutoDemoCombatEvent::Destroyed { .. }))
@@ -2481,6 +2555,8 @@ pub fn step_headless(
autodemo_combat_unavailable,
autodemo_reinforcements,
autodemo_reinforcement_unavailable,
+ produced_unit,
+ production_failure,
player_pitch_bits: engine
.loaded
.as_ref()
@@ -2533,7 +2609,7 @@ pub fn frame_with_player_motion(
/// Coverage entries for the subsystems still absent from the mission loop.
pub const SIMULATION_COVERAGE: &str =
- "sim_coverage research_startup_gate_stub=1 mission_handlers_stub=1 unit_behavior_stub=1 render_object_lifecycle_stub=1 render_winding_change_stub=1 mission_event_clock_approx=1 mission_tactical_ids_stub=1 mission_clan_roster_stub=1 mission_message_ui_stub=1";
+ "sim_coverage research_startup_gate_stub=1 mission_handlers_stub=1 unit_behavior_stub=1 render_object_lifecycle_stub=1 render_winding_change_stub=1 mission_event_clock_approx=1 mission_tactical_ids_stub=1 mission_clan_roster_stub=1 mission_message_ui_stub=1 factory_orders_approx=1";
/// Totals from a headless mission coverage run.
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -17636,7 +17712,7 @@ mod tests {
let vfs: Arc<dyn Vfs> = Arc::new(DirectoryVfs::new(licensed_root("IS")));
let mut engine = create(EngineServices::new(vfs)).unwrap();
- load_mission_with_init_stubs(
+ load_gameplay_mission(
&mut engine,
MissionRequest {
key: "MISSIONS/CAMPAIGN/CAMPAIGN.00/Mission.02/data.tma".into(),
@@ -17646,6 +17722,7 @@ mod tests {
queue_time_ms: 0,
research_creation_gate: false,
},
+ Some("UNITS/UNITS/PREBLD/tut2_f1.dat"),
)
.unwrap();
let initial = frame(&mut engine, 1).unwrap().mission_event.unwrap();
@@ -17655,6 +17732,7 @@ mod tests {
.iter()
.any(|notice| matches!(notice, MissionNotice::ObjectiveComplete(0 | 2))));
let cockpit = starting_cockpit(&engine).unwrap();
+ assert!(order_factory_robot(&mut engine, cockpit, 1).is_err());
assert_eq!(
capture_neutral_building(&mut engine, cockpit).unwrap(),
None
@@ -17714,6 +17792,34 @@ mod tests {
loaded_mission_script_outcome(&engine),
Some(MissionScriptOutcome::Active)
);
+ player_pose.position = [391.3_f32, 740.1, 145.12].map(f32::to_bits);
+ set_transform(&mut engine.world, cockpit.handle, player_pose).unwrap();
+ assert_eq!(
+ order_factory_robot(&mut engine, cockpit, 4001).unwrap(),
+ 60_000
+ );
+ assert!(order_factory_robot(&mut engine, cockpit, 4002).is_err());
+ let early = frame(&mut engine, 64_000).unwrap();
+ assert!(early.produced_unit.is_none());
+ let complete = frame(&mut engine, 64_001).unwrap();
+ let robot = complete.produced_unit.expect("finished robot");
+ assert!(complete.snapshot.objects.contains(&robot.handle));
+ assert_eq!(
+ identity_metadata(&engine.world, robot.handle)
+ .unwrap()
+ .owner_id,
+ Some(OwnerId(0))
+ );
+ assert!(order_factory_robot(&mut engine, cockpit, 64_001).is_err());
+ let next = frame(&mut engine, 66_001).unwrap();
+ assert!(next.produced_unit.is_none());
+ let event = next.mission_event.unwrap();
+ assert!(event.stop.is_none(), "{:?}", event.stop);
+ assert!(event.notices.contains(&MissionNotice::ObjectiveComplete(1)));
+ assert_eq!(
+ loaded_mission_script_outcome(&engine),
+ Some(MissionScriptOutcome::Completed)
+ );
}
#[test]
@@ -18568,6 +18674,7 @@ mod tests {
queue_time_ms: 0,
research_creation_gate: false,
}),
+ None,
)
.expect_err("forced registration failure");
diff --git a/crates/fparkan-runtime/src/mission_events.rs b/crates/fparkan-runtime/src/mission_events.rs
index cc78bf6a..10a0e867 100644
--- a/crates/fparkan-runtime/src/mission_events.rs
+++ b/crates/fparkan-runtime/src/mission_events.rs
@@ -303,7 +303,7 @@ pub fn capture_neutral_building(
}
}
-fn on_communicator(
+pub(super) fn on_communicator(
assets: &super::MissionAssets,
object_index: usize,
pose: super::TransformState,
diff --git a/crates/fparkan-runtime/src/production.rs b/crates/fparkan-runtime/src/production.rs
new file mode 100644
index 00000000..b944089a
--- /dev/null
+++ b/crates/fparkan-runtime/src/production.rs
@@ -0,0 +1,215 @@
+use super::{
+ autodemo::{
+ reinforcement_position, spawn_prepared_unit, SpawnedUnit, MOBILE_UNIT, PLANT_CLASS,
+ },
+ mission_events::on_communicator,
+ Engine, EngineError, LoadedMissionState, MissionControlDeviceTableState, MissionObjectDraft,
+ StartingCockpit, World,
+};
+use fparkan_world::{
+ handle_by_original_id, identity_metadata, transform_state, ObjectHandle, OwnerId,
+};
+
+pub(super) struct Production {
+ reserve: usize,
+ control: MissionControlDeviceTableState,
+ free_units: Vec<(usize, u32)>,
+ pending: Option<Order>,
+ rng: u32,
+}
+
+struct Order {
+ plant: ObjectHandle,
+ plant_index: usize,
+ owner: OwnerId,
+ start_ms: u32,
+ duration_ms: u32,
+}
+
+impl Production {
+ pub(super) fn new(
+ reserve: usize,
+ control: MissionControlDeviceTableState,
+ drafts: &[MissionObjectDraft],
+ ) -> Result<Self, EngineError> {
+ if !drafts[reserve]
+ .unit_dat_header_flags
+ .is_some_and(|class| class & MOBILE_UNIT != 0 && class != super::HERO_UNIT_CLASS)
+ {
+ return Err(EngineError::Production(
+ "build scheme must be a mobile Unit DAT".into(),
+ ));
+ }
+ let free_units = drafts[..reserve]
+ .iter()
+ .enumerate()
+ .filter(|(_, draft)| draft.unit_dat_header_flags == Some(PLANT_CLASS))
+ .map(|(index, draft)| {
+ let count = draft
+ .properties
+ .iter()
+ .find(|property| property.name_raw == b"FreeBotNum")
+ .map_or(1, |property| property.raw_value[1] as i32);
+ (index, count.max(0) as u32)
+ })
+ .collect();
+ Ok(Self {
+ reserve,
+ control,
+ free_units,
+ pending: None,
+ rng: 1,
+ })
+ }
+
+ pub(super) fn tick(
+ &mut self,
+ world: &mut World,
+ mission: &mut LoadedMissionState,
+ now_ms: u32,
+ ) -> Result<Option<SpawnedUnit>, EngineError> {
+ let Some(order) = &self.pending else {
+ return Ok(None);
+ };
+ if !identity_metadata(world, order.plant)
+ .is_ok_and(|identity| identity.owner_id == Some(order.owner))
+ {
+ self.pending = None;
+ return Ok(None);
+ }
+ if now_ms.wrapping_sub(order.start_ms) < order.duration_ms {
+ return Ok(None);
+ }
+ let order = self.pending.take().expect("due construction order");
+ let pose = transform_state(world, order.plant)?;
+ // shortcut: reuse the outdoor spawn point until the factory exit
+ // device and its clear-space check are available.
+ let position = reinforcement_position(
+ pose.position.map(f32::from_bits),
+ pose.orientation.map(f32::from_bits),
+ pose.scale.map(f32::from_bits),
+ order.plant_index,
+ &mission.mission_assets,
+ &mission.terrain,
+ &mut self.rng,
+ )?;
+ let handle = spawn_prepared_unit(
+ world,
+ mission,
+ self.reserve,
+ order.owner.0,
+ position,
+ self.control.clone(),
+ )?;
+ if let Some((_, count)) = self
+ .free_units
+ .iter_mut()
+ .find(|(index, _)| *index == order.plant_index)
+ {
+ *count -= 1;
+ }
+ Ok(Some(SpawnedUnit {
+ object_index: self.reserve,
+ handle,
+ clan: order.owner.0,
+ }))
+ }
+}
+
+/// Queues the selected free robot scheme at a friendly factory communicator.
+/// Returns its construction time in milliseconds on success.
+///
+/// # Errors
+///
+/// Returns a diagnostic when no eligible factory or scheme is available or the
+/// prepared construction slot is occupied.
+pub fn order_factory_robot(
+ engine: &mut Engine,
+ cockpit: StartingCockpit,
+ now_ms: u32,
+) -> Result<u32, EngineError> {
+ let (Some(mission), Some(production)) = (&engine.loaded, &mut engine.production) else {
+ return Err(EngineError::Production(
+ "launch with --build-scheme to choose a robot".into(),
+ ));
+ };
+ if production.pending.is_some() {
+ return Err(EngineError::Production(
+ "factory order already in progress".into(),
+ ));
+ }
+ let draft = &mission.object_drafts[production.reserve];
+ if draft
+ .original_id
+ .is_some_and(|id| handle_by_original_id(&engine.world, id).is_some())
+ {
+ return Err(EngineError::Production(
+ "the previous robot is still active".into(),
+ ));
+ }
+ let player = identity_metadata(&engine.world, cockpit.handle)?;
+ let owner = player
+ .owner_id
+ .ok_or_else(|| EngineError::Production("player clan is unavailable".into()))?;
+ let position = transform_state(&engine.world, cockpit.handle)?
+ .position
+ .map(f32::from_bits);
+ let (plant_index, plant) = production
+ .free_units
+ .iter()
+ .find_map(|(index, slots)| {
+ let plant =
+ handle_by_original_id(&engine.world, mission.object_drafts[*index].original_id?)?;
+ (*slots != 0
+ && identity_metadata(&engine.world, plant).ok()?.owner_id == Some(owner)
+ && on_communicator(
+ &mission.mission_assets,
+ *index,
+ transform_state(&engine.world, plant).ok()?,
+ position,
+ ))
+ .then_some((*index, plant))
+ })
+ .ok_or_else(|| {
+ EngineError::Production(
+ "stand on a friendly factory communicator with free capacity".into(),
+ )
+ })?;
+ let plant_draft = &mission.object_drafts[plant_index];
+ let plant_key = &plant_draft.unit_components[0].resource_raw;
+ let robot_key = &draft.unit_components[0].resource_raw;
+ let duration_ms = free_duration_ms(plant_key, robot_key).ok_or_else(|| {
+ EngineError::Production("scheme size is unsupported by this factory".into())
+ })?;
+ production.pending = Some(Order {
+ plant,
+ plant_index,
+ owner,
+ start_ms: now_ms,
+ duration_ms,
+ });
+ Ok(duration_ms)
+}
+
+fn free_duration_ms(plant: &[u8; 32], robot: &[u8; 32]) -> Option<u32> {
+ // shortcut: stock chassis and factory keys supply sizes until the
+ // calculated capacity and assembled-scheme descriptors are wired.
+ let plant = plant.split(|&byte| byte == 0).next()?;
+ let size = match robot.get(..3)? {
+ [b'R' | b'r', b'_', b'T' | b't'] => 1,
+ [b'R' | b'r', b'_', b'L' | b'l' | b'H' | b'h'] => 2,
+ [b'R' | b'r', b'_', b'M' | b'm'] => 3,
+ [b'R' | b'r', b'_', b'B' | b'b'] => 4,
+ _ => return None,
+ };
+ let seconds = if plant.eq_ignore_ascii_case(b"fr_l_plant") {
+ [30, 60].get(size - 1)?
+ } else if plant.eq_ignore_ascii_case(b"fr_m_plant") {
+ [20, 35, 60].get(size - 1)?
+ } else if plant.eq_ignore_ascii_case(b"fr_b_plant") {
+ [10, 20, 40, 60].get(size - 1)?
+ } else {
+ return None;
+ };
+ Some(*seconds * 1_000)
+}