1use crate::persistence::{Document, SaveData, SaveError, Value, checksum};
5#[derive(Clone, Copy, Debug, PartialEq)]
6pub struct MotionTuning {
7 pub acceleration: f32,
8 pub braking: f32,
9 pub max_speed: f32,
10 pub response: f32,
12 pub traction: f32,
14}
15#[derive(Clone, Copy, Debug, Default, PartialEq)]
16pub struct Assists {
17 pub steering: f32,
18 pub aim: f32,
19 pub jump_buffer_seconds: f32,
20}
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct TuningProfile {
23 pub rules: u32,
25 pub motion: MotionTuning,
26 pub difficulty: f32,
28 pub assists: Assists,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum TuningField {
35 Acceleration,
36 Braking,
37 MaxSpeed,
38 Response,
39 Traction,
40 Difficulty,
41 Steering,
42 Aim,
43 JumpBufferSeconds,
44}
45
46impl TuningField {
47 pub const fn name(self) -> &'static str {
54 match self {
55 Self::Acceleration => "motion.acceleration",
56 Self::Braking => "motion.braking",
57 Self::MaxSpeed => "motion.max_speed",
58 Self::Response => "motion.response",
59 Self::Traction => "motion.traction",
60 Self::Difficulty => "difficulty",
61 Self::Steering => "assists.steering",
62 Self::Aim => "assists.aim",
63 Self::JumpBufferSeconds => "assists.jump_buffer_seconds",
64 }
65 }
66
67 fn value(self, profile: &TuningProfile) -> f32 {
68 match self {
69 Self::Acceleration => profile.motion.acceleration,
70 Self::Braking => profile.motion.braking,
71 Self::MaxSpeed => profile.motion.max_speed,
72 Self::Response => profile.motion.response,
73 Self::Traction => profile.motion.traction,
74 Self::Difficulty => profile.difficulty,
75 Self::Steering => profile.assists.steering,
76 Self::Aim => profile.assists.aim,
77 Self::JumpBufferSeconds => profile.assists.jump_buffer_seconds,
78 }
79 }
80}
81
82#[derive(Clone, Copy, Debug, PartialEq)]
84pub struct TuningChange {
85 pub field: TuningField,
86 pub before: f32,
88 pub after: f32,
90}
91
92#[derive(Clone, Copy, Debug)]
99pub struct TuningDiff {
100 before: TuningProfile,
101 after: TuningProfile,
102}
103
104impl TuningDiff {
105 pub fn changes(&self) -> impl Iterator<Item = TuningChange> + '_ {
113 [
114 TuningField::Acceleration,
115 TuningField::Braking,
116 TuningField::MaxSpeed,
117 TuningField::Response,
118 TuningField::Traction,
119 TuningField::Difficulty,
120 TuningField::Steering,
121 TuningField::Aim,
122 TuningField::JumpBufferSeconds,
123 ]
124 .into_iter()
125 .filter_map(|field| {
126 let before = field.value(&self.before);
127 let after = field.value(&self.after);
128 (before.to_bits() != after.to_bits()).then_some(TuningChange {
129 field,
130 before,
131 after,
132 })
133 })
134 }
135
136 pub fn is_empty(&self) -> bool {
139 self.changes().next().is_none()
140 }
141}
142
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum TuningDiffError {
146 InvalidCurrent,
148 InvalidCandidate,
150 RulesMismatch { current: u32, candidate: u32 },
152}
153
154impl std::fmt::Display for TuningDiffError {
155 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156 match self {
157 Self::InvalidCurrent => f.write_str("current tuning profile is invalid"),
158 Self::InvalidCandidate => f.write_str("candidate tuning profile is invalid"),
159 Self::RulesMismatch { current, candidate } => write!(
160 f,
161 "tuning rules mismatch: current {current}, candidate {candidate}"
162 ),
163 }
164 }
165}
166
167impl std::error::Error for TuningDiffError {}
168
169impl TuningProfile {
170 pub const fn rally() -> Self {
171 Self {
172 rules: 1,
173 motion: MotionTuning {
174 acceleration: 155.,
175 braking: 260.,
176 max_speed: 265.,
177 response: 14.,
178 traction: 9.,
179 },
180 difficulty: 1.,
181 assists: Assists {
182 steering: 0.,
183 aim: 0.,
184 jump_buffer_seconds: 0.,
185 },
186 }
187 }
188 pub const fn arena() -> Self {
189 Self {
190 rules: 2,
191 motion: MotionTuning {
192 acceleration: 2300.,
193 braking: 3000.,
194 max_speed: 230.,
195 response: 24.,
196 traction: 15.,
197 },
198 ..Self::rally()
199 }
200 }
201 pub fn validated(self) -> Result<Self, SaveError> {
202 let m = self.motion;
203 if self.rules == 0
204 || ![
205 m.acceleration,
206 m.braking,
207 m.max_speed,
208 m.response,
209 m.traction,
210 ]
211 .iter()
212 .all(|v| v.is_finite() && (0.0001..=10000.).contains(v))
213 || !self.difficulty.is_finite()
214 || !(0.25..=4.).contains(&self.difficulty)
215 || ![self.assists.steering, self.assists.aim]
216 .iter()
217 .all(|v| v.is_finite() && (0. ..=1.).contains(v))
218 || !self.assists.jump_buffer_seconds.is_finite()
219 || !(0. ..=0.5).contains(&self.assists.jump_buffer_seconds)
220 {
221 return Err(SaveError::InvalidData);
222 }
223 Ok(self)
224 }
225 pub fn diff(&self, candidate: &Self) -> Result<TuningDiff, TuningDiffError> {
264 self.validated()
265 .map_err(|_| TuningDiffError::InvalidCurrent)?;
266 candidate
267 .validated()
268 .map_err(|_| TuningDiffError::InvalidCandidate)?;
269 if self.rules != candidate.rules {
270 return Err(TuningDiffError::RulesMismatch {
271 current: self.rules,
272 candidate: candidate.rules,
273 });
274 }
275 Ok(TuningDiff {
276 before: *self,
277 after: *candidate,
278 })
279 }
280 pub fn replace(&mut self, candidate: Self) -> Result<(), SaveError> {
282 candidate.validated()?;
283 if candidate.rules != self.rules {
284 return Err(SaveError::InvalidData);
285 }
286 *self = candidate;
287 Ok(())
288 }
289 fn bytes(self) -> [u8; 40] {
290 let m = self.motion;
291 let mut bytes = [0; 40];
292 bytes[..4].copy_from_slice(&self.rules.to_le_bytes());
293 for (out, value) in bytes[4..].as_chunks_mut::<4>().0.iter_mut().zip([
294 m.acceleration,
295 m.braking,
296 m.max_speed,
297 m.response,
298 m.traction,
299 self.difficulty,
300 self.assists.steering,
301 self.assists.aim,
302 self.assists.jump_buffer_seconds,
303 ]) {
304 out.copy_from_slice(&value.to_le_bytes());
305 }
306 bytes
307 }
308 pub fn fingerprint(self) -> Result<u64, SaveError> {
311 self.validated()?;
312 Ok(checksum(&self.bytes()))
313 }
314}
315impl SaveData for TuningProfile {
316 const SCHEMA: u64 = 0x465854554e494e47;
317 const VERSION: u32 = 1;
318 const MAX_BYTES: usize = 256;
319 fn write(&self, d: &mut Document) -> Result<(), SaveError> {
320 self.validated()?;
321 d.set("profile", Value::Bytes(self.bytes().to_vec()))
322 }
323 fn read(d: &Document) -> Result<Self, SaveError> {
324 let bytes = d.bytes("profile")?;
325 if bytes.len() != 40 {
326 return Err(SaveError::InvalidData);
327 }
328 let rules = u32::from_le_bytes(bytes[..4].try_into().unwrap());
329 let mut values = [0.; 9];
330 for (out, word) in values.iter_mut().zip(bytes[4..].as_chunks::<4>().0) {
331 *out = f32::from_le_bytes(*word);
332 }
333 let [
334 acceleration,
335 braking,
336 max_speed,
337 response,
338 traction,
339 difficulty,
340 steering,
341 aim,
342 jump_buffer_seconds,
343 ] = values;
344 Self {
345 rules,
346 motion: MotionTuning {
347 acceleration,
348 braking,
349 max_speed,
350 response,
351 traction,
352 },
353 difficulty,
354 assists: Assists {
355 steering,
356 aim,
357 jump_buffer_seconds,
358 },
359 }
360 .validated()
361 }
362}
363#[cfg(test)]
364mod tests {
365 use super::*;
366
367 const FIELDS: [(TuningField, &str, f32, f32, f32); 9] = [
369 (
370 TuningField::Acceleration,
371 "motion.acceleration",
372 155.,
373 0.0001,
374 10000.,
375 ),
376 (TuningField::Braking, "motion.braking", 260., 0.0001, 10000.),
377 (
378 TuningField::MaxSpeed,
379 "motion.max_speed",
380 265.,
381 0.0001,
382 10000.,
383 ),
384 (
385 TuningField::Response,
386 "motion.response",
387 14.,
388 0.0001,
389 10000.,
390 ),
391 (TuningField::Traction, "motion.traction", 9., 0.0001, 10000.),
392 (TuningField::Difficulty, "difficulty", 1., 0.25, 4.),
393 (TuningField::Steering, "assists.steering", 0., 0., 1.),
394 (TuningField::Aim, "assists.aim", 0., 0., 1.),
395 (
396 TuningField::JumpBufferSeconds,
397 "assists.jump_buffer_seconds",
398 0.,
399 0.,
400 0.5,
401 ),
402 ];
403
404 fn field_mut(profile: &mut TuningProfile, field: TuningField) -> &mut f32 {
405 match field {
406 TuningField::Acceleration => &mut profile.motion.acceleration,
407 TuningField::Braking => &mut profile.motion.braking,
408 TuningField::MaxSpeed => &mut profile.motion.max_speed,
409 TuningField::Response => &mut profile.motion.response,
410 TuningField::Traction => &mut profile.motion.traction,
411 TuningField::Difficulty => &mut profile.difficulty,
412 TuningField::Steering => &mut profile.assists.steering,
413 TuningField::Aim => &mut profile.assists.aim,
414 TuningField::JumpBufferSeconds => &mut profile.assists.jump_buffer_seconds,
415 }
416 }
417
418 #[test]
419 fn profile_roundtrip_rules_and_transactional_rejection() {
420 let mut profile = TuningProfile::rally();
421 let bytes = profile.encode(4).unwrap();
422 assert_eq!(TuningProfile::decode(&bytes).unwrap(), (profile, 4));
423 let original = profile;
424 let mut invalid = profile;
425 invalid.motion.max_speed = f32::NAN;
426 assert!(profile.replace(invalid).is_err());
427 assert_eq!(profile, original);
428 assert!(profile.replace(TuningProfile::arena()).is_err());
429 let mut assisted = profile;
430 assisted.assists.steering = 0.5;
431 assert_ne!(profile.fingerprint(), assisted.fingerprint());
432 }
433
434 #[test]
435 fn identical_profiles_have_empty_previews() {
436 for profile in [TuningProfile::rally(), TuningProfile::arena()] {
437 let diff = profile.diff(&profile).unwrap();
438 assert!(diff.is_empty());
439 assert_eq!(diff.changes().count(), 0);
440 }
441 }
442
443 #[test]
444 fn every_field_has_an_inspectable_directional_change() {
445 let current = TuningProfile::rally();
446 for (field, label, before, _, after) in FIELDS {
447 let mut candidate = current;
448 *field_mut(&mut candidate, field) = after;
449 let diff = current.diff(&candidate).unwrap();
450 assert!(!diff.is_empty());
451 assert_eq!(field.name(), label);
452 assert_eq!(
453 diff.changes().collect::<Vec<_>>(),
454 [TuningChange {
455 field,
456 before,
457 after,
458 }]
459 );
460 assert_eq!(
461 candidate
462 .diff(¤t)
463 .unwrap()
464 .changes()
465 .collect::<Vec<_>>(),
466 [TuningChange {
467 field,
468 before: after,
469 after: before,
470 }]
471 );
472 }
473 }
474
475 #[test]
476 fn all_nine_changes_have_stable_order_and_iteration_can_repeat() {
477 let current = TuningProfile::rally();
478 let mut candidate = current;
479 for (field, _, _, _, upper) in FIELDS {
480 *field_mut(&mut candidate, field) = upper;
481 }
482 let diff = current.diff(&candidate).unwrap();
483 let expected = FIELDS.map(|(field, _, before, _, after)| TuningChange {
484 field,
485 before,
486 after,
487 });
488 assert_eq!(diff.changes().collect::<Vec<_>>(), expected);
489 assert_eq!(diff.changes().collect::<Vec<_>>(), expected);
490 }
491
492 #[test]
493 fn sparse_preview_does_not_mutate_inputs_and_survives_later_edits() {
494 let mut current = TuningProfile::rally();
495 let mut candidate = current;
496 candidate.motion.response = 12.;
497 candidate.difficulty = 2.;
498 candidate.assists.aim = 0.25;
499 let current_save = current.encode(7).unwrap();
500 let candidate_save = candidate.encode(7).unwrap();
501 let diff = current.diff(&candidate).unwrap();
502 assert_eq!(current.encode(7).unwrap(), current_save);
503 assert_eq!(candidate.encode(7).unwrap(), candidate_save);
504 let expected = [
505 TuningChange {
506 field: TuningField::Response,
507 before: 14.,
508 after: 12.,
509 },
510 TuningChange {
511 field: TuningField::Difficulty,
512 before: 1.,
513 after: 2.,
514 },
515 TuningChange {
516 field: TuningField::Aim,
517 before: 0.,
518 after: 0.25,
519 },
520 ];
521 assert_eq!(diff.changes().collect::<Vec<_>>(), expected);
522 current.replace(candidate).unwrap();
523 assert!(current.diff(&candidate).unwrap().is_empty());
524 candidate.assists.aim = 0.75;
525 assert_eq!(diff.changes().collect::<Vec<_>>(), expected);
526 assert_eq!(current.diff(&candidate).unwrap().changes().count(), 1);
527 }
528
529 #[test]
530 fn diff_validates_both_sides_at_every_scalar_boundary() {
531 let current = TuningProfile::rally();
532 for (field, _, _, lower, upper) in FIELDS {
533 for value in [lower, upper] {
534 let mut candidate = current;
535 *field_mut(&mut candidate, field) = value;
536 assert!(current.diff(&candidate).is_ok(), "{field:?} = {value}");
537 assert!(candidate.diff(¤t).is_ok(), "{field:?} = {value}");
538 }
539 for value in [
540 f32::NAN,
541 f32::INFINITY,
542 f32::NEG_INFINITY,
543 lower.next_down(),
544 upper.next_up(),
545 ] {
546 let mut invalid = current;
547 *field_mut(&mut invalid, field) = value;
548 let before = invalid.bytes();
549 assert_eq!(
550 current.diff(&invalid).unwrap_err(),
551 TuningDiffError::InvalidCandidate,
552 "{field:?} = {value}"
553 );
554 assert_eq!(
555 invalid.diff(¤t).unwrap_err(),
556 TuningDiffError::InvalidCurrent,
557 "{field:?} = {value}"
558 );
559 assert_eq!(invalid.bytes(), before);
560 }
561 }
562 }
563
564 #[test]
565 fn rules_rejection_and_error_precedence_are_explicit() {
566 let current = TuningProfile::rally();
567 let candidate = TuningProfile::arena();
568 let error = current.diff(&candidate).unwrap_err();
569 assert_eq!(
570 error,
571 TuningDiffError::RulesMismatch {
572 current: 1,
573 candidate: 2
574 }
575 );
576 assert_eq!(
577 error.to_string(),
578 "tuning rules mismatch: current 1, candidate 2"
579 );
580 let invalid = TuningProfile {
581 rules: 0,
582 ..current
583 };
584 assert_eq!(
585 current.diff(&invalid).unwrap_err(),
586 TuningDiffError::InvalidCandidate
587 );
588 assert_eq!(
589 invalid.diff(¤t).unwrap_err(),
590 TuningDiffError::InvalidCurrent
591 );
592 assert_eq!(
593 invalid.diff(&invalid).unwrap_err(),
594 TuningDiffError::InvalidCurrent
595 );
596 let invalid_candidate = TuningProfile {
597 difficulty: f32::NAN,
598 ..candidate
599 };
600 assert_eq!(
601 current.diff(&invalid_candidate).unwrap_err(),
602 TuningDiffError::InvalidCandidate
603 );
604 assert_eq!(
605 invalid.diff(&candidate).unwrap_err(),
606 TuningDiffError::InvalidCurrent
607 );
608 assert_eq!(current, TuningProfile::rally());
609 assert_eq!(candidate, TuningProfile::arena());
610 }
611
612 #[test]
613 fn signed_zero_assists_are_reported_without_normalization() {
614 let current = TuningProfile::rally();
615 for field in [
616 TuningField::Steering,
617 TuningField::Aim,
618 TuningField::JumpBufferSeconds,
619 ] {
620 let mut candidate = current;
621 *field_mut(&mut candidate, field) = -0.;
622 assert_eq!(current, candidate); assert_ne!(
624 current.fingerprint().unwrap(),
625 candidate.fingerprint().unwrap()
626 );
627 let diff = current.diff(&candidate).unwrap();
628 assert!(!diff.is_empty());
629 let changes: Vec<_> = diff.changes().collect();
630 assert_eq!(changes.len(), 1);
631 assert_eq!(changes[0].field, field);
632 assert_eq!(changes[0].before.to_bits(), 0.0_f32.to_bits());
633 assert_eq!(changes[0].after.to_bits(), (-0.0_f32).to_bits());
634 let (decoded, _) = TuningProfile::decode(&candidate.encode(1).unwrap()).unwrap();
635 assert_eq!(decoded.bytes(), candidate.bytes());
636 assert!(decoded.diff(&candidate).unwrap().is_empty());
637 }
638 }
639
640 #[test]
641 fn adjacent_float_changes_are_not_hidden_by_a_tolerance() {
642 let current = TuningProfile::rally();
643 let mut candidate = current;
644 candidate.motion.max_speed = current.motion.max_speed.next_up();
645 let diff = current.diff(&candidate).unwrap();
646 assert_eq!(diff.changes().count(), 1);
647 let change = diff.changes().next().unwrap();
648 assert_eq!(change.field, TuningField::MaxSpeed);
649 assert_eq!(change.after.to_bits(), change.before.to_bits() + 1);
650 }
651
652 #[test]
653 fn replace_can_still_repair_an_invalid_current_profile() {
654 let candidate = TuningProfile::rally();
655 let mut current = candidate;
656 current.motion.acceleration = f32::NAN;
657 assert_eq!(
658 current.diff(&candidate).unwrap_err(),
659 TuningDiffError::InvalidCurrent
660 );
661 current.replace(candidate).unwrap();
662 assert_eq!(current, candidate);
663 }
664
665 #[test]
666 fn version_one_save_and_fingerprints_remain_compatible() {
667 let saved = [
670 0x46, 0x58, 0x53, 0x56, 0x30, 0x30, 0x30, 0x31, 0x47, 0x4e, 0x49, 0x4e, 0x55, 0x54,
671 0x58, 0x46, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
672 0x35, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x70, 0x72, 0x6f, 0x66, 0x69,
673 0x6c, 0x65, 0x05, 0x28, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b,
674 0x43, 0x00, 0x00, 0x82, 0x43, 0x00, 0x80, 0x84, 0x43, 0x00, 0x00, 0x60, 0x41, 0x00,
675 0x00, 0x10, 0x41, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
676 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x35, 0xe0, 0x48, 0x8c, 0x3e, 0xf2, 0xdf,
677 ];
678 let profile = TuningProfile::rally();
679 assert_eq!(TuningProfile::VERSION, 1);
680 assert_eq!(TuningProfile::SCHEMA, 0x465854554e494e47);
681 assert_eq!(TuningProfile::MAX_BYTES, 256);
682 assert_eq!(profile.encode(4).unwrap(), saved);
683 assert_eq!(TuningProfile::decode(&saved).unwrap(), (profile, 4));
684 assert_eq!(profile.fingerprint().unwrap(), 0x8f2a5be84b60f391);
685 assert_eq!(
686 TuningProfile::arena().fingerprint().unwrap(),
687 0x6c4660d1d0b6d881
688 );
689 }
690}