aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-runtime
diff options
context:
space:
mode:
Diffstat (limited to 'crates/fparkan-runtime')
-rw-r--r--crates/fparkan-runtime/src/lib.rs689
-rw-r--r--crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs243
2 files changed, 876 insertions, 56 deletions
diff --git a/crates/fparkan-runtime/src/lib.rs b/crates/fparkan-runtime/src/lib.rs
index 82bd07c..5e352fc 100644
--- a/crates/fparkan-runtime/src/lib.rs
+++ b/crates/fparkan-runtime/src/lib.rs
@@ -517,6 +517,9 @@ pub struct MissionControlOwnerProfile {
MissionControlOwnerProfileLoadProjection,
MissionControlOwnerProfileLoadProjectionUnavailableReason,
>,
+ /// FCA0 status after FAC0, recorded separately from the FAC0 result.
+ /// Native class 9 returns `Ok(())` without changing the prepared copy.
+ pub fca0_projection: Result<(), MissionControlOwnerProfileFca0UnavailableReason>,
}
/// Initial Control FAC0 load-time values for one owner profile.
@@ -547,6 +550,20 @@ pub enum MissionControlOwnerProfileLoadProjectionUnavailableReason {
MissingProfileCacheOnInto,
}
+/// Why the initial Control FCA0 profile projection is unavailable.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum MissionControlOwnerProfileFca0UnavailableReason {
+ /// Rust could not project the native Control class for this owner.
+ MissingNativeControlClass,
+ /// A non-class-9 FCA0 route requires a completed FAC0 result; class 9
+ /// returns before this result is inspected.
+ Fac0Unavailable(MissionControlOwnerProfileLoadProjectionUnavailableReason),
+ /// The original current-tag E00 query failed with a typed reason.
+ QueryUnavailable(Arc<ControlResourceAccessError>),
+ /// An input or intermediate float is outside the supported domain.
+ UnsupportedFloat { field: &'static str },
+}
+
struct ControlDeviceProjection {
devices: Vec<EffectiveControlDevice>,
owner_profile: Option<MissionControlOwnerProfile>,
@@ -1592,12 +1609,13 @@ fn load_mission_with_options(
prototype_span,
&resolved_prototypes,
);
- let projection = build_control_device_projection(
+ let projection = build_control_device_projection_with_class(
object_index,
draft,
&mission_assets,
prototype_span,
&resolved_prototypes,
+ native_control_class,
);
match projection {
Ok(projection) => MissionControlDeviceTableState {
@@ -2068,10 +2086,13 @@ pub fn query_loaded_mission_control_resource(
/// Queries one loaded Control device through its original factory getter.
///
-/// Selector `0xe00` is currently modeled for current descriptor tag 26 with
-/// factory tag 26. The query reads the current provider, coefficient, and
-/// multiplier in the CPU projection. Explicit Control update calls can change
-/// those values; the mission clock does not advance them automatically.
+/// Selector `0xe00` is modeled for current descriptor tags 5 and 26 with
+/// factory tags 5 and 26. Both common factory readers use the device key to
+/// read the current provider value and multiply it by coefficient 0. Only
+/// current tag 26 also multiplies by `M`; current tag 5 ignores `M` and
+/// descriptor word 8 for this selector. Explicit Control update calls can
+/// change current provider or multiplier values; the mission clock does not
+/// advance them automatically.
///
/// # Errors
/// Returns an error for an invalid handle, unavailable mission/table/provider,
@@ -2764,7 +2785,14 @@ fn control_node_provider_row(
table: &MissionControlDeviceTableState,
key: u32,
) -> Result<&MissionControlNodeProviderRow, ControlResourceAccessError> {
- let rows = match &table.node_provider_status {
+ control_node_provider_row_from_status(&table.node_provider_status, key)
+}
+
+fn control_node_provider_row_from_status(
+ status: &MissionControlNodeProviderTableStatus,
+ key: u32,
+) -> Result<&MissionControlNodeProviderRow, ControlResourceAccessError> {
+ let rows = match status {
MissionControlNodeProviderTableStatus::Available(rows) => rows,
MissionControlNodeProviderTableStatus::Unavailable(reason) => {
return Err(ControlResourceAccessError::NodeProviderTableUnavailable(
@@ -3187,7 +3215,14 @@ fn control_device_provider_value(
table: &MissionControlDeviceTableState,
device: &EffectiveControlDevice,
) -> Result<f32, ControlResourceAccessError> {
- let provider = control_node_provider_row(table, device.key)?;
+ control_device_provider_value_from_status(&table.node_provider_status, device)
+}
+
+fn control_device_provider_value_from_status(
+ status: &MissionControlNodeProviderTableStatus,
+ device: &EffectiveControlDevice,
+) -> Result<f32, ControlResourceAccessError> {
+ let provider = control_node_provider_row_from_status(status, device.key)?;
checked_control_float(
device.factory_tag,
"node provider value",
@@ -4154,62 +4189,47 @@ fn query_control_device_table_selector(
device_index,
device_count: devices.len(),
})?;
+ query_control_device_selector(device, &table.node_provider_status)
+}
+
+fn query_control_device_selector(
+ device: &EffectiveControlDevice,
+ provider_status: &MissionControlNodeProviderTableStatus,
+) -> Result<Option<f32>, ControlResourceAccessError> {
match device.descriptor.tag {
- 26 => {}
- 5 | 10 | 21 => {
+ 5 | 26 => {}
+ 10 | 21 => {
return Err(ControlResourceAccessError::UnsupportedCurrentTag {
tag: device.descriptor.tag,
});
}
_ => return Ok(None),
}
- if device.factory_tag != 26 {
+ if !matches!(device.factory_tag, 5 | 26) {
return Err(ControlResourceAccessError::UnsupportedFactoryTag {
factory_tag: device.factory_tag,
});
}
-
- let providers = match &table.node_provider_status {
- MissionControlNodeProviderTableStatus::Available(providers) => providers,
- MissionControlNodeProviderTableStatus::Unavailable(reason) => {
- return Err(ControlResourceAccessError::NodeProviderTableUnavailable(
- reason.clone(),
- ));
- }
- };
- let key = usize::try_from(device.key).map_err(|_| {
- ControlResourceAccessError::NodeProviderKeyOutOfRange {
- key: device.key,
- row_count: providers.len(),
- }
- })?;
- let provider =
- providers
- .get(key)
- .ok_or(ControlResourceAccessError::NodeProviderKeyOutOfRange {
- key: device.key,
- row_count: providers.len(),
- })?;
- let provider_value = checked_control_float(
- device.factory_tag,
- "node provider value",
- f32::from_bits(provider.current_type1_value_bits),
- )?;
+ let provider_value = control_device_provider_value_from_status(provider_status, device)?;
let coefficient = control_device_coefficient(device)?;
- let multiplier = control_device_float(device, device.multiplier_bits, "multiplier")?;
let provider_weighted = checked_control_product(
device.factory_tag,
"provider times coefficient",
provider_value,
coefficient,
)?;
- checked_control_product(
- device.factory_tag,
- "then multiplier",
- provider_weighted,
- multiplier,
- )
- .map(Some)
+ if device.descriptor.tag == 26 {
+ let multiplier = control_device_float(device, device.multiplier_bits, "multiplier")?;
+ checked_control_product(
+ device.factory_tag,
+ "then multiplier",
+ provider_weighted,
+ multiplier,
+ )
+ .map(Some)
+ } else {
+ Ok(Some(provider_weighted))
+ }
}
fn set_control_device_table_selector(
@@ -5029,6 +5049,155 @@ fn project_control_load_profile(
})
}
+fn control_fca0_float(
+ value: f32,
+ field: &'static str,
+) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
+ checked_control_float(0, field, value)
+ .map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
+}
+
+fn control_fca0_product(
+ lhs: f32,
+ rhs: f32,
+ field: &'static str,
+) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
+ checked_control_product(0, field, lhs, rhs)
+ .map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
+}
+
+fn control_fca0_sum(
+ lhs: f32,
+ rhs: f32,
+ field: &'static str,
+) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
+ checked_control_sum(0, field, lhs, rhs)
+ .map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
+}
+
+fn control_fca0_ratio(
+ numerator: f32,
+ denominator: f32,
+ field: &'static str,
+) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
+ checked_control_ratio(field, numerator, denominator)
+ .map_err(|_| MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat { field })
+}
+
+fn control_fca0_clamp_to_profile_cap(
+ value: f32,
+ cap: f32,
+ field: &'static str,
+) -> Result<f32, MissionControlOwnerProfileFca0UnavailableReason> {
+ let value = control_fca0_float(value, field)?;
+ let cap = control_fca0_float(cap, field)?;
+ let magnitude = if value < 0.0 { -value } else { value };
+ Ok(if magnitude > cap {
+ if value < 0.0 {
+ -cap
+ } else {
+ cap
+ }
+ } else {
+ value
+ })
+}
+
+fn project_control_owner_profile_fca0(
+ native_class: Option<MissionControlClassProjection>,
+ original_words: &[u32; 27],
+ current_words: &[u32; 27],
+ fac0_projection: &Result<
+ MissionControlOwnerProfileLoadProjection,
+ MissionControlOwnerProfileLoadProjectionUnavailableReason,
+ >,
+ devices: &[EffectiveControlDevice],
+ provider_status: &MissionControlNodeProviderTableStatus,
+) -> Result<[u32; 27], MissionControlOwnerProfileFca0UnavailableReason> {
+ use MissionControlOwnerProfileFca0UnavailableReason as Unavailable;
+
+ if native_class.is_some_and(|class| class.class_id == 9) {
+ return Ok(*current_words);
+ }
+ if native_class.is_none() {
+ return Err(Unavailable::MissingNativeControlClass);
+ }
+ if let Err(reason) = fac0_projection {
+ return Err(Unavailable::Fac0Unavailable(reason.clone()));
+ }
+
+ let mut e00_sum = 0.0_f32;
+ for device_index in (0..devices.len()).rev() {
+ if devices[device_index].descriptor.tag != 5 {
+ continue;
+ }
+ if let Some(value) = query_control_device_selector(&devices[device_index], provider_status)
+ .map_err(|error| Unavailable::QueryUnavailable(Arc::new(error)))?
+ {
+ e00_sum = control_fca0_sum(e00_sum, value, "FCA0 reverse E00 sum")?;
+ }
+ }
+
+ // The canonical owner constructor initializes +0x1a8, +0x354, and +0x358
+ // to 1.0; the traced event-4 loader does not overwrite these fields.
+ let owner_scalar = 1.0_f32;
+ let owner_mean = control_fca0_sum(1.0, 1.0, "FCA0 owner scalar mean")?;
+ let owner_mean = control_fca0_product(owner_mean, 0.5, "FCA0 owner scalar mean")?;
+ let weight = control_fca0_product(owner_mean, e00_sum, "FCA0 weighted E00 sum")?;
+ let ratio = control_fca0_ratio(
+ control_fca0_float(f32::from_bits(current_words[26]), "current profile word 26")?,
+ control_fca0_float(
+ f32::from_bits(original_words[26]),
+ "original profile word 26",
+ )?,
+ "FCA0 profile word 26 ratio",
+ )?;
+ let factor_a = control_fca0_product(
+ control_fca0_sum(ratio, 1.0, "FCA0 factor A")?,
+ 0.5,
+ "FCA0 factor A",
+ )?;
+ let factor_b = control_fca0_sum(
+ control_fca0_product(ratio, 0.75, "FCA0 factor B")?,
+ 0.25,
+ "FCA0 factor B",
+ )?;
+
+ let mut current_words = *current_words;
+ for index in 6..9 {
+ let original = control_fca0_float(
+ f32::from_bits(original_words[index]),
+ "original profile words 6..8",
+ )?;
+ let owner_scaled =
+ control_fca0_product(owner_scalar, original, "FCA0 first profile triple")?;
+ let weighted = control_fca0_product(owner_scaled, weight, "FCA0 first profile triple")?;
+ let factored = control_fca0_product(weighted, factor_a, "FCA0 first profile triple")?;
+ current_words[index] =
+ control_fca0_clamp_to_profile_cap(factored, original, "FCA0 first profile triple")?
+ .to_bits();
+ }
+ for index in 9..12 {
+ let original = control_fca0_float(
+ f32::from_bits(original_words[index]),
+ "original profile words 9..11",
+ )?;
+ let weighted = control_fca0_product(weight, original, "FCA0 second profile triple")?;
+ let factored = control_fca0_product(weighted, factor_b, "FCA0 second profile triple")?;
+ current_words[index] =
+ control_fca0_sum(factored, factored, "FCA0 doubled second profile triple")?.to_bits();
+ }
+ for index in 0..3 {
+ let original = control_fca0_float(
+ f32::from_bits(original_words[index]),
+ "original profile words 0..2",
+ )?;
+ current_words[index] =
+ control_fca0_sum(original, original, "FCA0 doubled profile words")?.to_bits();
+ }
+ Ok(current_words)
+}
+
fn behavior_clan_for_selector(
selector: u32,
clan_count: usize,
@@ -5476,6 +5645,7 @@ fn build_control_device_table(
.map(|projection| projection.devices)
}
+#[cfg(test)]
fn build_control_device_projection(
object_index: usize,
draft: &MissionObjectDraft,
@@ -5483,6 +5653,26 @@ fn build_control_device_projection(
prototype_span: Option<&std::ops::Range<usize>>,
prototypes: &[fparkan_prototype::EffectivePrototype],
) -> Result<ControlDeviceProjection, MissionControlDeviceTableUnavailableReason> {
+ let native_class =
+ native_control_class_for_root(draft.unit_dat_header_flags, prototype_span, prototypes);
+ build_control_device_projection_with_class(
+ object_index,
+ draft,
+ assets,
+ prototype_span,
+ prototypes,
+ native_class,
+ )
+}
+
+fn build_control_device_projection_with_class(
+ object_index: usize,
+ draft: &MissionObjectDraft,
+ assets: &MissionAssets,
+ prototype_span: Option<&std::ops::Range<usize>>,
+ prototypes: &[fparkan_prototype::EffectivePrototype],
+ native_control_class: Option<MissionControlClassProjection>,
+) -> Result<ControlDeviceProjection, MissionControlDeviceTableUnavailableReason> {
use MissionControlDeviceTableUnavailableReason as Unavailable;
draft
@@ -5892,6 +6082,20 @@ fn build_control_device_projection(
),
),
};
+ let fca0_projection = match project_control_owner_profile_fca0(
+ native_control_class,
+ &original_words,
+ &current_words,
+ &load_projection,
+ &devices,
+ &node_provider_status,
+ ) {
+ Ok(projected_words) => {
+ current_words = projected_words;
+ Ok(())
+ }
+ Err(reason) => Err(reason),
+ };
MissionControlOwnerProfile {
source,
unit_component_index,
@@ -5899,6 +6103,7 @@ fn build_control_device_projection(
original_words,
current_words,
load_projection,
+ fca0_projection,
}
},
);
@@ -7302,8 +7507,10 @@ mod tests {
);
assert_eq!(device.tag26_extra_rate_bits, Some(0));
device.tag26_extra_rate_bits = Some(0.3_f32.to_bits());
+ device.multiplier_bits = Some(17.0_f32.to_bits());
- let replacement = synthetic_control_record(19, 99, 0x30, None);
+ let mut replacement = synthetic_control_record(5, 99, 3.0_f32.to_bits(), None);
+ replacement.fixed_words[8] = 13.0_f32.to_bits();
let control = synthetic_component_control(
1,
vec![replacement.clone()],
@@ -7312,8 +7519,28 @@ mod tests {
apply_effective_control_override(&mut device, &replacement, 1, 0, &control);
assert_eq!(device.factory_tag, 26);
- assert_eq!(device.descriptor.tag, 19);
+ assert_eq!(device.key, 2, "INTO preserves the original provider key");
+ assert_eq!(device.descriptor.tag, 5);
+ assert_eq!(device.coefficient_bits.unwrap()[0], 3.0_f32.to_bits());
+ assert_eq!(device.multiplier_bits, Some(17.0_f32.to_bits()));
+ assert_eq!(device.descriptor.fixed_words[8], 13.0_f32.to_bits());
assert_eq!(device.tag26_extra_rate_bits, Some(0.3_f32.to_bits()));
+
+ let table = synthetic_control_device_table_with_providers(
+ MissionControlDeviceTableStatus::Available(vec![device]),
+ MissionControlNodeProviderTableStatus::Available(vec![
+ synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 1, 2.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 2, 7.0_f32.to_bits()),
+ ]),
+ );
+ assert_eq!(
+ query_control_device_table_selector(&table, 0, 0xe00)
+ .expect("factory-26/current-tag-5 E00 query")
+ .map(f32::to_bits),
+ Some(21.0_f32.to_bits()),
+ "tag-5 E00 uses current coefficient and provider value, without multiplier M or descriptor word 8"
+ );
}
#[test]
@@ -9719,6 +9946,7 @@ mod tests {
root.node_data.as_mut().unwrap().rows[0].mobility_per_volume = 2.0;
let (mut draft, mut assets, prototypes) =
synthetic_control_fixture(&[None], &[1], &[0], &[0], &[1], vec![Some(root)]);
+ draft.unit_dat_header_flags = Some(UNIT_DAT_CONTROL_CLASS_HIGH_BIT);
attach_synthetic_model(&mut assets, 0, &[synthetic_node38(0, 0, [true; 3])]);
assets.models[0].validated.slots[0].opaque =
[7.0_f32.to_bits(), 11.0_f32.to_bits(), 0, 0, 0];
@@ -9747,10 +9975,272 @@ mod tests {
assert_eq!(load.row_20_bits, [41.25_f32.to_bits()]);
assert_eq!(profile.original_words[26], 1000.0_f32.to_bits());
assert_eq!(profile.current_words[26], 980.75_f32.to_bits());
+ assert_eq!(profile.fca0_projection, Ok(()));
assert_eq!(
profile.current_words[..26],
profile.original_words[..26],
- "FAC0 changes only mutable profile word 26"
+ "FAC0 changes only word 26 in this tag-19-only fixture; FCA0 has no E00 contribution"
+ );
+ }
+
+ #[test]
+ fn full_control_fca0_late_float_failure_preserves_fac0_copy() {
+ let native_class = MissionControlClassProjection {
+ class_id: 3,
+ source: MissionControlClassSource::UnitDatHighBit { header_flags: 0 },
+ };
+
+ for (failure, coefficient, profile_word2, expected_error) in [
+ (
+ "nonfinite coefficient during E00 query",
+ f32::INFINITY,
+ 0.0,
+ Err(
+ MissionControlOwnerProfileFca0UnavailableReason::QueryUnavailable(Arc::new(
+ ControlResourceAccessError::NonFiniteValue {
+ factory_tag: 5,
+ field: "coefficient",
+ },
+ )),
+ ),
+ ),
+ (
+ "overflow in final profile-word doubling",
+ 1.0,
+ f32::MAX,
+ Err(
+ MissionControlOwnerProfileFca0UnavailableReason::UnsupportedFloat {
+ field: "FCA0 doubled profile words",
+ },
+ ),
+ ),
+ ] {
+ let mut cache_record = synthetic_control_record(27, 0, 2.0_f32.to_bits(), None);
+ cache_record.fixed_words[7] = 0.0_f32.to_bits();
+ let mut device_record = synthetic_control_record(5, 0, coefficient.to_bits(), None);
+ device_record.fixed_words[7] = 5.25_f32.to_bits();
+ let mut root =
+ control_with_synthetic_node_data(0, vec![cache_record, device_record], 1);
+ root.native_profile_words[0] = 1.0_f32.to_bits();
+ root.native_profile_words[2] = profile_word2.to_bits();
+ root.native_profile_words[26] = 1000.0_f32.to_bits();
+ root.node_data.as_mut().unwrap().rows[0].mobility_per_volume = 2.0;
+ let (mut draft, mut assets, prototypes) =
+ synthetic_control_fixture(&[None], &[1], &[0], &[0], &[1], vec![Some(root)]);
+ attach_synthetic_model(&mut assets, 0, &[synthetic_node38(0, 0, [true; 3])]);
+ assets.models[0].validated.slots[0].opaque =
+ [7.0_f32.to_bits(), 11.0_f32.to_bits(), 0, 0, 0];
+ draft.scale = [2.0, 3.0, 5.0];
+
+ let projection = build_control_device_projection_with_class(
+ 0,
+ &draft,
+ &assets,
+ Some(&(0..prototypes.len())),
+ &prototypes,
+ Some(native_class),
+ )
+ .expect("base device and FAC0 projections");
+ let profile = projection
+ .owner_profile
+ .expect("native component-zero profile");
+ assert!(profile.load_projection.is_ok());
+ assert_eq!(profile.current_words[26], 980.75_f32.to_bits());
+ assert_eq!(profile.fca0_projection, expected_error, "{failure}");
+ assert_eq!(
+ profile.current_words[..26],
+ profile.original_words[..26],
+ "{failure} must not publish any partial FCA0 words"
+ );
+ }
+ }
+
+ #[test]
+ fn fca0_load_profile_matches_native_combined_vector() {
+ let mut original_words = [0_u32; 27];
+ original_words[0] = 1.25_f32.to_bits();
+ original_words[1] = (-2.5_f32).to_bits();
+ original_words[2] = 3.0_f32.to_bits();
+ original_words[6] = 1.0_f32.to_bits();
+ original_words[7] = (-2.0_f32).to_bits();
+ original_words[8] = 10.0_f32.to_bits();
+ original_words[9] = 2.0_f32.to_bits();
+ original_words[10] = (-3.0_f32).to_bits();
+ original_words[11] = 0.5_f32.to_bits();
+ original_words[26] = 4.0_f32.to_bits();
+ for index in [3, 4, 5].into_iter().chain(12..26) {
+ original_words[index] = f32::NAN.to_bits();
+ }
+ let mut current_words = original_words;
+ current_words[26] = 6.0_f32.to_bits();
+ let fac0_projection = Ok(MissionControlOwnerProfileLoadProjection {
+ aggregate_530_bits: 0,
+ aggregate_534_bits: 0,
+ aggregate_538_bits: 0,
+ row_20_bits: vec![0; 3],
+ });
+ let mut device = synthetic_effective_control_device(
+ 5,
+ 5,
+ 2.0_f32.to_bits(),
+ Some(17.0_f32.to_bits()),
+ None,
+ );
+ device.key = 2;
+ device.descriptor.fixed_words[8] = 7.0_f32.to_bits();
+ let mut second_device = synthetic_effective_control_device(
+ 5,
+ 5,
+ 0.5_f32.to_bits(),
+ Some(17.0_f32.to_bits()),
+ None,
+ );
+ second_device.key = 0;
+ second_device.descriptor.fixed_words[8] = 7.0_f32.to_bits();
+ let devices = vec![device, second_device];
+ let provider_status = MissionControlNodeProviderTableStatus::Available(vec![
+ synthetic_node_provider_row(0, 0, (-1.5_f32).to_bits()),
+ synthetic_node_provider_row(0, 1, 123.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 2, 3.0_f32.to_bits()),
+ ]);
+ let mut expected = current_words;
+ expected[0] = 2.5_f32.to_bits();
+ expected[1] = (-5.0_f32).to_bits();
+ expected[2] = 6.0_f32.to_bits();
+ expected[6] = 1.0_f32.to_bits();
+ // The native signed-cap comparison turns this negative result into +2.
+ expected[7] = 2.0_f32.to_bits();
+ expected[8] = 10.0_f32.to_bits();
+ expected[9] = 28.875_f32.to_bits();
+ expected[10] = (-43.3125_f32).to_bits();
+ expected[11] = 7.21875_f32.to_bits();
+ for class_id in [0, 3, 4] {
+ assert_eq!(
+ project_control_owner_profile_fca0(
+ Some(MissionControlClassProjection {
+ class_id,
+ source: MissionControlClassSource::UnitDatHighBit { header_flags: 0 },
+ }),
+ &original_words,
+ &current_words,
+ &fac0_projection,
+ &devices,
+ &provider_status,
+ ),
+ Ok(expected),
+ "native class {class_id} follows FCA0 unless it is class 9"
+ );
+ }
+ }
+
+ #[test]
+ fn fca0_load_profile_uses_reverse_device_order_for_e00_sum() {
+ let mut original_words = [0_u32; 27];
+ original_words[6] = 2.0_f32.to_bits();
+ original_words[26] = 1.0_f32.to_bits();
+ let current_words = original_words;
+ let fac0_projection = Ok(MissionControlOwnerProfileLoadProjection {
+ aggregate_530_bits: 0,
+ aggregate_534_bits: 0,
+ aggregate_538_bits: 0,
+ row_20_bits: vec![0; 3],
+ });
+ let mut first = synthetic_effective_control_device(
+ 5,
+ 5,
+ 1.0_f32.to_bits(),
+ Some(1.0_f32.to_bits()),
+ None,
+ );
+ first.key = 2;
+ let mut second = first.clone();
+ second.key = 0;
+ let mut third = first.clone();
+ third.key = 1;
+ let devices = vec![first, second, third];
+ let provider_status = MissionControlNodeProviderTableStatus::Available(vec![
+ synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 1, (-16_777_216.0_f32).to_bits()),
+ synthetic_node_provider_row(0, 2, 16_777_216.0_f32.to_bits()),
+ ]);
+ let class = MissionControlClassProjection {
+ class_id: 3,
+ source: MissionControlClassSource::UnitDatHighBit { header_flags: 0 },
+ };
+
+ assert_eq!(
+ project_control_owner_profile_fca0(
+ Some(class),
+ &original_words,
+ &current_words,
+ &fac0_projection,
+ &devices,
+ &provider_status,
+ ),
+ Ok(current_words),
+ "reverse E00 order sums to one, so profile word 6 remains capped at two"
+ );
+ }
+
+ #[test]
+ fn fca0_class9_returns_before_profile_or_device_inputs() {
+ let original_words = [f32::NAN.to_bits(); 27];
+ let current_words = [0x7f80_0000; 27];
+ let fac0_projection = Err(
+ MissionControlOwnerProfileLoadProjectionUnavailableReason::UnknownModelMapping {
+ global_node_ordinal: None,
+ },
+ );
+ let provider_status = MissionControlNodeProviderTableStatus::Unavailable(
+ MissionControlNodeProviderTableUnavailableReason::MissingNodeData {
+ unit_component_index: 0,
+ source: None,
+ },
+ );
+ let class9 = MissionControlClassProjection {
+ class_id: 9,
+ source: MissionControlClassSource::RootPrototypeFourCc { source_type: 0 },
+ };
+
+ assert_eq!(
+ project_control_owner_profile_fca0(
+ Some(class9),
+ &original_words,
+ &current_words,
+ &fac0_projection,
+ &[],
+ &provider_status,
+ ),
+ Ok(current_words)
+ );
+ assert_eq!(
+ project_control_owner_profile_fca0(
+ None,
+ &original_words,
+ &current_words,
+ &fac0_projection,
+ &[],
+ &provider_status,
+ ),
+ Err(MissionControlOwnerProfileFca0UnavailableReason::MissingNativeControlClass)
+ );
+ assert_eq!(
+ project_control_owner_profile_fca0(
+ Some(MissionControlClassProjection {
+ class_id: 4,
+ source: class9.source,
+ }),
+ &original_words,
+ &current_words,
+ &fac0_projection,
+ &[],
+ &provider_status,
+ ),
+ Err(MissionControlOwnerProfileFca0UnavailableReason::Fac0Unavailable(
+ MissionControlOwnerProfileLoadProjectionUnavailableReason::UnknownModelMapping {
+ global_node_ordinal: None,
+ }
+ ))
);
}
@@ -10515,6 +11005,72 @@ mod tests {
}
#[test]
+ fn factory5_e00_uses_provider_times_coefficient_only() {
+ let mut device = synthetic_effective_control_device(
+ 5,
+ 5,
+ 3.0_f32.to_bits(),
+ Some(17.0_f32.to_bits()),
+ None,
+ );
+ device.descriptor.fixed_words[8] = 13.0_f32.to_bits();
+ let table = synthetic_control_device_table_with_providers(
+ MissionControlDeviceTableStatus::Available(vec![device]),
+ MissionControlNodeProviderTableStatus::Available(vec![
+ synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 1, 2.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 2, 7.0_f32.to_bits()),
+ ]),
+ );
+
+ assert_eq!(
+ query_control_device_table_selector(&table, 0, 0xe00)
+ .expect("factory-5 E00 query")
+ .map(f32::to_bits),
+ Some(21.0_f32.to_bits()),
+ "E00 uses the provider row and coefficient, without the multiplier or descriptor word 8"
+ );
+ }
+
+ #[test]
+ fn e00_common_reader_covers_current_tags_and_both_factories() {
+ let devices = [(5, 5), (5, 26), (26, 5), (26, 26)]
+ .into_iter()
+ .map(|(current_tag, factory_tag)| {
+ let mut device = synthetic_effective_control_device(
+ factory_tag,
+ current_tag,
+ 3.0_f32.to_bits(),
+ Some(17.0_f32.to_bits()),
+ None,
+ );
+ device.descriptor.fixed_words[8] = 13.0_f32.to_bits();
+ device
+ })
+ .collect();
+ let table = synthetic_control_device_table_with_providers(
+ MissionControlDeviceTableStatus::Available(devices),
+ MissionControlNodeProviderTableStatus::Available(vec![
+ synthetic_node_provider_row(0, 0, 1.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 1, 2.0_f32.to_bits()),
+ synthetic_node_provider_row(0, 2, 7.0_f32.to_bits()),
+ ]),
+ );
+
+ for (device_index, (current_tag, factory_tag)) in
+ [(5, 5), (5, 26), (26, 5), (26, 26)].into_iter().enumerate()
+ {
+ let expected = if current_tag == 5 { 21.0 } else { 357.0 };
+ assert_eq!(
+ query_control_device_table_selector(&table, device_index, 0xe00)
+ .expect("shared E00 factory getter"),
+ Some(expected),
+ "current tag {current_tag}, factory tag {factory_tag}"
+ );
+ }
+ }
+
+ #[test]
fn native_mesh_metadata_maps_control_flags_and_parent_words() {
assert_eq!(control_flags_from_node38_header(0x0701), 0x0f);
assert_eq!(control_flags_from_node38_header(0x0781), 0x07);
@@ -10670,7 +11226,7 @@ mod tests {
query_control_device_table_selector(&table, 1, 0xe00),
Ok(None)
);
- for tag in [5, 10, 21] {
+ for tag in [10, 21] {
let mut unsupported = table.clone();
let MissionControlDeviceTableStatus::Available(entries) = &mut unsupported.status
else {
@@ -10682,6 +11238,16 @@ mod tests {
Err(ControlResourceAccessError::UnsupportedCurrentTag { tag })
);
}
+ let mut current_tag5_factory9 = table.clone();
+ let MissionControlDeviceTableStatus::Available(entries) = &mut current_tag5_factory9.status
+ else {
+ unreachable!();
+ };
+ entries[3].descriptor.tag = 5;
+ assert_eq!(
+ query_control_device_table_selector(&current_tag5_factory9, 3, 0xe00),
+ Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag: 9 })
+ );
assert_eq!(
query_control_device_table_selector(&table, 3, 0xe00),
Err(ControlResourceAccessError::UnsupportedFactoryTag { factory_tag: 9 })
@@ -10982,6 +11548,19 @@ mod tests {
.owner_profile
.as_ref()
.expect("loaded root owner profile");
+ let fca0_target_indices = [0, 1, 2, 6, 7, 8, 9, 10, 11];
+ let fca0_target_words = fca0_target_indices.map(|index| owner_profile.current_words[index]);
+ println!(
+ "licensed mine FCA0: class={:?} projection={:?} indices={fca0_target_indices:?} targets={:08x?}",
+ mine_control_before[0].native_control_class,
+ owner_profile.fca0_projection,
+ fca0_target_words,
+ );
+ assert_eq!(owner_profile.fca0_projection, Ok(()));
+ assert_eq!(
+ fca0_target_words,
+ [0x4000_0000, 0x4000_0000, 0x4000_0000, 0, 0, 0, 0, 0, 0,]
+ );
assert_eq!(owner_profile.unit_component_index, 0);
assert_eq!(owner_profile.native_component_id, 0);
assert_eq!(owner_profile.source, root_control.source);
@@ -11035,10 +11614,14 @@ mod tests {
assert_eq!(mine_fac0.row_20_bits.len(), 25);
assert_eq!(owner_profile.original_words[26], 0x7f7f_ffff);
assert_eq!(owner_profile.current_words[26], 0x7f7f_ffff);
- assert_eq!(
- &owner_profile.current_words[..26],
- &root_control.native_profile_words[..26]
- );
+ for index in 0..26 {
+ if !fca0_target_indices.contains(&index) {
+ assert_eq!(
+ owner_profile.current_words[index], owner_profile.original_words[index],
+ "FCA0 leaves profile word {index} unchanged"
+ );
+ }
+ }
assert_ne!(
root_control.native_profile_words, child_control.native_profile_words,
"the licensed child CTLD has its own profile words"
diff --git a/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs b/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs
index 4fcee01..fe76909 100644
--- a/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs
+++ b/crates/fparkan-runtime/tests/behavior_distributor_tick_native_oracle.cs
@@ -15,6 +15,7 @@ internal static class BehaviorDistributorTickOracle {
private const uint PageExecuteReadWrite = 0x40;
private const uint MemRelease = 0x00008000;
private const uint PageReadWrite = 0x04;
+ private const uint PageNoAccess = 0x01;
private const string ExpectedBehaviorSha256 = "ddfbdbde07832358fe6e35e01c8dba9b58e7313789498b6049ed51d4ed9baf99";
private const string ExpectedControlSha256 = "bcb86318089028548a178b03a21accdce15df0cc85ddd91674cf3c2f55012c6e";
private const string ExpectedArealMapSha256 = "a25f9254ebb339d70e2e07c8121950191e9584ca0858d8e9c2e2b6c671edf6ea";
@@ -82,10 +83,12 @@ internal static class BehaviorDistributorTickOracle {
private const int ControlResourceTag19VtableRva = 0x3c608;
private const int ControlResourceTag19StringPairNoOpRva = 0x0bcd0;
private const int ControlProfileFac0Rva = 0x0fac0;
+ private const int ControlProfileFca0Rva = 0x0fca0;
private const int ControlProfileOwnerConstructorRva = 0x31490;
private const int ControlProfileDeviceVtableRva = 0x3d1b4;
private const int ControlProfileDeviceCountRva = 0x08830;
private const int ControlProfileDeviceQueryRva = 0x2bb40;
+ private const int ControlResourceTag5VtableRva = 0x3cdf8;
private const int AniMeshComponentFirstRva = 0x05780;
private const int AniMeshComponentCountRva = 0x057c0;
private const int BehaviorVarTableVtableRva = 0x591b0;
@@ -150,6 +153,8 @@ internal static class BehaviorDistributorTickOracle {
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate IntPtr NativeControlResourceComponentOverride(IntPtr self, int deviceIndex, IntPtr typedRecord);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeControlAggregateQuery(IntPtr self, uint selector, IntPtr result);
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NativeControlAggregateSet(IntPtr self, uint selector, IntPtr value);
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint NativeControlOwnerDeviceQuery(IntPtr ownerInterface, uint deviceIndex, uint selector, IntPtr result);
+ [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlDeviceBind(IntPtr device, IntPtr owner, IntPtr provider, IntPtr model);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeAniMeshNodeConstructor(IntPtr self, IntPtr model, IntPtr source, uint component, IntPtr meshData);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderAmountUpdate(IntPtr self, int nodeIndex, float delta, uint animationFlag);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void NativeControlProviderAmountDistribute(IntPtr self, float delta, uint mode, uint flags);
@@ -700,7 +705,7 @@ internal static class BehaviorDistributorTickOracle {
Marshal.WriteIntPtr(import, Marshal.GetFunctionPointerForDelegate(AreaMapGetterCallback));
Marshal.WriteIntPtr(queueImport, Marshal.GetFunctionPointerForDelegate(QueueGetterCallback));
RunSmokeCases(module, controlModule, arealMapModule, aniMeshModule);
- Console.WriteLine("original native Behavior/ArealMap/Control oracle passed (Behavior Add 0x1aac0, normalize 0x1ac90, scheduler 0x1adb0, tick 0x19e80; ArealMap UnitDAT projection 0x14b90; Control INTO override 0x2d890, FAC0 load profile 0xfac0, provider distribution 0x10ba0, class-4 update 0x12a40 and bounded class-10 active clock 0xbcf0; FAC0 uses synthetic backing with original AniMesh and Control query methods; other host callbacks, GetSystemArealMap/GetQueue IAT slots, and bounded vector insertion are substituted; no full UnitDAT loading or gameplay parity is claimed).");
+ Console.WriteLine("original native Behavior/ArealMap/Control oracle passed (Behavior Add 0x1aac0, normalize 0x1ac90, scheduler 0x1adb0, tick 0x19e80; ArealMap UnitDAT projection 0x14b90; Control INTO override 0x2d890, FAC0 initial profile 0xfac0, FCA0 initial profile 0xfca0, provider distribution 0x10ba0, class-4 update 0x12a40 and bounded class-10 active clock 0xbcf0; FAC0/FCA0 use synthetic backing with original AniMesh and Control query methods; other host callbacks, GetSystemArealMap/GetQueue IAT slots, and bounded vector insertion are substituted; no full UnitDAT loading or gameplay parity is claimed).");
return 0;
}
catch (Exception error) {
@@ -2801,6 +2806,7 @@ internal static class BehaviorDistributorTickOracle {
RunFac0NegativeClamp(controlModule, aniMeshModule, constructOwner, fac0, findFirst, countMatches);
RunFac0NullAndSignedZeroCases(controlModule, aniMeshModule, constructOwner, fac0);
RunFac0OrderedCase(controlModule, aniMeshModule, constructOwner, fac0);
+ RunNativeControlFca0LoadCases(controlModule, constructOwner);
Expect(CurrentX87ControlWord() == 0x007f, "FAC0 vectors use x87 control word 0x007f");
Console.WriteLine("native-control-fac0-load: controlHash=" + ExpectedControlSha256 +
" aniMeshHash=" + ExpectedAniMeshSha256 + " rva=0x0fac0 cw=0x" +
@@ -2847,11 +2853,11 @@ internal static class BehaviorDistributorTickOracle {
private static IntPtr CreateFac0Owner(Fixture fixture, IntPtr controlModule,
NativeControlOwnerConstructor constructOwner, IntPtr ani, uint originalWord26,
float[] descriptorMobility, float[] mutableAmounts, bool hasCache, float cacheC,
- uint[] deviceKeys, float[] deviceValues) {
+ uint[] deviceKeys, float[] deviceValues, uint classCode = 4) {
Expect(descriptorMobility.Length == mutableAmounts.Length, "FAC0 provider fixture lengths");
Expect(deviceKeys.Length == deviceValues.Length, "FAC0 device fixture lengths");
IntPtr owner = fixture.Allocate(0x700);
- Expect(constructOwner(owner, IntPtr.Zero, 4) == owner, "original Control owner constructor 0x31490");
+ Expect(constructOwner(owner, IntPtr.Zero, classCode) == owner, "original Control owner constructor 0x31490");
IntPtr deviceInterface = IntPtr.Add(owner, 0x0c);
IntPtr deviceVtable = Marshal.ReadIntPtr(deviceInterface);
Expect(deviceVtable == IntPtr.Add(controlModule, ControlProfileDeviceVtableRva) &&
@@ -2898,6 +2904,237 @@ internal static class BehaviorDistributorTickOracle {
return owner;
}
+ private static IntPtr CreateFca0Owner(Fixture fixture, IntPtr controlModule,
+ NativeControlOwnerConstructor constructOwner, int rowCount, int deviceCapacity) {
+ float[] rowDefaults = new float[rowCount];
+ IntPtr owner = CreateFac0Owner(fixture, controlModule, constructOwner, IntPtr.Zero,
+ FloatBitsUnsigned(4.0f), rowDefaults, rowDefaults, false, 0.0f,
+ new uint[0], new float[0], 3);
+ IntPtr deviceInterface = IntPtr.Add(owner, 0x0c);
+ Expect(Marshal.ReadIntPtr(owner, 0x38) == deviceInterface,
+ "FCA0 owner+0x38 uses its canonical owner+0x0c interface");
+ IntPtr providerInterface = IntPtr.Add(owner, 4);
+ IntPtr providerVtable = Marshal.ReadIntPtr(providerInterface);
+ Expect(providerVtable == IntPtr.Add(controlModule, ControlProviderInterfaceVtableRva) &&
+ Marshal.ReadIntPtr(providerVtable, 0x0c) == IntPtr.Add(controlModule, ControlProviderType1GetterRva),
+ "FCA0 binder receives owner+4 with the original FUN_1000dc40 provider slot");
+ Marshal.WriteIntPtr(owner, 0x5bc, fixture.Allocate(Math.Max(1, deviceCapacity) * IntPtr.Size));
+ Marshal.WriteInt32(owner, 0x5c0, 0);
+ Marshal.WriteInt32(owner, 0x5c4, deviceCapacity);
+ return owner;
+ }
+
+ private static IntPtr CreateFca0Factory5Device(Fixture fixture, IntPtr controlModule,
+ NativeControlDeviceFactory createDevice, NativeControlDeviceBind bindDevice, IntPtr owner,
+ uint key, float coefficient, float descriptorWord8, int ordinal) {
+ IntPtr deviceArrayBeforeFactory = Marshal.ReadIntPtr(owner, 0x5bc);
+ int countBeforeFactory = Marshal.ReadInt32(owner, 0x5c0);
+ int capacityBeforeFactory = Marshal.ReadInt32(owner, 0x5c4);
+ Expect(ordinal == countBeforeFactory,
+ "factory-5 ordinal matches the owner device count before append " + ordinal);
+ Expect(capacityBeforeFactory > countBeforeFactory + 1,
+ "factory-5 fixture reserves a spare device-vector slot before appending ordinal " + ordinal);
+ IntPtr record = fixture.Allocate(0xc0);
+ Marshal.WriteInt32(record, 0, 5);
+ Marshal.WriteInt32(record, 4, unchecked((int)key));
+ Marshal.WriteInt32(record, 0x18, -1);
+ Marshal.WriteInt32(record, 0x20, FloatBits(descriptorWord8));
+ for (int i = 0; i < 16; i++)
+ Marshal.WriteInt32(record, 0x2c + i * 4, FloatBits(i == 0 ? coefficient : 0.0f));
+ Marshal.WriteInt32(record, 0xac, 0);
+ Marshal.WriteInt32(record, 0xb0, 0);
+ Expect(createDevice(owner, 0, 0, record) == IntPtr.Add(record, 0xb4),
+ "original Control factory-5 dispatch 0x2d4b0 consumes its typed record");
+ Expect(Marshal.ReadIntPtr(owner, 0x5bc) == deviceArrayBeforeFactory,
+ "factory-5 append keeps the owner device-vector pointer captured before construction");
+ Expect(Marshal.ReadInt32(owner, 0x5c0) == countBeforeFactory + 1,
+ "factory-5 append advances the owner device count before reading the captured array");
+ IntPtr device = Marshal.ReadIntPtr(deviceArrayBeforeFactory, ordinal * IntPtr.Size);
+ Expect(device != IntPtr.Zero, "original factory-5 publishes its device at the expected ordinal");
+ IntPtr deviceVtable = Marshal.ReadIntPtr(device);
+ Expect(deviceVtable == IntPtr.Add(controlModule, ControlResourceTag5VtableRva) &&
+ Marshal.ReadIntPtr(deviceVtable, 0x10) == IntPtr.Add(controlModule, ControlResourceDeviceGetterRva) &&
+ Marshal.ReadIntPtr(deviceVtable, 0x1c) == IntPtr.Add(controlModule, ControlResourceCommonSetterRva),
+ "factory-5 vtable uses the original reader 0x21d00 and setter 0x21d50");
+ Expect(Marshal.ReadIntPtr(device, 0x48) == record && Marshal.ReadInt32(device, 4) == unchecked((int)key) &&
+ Marshal.ReadInt32(device, 0x50) == 5 && Marshal.ReadInt32(device, 0x4c) == FloatBits(1.0f),
+ "factory-5 current descriptor, key, and constructor defaults");
+ bindDevice(device, owner, IntPtr.Add(owner, 4), IntPtr.Zero);
+ Expect(Marshal.ReadIntPtr(device, 0x3c) == owner && Marshal.ReadIntPtr(device, 0x44) == IntPtr.Add(owner, 4) &&
+ Marshal.ReadIntPtr(device, 0x40) == IntPtr.Zero,
+ "original binder 0x21990 binds owner and owner+4 with a null model");
+ Console.WriteLine("native-control-fca0-factory5: ordinal=" + ordinal + " key=" + key +
+ " coefficient0=" + Float((uint)FloatBits(coefficient)) + " descriptor+0x20=" + Float((uint)FloatBits(descriptorWord8)) +
+ " model=null vtable=0x3cdf8");
+ return device;
+ }
+
+ private static float QueryFca0E00(IntPtr controlModule, NativeControlOwnerDeviceQuery query,
+ Fixture fixture, IntPtr owner, uint ordinal) {
+ IntPtr ownerInterface = IntPtr.Add(owner, 0x0c);
+ IntPtr ownerVtable = Marshal.ReadIntPtr(ownerInterface);
+ Expect(Marshal.ReadIntPtr(ownerVtable, 0x18) == IntPtr.Add(controlModule, ControlProfileDeviceQueryRva),
+ "owner device query table resolves to original FUN_1002bb40");
+ IntPtr result = fixture.Allocate(sizeof(uint));
+ Expect((query(ownerInterface, ordinal, 0x0e00, result) & 0xff) == 1,
+ "original owner query returns selector E00 for factory-5 device " + ordinal);
+ return ReadFloat(result, 0);
+ }
+
+ private static void RunNativeControlFca0LoadCases(IntPtr controlModule,
+ NativeControlOwnerConstructor constructOwner) {
+ NativeControlProfileFac0 fca0 = (NativeControlProfileFac0)Marshal.GetDelegateForFunctionPointer(
+ WriteStdCallToFastcallOneArgThunk(0x4c0, IntPtr.Add(controlModule, ControlProfileFca0Rva)),
+ typeof(NativeControlProfileFac0));
+ NativeControlOwnerDeviceQuery query = (NativeControlOwnerDeviceQuery)Marshal.GetDelegateForFunctionPointer(
+ WriteStdCallFourArgsToFastcallThunk(0x500, IntPtr.Add(controlModule, ControlProfileDeviceQueryRva)),
+ typeof(NativeControlOwnerDeviceQuery));
+ NativeControlDeviceFactory createDevice = (NativeControlDeviceFactory)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(controlModule, ControlResourceTag26ConstructorRva), typeof(NativeControlDeviceFactory));
+ NativeControlDeviceBind bindDevice = (NativeControlDeviceBind)Marshal.GetDelegateForFunctionPointer(
+ IntPtr.Add(controlModule, 0x21990), typeof(NativeControlDeviceBind));
+ Expect(CurrentX87ControlWord() == 0x007f, "FCA0 vectors start with the game x87 control word");
+
+ using (Fixture fixture = NewFixture()) {
+ IntPtr owner = CreateFca0Owner(fixture, controlModule, constructOwner, 3, 2);
+ Marshal.WriteInt32(owner, 0x1a8, FloatBits(17.0f));
+ Marshal.WriteInt32(owner, 0x354, FloatBits(1.0f));
+ Marshal.WriteInt32(owner, 0x358, FloatBits(1.0f));
+ IntPtr rows = Marshal.ReadIntPtr(owner, 0x55c);
+ Marshal.WriteInt32(rows, 2 * 0x2c + 0x14, FloatBits(7.0f));
+ IntPtr device = CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice,
+ owner, 2, 3.0f, 13.0f, 0);
+ Marshal.WriteInt32(device, 0x4c, FloatBits(17.0f));
+ float value = QueryFca0E00(controlModule, query, fixture, owner, 0);
+ Expect(unchecked((uint)FloatBits(value)) == 0x41a80000,
+ "E00 uses provider key 2 value 7 times coefficient 3, ignoring M=17 and descriptor word8=13");
+ Console.WriteLine("native-control-fca0-reader-aligned: class=3 factory=5 ordinal=0 providerKey=2 type1=0x40e00000" +
+ " coefficient0=0x40400000 device+4c(M)=0x41880000 descriptorWord8=13 E00=21 raw=0x" +
+ unchecked((uint)FloatBits(value)).ToString("x8"));
+ }
+
+ using (Fixture fixture = NewFixture()) {
+ IntPtr owner = CreateFca0Owner(fixture, controlModule, constructOwner, 3, 3);
+ IntPtr rows = Marshal.ReadIntPtr(owner, 0x55c);
+ Marshal.WriteInt32(rows, 0x14, FloatBits(-1.5f));
+ Marshal.WriteInt32(rows, 0x2c + 0x14, FloatBits(123.0f));
+ Marshal.WriteInt32(rows, 2 * 0x2c + 0x14, FloatBits(3.0f));
+ Marshal.WriteInt32(owner, 0x1a8, FloatBits(1.0f));
+ Marshal.WriteInt32(owner, 0x354, FloatBits(1.0f));
+ Marshal.WriteInt32(owner, 0x358, FloatBits(1.0f));
+ IntPtr profile = Marshal.ReadIntPtr(owner, 0x46c);
+ float[] words = { 1.25f, -2.5f, 3.0f };
+ for (int i = 0; i < words.Length; i++) Marshal.WriteInt32(profile, i * 4, FloatBits(words[i]));
+ Marshal.WriteInt32(profile, 6 * 4, FloatBits(1.0f));
+ Marshal.WriteInt32(profile, 7 * 4, FloatBits(-2.0f));
+ Marshal.WriteInt32(profile, 8 * 4, FloatBits(10.0f));
+ Marshal.WriteInt32(profile, 9 * 4, FloatBits(2.0f));
+ Marshal.WriteInt32(profile, 10 * 4, FloatBits(-3.0f));
+ Marshal.WriteInt32(profile, 11 * 4, FloatBits(0.5f));
+ Marshal.WriteInt32(profile, 26 * 4, FloatBits(4.0f));
+ Marshal.WriteInt32(owner, 0x4d8, FloatBits(6.0f));
+ CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 2, 2.0f, 7.0f, 0);
+ CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 0, 0.5f, 7.0f, 1);
+ float first = QueryFca0E00(controlModule, query, fixture, owner, 0);
+ float second = QueryFca0E00(controlModule, query, fixture, owner, 1);
+ Expect(unchecked((uint)FloatBits(first)) == 0x40c00000 &&
+ unchecked((uint)FloatBits(second)) == 0xbf400000,
+ "canonical FCA0 E00 samples use provider keys 2 and 0");
+ fca0(owner);
+ Expect(CurrentX87ControlWord() == 0x007f, "FCA0 canonical vector retains CW=0x007f");
+ int[] offsets = { 0x470, 0x474, 0x478, 0x488, 0x48c, 0x490, 0x494, 0x498, 0x49c };
+ uint[] expected = {
+ 0x40200000, 0xc0a00000, 0x40c00000, 0x3f800000, 0x40000000,
+ 0x41200000, 0x41e70000, 0xc22d4000, 0x40e70000
+ };
+ for (int i = 0; i < offsets.Length; i++)
+ Expect(ReadFac0Word(owner, offsets[i]) == expected[i],
+ "canonical FCA0 owner+0x" + offsets[i].ToString("x") + " raw word " + Hex(expected[i]));
+ Expect(ReadFac0Word(owner, 0x4d8) == FloatBitsUnsigned(6.0f),
+ "FCA0 leaves its current word-26 ratio input unchanged");
+ Console.WriteLine("native-control-fca0-canonical-default: class=3 devices=[i0:key2:E00=0x40c00000,i1:key0:E00=0xbf400000]" +
+ " scalar+1a8=0x3f800000 means+354/+358=0x3f800000 ratio=6/4 outputs=[470=40200000,474=c0a00000,478=40c00000" +
+ ",488=3f800000,48c=40000000,490=41200000,494=41e70000,498=c22d4000,49c=40e70000]");
+ }
+
+ using (Fixture fixture = NewFixture()) {
+ IntPtr owner = CreateFca0Owner(fixture, controlModule, constructOwner, 3, 4);
+ IntPtr rows = Marshal.ReadIntPtr(owner, 0x55c);
+ Marshal.WriteInt32(rows, 0x14, FloatBits(1.0f));
+ Marshal.WriteInt32(rows, 0x2c + 0x14, FloatBits(-16777216.0f));
+ Marshal.WriteInt32(rows, 2 * 0x2c + 0x14, FloatBits(16777216.0f));
+ Marshal.WriteInt32(owner, 0x1a8, FloatBits(1.0f));
+ Marshal.WriteInt32(owner, 0x354, FloatBits(1.0f));
+ Marshal.WriteInt32(owner, 0x358, FloatBits(1.0f));
+ IntPtr profile = Marshal.ReadIntPtr(owner, 0x46c);
+ Marshal.WriteInt32(profile, 6 * 4, FloatBits(2.0f));
+ Marshal.WriteInt32(profile, 26 * 4, FloatBits(1.0f));
+ Marshal.WriteInt32(owner, 0x4d8, FloatBits(1.0f));
+ CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 2, 1.0f, 1.0f, 0);
+ CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 0, 1.0f, 1.0f, 1);
+ CreateFca0Factory5Device(fixture, controlModule, createDevice, bindDevice, owner, 1, 1.0f, 1.0f, 2);
+ float[] samples = {
+ QueryFca0E00(controlModule, query, fixture, owner, 0),
+ QueryFca0E00(controlModule, query, fixture, owner, 1),
+ QueryFca0E00(controlModule, query, fixture, owner, 2)
+ };
+ Expect(unchecked((uint)FloatBits(samples[0])) == 0x4b800000 &&
+ unchecked((uint)FloatBits(samples[1])) == 0x3f800000 &&
+ unchecked((uint)FloatBits(samples[2])) == 0xcb800000,
+ "reverse-order vector E00 values");
+ float forward = 0.0f;
+ for (int i = 0; i < samples.Length; i++)
+ forward = BitConverter.ToSingle(BitConverter.GetBytes(forward + samples[i]), 0);
+ float reverse = 0.0f;
+ for (int i = samples.Length - 1; i >= 0; i--)
+ reverse = BitConverter.ToSingle(BitConverter.GetBytes(reverse + samples[i]), 0);
+ Expect(unchecked((uint)FloatBits(forward)) == 0x00000000 &&
+ unchecked((uint)FloatBits(reverse)) == 0x3f800000,
+ "single-precision forward sum is zero while native reverse-order sum is one");
+ fca0(owner);
+ Expect(ReadFac0Word(owner, 0x488) == 0x40000000,
+ "FCA0 owner+0x488 uses reverse E00 sum one times original word 6 two");
+ Console.WriteLine("native-control-fca0-reverse: device-array=[16777216,1,-16777216]" +
+ " reverse-visits=[-16777216,1,16777216] forward=0x00000000 reverse=0x3f800000 owner+488=0x40000000");
+ }
+
+ int pageSize = Environment.SystemPageSize;
+ IntPtr guarded = VirtualAlloc(IntPtr.Zero, new UIntPtr((uint)(pageSize * 2)), MemCommitReserve, PageReadWrite);
+ if (guarded == IntPtr.Zero)
+ throw new InvalidOperationException("VirtualAlloc class-9 FCA0 guard pages error=" + Marshal.GetLastWin32Error());
+ try {
+ for (int i = 0; i < pageSize; i++) Marshal.WriteByte(guarded, i, 0xa5);
+ IntPtr owner = IntPtr.Add(guarded, pageSize - 0x100);
+ Marshal.WriteIntPtr(owner, 0x38, IntPtr.Zero);
+ Marshal.WriteInt32(owner, 0x50, 9);
+ byte[] before = new byte[pageSize];
+ Marshal.Copy(guarded, before, 0, pageSize);
+ uint oldProtect;
+ if (!VirtualProtect(IntPtr.Add(guarded, pageSize), new UIntPtr((uint)pageSize), PageNoAccess, out oldProtect))
+ throw new InvalidOperationException("VirtualProtect class-9 FCA0 guard page error=" + Marshal.GetLastWin32Error());
+ fca0(owner);
+ byte[] after = new byte[pageSize];
+ Marshal.Copy(guarded, after, 0, pageSize);
+ bool unchanged = true;
+ for (int i = 0; i < before.Length; i++) unchanged &= before[i] == after[i];
+ Expect(unchanged && Marshal.ReadInt32(owner, 0x50) == 9,
+ "class 9 FCA0 returns without reading inaccessible profile/output memory or writing owner state");
+ Console.WriteLine("native-control-fca0-class9: owner+50=9 profile/output page is PAGE_NOACCESS; returned without fault or writes");
+ } finally {
+ VirtualFree(guarded, UIntPtr.Zero, MemRelease);
+ }
+
+ Expect(CurrentX87ControlWord() == 0x007f, "FCA0 vectors retain x87 control word 0x007f");
+ Console.WriteLine("native-control-fca0-load: controlHash=" + ExpectedControlSha256 +
+ " rva=0x0fca0 cw=0x" + CurrentX87ControlWord().ToString("x4") +
+ " original owner/factory5/binder/provider/query/reader/setter paths");
+ GC.KeepAlive(fca0);
+ GC.KeepAlive(query);
+ GC.KeepAlive(createDevice);
+ GC.KeepAlive(bindDevice);
+ GC.KeepAlive(constructOwner);
+ }
+
private static uint ReadFac0Word(IntPtr address, int offset) {
return unchecked((uint)Marshal.ReadInt32(address, offset));
}