diff options
Diffstat (limited to 'crates')
| -rw-r--r-- | crates/fparkan-runtime/src/clan_ai_events.rs | 62 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/clan_problem_priority.rs | 110 | ||||
| -rw-r--r-- | crates/fparkan-runtime/src/lib.rs | 1 | ||||
| -rw-r--r-- | crates/fparkan-script/src/lib.rs | 49 | ||||
| -rw-r--r-- | crates/fparkan-script/tests/handler2_native_oracle.cs | 50 |
5 files changed, 198 insertions, 74 deletions
diff --git a/crates/fparkan-runtime/src/clan_ai_events.rs b/crates/fparkan-runtime/src/clan_ai_events.rs index f5dad22f..65e602a6 100644 --- a/crates/fparkan-runtime/src/clan_ai_events.rs +++ b/crates/fparkan-runtime/src/clan_ai_events.rs @@ -330,6 +330,7 @@ impl LoadedMissionState { continue; }; let mut problems_event = Some((event_index, event, None::<Handler2Record>)); + let mut start_pass = crate::clan_problem_priority::StartPass::default(); // shortcut: task continuations still share the clan cycle rather than per-task scheduling. let mut pending = self .clan_ai_events @@ -412,7 +413,16 @@ impl LoadedMissionState { let Some((event_index, _event, mut problem)) = next.or_else(|| problems_event.take()) else { - break; + let Some(queue) = self.clan_ai_events.problems.get(&clan) else { + break; + }; + pending = start_pass.next_batch(queue.records(), |key| { + self.clan_ai_events.problem_in_progress(clan, key) + }); + if pending.is_empty() { + break; + } + continue; }; let mut solved = false; let mut transport_factory_busy = false; @@ -892,12 +902,9 @@ impl LoadedMissionState { ); } let owner = OwnerId(clan as u16); - let plant = crate::mission_events::placed_logic_objects( - &self.mission, - world, - order.word_0, - ) - .find(|&handle| { + let plant = self.mission_events.logic_objects( + &self.mission, world, order.word_0, + ).find(|&handle| { identity_metadata(world, handle) .is_ok_and(|identity| identity.owner_id == Some(owner)) }); @@ -1020,7 +1027,7 @@ impl LoadedMissionState { }) .ok_or("Handler(27) requires an active construction order")?; if assignment != Some(order.plant) - || !crate::mission_events::placed_logic_objects( + || !self.mission_events.logic_objects( &self.mission, world, id, @@ -1359,6 +1366,9 @@ impl LoadedMissionState { } } if let Some(problem) = problem { + if problems_event.is_none() && !solved && !solving { + start_pass.stop_after_batch(); + } // shortcut: keep transport demand queued until the factory can accept it. if solved && !transport_factory_busy { self.clan_ai_events @@ -1386,8 +1396,6 @@ impl LoadedMissionState { .waits .insert((clan, problem.key), conditions); } - } else if let Some(queue) = self.clan_ai_events.problems.get(&clan) { - pending = ranked_problems(queue.records()); } } } @@ -1395,17 +1403,6 @@ impl LoadedMissionState { } } -fn ranked_problems(problems: &[Handler2Record]) -> Vec<Handler2Record> { - let mut pending: Vec<_> = problems - .iter() - .filter(|record| record.scalar_1 > 0.0) - .cloned() - .collect(); - pending.sort_by(|a, b| b.scalar_1.total_cmp(&a.scalar_1)); - pending.reverse(); - pending -} - fn single_dword(references: &[u32], values: &[VarSetDefault]) -> Option<u32> { let &[index] = references else { return None; @@ -2153,29 +2150,6 @@ mod tests { } #[test] - fn problem_selection_requires_a_positive_priority_and_preserves_order_on_ties() { - let mut queue = Handler2RecordScheduler::default(); - for (word_0, scalar_1) in [(1, 0.0), (2, -3.0), (3, 0.5), (4, 0.5)] { - queue.submit(Handler2RecordInput { - word_0, - scalar_1, - word_2: 0, - word_3: 0, - argument_0: 0, - argument_1: 0, - argument_2: 0, - }); - } - let first = ranked_problems(queue.records()).pop().unwrap().key; - assert_eq!(first.word_0, 3); - queue.remove(first); - assert_eq!( - ranked_problems(queue.records()).pop().unwrap().key.word_0, - 4 - ); - } - - #[test] fn free_ore_space_follows_storage_ownership_and_lifecycle() { use fparkan_world::{ construct_object, new, register_object, request_delete, set_owner, step, InputSnapshot, diff --git a/crates/fparkan-runtime/src/clan_problem_priority.rs b/crates/fparkan-runtime/src/clan_problem_priority.rs new file mode 100644 index 00000000..200b76cd --- /dev/null +++ b/crates/fparkan-runtime/src/clan_problem_priority.rs @@ -0,0 +1,110 @@ +use fparkan_script::{Handler2Record, Handler2RecordKey}; +use std::collections::BTreeSet; + +#[derive(Default)] +pub(super) struct StartPass { + attempted: BTreeSet<Handler2RecordKey>, + stalled: bool, +} + +impl StartPass { + pub(super) fn next_batch( + &mut self, + records: &[Handler2Record], + in_progress: impl Fn(Handler2RecordKey) -> bool, + ) -> Vec<Handler2Record> { + if self.stalled { + return Vec::new(); + } + + let mut highest = 0.0; + let mut batch = Vec::new(); + for record in records { + if record.scalar_1 <= 0.0 + || self.attempted.contains(&record.key) + || in_progress(record.key) + { + continue; + } + if record.scalar_1 > highest { + highest = record.scalar_1; + batch.clear(); + } + if record.scalar_1 == highest { + batch.push(record.clone()); + } + } + self.attempted.extend(batch.iter().map(|record| record.key)); + batch.reverse(); + batch + } + + pub(super) fn stop_after_batch(&mut self) { + self.stalled = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use fparkan_script::{Handler2RecordInput, Handler2RecordScheduler}; + + #[test] + fn attempts_all_tied_requests_and_keeps_lower_weights_waiting_if_one_stalls() { + let mut queue = Handler2RecordScheduler::default(); + for (kind, weight) in [(1, 5.0), (2, 5.0), (3, 1.0), (4, 0.0), (5, -1.0)] { + submit(&mut queue, kind, weight); + } + let mut pass = StartPass::default(); + let mut batch = pass.next_batch(queue.records(), |_| false); + assert_eq!(batch.pop().unwrap().key.word_0, 1); + pass.stop_after_batch(); + assert_eq!(batch.pop().unwrap().key.word_0, 2); + assert!(batch.is_empty()); + assert!(pass.next_batch(queue.records(), |_| false).is_empty()); + let mut next_pass = StartPass::default(); + assert_eq!( + kinds(next_pass.next_batch(queue.records(), |key| key.word_0 == 2)), + [1] + ); + } + + #[test] + fn reselects_from_live_weights_after_a_batch_advances() { + let mut queue = Handler2RecordScheduler::default(); + for (kind, weight) in [(1, 5.0), (2, 5.0), (3, 1.0), (4, 8.0)] { + submit(&mut queue, kind, weight); + } + let mut pass = StartPass::default(); + assert_eq!( + kinds(pass.next_batch(queue.records(), |key| key.word_0 == 4)), + [1, 2] + ); + submit(&mut queue, 5, 7.0); + for expected in [5, 3] { + assert_eq!( + kinds(pass.next_batch(queue.records(), |key| key.word_0 == 4)), + [expected] + ); + } + assert!(pass + .next_batch(queue.records(), |key| key.word_0 == 4) + .is_empty()); + } + + fn kinds(batch: Vec<Handler2Record>) -> Vec<u32> { + batch.iter().rev().map(|record| record.key.word_0).collect() + } + + fn submit(queue: &mut Handler2RecordScheduler, word_0: u32, scalar_1: f32) { + queue.submit(Handler2RecordInput { + word_0, + scalar_1, + word_2: 0, + word_3: 0, + argument_0: 0, + argument_1: 0, + argument_2: 0, + }); + } +} diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs index f53a3ae2..da5af6d8 100644 --- a/crates/fparkan-runtime/src/lib.rs +++ b/crates/fparkan-runtime/src/lib.rs @@ -84,6 +84,7 @@ mod clan_factory_schemes; mod clan_minds; mod clan_mining; mod clan_problem_conditions; +mod clan_problem_priority; mod clan_research; mod clan_script_init; mod clan_targeting; diff --git a/crates/fparkan-script/src/lib.rs b/crates/fparkan-script/src/lib.rs index 4dd73efd..e9e10722 100644 --- a/crates/fparkan-script/src/lib.rs +++ b/crates/fparkan-script/src/lib.rs @@ -1967,9 +1967,10 @@ impl Handler2RecordScheduler { /// Inserts or refreshes one resolved handler input. /// /// The original compares the three identity words bit-for-bit. On an - /// existing key, it refreshes only when `scalar_1` compares unequal; that - /// update replaces `scalar_1` and `argument_2`, then adds the slot-2 word - /// captured when that record was created, with x86 wrapping arithmetic. + /// existing key, it accepts a weight at least as high as the stored + /// weight. An unordered comparison leaves the record unchanged. + /// Refresh updates `scalar_1` and `argument_2`, then adds the initial + /// slot-2 word with x86 wrapping arithmetic. pub fn submit(&mut self, input: Handler2RecordInput) -> Handler2RecordUpdate { let key = Handler2RecordKey::from(input); if let Some((index, record)) = self @@ -1978,7 +1979,7 @@ impl Handler2RecordScheduler { .enumerate() .find(|(_, record)| record.key == key) { - if !handler_two_scalar_equal(record.scalar_1, input.scalar_1) { + if record.scalar_1 <= input.scalar_1 { record.scalar_1 = input.scalar_1; record.argument_2 = input.argument_2; record.counter = record.counter.wrapping_add(record.increment); @@ -2011,19 +2012,6 @@ impl Handler2RecordScheduler { } } -fn handler_two_scalar_equal(left: f32, right: f32) -> bool { - if left.is_nan() || right.is_nan() { - return false; - } - let left_bits = left.to_bits(); - let right_bits = right.to_bits(); - left_bits == right_bits || (is_f32_zero_bits(left_bits) && is_f32_zero_bits(right_bits)) -} - -fn is_f32_zero_bits(bits: u32) -> bool { - matches!(bits, 0 | 0x8000_0000) -} - /// Parses the numeric `VAR(...)` declarations from a legacy `varset.var` file. /// /// Parsing is line-oriented and byte-safe: non-UTF-8 comments remain opaque, @@ -2489,7 +2477,7 @@ mod tests { assert_eq!(scheduler.records().len(), 1); assert_eq!(scheduler.records()[0].counter, 4); - let unchanged = handler_two_input(1.5, -0.0, 3.0, 12.0, 99); + let unchanged = handler_two_input(1.0, -0.0, 3.0, 12.0, 99); assert_eq!( scheduler.submit(unchanged), super::Handler2RecordUpdate { @@ -2501,7 +2489,7 @@ mod tests { assert_eq!(scheduler.records()[0].counter, 4); assert_eq!(scheduler.records()[0].argument_2, 9.0_f32.to_bits()); - let refreshed = handler_two_input(2.5, -0.0, 3.0, 12.0, 99); + let refreshed = handler_two_input(1.5, -0.0, 3.0, 12.0, 99); assert_eq!( scheduler.submit(refreshed), super::Handler2RecordUpdate { @@ -2536,30 +2524,31 @@ mod tests { } #[test] - fn handler_two_scheduler_refreshes_nan_and_wraps_counter() { + fn handler_two_scheduler_skips_unordered_weights_and_wraps_on_refresh() { let mut scheduler = Handler2RecordScheduler::default(); - scheduler.submit(handler_two_input(f32::NAN, 1.0, 2.0, 3.0, u32::MAX)); + scheduler.submit(handler_two_input(0.5, 1.0, 2.0, 3.0, u32::MAX)); let update = scheduler.submit(handler_two_input(f32::NAN, 1.0, 2.0, 4.0, 2)); assert_eq!(update.index, 0); - assert!(update.refreshed); - assert_eq!(scheduler.records()[0].counter, u32::MAX - 1); - assert_eq!(scheduler.records()[0].argument_2, 4.0_f32.to_bits()); + assert!(!update.refreshed); + assert_eq!(scheduler.records()[0].counter, u32::MAX); + assert_eq!(scheduler.records()[0].argument_2, 3.0_f32.to_bits()); - let update = scheduler.submit(handler_two_input(f32::NAN, 1.0, 2.0, 5.0, 17)); + let update = scheduler.submit(handler_two_input(0.5, 1.0, 2.0, 5.0, 17)); assert!(update.refreshed); - assert_eq!(scheduler.records()[0].counter, u32::MAX - 2); + assert_eq!(scheduler.records()[0].counter, u32::MAX - 1); assert_eq!(scheduler.records()[0].argument_2, 5.0_f32.to_bits()); } #[test] - fn handler_two_scheduler_treats_signed_zero_value_as_unchanged() { + fn handler_two_scheduler_refreshes_equal_weights_across_signed_zero() { let mut scheduler = Handler2RecordScheduler::default(); scheduler.submit(handler_two_input(-0.0, 1.0, 2.0, 3.0, 5)); let update = scheduler.submit(handler_two_input(0.0, 1.0, 2.0, 4.0, 9)); assert!(!update.created); - assert!(!update.refreshed); - assert_eq!(scheduler.records()[0].counter, 5); - assert_eq!(scheduler.records()[0].argument_2, 3.0_f32.to_bits()); + assert!(update.refreshed); + assert_eq!(scheduler.records()[0].counter, 10); + assert_eq!(scheduler.records()[0].scalar_1.to_bits(), 0); + assert_eq!(scheduler.records()[0].argument_2, 4.0_f32.to_bits()); } #[test] diff --git a/crates/fparkan-script/tests/handler2_native_oracle.cs b/crates/fparkan-script/tests/handler2_native_oracle.cs index f632c688..52e9456b 100644 --- a/crates/fparkan-script/tests/handler2_native_oracle.cs +++ b/crates/fparkan-script/tests/handler2_native_oracle.cs @@ -7,6 +7,7 @@ using System.Text; internal static class Handler2NativeOracle { private const uint LoadWithAlteredSearchPath = 0x00000008; private const int RefreshRecordRva = 0x5070; + private const int SubmitRva = 0x59f0; private const string ExpectedSha256 = "c19cd6cd31cd2896f8c4ba0f0e700dd3408aec8182daaf4863d98a7d233a2abc"; [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] @@ -18,6 +19,10 @@ internal static class Handler2NativeOracle { [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void RefreshRecord(IntPtr record); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void SubmitRecord(IntPtr queue, int kind, float priority, uint increment, + uint sender, uint first, uint second, uint third, IntPtr name); + private static int Main() { if (IntPtr.Size != 4) { Console.Error.WriteLine("Build this oracle with an x86 target; ai.dll is 32-bit."); @@ -66,11 +71,56 @@ internal static class Handler2NativeOracle { AssertRefresh(refresh, record, UInt32.MaxValue - 2); } finally { Marshal.FreeHGlobal(record); } + + var submit = (SubmitRecord)Marshal.GetDelegateForFunctionPointer( + IntPtr.Add(module, SubmitRva), typeof(SubmitRecord)); + AssertMatchingSubmission(submit, 0.55011004f, 0.545f, false); + AssertMatchingSubmission(submit, 0.545f, 0.55011004f, true); + AssertMatchingSubmission(submit, 1.0f, 1.0f, true); + AssertMatchingSubmission(submit, -0.0f, 0.0f, true); + AssertMatchingSubmission(submit, Single.NaN, 1.0f, false); + AssertMatchingSubmission(submit, 1.0f, Single.NaN, false); } finally { FreeLibrary(module); } return 0; } + private static void AssertMatchingSubmission(SubmitRecord submit, float before, float incoming, + bool expectedRefresh) { + IntPtr queue = Marshal.AllocHGlobal(0x380); + IntPtr record = Marshal.AllocHGlobal(100); + try { + Marshal.Copy(new byte[0x380], 0, queue, 0x380); + Marshal.Copy(new byte[100], 0, record, 100); + Marshal.WriteInt32(queue, 0x28, 1); + Marshal.WriteIntPtr(queue, 0x30, record); + Marshal.WriteInt32(record, 0, 3); + Marshal.WriteInt32(record, 4, unchecked((int)0x80000010)); + Marshal.WriteInt32(record, 0xc, 91); + Marshal.WriteInt32(record, 0x14, Bits(before)); + Marshal.WriteInt32(record, 0x24, 7); + Marshal.WriteInt32(record, 0x28, 4); + submit(queue, 3, incoming, 99, 0, 0x80000010, 0, 92, IntPtr.Zero); + int counter = Marshal.ReadInt32(record, 0x24); + Console.WriteLine("stored={0:R} submitted={1:R} counter={2}", before, incoming, counter); + if (Marshal.ReadInt32(queue, 0x28) != 1 || + Marshal.ReadInt32(record, 0x14) != Bits(expectedRefresh ? incoming : before) || + counter != (expectedRefresh ? 11 : 7) || + Marshal.ReadInt32(record, 0xc) != (expectedRefresh ? 92 : 91) || + Marshal.ReadInt32(record, 0x28) != 4) { + throw new InvalidOperationException("Unexpected matching submission result."); + } + } + finally { + Marshal.FreeHGlobal(record); + Marshal.FreeHGlobal(queue); + } + } + + private static int Bits(float value) { + return BitConverter.ToInt32(BitConverter.GetBytes(value), 0); + } + private static void AssertRefresh(RefreshRecord refresh, IntPtr record, uint expectedCounter) { uint savedIncrement = unchecked((uint)Marshal.ReadInt32(record, 0x28)); refresh(record); |
