From f8dcceda5e83d1ca64365cc95489a1cd0087cc70 Mon Sep 17 00:00:00 2001 From: ddidderr Date: Sun, 23 Aug 2026 18:46:44 +0200 Subject: [PATCH] fix(physics): restore binary record scan order Interleave static ranges, type-three captures, type-four triggers, magnetic records, and dynamic ball records in exact ID order while tracking predicted position separately from mutable motion. Preserve type-three/dynamic broadphase and the raw stack quirk where fixed candidate slot one wins even when a later candidate is nearer; seal that behavior in both C and Rust harnesses. Test Plan: - bash original/tools/test_reconstructed_c.sh - python3 original/tools/audit_reconstruction.py --require-complete - cargo test --all-targets - cargo clippy --all-targets --all-features -- -D warnings - rumdl check original/C_RECONSTRUCTION_FINAL_AUDIT.md original/MECHANICS_PROGRESS.md tdkpin-rs/CHANGELOG.md tdkpin-rs/RECONSTRUCTION.md tdkpin-rs/README.md - git diff --check --- original/C_RECONSTRUCTION_FINAL_AUDIT.md | 5 +- original/MECHANICS_PROGRESS.md | 9 +- original/reconstructed/tdkpin_physics.c | 3 + original/reconstructed/tests/test_physics.c | 16 + tdkpin-rs/CHANGELOG.md | 4 + tdkpin-rs/RECONSTRUCTION.md | 4 +- tdkpin-rs/src/game.rs | 473 ++++++++++++++++---- tdkpin-rs/src/original_physics.rs | 49 +- 8 files changed, 458 insertions(+), 105 deletions(-) diff --git a/original/C_RECONSTRUCTION_FINAL_AUDIT.md b/original/C_RECONSTRUCTION_FINAL_AUDIT.md index bbdddd0..2af06a2 100644 --- a/original/C_RECONSTRUCTION_FINAL_AUDIT.md +++ b/original/C_RECONSTRUCTION_FINAL_AUDIT.md @@ -74,7 +74,10 @@ the original Borland compiler. Post-audit evidence correction (2026-08-23): raw `1000:9b69` reads predicted DGROUP coordinates `1028:07db/07df`, not current `07d3/07d7`. The readable helper and its harness now reflect that distinction; the complete C test and -ledger gates below still pass. +ledger gates below still pass. Raw `1000:c79c` also confirms that the response +reads fixed candidate slot 1 at `SS:...d8a2`; later nearer candidates are stored +in subsequent 0x34-byte slots but do not replace the applied record. A focused +two-candidate harness now seals that record-order behavior. ## Reproducible gates diff --git a/original/MECHANICS_PROGRESS.md b/original/MECHANICS_PROGRESS.md index f5f2244..79b9cb1 100644 --- a/original/MECHANICS_PROGRESS.md +++ b/original/MECHANICS_PROGRESS.md @@ -164,10 +164,11 @@ the associated magnetic gate; there is no recovered 1,500-per-target plus scores and use the same enter-once contact bit, which clears after the ball leaves their radius. -The collision scan at `1000:c79c` does not resolve the first matching object id. -It retains the smallest path-progress value while traversing all 175 records, -then applies that response from the previous position. The Rust fixed-point -solver now follows that ordering for recovered type-1 and type-2 objects. +Post-audit raw-stack correction: the collision scan at `1000:c79c` stores each +later, nearer candidate in the next 0x34-byte stack slot, but response code +continues to read the first slot at `SS:...d8a2`. The first detected object ID +therefore wins even when a later candidate has smaller surface distance. The +readable C harness and Rust scanner preserve this binary quirk. `1000:b476` decodes the physical bank flags in `OBJECTS.tsv`. Flags `0x208a` on records 90-104 deactivate five complete three-line groups; clearing all five diff --git a/original/reconstructed/tdkpin_physics.c b/original/reconstructed/tdkpin_physics.c index 655e039..b3e4d0e 100644 --- a/original/reconstructed/tdkpin_physics.c +++ b/original/reconstructed/tdkpin_physics.c @@ -1081,6 +1081,9 @@ static void integrate_one_ball( candidates, &candidate_count); if (collided) { + /* Raw 1000:c79c stores each later, nearer candidate at the next + * 0x34-byte stack slot but resolves the fixed first slot at + * SS:...d8a2. Record order therefore wins over closest distance. */ apply_collision_response( caller_bp, window, diff --git a/original/reconstructed/tests/test_physics.c b/original/reconstructed/tests/test_physics.c index cb9a58c..e4a076b 100644 --- a/original/reconstructed/tests/test_physics.c +++ b/original/reconstructed/tests/test_physics.c @@ -336,6 +336,22 @@ static void test_circle_and_segment_collisions(void) win16_far_add_offset(g_window, 0x0baa)) == -1000); assert(g_event_calls == 1 && g_last_event_flags == 0x0020); assert(g_score_total == 100); + + prepare_fixture(); + set_ball(100000, 100000, 0, 1000); + segment = base_record(2); + segment.point1_x_milli = 50000; + segment.point1_y_milli = 101000; + segment.point2_x_milli = 150000; + segment.point2_y_milli = 101000; + write_record(1, &segment); + segment.point1_y_milli = 100500; + segment.point2_y_milli = 100500; + segment.response_normal = borland_i32_to_real48(1); + write_record(2, &segment); + tdkpin_simulate_ball_and_dispatch_collision(0x0300); + assert((int32_t)win16_read_u32( + win16_far_add_offset(g_window, 0x0bae)) == 0); } static void test_capture_and_trigger_records(void) diff --git a/tdkpin-rs/CHANGELOG.md b/tdkpin-rs/CHANGELOG.md index b143ab1..5ab5465 100644 --- a/tdkpin-rs/CHANGELOG.md +++ b/tdkpin-rs/CHANGELOG.md @@ -10,6 +10,10 @@ and this project adheres to ### Fixed +- Scan static, capture, trigger, magnetic, and dynamic record ranges in exact + ID order with a separately tracked prediction. Preserve the raw scanner's + first-detected-candidate quirk even when a later record is geometrically + nearer, plus type-3 and dynamic-record broadphase behavior. - Run type-3/type-4 processing before response and position publication: captures now test the old position, contacted type-3 rims contribute radial candidates, triggers mutate the live motion first, and sensor IDs execute in diff --git a/tdkpin-rs/RECONSTRUCTION.md b/tdkpin-rs/RECONSTRUCTION.md index d7511cc..28f993e 100644 --- a/tdkpin-rs/RECONSTRUCTION.md +++ b/tdkpin-rs/RECONSTRUCTION.md @@ -22,9 +22,9 @@ implementation. | Artwork | Exact | All 34 custom DIB images, three standard bitmaps, icon, and palette derivatives are preserved in `assets/original/`. The game uses the original 640x460 table, loading, help, ball, wheel, robot, plunger, media, and diamond frames. | | Audio | Exact samples and recovered dispatch | All 16 mono PCM WAV resources are embedded unchanged. Playback is emitted at the reconstructed call sites, including multi-sound bank completions and nudge-then-tilt ordering. WAV 2022 is loaded by the original generic resource loop but has no playback call and is therefore never played by Rust. | | Help and languages | Exact | Original resource images 1001-1005 are displayed directly. | -| Playfield collision layout | Recovered | All 109 active type-2 line objects and 40 static active type-1 circles are transcribed from the original 175-object registration table. The registration routine converts its sideways inputs with `screen = (y, x - 20)` and accumulates explicitly relative objects. Every static record retains its `+0x49` layer mask; the scanner selects layer 1 below the old Y value 250,000 and layer 2 at or above it, while mask 3 records remain shared. Before detection, the raw `1000:9b69` predicted position must lie in the record bounds derived with the registered five-pixel ball margin. Type-2 records retain every recovered Real48 normal/tangent response pair and registered one-sided orientation. Type-1 records retain their swept-circle radius, radial rebound, tangent coupling, and bumper kick. Detection retains unresolved normal/material candidates so later scan-time motion changes can participate in the selected response. Each flipper uses its exact two line records plus moving tip circle in both positions. Moving-flipper contact ports `1000:7ed9` rather than fitting live samples: delta-specific pivots/edges, integer cross gates, radial/penetration calculations, response-record gain, and position/velocity publication are tested against all four C harness directions and the raised release geometry. Object 174 is overwritten with the live first ball and Rust handles its ball-to-ball role directly. | +| Playfield collision layout | Recovered | All 109 active type-2 line objects and 40 static active type-1 circles are transcribed from the original 175-object registration table. The registration routine converts its sideways inputs with `screen = (y, x - 20)` and accumulates explicitly relative objects. Every static record retains its `+0x49` layer mask; the scanner selects layer 1 below the old Y value 250,000 and layer 2 at or above it, while mask 3 records remain shared. Before detection, the raw `1000:9b69` predicted position must lie in the record bounds derived with the registered five-pixel ball margin. Type-2 records retain every recovered Real48 normal/tangent response pair and registered one-sided orientation. Type-1 records retain their swept-circle radius, radial rebound, tangent coupling, and bumper kick. Detection retains unresolved normal/material candidates so later scan-time motion changes can participate in the selected response. Raw stack slot `SS:...d8a2` makes the first detected record ID win; later nearer candidates are stored but never applied, and both C/Rust have two-candidate regression coverage for this quirk. Each flipper uses its exact two line records plus moving tip circle in both positions. Moving-flipper contact ports `1000:7ed9` rather than fitting live samples: delta-specific pivots/edges, integer cross gates, radial/penetration calculations, response-record gain, and position/velocity publication are tested against all four C harness directions and the raised release geometry. Object 174 is overwritten with the live first ball and Rust handles its ball-to-ball role directly. | | Ball launcher and nudge input | Recovered | The initial 32-bit fixed-point coordinates decode to `(325, 413)` in the right shooter lane. Each Down keydown subtracts `15*50 = 750` millipixels, release subtracts another `15*100 = 1500`, and the result follows the recovered randomized `-3800` lower and `-2280` weak upper clamp branches. The ten decoration frames use the same strict 750-millipixel thresholds. Left Shift and keypad 3 apply their directional `(50-Random(20))*15` impulses; Space uses the recovered Real48 horizontal factor and `(60-Random(20))*15` vertical impulse. With two balls, the key path still consumes those active-window draws, then applies its separately recovered fixed/shared random slot impulse to both saved velocities. Each nudge adds 25 to the wrapping 16-bit tilt counter, compares it with `30+Random(10)`, and the detail timer decrements a nonzero counter once per callback. | -| Physics arithmetic | Recovered Real48 core | Production movement uses the original 10 ms millipixel substep, `+15` vertical acceleration, Real48 `3800/speed` clamp, type-2 distance/cross gates, type-1 midpoint normal, surface-distance candidate ordering, persistent Real48 spin, and the common impulse response. Negative auxiliary thresholds and kick coefficients are retained for bumpers 51-53 and lines 55/74/107, including weak-hit score behavior, unscored-rail WAVE 2019, and tilt suppression. Type-3 reads the pre-movement coordinate for pull/hold and contributes its recovered radial rim candidate when a nonzero contact is outside the deep zone. Type-4 randomization mutates motion before the selected candidate is resolved and before position publication; sensor groups execute in record order 89, 129-133, 140-152 without Hold/Complete aborting later records. Detail callbacks freeze their starting ball count, run all 5/4/3/2/1 substeps for slot 1 before slot 2, stop a slot after its first collision/reset/removal, and apply effect-seven spawn requests after the current batch. Dynamic records 174/175 transfer normal impulse to the other ball before applying `normal_velocity-1000` to the moving ball; effect seven spawns record/slot 2 from record 148 coordinates `(17000,23000)` with exact `(0,3040)` velocity. Both slots traverse the same type-3/type-4 dispatcher. Capture age is saved per slot, contact words retain ball ownership, a completed multiball capture removes exactly that slot and promotes the survivor when needed, and effect seven's argument-2 guard prevents a third ball. The original Borland seed update, high-word `Random(n)`, and normalized Real48 random register result drive launcher variation, effects, claw terminals, magnetic fields, and trigger response. Type-4 triggers retain a shared transient entry flag; type-3 captures retain per-player 16-bit contact words, deep-inside pull/hold progression to age 300, first-contact sound, and `99`/`2` completion sentinels. Zero-spin C harnesses and retained-spin Wine probes are tested separately rather than conflated. | +| Physics arithmetic | Recovered Real48 core | Production movement uses the original 10 ms millipixel substep, `+15` vertical acceleration, Real48 `3800/speed` clamp, type-2 distance/cross gates, type-1 midpoint normal, first-detected candidate selection, persistent Real48 spin, and the common impulse response. The scan follows record chunks 1-5, 6, 7-88, 89, 90-128, 129-133, 134-139, 140-152, 153-154, 155-173, and dynamic 174/175 while carrying prediction separately from mutable motion. Negative auxiliary thresholds and kick coefficients are retained for bumpers 51-53 and lines 55/74/107, including weak-hit score behavior, unscored-rail WAVE 2019, and tilt suppression. Type-3 reads the pre-movement coordinate for pull/hold, obeys its prediction broadphase, and contributes its recovered radial rim candidate when a nonzero contact is outside the deep zone. Type-4 randomization mutates motion before the selected candidate is resolved and before position publication; only rectangular magnetic records rewrite prediction. Detail callbacks freeze their starting ball count, run all 5/4/3/2/1 substeps for slot 1 before slot 2, stop a slot after its first collision/reset/removal, and apply effect-seven spawn requests after the current batch. Dynamic records 174/175 use their 21-pixel prediction bounds, transfer normal impulse to the other ball, then apply `normal_velocity-1000` to the moving ball; effect seven spawns record/slot 2 from record 148 coordinates `(17000,23000)` with exact `(0,3040)` velocity. Both slots traverse the same type-3/type-4 dispatcher. Capture age is saved per slot, contact words retain ball ownership, a completed multiball capture removes exactly that slot and promotes the survivor when needed, and effect seven's argument-2 guard prevents a third ball. The original Borland seed update, high-word `Random(n)`, and normalized Real48 random register result drive launcher variation, effects, claw terminals, magnetic fields, and trigger response. Type-4 triggers retain a shared transient entry flag; type-3 captures retain per-player 16-bit contact words, deep-inside pull/hold progression to age 300, first-contact sound, and `99`/`2` completion sentinels. Zero-spin C harnesses and retained-spin Wine probes are tested separately rather than conflated. | | Rules | Recovered gameplay paths | Player count, controls, the five three-line bumper-value groups, four three-line TDK-diamond groups, five doubling-value lock holes, wheel-reset target, seven-way effect selector/consumer including multiball, permanent double scoring, and four exact media/extra-ball thresholds follow original help/code paths, globals, and object flags. The ninth diamond pays the original 24,464 completion value; the following completed bank enables double scoring, and later completions add 100,000 to the per-player secondary score. Bumpers 51-53 and targets 140-147/150-152 use the original 5/20/10 active-callback countdowns and exact overlay-A render rectangles. Record 121 runs the six-callback DAT600 target rotation with exact 91x90 frames/target points and rotates the five contact/item values at state 6. Completing all five lock holes suspends physics for the full 281-callback panel animation, clears contact/item state at the recovered boundaries, and uses the exact WAVE 2013/2012/stop sequence. Turn changes mirror the original save/load of all 175 collision record states: wheel/top targets, active/contact slots, selected effect, and multiball readiness remain attached to their player. Claw contact and all initially active type-4 targets use recovered records. The top three targets score 500 each and independently enable the left, center, or right magnetic field record. Each rectangular field requires the previous position inside, applies its Real48/random pull, and deactivates when raw `1000:9b69` finds the resulting `07db/07df` prediction outside any edge. The claw state machine and release table have live differential coverage for all four random terminals. | | Numeric scoring | Recovered gameplay values | Static scores come from the initialized 175-object ledger. Dynamic bumper progression, target-bank completion, diamond awards, 10k-160k lock bonuses, 310k transfer, six effect values, multiball mode, and all four media thresholds are transcribed from `1000:b476`, `1000:c4e1`, `1000:bc36`, and live state probes. Lock and effect awards share the original per-player secondary score and display multiplier; the fifth hole transfers and clears it, increments the multiplier, and grants the recovered ball award. Score mutation uses the original 32-bit wrapping behavior, and each add operation can advance at most one media threshold. | | High scores | Recovered visible flow; portable storage | The original 276-byte table is decoded as ten `IWIK`-XOR-obfuscated little-endian scores plus ten 22-byte names. Each player is checked immediately when their own last ball is lost; qualifying scores use the original signed-high/unsigned-low comparison and a `TDK Pinball Player`-prefilled name screen before the table is shown and play resumes. Persisted updates use portable JSON rather than rewriting the Win16 file. | diff --git a/tdkpin-rs/src/game.rs b/tdkpin-rs/src/game.rs index 0b9edbe..a96dcb1 100644 --- a/tdkpin-rs/src/game.rs +++ b/tdkpin-rs/src/game.rs @@ -5,8 +5,8 @@ use crate::{ original_physics::{ CollisionMaterial, CollisionResponse, GRAVITY_MILLI_PER_STEP, MAXIMUM_SPEED_MILLI_PER_STEP, MilliVec, STEP_SECONDS, StaticCollisionCandidate, - ball_collision_response, capture_collision_candidate, circle_collision_candidate, - line_collision_candidate, milli_distance, path_intersects_circle, + ball_collision_response, capture_collision_candidate, circle_collision_candidate_at, + line_collision_candidate_at, milli_distance, path_intersects_circle, }, real48::Real48, table::{ @@ -225,7 +225,15 @@ enum BallAction { #[derive(Clone, Copy, Debug)] struct SensorScanResult { action: BallAction, - capture_candidate: Option<(u8, StaticCollisionCandidate)>, +} + +fn retain_first_collision( + best: &mut Option<(u8, bool, StaticCollisionCandidate)>, + candidate: (u8, bool, StaticCollisionCandidate), +) { + if best.is_none() { + *best = Some(candidate); + } } #[derive(Clone, Copy, Debug)] @@ -679,41 +687,32 @@ impl Game { let mut velocity = MilliVec::from_velocity_per_second(ball.velocity); velocity.y += GRAVITY_MILLI_PER_STEP; velocity.clamp_speed(MAXIMUM_SPEED_MILLI_PER_STEP); - self.apply_magnetic_fields(old_position, &mut velocity); - let movement_velocity = velocity; - let mut best_static = self.find_static_collision_candidate(old_position, velocity); - ball.velocity = velocity.to_velocity_per_second(); - let scan = self.check_sensor_objects_for_ball( + let (best_static, scan, predicted) = self.scan_ordered_records_for_ball( &mut ball, 1, ball_count, old_position, - movement_velocity, + &mut velocity, events, ); - if let Some((id, candidate)) = scan.capture_candidate - && best_static.is_none_or(|(_, _, closest)| { - candidate.surface_distance <= closest.surface_distance - }) - { - best_static = Some((id, false, candidate)); - } - velocity = MilliVec::from_velocity_per_second(ball.velocity); let mut best_collision = best_static .map(|(id, is_wall, candidate)| (id, is_wall, candidate.resolve(velocity, ball.spin))); let mut transferred_secondary_velocity = None; if let Some(secondary) = initial_secondary { + let other_position = MilliVec::from_position(secondary.position); let response = ball_collision_response( old_position, velocity, ball.spin, - MilliVec::from_position(secondary.position), + other_position, MilliVec::from_velocity_per_second(secondary.velocity), ); - if let Some(response) = response - && best_collision.is_none_or(|(_, _, closest)| { - response.surface_distance <= closest.surface_distance - }) + if predicted.x >= other_position.x.wrapping_sub(21_000) + && predicted.x <= other_position.x.wrapping_add(21_000) + && predicted.y >= other_position.y.wrapping_sub(21_000) + && predicted.y <= other_position.y.wrapping_add(21_000) + && let Some(response) = response + && best_collision.is_none() { transferred_secondary_velocity = Some(response.other_velocity); best_collision = Some(( @@ -815,15 +814,166 @@ impl Game { collided } - fn find_static_collision_candidate( + fn retain_static_range( &self, old_position: MilliVec, + predicted: MilliVec, velocity: MilliVec, + record_ids: std::ops::RangeInclusive, + best: &mut Option<(u8, bool, StaticCollisionCandidate)>, + ) { + if let Some(candidate) = self.find_static_collision_candidate_in_range( + old_position, + predicted, + velocity, + record_ids, + ) { + retain_first_collision(best, candidate); + } + } + + #[allow(clippy::too_many_arguments, clippy::too_many_lines)] + fn scan_ordered_records_for_ball( + &mut self, + ball: &mut Ball, + ball_number: u16, + ball_count: u16, + old_position: MilliVec, + velocity: &mut MilliVec, + events: &mut Vec, + ) -> ( + Option<(u8, bool, StaticCollisionCandidate)>, + SensorScanResult, + MilliVec, + ) { + let mut predicted = old_position.add(*velocity); + let mut best = None; + let mut capture_candidate = None; + let mut action = BallAction::Keep; + + self.retain_static_range(old_position, predicted, *velocity, 1..=5, &mut best); + if self.apply_magnetic_record(6, old_position, velocity) { + predicted = old_position.add(*velocity); + } + self.retain_static_range(old_position, predicted, *velocity, 7..=88, &mut best); + + if old_position.y < 250_000 && !self.claw.active { + ball.velocity = velocity.to_velocity_per_second(); + match self.capture_record_step( + ball, + ball_number, + ball_count, + 89, + CLAW_TRIGGER_CENTER, + CLAW_TRIGGER_RADIUS, + old_position, + predicted, + &mut capture_candidate, + events, + ) { + CaptureStep::Complete if ball_count == 1 => { + let terminal_frame = self.next_claw_terminal_frame(); + self.begin_claw_capture_after_hold(ball, terminal_frame, events); + action = BallAction::Suspend; + } + CaptureStep::Complete => action = BallAction::Remove, + CaptureStep::Outside | CaptureStep::Holding => {} + } + *velocity = MilliVec::from_velocity_per_second(ball.velocity); + } + + self.retain_static_range(old_position, predicted, *velocity, 90..=128, &mut best); + if old_position.y < 250_000 { + ball.velocity = velocity.to_velocity_per_second(); + if let Some(completed_action) = self.check_lock_holes( + ball, + ball_number, + ball_count, + old_position, + predicted, + &mut capture_candidate, + events, + ) { + action = completed_action; + } + *velocity = MilliVec::from_velocity_per_second(ball.velocity); + } + + self.retain_static_range(old_position, predicted, *velocity, 134..=139, &mut best); + if old_position.y < 250_000 { + ball.velocity = velocity.to_velocity_per_second(); + let predicted_velocity = MilliVec { + x: predicted.x.wrapping_sub(old_position.x), + y: predicted.y.wrapping_sub(old_position.y), + }; + self.check_target_sensors( + ball, + old_position, + predicted_velocity, + 140..=147, + events, + ); + if let Some(completed_action) = self.check_wheel_reset( + ball, + ball_number, + ball_count, + old_position, + predicted, + &mut capture_candidate, + events, + ) { + action = completed_action; + } + self.check_effect_sensor( + ball, + ball_number, + old_position, + predicted_velocity, + events, + ); + self.check_target_sensors( + ball, + old_position, + predicted_velocity, + 150..=152, + events, + ); + *velocity = MilliVec::from_velocity_per_second(ball.velocity); + } + + if self.apply_magnetic_record(153, old_position, velocity) { + predicted = old_position.add(*velocity); + } + if self.apply_magnetic_record(154, old_position, velocity) { + predicted = old_position.add(*velocity); + } + self.retain_static_range(old_position, predicted, *velocity, 155..=173, &mut best); + + if let Some((id, candidate)) = capture_candidate + && best.is_none_or(|(static_id, _, _)| id < static_id) + { + best = Some((id, false, candidate)); + } + ball.velocity = velocity.to_velocity_per_second(); + ( + best, + SensorScanResult { + action, + }, + predicted, + ) + } + + fn find_static_collision_candidate_in_range( + &self, + old_position: MilliVec, + predicted: MilliVec, + velocity: MilliVec, + record_ids: std::ops::RangeInclusive, ) -> Option<(u8, bool, StaticCollisionCandidate)> { let mut best = None; let layer = if old_position.y < 250_000 { 0x01 } else { 0x02 }; - let predicted = old_position.add(velocity); - for object_id in 1..=175 { + for object_id in record_ids { if !self.object_active[usize::from(object_id)] || self.claw.active && (12..=20).contains(&object_id) { @@ -856,16 +1006,15 @@ impl Game { f64::from(wall.response_kick), ) }; - if let Some(candidate) = line_collision_candidate( + if let Some(candidate) = line_collision_candidate_at( old_position, + predicted, velocity, segment.start, segment.end, material, - ) && best.is_none_or(|(_, _, closest): (u8, bool, StaticCollisionCandidate)| { - candidate.surface_distance <= closest.surface_distance - }) { - best = Some((wall.id, true, candidate)); + ) { + retain_first_collision(&mut best, (wall.id, true, candidate)); } } let circle = PASSIVE_CIRCLES @@ -885,8 +1034,9 @@ impl Game { && predicted.y >= center.y.wrapping_sub(margin) && predicted.y <= center.y.wrapping_add(margin) } - && let Some(candidate) = circle_collision_candidate( + && let Some(candidate) = circle_collision_candidate_at( old_position, + predicted, velocity, self.live_circle_center(circle.id, circle.center), circle.contact_radius, @@ -900,16 +1050,28 @@ impl Game { }, ), ) - && best.is_none_or(|(_, _, closest)| { - candidate.surface_distance <= closest.surface_distance - }) + && best.is_none() { - best = Some((circle.id, false, candidate)); + retain_first_collision(&mut best, (circle.id, false, candidate)); } } best } + #[cfg(test)] + fn find_static_collision_candidate( + &self, + old_position: MilliVec, + velocity: MilliVec, + ) -> Option<(u8, bool, StaticCollisionCandidate)> { + self.find_static_collision_candidate_in_range( + old_position, + old_position.add(velocity), + velocity, + 1..=175, + ) + } + fn advance_secondary_ball(&mut self, events: &mut Vec) -> bool { self.advance_secondary_ball_slot(events, true) } @@ -929,41 +1091,32 @@ impl Game { let mut velocity = MilliVec::from_velocity_per_second(ball.velocity); velocity.y += GRAVITY_MILLI_PER_STEP; velocity.clamp_speed(MAXIMUM_SPEED_MILLI_PER_STEP); - self.apply_magnetic_fields(old_position, &mut velocity); - let movement_velocity = velocity; - let mut best_static = self.find_static_collision_candidate(old_position, velocity); - ball.velocity = velocity.to_velocity_per_second(); - let scan = self.check_sensor_objects_for_ball( + let (best_static, scan, predicted) = self.scan_ordered_records_for_ball( &mut ball, 2, 2, old_position, - movement_velocity, + &mut velocity, events, ); - if let Some((id, candidate)) = scan.capture_candidate - && best_static.is_none_or(|(_, _, closest)| { - candidate.surface_distance <= closest.surface_distance - }) - { - best_static = Some((id, false, candidate)); - } - velocity = MilliVec::from_velocity_per_second(ball.velocity); let mut best_collision = best_static .map(|(id, is_wall, candidate)| (id, is_wall, candidate.resolve(velocity, ball.spin))); let mut transferred_primary_velocity = None; + let other_position = MilliVec::from_position(primary_position); if primary_slot_active + && predicted.x >= other_position.x.wrapping_sub(21_000) + && predicted.x <= other_position.x.wrapping_add(21_000) + && predicted.y >= other_position.y.wrapping_sub(21_000) + && predicted.y <= other_position.y.wrapping_add(21_000) && let Some(response) = ball_collision_response( old_position, velocity, ball.spin, - MilliVec::from_position(primary_position), + other_position, MilliVec::from_velocity_per_second(primary_velocity), ) - && best_collision.is_none_or(|(_, _, closest)| { - response.surface_distance <= closest.surface_distance - }) + && best_collision.is_none() { transferred_primary_velocity = Some(response.other_velocity); best_collision = Some(( @@ -1153,6 +1306,7 @@ impl Game { scan.action } + #[cfg(test)] fn check_sensor_objects_for_ball( &mut self, ball: &mut Ball, @@ -1164,10 +1318,10 @@ impl Game { ) -> SensorScanResult { let mut capture_candidate = None; let mut action = BallAction::Keep; + let predicted_position = old_position.add(movement_velocity); if old_position.y >= 250_000 { return SensorScanResult { action: BallAction::Keep, - capture_candidate, }; } if !self.claw.active { @@ -1179,6 +1333,7 @@ impl Game { CLAW_TRIGGER_CENTER, CLAW_TRIGGER_RADIUS, old_position, + predicted_position, &mut capture_candidate, events, ) { @@ -1201,6 +1356,7 @@ impl Game { ball_number, ball_count, old_position, + predicted_position, &mut capture_candidate, events, ) @@ -1220,6 +1376,7 @@ impl Game { ball_number, ball_count, old_position, + predicted_position, &mut capture_candidate, events, ) @@ -1242,7 +1399,6 @@ impl Game { ); SensorScanResult { action, - capture_candidate, } } @@ -1256,6 +1412,7 @@ impl Game { center: Vec2, radius: f32, previous_position: MilliVec, + predicted_position: MilliVec, best_capture: &mut Option<(u8, StaticCollisionCandidate)>, events: &mut Vec, ) -> CaptureStep { @@ -1264,6 +1421,14 @@ impl Game { let center = MilliVec::from_position(center_view); let radius_view = radius; let radius = (radius_view * 1_000.0).round() as i32; + let broadphase_margin = MilliVec::from_position(vec2(radius_view + 5.0, 0.0)).x; + if predicted_position.x < center.x.wrapping_sub(broadphase_margin) + || predicted_position.x > center.x.wrapping_add(broadphase_margin) + || predicted_position.y < center.y.wrapping_sub(broadphase_margin) + || predicted_position.y > center.y.wrapping_add(broadphase_margin) + { + return CaptureStep::Outside; + } let dx = center.x.wrapping_sub(current_position.x); let dy = center .y @@ -1340,21 +1505,21 @@ impl Game { radius_view, CollisionMaterial::line(0.6, 0.0), ) - && best_capture.is_none_or(|(_, closest)| { - candidate.surface_distance <= closest.surface_distance - }) + && best_capture.is_none() { *best_capture = Some((record_id, candidate)); } CaptureStep::Outside } + #[allow(clippy::too_many_arguments)] fn check_lock_holes( &mut self, ball: &mut Ball, ball_number: u16, ball_count: u16, old_position: MilliVec, + predicted_position: MilliVec, best_capture: &mut Option<(u8, StaticCollisionCandidate)>, events: &mut Vec, ) -> Option { @@ -1367,6 +1532,7 @@ impl Game { sensor.center, sensor.radius, old_position, + predicted_position, best_capture, events, ) { @@ -1397,12 +1563,14 @@ impl Game { None } + #[allow(clippy::too_many_arguments)] fn check_wheel_reset( &mut self, ball: &mut Ball, ball_number: u16, ball_count: u16, old_position: MilliVec, + predicted_position: MilliVec, best_capture: &mut Option<(u8, StaticCollisionCandidate)>, events: &mut Vec, ) -> Option { @@ -1414,6 +1582,7 @@ impl Game { WHEEL_RESET_SENSOR.center, WHEEL_RESET_SENSOR.radius, old_position, + predicted_position, best_capture, events, ) { @@ -1546,44 +1715,57 @@ impl Game { self.launcher_velocity_milli = 0; } + #[cfg(test)] fn apply_magnetic_fields(&mut self, old_position: MilliVec, velocity: &mut MilliVec) { - for (object_id, min_x, min_y, max_x, max_y) in [ - (6, 143_000, 421_000, 169_000, 452_000), - (153, 1_000, 315_000, 32_000, 389_000), - (154, 278_000, 315_000, 312_000, 387_000), - ] { - if !self.object_active[object_id] { - continue; - } - if old_position.x < min_x - || old_position.x > max_x - || old_position.y < min_y - || old_position.y > max_y - { - continue; - } - let damping = Real48::from_bytes([0x80, 0x66, 0x66, 0x66, 0x66, 0x66]); - velocity.x = Real48::from_i32(velocity.x).multiply(damping).round_i32(); - let vertical_factor = Real48::from_i32(1).subtract( - self.random - .real48() - .multiply(Real48::from_bytes([0x7f, 0x9a, 0x99, 0x99, 0x99, 0x19])), - ); - velocity.y = Real48::from_i32(MAXIMUM_SPEED_MILLI_PER_STEP) - .multiply(vertical_factor) - .round_i32() - .wrapping_neg(); - let predicted = old_position.add(*velocity); - if predicted.x < min_x - || predicted.x > max_x - || predicted.y < min_y - || predicted.y > max_y - { - self.object_active[object_id] = false; - } + for object_id in [6, 153, 154] { + self.apply_magnetic_record(object_id, old_position, velocity); } } + fn apply_magnetic_record( + &mut self, + object_id: usize, + old_position: MilliVec, + velocity: &mut MilliVec, + ) -> bool { + if self.tilted || !self.object_active[object_id] { + return false; + } + let (min_x, min_y, max_x, max_y) = match object_id { + 6 => (143_000, 421_000, 169_000, 452_000), + 153 => (1_000, 315_000, 32_000, 389_000), + 154 => (278_000, 315_000, 312_000, 387_000), + _ => unreachable!("only the three rectangular type-four records are magnetic"), + }; + if old_position.x < min_x + || old_position.x > max_x + || old_position.y < min_y + || old_position.y > max_y + { + return false; + } + let damping = Real48::from_bytes([0x80, 0x66, 0x66, 0x66, 0x66, 0x66]); + velocity.x = Real48::from_i32(velocity.x).multiply(damping).round_i32(); + let vertical_factor = Real48::from_i32(1).subtract( + self.random + .real48() + .multiply(Real48::from_bytes([0x7f, 0x9a, 0x99, 0x99, 0x99, 0x19])), + ); + velocity.y = Real48::from_i32(MAXIMUM_SPEED_MILLI_PER_STEP) + .multiply(vertical_factor) + .round_i32() + .wrapping_neg(); + let predicted = old_position.add(*velocity); + if predicted.x < min_x + || predicted.x > max_x + || predicted.y < min_y + || predicted.y > max_y + { + self.object_active[object_id] = false; + } + true + } + pub fn magnetic_field_active(&self, object_id: usize) -> bool { debug_assert!([6, 153, 154].contains(&object_id)); self.object_active[object_id] @@ -1882,6 +2064,7 @@ mod tests { ) -> CaptureStep { let mut ball = game.ball; let mut capture_candidate = None; + let predicted_position = previous_position.add(MilliVec::from_velocity_per_second(ball.velocity)); let result = game.capture_record_step( &mut ball, 1, @@ -1890,6 +2073,7 @@ mod tests { center, radius, previous_position, + predicted_position, &mut capture_candidate, events, ); @@ -2544,6 +2728,41 @@ mod tests { ); } + #[test] + fn first_detected_record_wins_even_when_a_later_candidate_is_nearer() { + let old = MilliVec::default(); + let velocity = MilliVec { x: 10_000, y: 0 }; + let predicted = old.add(velocity); + let material = CollisionMaterial::line(0.6, 0.1); + let first = line_collision_candidate_at( + old, + predicted, + velocity, + vec2(8.0, 1.0), + vec2(8.0, -1.0), + material, + ) + .expect("the first record must detect the farther rail"); + let later = line_collision_candidate_at( + old, + predicted, + velocity, + vec2(2.0, 1.0), + vec2(2.0, -1.0), + material, + ) + .expect("the later record must detect the nearer rail"); + assert!(later.surface_distance < first.surface_distance); + let mut retained = None; + + retain_first_collision(&mut retained, (10, true, first)); + retain_first_collision(&mut retained, (20, true, later)); + + let retained = retained.expect("one candidate must remain"); + assert_eq!(retained.0, 10); + assert_eq!(retained.2.surface_distance, 8_000); + } + #[test] fn bumper_base_score_and_kick_require_the_recovered_speed_threshold() { let mut weak = Game::new(1); @@ -3112,6 +3331,60 @@ mod tests { assert_eq!(exiting_sideways.x, -1_800); assert!(!game.object_active[153]); + + game.object_active[153] = true; + game.tilted = true; + let tilted_seed = game.random.seed(); + let mut tilted_velocity = MilliVec { x: 200, y: 300 }; + game.apply_magnetic_fields( + MilliVec { + x: 15_000, + y: 350_000, + }, + &mut tilted_velocity, + ); + assert_eq!(tilted_velocity, MilliVec { x: 200, y: 300 }); + assert_eq!(game.random.seed(), tilted_seed); + assert!(game.object_active[153]); + } + + #[test] + fn record_six_mutates_motion_after_earlier_candidate_detection() { + let mut game = Game::new_with_seed(1, 7); + game.object_active.fill(false); + game.object_active[5] = true; + game.object_active[6] = true; + game.ball.in_launcher = false; + game.ball.position = vec2(149.0, 430.0); + game.ball.velocity = MilliVec { x: -2_000, y: 0 }.to_velocity_per_second(); + let old_position = MilliVec::from_position(game.ball.position); + + let mut expected_game = game.clone(); + let mut expected_motion = MilliVec { x: -2_000, y: 15 }; + let candidate = expected_game + .find_static_collision_candidate_in_range( + old_position, + old_position.add(expected_motion), + expected_motion, + 1..=5, + ) + .expect("record five must be detected before record six"); + assert_eq!(candidate.0, 5); + assert!(expected_game.apply_magnetic_record(6, old_position, &mut expected_motion)); + let expected_response = candidate + .2 + .resolve(expected_motion, expected_game.ball.spin); + let mut expected_velocity = expected_response.velocity; + expected_velocity.clamp_speed(MAXIMUM_SPEED_MILLI_PER_STEP); + + assert!(game.fixed_update(STEP_SECONDS, &mut Vec::new())); + + assert_eq!(game.last_collision_id, Some(5)); + assert_eq!( + MilliVec::from_velocity_per_second(game.ball.velocity), + expected_velocity + ); + assert_eq!(game.random.seed(), expected_game.random.seed()); } #[test] @@ -3269,6 +3542,22 @@ mod tests { ); } + #[test] + fn type_three_broadphase_skip_preserves_contact_state() { + let sensor = LOCK_HOLES[0]; + let mut game = Game::new(1); + game.object_active.fill(false); + game.object_active[usize::from(sensor.id)] = true; + game.record_contacts[usize::from(sensor.id)] = 1; + game.ball.in_launcher = false; + game.ball.position = sensor.center + vec2(23.0, 0.0); + game.ball.velocity = MilliVec { x: 3_800, y: 0 }.to_velocity_per_second(); + + game.fixed_update(STEP_SECONDS, &mut Vec::new()); + + assert_eq!(game.record_contacts[usize::from(sensor.id)], 1); + } + #[test] fn production_type_four_randomizes_motion_before_position_publication() { let sensor = TARGET_SENSORS diff --git a/tdkpin-rs/src/original_physics.rs b/tdkpin-rs/src/original_physics.rs index 60d6eb2..6c5d18d 100644 --- a/tdkpin-rs/src/original_physics.rs +++ b/tdkpin-rs/src/original_physics.rs @@ -18,6 +18,7 @@ pub struct MilliVec { #[derive(Clone, Copy, Debug)] pub struct CollisionResponse { + #[allow(dead_code)] pub surface_distance: i32, pub velocity: MilliVec, pub spin: Real48, @@ -321,16 +322,34 @@ fn apply_response( } /// Calculate the original type-2 response in the registered segment's basis. +#[cfg(test)] pub fn line_collision_candidate( old_position: MilliVec, velocity: MilliVec, line_start: Vec2, line_end: Vec2, material: CollisionMaterial, +) -> Option { + line_collision_candidate_at( + old_position, + old_position.add(velocity), + velocity, + line_start, + line_end, + material, + ) +} + +pub fn line_collision_candidate_at( + old_position: MilliVec, + predicted_position: MilliVec, + velocity: MilliVec, + line_start: Vec2, + line_end: Vec2, + material: CollisionMaterial, ) -> Option { let start = MilliVec::from_position(line_start); let end = MilliVec::from_position(line_end); - let predicted = old_position.add(velocity); let segment = subtract(end, start); let normal_x = Real48::from_i32(segment.x); let normal_y = Real48::from_i32(segment.y); @@ -359,8 +378,8 @@ pub fn line_collision_candidate( if distance > speed || collision_velocity > 10 || distance.wrapping_sub(10) > collision_velocity.wrapping_abs() - || cross_at_endpoint(start, old_position, predicted) < -10 - || cross_at_endpoint(end, old_position, predicted) > 10 + || cross_at_endpoint(start, old_position, predicted_position) < -10 + || cross_at_endpoint(end, old_position, predicted_position) > 10 { return None; } @@ -410,12 +429,31 @@ pub fn collide_with_line( } /// Calculate the original type-1 circle response for a path entering it. +#[cfg(test)] pub fn circle_collision_candidate( old_position: MilliVec, velocity: MilliVec, center: Vec2, radius: f32, material: CollisionMaterial, +) -> Option { + circle_collision_candidate_at( + old_position, + old_position.add(velocity), + velocity, + center, + radius, + material, + ) +} + +pub fn circle_collision_candidate_at( + old_position: MilliVec, + predicted_position: MilliVec, + velocity: MilliVec, + center: Vec2, + radius: f32, + material: CollisionMaterial, ) -> Option { let center = MilliVec::from_position(center); let radius_milli = (radius * 1_000.0).round() as i32; @@ -425,10 +463,9 @@ pub fn circle_collision_candidate( if surface_distance > speed { return None; } - let predicted = old_position.add(velocity); let middle = MilliVec { - x: old_position.x.wrapping_add(predicted.x) / 2, - y: old_position.y.wrapping_add(predicted.y) / 2, + x: old_position.x.wrapping_add(predicted_position.x) / 2, + y: old_position.y.wrapping_add(predicted_position.y) / 2, }; let normal_x = Real48::from_i32(center.y.wrapping_sub(middle.y)); let normal_y = Real48::from_i32(middle.x.wrapping_sub(center.x));