Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53727a216c |
@@ -10,7 +10,3 @@ imported_assets
|
|||||||
*_old.glb
|
*_old.glb
|
||||||
/replay.json
|
/replay.json
|
||||||
*.replay.tmp
|
*.replay.tmp
|
||||||
|
|
||||||
# Python debugger formatter tests
|
|
||||||
__pycache__/
|
|
||||||
*.pyc
|
|
||||||
|
|||||||
@@ -2,15 +2,6 @@
|
|||||||
|
|
||||||
Fancy heavily advanced platform fighting game
|
Fancy heavily advanced platform fighting game
|
||||||
|
|
||||||
## Debugging fixed-point values with lldb
|
|
||||||
|
|
||||||
If using CodeLLDB:
|
|
||||||
```json
|
|
||||||
"preRunCommands": [
|
|
||||||
"command script import ${workspaceFolder}/tools/lldb_fixed.py"
|
|
||||||
]
|
|
||||||
```
|
|
||||||
|
|
||||||
## Direct P2P Debugging
|
## Direct P2P Debugging
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -25,9 +16,18 @@ cargo run -- --debug-match --players 2 --local-port 7001 \
|
|||||||
|
|
||||||
## Production Build
|
## Production Build
|
||||||
|
|
||||||
|
Production builds use the `production` Cargo profile and do not dynamically
|
||||||
|
link Bevy or Rust. Development builds retain Bevy dynamic linking for faster
|
||||||
|
iteration. Cargo stores the production profile under `target/production`,
|
||||||
|
separate from development artifacts under `target/debug`.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cargo run --locked \
|
cargo run --locked \
|
||||||
--bin process-assets --no-default-features --features debug_features
|
--bin process-assets --no-default-features --features debug_features
|
||||||
cargo build --locked \
|
cargo build --locked \
|
||||||
--profile production --no-default-features --features debug_features
|
--profile production --no-default-features --features debug_features
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The asset preprocessing command must be run from the repository root. It
|
||||||
|
populates `imported_assets/Default`, which is then consumed by the production
|
||||||
|
game without running the asset processor at startup.
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ mod asset_baking;
|
|||||||
mod runtime;
|
mod runtime;
|
||||||
mod visual_binding;
|
mod visual_binding;
|
||||||
|
|
||||||
pub use crate::math::fixed_transform::FixedMat4;
|
|
||||||
pub use asset_baking::{BakedAnimationAssetProcessingPlugin, BakedAnimationPlugin};
|
pub use asset_baking::{BakedAnimationAssetProcessingPlugin, BakedAnimationPlugin};
|
||||||
|
pub use crate::math::fixed_transform::FixedMat4;
|
||||||
pub use runtime::{
|
pub use runtime::{
|
||||||
BakedAnimationClip, BakedFighterAnimations, FighterBoneIndexMap, FighterBoneMatrices,
|
BakedAnimationClip, BakedFighterAnimations, FighterBoneIndexMap, FighterBoneMatrices,
|
||||||
update_fighter_bone_matrices,
|
update_fighter_bone_matrices,
|
||||||
@@ -164,20 +164,6 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn repeated_pose_updates_reuse_scratch_and_output_buffers() {
|
|
||||||
let mut matrices = FighterBoneMatrices::default();
|
|
||||||
let names = ["root".into(), "hand".into()];
|
|
||||||
let parents = [None, Some(0)];
|
|
||||||
let pose = [FixedMat4::IDENTITY, FixedMat4::IDENTITY];
|
|
||||||
|
|
||||||
matrices.set_pose(&names, &parents, &pose, FGi32::ONE);
|
|
||||||
let capacities = matrices.buffer_capacities();
|
|
||||||
matrices.set_pose(&names, &parents, &pose, FGi32::ONE);
|
|
||||||
|
|
||||||
assert_eq!(capacities, matrices.buffer_capacities());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn model_scale_affects_gameplay_bones_without_changing_visual_locals() {
|
fn model_scale_affects_gameplay_bones_without_changing_visual_locals() {
|
||||||
let mut root = FixedMat4::IDENTITY;
|
let mut root = FixedMat4::IDENTITY;
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::collections::HashMap;
|
|||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use super::BAKED_ANIMATION_FPS;
|
use super::{BAKED_ANIMATION_FPS};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
fighter::{
|
fighter::{
|
||||||
@@ -12,8 +12,8 @@ use crate::{
|
|||||||
manifest::FighterManifest,
|
manifest::FighterManifest,
|
||||||
visual::FighterAnimations,
|
visual::FighterAnimations,
|
||||||
},
|
},
|
||||||
math::fixed_transform::FixedMat4,
|
|
||||||
math::int::FGi32,
|
math::int::FGi32,
|
||||||
|
math::fixed_transform::FixedMat4
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||||
@@ -70,24 +70,12 @@ pub struct FighterBoneMatrices {
|
|||||||
previous_frame_matrices: Vec<FixedMat4>,
|
previous_frame_matrices: Vec<FixedMat4>,
|
||||||
local_matrices: Vec<FixedMat4>,
|
local_matrices: Vec<FixedMat4>,
|
||||||
previous_local_matrices: Vec<FixedMat4>,
|
previous_local_matrices: Vec<FixedMat4>,
|
||||||
model_matrices: Vec<Option<FixedMat4>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Component, Clone, Debug, Default)]
|
#[derive(Component, Clone, Debug, Default)]
|
||||||
pub struct FighterBoneIndexMap(pub HashMap<String, usize>);
|
pub struct FighterBoneIndexMap(pub HashMap<String, usize>);
|
||||||
|
|
||||||
impl FighterBoneMatrices {
|
impl FighterBoneMatrices {
|
||||||
#[cfg(test)]
|
|
||||||
pub(super) fn buffer_capacities(&self) -> [usize; 5] {
|
|
||||||
[
|
|
||||||
self.matrices.capacity(),
|
|
||||||
self.local_matrices.capacity(),
|
|
||||||
self.previous_frame_matrices.capacity(),
|
|
||||||
self.previous_local_matrices.capacity(),
|
|
||||||
self.model_matrices.capacity(),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(&self, bone: &str) -> Option<(FixedMat4, FixedMat4)> {
|
pub fn get(&self, bone: &str) -> Option<(FixedMat4, FixedMat4)> {
|
||||||
let index = self.bone_names.iter().position(|name| name == bone)?;
|
let index = self.bone_names.iter().position(|name| name == bone)?;
|
||||||
Some((
|
Some((
|
||||||
@@ -154,19 +142,13 @@ impl FighterBoneMatrices {
|
|||||||
assert_eq!(self.bone_names, bone_names, "baked bone names changed");
|
assert_eq!(self.bone_names, bone_names, "baked bone names changed");
|
||||||
assert_eq!(self.parents, parents, "baked bone parents changed");
|
assert_eq!(self.parents, parents, "baked bone parents changed");
|
||||||
}
|
}
|
||||||
self.matrices.reserve(local.len());
|
|
||||||
self.previous_frame_matrices.reserve(local.len());
|
|
||||||
self.local_matrices.reserve(local.len());
|
|
||||||
self.previous_local_matrices.reserve(local.len());
|
|
||||||
self.model_matrices.reserve(local.len());
|
|
||||||
std::mem::swap(&mut self.matrices, &mut self.previous_frame_matrices);
|
std::mem::swap(&mut self.matrices, &mut self.previous_frame_matrices);
|
||||||
std::mem::swap(&mut self.local_matrices, &mut self.previous_local_matrices);
|
std::mem::swap(&mut self.local_matrices, &mut self.previous_local_matrices);
|
||||||
self.local_matrices.clear();
|
self.local_matrices.clear();
|
||||||
self.local_matrices.extend_from_slice(local);
|
self.local_matrices.extend_from_slice(local);
|
||||||
self.model_matrices.resize(local.len(), None);
|
let mut model = vec![None; local.len()];
|
||||||
self.model_matrices.fill(None);
|
|
||||||
for index in 0..local.len() {
|
for index in 0..local.len() {
|
||||||
resolve_model_transform(index, parents, local, &mut self.model_matrices)
|
resolve_model_transform(index, parents, local, &mut model)
|
||||||
.expect("baked bone hierarchy should be valid");
|
.expect("baked bone hierarchy should be valid");
|
||||||
}
|
}
|
||||||
let model_scale = FixedMat4 {
|
let model_scale = FixedMat4 {
|
||||||
@@ -177,12 +159,10 @@ impl FighterBoneMatrices {
|
|||||||
[FGi32::ZERO, FGi32::ZERO, FGi32::ZERO, FGi32::ONE],
|
[FGi32::ZERO, FGi32::ZERO, FGi32::ZERO, FGi32::ONE],
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
self.matrices.clear();
|
self.matrices = model
|
||||||
self.matrices.extend(
|
.into_iter()
|
||||||
self.model_matrices.iter().map(|matrix| {
|
.map(|matrix| model_scale.mul(matrix.expect("baked bone hierarchy should be valid")))
|
||||||
model_scale.mul(matrix.expect("baked bone hierarchy should be valid"))
|
.collect();
|
||||||
}),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-12
@@ -50,13 +50,11 @@ pub fn air_collide_with_stage(
|
|||||||
translation.0 + ecb.get_bottom_point(),
|
translation.0 + ecb.get_bottom_point(),
|
||||||
);
|
);
|
||||||
|
|
||||||
stage_collision
|
let mut intersect_results = vec![];
|
||||||
.stage_polys
|
|
||||||
.iter()
|
for (poly_idx, poly) in stage_collision.stage_polys.iter().enumerate() {
|
||||||
.enumerate()
|
if let Some(intersect_result) = poly.intersect_ray(ray_segment) {
|
||||||
.filter_map(|(poly_idx, poly)| {
|
intersect_results.push((
|
||||||
poly.intersect_ray(ray_segment).map(|intersect_result| {
|
|
||||||
(
|
|
||||||
AirCollisionWithStageResult {
|
AirCollisionWithStageResult {
|
||||||
line_id: {
|
line_id: {
|
||||||
StageLineID {
|
StageLineID {
|
||||||
@@ -70,9 +68,13 @@ pub fn air_collide_with_stage(
|
|||||||
intersect_result
|
intersect_result
|
||||||
.position
|
.position
|
||||||
.distance_squared(ray_segment.point2()),
|
.distance_squared(ray_segment.point2()),
|
||||||
)
|
));
|
||||||
})
|
}
|
||||||
})
|
}
|
||||||
.max_by(|(_, a), (_, b)| a.cmp(b))
|
intersect_results.sort_by(|(_, a), (_, b)| a.cmp(b));
|
||||||
.map(|(result, _)| result)
|
|
||||||
|
intersect_results
|
||||||
|
.iter()
|
||||||
|
.last()
|
||||||
|
.map(|(val, _)| val.to_owned().clone())
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-74
@@ -1,8 +1,6 @@
|
|||||||
use std::panic::{self, AssertUnwindSafe};
|
use std::panic::{self, AssertUnwindSafe};
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::thread::JoinHandle;
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
use gc_adapter_neo::{Controller, GcAdapter};
|
use gc_adapter_neo::{Controller, GcAdapter};
|
||||||
@@ -57,11 +55,10 @@ impl GcPortState {
|
|||||||
/// Shared, `Send + Sync` handle to the latest snapshot from the poll
|
/// Shared, `Send + Sync` handle to the latest snapshot from the poll
|
||||||
/// thread. Safe to store as an ordinary [`Resource`] (no `NonSend` needed)
|
/// thread. Safe to store as an ordinary [`Resource`] (no `NonSend` needed)
|
||||||
/// because the `GcAdapter` itself never leaves its thread.
|
/// because the `GcAdapter` itself never leaves its thread.
|
||||||
#[derive(Resource)]
|
#[derive(Resource, Clone)]
|
||||||
pub struct GcAdapterSnapshot {
|
pub struct GcAdapterSnapshot {
|
||||||
ports: Arc<Mutex<[GcPortState; 4]>>,
|
ports: Arc<Mutex<[GcPortState; 4]>>,
|
||||||
shutdown: Arc<AtomicBool>,
|
shutdown: Arc<AtomicBool>,
|
||||||
poll_thread: Option<JoinHandle<()>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GcAdapterSnapshot {
|
impl GcAdapterSnapshot {
|
||||||
@@ -72,36 +69,12 @@ impl GcAdapterSnapshot {
|
|||||||
|
|
||||||
impl Drop for GcAdapterSnapshot {
|
impl Drop for GcAdapterSnapshot {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.shutdown.store(true, Ordering::Release);
|
// Only actually signals shutdown once the last clone (this resource
|
||||||
|
// is never cloned in practice, but be defensive) is dropped.
|
||||||
if let Some(poll_thread) = self.poll_thread.take() {
|
if Arc::strong_count(&self.shutdown) <= 1 {
|
||||||
if let Err(payload) = poll_thread.join() {
|
self.shutdown.store(true, Ordering::Relaxed);
|
||||||
error!(
|
|
||||||
"GameCube Controller Adapter poll thread panicked during shutdown: {payload:?}"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const INITIAL_ERROR_BACKOFF: Duration = Duration::from_millis(1);
|
|
||||||
const MAX_ERROR_BACKOFF: Duration = Duration::from_millis(100);
|
|
||||||
|
|
||||||
fn next_error_backoff(backoff: Duration) -> Duration {
|
|
||||||
backoff.saturating_mul(2).min(MAX_ERROR_BACKOFF)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wait for a retry while still allowing the owner to shut the poll thread down promptly.
|
|
||||||
fn wait_for_retry(shutdown: &AtomicBool, delay: Duration) -> bool {
|
|
||||||
let deadline = Instant::now() + delay;
|
|
||||||
while !shutdown.load(Ordering::Acquire) {
|
|
||||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
|
||||||
if remaining.is_zero() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
std::thread::sleep(remaining.min(Duration::from_millis(10)));
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Connects to the first GameCube adapter found on the USB bus and starts
|
/// Connects to the first GameCube adapter found on the USB bus and starts
|
||||||
@@ -121,7 +94,7 @@ pub fn spawn_poll_thread() -> Result<GcAdapterSnapshot, gc_adapter_neo::UsbError
|
|||||||
|
|
||||||
let thread_ports = ports.clone();
|
let thread_ports = ports.clone();
|
||||||
let thread_shutdown = shutdown.clone();
|
let thread_shutdown = shutdown.clone();
|
||||||
let poll_thread = std::thread::Builder::new()
|
std::thread::Builder::new()
|
||||||
.name("gc-adapter-poll".into())
|
.name("gc-adapter-poll".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
// Flush whatever the adapter had buffered before we started
|
// Flush whatever the adapter had buffered before we started
|
||||||
@@ -134,27 +107,17 @@ pub fn spawn_poll_thread() -> Result<GcAdapterSnapshot, gc_adapter_neo::UsbError
|
|||||||
let mut rate_window_start = std::time::Instant::now();
|
let mut rate_window_start = std::time::Instant::now();
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
let mut rate_window_count: u32 = 0;
|
let mut rate_window_count: u32 = 0;
|
||||||
let mut error_backoff = INITIAL_ERROR_BACKOFF;
|
|
||||||
|
|
||||||
while !thread_shutdown.load(Ordering::Acquire) {
|
while !thread_shutdown.load(Ordering::Relaxed) {
|
||||||
let result = panic::catch_unwind(AssertUnwindSafe(|| adapter.read_controllers()));
|
let result = panic::catch_unwind(AssertUnwindSafe(|| adapter.read_controllers()));
|
||||||
|
|
||||||
let controllers = match result {
|
let controllers = match result {
|
||||||
Ok(Ok(controllers)) => {
|
Ok(Ok(controllers)) => controllers,
|
||||||
error_backoff = INITIAL_ERROR_BACKOFF;
|
|
||||||
controllers
|
|
||||||
}
|
|
||||||
// Ignore this, for some reason we get a bunch of these when we start reading
|
// Ignore this, for some reason we get a bunch of these when we start reading
|
||||||
Ok(Err(
|
Ok(Err(
|
||||||
gc_adapter_neo::AdapterError::Parse(_)
|
gc_adapter_neo::AdapterError::Parse(_)
|
||||||
| gc_adapter_neo::AdapterError::ShortRead(_),
|
| gc_adapter_neo::AdapterError::ShortRead(_),
|
||||||
)) => {
|
)) => continue,
|
||||||
if !wait_for_retry(&thread_shutdown, error_backoff) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
error_backoff = next_error_backoff(error_backoff);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
Ok(Err(gc_adapter_neo::AdapterError::Usb(err))) => {
|
Ok(Err(gc_adapter_neo::AdapterError::Usb(err))) => {
|
||||||
error!(
|
error!(
|
||||||
"GameCube Controller Adapter USB read failed ({err:?}); stopping \
|
"GameCube Controller Adapter USB read failed ({err:?}); stopping \
|
||||||
@@ -197,32 +160,5 @@ pub fn spawn_poll_thread() -> Result<GcAdapterSnapshot, gc_adapter_neo::UsbError
|
|||||||
})
|
})
|
||||||
.expect("failed to spawn gc-adapter poll thread");
|
.expect("failed to spawn gc-adapter poll thread");
|
||||||
|
|
||||||
Ok(GcAdapterSnapshot {
|
Ok(GcAdapterSnapshot { ports, shutdown })
|
||||||
ports,
|
|
||||||
shutdown,
|
|
||||||
poll_thread: Some(poll_thread),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn error_backoff_is_capped() {
|
|
||||||
let mut backoff = INITIAL_ERROR_BACKOFF;
|
|
||||||
for _ in 0..16 {
|
|
||||||
backoff = next_error_backoff(backoff);
|
|
||||||
}
|
|
||||||
|
|
||||||
assert_eq!(backoff, MAX_ERROR_BACKOFF);
|
|
||||||
assert_eq!(next_error_backoff(MAX_ERROR_BACKOFF), MAX_ERROR_BACKOFF);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn retry_wait_stops_when_shutdown_is_requested() {
|
|
||||||
let shutdown = AtomicBool::new(true);
|
|
||||||
|
|
||||||
assert!(!wait_for_retry(&shutdown, Duration::from_secs(1)));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -241,7 +241,7 @@ pub fn copy_cursor_transform_to_token(
|
|||||||
character_boxes: Query<(&CharacterBox, &ComputedNode, &UiGlobalTransform)>,
|
character_boxes: Query<(&CharacterBox, &ComputedNode, &UiGlobalTransform)>,
|
||||||
match_config: Res<MenuMatchConfig>,
|
match_config: Res<MenuMatchConfig>,
|
||||||
cursors: Query<&UiGlobalTransform, With<FGMenuCursor>>,
|
cursors: Query<&UiGlobalTransform, With<FGMenuCursor>>,
|
||||||
cam: Single<&Camera>,
|
cam: Single<&Camera, With<IsDefaultUiCamera>>,
|
||||||
ui_scale: Res<UiScale>,
|
ui_scale: Res<UiScale>,
|
||||||
) -> Result {
|
) -> Result {
|
||||||
let camera = cam.into_inner();
|
let camera = cam.into_inner();
|
||||||
|
|||||||
+1
-1
@@ -181,7 +181,7 @@ pub fn cursor_input(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_cursor_transform(
|
pub fn update_cursor_transform(
|
||||||
camera: Single<&Camera>,
|
camera: Single<&Camera, With<IsDefaultUiCamera>>,
|
||||||
query: Query<(&mut Node, &PointerLocation), With<FGMenuCursor>>,
|
query: Query<(&mut Node, &PointerLocation), With<FGMenuCursor>>,
|
||||||
ui_scale: Res<UiScale>,
|
ui_scale: Res<UiScale>,
|
||||||
) {
|
) {
|
||||||
|
|||||||
+14
-14
@@ -25,8 +25,6 @@ pub mod style;
|
|||||||
|
|
||||||
#[derive(Component, Clone, Default)]
|
#[derive(Component, Clone, Default)]
|
||||||
pub struct MenuMarker {}
|
pub struct MenuMarker {}
|
||||||
#[derive(Component, Clone, Default)]
|
|
||||||
pub struct MenuCameraMarker {}
|
|
||||||
|
|
||||||
pub struct MenuPlugin;
|
pub struct MenuPlugin;
|
||||||
|
|
||||||
@@ -40,7 +38,6 @@ pub fn wrap_menu(menu: impl Scene) -> impl Scene {
|
|||||||
bsn! {
|
bsn! {
|
||||||
#MenuRoot
|
#MenuRoot
|
||||||
MenuMarker
|
MenuMarker
|
||||||
Transform
|
|
||||||
Node {
|
Node {
|
||||||
width: percent(100),
|
width: percent(100),
|
||||||
height: percent(100),
|
height: percent(100),
|
||||||
@@ -49,11 +46,6 @@ pub fn wrap_menu(menu: impl Scene) -> impl Scene {
|
|||||||
flex_direction: FlexDirection::Column,
|
flex_direction: FlexDirection::Column,
|
||||||
}
|
}
|
||||||
Children [
|
Children [
|
||||||
(
|
|
||||||
#MenuCamera
|
|
||||||
Camera
|
|
||||||
Camera2d
|
|
||||||
),
|
|
||||||
(
|
(
|
||||||
#MenuContainer
|
#MenuContainer
|
||||||
Node {
|
Node {
|
||||||
@@ -73,18 +65,15 @@ pub fn wrap_menu(menu: impl Scene) -> impl Scene {
|
|||||||
|
|
||||||
pub fn despawn_menu(
|
pub fn despawn_menu(
|
||||||
existing_menu: Option<Single<Entity, With<MenuMarker>>>,
|
existing_menu: Option<Single<Entity, With<MenuMarker>>>,
|
||||||
existing_menu_camera: Option<Single<Entity, With<MenuCameraMarker>>>,
|
|
||||||
mut commands: Commands,
|
mut commands: Commands,
|
||||||
) {
|
) {
|
||||||
if let Some(entity) = existing_menu {
|
if let Some(entity) = existing_menu {
|
||||||
commands
|
commands
|
||||||
.entity(entity.into_inner())
|
.entity(entity.into_inner())
|
||||||
|
.remove::<Camera2d>()
|
||||||
|
.remove::<Camera>()
|
||||||
.despawn();
|
.despawn();
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(menu_cam) = existing_menu_camera {
|
|
||||||
commands.entity(*menu_cam).despawn();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn spawn_menu(
|
pub fn spawn_menu(
|
||||||
@@ -95,6 +84,8 @@ pub fn spawn_menu(
|
|||||||
if let Some(entity) = existing_menu {
|
if let Some(entity) = existing_menu {
|
||||||
commands
|
commands
|
||||||
.entity(entity.into_inner())
|
.entity(entity.into_inner())
|
||||||
|
.remove::<Camera2d>()
|
||||||
|
.remove::<Camera>()
|
||||||
.despawn();
|
.despawn();
|
||||||
}
|
}
|
||||||
commands.queue_spawn_scene(wrap_menu(menu));
|
commands.queue_spawn_scene(wrap_menu(menu));
|
||||||
@@ -122,7 +113,16 @@ impl Plugin for MenuPlugin {
|
|||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut App) {
|
||||||
app.add_systems(
|
app.add_systems(
|
||||||
OnEnter(AppState::MainMenu),
|
OnEnter(AppState::MainMenu),
|
||||||
build_menu::<MainMenu>,
|
(build_menu::<MainMenu>, |mut commands: Commands| {
|
||||||
|
commands.spawn((Camera2d, IsDefaultUiCamera));
|
||||||
|
commands.spawn((
|
||||||
|
Camera2d,
|
||||||
|
Camera {
|
||||||
|
order: 1,
|
||||||
|
..default()
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
.add_message::<character_select::PlayerSlotAssigned>()
|
.add_message::<character_select::PlayerSlotAssigned>()
|
||||||
.init_resource::<navigation::UINavigationActionState>()
|
.init_resource::<navigation::UINavigationActionState>()
|
||||||
|
|||||||
+14
-70
@@ -152,20 +152,6 @@ fn validate(replay: &Replay) -> Result<(), String> {
|
|||||||
{
|
{
|
||||||
return Err("replay frames must be strictly ordered".into());
|
return Err("replay frames must be strictly ordered".into());
|
||||||
}
|
}
|
||||||
if replay
|
|
||||||
.frames
|
|
||||||
.windows(2)
|
|
||||||
.any(|frames| frames[0].frame.checked_add(1) != Some(frames[1].frame))
|
|
||||||
{
|
|
||||||
return Err("replay frames must be contiguous".into());
|
|
||||||
}
|
|
||||||
if replay
|
|
||||||
.checksums
|
|
||||||
.windows(2)
|
|
||||||
.any(|checksums| checksums[0].frame >= checksums[1].frame)
|
|
||||||
{
|
|
||||||
return Err("replay checksums must be strictly ordered".into());
|
|
||||||
}
|
|
||||||
if replay
|
if replay
|
||||||
.frames
|
.frames
|
||||||
.iter()
|
.iter()
|
||||||
@@ -187,21 +173,6 @@ impl Replay {
|
|||||||
handles.sort_unstable();
|
handles.sort_unstable();
|
||||||
handles != (0..handles.len()).collect::<Vec<_>>()
|
handles != (0..handles.len()).collect::<Vec<_>>()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn frame(&self, frame: i32) -> Option<&ReplayFrame> {
|
|
||||||
let first_frame = self.frames.first()?.frame;
|
|
||||||
let index = frame.checked_sub(first_frame)? as usize;
|
|
||||||
self.frames
|
|
||||||
.get(index)
|
|
||||||
.filter(|recorded| recorded.frame == frame)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn checksum(&self, frame: i32) -> Option<u128> {
|
|
||||||
self.checksums
|
|
||||||
.binary_search_by_key(&frame, |checksum| checksum.frame)
|
|
||||||
.ok()
|
|
||||||
.map(|index| self.checksums[index].checksum)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_replay(mut commands: Commands, args: Res<Args>, loaded: Option<Res<LoadedReplay>>) {
|
fn start_replay(mut commands: Commands, args: Res<Args>, loaded: Option<Res<LoadedReplay>>) {
|
||||||
@@ -239,7 +210,11 @@ fn replay_inputs(
|
|||||||
.insert(frame.0, inputs.iter().map(|(input, _)| *input).collect());
|
.insert(frame.0, inputs.iter().map(|(input, _)| *input).collect());
|
||||||
}
|
}
|
||||||
ReplayMode::Playback { replay, mismatch } if !*mismatch => {
|
ReplayMode::Playback { replay, mismatch } if !*mismatch => {
|
||||||
let Some(recorded) = replay.frame(frame.0) else {
|
let Some(recorded) = replay
|
||||||
|
.frames
|
||||||
|
.iter()
|
||||||
|
.find(|recorded| recorded.frame == frame.0)
|
||||||
|
else {
|
||||||
error!("Replay has no input for frame {}", frame.0);
|
error!("Replay has no input for frame {}", frame.0);
|
||||||
*mismatch = true;
|
*mismatch = true;
|
||||||
return;
|
return;
|
||||||
@@ -260,16 +235,22 @@ fn record_checksum(
|
|||||||
let Some(mut runtime) = runtime else { return };
|
let Some(mut runtime) = runtime else { return };
|
||||||
if matches!(&runtime.mode, ReplayMode::Record { .. }) {
|
if matches!(&runtime.mode, ReplayMode::Record { .. }) {
|
||||||
runtime.checksums.insert(frame.0, checksum.0);
|
runtime.checksums.insert(frame.0, checksum.0);
|
||||||
} else if let ReplayMode::Playback { replay, mismatch } = &mut runtime.mode
|
} else if let ReplayMode::Playback { replay, mismatch } = &mut runtime.mode {
|
||||||
&& let Some(expected) = replay.checksum(frame.0)
|
if let Some(expected) = replay
|
||||||
&& expected != checksum.0
|
.checksums
|
||||||
|
.iter()
|
||||||
|
.find(|value| value.frame == frame.0)
|
||||||
|
.map(|value| value.checksum)
|
||||||
{
|
{
|
||||||
|
if expected != checksum.0 {
|
||||||
error!(
|
error!(
|
||||||
"Replay desync at frame {}: expected {:X}, got {:X}",
|
"Replay desync at frame {}: expected {:X}, got {:X}",
|
||||||
frame.0, expected, checksum.0
|
frame.0, expected, checksum.0
|
||||||
);
|
);
|
||||||
*mismatch = true;
|
*mismatch = true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn stop_recording(
|
fn stop_recording(
|
||||||
@@ -426,41 +407,4 @@ mod tests {
|
|||||||
"unsupported replay version 1"
|
"unsupported replay version 1"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn playback_lookups_use_frame_offsets_and_support_sparse_checksums() {
|
|
||||||
let mut replay = sample();
|
|
||||||
replay.frames[0].frame = 10;
|
|
||||||
replay.frames.push(ReplayFrame {
|
|
||||||
frame: 11,
|
|
||||||
inputs: replay.frames[0].inputs.clone(),
|
|
||||||
});
|
|
||||||
replay.checksums.push(ReplayChecksum {
|
|
||||||
frame: 11,
|
|
||||||
checksum: 84,
|
|
||||||
});
|
|
||||||
replay.checksums[0].frame = 10;
|
|
||||||
validate(&replay).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(replay.frame(10).unwrap().frame, 10);
|
|
||||||
assert_eq!(replay.frame(11).unwrap().frame, 11);
|
|
||||||
assert!(replay.frame(9).is_none());
|
|
||||||
assert_eq!(replay.checksum(10), Some(42));
|
|
||||||
assert_eq!(replay.checksum(11), Some(84));
|
|
||||||
assert_eq!(replay.checksum(12), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn noncontiguous_input_frames_are_rejected() {
|
|
||||||
let mut replay = sample();
|
|
||||||
replay.frames.push(ReplayFrame {
|
|
||||||
frame: 3,
|
|
||||||
inputs: replay.frames[0].inputs.clone(),
|
|
||||||
});
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
validate(&replay).unwrap_err(),
|
|
||||||
"replay frames must be contiguous"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-52
@@ -1,17 +1,13 @@
|
|||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
|
|
||||||
use crate::{
|
use crate::{fighter::{attack::FighterDamage, manifest::{FighterManifest}}, match_loading::MatchPlayer, player::Player};
|
||||||
fighter::{attack::FighterDamage, manifest::FighterManifest}, match_loading::{MatchPlayer}, match_runtime::MatchState, player::Player, ui::stock_icon::BattleUIStockIcon,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Component, FromTemplate)]
|
#[derive(Component, FromTemplate)]
|
||||||
pub struct FighterInfoUI {
|
pub struct FighterInfoUI {
|
||||||
percentage_text: Entity,
|
percentage_text: Entity,
|
||||||
stock_icon_container: Entity,
|
|
||||||
_name_text: Entity,
|
_name_text: Entity,
|
||||||
player_handle: usize,
|
player_handle: usize,
|
||||||
visible_damage: FighterDamage,
|
visible_damage: FighterDamage,
|
||||||
visible_stocks: u8,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FighterInfoUI {
|
impl FighterInfoUI {
|
||||||
@@ -20,7 +16,6 @@ impl FighterInfoUI {
|
|||||||
bsn! {
|
bsn! {
|
||||||
FighterInfoUI {
|
FighterInfoUI {
|
||||||
percentage_text: #PercentageText,
|
percentage_text: #PercentageText,
|
||||||
stock_icon_container: #StockIconContainer,
|
|
||||||
_name_text: #NameText,
|
_name_text: #NameText,
|
||||||
player_handle: {match_player.handle}
|
player_handle: {match_player.handle}
|
||||||
}
|
}
|
||||||
@@ -30,10 +25,6 @@ impl FighterInfoUI {
|
|||||||
justify_content: JustifyContent::Center,
|
justify_content: JustifyContent::Center,
|
||||||
}
|
}
|
||||||
Children [
|
Children [
|
||||||
(
|
|
||||||
#StockIconContainer
|
|
||||||
Node
|
|
||||||
)
|
|
||||||
(
|
(
|
||||||
#PercentageText
|
#PercentageText
|
||||||
Text("0.00%")
|
Text("0.00%")
|
||||||
@@ -50,54 +41,17 @@ impl FighterInfoUI {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_fighter_info_damage(
|
pub fn update_fighter_info_damage(fighters: Query<(&Player, &FighterDamage)>, ui_elements: Query<&mut FighterInfoUI>, mut commands: Commands) {
|
||||||
fighters: Query<(&Player, &FighterDamage)>,
|
|
||||||
ui_elements: Query<&mut FighterInfoUI>,
|
|
||||||
mut commands: Commands,
|
|
||||||
) {
|
|
||||||
for mut ui_element in ui_elements {
|
for mut ui_element in ui_elements {
|
||||||
let Some((_, damage)) = fighters
|
let Some((_, damage)) = fighters.iter().find(|(player, _)| {
|
||||||
.iter()
|
player.handle == ui_element.player_handle
|
||||||
.find(|(player, _)| player.handle == ui_element.player_handle)
|
}) else {
|
||||||
else {
|
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
if *damage != ui_element.visible_damage {
|
if *damage != ui_element.visible_damage {
|
||||||
commands
|
commands.entity(ui_element.percentage_text).insert(Text(format!("{}%", damage)));
|
||||||
.entity(ui_element.percentage_text)
|
|
||||||
.insert(Text(format!("{}%", damage)));
|
|
||||||
ui_element.visible_damage = damage.clone();
|
ui_element.visible_damage = damage.clone();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_fighter_info_stocks(
|
|
||||||
match_state: Res<MatchState>,
|
|
||||||
ui_elements: Query<&mut FighterInfoUI>,
|
|
||||||
mut commands: Commands,
|
|
||||||
) {
|
|
||||||
|
|
||||||
for mut ui_element in ui_elements {
|
|
||||||
let handle = ui_element.player_handle;
|
|
||||||
let Some(match_player) = match_state.players.get(handle) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(stocks) = match_player.stocks_remaining else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
if stocks != ui_element.visible_stocks {
|
|
||||||
commands
|
|
||||||
.entity(ui_element.stock_icon_container)
|
|
||||||
.despawn_children()
|
|
||||||
.with_children(|spawner| {
|
|
||||||
for _ in 0..stocks {
|
|
||||||
spawner.spawn_empty().apply_scene(BattleUIStockIcon::scene());
|
|
||||||
}
|
|
||||||
});
|
|
||||||
ui_element.visible_stocks = stocks;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+2
-21
@@ -1,15 +1,10 @@
|
|||||||
use bevy::prelude::*;
|
use bevy::prelude::*;
|
||||||
|
|
||||||
use crate::{
|
use crate::AppState;
|
||||||
AppState,
|
|
||||||
match_loading::{MatchConfig, MatchRules},
|
|
||||||
match_runtime::MatchState,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub mod battle_ui;
|
pub mod battle_ui;
|
||||||
pub mod errors;
|
pub mod errors;
|
||||||
pub mod fighter_info;
|
pub mod fighter_info;
|
||||||
pub mod stock_icon;
|
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct InGameUIPlugin;
|
pub struct InGameUIPlugin;
|
||||||
@@ -18,20 +13,6 @@ impl Plugin for InGameUIPlugin {
|
|||||||
fn build(&self, app: &mut App) {
|
fn build(&self, app: &mut App) {
|
||||||
app.add_systems(OnEnter(AppState::InMatch), battle_ui::spawn_battle_ui)
|
app.add_systems(OnEnter(AppState::InMatch), battle_ui::spawn_battle_ui)
|
||||||
.add_systems(OnExit(AppState::InMatch), battle_ui::cleanup_battle_ui)
|
.add_systems(OnExit(AppState::InMatch), battle_ui::cleanup_battle_ui)
|
||||||
.add_systems(PostUpdate, fighter_info::update_fighter_info_damage)
|
.add_systems(PostUpdate, fighter_info::update_fighter_info_damage);
|
||||||
.add_systems(
|
|
||||||
PostUpdate,
|
|
||||||
fighter_info::update_fighter_info_stocks.run_if(
|
|
||||||
resource_exists::<MatchState>
|
|
||||||
.and_then(resource_exists::<MatchConfig>)
|
|
||||||
.and_then(|match_config: Res<MatchConfig>| {
|
|
||||||
if let MatchRules::Stock { .. } = match_config.rules {
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
use bevy::prelude::*;
|
|
||||||
|
|
||||||
#[derive(SceneComponent, Clone, FromTemplate)]
|
|
||||||
pub struct BattleUIStockIcon;
|
|
||||||
|
|
||||||
impl BattleUIStockIcon {
|
|
||||||
pub fn scene() -> impl Scene {
|
|
||||||
bsn! {
|
|
||||||
Node {
|
|
||||||
width: px(32),
|
|
||||||
height: px(32),
|
|
||||||
border_radius: BorderRadius::MAX,
|
|
||||||
}
|
|
||||||
BackgroundColor({bevy::color::palettes::css::RED})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
"""LLDB summaries for Rust's `fixed` crate.
|
|
||||||
|
|
||||||
Load this file from LLDB with:
|
|
||||||
|
|
||||||
command script import /path/to/shinespark/tools/lldb_fixed.py
|
|
||||||
|
|
||||||
The implementation does not use floating-point arithmetic, so displayed values
|
|
||||||
are exact even for FixedI128/FixedU128 values.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import re
|
|
||||||
|
|
||||||
try:
|
|
||||||
import lldb
|
|
||||||
except ImportError:
|
|
||||||
# Keep the pure parsing and formatting helpers testable without LLDB.
|
|
||||||
lldb = None
|
|
||||||
|
|
||||||
|
|
||||||
_FIXED_TYPE_RE = re.compile(r"(?:^|::)Fixed([IU])(8|16|32|64|128)<(.+)>$")
|
|
||||||
_DIRECT_TYPENUM_RE = re.compile(r"(?:^|::)U(\d+)$")
|
|
||||||
_TYPENUM_BIT_RE = re.compile(r"(?:^|::)B([01])(?=\s*[,>])")
|
|
||||||
|
|
||||||
|
|
||||||
def parse_fixed_type(type_name):
|
|
||||||
"""Return (signed, storage_bits, fractional_bits), or None."""
|
|
||||||
if not type_name:
|
|
||||||
return None
|
|
||||||
|
|
||||||
match = _FIXED_TYPE_RE.search(type_name.replace(" ", ""))
|
|
||||||
if match is None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
signed = match.group(1) == "I"
|
|
||||||
storage_bits = int(match.group(2))
|
|
||||||
fractional_type = match.group(3)
|
|
||||||
|
|
||||||
direct = _DIRECT_TYPENUM_RE.search(fractional_type)
|
|
||||||
if direct is not None:
|
|
||||||
fractional_bits = int(direct.group(1))
|
|
||||||
else:
|
|
||||||
# typenum represents UInt<N, B> as a binary tree. Its textual Rust
|
|
||||||
# type lists the bits from most significant to least significant.
|
|
||||||
digits = _TYPENUM_BIT_RE.findall(fractional_type)
|
|
||||||
if not digits:
|
|
||||||
return None
|
|
||||||
fractional_bits = int("".join(digits), 2)
|
|
||||||
|
|
||||||
if fractional_bits > storage_bits:
|
|
||||||
return None
|
|
||||||
return signed, storage_bits, fractional_bits
|
|
||||||
|
|
||||||
|
|
||||||
def normalize_bits(raw_bits, signed, storage_bits):
|
|
||||||
"""Interpret a possibly unsigned LLDB integer using the fixed type's width."""
|
|
||||||
mask = (1 << storage_bits) - 1
|
|
||||||
raw_bits &= mask
|
|
||||||
if signed and raw_bits >= 1 << (storage_bits - 1):
|
|
||||||
raw_bits -= 1 << storage_bits
|
|
||||||
return raw_bits
|
|
||||||
|
|
||||||
|
|
||||||
def format_fixed(raw_bits, fractional_bits):
|
|
||||||
"""Format a scaled integer exactly as a decimal string."""
|
|
||||||
if fractional_bits == 0:
|
|
||||||
return str(raw_bits)
|
|
||||||
|
|
||||||
negative = raw_bits < 0
|
|
||||||
magnitude = -raw_bits if negative else raw_bits
|
|
||||||
whole = magnitude >> fractional_bits
|
|
||||||
remainder = magnitude & ((1 << fractional_bits) - 1)
|
|
||||||
|
|
||||||
if remainder == 0:
|
|
||||||
result = str(whole)
|
|
||||||
else:
|
|
||||||
# remainder / 2^n == (remainder * 5^n) / 10^n, which gives a finite,
|
|
||||||
# exact decimal representation without converting through a float.
|
|
||||||
decimal = str(remainder * 5**fractional_bits).zfill(fractional_bits)
|
|
||||||
result = f"{whole}.{decimal.rstrip('0')}"
|
|
||||||
|
|
||||||
return f"-{result}" if negative else result
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_lldb_integer(value):
|
|
||||||
text = value.GetValue()
|
|
||||||
if text is not None:
|
|
||||||
try:
|
|
||||||
return int(text, 0)
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# GetValueAsUnsigned is also useful on LLDB versions that do not render
|
|
||||||
# primitive values through GetValue. It is sufficient for all <= 64-bit
|
|
||||||
# fixed types; current LLDB versions render i128/u128 through GetValue.
|
|
||||||
return value.GetValueAsUnsigned()
|
|
||||||
|
|
||||||
|
|
||||||
def fixed_summary(value, _internal_dict):
|
|
||||||
layout = parse_fixed_type(value.GetTypeName())
|
|
||||||
if layout is None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
signed, storage_bits, fractional_bits = layout
|
|
||||||
bits = value.GetChildMemberWithName("bits")
|
|
||||||
if not bits.IsValid():
|
|
||||||
return None
|
|
||||||
|
|
||||||
raw_bits = _parse_lldb_integer(bits)
|
|
||||||
raw_bits = normalize_bits(raw_bits, signed, storage_bits)
|
|
||||||
return format_fixed(raw_bits, fractional_bits)
|
|
||||||
|
|
||||||
|
|
||||||
def __lldb_init_module(debugger, _internal_dict):
|
|
||||||
# LLDB's type-name regex sees the concrete fixed type rather than project
|
|
||||||
# aliases such as FGi32 and FGWide.
|
|
||||||
debugger.HandleCommand(
|
|
||||||
"type summary add --python-function lldb_fixed.fixed_summary "
|
|
||||||
"--category Shinespark --regex "
|
|
||||||
"'^fixed::Fixed(I|U)(8|16|32|64|128)<.+>$'"
|
|
||||||
)
|
|
||||||
# A dedicated category makes the formatter work even when CodeLLDB has not
|
|
||||||
# enabled rustc's standard `Rust` formatter category yet.
|
|
||||||
debugger.HandleCommand("type category enable Shinespark")
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
import unittest
|
|
||||||
|
|
||||||
import lldb_fixed
|
|
||||||
|
|
||||||
|
|
||||||
class ParseFixedTypeTests(unittest.TestCase):
|
|
||||||
def test_direct_typenum_alias(self):
|
|
||||||
self.assertEqual(
|
|
||||||
lldb_fixed.parse_fixed_type("fixed::FixedI32<typenum::uint::U16>"),
|
|
||||||
(True, 32, 16),
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_expanded_typenum(self):
|
|
||||||
type_name = (
|
|
||||||
"fixed::FixedI32<"
|
|
||||||
"typenum::uint::UInt<"
|
|
||||||
"typenum::uint::UInt<"
|
|
||||||
"typenum::uint::UInt<"
|
|
||||||
"typenum::uint::UInt<"
|
|
||||||
"typenum::uint::UInt<typenum::uint::UTerm, typenum::bit::B1>, "
|
|
||||||
"typenum::bit::B0>, typenum::bit::B0>, typenum::bit::B0>, "
|
|
||||||
"typenum::bit::B0>>"
|
|
||||||
)
|
|
||||||
self.assertEqual(lldb_fixed.parse_fixed_type(type_name), (True, 32, 16))
|
|
||||||
|
|
||||||
def test_unsigned_type(self):
|
|
||||||
self.assertEqual(
|
|
||||||
lldb_fixed.parse_fixed_type("fixed::FixedU64<typenum::uint::U24>"),
|
|
||||||
(False, 64, 24),
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_unrelated_type(self):
|
|
||||||
self.assertIsNone(lldb_fixed.parse_fixed_type("core::primitive::i32"))
|
|
||||||
|
|
||||||
|
|
||||||
class FormatFixedTests(unittest.TestCase):
|
|
||||||
def test_q16_16(self):
|
|
||||||
self.assertEqual(lldb_fixed.format_fixed(3 << 15, 16), "1.5")
|
|
||||||
self.assertEqual(lldb_fixed.format_fixed(-(3 << 15), 16), "-1.5")
|
|
||||||
self.assertEqual(lldb_fixed.format_fixed(1, 16), "0.0000152587890625")
|
|
||||||
|
|
||||||
def test_integer_value_has_no_decimal_suffix(self):
|
|
||||||
self.assertEqual(lldb_fixed.format_fixed(12 << 16, 16), "12")
|
|
||||||
|
|
||||||
def test_q96_32(self):
|
|
||||||
raw = (1 << 100) + (1 << 31)
|
|
||||||
self.assertEqual(
|
|
||||||
lldb_fixed.format_fixed(raw, 32),
|
|
||||||
"295147905179352825856.5",
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_twos_complement_normalization(self):
|
|
||||||
self.assertEqual(lldb_fixed.normalize_bits(0xFFFF8000, True, 32), -32768)
|
|
||||||
self.assertEqual(lldb_fixed.normalize_bits(0xFFFF8000, False, 32), 0xFFFF8000)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
Reference in New Issue
Block a user