1use std::{error::Error, fmt};
4
5use bevy_ecs::prelude::Component;
6use sim_engine::{Camera2dError, Vec2};
7
8use crate::{
9 input::{Action, DigitalAxis2d, FixedInput},
10 query::{Query, QuerySingleError},
11 time::FixedTime,
12 visual::{ActiveCamera2d, Transform2d, VisualValueError},
13};
14
15#[derive(Debug, Clone, Copy, PartialEq, Component)]
26#[require(Transform2d)]
27pub struct LinearVelocity2d {
28 velocity: Vec2,
29}
30
31impl LinearVelocity2d {
32 pub fn new(velocity: Vec2) -> Result<Self, LinearVelocity2dError> {
34 validate_velocity(velocity)?;
35 Ok(Self { velocity })
36 }
37
38 pub const fn velocity(&self) -> Vec2 {
40 self.velocity
41 }
42
43 pub fn set_velocity(&mut self, velocity: Vec2) -> Result<(), LinearVelocity2dError> {
47 validate_velocity(velocity)?;
48 self.velocity = velocity;
49 Ok(())
50 }
51}
52
53impl Default for LinearVelocity2d {
54 fn default() -> Self {
55 Self {
56 velocity: Vec2::ZERO,
57 }
58 }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq)]
63pub enum LinearVelocity2dError {
64 InvalidVelocity {
66 value: Vec2,
68 },
69}
70
71impl fmt::Display for LinearVelocity2dError {
72 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
73 match self {
74 Self::InvalidVelocity { value } => {
75 write!(
76 formatter,
77 "linear velocity must be finite, but received {value:?}"
78 )
79 }
80 }
81 }
82}
83
84impl Error for LinearVelocity2dError {}
85
86#[derive(Debug, Clone, Copy, PartialEq, Component)]
99#[require(LinearVelocity2d)]
100pub struct LinearAcceleration2d {
101 acceleration: Vec2,
102}
103
104impl LinearAcceleration2d {
105 pub fn new(acceleration: Vec2) -> Result<Self, LinearAcceleration2dError> {
107 validate_acceleration(acceleration)?;
108 Ok(Self { acceleration })
109 }
110
111 pub const fn acceleration(&self) -> Vec2 {
113 self.acceleration
114 }
115
116 pub fn set_acceleration(
120 &mut self,
121 acceleration: Vec2,
122 ) -> Result<(), LinearAcceleration2dError> {
123 validate_acceleration(acceleration)?;
124 self.acceleration = acceleration;
125 Ok(())
126 }
127}
128
129impl Default for LinearAcceleration2d {
130 fn default() -> Self {
131 Self {
132 acceleration: Vec2::ZERO,
133 }
134 }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq)]
139pub enum LinearAcceleration2dError {
140 InvalidAcceleration {
142 value: Vec2,
144 },
145}
146
147impl fmt::Display for LinearAcceleration2dError {
148 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
149 match self {
150 Self::InvalidAcceleration { value } => write!(
151 formatter,
152 "linear acceleration must be finite, but received {value:?}"
153 ),
154 }
155 }
156}
157
158impl Error for LinearAcceleration2dError {}
159
160#[derive(Debug, Clone, Copy, PartialEq, Component)]
174#[require(Transform2d)]
175pub struct CameraFollowTarget2d {
176 camera_offset: Vec2,
177}
178
179impl CameraFollowTarget2d {
180 pub fn new(camera_offset: Vec2) -> Result<Self, CameraFollowTarget2dError> {
182 validate_camera_offset(camera_offset)?;
183 Ok(Self { camera_offset })
184 }
185
186 pub const fn camera_offset(&self) -> Vec2 {
188 self.camera_offset
189 }
190
191 pub fn set_camera_offset(
195 &mut self,
196 camera_offset: Vec2,
197 ) -> Result<(), CameraFollowTarget2dError> {
198 validate_camera_offset(camera_offset)?;
199 self.camera_offset = camera_offset;
200 Ok(())
201 }
202}
203
204impl Default for CameraFollowTarget2d {
205 fn default() -> Self {
206 Self {
207 camera_offset: Vec2::ZERO,
208 }
209 }
210}
211
212#[derive(Debug, Clone, Copy, PartialEq)]
214pub enum CameraFollowTarget2dError {
215 InvalidCameraOffset {
217 value: Vec2,
219 },
220}
221
222impl fmt::Display for CameraFollowTarget2dError {
223 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
224 match self {
225 Self::InvalidCameraOffset { value } => write!(
226 formatter,
227 "camera follow offset must be finite, but received {value:?}"
228 ),
229 }
230 }
231}
232
233impl Error for CameraFollowTarget2dError {}
234
235#[derive(Debug, Clone, Copy, PartialEq, Component)]
253#[require(Transform2d)]
254pub struct DigitalMovement2d<A: Action> {
255 axis: DigitalAxis2d<A>,
256 speed: f32,
257}
258
259impl<A: Action> DigitalMovement2d<A> {
260 pub fn new(axis: DigitalAxis2d<A>, speed: f32) -> Result<Self, DigitalMovement2dError> {
262 validate_speed(speed)?;
263 Ok(Self { axis, speed })
264 }
265
266 pub const fn axis(&self) -> DigitalAxis2d<A> {
268 self.axis
269 }
270
271 pub const fn speed(&self) -> f32 {
273 self.speed
274 }
275
276 pub fn set_axis(&mut self, axis: DigitalAxis2d<A>) {
278 self.axis = axis;
279 }
280
281 pub fn set_speed(&mut self, speed: f32) -> Result<(), DigitalMovement2dError> {
285 validate_speed(speed)?;
286 self.speed = speed;
287 Ok(())
288 }
289}
290
291#[derive(Debug, Clone, Copy, PartialEq)]
293pub enum DigitalMovement2dError {
294 InvalidSpeed {
296 value: f32,
298 },
299}
300
301impl fmt::Display for DigitalMovement2dError {
302 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
303 match self {
304 Self::InvalidSpeed { value } => write!(
305 formatter,
306 "digital movement speed must be finite and nonnegative, but received {value}"
307 ),
308 }
309 }
310}
311
312impl Error for DigitalMovement2dError {}
313
314pub(crate) fn integrate_linear_velocity2d(
315 time: FixedTime,
316 mut moving: Query<(&LinearVelocity2d, &mut Transform2d)>,
317) -> Result<(), VisualValueError> {
318 let delta_seconds = time.seconds_f32();
319 for (velocity, mut transform) in &mut moving {
320 transform.translate_by(velocity.velocity * delta_seconds)?;
321 }
322 Ok(())
323}
324
325pub(crate) fn integrate_linear_acceleration2d(
326 time: FixedTime,
327 mut accelerating: Query<(&LinearAcceleration2d, &mut LinearVelocity2d)>,
328) -> Result<(), LinearVelocity2dError> {
329 let delta_seconds = time.seconds_f32();
330 for (acceleration, mut velocity) in &mut accelerating {
331 if acceleration.acceleration == Vec2::ZERO {
332 continue;
333 }
334 let next = velocity.velocity + acceleration.acceleration * delta_seconds;
335 velocity.set_velocity(next)?;
336 }
337 Ok(())
338}
339
340#[derive(Debug)]
341pub(crate) enum CameraFollow2dSystemError {
342 MultipleTargets,
343 InvalidCenter(Camera2dError),
344}
345
346impl fmt::Display for CameraFollow2dSystemError {
347 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
348 match self {
349 Self::MultipleTargets => {
350 formatter.write_str("camera follow has more than one enabled target")
351 }
352 Self::InvalidCenter(error) => write!(formatter, "camera follow failed: {error}"),
353 }
354 }
355}
356
357impl Error for CameraFollow2dSystemError {
358 fn source(&self) -> Option<&(dyn Error + 'static)> {
359 match self {
360 Self::InvalidCenter(error) => Some(error),
361 Self::MultipleTargets => None,
362 }
363 }
364}
365
366pub(crate) fn follow_camera_target2d(
367 targets: Query<(&Transform2d, &CameraFollowTarget2d)>,
368 mut cameras: Query<&mut ActiveCamera2d>,
369) -> Result<(), CameraFollow2dSystemError> {
370 let (transform, target) = match targets.single() {
371 Ok(target) => target,
372 Err(QuerySingleError::NoEntities) => return Ok(()),
373 Err(QuerySingleError::MultipleEntities) => {
374 return Err(CameraFollow2dSystemError::MultipleTargets);
375 }
376 };
377 let Ok(mut camera) = cameras.single_mut() else {
378 return Ok(());
381 };
382 let translation = transform.translation();
383 let center = if target.camera_offset == Vec2::ZERO {
384 translation
385 } else {
386 translation + target.camera_offset
387 };
388 camera
389 .set_center(center)
390 .map_err(CameraFollow2dSystemError::InvalidCenter)
391}
392
393pub(crate) fn integrate_digital_movement2d<A: Action>(
394 input: FixedInput<A>,
395 time: FixedTime,
396 mut moving: Query<(&DigitalMovement2d<A>, &mut Transform2d)>,
397) -> Result<(), VisualValueError> {
398 let delta_seconds = time.seconds_f32();
399 let mut last_axis = None;
403 for (movement, mut transform) in &mut moving {
404 let direction = match last_axis {
405 Some((axis, direction)) if axis == movement.axis => direction,
406 _ => {
407 let direction = input.normalized_digital_axis(movement.axis);
408 last_axis = Some((movement.axis, direction));
409 direction
410 }
411 };
412 if direction == Vec2::ZERO {
413 continue;
414 }
415 transform.translate_by(direction * (movement.speed * delta_seconds))?;
416 }
417 Ok(())
418}
419
420fn validate_velocity(value: Vec2) -> Result<(), LinearVelocity2dError> {
421 value
422 .is_finite()
423 .then_some(())
424 .ok_or(LinearVelocity2dError::InvalidVelocity { value })
425}
426
427fn validate_acceleration(value: Vec2) -> Result<(), LinearAcceleration2dError> {
428 value
429 .is_finite()
430 .then_some(())
431 .ok_or(LinearAcceleration2dError::InvalidAcceleration { value })
432}
433
434fn validate_camera_offset(value: Vec2) -> Result<(), CameraFollowTarget2dError> {
435 value
436 .is_finite()
437 .then_some(())
438 .ok_or(CameraFollowTarget2dError::InvalidCameraOffset { value })
439}
440
441fn validate_speed(value: f32) -> Result<(), DigitalMovement2dError> {
442 (value.is_finite() && value >= 0.0)
443 .then_some(())
444 .ok_or(DigitalMovement2dError::InvalidSpeed { value })
445}
446
447#[cfg(test)]
448mod tests {
449 use super::*;
450
451 #[test]
452 fn velocity_validation_and_mutation_are_atomic_and_bit_exact() {
453 let valid = [
454 Vec2::ZERO,
455 Vec2::new(-0.0, 0.0),
456 Vec2::new(f32::from_bits(1), -f32::from_bits(1)),
457 Vec2::new(12.5, -98.25),
458 Vec2::new(f32::MAX, -f32::MAX),
459 ];
460 for value in valid {
461 let velocity = LinearVelocity2d::new(value).expect("finite velocity should be valid");
462 assert_vec2_bits_eq(velocity.velocity(), value);
463 }
464 assert_vec2_bits_eq(LinearVelocity2d::default().velocity(), Vec2::ZERO);
465
466 let initial = Vec2::new(-0.0, f32::from_bits(1));
467 let mut velocity =
468 LinearVelocity2d::new(initial).expect("initial velocity should be valid");
469 let updated = Vec2::new(-12.5, f32::MAX);
470 velocity
471 .set_velocity(updated)
472 .expect("finite replacement velocity should be valid");
473 assert_vec2_bits_eq(velocity.velocity(), updated);
474 let nan = f32::from_bits(0x7fc0_1234);
475 for value in [
476 Vec2::new(nan, -0.0),
477 Vec2::new(-0.0, f32::INFINITY),
478 Vec2::new(f32::NEG_INFINITY, nan),
479 ] {
480 let error = velocity
481 .set_velocity(value)
482 .expect_err("non-finite velocity should be rejected");
483 match error {
484 LinearVelocity2dError::InvalidVelocity { value: rejected } => {
485 assert_vec2_bits_eq(rejected, value);
486 }
487 }
488 assert_vec2_bits_eq(velocity.velocity(), updated);
489
490 let constructor = LinearVelocity2d::new(value)
491 .expect_err("constructor should reject the same non-finite velocity");
492 match constructor {
493 LinearVelocity2dError::InvalidVelocity { value: rejected } => {
494 assert_vec2_bits_eq(rejected, value);
495 }
496 }
497 }
498 }
499
500 #[test]
501 fn acceleration_validation_and_mutation_are_atomic_and_bit_exact() {
502 let valid = [
503 Vec2::ZERO,
504 Vec2::new(-0.0, 0.0),
505 Vec2::new(f32::from_bits(1), -f32::from_bits(1)),
506 Vec2::new(12.5, -98.25),
507 Vec2::new(f32::MAX, -f32::MAX),
508 ];
509 for value in valid {
510 let acceleration =
511 LinearAcceleration2d::new(value).expect("finite acceleration should be valid");
512 assert_vec2_bits_eq(acceleration.acceleration(), value);
513 }
514 assert_vec2_bits_eq(LinearAcceleration2d::default().acceleration(), Vec2::ZERO);
515
516 let initial = Vec2::new(-0.0, f32::from_bits(1));
517 let mut acceleration =
518 LinearAcceleration2d::new(initial).expect("initial acceleration should be valid");
519 let updated = Vec2::new(-12.5, f32::MAX);
520 acceleration
521 .set_acceleration(updated)
522 .expect("finite replacement acceleration should be valid");
523 assert_vec2_bits_eq(acceleration.acceleration(), updated);
524 let nan = f32::from_bits(0x7fc0_4321);
525 for value in [
526 Vec2::new(nan, -0.0),
527 Vec2::new(-0.0, f32::INFINITY),
528 Vec2::new(f32::NEG_INFINITY, nan),
529 ] {
530 let error = acceleration
531 .set_acceleration(value)
532 .expect_err("non-finite acceleration should be rejected");
533 match error {
534 LinearAcceleration2dError::InvalidAcceleration { value: rejected } => {
535 assert_vec2_bits_eq(rejected, value);
536 }
537 }
538 assert_vec2_bits_eq(acceleration.acceleration(), updated);
539
540 let constructor = LinearAcceleration2d::new(value)
541 .expect_err("constructor should reject the same non-finite acceleration");
542 match constructor {
543 LinearAcceleration2dError::InvalidAcceleration { value: rejected } => {
544 assert_vec2_bits_eq(rejected, value);
545 }
546 }
547 }
548 }
549
550 #[test]
551 fn camera_follow_offset_validation_and_mutation_are_atomic_and_bit_exact() {
552 let valid = [
553 Vec2::ZERO,
554 Vec2::new(-0.0, 0.0),
555 Vec2::new(f32::from_bits(1), -f32::from_bits(1)),
556 Vec2::new(12.5, -98.25),
557 Vec2::new(f32::MAX, -f32::MAX),
558 ];
559 for value in valid {
560 let target =
561 CameraFollowTarget2d::new(value).expect("finite camera offset should be valid");
562 assert_vec2_bits_eq(target.camera_offset(), value);
563 }
564 assert_vec2_bits_eq(CameraFollowTarget2d::default().camera_offset(), Vec2::ZERO);
565
566 let initial = Vec2::new(-0.0, f32::from_bits(1));
567 let mut target =
568 CameraFollowTarget2d::new(initial).expect("initial camera offset should be valid");
569 let updated = Vec2::new(-12.5, f32::MAX);
570 target
571 .set_camera_offset(updated)
572 .expect("finite replacement camera offset should be valid");
573 assert_vec2_bits_eq(target.camera_offset(), updated);
574 let nan = f32::from_bits(0x7fc0_5678);
575 for value in [
576 Vec2::new(nan, -0.0),
577 Vec2::new(-0.0, f32::INFINITY),
578 Vec2::new(f32::NEG_INFINITY, nan),
579 ] {
580 let error = target
581 .set_camera_offset(value)
582 .expect_err("non-finite camera offset should be rejected");
583 match error {
584 CameraFollowTarget2dError::InvalidCameraOffset { value: rejected } => {
585 assert_vec2_bits_eq(rejected, value);
586 }
587 }
588 assert_vec2_bits_eq(target.camera_offset(), updated);
589
590 let constructor = CameraFollowTarget2d::new(value)
591 .expect_err("constructor should reject the same non-finite camera offset");
592 match constructor {
593 CameraFollowTarget2dError::InvalidCameraOffset { value: rejected } => {
594 assert_vec2_bits_eq(rejected, value);
595 }
596 }
597 }
598 }
599
600 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
601 enum TestAction {
602 Left,
603 Right,
604 Down,
605 Up,
606 Alternate,
607 }
608
609 const AXIS: DigitalAxis2d<TestAction> = DigitalAxis2d::new(
610 TestAction::Left,
611 TestAction::Right,
612 TestAction::Down,
613 TestAction::Up,
614 );
615
616 #[test]
617 fn digital_movement_validation_and_mutation_are_atomic_and_bit_exact() {
618 for speed in [0.0, -0.0, f32::from_bits(1), 12.5, f32::MAX] {
619 let movement = DigitalMovement2d::new(AXIS, speed)
620 .expect("finite nonnegative speed should be valid");
621 assert_eq!(movement.axis(), AXIS);
622 assert_eq!(movement.speed().to_bits(), speed.to_bits());
623 }
624
625 let mut movement =
626 DigitalMovement2d::new(AXIS, 4.0).expect("initial speed should be valid");
627 let alternate = DigitalAxis2d::new(
628 TestAction::Alternate,
629 TestAction::Left,
630 TestAction::Up,
631 TestAction::Down,
632 );
633 movement.set_axis(alternate);
634 assert_eq!(movement.axis(), alternate);
635 movement
636 .set_speed(f32::MAX)
637 .expect("finite replacement speed should be valid");
638 assert_eq!(movement.speed().to_bits(), f32::MAX.to_bits());
639
640 let nan = f32::from_bits(0x7fc0_1234);
641 for speed in [
642 -f32::from_bits(1),
643 -1.0,
644 nan,
645 f32::INFINITY,
646 f32::NEG_INFINITY,
647 ] {
648 let error = movement
649 .set_speed(speed)
650 .expect_err("invalid replacement speed should be rejected");
651 match error {
652 DigitalMovement2dError::InvalidSpeed { value } => {
653 assert_eq!(value.to_bits(), speed.to_bits());
654 }
655 }
656 assert_eq!(movement.speed().to_bits(), f32::MAX.to_bits());
657
658 let constructor = DigitalMovement2d::new(AXIS, speed)
659 .expect_err("constructor should reject the same invalid speed");
660 match constructor {
661 DigitalMovement2dError::InvalidSpeed { value } => {
662 assert_eq!(value.to_bits(), speed.to_bits());
663 }
664 }
665 }
666 }
667
668 fn assert_vec2_bits_eq(actual: Vec2, expected: Vec2) {
669 assert_eq!(actual.x().to_bits(), expected.x().to_bits());
670 assert_eq!(actual.y().to_bits(), expected.y().to_bits());
671 }
672}