Compare commits

..
Author SHA1 Message Date
EIREXE 77cd5033c3 Add debug save states
CI / build-and-test (pull_request) Successful in 25m8s
2026-09-15 08:46:15 +02:00
EIREXE cd9c39b70c Add debug frame stepping (#5)
CI / build-and-test (push) Successful in 24m23s
Reviewed-on: #5
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-09-14 20:03:47 +00:00
EIREXE 0d96a8aed8 Make warnings an error
CI / build-and-test (push) Failing after 15m6s
2026-09-14 18:25:15 +02:00
EIREXE cebf1148c2 Persist Rust CI cache (#4)
CI / build-and-test (push) Successful in 11m1s
## Summary

- Pin the nightly Rust toolchain used by CI
- Cache Cargo dependencies and build artifacts between Gitea Actions runs
- Share the Linux nightly cache across branches

Reviewed-on: #4
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-09-14 16:16:48 +00:00
EIREXE 088d594e97 Merge pull request 'Make debug menu usable with mouse and keyboard' (#2) from debug-menu-input into master
CI / build-and-test (push) Successful in 11m29s
Reviewed-on: #2
2026-09-14 13:32:42 +00:00
EIREXE 868df95cd4 wording fixes
CI / build-and-test (pull_request) Successful in 11m31s
2026-09-14 15:20:07 +02:00
EIREXE 504f63be54 Add support for split .gltf and .bin files (#3)
CI / build-and-test (push) Canceled after 15s
Reviewed-on: #3
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-09-14 13:19:29 +00:00
EIREXE 8c11a01446 Make debug menu usable with mouse and keyboard
CI / build-and-test (pull_request) Successful in 11m27s
2026-09-14 14:33:04 +02:00
EIREXE 30477254e5 Add build and test CI (#1)
CI / build-and-test (push) Successful in 11m30s
Reviewed-on: #1
Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
2026-09-14 12:02:24 +00:00
EIREXE 4861374aef Add test fighter for CI 2026-09-14 11:38:42 +02:00
EIREXE d3a688e768 Fix build and add some assets 2026-09-14 11:25:27 +02:00
EIREXE 376a40d38c Updated game settings and fighter assets 2026-09-13 23:28:40 +02:00
eirexe-test b29085f8a5 Update .gitignore 2026-09-13 23:28:09 +02:00
eirexe-test b0b1420f48 Add mailmap 2026-09-13 23:25:52 +02:00
eirexe-test 711d0d923f Rename package to shinespark 2026-09-13 23:06:43 +02:00
eirexe-test 4570860d64 Implement hitstun and knockback. 2026-09-13 23:01:25 +02:00
eirexe-test 811578af2f Make dashback configurable, fix movement bugs, add double jump forward and back. 2026-09-13 01:00:15 +02:00
eirexe-test ad105418be Allow other controllers in debug match 2026-09-13 00:57:27 +02:00
eirexe-test 531ecc1aec Moar fixes and optimizations 2026-09-12 17:10:20 +02:00
eirexe-test df18ffa1a7 Fix all warnings 2026-09-12 17:01:15 +02:00
eirexe-test 50f0371b54 Improve hitbox determinisim and performance. 2026-09-12 16:48:16 +02:00
eirexe-test 6e01147125 Some other bullshit 2026-09-12 14:55:40 +02:00
eirexe-test 74a635785e Make CSS and SSS reach a match 2026-09-11 22:01:16 +02:00
eirexe-test f3701bd8b0 Formatting 2026-09-11 22:01:03 +02:00
86 changed files with 85693 additions and 1383 deletions
+51
View File
@@ -0,0 +1,51 @@
name: CI
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
jobs:
build-and-test:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Check out source
uses: actions/checkout@v4
- name: Install Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | \
sh -s -- -y --profile minimal
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
"$HOME/.cargo/bin/rustup" toolchain install nightly-2026-09-14 --profile minimal
- name: Cache Rust dependencies and build artifacts
uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2
with:
shared-key: linux-nightly
cache-bin: false
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install --no-install-recommends -y \
clang \
libasound2-dev \
libudev-dev \
libusb-1.0-0-dev \
libwayland-dev \
libx11-dev \
libxkbcommon-dev \
libxkbcommon-x11-0 \
mesa-vulkan-drivers \
mold \
pkg-config
- name: Build
run: RUSTFLAGS="-D warnings" cargo build --locked -j 4
- name: Run unit tests
run: cargo test --locked --lib -j 4
+9
View File
@@ -1,3 +1,12 @@
/target /target
/.jackdaw /.jackdaw
imported_assets imported_assets
# Local editor configuration
**/.vscode/
# Generated and backup assets
*.blend1
*_old.glb
/replay.json
*.replay.tmp
+1
View File
@@ -0,0 +1 @@
Álex Román (EIREXE) <eirexe123@gmail.com> <eirexe@eirteam.moe>
Generated
+106 -407
View File
@@ -24,8 +24,6 @@ version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320"
dependencies = [ dependencies = [
"enumn",
"serde",
"uuid", "uuid",
] ]
@@ -133,9 +131,9 @@ checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]] [[package]]
name = "alsa" name = "alsa"
version = "0.11.0" version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d" checksum = "7c88dbbce13b232b26250e1e2e6ac18b6a891a646b8148285036ebce260ac5c3"
dependencies = [ dependencies = [
"alsa-sys", "alsa-sys",
"bitflags 2.13.1", "bitflags 2.13.1",
@@ -145,9 +143,9 @@ dependencies = [
[[package]] [[package]]
name = "alsa-sys" name = "alsa-sys"
version = "0.4.0" version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04" checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527"
dependencies = [ dependencies = [
"libc", "libc",
"pkg-config", "pkg-config",
@@ -308,15 +306,6 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
[[package]]
name = "ascii-canvas"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1e3e699d84ab1b0911a1010c5c106aa34ae89aeac103be5ce0c3859db1e891"
dependencies = [
"term",
]
[[package]] [[package]]
name = "ash" name = "ash"
version = "0.38.0+1.3.281" version = "0.38.0+1.3.281"
@@ -504,6 +493,26 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "basis-universal"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "555fb05709f4e12fa2f6b93a480facf167eb0ecb2558ba41f610f588e77cbd14"
dependencies = [
"basis-universal-sys",
"bitflags 1.3.2",
"lazy_static",
]
[[package]]
name = "basis-universal-sys"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd9bde5e9547958fb0e77d79fc7879edcf91d5e0c8e372ef8959916cf35e8506"
dependencies = [
"cc",
]
[[package]] [[package]]
name = "bevy" name = "bevy"
version = "0.19.0" version = "0.19.0"
@@ -596,7 +605,6 @@ dependencies = [
"bevy_derive", "bevy_derive",
"bevy_ecs", "bevy_ecs",
"bevy_reflect", "bevy_reflect",
"serde",
] ]
[[package]] [[package]]
@@ -632,7 +640,7 @@ dependencies = [
"downcast-rs 2.0.2", "downcast-rs 2.0.2",
"either", "either",
"petgraph", "petgraph",
"ron 0.12.2", "ron",
"serde", "serde",
"smallvec", "smallvec",
"thiserror 2.0.19", "thiserror 2.0.19",
@@ -729,7 +737,7 @@ dependencies = [
"futures-util", "futures-util",
"js-sys", "js-sys",
"notify-debouncer-full", "notify-debouncer-full",
"ron 0.12.2", "ron",
"serde", "serde",
"stackfuture", "stackfuture",
"thiserror 2.0.19", "thiserror 2.0.19",
@@ -873,21 +881,6 @@ dependencies = [
"wgpu-types", "wgpu-types",
] ]
[[package]]
name = "bevy_common_assets"
version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b9a9509ff29e5db89e1697c047fbbdc55208c8c3d07a494b013cc96814fcddb"
dependencies = [
"anyhow",
"bevy_app",
"bevy_asset",
"bevy_reflect",
"ron 0.11.0",
"serde",
"thiserror 2.0.19",
]
[[package]] [[package]]
name = "bevy_core_pipeline" name = "bevy_core_pipeline"
version = "0.19.0" version = "0.19.0"
@@ -1275,6 +1268,7 @@ version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37bc41f69a0c6ade2e7961602517545b39ab8e42bc8c4a729bd24ffee3bcd904" checksum = "37bc41f69a0c6ade2e7961602517545b39ab8e42bc8c4a729bd24ffee3bcd904"
dependencies = [ dependencies = [
"basis-universal",
"bevy_app", "bevy_app",
"bevy_asset", "bevy_asset",
"bevy_color", "bevy_color",
@@ -1311,7 +1305,6 @@ dependencies = [
"bevy_reflect", "bevy_reflect",
"derive_more", "derive_more",
"log", "log",
"serde",
"smol_str", "smol_str",
"thiserror 2.0.19", "thiserror 2.0.19",
] ]
@@ -1527,7 +1520,6 @@ dependencies = [
"glam 0.32.1", "glam 0.32.1",
"half", "half",
"hexasphere", "hexasphere",
"serde",
"thiserror 2.0.19", "thiserror 2.0.19",
"tracing", "tracing",
"wgpu-types", "wgpu-types",
@@ -2026,7 +2018,6 @@ dependencies = [
"bevy_window", "bevy_window",
"derive_more", "derive_more",
"parley", "parley",
"serde",
"smallvec", "smallvec",
"swash", "swash",
"taffy", "taffy",
@@ -2181,7 +2172,7 @@ dependencies = [
"bevy_transform", "bevy_transform",
"bevy_utils", "bevy_utils",
"derive_more", "derive_more",
"ron 0.12.2", "ron",
"serde", "serde",
"thiserror 2.0.19", "thiserror 2.0.19",
"uuid", "uuid",
@@ -2294,16 +2285,7 @@ dependencies = [
"cc", "cc",
"cfg-if", "cfg-if",
"constant_time_eq", "constant_time_eq",
"cpufeatures 0.3.0", "cpufeatures",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
] ]
[[package]] [[package]]
@@ -2471,16 +2453,6 @@ dependencies = [
"shlex", "shlex",
] ]
[[package]]
name = "cdt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b91b872294f63ef586b32aa94141561681aa35ca2d703960cca4f661f4e18184"
dependencies = [
"geometry-predicates",
"thiserror 1.0.69",
]
[[package]] [[package]]
name = "cesu8" name = "cesu8"
version = "1.1.0" version = "1.1.0"
@@ -2767,11 +2739,11 @@ dependencies = [
[[package]] [[package]]
name = "coreaudio-rs" name = "coreaudio-rs"
version = "0.14.2" version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58" checksum = "1aae284fbaf7d27aa0e292f7677dfbe26503b0d555026f702940805a630eac17"
dependencies = [ dependencies = [
"bitflags 2.13.1", "bitflags 1.3.2",
"libc", "libc",
"objc2-audio-toolbox", "objc2-audio-toolbox",
"objc2-core-audio", "objc2-core-audio",
@@ -2781,9 +2753,9 @@ dependencies = [
[[package]] [[package]]
name = "cpal" name = "cpal"
version = "0.17.3" version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8942da362c0f0d895d7cac616263f2f9424edc5687364dfd1d25ef7eba506d7" checksum = "5b1f9c7312f19fc2fa12fd7acaf38de54e8320ba10d1a02dcbe21038def51ccb"
dependencies = [ dependencies = [
"alsa", "alsa",
"coreaudio-rs", "coreaudio-rs",
@@ -2809,15 +2781,6 @@ dependencies = [
"windows", "windows",
] ]
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.3.0" version = "0.3.0"
@@ -2927,16 +2890,6 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]] [[package]]
name = "ctrlc" name = "ctrlc"
version = "3.5.2" version = "3.5.2"
@@ -2989,16 +2942,6 @@ dependencies = [
"unicode-xid", "unicode-xid",
] ]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]] [[package]]
name = "dispatch" name = "dispatch"
version = "0.2.0" version = "0.2.0"
@@ -3070,16 +3013,6 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
[[package]]
name = "earcutr"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afc28d89ac6cb489f679fcf51aaa62b4667bb0fb73a30f1d4d23949069707c07"
dependencies = [
"itertools 0.14.0",
"num-traits",
]
[[package]] [[package]]
name = "ecolor" name = "ecolor"
version = "0.34.3" version = "0.34.3"
@@ -3180,17 +3113,6 @@ dependencies = [
"syn 1.0.109", "syn 1.0.109",
] ]
[[package]]
name = "enumn"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]] [[package]]
name = "epaint" name = "epaint"
version = "0.34.3" version = "0.34.3"
@@ -3349,6 +3271,17 @@ dependencies = [
"typenum", "typenum",
] ]
[[package]]
name = "fixed_math"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41c7bdc2634a5ddb634f556681dc3bb8f37a1b0419590b206a103cc89eb9ecce"
dependencies = [
"fixed",
"seq-macro",
"typenum",
]
[[package]] [[package]]
name = "fixedbitset" name = "fixedbitset"
version = "0.5.7" version = "0.5.7"
@@ -3533,36 +3466,6 @@ dependencies = [
"thread_local", "thread_local",
] ]
[[package]]
name = "game-test"
version = "0.1.0"
dependencies = [
"arrayvec",
"avian3d",
"bevy",
"bevy-inspector-egui",
"bevy_asset_loader",
"bevy_common_assets",
"bevy_egui",
"bevy_ggrs",
"bevy_wind_waker_shader",
"bincode",
"bitfields",
"clap",
"enum_cycling",
"enum_cycling_derive",
"fixed",
"gc-adapter-neo",
"gltf",
"jackdaw_runtime",
"rhai",
"ron 0.12.2",
"serde",
"serde_json",
"strum",
"strum_macros",
]
[[package]] [[package]]
name = "gc-adapter-neo" name = "gc-adapter-neo"
version = "1.0.0" version = "1.0.0"
@@ -3574,22 +3477,6 @@ dependencies = [
"rusb", "rusb",
] ]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "geometry-predicates"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8dba84198cf199c11b83f1cb9243eaeb70dc50b719d2835ebf34bf2481bca010"
[[package]] [[package]]
name = "gethostname" name = "gethostname"
version = "1.1.0" version = "1.1.0"
@@ -3872,7 +3759,6 @@ dependencies = [
"cfg-if", "cfg-if",
"crunchy", "crunchy",
"num-traits", "num-traits",
"serde",
"zerocopy", "zerocopy",
] ]
@@ -4249,89 +4135,6 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jackdaw_avian_integration"
version = "0.19.0"
dependencies = [
"avian3d",
"bevy",
"jackdaw_geometry",
"jackdaw_scene_types",
]
[[package]]
name = "jackdaw_bsn"
version = "0.19.0"
dependencies = [
"bevy",
"lalrpop",
"lalrpop-util",
"log",
"nom",
"pathdiff",
"thiserror 2.0.19",
]
[[package]]
name = "jackdaw_geometry"
version = "0.19.0"
dependencies = [
"bevy",
"bitflags 2.13.1",
"cdt",
"earcutr",
"glam 0.32.1",
"serde",
"slotmap",
]
[[package]]
name = "jackdaw_runtime"
version = "0.19.0"
dependencies = [
"avian3d",
"bevy",
"jackdaw_avian_integration",
"jackdaw_bsn",
"jackdaw_geometry",
"jackdaw_scene_types",
"jackdaw_schema",
"jackdaw_ui",
"serde",
"serde_json",
"thiserror 2.0.19",
]
[[package]]
name = "jackdaw_scene_types"
version = "0.19.0"
dependencies = [
"bevy",
"glam 0.32.1",
"jackdaw_geometry",
"rand 0.9.5",
"serde",
"serde_json",
]
[[package]]
name = "jackdaw_schema"
version = "0.19.0"
dependencies = [
"bevy",
"jackdaw_scene_types",
"serde",
"serde_json",
]
[[package]]
name = "jackdaw_ui"
version = "0.19.0"
dependencies = [
"bevy",
"bevy_scene",
]
[[package]] [[package]]
name = "jni" name = "jni"
version = "0.21.1" version = "0.21.1"
@@ -4427,15 +4230,6 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "keccak"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653"
dependencies = [
"cpufeatures 0.2.17",
]
[[package]] [[package]]
name = "khronos-egl" name = "khronos-egl"
version = "6.0.0" version = "6.0.0"
@@ -4494,37 +4288,6 @@ dependencies = [
"smallvec", "smallvec",
] ]
[[package]]
name = "lalrpop"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98a80a963123205c7157323c99611bc4abb65dcbd62ef46dc4bac74a3941bc75"
dependencies = [
"ascii-canvas",
"bit-set",
"ena",
"itertools 0.14.0",
"lalrpop-util",
"petgraph",
"pico-args",
"regex",
"regex-syntax",
"sha3",
"string_cache",
"term",
"unicode-xid",
"walkdir",
]
[[package]]
name = "lalrpop-util"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "884f3e747ed2dcee867cda1b0c31a048f9e20de2d916a248949319921a2e666e"
dependencies = [
"regex-automata",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.5.0" version = "1.5.0"
@@ -4831,12 +4594,6 @@ dependencies = [
"jni-sys 0.3.1", "jni-sys 0.3.1",
] ]
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]] [[package]]
name = "nix" name = "nix"
version = "0.31.3" version = "0.31.3"
@@ -4855,15 +4612,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "nonmax" name = "nonmax"
version = "0.5.5" version = "0.5.5"
@@ -5607,12 +5355,6 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e91099d4268b0e11973f036e885d652fb0b21fedcf69738c627f94db6a44f42" checksum = "1e91099d4268b0e11973f036e885d652fb0b21fedcf69738c627f94db6a44f42"
[[package]]
name = "pathdiff"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
[[package]] [[package]]
name = "peniko" name = "peniko"
version = "0.6.1" version = "0.6.1"
@@ -5645,21 +5387,6 @@ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]]
name = "phf_shared"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
dependencies = [
"siphasher",
]
[[package]]
name = "pico-args"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
[[package]] [[package]]
name = "pin-project" name = "pin-project"
version = "1.1.13" version = "1.1.13"
@@ -5817,12 +5544,6 @@ dependencies = [
"zerocopy", "zerocopy",
] ]
[[package]]
name = "precomputed-hash"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]] [[package]]
name = "presser" name = "presser"
version = "0.3.1" version = "0.3.1"
@@ -5930,20 +5651,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a"
dependencies = [ dependencies = [
"libc", "libc",
"rand_chacha 0.3.1", "rand_chacha",
"rand_core 0.6.4", "rand_core 0.6.4",
] ]
[[package]]
name = "rand"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.5",
]
[[package]] [[package]]
name = "rand" name = "rand"
version = "0.10.2" version = "0.10.2"
@@ -5964,16 +5675,6 @@ dependencies = [
"rand_core 0.6.4", "rand_core 0.6.4",
] ]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]] [[package]]
name = "rand_core" name = "rand_core"
version = "0.6.4" version = "0.6.4"
@@ -5983,15 +5684,6 @@ dependencies = [
"getrandom 0.2.17", "getrandom 0.2.17",
] ]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]] [[package]]
name = "rand_core" name = "rand_core"
version = "0.10.1" version = "0.10.1"
@@ -6219,19 +5911,6 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "ron"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db09040cc89e461f1a265139777a2bde7f8d8c67c4936f700c63ce3e2904d468"
dependencies = [
"base64 0.22.1",
"bitflags 2.13.1",
"serde",
"serde_derive",
"unicode-ident",
]
[[package]] [[package]]
name = "ron" name = "ron"
version = "0.12.2" version = "0.12.2"
@@ -6246,6 +5925,29 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "ron_asset_derive"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb312bdc83344894927694f5549e55c358a34d94c0d2262f241015413cb7cbb"
dependencies = [
"quote",
"syn 2.0.119",
]
[[package]]
name = "ron_asset_manager"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f08cf385fe993fb4002dcb90e39e0d081c49db07a5a96a40d631d88080602df3"
dependencies = [
"bevy",
"ron",
"ron_asset_derive",
"serde",
"thiserror 1.0.69",
]
[[package]] [[package]]
name = "rstar" name = "rstar"
version = "0.12.2" version = "0.12.2"
@@ -6390,6 +6092,12 @@ version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
[[package]]
name = "seq-macro"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.229" version = "1.0.229"
@@ -6442,16 +6150,6 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "sha3"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874"
dependencies = [
"digest",
"keccak",
]
[[package]] [[package]]
name = "sharded-slab" name = "sharded-slab"
version = "0.1.7" version = "0.1.7"
@@ -6461,6 +6159,37 @@ dependencies = [
"lazy_static", "lazy_static",
] ]
[[package]]
name = "shinespark"
version = "0.1.0"
dependencies = [
"arrayvec",
"avian3d",
"bevy",
"bevy-inspector-egui",
"bevy_asset_loader",
"bevy_egui",
"bevy_ggrs",
"bevy_wind_waker_shader",
"bincode",
"bitfields",
"clap",
"enum_cycling",
"enum_cycling_derive",
"fixed",
"fixed_math",
"gc-adapter-neo",
"gltf",
"rhai",
"ron",
"ron_asset_manager",
"serde",
"serde_json",
"strum",
"strum_macros",
"thiserror 2.0.19",
]
[[package]] [[package]]
name = "shlex" name = "shlex"
version = "2.0.1" version = "2.0.1"
@@ -6502,12 +6231,6 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "siphasher"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649"
[[package]] [[package]]
name = "skrifa" name = "skrifa"
version = "0.40.0" version = "0.40.0"
@@ -6558,9 +6281,6 @@ name = "smallvec"
version = "1.15.2" version = "1.15.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
dependencies = [
"serde",
]
[[package]] [[package]]
name = "smartstring" name = "smartstring"
@@ -6702,18 +6422,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
[[package]]
name = "string_cache"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
dependencies = [
"new_debug_unreachable",
"parking_lot",
"phf_shared",
"precomputed-hash",
]
[[package]] [[package]]
name = "strsim" name = "strsim"
version = "0.11.1" version = "0.11.1"
@@ -6845,15 +6553,6 @@ dependencies = [
"xattr", "xattr",
] ]
[[package]]
name = "term"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8c27177b12a6399ffc08b98f76f7c9a1f4fe9fc967c784c5a071fa8d93cf7e1"
dependencies = [
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "termcolor" name = "termcolor"
version = "1.4.1" version = "1.4.1"
+5 -12
View File
@@ -1,25 +1,17 @@
[package] [package]
name = "game-test" name = "shinespark"
version = "0.1.0" version = "0.1.0"
edition = "2024" edition = "2024"
authors = [""] authors = [""]
# A normal Bevy project. jackdaw builds its own editor artifacts in
# .jackdaw/ and never changes this manifest; `cargo run` works with or
# without the editor installed.
# Stand this project on its own even when it is created inside another
# cargo workspace, which would otherwise adopt it and refuse to build
# ("current package believes it's in a workspace when it's not").
# Delete this to make it a member of the surrounding workspace instead.
[workspace] [workspace]
[dependencies] [dependencies]
bevy = { version = "0.19", features = ["asset_processor", "dynamic_linking", "free_camera", "file_watcher", "bevy_settings"] } bevy = { version = "0.19", features = ["asset_processor", "basis-universal", "dynamic_linking", "free_camera", "file_watcher", "bevy_settings"] }
# Loads the scenes you author in the editor (assets/*.bsn) and builds # Loads the scenes you author in the editor (assets/*.bsn) and builds
# physics colliders from them. An ordinary dependency; remove it if you # physics colliders from them. An ordinary dependency; remove it if you
# stop using authored scenes. # stop using authored scenes.
jackdaw_runtime = { version = "0.19", features = ["physics"], path="../jackdaw/crates/jackdaw_runtime" } thiserror = "2"
avian3d = "0.7" avian3d = "0.7"
arrayvec = "0.7.8" arrayvec = "0.7.8"
bevy-inspector-egui = "0.37.0" bevy-inspector-egui = "0.37.0"
@@ -36,12 +28,13 @@ bevy_wind_waker_shader = { git = "https://github.com/lavaeater/bevy_wind_waker_s
fixed = { version = "1.31.0", features = ["serde", "serde-str"] } fixed = { version = "1.31.0", features = ["serde", "serde-str"] }
strum = "0.28.0" strum = "0.28.0"
strum_macros = "0.28.0" strum_macros = "0.28.0"
bevy_common_assets = { version = "0.17.0", features = ["ron"] }
bevy_asset_loader = "0.27.0" bevy_asset_loader = "0.27.0"
ron_asset_manager = "0.9.0"
gc-adapter-neo = { version = "1.0.0", features = ["libusb"] } gc-adapter-neo = { version = "1.0.0", features = ["libusb"] }
rhai = "1.26.0" rhai = "1.26.0"
enum_cycling = "0.2.1" enum_cycling = "0.2.1"
enum_cycling_derive = "0.2.1" enum_cycling_derive = "0.2.1"
fixed_math = "0.4.1"
# Enable a large amount of optimization in the dev profile for dependencies. # Enable a large amount of optimization in the dev profile for dependencies.
[profile.dev.package."*"] [profile.dev.package."*"]
Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

@@ -1,12 +1,12 @@
frame(3); frame(4);
hitbox(0, hitbox(0,
"Foot.L", "hand_l",
damage("5.0"), damage("5.0"),
vec3("0.0", "0.0", "0.0"), vec3("0.0", "0.0", "0.0"),
fg32("20.0"), fg32("5.0"),
angle_sakurai(), angle_sakurai(),
knockback_normal(), knockback_normal(),
knockback("10.0"), knockback("10.0"),
fg32("1.0") fg32("1.0")
); );
frame(6); frame(8);
@@ -0,0 +1,12 @@
frame(3);
hitbox(0,
"hand_l",
damage("5.0"),
vec3("0.0", "0.0", "0.0"),
fg32("5.0"),
angle(fg32("45.0")),
knockback_normal(),
knockback("18.0"),
fg32("140.0")
);
frame(8);
@@ -0,0 +1,13 @@
frame(9);
hitbox(0,
"hand_l",
damage("5.0"),
vec3("1.0", "0.0", "0.0"),
fg32("7.0"),
angle_sakurai(),
knockback_normal(),
knockback("10.0"),
fg32("1.0")
);
frame(15);
+188 -31
View File
@@ -1,37 +1,44 @@
( (
id: TestFighter, id: TestFighter,
model_path: "fighters/test/test-fighter-normal.glb", model_path: "fighters/test/test_fighter.gltf",
model_scale: "10.0",
baked_animation_path: "fighters/test/test.fighterbake", baked_animation_path: "fighters/test/test.fighterbake",
icon: (
path: "fighters/test/icon.png",
),
attributes: ( attributes: (
base_walk_accel: "0.1", base_walk_accel: "0.1",
stick_walk_accel: "0.16", stick_walk_accel: "0.16",
max_walk_vel: "0.7", max_walk_vel: "1.0",
ground_friction: "0.09", ground_friction: "0.1",
dash_acceleration_duration: 13, dash_acceleration_duration: 13,
dash_duration: 24, dash_duration: 24,
base_dash_accel: "0.02", base_dash_accel: "0.1",
stick_dash_accel: "0.065", stick_dash_accel: "0.05",
max_dash_vel: "1.1", max_dash_vel: "2.0",
short_hop_vertical_velocity: "1.05", short_hop_vertical_velocity: "1.45",
full_jump_vertical_velocity: "1.6", full_jump_vertical_velocity: "2.0",
jump_horizontal_velocity: "0.7", jump_horizontal_velocity: "0.6",
air_jump_horizontal_velocity: "0.5", air_jump_horizontal_velocity: "0.96",
air_jump_multiplier: "1.0", air_jump_multiplier: "1.0",
dash_initial_velocity: "1.4", dash_initial_velocity: "1.4",
terminal_velocity: "1.3", terminal_velocity: "1.6",
gravity: "0.064", gravity: "0.084",
weight: "100.0",
jumpsquat_duration: 5, jumpsquat_duration: 5,
landing_iasa: 4, landing_iasa: 4,
landing_duration: 30, landing_duration: 30,
max_air_horizontal_velocity: "1.35", max_air_horizontal_velocity: "2.5",
air_acceleration_base: "0.19", air_drift_max: "1.0",
air_acceleration_stick: "0.09", air_acceleration_base: "0.03",
air_friction: "0.05", air_acceleration_stick: "0.01",
air_friction: "0.01",
air_dodge_duration: 49, air_dodge_duration: 49,
air_dodge_velocity: "2.790", air_dodge_velocity: "2.790",
air_dodge_decay: "0.9" air_dodge_decay: "0.9",
ecb_vertical_midpoint_offset: "0.0"
), ),
camera: ( camera: (
vertical_origin_offset: "8.0", vertical_origin_offset: "8.0",
@@ -42,20 +49,170 @@
visibility_radius: "5.0", visibility_radius: "5.0",
), ),
animations: { animations: {
Wait: "PlyPurin5K_Share_ACTION_Wait", Wait: "Idle_Loop_Game",
Walk: "PlyPurin5K_Share_ACTION_WalkFast", Walk: "Walk_Loop_IK_Game",
Run: "PlyPurin5K_Share_ACTION_Run", Run: "Run_Game",
Dash: "PlyPurin5K_Share_ACTION_Dash", Dash: "Dash_Game",
JumpSquat: "PlyPurin5K_Share_ACTION_Landing", JumpSquat: "Jump_Squat_Game",
JumpForward: "PlyPurin5K_Share_ACTION_JumpF", JumpForward: "Jump_Start_IK_Game",
JumpBack: "PlyPurin5K_Share_ACTION_JumpB", JumpBack: "JumpB_Game",
Landing: "PlyPurin5K_Share_ACTION_Landing", LandingSpecial: "SpecialLand_Game",
AirDodge: "PlyPurin5K_Share_ACTION_EscapeAir", Landing: "Jump_Land_Game",
DoubleJump: "PlyPurin5K_Share_ACTION_JumpAerialF1", AirDodge: "Idle_Loop_Game",
Fall: "PlyPurin5K_Share_ACTION_Fall", DoubleJumpForward: "Jump_Start_IK_Game",
Turn: "PlyPurin5K_Share_ACTION_Turn", DoubleJumpBack: "JumpB_Game",
Fall: "Fall_Loop_Game",
Turn: "Turn_Game",
FlinchGround: "Air_Hit_Game",
FlinchAir: "Air_Hit_Game",
AttackJab1: "Punch_Jab_Game",
AttackUpTilt: "Idle_Loop_Game",
AttackForwardTilt: "Idle_Loop_Game",
AttackDownTilt: "Idle_Loop_Game"
}, },
attack_scripts: { attack_scripts: {
NAir: "fighters/test/scripts/fair.attack.rhai" NeutralAir: "fighters/test/scripts/fair.attack.rhai",
} Jab: "fighters/test/scripts/jab.attack.rhai",
UpTilt: "fighters/test/scripts/uptilt.attack.rhai",
ForwardTilt: "fighters/test/scripts/uptilt.attack.rhai",
DownTilt: "fighters/test/scripts/uptilt.attack.rhai",
},
hurtboxes: [
// center one
(
bone: "spine_01",
offset: (x: "0.0", y: "0.0", z: "0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.05",
radius: "0.15"
),
(
bone: "spine_03",
offset: (x: "0.0", y: "0.0", z: "0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.05",
radius: "0.15"
),
(
bone: "Head",
offset: (x: "0.0", y: "0.125", z: "0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.05",
radius: "0.1"
),
(
bone: "thigh_r",
offset: (x: "0.0", y: "0.15", z: "-0.01"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.2",
radius: "0.07"
),
(
bone: "thigh_l",
offset: (x: "0.0", y: "0.15", z: "-0.01"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.2",
radius: "0.07"
),
(
bone: "calf_l",
offset: (x: "0.0", y: "0.15", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.2",
radius: "0.05"
),
(
bone: "calf_r",
offset: (x: "0.0", y: "0.15", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.2",
radius: "0.05"
),
(
bone: "foot_r",
offset: (x: "0.0", y: "0.1", z: "0.01"),
rotation: FGVec3(x: "-25.0", y: "0.0", z: "0.0"),
half_length: "0.1",
radius: "0.04"
),
(
bone: "foot_l",
offset: (x: "0.0", y: "0.1", z: "0.01"),
rotation: FGVec3(x: "-25.0", y: "0.0", z: "0.0"),
half_length: "0.1",
radius: "0.04"
),
(
bone: "upperarm_l",
offset: (x: "0.0", y: "0.09", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.125",
radius: "0.05"
),
(
bone: "lowerarm_l",
offset: (x: "0.0", y: "0.12", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.115",
radius: "0.04"
),
(
bone: "hand_l",
offset: (x: "0.0", y: "0.05", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.01",
radius: "0.04"
),
(
bone: "upperarm_r",
offset: (x: "0.0", y: "0.09", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.125",
radius: "0.05"
),
(
bone: "lowerarm_r",
offset: (x: "0.0", y: "0.12", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.115",
radius: "0.04"
),
(
bone: "hand_r",
offset: (x: "0.0", y: "0.05", z: "-0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "0.0"),
half_length: "0.01",
radius: "0.04"
),
/*(
bone: "RFootJA",
offset: (x: "0.0", y: "0.5", z: "0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "90.0"),
half_length: "0.5",
radius: "1.0"
),
(
bone: "JOBJ_47",
offset: (x: "0.0", y: "0.0", z: "0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "90.0"),
half_length: "0.5",
radius: "1.0"
),
(
bone: "LFootJA",
offset: (x: "0.0", y: "0.5", z: "0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "90.0"),
half_length: "0.5",
radius: "1.0"
),
(
bone: "JOBJ_41",
offset: (x: "0.0", y: "0.0", z: "0.0"),
rotation: FGVec3(x: "0.0", y: "0.0", z: "90.0"),
half_length: "0.5",
radius: "1.0"
),*/
]
) )
Binary file not shown.
File diff suppressed because it is too large Load Diff
+84 -3
View File
@@ -1,4 +1,19 @@
( (
cursor: (
path: "ui/textures/cursor.png",
sampling: Nearest
),
css_token: (
path: "ui/textures/fighter_select_token.png",
sampling: Linear
),
player_colors: [
Srgba((red: 0.780, green: 0.420, blue: 0.933, alpha: 1.000)),
Srgba((red: 0.843, green: 0.227, blue: 0.204, alpha: 1.000)),
Srgba((red: 0.333, green: 0.804, blue: 0.078, alpha: 1.000)),
Srgba((red: 0.075, green: 0.376, blue: 0.416, alpha: 1.000)),
Srgba((red: 0.682, green: 0.878, blue: 0.914, alpha: 1.000))
],
button_styles: { button_styles: {
MainMenu: ( MainMenu: (
focus_outline_width_px: 4, focus_outline_width_px: 4,
@@ -24,8 +39,29 @@
) )
), ),
CharacterSelectCharacter: ( CharacterSelectCharacter: (
focus_outline_width_px: 4, focus_outline_width_px: 10,
focus_outline_offset_px: 2, focus_outline_offset_px: 5,
focus_outline_color: Srgba((red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0)),
normal: (
background_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
box_shadow: (),
border_size: 10,
),
press: (
background_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
box_shadow: (),
),
hover: (
background_color: Srgba((red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)),
text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
box_shadow: (),
)
),
CharacterSelectStartBanner: (
focus_outline_width_px: 10,
focus_outline_offset_px: 5,
focus_outline_color: Srgba((red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0)), focus_outline_color: Srgba((red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0)),
normal: ( normal: (
background_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)), background_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
@@ -42,6 +78,51 @@
text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)), text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
box_shadow: (), box_shadow: (),
) )
) ),
StageSelectIcon: (
focus_outline_width_px: 4,
focus_outline_offset_px: 2,
focus_outline_color: Srgba((red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0)),
normal: (
border_color: Srgba((red: 1.0, green: 1.0, blue: 0.0, alpha: 1.0)),
background_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 0.0)),
text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
border_size: 10,
border_radius: 40.0,
box_shadow: (
spread_radius: 5.0,
blur_radius: 5.0,
offset_px_y: 10,
offset_px_x: 10,
color: Srgba((red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0))
),
),
press: (
background_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
border_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
border_radius: 40.0,
border_size: 10,
box_shadow: (
spread_radius: 5.0,
offset_px_y: 10,
offset_px_x: 10,
color: Srgba((red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0))
),
),
hover: (
background_color: Srgba((red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)),
border_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
border_radius: 40.0,
border_size: 10,
text_color: Srgba((red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)),
box_shadow: (
spread_radius: 5.0,
offset_px_y: 10,
offset_px_x: 10,
color: Srgba((red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0))
),
)
),
} }
) )
+10 -5
View File
@@ -5,17 +5,22 @@
smash_input_reset_axis_threshold: "0.25", smash_input_reset_axis_threshold: "0.25",
smash_input_axis_threshold: "0.8", smash_input_axis_threshold: "0.8",
run_stick_threshold: "0.625", run_stick_threshold: "0.625",
smash_input_frame_threshold: 2, smash_input_frame_threshold: 3,
input_buffer_size: 5 input_buffer_size: 3,
turn_into_dashback_window: 2,
), ),
fighter_common: ( fighter_common: (
walk_speed_ease: "0.5", walk_speed_ease: "0.5",
ground_max_horizontal_velocity: "3.0", ground_max_horizontal_velocity: "3.0",
ground_friction_over_walk_speed_multiplier: "2.0" ground_friction_over_walk_speed_multiplier: "2.0",
knockback_stacking_window: 2,
knockback_decay_per_frame: "0.051",
knockback_launch_velocity_multiplier: "0.03",
hitstun_frames_per_unit_knockback: "0.4",
), ),
stage_manifest_paths: [ stage_manifest_paths: [
"stages/test.stage.ron" "stages/battlefield/test.stage.ron"
], ],
fighter_manifest_paths: [ fighter_manifest_paths: [
"fighters/test/test.fighter.ron" "fighters/test/test.fighter.ron"
Binary file not shown.
Binary file not shown.
+139
View File
@@ -0,0 +1,139 @@
(
id: TestStage,
model_path: "stages/battlefield/battlefield.glb#Scene0",
icon: (
path: "stages/battlefield/icon.png"
),
// Battlefield
/*camera: (
left: -200.0,
right: 200.0,
bottom: -59.0,
top: 170.0,
origin: (0.0, 44.0),
vertical_fov_degrees: 30.0,
min_depth: 83.0,
max_depth: 1000.0,
subject_scale: 1.5,
fighter_forward_extent_scale: 1.5,
tracking_smoothness: 1.8,
vertical_pan_degrees: -10.0,
horizontal_pan_degrees_per_unit: 0.1,
vertical_pan_degrees_per_unit: 0.1,
max_horizontal_pan_degrees: 17.5,
max_upward_pan_degrees: 5.0,
max_downward_pan_degrees: 7.0,
),*/
// Yoshi's story
/*camera: (
left: -180.0,
right: 179.0,
bottom: -71.0,
top: 169.0,
origin: (0.0, 44.0),
vertical_fov_degrees: 20.0,
min_depth: 100.0,
max_depth: 1000.0,
subject_scale: 1.0,
fighter_forward_extent_scale: 1.0,
tracking_smoothness: 1.0,
vertical_pan_degrees: -10.0,
horizontal_pan_degrees_per_unit: 0.05,
vertical_pan_degrees_per_unit: 0.15,
max_horizontal_pan_degrees: 17.5,
max_upward_pan_degrees: 5.0,
max_downward_pan_degrees: 7.0,
),*/
camera: (
left: -180.0,
right: 179.0,
bottom: -71.0,
top: 169.0,
origin: (0.0, 44.0),
vertical_fov_degrees: 20.0,
min_depth: 100.0,
max_depth: 1000.0,
subject_scale: 1.5,
fighter_forward_extent_scale: 1.0,
tracking_smoothness: 1.0,
vertical_pan_degrees: -10.0,
horizontal_pan_degrees_per_unit: 0.05,
vertical_pan_degrees_per_unit: 0.15,
max_horizontal_pan_degrees: 17.5,
max_upward_pan_degrees: 5.0,
max_downward_pan_degrees: 7.0,
),
polygons: [
(
poly_type: Platform,
lines: [
(
(x: "-20.0", y: "47.0"),
Floor
),
(
(x: "20.0", y: "47.0"),
Floor
)
]
),
(
poly_type: Platform,
lines: [
(
(x: "-65.0", y: "24.0"),
Floor
),
(
(x: "-25.0", y: "24.0"),
Floor
)
]
),
(
poly_type: Platform,
lines: [
(
(x: "25.0", y: "24.0"),
Floor
),
(
(x: "65.0", y: "24.0"),
Floor
)
]
),
(
poly_type: Closed,
lines: [
(
(x: "-68.0", y: "-3.0"),
Wall
),
(
(x: "-68.0", y: "0.0"),
Floor,
),
(
(x: "0.0", y: "0.0"),
Floor
),
(
(x: "68", y: "0.0"),
Wall
),
(
(x: "68.0", y: "-3.0"),
Ceiling
),
(
(x: "0.0", y: "-15.0"),
Ceiling
),
]
)
]
)
-84
View File
@@ -1,84 +0,0 @@
(
id: TestStage,
model_path: "stages/battlefield.glb#Scene0",
camera: (
left: -75.0,
right: 75.0,
bottom: -30.0,
top: 70.0,
origin: (0.0, 15.0),
vertical_fov_degrees: 30.0,
min_depth: 150.0,
max_depth: 400.0,
subject_scale: 1.0,
tracking_smoothness: 3.0,
vertical_tilt_degrees: 0.0,
horizontal_pan_coefficient: 0.0,
vertical_pan_coefficient: 0.0,
max_horizontal_pan_degrees: 17.5,
max_upward_pan_degrees: 5.0,
max_downward_pan_degrees: 7.0,
max_downward_expansion: 40.0,
),
polygons: [
(
poly_type: Platform,
lines: [
(
(x: "-59.5", y: "23.45"),
Floor
),
(
(x: "-28.0", y: "23.45"),
Floor
)
]
),
(
poly_type: Platform,
lines: [
(
(x: "28.0", y: "23.45"),
Floor
),
(
(x: "59.5", y: "23.45"),
Floor
)
]
),
(
poly_type: Closed,
lines: [
(
(x: "-56", y: "-200.0"),
Wall
),
(
(x: "-56.0", y: "-3.5"),
Floor,
),
(
(x: "-39.2", y: "0.0"),
Floor,
),
(
(x: "0.0", y: "0.0"),
Floor
),
(
(x: "39.2", y: "0.0"),
Floor
),
(
(x: "56.0", y: "-3.5"),
Wall
),
(
(x: "56", y: "-200.0"),
Wall
),
]
)
]
)
Binary file not shown.

After

Width:  |  Height:  |  Size: 871 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="128"
height="128"
viewBox="0 0 33.866666 33.866666"
version="1.1"
id="svg1"
inkscape:version="1.4.4 (dcaf3e7d9e, 2026-05-05)"
sodipodi:docname="cursor.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview1"
pagecolor="#000000"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:document-units="mm"
inkscape:zoom="5.6568542"
inkscape:cx="8.6620581"
inkscape:cy="67.086756"
inkscape:window-width="2560"
inkscape:window-height="1006"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="layer1" />
<defs
id="defs1">
<linearGradient
id="linearGradient1"
inkscape:collect="always">
<stop
style="stop-color:#949494;stop-opacity:1;"
offset="0"
id="stop1" />
<stop
style="stop-color:#6c6c6c;stop-opacity:1;"
offset="0.77473962"
id="stop3" />
<stop
style="stop-color:#9f9f9f;stop-opacity:1;"
offset="1"
id="stop2" />
</linearGradient>
<radialGradient
inkscape:collect="always"
xlink:href="#linearGradient1"
id="radialGradient2"
cx="16.933332"
cy="16.933332"
fx="16.933332"
fy="16.933332"
r="12.733072"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(1.2093771,0,0,1.2093771,-3.5454518,-3.5454518)" />
</defs>
<g
inkscape:label="Capa 1"
inkscape:groupmode="layer"
id="layer1">
<circle
style="fill:url(#radialGradient2);stroke-width:0.319981"
id="path1"
cx="16.933332"
cy="16.933332"
r="15.399086" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

+1 -1
View File
@@ -1,2 +1,2 @@
[toolchain] [toolchain]
channel = "nightly" channel = "nightly-2026-09-14"
+2
View File
@@ -5,6 +5,8 @@ use std::path::PathBuf;
#[derive(Parser, Debug, Clone, Resource)] #[derive(Parser, Debug, Clone, Resource)]
#[command(version, about, long_about = None)] #[command(version, about, long_about = None)]
pub struct Args { pub struct Args {
#[clap(long)]
pub debug_match: bool,
#[clap(long)] #[clap(long)]
pub synctest: bool, pub synctest: bool,
#[clap(long, default_value_t = 2)] #[clap(long, default_value_t = 2)]
+372 -121
View File
@@ -3,15 +3,18 @@
use std::{collections::HashMap, time::Duration}; use std::{collections::HashMap, time::Duration};
use bevy::{ use bevy::{
input::InputSystems,
prelude::*, prelude::*,
settings::{ReflectSettingsGroup, SaveSettingsDeferred, SettingsGroup}, settings::{ReflectSettingsGroup, SaveSettingsDeferred, SettingsGroup},
}; };
use bevy_egui::{EguiContexts, EguiPrimaryContextPass, egui}; use bevy_egui::{EguiContexts, EguiPrimaryContextPass, egui};
use bevy_ggrs::RollbackFrameRate; use bevy_ggrs::{RollbackFrameRate, RunGgrsSystems};
use enum_cycling::EnumCycle; use enum_cycling::EnumCycle;
use enum_cycling_derive::EnumCycle; use enum_cycling_derive::EnumCycle;
use crate::{player::Player, replay::StopReplayRecording, AppState}; use crate::{AppState, player::Player, replay::StopReplayRecording};
mod save_state;
pub const PLAYER_DEBUG_ROW_COUNT: usize = 6; pub const PLAYER_DEBUG_ROW_COUNT: usize = 6;
@@ -48,7 +51,7 @@ impl PresentationMotionMode {
} }
} }
#[derive(EnumCycle, Reflect)] #[derive(Clone, Copy, Debug, PartialEq, Eq, EnumCycle, Reflect)]
pub enum GameSpeedDebug { pub enum GameSpeedDebug {
Full, Full,
Half, Half,
@@ -114,6 +117,7 @@ enum DebugFlag {
Hurtboxes, Hurtboxes,
Camera, Camera,
DrawThroughGeometry, DrawThroughGeometry,
FrameStepping,
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -174,6 +178,10 @@ const WORLD_MENU: &[DebugMenuEntry] = &[
DebugMenuEntry::GameSpeed { DebugMenuEntry::GameSpeed {
label: "Game speed", label: "Game speed",
}, },
DebugMenuEntry::Toggle {
label: "Frame stepping",
flag: DebugFlag::FrameStepping,
},
]; ];
const DIAGNOSTICS_MENU: &[DebugMenuEntry] = &[DebugMenuEntry::Toggle { const DIAGNOSTICS_MENU: &[DebugMenuEntry] = &[DebugMenuEntry::Toggle {
@@ -233,6 +241,8 @@ pub struct DebugSettings {
selections: Vec<usize>, selections: Vec<usize>,
#[reflect(ignore)] #[reflect(ignore)]
pub player_rows: HashMap<usize, [FighterDebugRowKind; PLAYER_DEBUG_ROW_COUNT]>, pub player_rows: HashMap<usize, [FighterDebugRowKind; PLAYER_DEBUG_ROW_COUNT]>,
#[reflect(ignore)]
pub frame_stepping: bool,
pub network: bool, pub network: bool,
pub ecb: bool, pub ecb: bool,
pub stage_collision: bool, pub stage_collision: bool,
@@ -253,6 +263,7 @@ impl Default for DebugSettings {
pages: vec![DebugMenuPage::Static(ROOT_MENU)], pages: vec![DebugMenuPage::Static(ROOT_MENU)],
selections: vec![0], selections: vec![0],
player_rows: HashMap::new(), player_rows: HashMap::new(),
frame_stepping: false,
network: false, network: false,
ecb: false, ecb: false,
stage_collision: false, stage_collision: false,
@@ -325,6 +336,7 @@ impl DebugSettings {
DebugFlag::Hurtboxes => self.hurtboxes, DebugFlag::Hurtboxes => self.hurtboxes,
DebugFlag::DrawThroughGeometry => self.draw_through_geometry, DebugFlag::DrawThroughGeometry => self.draw_through_geometry,
DebugFlag::Camera => self.camera, DebugFlag::Camera => self.camera,
DebugFlag::FrameStepping => self.frame_stepping,
} }
} }
@@ -340,6 +352,7 @@ impl DebugSettings {
self.draw_through_geometry = !self.draw_through_geometry self.draw_through_geometry = !self.draw_through_geometry
} }
DebugFlag::Camera => self.camera = !self.camera, DebugFlag::Camera => self.camera = !self.camera,
DebugFlag::FrameStepping => self.frame_stepping = !self.frame_stepping,
} }
} }
@@ -347,10 +360,6 @@ impl DebugSettings {
self.motion_sampling.cycle(); self.motion_sampling.cycle();
} }
fn cycle_game_speed(&mut self) {
self.motion_sampling.cycle();
}
fn rows_mut(&mut self, handle: usize) -> &mut [FighterDebugRowKind; PLAYER_DEBUG_ROW_COUNT] { fn rows_mut(&mut self, handle: usize) -> &mut [FighterDebugRowKind; PLAYER_DEBUG_ROW_COUNT] {
self.player_rows self.player_rows
.entry(handle) .entry(handle)
@@ -360,9 +369,35 @@ impl DebugSettings {
pub struct DebugToolsPlugin; pub struct DebugToolsPlugin;
#[derive(Resource, Default)]
struct FrameStepState {
requested: bool,
time_backup: Option<Time>,
last_step_time: Time
}
impl Plugin for DebugToolsPlugin { impl Plugin for DebugToolsPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.init_resource::<DebugSettings>() app.init_resource::<DebugSettings>()
.init_resource::<FrameStepState>()
.init_resource::<save_state::DebugSaveState>()
.add_systems(OnEnter(AppState::InMatch), save_state::clear)
.add_systems(OnExit(AppState::InMatch), save_state::clear)
.add_systems(
PreUpdate,
prepare_frame_step
.after(InputSystems)
.before(RunGgrsSystems)
.run_if(in_state(AppState::InMatch)),
)
.add_systems(
PreUpdate,
save_state::save_or_restore
.after(InputSystems)
.before(RunGgrsSystems)
.run_if(in_state(AppState::InMatch)),
)
.add_systems(PreUpdate, restore_frame_step_time.after(RunGgrsSystems))
.add_systems( .add_systems(
Update, Update,
(handle_palette_input, sync_gizmo_depth_bias) (handle_palette_input, sync_gizmo_depth_bias)
@@ -391,6 +426,141 @@ fn page_len(page: DebugMenuPage, player_handles: &[usize]) -> usize {
} }
} }
fn queue_settings_save(commands: &mut Commands) {
commands.queue(SaveSettingsDeferred(Duration::from_secs_f32(0.1)));
}
fn frame_step_duration(frame_rate: usize) -> Duration {
Duration::from_nanos(1_000_000_000u64 / frame_rate as u64)
}
fn prepare_frame_step(
settings: Res<DebugSettings>,
gamepads: Query<&Gamepad>,
key: Res<ButtonInput<KeyCode>>,
mut state: ResMut<FrameStepState>,
mut time: ResMut<Time>,
frame_rate: Res<RollbackFrameRate>,
) {
if !settings.frame_stepping {
state.requested = false;
return;
}
let pressed = gamepads
.iter()
.any(|gamepad| gamepad.pressed(GamepadButton::DPadDown));
let just_pressed = gamepads
.iter()
.any(|gamepad| gamepad.just_pressed(GamepadButton::DPadDown));
let just_pressed = key.just_pressed(KeyCode::F4) || just_pressed;
let pressed = key.pressed(KeyCode::F4) || pressed;
if just_pressed {
state.last_step_time = time.clone();
}
let can_repress = pressed && (time.elapsed() - state.last_step_time.elapsed()).as_millis() > 500;
if !settings.menu_open && (just_pressed || can_repress)
{
state.requested = true;
}
state.time_backup = Some(*time);
let delta = if state.requested {
frame_step_duration(**frame_rate)
} else {
Duration::ZERO
};
time.advance_by(delta);
}
fn restore_frame_step_time(mut state: ResMut<FrameStepState>, mut time: ResMut<Time>) {
if let Some(backup) = state.time_backup.take() {
*time = backup;
state.requested = false;
}
}
fn activate_selected(
settings: &mut DebugSettings,
page_len: usize,
player_handles: &[usize],
commands: &mut Commands,
) {
if page_len == 0 {
return;
}
match settings.page() {
DebugMenuPage::Static(entries) => match entries[settings.selected()] {
DebugMenuEntry::StopRecording { .. } => {
commands.insert_resource(StopReplayRecording);
}
DebugMenuEntry::Toggle { flag, .. } => {
settings.toggle_flag(flag);
if !matches!(flag, DebugFlag::FrameStepping) {
queue_settings_save(commands);
}
}
DebugMenuEntry::Submenu { entries, .. } => {
settings.push_page(DebugMenuPage::Static(entries));
}
DebugMenuEntry::PlayerSlots { .. } => settings.push_page(DebugMenuPage::PlayerList),
DebugMenuEntry::MotionSampling { .. } => {
settings.cycle_motion_sampling();
queue_settings_save(commands);
}
DebugMenuEntry::GameSpeed { .. } => {
commands.insert_resource(RollbackFrameRate(settings.game_speed.frame_rate()));
queue_settings_save(commands);
}
},
DebugMenuPage::PlayerList => {
let handle = player_handles[settings.selected()];
settings.rows_mut(handle);
settings.push_page(DebugMenuPage::PlayerRows(handle));
}
DebugMenuPage::PlayerRows(_) => {}
}
}
fn cycle_selected_value(settings: &mut DebugSettings, direction: i8, commands: &mut Commands) {
match settings.page() {
DebugMenuPage::Static(entries) => {
if let Some(entry) = entries.get(settings.selected()) {
match entry {
DebugMenuEntry::MotionSampling { .. } => {
settings.cycle_motion_sampling();
queue_settings_save(commands);
}
DebugMenuEntry::GameSpeed { .. } => {
settings.game_speed = if direction > 0 {
settings.game_speed.up()
} else {
settings.game_speed.down()
};
commands
.insert_resource(RollbackFrameRate(settings.game_speed.frame_rate()));
queue_settings_save(commands);
}
_ => {}
}
}
}
DebugMenuPage::PlayerRows(handle) => {
let selected = settings.selected();
let rows = settings.rows_mut(handle);
rows[selected] = rows[selected].cycle(direction);
queue_settings_save(commands);
}
DebugMenuPage::PlayerList => {}
}
}
fn handle_palette_input( fn handle_palette_input(
keyboard: Res<ButtonInput<KeyCode>>, keyboard: Res<ButtonInput<KeyCode>>,
gamepads: Query<(Entity, &Gamepad)>, gamepads: Query<(Entity, &Gamepad)>,
@@ -402,6 +572,15 @@ fn handle_palette_input(
settings.toggle_flag(DebugFlag::DrawThroughGeometry); settings.toggle_flag(DebugFlag::DrawThroughGeometry);
} }
if keyboard.just_pressed(KeyCode::F3) {
settings.menu_open = !settings.menu_open;
settings.controller = None;
if settings.menu_open {
settings.reset_navigation();
}
return;
}
if !settings.menu_open { if !settings.menu_open {
for (entity, gamepad) in &gamepads { for (entity, gamepad) in &gamepads {
if gamepad.just_pressed(GamepadButton::Start) && gamepad.pressed(GamepadButton::DPadUp) if gamepad.just_pressed(GamepadButton::Start) && gamepad.pressed(GamepadButton::DPadUp)
@@ -415,14 +594,15 @@ fn handle_palette_input(
return; return;
} }
let Some(controller) = settings.controller else { let gamepad = if let Some(controller) = settings.controller {
settings.menu_open = false; let Ok((_, gamepad)) = gamepads.get(controller) else {
return; settings.menu_open = false;
}; settings.controller = None;
let Ok((_, gamepad)) = gamepads.get(controller) else { return;
settings.menu_open = false; };
settings.controller = None; Some(gamepad)
return; } else {
None
}; };
let player_handles = player_handles(&players); let player_handles = player_handles(&players);
let page = settings.page(); let page = settings.page();
@@ -432,95 +612,51 @@ fn handle_palette_input(
*settings.selected_mut() = 0; *settings.selected_mut() = 0;
} }
if gamepad.just_pressed(GamepadButton::DPadUp) && page_len != 0 { if (gamepad.is_some_and(|pad| pad.just_pressed(GamepadButton::DPadUp))
|| keyboard.just_pressed(KeyCode::ArrowUp)
|| keyboard.just_pressed(KeyCode::KeyW))
&& page_len != 0
{
let selected = settings.selected_mut(); let selected = settings.selected_mut();
*selected = selected.checked_sub(1).unwrap_or(page_len - 1); *selected = selected.checked_sub(1).unwrap_or(page_len - 1);
} }
if gamepad.just_pressed(GamepadButton::DPadDown) && page_len != 0 { if (gamepad.is_some_and(|pad| pad.just_pressed(GamepadButton::DPadDown))
|| keyboard.just_pressed(KeyCode::ArrowDown)
|| keyboard.just_pressed(KeyCode::KeyS))
&& page_len != 0
{
let selected = settings.selected_mut(); let selected = settings.selected_mut();
*selected = (*selected + 1) % page_len; *selected = (*selected + 1) % page_len;
} }
let direction = if gamepad.just_pressed(GamepadButton::DPadLeft) { let direction = if gamepad.is_some_and(|pad| pad.just_pressed(GamepadButton::DPadLeft))
|| keyboard.just_pressed(KeyCode::ArrowLeft)
|| keyboard.just_pressed(KeyCode::KeyA)
{
Some(-1) Some(-1)
} else if gamepad.just_pressed(GamepadButton::DPadRight) { } else if gamepad.is_some_and(|pad| pad.just_pressed(GamepadButton::DPadRight))
|| keyboard.just_pressed(KeyCode::ArrowRight)
|| keyboard.just_pressed(KeyCode::KeyD)
{
Some(1) Some(1)
} else { } else {
None None
}; };
if let Some(direction) = direction { if let Some(direction) = direction {
match page { cycle_selected_value(&mut settings, direction, &mut commands);
DebugMenuPage::Static(entries) => {
if let Some(entry) = entries.get(settings.selected()) {
match entry {
DebugMenuEntry::StopRecording { .. } => {}
DebugMenuEntry::MotionSampling { .. } => settings.cycle_motion_sampling(),
DebugMenuEntry::GameSpeed { .. } => {
if direction > 0 {
settings.game_speed = settings.game_speed.up();
} else {
settings.game_speed = settings.game_speed.down();
}
commands.insert_resource(RollbackFrameRate(
settings.game_speed.frame_rate(),
));
}
_ => {}
}
}
}
DebugMenuPage::PlayerList => todo!(),
DebugMenuPage::PlayerRows(_) => {
let DebugMenuPage::PlayerRows(handle) = page else {
unreachable!("player row navigation must have a player row page")
};
let selected = settings.selected();
let rows = settings.rows_mut(handle);
rows[selected] = rows[selected].cycle(direction);
commands.queue(SaveSettingsDeferred(Duration::from_secs_f32(0.1)));
}
}
} }
if (gamepad.is_some_and(|pad| pad.just_pressed(GamepadButton::South))
if matches!(page, DebugMenuPage::PlayerRows(_)) { || keyboard.just_pressed(KeyCode::Enter)
let direction = if gamepad.just_pressed(GamepadButton::DPadLeft) { || keyboard.just_pressed(KeyCode::Space))
Some(-1) && page_len != 0
} else if gamepad.just_pressed(GamepadButton::DPadRight) { {
Some(1) activate_selected(&mut settings, page_len, &player_handles, &mut commands);
} else {
None
};
if let Some(direction) = direction {}
} }
if gamepad.just_pressed(GamepadButton::South) { if (gamepad.is_some_and(|pad| pad.just_pressed(GamepadButton::West))
match page { || keyboard.just_pressed(KeyCode::Escape))
DebugMenuPage::Static(entries) if page_len != 0 => match entries[settings.selected()] { && !settings.pop_page()
DebugMenuEntry::StopRecording { .. } => { {
commands.insert_resource(StopReplayRecording);
}
DebugMenuEntry::Toggle { flag, .. } => {
settings.toggle_flag(flag);
commands.queue(SaveSettingsDeferred(Duration::from_secs_f32(0.1)));
}
DebugMenuEntry::Submenu { entries, .. } => {
settings.push_page(DebugMenuPage::Static(entries));
}
DebugMenuEntry::PlayerSlots { .. } => settings.push_page(DebugMenuPage::PlayerList),
DebugMenuEntry::MotionSampling { .. } => settings.cycle_motion_sampling(),
DebugMenuEntry::GameSpeed { .. } => {}
},
DebugMenuPage::PlayerList if page_len != 0 => {
let handle = player_handles[settings.selected()];
settings.rows_mut(handle);
settings.push_page(DebugMenuPage::PlayerRows(handle));
}
_ => {}
}
}
if gamepad.just_pressed(GamepadButton::West) && !settings.pop_page() {
settings.menu_open = false; settings.menu_open = false;
settings.controller = None; settings.controller = None;
} }
@@ -542,8 +678,9 @@ fn sync_gizmo_depth_bias(settings: Res<DebugSettings>, mut configs: ResMut<Gizmo
fn draw_palette( fn draw_palette(
mut contexts: EguiContexts, mut contexts: EguiContexts,
settings: Res<DebugSettings>, mut settings: ResMut<DebugSettings>,
players: Query<&Player>, players: Query<&Player>,
mut commands: Commands,
) -> Result { ) -> Result {
if !settings.menu_open { if !settings.menu_open {
return Ok(()); return Ok(());
@@ -551,7 +688,7 @@ fn draw_palette(
let player_handles = player_handles(&players); let player_handles = player_handles(&players);
let page = settings.page(); let page = settings.page();
let selected = settings.selected(); let page_len = page_len(page, &player_handles);
egui::Window::new("Debug") egui::Window::new("Debug")
.anchor(egui::Align2::RIGHT_TOP, egui::vec2(-12.0, 12.0)) .anchor(egui::Align2::RIGHT_TOP, egui::vec2(-12.0, 12.0))
.resizable(false) .resizable(false)
@@ -560,38 +697,113 @@ fn draw_palette(
match page { match page {
DebugMenuPage::Static(entries) => { DebugMenuPage::Static(entries) => {
for (index, entry) in entries.iter().enumerate() { for (index, entry) in entries.iter().enumerate() {
let marker = if index == selected { ">" } else { " " }; ui.horizontal(|ui| {
match entry { ui.label(if index == settings.selected() {
DebugMenuEntry::StopRecording { label } => { ">"
ui.label(format!("{marker} {label}")); } else {
" "
});
match entry {
DebugMenuEntry::StopRecording { label } => {
if ui.button(*label).clicked() {
*settings.selected_mut() = index;
activate_selected(
&mut settings,
page_len,
&player_handles,
&mut commands,
);
}
}
DebugMenuEntry::Toggle { label, flag } => {
let mut value = settings.flag(*flag);
if ui.checkbox(&mut value, *label).changed() {
settings.toggle_flag(*flag);
if !matches!(flag, DebugFlag::FrameStepping) {
queue_settings_save(&mut commands);
}
}
}
DebugMenuEntry::Submenu { label, .. }
| DebugMenuEntry::PlayerSlots { label } => {
if ui.button(format!("{label} >")).clicked() {
*settings.selected_mut() = index;
activate_selected(
&mut settings,
page_len,
&player_handles,
&mut commands,
);
}
}
DebugMenuEntry::MotionSampling { label } => {
let old = settings.motion_sampling;
egui::ComboBox::from_id_salt(("debug-motion", index))
.width(180.0)
.selected_text(format!("{label}: {}", old.label()))
.show_ui(ui, |ui| {
ui.selectable_value(
&mut settings.motion_sampling,
PresentationMotionMode::Interpolation,
"Interpolation",
);
ui.selectable_value(
&mut settings.motion_sampling,
PresentationMotionMode::Extrapolation,
"Extrapolation",
);
});
if settings.motion_sampling != old {
queue_settings_save(&mut commands);
}
}
DebugMenuEntry::GameSpeed { label } => {
let old = settings.game_speed;
egui::ComboBox::from_id_salt(("debug-speed", index))
.width(180.0)
.selected_text(format!("{label}: {}", old.label()))
.show_ui(ui, |ui| {
for speed in [
GameSpeedDebug::Full,
GameSpeedDebug::Half,
GameSpeedDebug::Quarter,
] {
ui.selectable_value(
&mut settings.game_speed,
speed,
speed.label(),
);
}
});
if settings.game_speed != old {
commands.insert_resource(RollbackFrameRate(
settings.game_speed.frame_rate(),
));
queue_settings_save(&mut commands);
}
}
} }
DebugMenuEntry::Toggle { label, flag } => { });
let state = if settings.flag(*flag) { "on" } else { "off" };
ui.label(format!("{marker} {label}: {state}"));
}
DebugMenuEntry::Submenu { label, .. }
| DebugMenuEntry::PlayerSlots { label } => {
ui.label(format!("{marker} {label} >"));
}
DebugMenuEntry::MotionSampling { label } => {
ui.label(format!(
"{marker} {label}: {}",
settings.motion_sampling.label()
));
}
DebugMenuEntry::GameSpeed { label } => {
ui.label(format!(
"{marker} {label}: {}",
settings.game_speed.label()
));
}
}
} }
} }
DebugMenuPage::PlayerList => { DebugMenuPage::PlayerList => {
for (index, handle) in player_handles.iter().enumerate() { for (index, handle) in player_handles.iter().enumerate() {
let marker = if index == selected { ">" } else { " " }; ui.horizontal(|ui| {
ui.label(format!("{marker} Player {} >", handle + 1)); ui.label(if index == settings.selected() {
">"
} else {
" "
});
if ui.button(format!("Player {} >", handle + 1)).clicked() {
*settings.selected_mut() = index;
activate_selected(
&mut settings,
page_len,
&player_handles,
&mut commands,
);
}
});
} }
if player_handles.is_empty() { if player_handles.is_empty() {
ui.label("No players in match"); ui.label("No players in match");
@@ -604,16 +816,30 @@ fn draw_palette(
.unwrap_or([FighterDebugRowKind::None; PLAYER_DEBUG_ROW_COUNT]); .unwrap_or([FighterDebugRowKind::None; PLAYER_DEBUG_ROW_COUNT]);
ui.label(format!("Player {}", handle + 1)); ui.label(format!("Player {}", handle + 1));
for (index, row) in rows.iter().enumerate() { for (index, row) in rows.iter().enumerate() {
let marker = if index == selected { ">" } else { " " }; ui.horizontal(|ui| {
ui.label(format!("{marker} Row {}: {}", index + 1, row.label())); ui.label(if index == settings.selected() {
">"
} else {
" "
});
egui::ComboBox::from_id_salt(("debug-row", handle, index))
.width(180.0)
.selected_text(format!("Row {}: {}", index + 1, row.label()))
.show_ui(ui, |ui| {
let rows = settings.rows_mut(handle);
for kind in FighterDebugRowKind::ALL {
ui.selectable_value(&mut rows[index], kind, kind.label());
}
});
});
} }
} }
} }
ui.separator(); ui.separator();
let controls = if matches!(page, DebugMenuPage::PlayerRows(_)) { let controls = if matches!(page, DebugMenuPage::PlayerRows(_)) {
"D-pad: select/change B: back" "Arrows/WASD: select/change Escape/B: back"
} else { } else {
"D-pad: select A: enter/toggle Left/right: change B: back" "Arrows/WASD: select Enter/A: activate Escape/B: back"
}; };
ui.label(controls); ui.label(controls);
}); });
@@ -703,4 +929,29 @@ mod tests {
mode.cycle(); mode.cycle();
assert_eq!(mode, PresentationMotionMode::Interpolation); assert_eq!(mode, PresentationMotionMode::Interpolation);
} }
#[test]
fn game_speed_has_expected_frame_rates() {
assert_eq!(GameSpeedDebug::Full.frame_rate(), 60);
assert_eq!(GameSpeedDebug::Half.frame_rate(), 30);
assert_eq!(GameSpeedDebug::Quarter.frame_rate(), 15);
}
#[test]
fn frame_stepping_is_disabled_by_default_and_uses_game_speed_timestep() {
let settings = DebugSettings::default();
assert!(!settings.frame_stepping);
assert_eq!(frame_step_duration(60), Duration::from_nanos(16_666_666));
assert_eq!(frame_step_duration(30), Duration::from_nanos(33_333_333));
}
#[test]
fn empty_player_list_does_not_activate() {
let mut settings = DebugSettings::default();
settings.push_page(DebugMenuPage::PlayerList);
assert_eq!(page_len(settings.page(), &[]), 0);
assert_eq!(settings.selected(), 0);
}
} }
+196
View File
@@ -0,0 +1,196 @@
use bevy::prelude::*;
use crate::{
camera::MatchCamera,
fighter::{
FighterECB, FighterFacingDirection, FighterHitboxes, FighterHitstop,
FighterPreviousFacingDirection, FighterPreviousTranslation, FighterTranslation,
FighterVelocity, Grounded,
animation::FighterAnimationFrame,
attack::{
FighterDamage, FighterKnockbackVelocity, FighterPendingHitReaction,
FighterReceivedAttacks, FighterSolvedHurtboxes, FighterStaleMoveQueue,
},
baked_animation::FighterBoneMatrices,
state::FighterState,
},
input::FighterInput,
player::Player,
stage::line::StageCollision,
};
#[derive(Resource, Default)]
pub(super) struct DebugSaveState {
checkpoint: Option<Checkpoint>,
}
#[derive(Clone)]
struct Checkpoint {
fighters: Vec<FighterCheckpoint>,
stage_collision: StageCollision,
}
#[derive(Clone)]
struct FighterCheckpoint {
entity: Entity,
handle: usize,
ecb: FighterECB,
previous_ecb: crate::fighter::ecb::FighterPreviousECB,
velocity: FighterVelocity,
translation: FighterTranslation,
previous_translation: FighterPreviousTranslation,
facing: FighterFacingDirection,
previous_facing: FighterPreviousFacingDirection,
animation: FighterAnimationFrame,
state: FighterState,
input: FighterInput,
damage: FighterDamage,
pending_hit_reaction: FighterPendingHitReaction,
hitstop: FighterHitstop,
knockback_velocity: FighterKnockbackVelocity,
stale_moves: FighterStaleMoveQueue,
hitboxes: FighterHitboxes,
received_attacks: FighterReceivedAttacks,
solved_hurtboxes: FighterSolvedHurtboxes,
bone_matrices: FighterBoneMatrices,
grounded: bool,
}
pub(super) fn save_or_restore(world: &mut World) {
if world.resource::<super::DebugSettings>().menu_open {
return;
}
let left = world
.query::<&Gamepad>()
.iter(world)
.any(|gamepad| gamepad.just_pressed(GamepadButton::DPadLeft));
let right = world
.query::<&Gamepad>()
.iter(world)
.any(|gamepad| gamepad.just_pressed(GamepadButton::DPadRight));
if left == right {
return;
}
let Some(roster) = world
.get_resource::<crate::fighter::FighterRoster>()
.map(|roster| roster.0.clone())
else {
return;
};
if roster.len() != 1 {
warn!("Save states are only available in single-player matches");
return;
}
if left {
let Some(stage_collision) = world.get_resource::<StageCollision>().cloned() else {
return;
};
let mut checkpoint_fighters = Vec::with_capacity(roster.len());
for entity in roster.iter().copied() {
let Some(checkpoint) = capture_fighter(world, entity) else {
warn!("Could not save the current fighter state");
return;
};
checkpoint_fighters.push(checkpoint);
}
world.resource_mut::<DebugSaveState>().checkpoint = Some(Checkpoint {
fighters: checkpoint_fighters,
stage_collision,
});
info!("Saved debug game state");
return;
}
let Some(checkpoint) = world.resource::<DebugSaveState>().checkpoint.clone() else {
warn!("No debug game state has been saved");
return;
};
if checkpoint.fighters.len() != roster.len()
|| checkpoint
.fighters
.iter()
.zip(roster.iter())
.any(|(saved, current)| saved.entity != *current)
{
warn!("Saved debug game state belongs to another match");
return;
}
for saved in &checkpoint.fighters {
let Some(player) = world.entity(saved.entity).get::<Player>() else {
warn!("Could not restore the saved fighter state");
return;
};
if player.handle != saved.handle {
warn!("Saved debug game state belongs to another match");
return;
}
let mut entity = world.entity_mut(saved.entity);
entity.insert(saved.ecb);
entity.insert(saved.previous_ecb);
entity.insert(saved.velocity);
entity.insert(saved.translation);
entity.insert(saved.previous_translation);
entity.insert(saved.facing);
entity.insert(saved.previous_facing);
entity.insert(saved.animation);
entity.insert(saved.state.clone());
entity.insert(saved.input);
entity.insert(saved.damage);
entity.insert(saved.pending_hit_reaction.clone());
entity.insert(saved.hitstop);
entity.insert(saved.knockback_velocity);
entity.insert(saved.stale_moves.clone());
entity.insert(saved.hitboxes.clone());
entity.insert(saved.received_attacks.clone());
entity.insert(saved.solved_hurtboxes.clone());
entity.insert(saved.bone_matrices.clone());
if saved.grounded {
entity.insert(Grounded);
} else {
entity.remove::<Grounded>();
}
}
world.insert_resource(checkpoint.stage_collision);
for mut match_camera in world.query::<&mut MatchCamera>().iter_mut(world) {
match_camera.needs_snap = true;
}
info!("Restored debug game state");
}
fn capture_fighter(world: &World, entity: Entity) -> Option<FighterCheckpoint> {
let fighter = world.entity(entity);
Some(FighterCheckpoint {
entity,
handle: fighter.get::<Player>()?.handle,
ecb: *fighter.get::<FighterECB>()?,
previous_ecb: *fighter.get::<crate::fighter::ecb::FighterPreviousECB>()?,
velocity: *fighter.get::<FighterVelocity>()?,
translation: *fighter.get::<FighterTranslation>()?,
previous_translation: *fighter.get::<FighterPreviousTranslation>()?,
facing: *fighter.get::<FighterFacingDirection>()?,
previous_facing: *fighter.get::<FighterPreviousFacingDirection>()?,
animation: *fighter.get::<FighterAnimationFrame>()?,
state: fighter.get::<FighterState>()?.clone(),
input: *fighter.get::<FighterInput>()?,
damage: *fighter.get::<FighterDamage>()?,
pending_hit_reaction: fighter.get::<FighterPendingHitReaction>()?.clone(),
hitstop: *fighter.get::<FighterHitstop>()?,
knockback_velocity: *fighter.get::<FighterKnockbackVelocity>()?,
stale_moves: fighter.get::<FighterStaleMoveQueue>()?.clone(),
hitboxes: fighter.get::<FighterHitboxes>()?.clone(),
received_attacks: fighter.get::<FighterReceivedAttacks>()?.clone(),
solved_hurtboxes: fighter.get::<FighterSolvedHurtboxes>()?.clone(),
bone_matrices: fighter.get::<FighterBoneMatrices>()?.clone(),
grounded: fighter.contains::<Grounded>(),
})
}
pub(super) fn clear(mut save_state: ResMut<DebugSaveState>) {
save_state.checkpoint = None;
}
+15 -7
View File
@@ -1,7 +1,7 @@
use bevy::prelude::*; use bevy::prelude::*;
use strum_macros::EnumIter; use strum_macros::EnumIter;
use crate::fighter::{FighterFacingDirection, FighterVisual}; use crate::fighter::{FighterFacingDirection, FighterHitstop, FighterVisual};
/// The simulation-owned animation clock. Rendering may interpolate freely, but /// The simulation-owned animation clock. Rendering may interpolate freely, but
/// gameplay samples baked data only with this rollback-tracked value. /// gameplay samples baked data only with this rollback-tracked value.
@@ -32,9 +32,13 @@ impl FighterAnimationFrame {
} }
} }
pub fn advance_fighter_animation_frames(mut fighters: Query<&mut FighterAnimationFrame>) { pub fn advance_fighter_animation_frames(
for mut animation in &mut fighters { mut fighters: Query<(&mut FighterAnimationFrame, &FighterHitstop)>,
animation.advance(); ) {
for (mut animation, hitstop) in &mut fighters {
if hitstop.remaining_frames == 0 {
animation.advance();
}
} }
} }
@@ -49,7 +53,6 @@ pub fn apply_animation(
>, >,
) { ) {
for (mut trf, facing_direction, frame) in children { for (mut trf, facing_direction, frame) in children {
// Melee model scale is in decimeters
trf.rotation = Quat::IDENTITY; trf.rotation = Quat::IDENTITY;
if let AnimKind::Turn = frame.kind { if let AnimKind::Turn = frame.kind {
trf.rotate_local_y( trf.rotate_local_y(
@@ -64,7 +67,7 @@ pub fn apply_animation(
} }
#[derive( #[derive(
Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize, Reflect, EnumIter Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize, Reflect, EnumIter,
)] )]
pub enum AnimKind { pub enum AnimKind {
Wait, Wait,
@@ -74,12 +77,17 @@ pub enum AnimKind {
JumpSquat, JumpSquat,
JumpForward, JumpForward,
JumpBack, JumpBack,
DoubleJump, DoubleJumpForward,
DoubleJumpBack,
Landing, Landing,
LandingSpecial,
AirDodge, AirDodge,
Fall, Fall,
Turn, Turn,
FlinchGround,
FlinchAir,
// Attacks // Attacks
AttackJab1, AttackJab1,
AttackUpTilt, AttackUpTilt,
+450 -89
View File
@@ -1,27 +1,85 @@
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use bevy::prelude::*; use bevy::prelude::*;
use bevy_ggrs::prelude::GgrsSchedule; use bevy_ggrs::{Rollback, prelude::GgrsSchedule};
use fixed_math::SinCos;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
fighter::{ fighter::{
Fighter, FighterAttributes, FighterFacingDirection, FighterHitboxes, FighterTranslation, animation::{AnimKind, FighterAnimationFrame}, baked_animation::{FighterBoneMatrices, FixedMat4}, hurtbox::{FixedAffineCapsule, FixedCapsule}, manifest::FighterManifest, Fighter, FighterAttributes, FighterFacingDirection, FighterHitboxes, FighterHitstop,
}, math::{ FighterPreviousFacingDirection, FighterPreviousTranslation, FighterRoster,
int::{FGi32, FGi32Ext}, FighterTranslation,
animation::{AnimKind, FighterAnimationFrame},
baked_animation::{FighterBoneIndexMap, FighterBoneMatrices, FixedMat4},
errors::FighterErrors,
hurtbox::{FixedAffineCapsule, FixedCapsule},
manifest::FighterManifest,
},
game_settings::GameSettings,
math::{
int::{FGWide, FGi32, FGi32Ext},
vec::FGVec2,
vec3::FGVec3, vec3::FGVec3,
}, schedule::GameplaySet, scripting::FighterAttackScript, },
player::Player,
schedule::GameplaySet,
scripting::FighterAttackScript,
}; };
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[derive(Deref, Component, Default, Hash, Debug, Copy, Clone)]
pub struct FighterKnockbackVelocity(pub FGVec2);
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, Component, Hash)]
pub struct FighterDamage(FGi32); pub struct FighterDamage(FGi32);
#[derive(Debug, Hash, Clone)]
pub enum HitReactionKind {
Flinch,
Tumble,
}
#[derive(Debug, Hash, Clone)]
pub struct FighterHitReaction {
pub launch_velocity: FGVec2,
pub hitstop_frames: HitStop,
pub hitstun_frames: u32,
pub kind: HitReactionKind,
}
#[derive(Component, DerefMut, Deref, Debug, Default, Hash, Clone)]
pub struct FighterPendingHitReaction(pub Option<FighterHitReaction>);
impl FighterDamage { impl FighterDamage {
pub fn lit(text: &str) -> Self { pub fn lit(text: &str) -> Self {
Self(FGi32::lit(text)) Self(FGi32::lit(text))
} }
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Component)]
pub struct FighterLastAttackDebug {
pub trajectory_points: Vec<Vec3>,
}
#[derive(Debug, Default, Clone, Deref, DerefMut, Hash)]
pub struct HitStop(u32);
impl HitStop {
pub fn calculate(attack_damage_stalled: FighterDamage, crouch_cancelling: bool) -> Self {
let a = (attack_damage_stalled.0 / FGi32::lit("3.0") + FGi32::lit("4.0")).round_to_zero();
let crouch_cancelling_factor = if crouch_cancelling {
FGi32::lit("0.66666666")
} else {
FGi32::ONE
};
let frames: u32 = ((a * crouch_cancelling_factor).round_to_zero()).to_num();
Self(frames)
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum KnockbackType { pub enum KnockbackType {
Normal, Normal,
Fixed, Fixed,
@@ -44,6 +102,22 @@ impl Knockback {
pub fn lit(val: &str) -> Self { pub fn lit(val: &str) -> Self {
Self(FGi32::lit(val)) Self(FGi32::lit(val))
} }
pub fn get_launch_speed(&self, game_settings: &GameSettings) -> FGi32 {
self.0
* game_settings
.fighter_common
.knockback_launch_velocity_multiplier
}
pub fn get_hitstun_frames(&self, game_settings: &GameSettings) -> u32 {
(self.0
* game_settings
.fighter_common
.hitstun_frames_per_unit_knockback)
.floor()
.to_num()
}
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -68,8 +142,9 @@ impl AttackAngle {
} }
} }
#[derive(Serialize, Deserialize, Reflect, PartialEq, Eq, Hash, Clone, Debug)] #[derive(Serialize, Deserialize, Reflect, PartialEq, Eq, Hash, Clone, Debug, Default, Copy)]
pub enum AttackKind { pub enum AttackKind {
#[default]
NeutralAir, NeutralAir,
ForwardAir, ForwardAir,
BackAir, BackAir,
@@ -119,14 +194,78 @@ pub struct AttackHitbox {
pub end_frame: u32, pub end_frame: u32,
} }
pub struct StaleMoveQueue(pub VecDeque<AttackKind>); const STALE_MOVE_QUEUE_COUNT: usize = 9;
#[derive(Component, Hash, Clone, Default)]
#[require(Rollback)]
pub struct FighterStaleMoveQueue(VecDeque<AttackKind>);
const STALENESS_REDUCTIONS: [FGi32; 9] = [
FGi32::lit("0.09"),
FGi32::lit("0.08"),
FGi32::lit("0.07"),
FGi32::lit("0.06"),
FGi32::lit("0.05"),
FGi32::lit("0.04"),
FGi32::lit("0.03"),
FGi32::lit("0.02"),
FGi32::lit("0.01"),
];
impl FighterStaleMoveQueue {
pub fn push(&mut self, attack: AttackKind) {
if self.0.len() == STALE_MOVE_QUEUE_COUNT {
self.0.pop_front();
}
self.0.push_back(attack);
}
pub fn get_attack_damage_multiplier(&self, attack: AttackKind) -> FGi32 {
FGi32::ONE
- self
.0
.iter()
.rev()
.enumerate()
.map(|(idx, kind)| {
if *kind == attack {
STALENESS_REDUCTIONS[idx]
} else {
FGi32::ZERO
}
})
.sum::<FGi32>()
.min(FGi32::ONE)
}
}
impl AttackHitbox { impl AttackHitbox {
pub fn validate(&self) -> Result<(), String> {
if self.bone.trim().is_empty() {
return Err("bone name is empty".into());
}
if self.radius <= FGi32::ZERO {
return Err("radius must be positive".into());
}
if self.damage.0 < FGi32::ZERO {
return Err("damage must be non-negative".into());
}
if self.knockback.0 < FGi32::ZERO {
return Err("knockback must be non-negative".into());
}
if self.knockback_growth < FGi32::ZERO {
return Err("knockback growth must be non-negative".into());
}
if self.end_frame <= self.start_frame {
return Err("end frame must be greater than start frame".into());
}
Ok(())
}
/// Knockback calculation /// Knockback calculation
pub fn calculate_knockback( pub fn calculate_knockback(
&self, &self,
attack: AttackKind,
receiver_attribs: &FighterAttributes, receiver_attribs: &FighterAttributes,
receiver_damage: FighterDamage, receiver_damage: FighterDamage,
total_damage_received_this_frame: FighterDamage, total_damage_received_this_frame: FighterDamage,
@@ -163,27 +302,36 @@ impl AttackHitbox {
out out
}; };
let s = KB_GROWTH_SCALE * self.knockback_growth; let kb = match self.knockback_type {
let p = receiver_damage.0.floor() + total_damage_received_this_frame.0; KnockbackType::Fixed => FGWide::from_num(self.knockback.0),
let d = attack_damage_unstalled; KnockbackType::Normal => {
let damage_term = p / DAMAGE_TERM_DIVISOR * (d + DAMAGE_BONUS); let p = FGWide::from_num(receiver_damage.0.floor())
+ FGWide::from_num(total_damage_received_this_frame.0);
let d = FGWide::from_num(attack_damage_unstalled);
let s = FGWide::from_num(KB_GROWTH_SCALE * self.knockback_growth);
let damage_term = p / FGWide::from_num(DAMAGE_TERM_DIVISOR)
* (d + FGWide::from_num(DAMAGE_BONUS));
let scaled = damage_term * FGWide::from_num(FGi32::lit("2.0") * BASELINE_WEIGHT)
/ FGWide::from_num(receiver_attribs.weight + BASELINE_WEIGHT);
(scaled * FGWide::from_num(KB_GAIN) + FGWide::from_num(KB_OFFSET)) * s
+ FGWide::from_num(self.knockback.0)
}
};
let scaled = damage_term * (FGi32::lit("2.0") * BASELINE_WEIGHT) Knockback((FGWide::from_num(modifier) * kb).saturating_to_num())
/ (receiver_attribs.weight + BASELINE_WEIGHT);
let kb = (scaled * KB_GAIN + KB_OFFSET) * s + self.knockback.0;
Knockback(modifier * kb)
} }
} }
pub fn update_active_hitbox_list(script: &FighterAttackScript, list: &mut Vec<usize>, frame: u32) { pub fn update_active_hitbox_list(script: &FighterAttackScript, list: &mut Vec<usize>, frame: u32) {
*list = script list.clear();
.hitboxes list.extend(
.iter() script
.enumerate() .hitboxes
.filter(|(_, hb)| hb.start_frame <= frame && hb.end_frame > frame) .iter()
.map(|(i, _)| i) .enumerate()
.collect() .filter(|(_, hb)| hb.start_frame <= frame && hb.end_frame > frame)
.map(|(i, _)| i),
);
} }
#[derive(Clone, Debug, PartialEq, Hash)] #[derive(Clone, Debug, PartialEq, Hash)]
@@ -198,59 +346,81 @@ pub struct FighterSolvedHitbox {
pub capsule: FixedCapsule, pub capsule: FixedCapsule,
} }
#[derive(Component, Clone, Debug, Default, Hash)]
pub struct FighterSolvedHitboxes(pub Vec<FighterSolvedHitbox>);
pub fn solve_hitboxes( pub fn solve_hitboxes(
mut query: Query<( mut query: Query<(
&FighterBoneMatrices, &FighterBoneMatrices,
&FighterBoneIndexMap,
&FighterTranslation, &FighterTranslation,
&FighterPreviousTranslation,
&FighterFacingDirection, &FighterFacingDirection,
&FighterPreviousFacingDirection,
&mut FighterHitboxes, &mut FighterHitboxes,
&FighterAnimationFrame &FighterAnimationFrame,
)>, )>,
attack_scripts: Res<Assets<FighterAttackScript>>, attack_scripts: Res<Assets<FighterAttackScript>>,
) { ) {
for (matrices, translation, facing_direction, mut hitboxes, animation_frame) in &mut query { for (
hitboxes.active_hitboxes_solved.clear(); matrices,
if let Some(ref attack_script) = hitboxes.attack_script { bone_indices,
let attack_script = attack_scripts.get(attack_script).expect("Attack script should be valid"); translation,
let fighter_trf = translation.get_3d_transform(facing_direction); previous_translation,
let active_hitboxes = hitboxes.active_hitboxes.clone(); facing_direction,
for hitbox_idx in active_hitboxes { previous_facing_direction,
let hitbox = attack_script.hitboxes.get(hitbox_idx).expect("Hitbox IDX should be valid"); mut hitboxes,
let matrices = matrices.get(&hitbox.bone); animation_frame,
) in &mut query
{
let Some(active_attack) = hitboxes.0.as_mut() else {
continue;
};
active_attack.solved_hitboxes.clear();
let attack_script = attack_scripts
.get(&active_attack.script)
.expect("Attack script should be valid");
let fighter_trf = translation.get_3d_transform(facing_direction);
let previous_fighter_trf = FighterTranslation(previous_translation.0)
.get_3d_transform(&previous_facing_direction.0);
for hitbox_idx in active_attack.active_hitboxes.iter().copied() {
let hitbox = attack_script
.hitboxes
.get(hitbox_idx)
.expect("Hitbox IDX should be valid");
let matrices = bone_indices
.0
.get(&hitbox.bone)
.and_then(|index| matrices.get_index(*index));
if let None = matrices { if matrices.is_none() {
warn!("Bone {} not found!", hitbox.bone); warn!("Bone {} not found!", hitbox.bone);
continue; continue;
} }
let (prev_bone_matrix, curr_bone_matrix) = matrices.unwrap(); let (prev_bone_matrix, curr_bone_matrix) = matrices.unwrap();
let curr_hbox_matrix = fighter_trf.mul(curr_bone_matrix); let curr_hbox_matrix = fighter_trf.mul(curr_bone_matrix);
let curr_hbox_pos = curr_hbox_matrix.transform_point(hitbox.offset); let curr_hbox_pos = curr_hbox_matrix.transform_point(hitbox.offset);
if hitbox.start_frame == animation_frame.frame { if hitbox.start_frame == animation_frame.frame {
// Sphere only // Sphere only
hitboxes.active_hitboxes_solved.push( active_attack.solved_hitboxes.push(FighterSolvedHitbox {
FixedCapsule { hitbox_idx,
start: curr_hbox_pos, capsule: FixedCapsule {
end: curr_hbox_pos, start: curr_hbox_pos,
radius: hitbox.radius end: curr_hbox_pos,
} radius: hitbox.radius,
) },
} else { })
let prev_hbox_matrix = fighter_trf.mul(prev_bone_matrix); } else {
let prev_hbox_pos = prev_hbox_matrix.transform_point(hitbox.offset); let prev_hbox_matrix = previous_fighter_trf.mul(prev_bone_matrix);
hitboxes.active_hitboxes_solved.push( let prev_hbox_pos = prev_hbox_matrix.transform_point(hitbox.offset);
FixedCapsule { active_attack.solved_hitboxes.push(FighterSolvedHitbox {
start: prev_hbox_pos, hitbox_idx,
end: curr_hbox_pos, capsule: FixedCapsule {
radius: hitbox.radius start: prev_hbox_pos,
} end: curr_hbox_pos,
); radius: hitbox.radius,
} },
});
} }
} }
} }
@@ -262,9 +432,20 @@ pub struct FighterAttackScriptAssets {
#[derive(Component, Clone, Debug, Default, Hash)] #[derive(Component, Clone, Debug, Default, Hash)]
pub struct FighterSolvedHurtboxes(pub Vec<FighterSolvedHurtbox>); pub struct FighterSolvedHurtboxes(pub Vec<FighterSolvedHurtbox>);
#[derive(Component, Clone, Debug, Default, Hash, DerefMut, Deref)]
pub struct FighterReceivedAttacks(
pub Vec<(
/* attacker */ Entity,
Handle<FighterAttackScript>,
AttackKind,
/* hitbox_idx */ usize,
)>,
);
pub fn solve_hurtboxes( pub fn solve_hurtboxes(
mut query: Query<( mut query: Query<(
&FighterBoneMatrices, &FighterBoneMatrices,
&FighterBoneIndexMap,
&FighterTranslation, &FighterTranslation,
&FighterFacingDirection, &FighterFacingDirection,
&mut FighterSolvedHurtboxes, &mut FighterSolvedHurtboxes,
@@ -272,14 +453,19 @@ pub fn solve_hurtboxes(
)>, )>,
manifests: Res<Assets<FighterManifest>>, manifests: Res<Assets<FighterManifest>>,
) { ) {
for (matrices, translation, facing_direction, mut solved_hurtboxes, fighter) in &mut query { for (matrices, bone_indices, translation, facing_direction, mut solved_hurtboxes, fighter) in
&mut query
{
let manifest = manifests let manifest = manifests
.get(&fighter.manifest) .get(&fighter.manifest)
.expect("Manifest should be valid"); .expect("Manifest should be valid");
let fighter_trf = translation.get_3d_transform(facing_direction); let fighter_trf = translation.get_3d_transform(facing_direction);
solved_hurtboxes.0.clear(); solved_hurtboxes.0.clear();
for (hurtbox_idx, hurtbox) in manifest.hurtboxes.iter().enumerate() { for (hurtbox_idx, hurtbox) in manifest.hurtboxes.iter().enumerate() {
let bone_matrix = matrices.get_current(&hurtbox.bone); let bone_matrix = bone_indices
.0
.get(&hurtbox.bone)
.and_then(|index| matrices.get_current_index(*index));
if let Some(bone_matrix) = bone_matrix { if let Some(bone_matrix) = bone_matrix {
let to_global = fighter_trf.mul(bone_matrix); let to_global = fighter_trf.mul(bone_matrix);
@@ -303,33 +489,202 @@ pub fn solve_hurtboxes(
} }
} }
pub fn intersect_attacks_with_hurtboxes(query: Query<(Entity, &FighterSolvedHurtboxes, &FighterHitboxes)>, attack_scripts: Res<Assets<FighterAttackScript>>) { pub fn intersect_attacks_with_hurtboxes(
/*for (entity_hurting, _, hitboxes) in query { roster: Res<FighterRoster>,
if hitboxes.attack_script.is_none() { mut query_attacker: Query<(
Entity,
&mut FighterHitboxes,
&Fighter,
&Player,
&FighterStaleMoveQueue,
)>,
mut query_attacked: Query<(
Entity,
&FighterSolvedHurtboxes,
&Player,
&Fighter,
&mut FighterReceivedAttacks,
)>,
attack_scripts: Res<Assets<FighterAttackScript>>,
) {
for &entity_receiving in &roster.0 {
let Ok((_, hurtboxes, _, _receiving_fighter, mut received_attacks)) =
query_attacked.get_mut(entity_receiving)
else {
continue; continue;
} };
if let Some(ref attack_script) = hitboxes.attack_script { for &entity_hurting in &roster.0 {
let attack_script = attack_scripts.get(attack_script); if entity_hurting == entity_receiving {
continue;
if attack_script.is_none() { }
let Ok((_, mut hitboxes, _, _, _)) = query_attacker.get_mut(entity_hurting) else {
continue;
};
let Some(active_attack) = hitboxes.0.as_mut() else {
continue;
};
if active_attack.hit_fighters.contains(&entity_receiving) {
continue; continue;
} }
let attack_script = attack_script.unwrap(); let attack_script = attack_scripts
.get(&active_attack.script)
.expect("Attack script should be valid");
let capsules: Vec<(&AttackHitbox, FixedCapsule)> = hitboxes.active_hitboxes.iter().map(|idx| { let mut hitting_hitbox_idx = None;
(attack_script.hitboxes.get(*idx).unwrap(), ) for hurtbox in hurtboxes.0.iter() {
}).collect(); for solved_hitbox in active_attack.solved_hitboxes.iter() {
if hurtbox.capsule.intersects(solved_hitbox.capsule) {
for (entity_to_hurt, hurtboxes, _) in query { let candidate = solved_hitbox.hitbox_idx;
// Self collisions not allowed if hitting_hitbox_idx.is_none_or(|current: usize| {
if entity_to_hurt == entity_hurting { attack_script.hitboxes[candidate].id
continue; < attack_script.hitboxes[current].id
}) {
hitting_hitbox_idx = Some(candidate);
}
}
} }
} }
let Some(hitting_hitbox_idx) = hitting_hitbox_idx else {
continue;
};
received_attacks.push((
entity_hurting,
active_attack.script.clone(),
active_attack.kind,
hitting_hitbox_idx,
));
info!("Hit by hitbox {}!!!!", hitting_hitbox_idx);
active_attack.hit_fighters.push(entity_receiving);
} }
}*/ }
}
pub fn calculate_received_attacks_trajectories(
mut attacker: Query<(
&mut FighterStaleMoveQueue,
&FighterFacingDirection,
&FighterHitboxes,
&Player,
&mut FighterHitstop,
)>,
receiver: Query<(
&mut FighterReceivedAttacks,
&mut FighterDamage,
&Fighter,
&mut FighterPendingHitReaction,
)>,
attack_scripts: Res<Assets<FighterAttackScript>>,
game_settings: Res<GameSettings>,
fighter_manifests: Res<Assets<FighterManifest>>,
) -> Result {
for (mut received_attacks, mut receiver_damage, fighter, mut pending_reactions) in receiver {
if received_attacks.is_empty() {
continue;
}
// we got attacked, time to calculate the total damage
let damage_data = received_attacks
.iter()
.filter_map(|(from_entity, attack_script, attack_kind, hitbox_idx)| {
let Ok((stale_move_queue, facing_dir, _hitboxes, player, _attacker_hitstop)) =
attacker.get(*from_entity)
else {
return None;
};
let Some(attack_script) = attack_scripts.get(attack_script) else {
return None;
};
let hitbox = &attack_script.hitboxes[*hitbox_idx];
let damage_received =
stale_move_queue.get_attack_damage_multiplier(*attack_kind) * hitbox.damage.0;
Some((
from_entity,
damage_received,
hitbox,
attack_script,
matches!(facing_dir, FighterFacingDirection::Left),
player.handle,
))
})
.collect::<Vec<_>>();
let total_damage_received_this_frame = damage_data
.iter()
.map(|(_, damage, ..)| damage)
.sum::<FGi32>();
let fighter_manifest = fighter_manifests
.get(&fighter.manifest)
.ok_or(FighterErrors::FighterManifestNotFound)?;
let mut reactions = vec![];
for (attacker_entity, attack_damage, hitbox, _attack_script, facing_left, attacker_slot) in
damage_data
{
let knockback = hitbox.calculate_knockback(
&fighter_manifest.attributes,
*receiver_damage,
FighterDamage(total_damage_received_this_frame),
false,
false,
);
let angle = match &hitbox.angle {
AttackAngle::Normal(angle) => *angle,
AttackAngle::Sakurai => FGi32::lit("32.0"),
};
let launch_angle = if facing_left {
FGi32::lit("180.0") - angle
} else {
angle
};
let (sin, cos) = launch_angle.sin_cos();
let launch_direction = FGVec2::new(cos, sin);
let hitstop = HitStop::calculate(FighterDamage(attack_damage), false);
reactions.push((
*attacker_entity,
attacker_slot,
FighterHitReaction {
launch_velocity: launch_direction * knockback.get_launch_speed(&game_settings),
hitstun_frames: knockback.get_hitstun_frames(&game_settings),
hitstop_frames: hitstop,
kind: HitReactionKind::Flinch,
},
));
}
receiver_damage.0 += total_damage_received_this_frame;
for (attacker_entity, _, reaction) in reactions.iter() {
let Ok((.., mut hitstop)) = attacker.get_mut(*attacker_entity) else {
continue;
};
hitstop.remaining_frames = reaction.hitstop_frames.max(hitstop.remaining_frames);
}
// Pick attack by port priority
pending_reactions.0 = reactions
.into_iter()
.min_by(|(_, port_a, _), (_, port_b, _)| port_a.cmp(port_b))
.map(|(_, _, reaction)| reaction);
received_attacks.clear();
}
Ok(())
} }
pub struct FighterAttackPlugin; pub struct FighterAttackPlugin;
@@ -338,9 +693,15 @@ impl Plugin for FighterAttackPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems( app.add_systems(
GgrsSchedule, GgrsSchedule,
(solve_hurtboxes, solve_hitboxes).chain() (
solve_hurtboxes,
solve_hitboxes,
intersect_attacks_with_hurtboxes,
calculate_received_attacks_trajectories,
)
.chain()
.after(crate::fighter::baked_animation::update_fighter_bone_matrices) .after(crate::fighter::baked_animation::update_fighter_bone_matrices)
.in_set(GameplaySet::Animation), .in_set(GameplaySet::Attacks),
); );
} }
} }
+8
View File
@@ -32,6 +32,7 @@ pub struct FighterAttributes {
pub air_acceleration_base: FGi32, pub air_acceleration_base: FGi32,
pub air_acceleration_stick: FGi32, pub air_acceleration_stick: FGi32,
pub max_air_horizontal_velocity: FGi32, pub max_air_horizontal_velocity: FGi32,
pub air_drift_max: FGi32,
pub ground_friction: FGi32, pub ground_friction: FGi32,
pub terminal_velocity: FGi32, pub terminal_velocity: FGi32,
@@ -45,6 +46,13 @@ pub struct FighterAttributes {
} }
impl FighterAttributes { impl FighterAttributes {
pub fn validate(&self) -> Result<(), String> {
if self.weight <= FGi32::ZERO {
return Err("weight must be positive".into());
}
Ok(())
}
pub fn get_accel_and_target_dashrun( pub fn get_accel_and_target_dashrun(
&self, &self,
input: &FighterInputFrame, input: &FighterInputFrame,
+258 -31
View File
@@ -18,11 +18,12 @@ use bevy::{
reflect::TypePath, reflect::TypePath,
world_serialization::{WorldInstanceReady, WorldInstanceSpawner}, world_serialization::{WorldInstanceReady, WorldInstanceSpawner},
}; };
use bevy_ggrs::prelude::GgrsSchedule; use bevy_ggrs::{GgrsFrameTiming, prelude::GgrsSchedule};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{ use crate::{
fighter::{ fighter::{
Fighter,
animation::{AnimKind, FighterAnimationFrame}, animation::{AnimKind, FighterAnimationFrame},
manifest::FighterManifest, manifest::FighterManifest,
visual::FighterAnimations, visual::FighterAnimations,
@@ -115,9 +116,9 @@ impl FixedMat4 {
/// Replaces the rotation with XYZ Euler angles expressed in radians. /// Replaces the rotation with XYZ Euler angles expressed in radians.
pub fn with_rotation(mut self, rotation: FGVec3) -> Self { pub fn with_rotation(mut self, rotation: FGVec3) -> Self {
let (sin_x, cos_x) = rotation.x.sin_cos(); let (sin_x, cos_x) = rotation.x.sin_cos_rads();
let (sin_y, cos_y) = rotation.y.sin_cos(); let (sin_y, cos_y) = rotation.y.sin_cos_rads();
let (sin_z, cos_z) = rotation.z.sin_cos(); let (sin_z, cos_z) = rotation.z.sin_cos_rads();
self.cols[0][0] = cos_y * cos_z; self.cols[0][0] = cos_y * cos_z;
self.cols[0][1] = cos_x * sin_z + sin_x * sin_y * cos_z; self.cols[0][1] = cos_x * sin_z + sin_x * sin_y * cos_z;
self.cols[0][2] = sin_x * sin_z - cos_x * sin_y * cos_z; self.cols[0][2] = sin_x * sin_z - cos_x * sin_y * cos_z;
@@ -191,10 +192,22 @@ pub struct BakedFighterAnimations {
} }
impl BakedFighterAnimations { impl BakedFighterAnimations {
pub fn contains_bone(&self, bone: &str) -> bool {
self.bone_names.iter().any(|name| name == bone)
}
pub fn has_unique_bone_names(&self) -> bool {
let mut names = std::collections::HashSet::with_capacity(self.bone_names.len());
self.bone_names.iter().all(|name| names.insert(name))
}
pub fn sample_pose(&self, frame: &FighterAnimationFrame) -> Option<&[FixedMat4]> { pub fn sample_pose(&self, frame: &FighterAnimationFrame) -> Option<&[FixedMat4]> {
let frames = &self.clip(frame.kind)?.frames; let frames = &self.clip(frame.kind)?.frames;
let frame_index = if frame.repeat { let frame_index = if frame.repeat {
frame.frame % frames.len() as u32 // The terminal sample is retained for one-shot animations, but is
// the same point in time as the next loop's first sample.
let loop_frame_count = frames.len().saturating_sub(1).max(1) as u32;
frame.frame % loop_frame_count
} else { } else {
frame.frame frame.frame
}; };
@@ -224,8 +237,15 @@ pub struct FighterBoneMatrices {
matrices: Vec<FixedMat4>, matrices: Vec<FixedMat4>,
previous_frame_matrices: Vec<FixedMat4>, previous_frame_matrices: Vec<FixedMat4>,
local_matrices: Vec<FixedMat4>, local_matrices: Vec<FixedMat4>,
previous_local_matrices: Vec<FixedMat4>,
} }
/// Immutable lookup table populated from the baked skeleton. Keeping this
/// separate from rollback-tracked matrices avoids rebuilding string searches
/// during every simulated frame.
#[derive(Component, Clone, Debug, Default)]
pub struct FighterBoneIndexMap(pub HashMap<String, usize>);
#[derive(Component)] #[derive(Component)]
struct BakedFighterBone { struct BakedFighterBone {
fighter: Entity, fighter: Entity,
@@ -252,6 +272,17 @@ impl FighterBoneMatrices {
self.matrices.get(index).copied() self.matrices.get(index).copied()
} }
pub fn get_index(&self, index: usize) -> Option<(FixedMat4, FixedMat4)> {
Some((
*self.previous_frame_matrices.get(index)?,
*self.matrices.get(index)?,
))
}
pub fn get_current_index(&self, index: usize) -> Option<FixedMat4> {
self.matrices.get(index).copied()
}
pub fn iter(&self) -> impl Iterator<Item = (&str, FixedMat4)> { pub fn iter(&self) -> impl Iterator<Item = (&str, FixedMat4)> {
self.bone_names self.bone_names
.iter() .iter()
@@ -263,7 +294,23 @@ impl FighterBoneMatrices {
self.local_matrices.get(index).copied() self.local_matrices.get(index).copied()
} }
fn set_pose(&mut self, bone_names: &[String], parents: &[Option<usize>], local: &[FixedMat4]) { fn presentation_local(&self, index: usize, overstep_fraction: f32) -> Option<Transform> {
let current = self.local_matrices.get(index).copied()?;
let previous = self
.previous_local_matrices
.get(index)
.copied()
.unwrap_or(current);
Some(interpolate_transform(previous, current, overstep_fraction))
}
fn set_pose(
&mut self,
bone_names: &[String],
parents: &[Option<usize>],
local: &[FixedMat4],
model_scale: FGi32,
) {
assert_eq!( assert_eq!(
bone_names.len(), bone_names.len(),
local.len(), local.len(),
@@ -282,6 +329,7 @@ impl FighterBoneMatrices {
assert_eq!(self.parents, parents, "baked bone parents changed"); assert_eq!(self.parents, parents, "baked bone parents changed");
} }
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);
self.local_matrices.clear(); self.local_matrices.clear();
self.local_matrices.extend_from_slice(local); self.local_matrices.extend_from_slice(local);
let mut model = vec![None; local.len()]; let mut model = vec![None; local.len()];
@@ -289,9 +337,17 @@ impl FighterBoneMatrices {
resolve_model_transform(index, parents, local, &mut model) 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 {
cols: [
[model_scale, FGi32::ZERO, FGi32::ZERO, FGi32::ZERO],
[FGi32::ZERO, model_scale, FGi32::ZERO, FGi32::ZERO],
[FGi32::ZERO, FGi32::ZERO, model_scale, FGi32::ZERO],
[FGi32::ZERO, FGi32::ZERO, FGi32::ZERO, FGi32::ONE],
],
};
self.matrices = model self.matrices = model
.into_iter() .into_iter()
.map(|matrix| matrix.expect("baked bone hierarchy should be valid")) .map(|matrix| model_scale.mul(matrix.expect("baked bone hierarchy should be valid")))
.collect(); .collect();
} }
} }
@@ -300,18 +356,42 @@ pub fn update_fighter_bone_matrices(
mut fighters: Query<( mut fighters: Query<(
&FighterAnimationFrame, &FighterAnimationFrame,
&FighterAnimations, &FighterAnimations,
&Fighter,
&mut FighterBoneMatrices, &mut FighterBoneMatrices,
&mut FighterBoneIndexMap,
)>, )>,
baked_assets: Res<Assets<BakedFighterAnimations>>, baked_assets: Res<Assets<BakedFighterAnimations>>,
manifests: Res<Assets<FighterManifest>>,
) { ) {
for (frame, animations, mut matrices) in &mut fighters { for (frame, animations, fighter, mut matrices, mut bone_indices) in &mut fighters {
let baked = baked_assets let baked = baked_assets
.get(&animations.baked) .get(&animations.baked)
.expect("fighter baked animation asset should be loaded before the match starts"); .expect("fighter baked animation asset should be loaded before the match starts");
assert_eq!(
baked.frame_rate, BAKED_ANIMATION_FPS,
"fighter baked animation rate does not match the simulation rate"
);
let pose = baked let pose = baked
.sample_pose(frame) .sample_pose(frame)
.expect("fighter animation frame should select a baked pose"); .expect("fighter animation frame should select a baked pose");
matrices.set_pose(&baked.bone_names, &baked.parents, pose); let manifest = manifests
.get(&fighter.manifest)
.expect("fighter manifest should be loaded before the match starts");
matrices.set_pose(
&baked.bone_names,
&baked.parents,
pose,
manifest.model_scale,
);
if bone_indices.0.is_empty() {
bone_indices.0.extend(
baked
.bone_names
.iter()
.enumerate()
.map(|(index, name)| (name.clone(), index)),
);
}
} }
} }
@@ -403,15 +483,30 @@ fn bind_fighter_visual_bones(
fn apply_baked_fighter_visual_pose( fn apply_baked_fighter_visual_pose(
mut nodes: Query<(&mut Transform, &BakedFighterBone)>, mut nodes: Query<(&mut Transform, &BakedFighterBone)>,
fighters: Query<&FighterBoneMatrices>, fighters: Query<&FighterBoneMatrices>,
timing: Res<GgrsFrameTiming>,
) { ) {
let overstep_fraction = timing.overstep_fraction();
for (mut transform, bone) in &mut nodes { for (mut transform, bone) in &mut nodes {
let Ok(matrices) = fighters.get(bone.fighter) else { let Ok(matrices) = fighters.get(bone.fighter) else {
continue; continue;
}; };
let Some(local) = matrices.local(bone.index) else { let Some(local) = matrices.presentation_local(bone.index, overstep_fraction) else {
continue; continue;
}; };
*transform = Transform::from_matrix(local.to_mat4()); *transform = local;
}
}
fn interpolate_transform(previous: FixedMat4, current: FixedMat4, factor: f32) -> Transform {
let (previous_scale, previous_rotation, previous_translation) =
previous.to_mat4().to_scale_rotation_translation();
let (current_scale, current_rotation, current_translation) =
current.to_mat4().to_scale_rotation_translation();
let factor = factor.clamp(0.0, 1.0);
Transform {
translation: previous_translation.lerp(current_translation, factor),
rotation: previous_rotation.slerp(current_rotation, factor),
scale: previous_scale.lerp(current_scale, factor),
} }
} }
@@ -423,6 +518,7 @@ struct FighterBakeDeclaration {
#[derive(Asset, TypePath)] #[derive(Asset, TypePath)]
struct FighterBakeSource { struct FighterBakeSource {
model_bytes: Vec<u8>, model_bytes: Vec<u8>,
buffers: Vec<Vec<u8>>,
animations: HashMap<AnimKind, String>, animations: HashMap<AnimKind, String>,
} }
@@ -452,12 +548,35 @@ impl AssetLoader for FighterBakeSourceLoader {
let manifest: FighterManifest = ron::de::from_bytes(&manifest_bytes) let manifest: FighterManifest = ron::de::from_bytes(&manifest_bytes)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
// The processor's AssetServer reads processed assets. Reading this let model_bytes = load_context
// source dependency through it would wait for a processed GLB while .read_asset_bytes(&manifest.model_path)
// this processor is still producing the first processed asset. .await
let model_bytes = std::fs::read(Path::new("assets").join(&manifest.model_path))?; .map_err(|error| io::Error::other(error.to_string()))?;
let gltf = gltf::Gltf::from_slice(&model_bytes)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
let mut buffers = Vec::with_capacity(gltf.buffers().len());
for buffer in gltf.buffers() {
let bytes = match buffer.source() {
gltf::buffer::Source::Uri(uri) => load_context
.read_asset_bytes(AssetPath::from_path_buf(
Path::new(&manifest.model_path)
.parent()
.unwrap_or_else(|| Path::new(""))
.join(uri),
))
.await
.map_err(|error| io::Error::other(error.to_string()))?,
gltf::buffer::Source::Bin => gltf.blob.clone().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "missing glTF binary blob")
})?,
};
buffers.push(bytes);
}
Ok(FighterBakeSource { Ok(FighterBakeSource {
model_bytes, model_bytes,
buffers,
animations: manifest.animations, animations: manifest.animations,
}) })
} }
@@ -506,7 +625,7 @@ impl AssetTransformer for FighterBakeTransformer {
source: TransformedAsset<Self::AssetInput>, source: TransformedAsset<Self::AssetInput>,
_: &'a Self::Settings, _: &'a Self::Settings,
) -> Result<TransformedAsset<Self::AssetOutput>, Self::Error> { ) -> Result<TransformedAsset<Self::AssetOutput>, Self::Error> {
let baked = bake_gltf(&source.model_bytes, &source.animations)?; let baked = bake_gltf(&source.model_bytes, &source.buffers, &source.animations)?;
Ok(source.replace_asset(baked)) Ok(source.replace_asset(baked))
} }
} }
@@ -562,10 +681,43 @@ impl Plugin for BakedAnimationPlugin {
fn bake_gltf( fn bake_gltf(
bytes: &[u8], bytes: &[u8],
buffer_bytes: &[Vec<u8>],
animations: &HashMap<AnimKind, String>, animations: &HashMap<AnimKind, String>,
) -> io::Result<BakedFighterAnimations> { ) -> io::Result<BakedFighterAnimations> {
let (document, buffers, _) = gltf::import_slice(bytes) let gltf = gltf::Gltf::from_slice(bytes)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
let buffers = gltf
.buffers()
.zip(buffer_bytes)
.map(|(buffer, bytes)| {
if bytes.len() < buffer.length() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"glTF buffer {} is too short: expected {}, got {}",
buffer.index(),
buffer.length(),
bytes.len()
),
));
}
Ok(gltf::buffer::Data(bytes.clone()))
})
.collect::<io::Result<Vec<_>>>()?;
if buffers.len() != gltf.buffers().len() {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"glTF buffer data is incomplete",
));
}
bake_gltf_document(gltf.document, buffers, animations)
}
fn bake_gltf_document(
document: gltf::Document,
buffers: Vec<gltf::buffer::Data>,
animations: &HashMap<AnimKind, String>,
) -> io::Result<BakedFighterAnimations> {
let nodes: Vec<_> = document.nodes().collect(); let nodes: Vec<_> = document.nodes().collect();
if nodes.is_empty() { if nodes.is_empty() {
return Err(io::Error::new( return Err(io::Error::new(
@@ -616,10 +768,10 @@ fn bake_gltf(
.iter() .iter()
.filter_map(Channel::duration) .filter_map(Channel::duration)
.fold(0.0_f32, f32::max); .fold(0.0_f32, f32::max);
let frame_count = (duration * BAKED_ANIMATION_FPS as f32).ceil() as usize + 1; let frame_count = baked_frame_count(duration, BAKED_ANIMATION_FPS);
let mut frames = Vec::with_capacity(frame_count); let mut frames = Vec::with_capacity(frame_count);
for frame in 0..frame_count { for frame in 0..frame_count {
let time = frame as f32 / BAKED_ANIMATION_FPS as f32; let time = (frame as f32 / BAKED_ANIMATION_FPS as f32).min(duration);
let local = nodes let local = nodes
.iter() .iter()
.map(|node| local_transform(node.clone(), &channels, time)) .map(|node| local_transform(node.clone(), &channels, time))
@@ -658,6 +810,17 @@ fn bake_gltf(
}) })
} }
fn baked_frame_count(duration: f32, frame_rate: u32) -> usize {
let frame = duration as f64 * frame_rate as f64;
let nearest_frame = frame.round();
let last_frame = if (frame - nearest_frame).abs() < 0.0001 {
nearest_frame
} else {
frame.ceil()
};
last_frame as usize + 1
}
fn resolve_model_transform( fn resolve_model_transform(
index: usize, index: usize,
parents: &[Option<usize>], parents: &[Option<usize>],
@@ -828,19 +991,21 @@ mod tests {
fn configured_fighter_clips_bake_to_fixed_point_frames() { fn configured_fighter_clips_bake_to_fixed_point_frames() {
let manifest: FighterManifest = let manifest: FighterManifest =
ron::from_str(include_str!("../../assets/fighters/test/test.fighter.ron")).unwrap(); ron::from_str(include_str!("../../assets/fighters/test/test.fighter.ron")).unwrap();
let baked = bake_gltf( let (document, buffers, _) = gltf::import(concat!(
include_bytes!("../../assets/fighters/test/test-fighter-normal.glb"), env!("CARGO_MANIFEST_DIR"),
&manifest.animations, "/assets/fighters/test/test_fighter.gltf"
) ))
.unwrap(); .unwrap();
let baked = bake_gltf_document(document, buffers, &manifest.animations).unwrap();
assert_eq!(baked.frame_rate, BAKED_ANIMATION_FPS); assert_eq!(baked.frame_rate, BAKED_ANIMATION_FPS);
assert!(baked.frame_count(AnimKind::Wait).unwrap() > 1); assert_eq!(baked.frame_count(AnimKind::Wait), Some(121));
assert_eq!(baked.frame_count(AnimKind::Walk), Some(33));
assert_eq!(baked.frame_count(AnimKind::Run), Some(33));
assert_eq!(baked.frame_count(AnimKind::Dash), Some(21));
assert_eq!(baked.frame_count(AnimKind::Landing), Some(9));
assert_eq!(baked.frame_count(AnimKind::JumpBack), Some(57));
assert_eq!(baked.clip_indices.len(), manifest.animations.len()); assert_eq!(baked.clip_indices.len(), manifest.animations.len());
assert_eq!(
baked.clip_indices[&AnimKind::JumpSquat],
baked.clip_indices[&AnimKind::Landing]
);
assert_eq!( assert_eq!(
baked.clip(AnimKind::Wait).unwrap().frames[0].len(), baked.clip(AnimKind::Wait).unwrap().frames[0].len(),
baked.bone_names.len() baked.bone_names.len()
@@ -853,12 +1018,14 @@ mod tests {
let first = FixedMat4::IDENTITY; let first = FixedMat4::IDENTITY;
let mut second = FixedMat4::IDENTITY; let mut second = FixedMat4::IDENTITY;
second.translate(FGVec3::lit("2", "0", "0")); second.translate(FGVec3::lit("2", "0", "0"));
let mut terminal = FixedMat4::IDENTITY;
terminal.translate(FGVec3::lit("4", "0", "0"));
let baked = BakedFighterAnimations { let baked = BakedFighterAnimations {
frame_rate: BAKED_ANIMATION_FPS, frame_rate: BAKED_ANIMATION_FPS,
bone_names: vec!["root".into()], bone_names: vec!["root".into()],
parents: vec![None], parents: vec![None],
clips: vec![BakedAnimationClip { clips: vec![BakedAnimationClip {
frames: vec![vec![first], vec![second]], frames: vec![vec![first], vec![second], vec![terminal]],
}], }],
clip_indices: HashMap::from([(AnimKind::Wait, 0)]), clip_indices: HashMap::from([(AnimKind::Wait, 0)]),
}; };
@@ -870,12 +1037,48 @@ mod tests {
}; };
let finished = FighterAnimationFrame { let finished = FighterAnimationFrame {
kind: AnimKind::Wait, kind: AnimKind::Wait,
frame: 3, frame: 4,
repeat: false, repeat: false,
}; };
assert_eq!(baked.sample_pose(&repeating), Some(&[second][..])); assert_eq!(baked.sample_pose(&repeating), Some(&[second][..]));
assert_eq!(baked.sample_pose(&finished), Some(&[second][..])); assert_eq!(baked.sample_pose(&finished), Some(&[terminal][..]));
}
#[test]
fn frame_count_snaps_source_frame_rounding_error_to_the_bake_grid() {
assert_eq!(baked_frame_count(0.533333361, 60), 33);
assert_eq!(baked_frame_count(0.333333343, 60), 21);
assert_eq!(baked_frame_count(0.133333340, 60), 9);
assert_eq!(baked_frame_count(2.0, 60), 121);
}
#[test]
fn linear_source_channel_is_resampled_between_thirty_hz_keys() {
let channel = Channel {
node: 0,
property: gltf::animation::Property::Translation,
interpolation: gltf::animation::Interpolation::Linear,
times: vec![0.0, 1.0 / 30.0],
values: ChannelValues::Vec3(vec![[0.0, 0.0, 0.0], [2.0, 0.0, 0.0]]),
};
let ChannelValues::Vec3(values) = &channel.values else {
unreachable!()
};
assert_eq!(sample_vec3(&channel, values, 1.0 / 60.0), [1.0, 0.0, 0.0]);
}
#[test]
fn presentation_pose_interpolates_previous_and_current_local_transforms() {
let mut previous = FixedMat4::IDENTITY;
previous.translate(FGVec3::lit("2", "0", "0"));
let mut current = FixedMat4::IDENTITY;
current.translate(FGVec3::lit("6", "0", "0"));
let transform = interpolate_transform(previous, current, 0.25);
assert_eq!(transform.translation, Vec3::new(3.0, 0.0, 0.0));
} }
#[test] #[test]
@@ -888,6 +1091,7 @@ mod tests {
&["root".into(), "hand".into()], &["root".into(), "hand".into()],
&[None, Some(0)], &[None, Some(0)],
&[first, second], &[first, second],
FGi32::ONE,
); );
assert_eq!(matrices.get_current("hand"), Some(second)); assert_eq!(matrices.get_current("hand"), Some(second));
@@ -909,6 +1113,7 @@ mod tests {
&["root".into(), "hand".into()], &["root".into(), "hand".into()],
&[None, Some(0)], &[None, Some(0)],
&[root, hand], &[root, hand],
FGi32::ONE,
); );
assert_eq!(matrices.local(1), Some(hand)); assert_eq!(matrices.local(1), Some(hand));
@@ -926,6 +1131,28 @@ mod tests {
); );
} }
#[test]
fn model_scale_affects_gameplay_bones_without_changing_visual_locals() {
let mut root = FixedMat4::IDENTITY;
root.translate(FGVec3::lit("1", "0", "0"));
let mut hand = FixedMat4::IDENTITY;
hand.translate(FGVec3::lit("0", "2", "0"));
let mut matrices = FighterBoneMatrices::default();
matrices.set_pose(
&["root".into(), "hand".into()],
&[None, Some(0)],
&[root, hand],
FGi32::lit("10"),
);
assert_eq!(matrices.local(1), Some(hand));
assert_eq!(
matrices.get_current("hand").unwrap().get_translation(),
FGVec3::lit("10", "20", "0")
);
}
#[test] #[test]
fn fixed_matrix_transforms_points() { fn fixed_matrix_transforms_points() {
let transform = FixedMat4 { let transform = FixedMat4 {
+19 -15
View File
@@ -49,23 +49,27 @@ pub fn air_collide_with_stage(
for (poly_idx, poly) in state_context.stage_collision.stage_polys.iter().enumerate() { for (poly_idx, poly) in state_context.stage_collision.stage_polys.iter().enumerate() {
if let Some(intersect_result) = poly.intersect_ray(ray_segment) { if let Some(intersect_result) = poly.intersect_ray(ray_segment) {
intersect_results.push((AirCollisionWithStageResult { intersect_results.push((
line_id: { AirCollisionWithStageResult {
StageLineID { line_id: {
polygon: poly_idx, StageLineID {
segment: intersect_result.segment_idx, polygon: poly_idx,
} segment: intersect_result.segment_idx,
}
},
hit_position: intersect_result.position,
hit_normal: intersect_result.normal,
}, },
hit_position: intersect_result.position, intersect_result
hit_normal: intersect_result.normal, .position
}, intersect_result.position.distance_squared(ray_segment.point2()))); .distance_squared(ray_segment.point2()),
));
} }
} }
intersect_results.sort_by(| (_, a), (_, b) | { intersect_results.sort_by(|(_, a), (_, b)| a.cmp(b));
a.cmp(b)
});
intersect_results.iter().last().map(|(val, _)| { intersect_results
val.to_owned().clone() .iter()
}) .last()
.map(|(val, _)| val.to_owned().clone())
} }
+99 -19
View File
@@ -8,21 +8,26 @@ use bevy_egui::{EguiContexts, egui};
use crate::debug_tools::{DebugSettings, FighterDebugRowKind}; use crate::debug_tools::{DebugSettings, FighterDebugRowKind};
use crate::fighter::animation::FighterAnimationFrame; use crate::fighter::animation::FighterAnimationFrame;
use crate::fighter::attack::FighterSolvedHurtboxes; use crate::fighter::attack::{
FighterKnockbackVelocity, FighterLastAttackDebug, FighterPendingHitReaction,
FighterSolvedHurtboxes,
};
use crate::fighter::baked_animation::{BakedFighterAnimations, FighterBoneMatrices}; use crate::fighter::baked_animation::{BakedFighterAnimations, FighterBoneMatrices};
use crate::fighter::ecb::FighterPreviousECB; use crate::fighter::ecb::FighterPreviousECB;
use crate::fighter::errors::FighterErrors;
use crate::fighter::hurtbox::FixedAffineCapsule; use crate::fighter::hurtbox::FixedAffineCapsule;
use crate::fighter::state::StateNameDebug; use crate::fighter::manifest::FighterManifest;
use crate::fighter::state::{FighterState, air};
use crate::fighter::visual::FighterAnimations; use crate::fighter::visual::FighterAnimations;
use crate::fighter::{ use crate::fighter::{
FighterECB, FighterFacingDirection, FighterHitboxes, FighterPreviousTranslation, Fighter, FighterECB, FighterFacingDirection, FighterHitboxes, FighterPreviousTranslation,
FighterTranslation, FighterVelocity, FighterTranslation, FighterVelocity,
}; };
use crate::game_settings::GameSettings;
use crate::input::FighterInput; use crate::input::FighterInput;
use crate::math::int::FGi32; use crate::math::int::FGi32;
use crate::math::vec3::FGVec3; use crate::math::vec::FGVec2;
use crate::player::Player; use crate::player::Player;
use crate::scripting::FighterAttackScript;
pub fn debug_draw_ecb( pub fn debug_draw_ecb(
ecbs: Query<( ecbs: Query<(
@@ -52,7 +57,7 @@ pub fn fighter_debug(
&FighterVelocity, &FighterVelocity,
&FighterInput, &FighterInput,
&FighterAnimationFrame, &FighterAnimationFrame,
&StateNameDebug, &FighterState,
&FighterAnimations, &FighterAnimations,
&FighterTranslation, &FighterTranslation,
&FighterFacingDirection, &FighterFacingDirection,
@@ -63,7 +68,7 @@ pub fn fighter_debug(
let mut fighters = query.iter().collect::<Vec<_>>(); let mut fighters = query.iter().collect::<Vec<_>>();
fighters.sort_unstable_by_key(|(player, ..)| player.handle); fighters.sort_unstable_by_key(|(player, ..)| player.handle);
for (player, velocity, input, animation_frame, state_name, animations, translation, facing) in for (player, velocity, input, animation_frame, state, animations, translation, facing) in
fighters fighters
{ {
let Some(rows) = settings.player_rows(player.handle) else { let Some(rows) = settings.player_rows(player.handle) else {
@@ -86,7 +91,7 @@ pub fn fighter_debug(
if let Some(frame_count) = frame_count { if let Some(frame_count) = frame_count {
ui.label(format!( ui.label(format!(
"State: {:?} ({:?} {}/{})", "State: {:?} ({:?} {}/{})",
state_name.0, state.name(),
animation_frame.kind, animation_frame.kind,
animation_frame.frame, animation_frame.frame,
frame_count frame_count
@@ -94,7 +99,8 @@ pub fn fighter_debug(
} else { } else {
ui.label(format!( ui.label(format!(
"State: {:?} ({:?})", "State: {:?} ({:?})",
state_name.0, animation_frame.kind state.name(),
animation_frame.kind
)); ));
} }
} }
@@ -149,14 +155,16 @@ pub fn fighter_debug(
pub fn animation_debug(query: Query<(&GlobalTransform, &FighterBoneMatrices)>, mut gizmos: Gizmos) { pub fn animation_debug(query: Query<(&GlobalTransform, &FighterBoneMatrices)>, mut gizmos: Gizmos) {
for (global_transform, matrices) in query { for (global_transform, matrices) in query {
let (_, rotation, translation) = global_transform.to_scale_rotation_translation();
let marker_transform = Transform::from_translation(translation).with_rotation(rotation);
for (_, matrix) in matrices.iter() { for (_, matrix) in matrices.iter() {
let pos = global_transform.transform_point(Vec3::new( let pos = marker_transform.transform_point(Vec3::new(
matrix.cols[3][0].to_num(), matrix.cols[3][0].to_num(),
matrix.cols[3][1].to_num(), matrix.cols[3][1].to_num(),
matrix.cols[3][2].to_num(), matrix.cols[3][2].to_num(),
)); ));
gizmos.cross(pos, 0.5, bevy::color::palettes::css::RED); gizmos.cross(pos, 0.5, bevy::color::palettes::css::RED);
gizmos.axes(*global_transform, 1.0); gizmos.axes(marker_transform, 1.0);
} }
} }
} }
@@ -290,6 +298,20 @@ fn capsule_wireframe() -> &'static CapsuleWireframe {
mod capsule_debug_tests { mod capsule_debug_tests {
use super::*; use super::*;
#[test]
fn animation_markers_ignore_visual_scale() {
let global = GlobalTransform::from(Transform {
translation: Vec3::new(3.0, 4.0, 5.0),
rotation: Quat::from_rotation_y(std::f32::consts::FRAC_PI_2),
scale: Vec3::splat(10.0),
});
let (_, rotation, translation) = global.to_scale_rotation_translation();
let marker_transform = Transform::from_translation(translation).with_rotation(rotation);
let marker = marker_transform.transform_point(Vec3::new(2.0, 0.0, 0.0));
assert!(marker.abs_diff_eq(Vec3::new(3.0, 4.0, 3.0), 1e-5));
}
#[test] #[test]
fn capsule_wireframe_caps_extend_in_opposite_directions() { fn capsule_wireframe_caps_extend_in_opposite_directions() {
let wireframe = capsule_wireframe(); let wireframe = capsule_wireframe();
@@ -319,20 +341,20 @@ pub fn attack_debug(
&FighterFacingDirection, &FighterFacingDirection,
&FighterAnimationFrame, &FighterAnimationFrame,
)>, )>,
attack_scripts: Res<Assets<FighterAttackScript>>,
mut gizmos: Gizmos, mut gizmos: Gizmos,
) { ) {
for (hitboxes, matrices, translation, facing_direction, frame) in query { for (hitboxes, _matrices, _translation, _facing_direction, _frame) in query {
if let Some(script) = &hitboxes.attack_script { if let Some(active_attack) = &hitboxes.0 {
for solved_hitbox in hitboxes.active_hitboxes_solved.iter() { for solved_hitbox in active_attack.solved_hitboxes.iter() {
let start = solved_hitbox.start.to_vec3(); let start = solved_hitbox.capsule.start.to_vec3();
let end = solved_hitbox.end.to_vec3(); let end = solved_hitbox.capsule.end.to_vec3();
let center = (solved_hitbox.start + solved_hitbox.end) * FGi32::lit("0.5"); let center =
(solved_hitbox.capsule.start + solved_hitbox.capsule.end) * FGi32::lit("0.5");
let length = (start - end).length(); let length = (start - end).length();
let attack_capsule = Capsule3d { let attack_capsule = Capsule3d {
half_length: length * 0.5, half_length: length * 0.5,
radius: solved_hitbox.radius.to_num(), radius: solved_hitbox.capsule.radius.to_num(),
}; };
let aim_dir = (end - start).normalize_or(Vec3::Y); let aim_dir = (end - start).normalize_or(Vec3::Y);
@@ -353,3 +375,61 @@ pub fn attack_debug(
} }
} }
} }
pub fn attack_debug_gather(
query: Query<(
Entity,
&FighterPendingHitReaction,
&FighterTranslation,
&Fighter,
)>,
mut commands: Commands,
manifests: Res<Assets<FighterManifest>>,
game_settings: Res<GameSettings>,
) -> Result {
for (entity, reaction, translation, fighter) in query {
let Some(ref hit) = reaction.0 else {
commands.entity(entity).remove::<FighterLastAttackDebug>();
continue;
};
let manifest = manifests
.get(&fighter.manifest)
.ok_or(FighterErrors::FighterManifestNotFound)?;
let mut knockback_vel = FighterKnockbackVelocity(hit.launch_velocity);
let mut fighter_vel = FighterVelocity(FGVec2::ZERO);
let mut translation = Vec3::new(translation.x.to_num(), translation.y.to_num(), 0.0);
let mut points = vec![];
points.push(translation);
points.reserve(hit.hitstun_frames as usize);
for _ in 1..hit.hitstun_frames {
air::integrate_gravity(&mut fighter_vel, &manifest.attributes);
let vel = knockback_vel.length();
let new_vel = vel
.saturating_sub(game_settings.fighter_common.knockback_decay_per_frame)
.max(FGi32::ZERO);
knockback_vel = FighterKnockbackVelocity(knockback_vel.0.normalize_or_zero() * new_vel);
translation += Vec3::new(knockback_vel.x.to_num(), knockback_vel.y.to_num(), 0.0);
translation += Vec3::new(fighter_vel.x.to_num(), fighter_vel.y.to_num(), 0.0);
points.push(translation);
}
commands.entity(entity).insert(FighterLastAttackDebug {
trajectory_points: points,
});
}
Ok(())
}
pub fn attack_launch_debug_draw(query: Query<&FighterLastAttackDebug>, mut gizmos: Gizmos) {
for debug_attack in query {
gizmos.linestrip(
debug_attack.trajectory_points.iter().copied(),
bevy::color::palettes::css::GREEN,
);
}
}
+7
View File
@@ -0,0 +1,7 @@
use bevy::reflect::Reflect;
#[derive(thiserror::Error, Debug, Reflect)]
pub enum FighterErrors {
#[error("Fighter manifest not found")]
FighterManifestNotFound,
}
+17 -15
View File
@@ -52,11 +52,21 @@ impl FixedAffineCapsule {
} }
let mut simplex = [FGVec3::ZERO; 4]; let mut simplex = [FGVec3::ZERO; 4];
let mut simplex_len = 0; let mut simplex_len = 0;
for _ in 0..20 { let mut supports = [FGVec3::ZERO; 20];
let mut support_count = 0;
while support_count < supports.len() {
let point = self.support(direction) - rhs.support(-direction); let point = self.support(direction) - rhs.support(-direction);
if point.dot(direction) < FGWide::ZERO { if point.dot(direction) < FGWide::ZERO {
return false; return false;
} }
if supports[..support_count].contains(&point) {
// Fixed-point quantization can make GJK revisit a support
// point without making progress. This is not proof of an
// intersection, so terminate conservatively as a miss
return false;
}
supports[support_count] = point;
support_count += 1;
for index in (1..=simplex_len.min(3)).rev() { for index in (1..=simplex_len.min(3)).rev() {
simplex[index] = simplex[index - 1]; simplex[index] = simplex[index - 1];
} }
@@ -69,11 +79,11 @@ impl FixedAffineCapsule {
return true; return true;
} }
} }
// A capped GJK iteration means the origin remains enclosed by the // Exhaustion means the fixed-point solver could not prove an
// current simplex to fixed-point precision, so conservatively collide. // intersection. Treating it as a hit creates phantom contacts for
true // cycling or degenerate simplexes
false
} }
} }
trait SupportMap { trait SupportMap {
@@ -243,18 +253,10 @@ mod tests {
#[test] #[test]
fn affine_scale_changes_capsule_intersection() { fn affine_scale_changes_capsule_intersection() {
let sphere = FixedAffineCapsule::new( let sphere = FixedAffineCapsule::new(FixedMat4::IDENTITY, FGi32::ZERO, FGi32::lit("1"));
FixedMat4::IDENTITY,
FGi32::ZERO,
FGi32::lit("1"),
);
let mut squashed_transform = FixedMat4::IDENTITY; let mut squashed_transform = FixedMat4::IDENTITY;
squashed_transform.cols[1][1] = FGi32::lit("0.5"); squashed_transform.cols[1][1] = FGi32::lit("0.5");
let squashed = FixedAffineCapsule::new( let squashed = FixedAffineCapsule::new(squashed_transform, FGi32::ZERO, FGi32::lit("1"));
squashed_transform,
FGi32::ZERO,
FGi32::lit("1"),
);
let target = FixedCapsule::new( let target = FixedCapsule::new(
FGVec3::lit("0", "1.4", "0"), FGVec3::lit("0", "1.4", "0"),
FGVec3::lit("0", "1.4", "0"), FGVec3::lit("0", "1.4", "0"),
+33 -6
View File
@@ -1,9 +1,6 @@
use std::collections::HashMap; use std::collections::HashMap;
use bevy::{ use bevy::{asset::UntypedHandle, prelude::*};
asset::UntypedHandle,
prelude::*,
};
use bevy_asset_loader::asset_collection::AssetCollection; use bevy_asset_loader::asset_collection::AssetCollection;
use ron_asset_manager::prelude::RonAsset; use ron_asset_manager::prelude::RonAsset;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -11,10 +8,16 @@ use strum::IntoEnumIterator;
use strum_macros::EnumIter; use strum_macros::EnumIter;
use crate::{ use crate::{
AppState, fighter::{FighterAttributes, FighterCameraProfile, animation::AnimKind, attack::AttackKind}, game_settings::GameSettings, math::{int::FGi32, vec3::FGVec3}, texture_reference::TextureReference, AppState,
fighter::{FighterAttributes, FighterCameraProfile, animation::AnimKind, attack::AttackKind},
game_settings::GameSettings,
math::{int::FGi32, vec3::FGVec3},
texture_reference::TextureReference,
}; };
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Reflect, EnumIter, Default)] #[derive(
Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Reflect, EnumIter, Default,
)]
pub enum FighterId { pub enum FighterId {
#[default] #[default]
TestFighter, TestFighter,
@@ -31,10 +34,27 @@ pub struct FighterHurtbox {
pub radius: FGi32, pub radius: FGi32,
} }
impl FighterHurtbox {
pub fn validate(&self) -> Result<(), String> {
if self.bone.trim().is_empty() {
return Err("bone name is empty".into());
}
if self.radius <= FGi32::ZERO {
return Err("radius must be positive".into());
}
if self.half_length < FGi32::ZERO {
return Err("half-length must be non-negative".into());
}
Ok(())
}
}
#[derive(Clone, Asset, Deserialize, Reflect, RonAsset)] #[derive(Clone, Asset, Deserialize, Reflect, RonAsset)]
pub struct FighterManifest { pub struct FighterManifest {
pub id: FighterId, pub id: FighterId,
pub model_path: String, pub model_path: String,
#[reflect(ignore)]
pub model_scale: FGi32,
pub baked_animation_path: String, pub baked_animation_path: String,
#[asset] #[asset]
#[dependency] #[dependency]
@@ -108,6 +128,13 @@ pub fn prepare_fighter_manifests(
); );
return; return;
} }
if manifest.model_scale <= FGi32::ZERO {
fail(
&mut next_state,
&format!("{:?} has a non-positive model scale", manifest.id),
);
return;
}
if manifest.baked_animation_path.is_empty() { if manifest.baked_animation_path.is_empty() {
fail( fail(
&mut next_state, &mut next_state,
+109 -53
View File
@@ -13,6 +13,7 @@ pub mod baked_animation;
pub mod collision; pub mod collision;
pub mod debug; pub mod debug;
pub mod ecb; pub mod ecb;
pub mod errors;
pub mod hurtbox; pub mod hurtbox;
pub mod manifest; pub mod manifest;
pub mod motion; pub mod motion;
@@ -26,11 +27,22 @@ pub mod visual;
pub use attributes::FighterAttributes; pub use attributes::FighterAttributes;
pub use ecb::FighterECB; pub use ecb::FighterECB;
pub use manifest::FighterId; pub use manifest::FighterId;
pub use motion::{FighterPreviousTranslation, FighterTranslation, FighterVelocity, Grounded}; pub use motion::{
FighterPreviousFacingDirection, FighterPreviousTranslation, FighterTranslation,
FighterVelocity, Grounded,
};
use crate::{ use crate::{
fighter::{ AppState, fighter::{
attack::{FighterAttackPlugin, FighterAttackScriptAssets, FighterSolvedHurtboxes}, baked_animation::FighterBoneMatrices, hurtbox::FixedCapsule, manifest::FighterManifest, state::{FighterState, fall::FallState}, visual::FighterAnimations, attack::{
AttackKind, FighterAttackPlugin, FighterAttackScriptAssets, FighterDamage,
FighterKnockbackVelocity, FighterPendingHitReaction, FighterReceivedAttacks,
FighterSolvedHurtboxes, FighterStaleMoveQueue,
},
baked_animation::{FighterBoneIndexMap, FighterBoneMatrices},
manifest::FighterManifest,
state::{FighterState, fall::FallState},
visual::FighterAnimations,
}, input::FighterInput, math::{int::FGi32, vec::FGVec2}, player::Player, schedule::GameplaySet, scripting::FighterAttackScript, stage::line::StageCollision, }, input::FighterInput, math::{int::FGi32, vec::FGVec2}, player::Player, schedule::GameplaySet, scripting::FighterAttackScript, stage::line::StageCollision,
}; };
use state::state_interrupt_system; use state::state_interrupt_system;
@@ -46,6 +58,11 @@ pub enum FighterFacingDirection {
Right, Right,
} }
#[derive(Component, Default, Copy, Clone, Hash)]
pub struct FighterHitstop {
pub remaining_frames: u32,
}
impl FighterFacingDirection { impl FighterFacingDirection {
fn reverse(&self) -> Self { fn reverse(&self) -> Self {
match self { match self {
@@ -91,10 +108,21 @@ impl FighterFacingDirection {
pub struct FighterVisual; pub struct FighterVisual;
#[derive(Component)] #[derive(Component)]
#[require(
FighterReceivedAttacks,
FighterStaleMoveQueue,
FighterDamage,
FighterPendingHitReaction,
FighterHitstop,
FighterKnockbackVelocity
)]
pub struct Fighter { pub struct Fighter {
pub manifest: Handle<FighterManifest>, pub manifest: Handle<FighterManifest>,
} }
#[derive(Resource, Clone, Debug)]
pub struct FighterRoster(pub Vec<Entity>);
impl Plugin for FighterPlugin { impl Plugin for FighterPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins(FighterAttackPlugin) app.add_plugins(FighterAttackPlugin)
@@ -102,7 +130,8 @@ impl Plugin for FighterPlugin {
.add_systems( .add_systems(
GgrsSchedule, GgrsSchedule,
( (
ecb::snapshot_fighter_ecb.before(state_interrupt_system), (ecb::snapshot_fighter_ecb, motion::snapshot_fighter_motion)
.before(state_interrupt_system),
animation::advance_fighter_animation_frames.before(state_interrupt_system), animation::advance_fighter_animation_frames.before(state_interrupt_system),
state::state_interrupt_system, state::state_interrupt_system,
) )
@@ -110,7 +139,9 @@ impl Plugin for FighterPlugin {
) )
.add_systems( .add_systems(
GgrsSchedule, GgrsSchedule,
(state::state_update_system,).in_set(GameplaySet::StateUpdate), (state::state_update_system, decay_hitstop)
.chain()
.in_set(GameplaySet::StateUpdate),
) )
/*.add_systems( /*.add_systems(
GgrsSchedule, GgrsSchedule,
@@ -136,6 +167,8 @@ impl Plugin for FighterPlugin {
// is a desync waiting to happen. // is a desync waiting to happen.
.rollback_component_with_copy::<FighterECB>() .rollback_component_with_copy::<FighterECB>()
.checksum_component_with_hash::<FighterECB>() .checksum_component_with_hash::<FighterECB>()
.rollback_component_with_clone::<FighterStaleMoveQueue>()
.checksum_component_with_hash::<FighterStaleMoveQueue>()
.rollback_component_with_copy::<ecb::FighterPreviousECB>() .rollback_component_with_copy::<ecb::FighterPreviousECB>()
.checksum_component_with_hash::<ecb::FighterPreviousECB>() .checksum_component_with_hash::<ecb::FighterPreviousECB>()
.rollback_component_with_copy::<FighterVelocity>() .rollback_component_with_copy::<FighterVelocity>()
@@ -144,11 +177,23 @@ impl Plugin for FighterPlugin {
.checksum_component_with_hash::<FighterTranslation>() .checksum_component_with_hash::<FighterTranslation>()
.rollback_component_with_copy::<FighterPreviousTranslation>() .rollback_component_with_copy::<FighterPreviousTranslation>()
.checksum_component_with_hash::<FighterPreviousTranslation>() .checksum_component_with_hash::<FighterPreviousTranslation>()
.rollback_component_with_copy::<FighterPreviousFacingDirection>()
.checksum_component_with_hash::<FighterPreviousFacingDirection>()
.rollback_component_with_copy::<animation::FighterAnimationFrame>() .rollback_component_with_copy::<animation::FighterAnimationFrame>()
.checksum_component_with_hash::<animation::FighterAnimationFrame>() .checksum_component_with_hash::<animation::FighterAnimationFrame>()
.rollback_component_with_copy::<Grounded>() .rollback_component_with_copy::<Grounded>()
.checksum_component_with_hash::<Grounded>() .checksum_component_with_hash::<Grounded>()
.rollback_component_with_copy::<FighterFacingDirection>() .rollback_component_with_copy::<FighterFacingDirection>()
.rollback_component_with_copy::<FighterDamage>()
.checksum_component_with_hash::<FighterDamage>()
.rollback_component_with_clone::<FighterPendingHitReaction>()
.checksum_component_with_hash::<FighterPendingHitReaction>()
.rollback_component_with_copy::<FighterHitstop>()
.checksum_component_with_hash::<FighterHitstop>()
.rollback_component_with_copy::<FighterKnockbackVelocity>()
.checksum_component_with_hash::<FighterKnockbackVelocity>()
.rollback_component_with_clone::<FighterReceivedAttacks>()
.checksum_component_with_hash::<FighterReceivedAttacks>()
.rollback_resource_with_reflect::<StageCollision>() .rollback_resource_with_reflect::<StageCollision>()
// Debug views. // Debug views.
.add_systems( .add_systems(
@@ -165,7 +210,13 @@ impl Plugin for FighterPlugin {
) )
.add_systems( .add_systems(
FixedPostUpdate, FixedPostUpdate,
debug::attack_debug.run_if(crate::debug_tools::attack_hitboxes_enabled), (
debug::attack_debug_gather,
(debug::attack_debug, debug::attack_launch_debug_draw)
.after(debug::attack_debug_gather),
)
.chain()
.run_if(crate::debug_tools::attack_hitboxes_enabled).run_if(in_state(AppState::InMatch)),
) )
.add_systems( .add_systems(
FixedPostUpdate, FixedPostUpdate,
@@ -182,64 +233,69 @@ impl Plugin for FighterPlugin {
.register_type::<FighterFacingDirection>(); .register_type::<FighterFacingDirection>();
} }
} }
#[derive(Clone, Debug, Hash)]
#[derive(Component, Clone, Hash)] pub struct FighterActiveAttack {
pub struct FighterHitboxes { pub kind: AttackKind,
pub attack_script: Option<Handle<FighterAttackScript>>, pub script: Handle<FighterAttackScript>,
pub active_hitboxes: Vec<usize>, pub active_hitboxes: Vec<usize>,
pub active_hitboxes_solved: Vec<FixedCapsule>, pub solved_hitboxes: Vec<attack::FighterSolvedHitbox>,
pub hit_fighters: Vec<Entity>,
} }
impl FighterHitboxes { #[derive(Component, Clone, Debug, Default, Hash)]
pub fn clear(&mut self) { pub struct FighterHitboxes(pub Option<FighterActiveAttack>);
self.attack_script = None;
self.active_hitboxes.clear();
}
}
pub fn spawn_fighter( pub fn spawn_fighter(
commands: &mut Commands, commands: &mut Commands,
player_handle: usize, player_handle: usize,
spawn_position: FGVec2, spawn_position: FGVec2,
manifest: Handle<FighterManifest>, manifest: Handle<FighterManifest>,
model_scale: FGi32,
animations: FighterAnimations, animations: FighterAnimations,
attack_scripts: FighterAttackScriptAssets, attack_scripts: FighterAttackScriptAssets,
visual_root: WorldAssetRoot, visual_root: WorldAssetRoot,
) { ) -> Entity {
commands.spawn(( commands
Name(format!("Fighter {player_handle}").into()), .spawn((
Player { Name(format!("Fighter {player_handle}").into()),
handle: player_handle, Player {
}, handle: player_handle,
Fighter { manifest: manifest },
FighterFacingDirection::Right,
(
FighterECB {
vertical_half: FGi32::lit("5.0"),
horizontal_half: FGi32::lit("2.5"),
}, },
FighterHitboxes { Fighter { manifest: manifest },
attack_script: None, FighterFacingDirection::Right,
active_hitboxes: vec![], FighterPreviousFacingDirection(FighterFacingDirection::Right),
active_hitboxes_solved: vec![] Transform::from_scale(Vec3::splat(model_scale.to_num())),
}, (
), FighterECB {
( vertical_half: FGi32::lit("5.0"),
FighterVelocity::default(), horizontal_half: FGi32::lit("2.5"),
FighterTranslation(spawn_position), },
FighterPreviousTranslation(spawn_position), FighterHitboxes::default(),
), ),
visual_root, (
animations, FighterVelocity::default(),
attack_scripts, FighterTranslation(spawn_position),
FighterState::Fall(FallState), FighterPreviousTranslation(spawn_position),
animation::FighterAnimationFrame::new(animation::AnimKind::Wait, true), ),
( visual_root,
baked_animation::FighterBoneMatrices::default(), animations,
FighterSolvedHurtboxes::default(), attack_scripts,
FighterVisual, FighterState::Fall(FallState),
FighterInput::default(), animation::FighterAnimationFrame::new(animation::AnimKind::Wait, true),
crate::camera::FighterCameraExtents::default(), (
), baked_animation::FighterBoneMatrices::default(),
)); FighterBoneIndexMap::default(),
FighterSolvedHurtboxes::default(),
FighterVisual,
FighterInput::default(),
crate::camera::FighterCameraExtents::default(),
),
))
.id()
}
pub fn decay_hitstop(query: Query<&mut FighterHitstop>) {
for mut hitstop in query {
hitstop.remaining_frames = hitstop.remaining_frames.saturating_sub(1);
}
} }
+47
View File
@@ -10,6 +10,9 @@ use crate::{
math::{int::FGi32, vec::FGVec2, vec3::FGVec3}, math::{int::FGi32, vec::FGVec2, vec3::FGVec3},
}; };
#[derive(Component, Clone, Copy, Hash)]
pub struct FighterPreviousFacingDirection(pub FighterFacingDirection);
#[derive(Component, Clone, Copy, Hash)] #[derive(Component, Clone, Copy, Hash)]
pub struct Grounded; pub struct Grounded;
@@ -100,6 +103,20 @@ pub fn copy_fighter_transform_to_visuals(fighters: Query<(&FighterTranslation, &
pub fn fighter_movement() {} pub fn fighter_movement() {}
pub fn snapshot_fighter_motion(
query: Query<(
&FighterTranslation,
&FighterFacingDirection,
&mut FighterPreviousTranslation,
&mut FighterPreviousFacingDirection,
)>,
) {
for (translation, facing, mut previous_translation, mut previous_facing) in query {
previous_translation.0 = translation.0;
previous_facing.0 = *facing;
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -127,4 +144,34 @@ mod tests {
assert_eq!(position, Vec2::new(7.0, 14.0)); assert_eq!(position, Vec2::new(7.0, 14.0));
} }
#[test]
fn snapshot_fighter_motion_copies_current_world_state() {
let mut world = World::new();
world.spawn((
FighterTranslation(FGVec2::new(FGi32::lit("3"), FGi32::lit("4"))),
FighterFacingDirection::Left,
FighterPreviousTranslation::default(),
FighterPreviousFacingDirection(FighterFacingDirection::Right),
));
let mut schedule = Schedule::default();
schedule.add_systems(snapshot_fighter_motion);
schedule.run(&mut world);
let (_, _, previous_translation, previous_facing) = world
.query::<(
&FighterTranslation,
&FighterFacingDirection,
&FighterPreviousTranslation,
&FighterPreviousFacingDirection,
)>()
.single(&world)
.unwrap();
assert_eq!(
previous_translation.0,
FGVec2::new(FGi32::lit("3"), FGi32::lit("4"))
);
assert_eq!(previous_facing.0, FighterFacingDirection::Left);
}
} }
+84 -26
View File
@@ -18,32 +18,24 @@ pub fn apply_air_drift(
velocity.x += (-velocity_sign) * attribs.air_friction; velocity.x += (-velocity_sign) * attribs.air_friction;
} }
} else { } else {
let target_velocity = let target_velocity = input.get_last_frame().movement.x * attribs.air_drift_max;
input.get_last_frame().movement.x.signum() * attribs.max_air_horizontal_velocity; let mut acceleration = input.get_last_frame().movement.x.signum()
let acceleration = * attribs.air_acceleration_base
input.get_last_frame().movement.x.signum() * attribs.air_acceleration_base; + input.get_last_frame().movement.x * attribs.air_acceleration_stick;
let mut acceleration =
acceleration + input.get_last_frame().movement.x * attribs.air_acceleration_stick; // Acceleration opposes velocity
let velocity_x = velocity.x; if acceleration * velocity.x < 0 {
if !(velocity_x * acceleration < FGi32::ZERO) { // do nothing
if acceleration > FGi32::ZERO { } else {
if velocity_x + acceleration > target_velocity { let predicted_vel = velocity.x + acceleration;
acceleration = -attribs.air_friction; let will_go_past = predicted_vel.abs() > target_velocity.abs();
if velocity_x + acceleration < target_velocity {
acceleration = target_velocity - velocity_x; if velocity.x.abs() < target_velocity.abs() && will_go_past {
} // Prevent overshoot
if velocity_x + acceleration > attribs.max_air_horizontal_velocity { acceleration = target_velocity - velocity.x
acceleration = attribs.max_air_horizontal_velocity - velocity_x; } else if velocity.x.abs() > target_velocity.abs() {
} let diff = (velocity.x - target_velocity).abs();
} acceleration = velocity.x.signum() * (-(attribs.air_friction).min(diff));
} else if velocity_x + acceleration < target_velocity {
acceleration = attribs.air_friction;
if velocity_x + acceleration > target_velocity {
acceleration = target_velocity - velocity_x;
}
if velocity_x + acceleration < -attribs.max_air_horizontal_velocity {
acceleration = -attribs.max_air_horizontal_velocity - velocity_x;
}
} }
} }
@@ -60,3 +52,69 @@ pub fn apply_air_motion(
prev_translation.0 = translation.0; prev_translation.0 = translation.0;
translation.0 += velocity.0; translation.0 += velocity.0;
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::{
input::{FighterInput, FighterInputFrame},
math::vec::FGVec2,
};
fn test_attributes() -> FighterAttributes {
FighterAttributes {
base_walk_accel: FGi32::ZERO,
stick_walk_accel: FGi32::ZERO,
max_walk_vel: FGi32::ZERO,
dash_acceleration_duration: 0,
dash_duration: 0,
dash_initial_velocity: FGi32::ZERO,
base_dash_accel: FGi32::ZERO,
stick_dash_accel: FGi32::ZERO,
max_dash_vel: FGi32::ZERO,
jumpsquat_duration: 0,
short_hop_vertical_velocity: FGi32::ZERO,
full_jump_vertical_velocity: FGi32::ZERO,
jump_horizontal_velocity: FGi32::ZERO,
air_jump_multiplier: FGi32::ZERO,
air_jump_horizontal_velocity: FGi32::ZERO,
landing_iasa: 0,
landing_duration: 0,
air_acceleration_base: FGi32::ZERO,
air_acceleration_stick: FGi32::ZERO,
max_air_horizontal_velocity: FGi32::lit("1.2"),
air_drift_max: FGi32::lit("1.2"),
ground_friction: FGi32::ZERO,
terminal_velocity: FGi32::ZERO,
gravity: FGi32::ZERO,
weight: FGi32::lit("1"),
air_friction: FGi32::lit("0.001"),
air_dodge_duration: 0,
air_dodge_velocity: FGi32::ZERO,
air_dodge_decay: FGi32::ZERO,
}
}
#[test]
fn zero_air_acceleration_is_symmetric() {
let attributes = test_attributes();
let mut right_input = FighterInput::default();
right_input.push_input_frame(FighterInputFrame {
movement: FGVec2::new(FGi32::ONE, FGi32::ZERO),
..default()
});
let mut left_input = FighterInput::default();
left_input.push_input_frame(FighterInputFrame {
movement: FGVec2::new(-FGi32::ONE, FGi32::ZERO),
..default()
});
let mut right_velocity = FighterVelocity(FGVec2::ZERO);
let mut left_velocity = FighterVelocity(FGVec2::ZERO);
apply_air_drift(&mut right_velocity, &attributes, &right_input);
apply_air_drift(&mut left_velocity, &attributes, &left_input);
assert_eq!(right_velocity.x, FGi32::ZERO);
assert_eq!(left_velocity.x, FGi32::ZERO);
}
}
+8 -3
View File
@@ -3,8 +3,10 @@ use crate::{
animation::AnimKind, animation::AnimKind,
collision, collision,
state::{ state::{
FighterState, FighterStateContext, FighterStateImpl, air, fall::FallState, FighterState, FighterStateContext, FighterStateImpl, air,
ground::GroundedStateCommon, land::LandingState, fall::FallState,
ground::GroundedStateCommon,
land::{LandingState, LandingType},
}, },
}, },
input, input,
@@ -47,7 +49,10 @@ impl FighterStateImpl for AirDodgeState {
let grounded_common = GroundedStateCommon { let grounded_common = GroundedStateCommon {
current_line_id: res.line_id, current_line_id: res.line_id,
}; };
Some(FighterState::Land(LandingState { grounded_common })) Some(FighterState::Land(LandingState {
grounded_common,
landing_type: LandingType::Special,
}))
} else { } else {
None None
} }
+1 -1
View File
@@ -11,7 +11,7 @@ use crate::input::FighterCommands::{SmashMoveLeft, SmashMoveRight};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct DashState { pub struct DashState {
direction: FighterFacingDirection, direction: FighterFacingDirection,
ground_common: GroundedStateCommon, pub ground_common: GroundedStateCommon,
} }
impl std::hash::Hash for DashState { impl std::hash::Hash for DashState {
+5 -2
View File
@@ -2,7 +2,7 @@ use super::{FighterStateContext, FighterStateImpl};
use crate::fighter::animation::AnimKind; use crate::fighter::animation::AnimKind;
use crate::fighter::collision; use crate::fighter::collision;
use crate::fighter::state::ground::GroundedStateCommon; use crate::fighter::state::ground::GroundedStateCommon;
use crate::fighter::state::land::LandingState; use crate::fighter::state::land::{LandingState, LandingType};
use crate::fighter::state::{FighterState, air, jump}; use crate::fighter::state::{FighterState, air, jump};
#[derive(Debug, Clone, Copy, Hash)] #[derive(Debug, Clone, Copy, Hash)]
@@ -45,7 +45,10 @@ impl FighterStateImpl for FallState {
let grounded_common = GroundedStateCommon { let grounded_common = GroundedStateCommon {
current_line_id: res.line_id, current_line_id: res.line_id,
}; };
Some(FighterState::Land(LandingState { grounded_common })) Some(FighterState::Land(LandingState::create(
grounded_common,
LandingType::Normal,
)))
} else { } else {
None None
} }
+218 -39
View File
@@ -9,9 +9,9 @@ use crate::fighter::{
FighterAttributes, FighterPreviousTranslation, FighterTranslation, FighterVelocity, FighterAttributes, FighterPreviousTranslation, FighterTranslation, FighterVelocity,
}; };
use crate::game_settings::GameSettings; use crate::game_settings::GameSettings;
use crate::math::int::FGi32; use crate::math::int::{FGWide, FGi32};
use crate::math::vec::FGVec2; use crate::math::vec::FGVec2;
use crate::stage::line::{StageLineID, StagePolyLineSegmentType}; use crate::stage::line::{StageLineID, StagePoly, StagePolyLineSegment, StagePolyLineSegmentType};
use bevy::prelude::*; use bevy::prelude::*;
@@ -74,6 +74,85 @@ pub enum GroundedMotionResult {
InAir, InAir,
} }
enum GroundedPositionResult {
InGround {
point: FGVec2,
segment_idx: usize,
blocked: bool,
},
InAir,
}
fn is_walkable_floor(segment: &StagePolyLineSegment) -> bool {
segment.segment_type == StagePolyLineSegmentType::Floor && segment.normal.y > FGi32::ZERO
}
fn resolve_grounded_position(
stage_poly: &StagePoly,
starting_segment_idx: usize,
point: FGVec2,
can_walk_off: bool,
) -> GroundedPositionResult {
let mut segment_idx = starting_segment_idx;
// A single frame can cross several short connected segments. The bound also
// prevents malformed closed polygons from cycling forever.
for _ in 0..stage_poly.segments.len() {
let Some(segment) = stage_poly.get_segment(segment_idx) else {
return GroundedPositionResult::InAir;
};
if !is_walkable_floor(segment) {
return GroundedPositionResult::InAir;
}
let segment_vector = segment.segment.point2() - segment.segment.point1();
let projection = segment_vector.dot(point - segment.segment.point1());
let length_squared = segment_vector.length_squared();
let (next_segment_idx, edge_point) = if projection < FGWide::ZERO {
(
stage_poly.get_prev_segment_index(segment_idx),
segment.segment.point1(),
)
} else if projection > length_squared {
(
stage_poly.get_next_segment_index(segment_idx),
segment.segment.point2(),
)
} else {
let projected_point = segment.segment.point1()
+ (point - segment.segment.point1()).project_onto(segment.segment.direction());
return GroundedPositionResult::InGround {
point: projected_point,
segment_idx,
blocked: false,
};
};
if let Some(next_segment_idx) = next_segment_idx
&& next_segment_idx != segment_idx
&& stage_poly
.get_segment(next_segment_idx)
.is_some_and(is_walkable_floor)
{
segment_idx = next_segment_idx;
continue;
}
return if can_walk_off {
GroundedPositionResult::InAir
} else {
GroundedPositionResult::InGround {
point: edge_point,
segment_idx,
blocked: true,
}
};
}
GroundedPositionResult::InAir
}
pub fn apply_grounded_motion( pub fn apply_grounded_motion(
velocity: &FighterVelocity, velocity: &FighterVelocity,
translation: &mut FighterTranslation, translation: &mut FighterTranslation,
@@ -87,7 +166,7 @@ pub fn apply_grounded_motion(
pub fn collide_with_stage_grounded( pub fn collide_with_stage_grounded(
state_context: &mut FighterStateContext, state_context: &mut FighterStateContext,
ground_common: &mut GroundedStateCommon, ground_common: &mut GroundedStateCommon,
_can_walk_off: bool, can_walk_off: bool,
) -> GroundedMotionResult { ) -> GroundedMotionResult {
let translation = &mut state_context.translation; let translation = &mut state_context.translation;
let ecb = &state_context.ecb; let ecb = &state_context.ecb;
@@ -99,49 +178,149 @@ pub fn collide_with_stage_grounded(
if let Some(stage_poly) = stage_poly { if let Some(stage_poly) = stage_poly {
let ecb_bottom_pos = translation.0 + ecb.get_bottom_point(); let ecb_bottom_pos = translation.0 + ecb.get_bottom_point();
let current_segment_idx = ground_common.current_line_id.segment; match resolve_grounded_position(
stage_poly,
// First, we check the current segment, if that fails, we check the surrounding ones ground_common.current_line_id.segment,
let grounded_ecb_bottom_pos = [ ecb_bottom_pos,
Some(current_segment_idx), can_walk_off,
stage_poly.get_prev_segment_index(current_segment_idx), ) {
stage_poly.get_next_segment_index(current_segment_idx), GroundedPositionResult::InGround {
] point,
.into_iter() segment_idx,
.flatten() blocked,
.find_map(|segment_idx| { } => {
let segment = stage_poly.get_segment(segment_idx)?; let current_segment = stage_poly.get_segment(segment_idx).unwrap();
if segment.segment_type != StagePolyLineSegmentType::Floor { translation.0 = point - ecb.get_bottom_point();
return None; state_context.velocity.0 = if blocked {
FGVec2::ZERO
} else {
state_context.velocity.0
- state_context
.velocity
.0
.project_onto_normalized(current_segment.normal)
};
ground_common.current_line_id.segment = segment_idx;
GroundedMotionResult::InGround
} }
GroundedPositionResult::InAir => GroundedMotionResult::InAir,
let line_dir = segment.segment.direction();
let projected_point = segment.segment.point1()
+ (ecb_bottom_pos - segment.segment.point1()).project_onto(line_dir);
let closest_point = segment.segment.closest_point(ecb_bottom_pos);
let distance = closest_point.distance(projected_point);
if distance < 0.01 {
return Some((projected_point, segment_idx, segment.normal));
}
None
});
if let Some((bp, new_segment_idx, normal)) = grounded_ecb_bottom_pos {
translation.0 = bp - ecb.get_bottom_point();
state_context.velocity.0 =
state_context.velocity.0 - state_context.velocity.0.project_onto_normalized(normal);
ground_common.current_line_id.segment = new_segment_idx;
GroundedMotionResult::InGround
} else {
GroundedMotionResult::InAir
} }
} else { } else {
GroundedMotionResult::InAir GroundedMotionResult::InAir
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::stage::line::StagePolyType;
fn two_segment_floor() -> StagePoly {
StagePoly::build(
StagePolyType::Platform,
&[
(FGVec2::lit("0", "0"), StagePolyLineSegmentType::Floor),
(FGVec2::lit("10", "0"), StagePolyLineSegmentType::Floor),
(FGVec2::lit("20", "0"), StagePolyLineSegmentType::Floor),
],
)
}
#[test]
fn tiny_endpoint_crossing_moves_to_adjacent_floor() {
let stage = two_segment_floor();
let point = FGVec2::new(FGi32::from_bits(10 * 65_536 + 1), FGi32::ZERO);
let GroundedPositionResult::InGround {
point: resolved,
segment_idx,
blocked,
} = resolve_grounded_position(&stage, 0, point, false)
else {
panic!("connected floor should remain grounded");
};
assert_eq!(segment_idx, 1);
assert_eq!(resolved, point);
assert!(!blocked);
}
#[test]
fn blocked_edge_keeps_floor_and_can_move_inward() {
let stage = StagePoly::build(
StagePolyType::Platform,
&[
(FGVec2::lit("0", "0"), StagePolyLineSegmentType::Floor),
(FGVec2::lit("10", "0"), StagePolyLineSegmentType::Wall),
(FGVec2::lit("10", "-2"), StagePolyLineSegmentType::Ceiling),
],
);
let just_past_edge = FGVec2::new(FGi32::from_bits(10 * 65_536 + 1), FGi32::ZERO);
let GroundedPositionResult::InGround {
point,
segment_idx,
blocked,
} = resolve_grounded_position(&stage, 0, just_past_edge, false)
else {
panic!("non-walk-off movement should stop at the edge");
};
assert_eq!(point, FGVec2::lit("10", "0"));
assert_eq!(segment_idx, 0);
assert!(blocked);
let GroundedPositionResult::InGround {
point,
segment_idx,
blocked,
} = resolve_grounded_position(
&stage,
segment_idx,
FGVec2::new(FGi32::from_bits(10 * 65_536 - 1), FGi32::ZERO),
false,
)
else {
panic!("fighter should be able to move back from the edge");
};
assert!(point.x < FGi32::lit("10"));
assert_eq!(segment_idx, 0);
assert!(!blocked);
}
#[test]
fn walk_off_edge_enters_air() {
let stage = StagePoly::build(
StagePolyType::Platform,
&[
(FGVec2::lit("0", "0"), StagePolyLineSegmentType::Floor),
(FGVec2::lit("10", "0"), StagePolyLineSegmentType::Floor),
],
);
let just_past_edge = FGVec2::new(FGi32::from_bits(10 * 65_536 + 1), FGi32::ZERO);
assert!(matches!(
resolve_grounded_position(&stage, 0, just_past_edge, true),
GroundedPositionResult::InAir
));
}
#[test]
fn vertical_segment_cannot_hold_grounded_fighter() {
let stage = StagePoly::build(
StagePolyType::Platform,
&[
(FGVec2::lit("10", "0"), StagePolyLineSegmentType::Floor),
(FGVec2::lit("10", "-2"), StagePolyLineSegmentType::Floor),
],
);
assert!(matches!(
resolve_grounded_position(&stage, 0, FGVec2::lit("10", "0"), false),
GroundedPositionResult::InAir
));
}
}
pub fn grounded_movement_common_interrupts( pub fn grounded_movement_common_interrupts(
state_context: &FighterStateContext, state_context: &FighterStateContext,
ground_common: &GroundedStateCommon, ground_common: &GroundedStateCommon,
+24 -15
View File
@@ -1,11 +1,6 @@
use fixed::types::I16F16; use crate::fighter::{
attack::{AttackKind, update_active_hitbox_list},
use crate::{ state::{FighterState, FighterStateImpl, ground::GroundedStateCommon, wait::WaitState},
fighter::{
attack::{AttackKind, update_active_hitbox_list},
state::{FighterState, FighterStateImpl, ground::GroundedStateCommon, wait::WaitState},
},
math::int::FGi32,
}; };
#[derive(Clone, Debug, Hash)] #[derive(Clone, Debug, Hash)]
@@ -31,14 +26,19 @@ impl FighterStateImpl for GroundAttackState {
} }
fn update(&mut self, state_context: &mut super::FighterStateContext) { fn update(&mut self, state_context: &mut super::FighterStateContext) {
let animation_frame = state_context.get_current_animation_frame();
let script = state_context let script = state_context
.attack_scripts .attack_scripts
.get(&state_context.attack_script_assets.scripts[&self.attack_kind]); .get(&state_context.attack_script_assets.scripts[&self.attack_kind]);
if let Some(script) = script { if let Some(script) = script {
let animation_frame = state_context.get_current_animation_frame();
update_active_hitbox_list( update_active_hitbox_list(
script, script,
&mut state_context.hitboxes.active_hitboxes, &mut state_context
.hitboxes
.0
.as_mut()
.expect("ground attack must have active hitboxes")
.active_hitboxes,
animation_frame, animation_frame,
); );
} }
@@ -46,13 +46,19 @@ impl FighterStateImpl for GroundAttackState {
fn on_enter(&mut self, state_context: &mut super::FighterStateContext) { fn on_enter(&mut self, state_context: &mut super::FighterStateContext) {
state_context.play_animation(self.attack_kind.get_animation(), false); state_context.play_animation(self.attack_kind.get_animation(), false);
state_context.hitboxes.attack_script = let script = state_context.attack_script_assets.scripts[&self.attack_kind].clone();
Some(state_context.attack_script_assets.scripts[&self.attack_kind].clone()); state_context.stale_move_queue.push(self.attack_kind);
state_context.hitboxes.active_hitboxes.clear(); state_context.hitboxes.0 = Some(crate::fighter::FighterActiveAttack {
kind: self.attack_kind,
script,
active_hitboxes: Vec::new(),
solved_hitboxes: Vec::new(),
hit_fighters: Vec::new(),
});
} }
fn on_exit(&mut self, state_context: &mut super::FighterStateContext) { fn on_exit(&mut self, state_context: &mut super::FighterStateContext) {
state_context.hitboxes.clear(); state_context.hitboxes.0 = None;
} }
fn check_collision_interrupt( fn check_collision_interrupt(
@@ -71,7 +77,10 @@ pub fn check_interrupt(
.input .input
.has_command(crate::input::FighterCommands::Attack) .has_command(crate::input::FighterCommands::Attack)
{ {
let attack_kind = state_context.input.get_attack_command_type().to_attack_kind_grounded(); let attack_kind = state_context
.input
.get_attack_command_type()
.to_attack_kind_grounded();
Some(FighterState::GroundAttack(GroundAttackState { Some(FighterState::GroundAttack(GroundAttackState {
attack_kind, attack_kind,
grounded_common: grounded_common.clone(), grounded_common: grounded_common.clone(),
+117
View File
@@ -0,0 +1,117 @@
use crate::{
fighter::{
animation::AnimKind,
attack::FighterHitReaction,
collision,
state::{
FighterState, FighterStateContext, FighterStateImpl, air,
fall::FallState,
ground::{GroundedMotionResult, GroundedStateCommon, collide_with_stage_grounded},
land::{LandingState, LandingType},
wait::WaitState,
},
},
math::int::FGi32,
};
#[derive(Clone, Debug, Hash)]
pub enum HitstopStateKind {
Grounded(GroundedStateCommon),
Airborne,
}
#[derive(Clone, Debug, Hash)]
pub struct HitstunState {
pub hit_reaction: FighterHitReaction,
pub hitstop_kind: HitstopStateKind,
}
impl FighterStateImpl for HitstunState {
const NAME: &'static str = "Hitstun";
fn name(&self) -> String {
let hitstop_kind = match self.hitstop_kind {
HitstopStateKind::Grounded(_) => "Grounded",
HitstopStateKind::Airborne => "Airborne",
};
let hit_reaction_type = match &self.hit_reaction.kind {
crate::fighter::attack::HitReactionKind::Flinch => "Flinch",
crate::fighter::attack::HitReactionKind::Tumble => "Tumble",
};
format!("Hitstun ({hitstop_kind}, {hit_reaction_type})")
}
fn check_interrupt(&self, state_context: &mut FighterStateContext) -> Option<FighterState> {
if state_context.get_current_animation_frame() > self.hit_reaction.hitstun_frames {
match &self.hitstop_kind {
HitstopStateKind::Grounded(grounded_state_common) => {
Some(FighterState::Wait(WaitState {
grounded_common: grounded_state_common.clone(),
}))
}
HitstopStateKind::Airborne => Some(FighterState::Fall(FallState)),
}
} else {
None
}
}
fn update(&mut self, ctx: &mut FighterStateContext) {
air::integrate_gravity(ctx.velocity, &ctx.fighter_manifest.attributes);
let speed = ctx.knockback_velocity.length();
let next_speed = speed
.saturating_sub(ctx.game_settings.fighter_common.knockback_decay_per_frame)
.max(FGi32::ZERO);
ctx.knockback_velocity.0 = ctx.knockback_velocity.normalize_or_zero() * next_speed;
ctx.translation.0 += ctx.velocity.0 + ctx.knockback_velocity.0;
}
fn on_enter(&mut self, state_context: &mut FighterStateContext) {
let animation = match self.hitstop_kind {
HitstopStateKind::Grounded(_) => AnimKind::FlinchGround,
HitstopStateKind::Airborne => AnimKind::FlinchAir,
};
state_context.play_animation(animation, false);
state_context.knockback_velocity.0 = self.hit_reaction.launch_velocity;
}
fn on_exit(&mut self, _state_context: &mut FighterStateContext) {}
fn check_collision_interrupt(
&mut self,
state_context: &mut FighterStateContext,
) -> Option<FighterState> {
match &mut self.hitstop_kind {
HitstopStateKind::Grounded(grounded_state_common) => {
if let GroundedMotionResult::InAir =
collide_with_stage_grounded(state_context, grounded_state_common, true)
{
Some(FighterState::Fall(FallState {}))
} else {
None
}
}
HitstopStateKind::Airborne => {
if let Some(res) = collision::air_collide_with_stage(state_context) {
// Adjust translation
state_context.translation.0 =
res.hit_position - state_context.ecb.get_bottom_point();
let grounded_common = GroundedStateCommon {
current_line_id: res.line_id,
};
Some(FighterState::Land(LandingState::create(
grounded_common,
LandingType::Normal,
)))
} else {
None
}
}
}
}
}
+12 -3
View File
@@ -9,7 +9,7 @@ use crate::{
air_dodge::{self, AirDodgeState}, air_dodge::{self, AirDodgeState},
fall::FallState, fall::FallState,
ground::{self, GroundedMotionResult, GroundedStateCommon}, ground::{self, GroundedMotionResult, GroundedStateCommon},
land::LandingState, land::{LandingState, LandingType},
}, },
}, },
input::FighterCommands, input::FighterCommands,
@@ -174,7 +174,13 @@ impl FighterStateImpl for JumpState {
} }
} }
JumpType::DoubleJump => { JumpType::DoubleJump => {
state_context.play_animation(AnimKind::DoubleJump, false); if movement_stick_x.is_zero()
|| movement_stick_x.signum() == state_context.facing_direction.to_sign()
{
state_context.play_animation(AnimKind::DoubleJumpForward, false);
} else {
state_context.play_animation(AnimKind::DoubleJumpBack, false);
}
} }
} }
@@ -233,7 +239,10 @@ impl FighterStateImpl for JumpState {
let grounded_common = GroundedStateCommon { let grounded_common = GroundedStateCommon {
current_line_id: res.line_id, current_line_id: res.line_id,
}; };
Some(FighterState::Land(LandingState { grounded_common })) Some(FighterState::Land(LandingState::create(
grounded_common,
LandingType::Normal,
)))
} else { } else {
None None
} }
+22 -4
View File
@@ -11,14 +11,24 @@ use crate::fighter::{
}, },
}; };
#[derive(Debug, Clone, Hash)]
pub enum LandingType {
Normal,
Special,
}
#[derive(Debug, Clone, Hash)] #[derive(Debug, Clone, Hash)]
pub struct LandingState { pub struct LandingState {
pub grounded_common: GroundedStateCommon, pub grounded_common: GroundedStateCommon,
pub landing_type: LandingType,
} }
impl LandingState { impl LandingState {
pub fn create(grounded_common: GroundedStateCommon) -> Self { pub fn create(grounded_common: GroundedStateCommon, landing_type: LandingType) -> Self {
Self { grounded_common } Self {
grounded_common,
landing_type,
}
} }
} }
@@ -30,6 +40,7 @@ impl FighterStateImpl for LandingState {
grounded_movement_standstill_common_interrupts(state_context, &self.grounded_common) grounded_movement_standstill_common_interrupts(state_context, &self.grounded_common)
} else if state_context.get_current_animation_frame() } else if state_context.get_current_animation_frame()
>= state_context.fighter_manifest.attributes.landing_iasa >= state_context.fighter_manifest.attributes.landing_iasa
&& let LandingType::Normal = self.landing_type
{ {
dash::check_input(state_context, &self.grounded_common).or_else(|| { dash::check_input(state_context, &self.grounded_common).or_else(|| {
ground::grounded_movement_common_interrupts(state_context, &self.grounded_common) ground::grounded_movement_common_interrupts(state_context, &self.grounded_common)
@@ -69,7 +80,7 @@ impl FighterStateImpl for LandingState {
state_context: &mut FighterStateContext, state_context: &mut FighterStateContext,
) -> Option<FighterState> { ) -> Option<FighterState> {
if let GroundedMotionResult::InAir = if let GroundedMotionResult::InAir =
ground::collide_with_stage_grounded(state_context, &mut self.grounded_common, false) ground::collide_with_stage_grounded(state_context, &mut self.grounded_common, true)
{ {
Some(FighterState::Fall(FallState)) Some(FighterState::Fall(FallState))
} else { } else {
@@ -78,6 +89,13 @@ impl FighterStateImpl for LandingState {
} }
fn on_enter(&mut self, state_context: &mut FighterStateContext) { fn on_enter(&mut self, state_context: &mut FighterStateContext) {
state_context.play_animation(AnimKind::Landing, false); match self.landing_type {
LandingType::Normal => {
state_context.play_animation(AnimKind::Landing, false);
}
LandingType::Special => {
state_context.play_animation(AnimKind::LandingSpecial, false);
}
};
} }
} }
+86 -37
View File
@@ -6,14 +6,18 @@ use bevy::ecs::query::QueryData;
use bevy::prelude::*; use bevy::prelude::*;
use crate::fighter::animation::{AnimKind, FighterAnimationFrame}; use crate::fighter::animation::{AnimKind, FighterAnimationFrame};
use crate::fighter::attack::FighterAttackScriptAssets; use crate::fighter::attack::{
FighterAttackScriptAssets, FighterKnockbackVelocity, FighterPendingHitReaction,
FighterStaleMoveQueue,
};
use crate::fighter::baked_animation::BakedFighterAnimations; use crate::fighter::baked_animation::BakedFighterAnimations;
use crate::fighter::ecb::FighterPreviousECB; use crate::fighter::ecb::FighterPreviousECB;
use crate::fighter::manifest::FighterManifest; use crate::fighter::manifest::FighterManifest;
use crate::fighter::state::hitstun::HitstunState;
use crate::fighter::visual::FighterAnimations; use crate::fighter::visual::FighterAnimations;
use crate::fighter::{ use crate::fighter::{
Fighter, FighterECB, FighterFacingDirection, FighterHitboxes, FighterPreviousTranslation, Fighter, FighterECB, FighterFacingDirection, FighterHitboxes, FighterHitstop,
FighterTranslation, FighterVelocity, FighterPreviousTranslation, FighterTranslation, FighterVelocity,
}; };
use crate::game_settings::GameSettings; use crate::game_settings::GameSettings;
use crate::input::FighterInput; use crate::input::FighterInput;
@@ -26,6 +30,7 @@ pub mod dash;
pub mod fall; pub mod fall;
pub mod ground; pub mod ground;
pub mod ground_attack; pub mod ground_attack;
pub mod hitstun;
pub mod jump; pub mod jump;
pub mod land; pub mod land;
pub mod run; pub mod run;
@@ -74,6 +79,9 @@ pub trait FighterStateImpl: Sized {
fn on_enter(&mut self, _state_context: &mut FighterStateContext) {} fn on_enter(&mut self, _state_context: &mut FighterStateContext) {}
fn on_exit(&mut self, _state_context: &mut FighterStateContext) {} fn on_exit(&mut self, _state_context: &mut FighterStateContext) {}
fn name(&self) -> String {
Self::NAME.to_owned()
}
fn update(&mut self, _state_context: &mut FighterStateContext); fn update(&mut self, _state_context: &mut FighterStateContext);
fn check_collision_interrupt( fn check_collision_interrupt(
@@ -90,6 +98,8 @@ pub struct FighterStateContext<'a> {
pub input: &'a mut FighterInput, pub input: &'a mut FighterInput,
pub hitboxes: &'a mut FighterHitboxes, pub hitboxes: &'a mut FighterHitboxes,
pub velocity: &'a mut FighterVelocity, pub velocity: &'a mut FighterVelocity,
pub knockback_velocity: &'a mut FighterKnockbackVelocity,
pub stale_move_queue: &'a mut FighterStaleMoveQueue,
pub ecb: &'a mut FighterECB, pub ecb: &'a mut FighterECB,
pub prev_ecb: &'a mut FighterPreviousECB, pub prev_ecb: &'a mut FighterPreviousECB,
pub facing_direction: &'a mut FighterFacingDirection, pub facing_direction: &'a mut FighterFacingDirection,
@@ -136,6 +146,7 @@ fighter_states! {
AirDodge => air_dodge::AirDodgeState, AirDodge => air_dodge::AirDodgeState,
Turn => turn::TurnState, Turn => turn::TurnState,
GroundAttack => ground_attack::GroundAttackState, GroundAttack => ground_attack::GroundAttackState,
Hitstun => hitstun::HitstunState,
} }
#[derive(QueryData)] #[derive(QueryData)]
@@ -146,6 +157,8 @@ pub struct FighterFrameQuery {
pub input: &'static mut FighterInput, pub input: &'static mut FighterInput,
pub hitboxes: &'static mut FighterHitboxes, pub hitboxes: &'static mut FighterHitboxes,
pub velocity: &'static mut FighterVelocity, pub velocity: &'static mut FighterVelocity,
pub knockback_velocity: &'static mut FighterKnockbackVelocity,
pub stale_move_queue: &'static mut FighterStaleMoveQueue,
pub ecb: &'static mut FighterECB, pub ecb: &'static mut FighterECB,
pub prev_ecb: &'static mut FighterPreviousECB, pub prev_ecb: &'static mut FighterPreviousECB,
pub facing_direction: &'static mut FighterFacingDirection, pub facing_direction: &'static mut FighterFacingDirection,
@@ -170,6 +183,8 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
input: &mut self.input, input: &mut self.input,
hitboxes: &mut self.hitboxes, hitboxes: &mut self.hitboxes,
velocity: &mut self.velocity, velocity: &mut self.velocity,
knockback_velocity: &mut self.knockback_velocity,
stale_move_queue: &mut self.stale_move_queue,
ecb: &mut self.ecb, ecb: &mut self.ecb,
prev_ecb: &mut self.prev_ecb, prev_ecb: &mut self.prev_ecb,
facing_direction: &mut self.facing_direction, facing_direction: &mut self.facing_direction,
@@ -188,21 +203,13 @@ impl<'w, 's> FighterFrameQueryItem<'w, 's> {
#[derive(QueryData)] #[derive(QueryData)]
#[query_data(mutable)] #[query_data(mutable)]
pub struct StatefulFighterQuery { pub struct StatefulFighterQuery {
pub entity: Entity,
pub state: &'static mut FighterState, pub state: &'static mut FighterState,
pub frame: FighterFrameQuery, pub frame: FighterFrameQuery,
pub animations: &'static FighterAnimations, pub animations: &'static FighterAnimations,
pub fighter: &'static Fighter, pub fighter: &'static Fighter,
pub attack_script_assets: &'static FighterAttackScriptAssets, pub attack_script_assets: &'static FighterAttackScriptAssets,
} pub pending_hit_reaction: &'static mut FighterPendingHitReaction,
pub hitstop: &'static mut FighterHitstop,
#[derive(Component)]
pub struct StateNameDebug(pub &'static str);
impl std::fmt::Display for StateNameDebug {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
} }
pub fn state_update_system( pub fn state_update_system(
@@ -218,9 +225,14 @@ pub fn state_update_system(
mut state, mut state,
mut frame, mut frame,
animations, animations,
hitstop,
.. ..
} = fighter; } = fighter;
if hitstop.remaining_frames > 0 {
continue;
}
let mut update_ctx = frame.context( let mut update_ctx = frame.context(
&game_settings, &game_settings,
&stage_collision, &stage_collision,
@@ -236,6 +248,20 @@ pub fn state_update_system(
} }
} }
fn transition_state(
current: &mut FighterState,
mut next: FighterState,
ctx: &mut FighterStateContext,
) {
let old_name = current.name();
let new_name = next.name();
current.on_exit(ctx);
next.on_enter(ctx);
*current = next;
info!("{} -> {}", old_name, new_name);
}
pub fn state_interrupt_system( pub fn state_interrupt_system(
mut query: Query<StatefulFighterQuery>, mut query: Query<StatefulFighterQuery>,
stage_collision: Res<StageCollision>, stage_collision: Res<StageCollision>,
@@ -243,16 +269,16 @@ pub fn state_interrupt_system(
baked_animations: Res<Assets<BakedFighterAnimations>>, baked_animations: Res<Assets<BakedFighterAnimations>>,
fighter_manifests: Res<Assets<FighterManifest>>, fighter_manifests: Res<Assets<FighterManifest>>,
attack_scripts: Res<Assets<FighterAttackScript>>, attack_scripts: Res<Assets<FighterAttackScript>>,
mut commands: Commands,
) { ) {
for fighter in &mut query { for fighter in &mut query {
let StatefulFighterQueryItem { let StatefulFighterQueryItem {
entity,
mut state, mut state,
mut frame, mut frame,
animations, animations,
fighter, fighter,
attack_script_assets, attack_script_assets,
mut pending_hit_reaction,
mut hitstop,
} = fighter; } = fighter;
let mut state_context = frame.context( let mut state_context = frame.context(
&game_settings, &game_settings,
@@ -265,17 +291,43 @@ pub fn state_interrupt_system(
.get(&fighter.manifest) .get(&fighter.manifest)
.expect("Fighter manifest should be valid"), .expect("Fighter manifest should be valid"),
); );
if let Some(new_state) = state.check_interrupt(&mut state_context) {
let mut new_state = new_state; let new_state = if let Some(reaction) = pending_hit_reaction.take() {
let old_state_name = state.name(); hitstop.remaining_frames = *reaction.hitstop_frames;
let new_state_name = new_state.name(); let hitstop_kind = match &*state {
state.on_exit(&mut state_context); FighterState::Wait(value) => {
new_state.on_enter(&mut state_context); hitstun::HitstopStateKind::Grounded(value.grounded_common.clone())
commands }
.entity(entity) FighterState::Walk(value) => {
.insert((new_state, StateNameDebug(new_state_name))); hitstun::HitstopStateKind::Grounded(value.grounded_common.clone())
info!("State {} -> {}", old_state_name, new_state_name); }
} FighterState::Dash(value) => {
hitstun::HitstopStateKind::Grounded(value.ground_common.clone())
}
FighterState::Run(value) => {
hitstun::HitstopStateKind::Grounded(value.grounded_common.clone())
}
FighterState::Turn(value) => {
hitstun::HitstopStateKind::Grounded(value.grounded_common.clone())
}
FighterState::GroundAttack(value) => {
hitstun::HitstopStateKind::Grounded(value.grounded_common.clone())
}
_ => hitstun::HitstopStateKind::Airborne,
};
Some(FighterState::Hitstun(HitstunState {
hit_reaction: reaction,
hitstop_kind,
}))
} else if hitstop.remaining_frames > 0 {
None
} else {
state.check_interrupt(&mut state_context)
};
if let Some(new_state) = new_state {
transition_state(&mut state, new_state, &mut state_context);
};
} }
} }
@@ -286,16 +338,16 @@ pub fn state_collision_interrupt_system(
baked_animations: Res<Assets<BakedFighterAnimations>>, baked_animations: Res<Assets<BakedFighterAnimations>>,
fighter_manifests: Res<Assets<FighterManifest>>, fighter_manifests: Res<Assets<FighterManifest>>,
attack_scripts: Res<Assets<FighterAttackScript>>, attack_scripts: Res<Assets<FighterAttackScript>>,
mut commands: Commands,
) { ) {
for fighter in &mut query { for fighter in &mut query {
let StatefulFighterQueryItem { let StatefulFighterQueryItem {
entity,
mut state, mut state,
mut frame, mut frame,
animations, animations,
fighter, fighter,
attack_script_assets, attack_script_assets,
hitstop,
..
} = fighter; } = fighter;
let mut state_context = frame.context( let mut state_context = frame.context(
&game_settings, &game_settings,
@@ -308,16 +360,13 @@ pub fn state_collision_interrupt_system(
.get(&fighter.manifest) .get(&fighter.manifest)
.expect("Fighter manifest should be valid"), .expect("Fighter manifest should be valid"),
); );
if hitstop.remaining_frames > 0 {
continue;
}
if let Some(new_state) = state.check_collision_interrupt(&mut state_context) { if let Some(new_state) = state.check_collision_interrupt(&mut state_context) {
let mut new_state = new_state; transition_state(&mut state, new_state, &mut state_context);
let old_state_name = state.name();
let new_state_name = new_state.name();
state.on_exit(&mut state_context);
new_state.on_enter(&mut state_context);
commands
.entity(entity)
.insert((new_state, StateNameDebug(new_state_name)));
info!("State {} -> {}", old_state_name, new_state_name);
} }
} }
} }
+22 -6
View File
@@ -3,17 +3,29 @@ use crate::fighter::animation::AnimKind;
use crate::fighter::state::fall::FallState; use crate::fighter::state::fall::FallState;
use crate::fighter::state::ground::{self, GroundedMotionResult, GroundedStateCommon}; use crate::fighter::state::ground::{self, GroundedMotionResult, GroundedStateCommon};
use crate::fighter::state::{FighterState, dash, jump, wait, walk}; use crate::fighter::state::{FighterState, dash, jump, wait, walk};
use crate::input::FighterCommands;
#[derive(Debug, Clone, Hash)] #[derive(Debug, Clone, Hash)]
pub struct TurnState { pub struct TurnState {
grounded_common: GroundedStateCommon, pub grounded_common: GroundedStateCommon,
} }
impl FighterStateImpl for TurnState { impl FighterStateImpl for TurnState {
const NAME: &'static str = "Turn"; const NAME: &'static str = "Turn";
fn check_interrupt(&self, state_context: &mut FighterStateContext) -> Option<FighterState> { fn check_interrupt(&self, state_context: &mut FighterStateContext) -> Option<FighterState> {
// State chain that results in the turn completing // State chain that results in the turn completing
if state_context.get_current_animation_frame()
<= state_context
.game_settings
.input_common
.turn_into_dashback_window as u32
{
if let Some(state) = dash::check_input(state_context, &self.grounded_common) {
return Some(state);
}
}
if let Some(state) = jump::check_input(state_context, &self.grounded_common) { if let Some(state) = jump::check_input(state_context, &self.grounded_common) {
*state_context.facing_direction = state_context.facing_direction.reverse();
Some(state) Some(state)
} else if state_context.is_current_animation_finished() { } else if state_context.is_current_animation_finished() {
if let Some(state) = dash::check_input(state_context, &self.grounded_common) { if let Some(state) = dash::check_input(state_context, &self.grounded_common) {
@@ -78,13 +90,17 @@ pub fn check_input(
grounded_common: &GroundedStateCommon, grounded_common: &GroundedStateCommon,
) -> Option<FighterState> { ) -> Option<FighterState> {
let input_frame = state_context.input.get_last_frame(); let input_frame = state_context.input.get_last_frame();
let smash_input_frame_threshold = state_context
.game_settings let has_smash_input = state_context
.input_common .input
.smash_input_frame_threshold; .has_command(FighterCommands::SmashMoveLeft)
|| state_context
.input
.has_command(FighterCommands::SmashMoveRight);
if !input_frame.movement.x.is_zero() if !input_frame.movement.x.is_zero()
&& input_frame.movement.x.signum() != state_context.facing_direction.to_sign() && input_frame.movement.x.signum() != state_context.facing_direction.to_sign()
&& state_context.input.get_frames_in_smash_move_deadzone() > smash_input_frame_threshold && !has_smash_input
{ {
return Some(FighterState::Turn(TurnState { return Some(FighterState::Turn(TurnState {
grounded_common: grounded_common.clone(), grounded_common: grounded_common.clone(),
+1 -4
View File
@@ -3,7 +3,6 @@ use crate::fighter::animation::AnimKind;
use crate::fighter::state::FighterState; use crate::fighter::state::FighterState;
use crate::fighter::state::fall::FallState; use crate::fighter::state::fall::FallState;
use crate::fighter::state::ground::{GroundedMotionResult, GroundedStateCommon}; use crate::fighter::state::ground::{GroundedMotionResult, GroundedStateCommon};
use crate::fighter::state::turn;
#[derive(Debug, Clone, Hash)] #[derive(Debug, Clone, Hash)]
pub struct WalkState { pub struct WalkState {
@@ -13,9 +12,7 @@ pub struct WalkState {
impl FighterStateImpl for WalkState { impl FighterStateImpl for WalkState {
const NAME: &'static str = "Walk"; const NAME: &'static str = "Walk";
fn check_interrupt(&self, state_context: &mut FighterStateContext) -> Option<FighterState> { fn check_interrupt(&self, state_context: &mut FighterStateContext) -> Option<FighterState> {
if let Some(state) = turn::check_input(state_context, &self.grounded_common) { if let Some(state) =
return Some(state);
} else if let Some(state) =
ground::grounded_movement_common_interrupts(state_context, &self.grounded_common) ground::grounded_movement_common_interrupts(state_context, &self.grounded_common)
{ {
return Some(state); return Some(state);
+7 -1
View File
@@ -1,5 +1,6 @@
use bevy::prelude::*; use bevy::prelude::*;
use bevy_asset_loader::asset_collection::AssetCollection; use bevy_asset_loader::asset_collection::AssetCollection;
use ron_asset_manager::prelude::RonAsset;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{math::int::FGi32, menus::style::FGUiStyle}; use crate::{math::int::FGi32, menus::style::FGUiStyle};
@@ -10,6 +11,10 @@ pub struct FighterSettingsCommon {
pub walk_speed_ease: FGi32, pub walk_speed_ease: FGi32,
pub ground_max_horizontal_velocity: FGi32, pub ground_max_horizontal_velocity: FGi32,
pub ground_friction_over_walk_speed_multiplier: FGi32, pub ground_friction_over_walk_speed_multiplier: FGi32,
pub knockback_stacking_window: u32,
pub knockback_decay_per_frame: FGi32,
pub knockback_launch_velocity_multiplier: FGi32,
pub hitstun_frames_per_unit_knockback: FGi32,
} }
#[derive(Reflect, Serialize, Deserialize, Clone)] #[derive(Reflect, Serialize, Deserialize, Clone)]
#[reflect(opaque)] #[reflect(opaque)]
@@ -21,9 +26,10 @@ pub struct InputSettingsCommon {
pub run_stick_threshold: FGi32, pub run_stick_threshold: FGi32,
pub smash_input_frame_threshold: u8, pub smash_input_frame_threshold: u8,
pub input_buffer_size: u8, pub input_buffer_size: u8,
pub turn_into_dashback_window: u8,
} }
#[derive(Reflect, Serialize, Deserialize, Resource, Asset, Clone)] #[derive(Reflect, Serialize, Deserialize, Resource, Asset, Clone, RonAsset)]
pub struct GameSettings { pub struct GameSettings {
pub fighter_common: FighterSettingsCommon, pub fighter_common: FighterSettingsCommon,
pub input_common: InputSettingsCommon, pub input_common: InputSettingsCommon,
+12 -20
View File
@@ -12,7 +12,6 @@ use strum_macros::EnumIter;
use crate::fighter::attack::AttackKind; use crate::fighter::attack::AttackKind;
use crate::game_settings::GameSettings; use crate::game_settings::GameSettings;
use crate::input::FighterInputFrame; use crate::input::FighterInputFrame;
use crate::math::int::FGi32;
use crate::netcode::GGRSCfg; use crate::netcode::GGRSCfg;
use crate::player::Player; use crate::player::Player;
@@ -177,7 +176,8 @@ pub fn postprocess_input(
{ {
input.frames_in_x_flick_deadzone = 1; input.frames_in_x_flick_deadzone = 1;
} else { } else {
input.frames_in_x_flick_deadzone = input.frames_in_x_flick_deadzone.saturating_add(1); input.frames_in_x_flick_deadzone =
input.frames_in_x_flick_deadzone.saturating_add(1);
} }
} }
@@ -190,7 +190,8 @@ pub fn postprocess_input(
{ {
input.frames_in_y_flick_deadzone = 1; input.frames_in_y_flick_deadzone = 1;
} else { } else {
input.frames_in_y_flick_deadzone = input.frames_in_y_flick_deadzone.saturating_add(1); input.frames_in_y_flick_deadzone =
input.frames_in_y_flick_deadzone.saturating_add(1);
} }
} }
@@ -215,21 +216,10 @@ pub fn postprocess_input(
); );
} }
if x_abs >= axis_threshold && input.frames_in_x_flick_deadzone <= frame_threshold { let mut y_flick_detected =
input.clear_command(FighterCommands::SmashMoveLeft); y_abs >= axis_threshold && input.frames_in_y_flick_deadzone <= frame_threshold;
input.clear_command(FighterCommands::SmashMoveRight); let mut x_flick_detected =
x_abs >= axis_threshold && input.frames_in_x_flick_deadzone <= frame_threshold;
let command_to_set = if input.current_frame.movement.x > 0.0 {
FighterCommands::SmashMoveRight
} else {
FighterCommands::SmashMoveLeft
};
input.set_lifetime(command_to_set, game_settings.input_common.input_buffer_size);
}
let mut y_flick_detected = y_abs >= axis_threshold && input.frames_in_y_flick_deadzone <= frame_threshold;
let mut x_flick_detected = x_abs >= axis_threshold && input.frames_in_x_flick_deadzone <= frame_threshold;
// if both flicks are detected, only one wins // if both flicks are detected, only one wins
@@ -270,11 +260,13 @@ pub fn postprocess_input(
FighterAttackCommandType::Neutral FighterAttackCommandType::Neutral
}; };
input.set_lifetime(FighterCommands::Attack, game_settings.input_common.input_buffer_size); input.set_lifetime(
FighterCommands::Attack,
game_settings.input_common.input_buffer_size,
);
input.set_attack_command_type(attack_type); input.set_attack_command_type(attack_type);
} }
if x_flick_detected { if x_flick_detected {
input.clear_command(FighterCommands::SmashMoveLeft); input.clear_command(FighterCommands::SmashMoveLeft);
input.clear_command(FighterCommands::SmashMoveRight); input.clear_command(FighterCommands::SmashMoveRight);
+14 -14
View File
@@ -149,19 +149,19 @@ pub fn gc_event_system(
send_axis!(GamepadAxis::LeftStickY, now.left_stick.1); send_axis!(GamepadAxis::LeftStickY, now.left_stick.1);
} }
if prev.right_stick != now.right_stick { if prev.right_stick != now.right_stick {
send_axis!( send_axis!(GamepadAxis::RightStickX, now.right_stick.0);
GamepadAxis::RightStickX, send_axis!(GamepadAxis::RightStickY, now.right_stick.1);
now.right_stick.0
);
send_axis!(
GamepadAxis::RightStickY,
now.right_stick.1
);
} }
if prev.triggers != now.triggers { if prev.triggers != now.triggers {
// The analog triggers are represented as button-axis values, as we have no GamepadAxis to use. // The analog triggers are represented as button-axis values, as we have no GamepadAxis to use.
send_button!(GamepadButton::LeftTrigger2, unsigned_axis_float(now.triggers.0)); send_button!(
send_button!(GamepadButton::RightTrigger2, unsigned_axis_float(now.triggers.1)); GamepadButton::LeftTrigger2,
unsigned_axis_float(now.triggers.0)
);
send_button!(
GamepadButton::RightTrigger2,
unsigned_axis_float(now.triggers.1)
);
} }
macro_rules! digital { macro_rules! digital {
@@ -171,10 +171,10 @@ pub fn gc_event_system(
} }
}; };
} }
digital!(a, GamepadButton::South); digital!(a, GamepadButton::East);
digital!(b, GamepadButton::West); digital!(b, GamepadButton::South);
digital!(x, GamepadButton::East); digital!(x, GamepadButton::North);
digital!(y, GamepadButton::North); digital!(y, GamepadButton::West);
digital!(z, GamepadButton::Z); digital!(z, GamepadButton::Z);
digital!(start, GamepadButton::Start); digital!(start, GamepadButton::Start);
digital!(dpad_up, GamepadButton::DPadUp); digital!(dpad_up, GamepadButton::DPadUp);
+2 -2
View File
@@ -1,11 +1,11 @@
pub mod bridge; pub mod bridge;
pub mod poll; pub mod poll;
pub use bridge::{GcPort, GcPorts, GC_PORT_COUNT}; pub use bridge::{GC_PORT_COUNT, GcPort, GcPorts};
pub use poll::{GcAdapterSnapshot, GcPortState}; pub use poll::{GcAdapterSnapshot, GcPortState};
use bevy::input::gamepad::{gamepad_connection_system, gamepad_event_processing_system};
use bevy::input::InputSystems; use bevy::input::InputSystems;
use bevy::input::gamepad::{gamepad_connection_system, gamepad_event_processing_system};
use bevy::prelude::*; use bevy::prelude::*;
#[derive(Default)] #[derive(Default)]
+5 -8
View File
@@ -98,12 +98,9 @@ pub fn spawn_poll_thread() -> Result<GcAdapterSnapshot, gc_adapter_neo::UsbError
.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
if let Err(payload) = if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(|| adapter.refresh_inputs()))
panic::catch_unwind(AssertUnwindSafe(|| adapter.refresh_inputs()))
{ {
error!( error!("GameCube Controller Adapter USB refresh panicked on startup: {payload:?}");
"GameCube Controller Adapter USB refresh panicked on startup: {payload:?}"
);
} }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
@@ -112,8 +109,7 @@ pub fn spawn_poll_thread() -> Result<GcAdapterSnapshot, gc_adapter_neo::UsbError
let mut rate_window_count: u32 = 0; let mut rate_window_count: u32 = 0;
while !thread_shutdown.load(Ordering::Relaxed) { while !thread_shutdown.load(Ordering::Relaxed) {
let result = let result = panic::catch_unwind(AssertUnwindSafe(|| adapter.read_controllers()));
panic::catch_unwind(AssertUnwindSafe(|| adapter.read_controllers()));
let controllers = match result { let controllers = match result {
Ok(Ok(controllers)) => controllers, Ok(Ok(controllers)) => controllers,
@@ -142,7 +138,8 @@ pub fn spawn_poll_thread() -> Result<GcAdapterSnapshot, gc_adapter_neo::UsbError
let mut states = [GcPortState::default(); 4]; let mut states = [GcPortState::default(); 4];
for i in 0..4 { for i in 0..4 {
states[i] = GcPortState::make_port_state(&controllers[i], adapter.calibration(i)); states[i] =
GcPortState::make_port_state(&controllers[i], adapter.calibration(i));
} }
*thread_ports.lock().unwrap_or_else(|e| e.into_inner()) = states; *thread_ports.lock().unwrap_or_else(|e| e.into_inner()) = states;
+11 -3
View File
@@ -21,8 +21,16 @@ pub fn sample_gamepad(pad: &Gamepad, input_map: &BaseInputMap) -> FighterInputFr
// Digital buttons driving movement isn't used by the // Digital buttons driving movement isn't used by the
// default bindings (the stick covers that), but stay // default bindings (the stick covers that), but stay
// consistent with the keyboard backend if one is added. // consistent with the keyboard backend if one is added.
InputMapAction::MovementXDir(sign) => if pressed { movement.x += sign as f32 }, InputMapAction::MovementXDir(sign) => {
InputMapAction::MovementYDir(sign) => if pressed { movement.y += sign as f32 }, if pressed {
movement.x += sign as f32
}
}
InputMapAction::MovementYDir(sign) => {
if pressed {
movement.y += sign as f32
}
}
} }
} }
// gamepad does not have a separate axis for left and right, so sign here should be 1 // gamepad does not have a separate axis for left and right, so sign here should be 1
@@ -32,7 +40,7 @@ pub fn sample_gamepad(pad: &Gamepad, input_map: &BaseInputMap) -> FighterInputFr
InputMapAction::MovementXDir(_) => movement.x += value, InputMapAction::MovementXDir(_) => movement.x += value,
InputMapAction::MovementYDir(_) => movement.y += value, InputMapAction::MovementYDir(_) => movement.y += value,
_ => {} _ => {}
} }
} }
} }
} }
-1
View File
@@ -33,7 +33,6 @@ pub fn sample_keyboard(key: &ButtonInput<KeyCode>, input_map: &BaseInputMap) ->
InputMapAction::Jump => input_frame.jump = action_strength != FGi32::ZERO, InputMapAction::Jump => input_frame.jump = action_strength != FGi32::ZERO,
InputMapAction::Shield => input_frame.shield = action_strength != FGi32::ZERO, InputMapAction::Shield => input_frame.shield = action_strength != FGi32::ZERO,
InputMapAction::Attack => input_frame.attack = action_strength != FGi32::ZERO, InputMapAction::Attack => input_frame.attack = action_strength != FGi32::ZERO,
} }
} }
+99 -30
View File
@@ -41,6 +41,13 @@ impl LocalInputAssignments {
} }
None None
} }
pub fn get_from_slot(&self, slot: usize) -> Option<&LocalInputSource> {
self.0
.iter()
.find(|(c_slot, _)| slot == *c_slot)
.map(|(_, source)| source)
}
} }
use crate::game_settings::GameSettings; use crate::game_settings::GameSettings;
@@ -92,8 +99,6 @@ impl Plugin for FighterInputPlugin {
key: KeyCode::KeyJ, key: KeyCode::KeyJ,
action: InputMapAction::Attack, action: InputMapAction::Attack,
}, },
// Menu // Menu
], ],
gamepad: vec![ gamepad: vec![
@@ -125,33 +130,92 @@ impl Plugin for FighterInputPlugin {
binding: GamepadBinding::Button(GamepadButton::East), binding: GamepadBinding::Button(GamepadButton::East),
action: InputMapAction::Attack, action: InputMapAction::Attack,
}, },
], ],
}) })
.insert_resource(MenuInputMap { .insert_resource(MenuInputMap {
keyboard: vec![ keyboard: vec![
MenuKeyboardInputMapElement { key: KeyCode::ArrowUp, action: MenuInputMapAction::MovementYDir(1) }, MenuKeyboardInputMapElement {
MenuKeyboardInputMapElement { key: KeyCode::ArrowDown, action: MenuInputMapAction::MovementYDir(-1) }, key: KeyCode::ArrowUp,
MenuKeyboardInputMapElement { key: KeyCode::ArrowLeft, action: MenuInputMapAction::MovementXDir(-1) }, action: MenuInputMapAction::MovementYDir(1),
MenuKeyboardInputMapElement { key: KeyCode::ArrowRight, action: MenuInputMapAction::MovementXDir(1) }, },
MenuKeyboardInputMapElement { key: KeyCode::Enter, action: MenuInputMapAction::Accept }, MenuKeyboardInputMapElement {
MenuKeyboardInputMapElement { key: KeyCode::Escape, action: MenuInputMapAction::Back }, key: KeyCode::ArrowDown,
MenuKeyboardInputMapElement { key: KeyCode::Space, action: MenuInputMapAction::Start }, action: MenuInputMapAction::MovementYDir(-1),
MenuKeyboardInputMapElement { key: KeyCode::KeyW, action: MenuInputMapAction::MovementYDir(1) }, },
MenuKeyboardInputMapElement { key: KeyCode::KeyS, action: MenuInputMapAction::MovementYDir(-1) }, MenuKeyboardInputMapElement {
MenuKeyboardInputMapElement { key: KeyCode::KeyA, action: MenuInputMapAction::MovementXDir(-1) }, key: KeyCode::ArrowLeft,
MenuKeyboardInputMapElement { key: KeyCode::KeyD, action: MenuInputMapAction::MovementXDir(1) }, action: MenuInputMapAction::MovementXDir(-1),
},
MenuKeyboardInputMapElement {
key: KeyCode::ArrowRight,
action: MenuInputMapAction::MovementXDir(1),
},
MenuKeyboardInputMapElement {
key: KeyCode::Enter,
action: MenuInputMapAction::Accept,
},
MenuKeyboardInputMapElement {
key: KeyCode::Escape,
action: MenuInputMapAction::Back,
},
MenuKeyboardInputMapElement {
key: KeyCode::Space,
action: MenuInputMapAction::Start,
},
MenuKeyboardInputMapElement {
key: KeyCode::KeyW,
action: MenuInputMapAction::MovementYDir(1),
},
MenuKeyboardInputMapElement {
key: KeyCode::KeyS,
action: MenuInputMapAction::MovementYDir(-1),
},
MenuKeyboardInputMapElement {
key: KeyCode::KeyA,
action: MenuInputMapAction::MovementXDir(-1),
},
MenuKeyboardInputMapElement {
key: KeyCode::KeyD,
action: MenuInputMapAction::MovementXDir(1),
},
], ],
gamepad: vec![ gamepad: vec![
MenuGamepadInputMapElement { binding: GamepadBinding::Button(GamepadButton::DPadUp), action: MenuInputMapAction::MovementYDir(1) }, MenuGamepadInputMapElement {
MenuGamepadInputMapElement { binding: GamepadBinding::Button(GamepadButton::DPadDown), action: MenuInputMapAction::MovementYDir(-1) }, binding: GamepadBinding::Button(GamepadButton::DPadUp),
MenuGamepadInputMapElement { binding: GamepadBinding::Button(GamepadButton::DPadLeft), action: MenuInputMapAction::MovementXDir(-1) }, action: MenuInputMapAction::MovementYDir(1),
MenuGamepadInputMapElement { binding: GamepadBinding::Button(GamepadButton::DPadRight), action: MenuInputMapAction::MovementXDir(1) }, },
MenuGamepadInputMapElement { binding: GamepadBinding::Axis(GamepadAxis::LeftStickX, 1), action: MenuInputMapAction::MovementXDir(1) }, MenuGamepadInputMapElement {
MenuGamepadInputMapElement { binding: GamepadBinding::Axis(GamepadAxis::LeftStickY, 1), action: MenuInputMapAction::MovementYDir(1) }, binding: GamepadBinding::Button(GamepadButton::DPadDown),
MenuGamepadInputMapElement { binding: GamepadBinding::Button(GamepadButton::South), action: MenuInputMapAction::Accept }, action: MenuInputMapAction::MovementYDir(-1),
MenuGamepadInputMapElement { binding: GamepadBinding::Button(GamepadButton::West), action: MenuInputMapAction::Back }, },
MenuGamepadInputMapElement { binding: GamepadBinding::Button(GamepadButton::Start), action: MenuInputMapAction::Start }, MenuGamepadInputMapElement {
binding: GamepadBinding::Button(GamepadButton::DPadLeft),
action: MenuInputMapAction::MovementXDir(-1),
},
MenuGamepadInputMapElement {
binding: GamepadBinding::Button(GamepadButton::DPadRight),
action: MenuInputMapAction::MovementXDir(1),
},
MenuGamepadInputMapElement {
binding: GamepadBinding::Axis(GamepadAxis::LeftStickX, 1),
action: MenuInputMapAction::MovementXDir(1),
},
MenuGamepadInputMapElement {
binding: GamepadBinding::Axis(GamepadAxis::LeftStickY, 1),
action: MenuInputMapAction::MovementYDir(1),
},
MenuGamepadInputMapElement {
binding: GamepadBinding::Button(GamepadButton::South),
action: MenuInputMapAction::Accept,
},
MenuGamepadInputMapElement {
binding: GamepadBinding::Button(GamepadButton::West),
action: MenuInputMapAction::Back,
},
MenuGamepadInputMapElement {
binding: GamepadBinding::Button(GamepadButton::Start),
action: MenuInputMapAction::Start,
},
], ],
}) })
.init_resource::<LocalInputAssignments>() .init_resource::<LocalInputAssignments>()
@@ -183,16 +247,24 @@ fn read_local_inputs(
gamepads: Query<&Gamepad>, gamepads: Query<&Gamepad>,
assignments: Res<LocalInputAssignments>, assignments: Res<LocalInputAssignments>,
local_players: Res<LocalPlayers>, local_players: Res<LocalPlayers>,
game_settings: Res<GameSettings> game_settings: Res<GameSettings>,
) { ) {
let mut local_inputs = HashMap::new(); let mut local_inputs = HashMap::new();
for handle in &local_players.0 { for handle in &local_players.0 {
let assigned = assignments.0.iter().find(|(player_handle, _)| player_handle == handle); let assigned = assignments
.0
.iter()
.find(|(player_handle, _)| player_handle == handle);
let gamepad = match assigned { let gamepad = match assigned {
Some((_, LocalInputSource::Gamepad(entity))) => gamepads.get(*entity).ok(), Some((_, LocalInputSource::Gamepad(entity))) => gamepads.get(*entity).ok(),
Some((_, LocalInputSource::Keyboard)) => None, Some((_, LocalInputSource::Keyboard)) => None,
None => gc_ports.entities.get(*handle).copied().flatten().and_then(|entity| gamepads.get(entity).ok()), None => gc_ports
.entities
.get(*handle)
.copied()
.flatten()
.and_then(|entity| gamepads.get(entity).ok()),
}; };
let mut input_frame = match assigned { let mut input_frame = match assigned {
@@ -200,10 +272,7 @@ fn read_local_inputs(
Some((_, LocalInputSource::Gamepad(_))) => gamepad Some((_, LocalInputSource::Gamepad(_))) => gamepad
.map(|pad| gamepad::sample_gamepad(pad, &input_map)) .map(|pad| gamepad::sample_gamepad(pad, &input_map))
.unwrap_or_default(), .unwrap_or_default(),
None => match gamepad { None => FighterInputFrame::default(),
Some(pad) => gamepad::sample_gamepad(pad, &input_map),
None => keyboard::sample_keyboard(&key, &input_map),
},
}; };
// preprocess frame // preprocess frame
+8 -4
View File
@@ -22,12 +22,15 @@
//! appears in `Add Component`. No registration code is needed. //! appears in `Add Component`. No registration code is needed.
use bevy::{ use bevy::{
asset::processor::{AssetProcessor, ProcessorState}, prelude::*, settings::SettingsPlugin, tasks::block_on, asset::processor::{AssetProcessor, ProcessorState},
prelude::*,
settings::SettingsPlugin,
tasks::block_on,
}; };
use bevy_asset_loader::prelude::*; use bevy_asset_loader::prelude::*;
use ron_asset_manager::RonAssetPlugin;
use bevy_wind_waker_shader::prelude::*; use bevy_wind_waker_shader::prelude::*;
use clap::Parser; use clap::Parser;
use ron_asset_manager::RonAssetPlugin;
use crate::{ use crate::{
camera::MatchCameraPlugin, fighter::manifest::FighterManifest, game_settings::GameSettings, camera::MatchCameraPlugin, fighter::manifest::FighterManifest, game_settings::GameSettings,
@@ -42,13 +45,13 @@ pub mod game_settings;
pub mod input; pub mod input;
pub mod match_loading; pub mod match_loading;
mod math; mod math;
pub mod menus;
pub mod netcode; pub mod netcode;
pub mod player; pub mod player;
pub mod replay; pub mod replay;
pub mod schedule; pub mod schedule;
pub mod scripting; pub mod scripting;
pub mod stage; pub mod stage;
pub mod menus;
pub mod texture_reference; pub mod texture_reference;
#[derive(States, Debug, Clone, Copy, Eq, PartialEq, Hash, Default)] #[derive(States, Debug, Clone, Copy, Eq, PartialEq, Hash, Default)]
@@ -61,6 +64,7 @@ pub enum AppState {
LoadStageManifests, LoadStageManifests,
PrepareStageManifests, PrepareStageManifests,
CommonAssetLoadFailed, CommonAssetLoadFailed,
PreMainMenu,
MainMenu, MainMenu,
CharacterSelect, CharacterSelect,
StageSelect, StageSelect,
@@ -139,7 +143,7 @@ impl Plugin for GamePlugin {
stage::manifest::prepare_stage_manifests, stage::manifest::prepare_stage_manifests,
) )
.add_systems( .add_systems(
OnEnter(AppState::MainMenu), OnEnter(AppState::PreMainMenu),
match_loading::initiate_default_match, match_loading::initiate_default_match,
) )
.add_systems( .add_systems(
+1 -5
View File
@@ -1,7 +1,3 @@
//! Standalone binary for game-test: `cargo run` plays the game
//! without the editor. The editor's Play button runs the same
//! [`game_test::GamePlugin`] through its own game runner instead.
use bevy::asset::AssetMode::Processed; use bevy::asset::AssetMode::Processed;
use bevy::camera_controller::free_camera::FreeCameraPlugin; use bevy::camera_controller::free_camera::FreeCameraPlugin;
use bevy::image::{ImageAddressMode, ImagePlugin, ImageSamplerDescriptor}; use bevy::image::{ImageAddressMode, ImagePlugin, ImageSamplerDescriptor};
@@ -30,7 +26,7 @@ fn main() -> AppExit {
App::new() App::new()
.add_plugins(default_plugins) .add_plugins(default_plugins)
.add_plugins(avian3d::prelude::PhysicsPlugins::default()) .add_plugins(avian3d::prelude::PhysicsPlugins::default())
.add_plugins(game_test::GamePlugin) .add_plugins(shinespark::GamePlugin)
.add_plugins(FreeCameraPlugin) .add_plugins(FreeCameraPlugin)
.add_plugins(EguiPlugin::default()) .add_plugins(EguiPlugin::default())
.add_plugins(WorldInspectorPlugin::default()) // adds default options and `InspectorEguiImpl`s .add_plugins(WorldInspectorPlugin::default()) // adds default options and `InspectorEguiImpl`s
+113 -9
View File
@@ -11,14 +11,15 @@ use crate::{
AppState, AppState,
args::Args, args::Args,
fighter::{ fighter::{
FighterId, FighterId, FighterRoster,
animation::AnimKind, animation::AnimKind,
attack::{AttackKind, FighterAttackScriptAssets}, attack::{AttackKind, FighterAttackScriptAssets},
baked_animation::BakedFighterAnimations, baked_animation::{BAKED_ANIMATION_FPS, BakedFighterAnimations},
manifest::{FighterManifest, FighterManifestRegistry}, manifest::{FighterManifest, FighterManifestRegistry},
spawn_fighter, spawn_fighter,
visual::FighterAnimations, visual::FighterAnimations,
}, },
input::{LocalInputAssignments, LocalInputSource},
math::{int::FGi32, vec::FGVec2}, math::{int::FGi32, vec::FGVec2},
netcode::{GGRSCfg, session::create_session}, netcode::{GGRSCfg, session::create_session},
scripting::FighterAttackScript, scripting::FighterAttackScript,
@@ -146,9 +147,15 @@ pub fn initiate_match(
pub fn initiate_default_match( pub fn initiate_default_match(
mut commands: Commands, mut commands: Commands,
args: Res<Args>, args: Res<Args>,
gamepads: Query<Entity, With<Gamepad>>,
mut assigments: ResMut<LocalInputAssignments>,
mut next_state: ResMut<NextState<AppState>>, mut next_state: ResMut<NextState<AppState>>,
completed: Option<Res<crate::replay::ReplayComplete>>, completed: Option<Res<crate::replay::ReplayComplete>>,
) { ) {
if !args.debug_match {
next_state.set(AppState::MainMenu);
return;
}
if completed.is_some() { if completed.is_some() {
return; return;
} }
@@ -169,9 +176,6 @@ pub fn initiate_default_match(
} }
return; return;
} }
if !args.synctest {
return;
}
let players = (0..args.players) let players = (0..args.players)
.map(|handle| MatchPlayer { .map(|handle| MatchPlayer {
handle, handle,
@@ -179,6 +183,12 @@ pub fn initiate_default_match(
}) })
.collect(); .collect();
assigments.push((0, LocalInputSource::Keyboard));
for (idx, entity) in gamepads.iter().take(args.players - 1).enumerate() {
assigments.push((idx + 1, LocalInputSource::Gamepad(entity)));
}
initiate_match( initiate_match(
&mut commands, &mut commands,
&mut next_state, &mut next_state,
@@ -195,6 +205,7 @@ pub fn prepare_match(
assets: Res<MatchAssets>, assets: Res<MatchAssets>,
gltfs: Res<Assets<Gltf>>, gltfs: Res<Assets<Gltf>>,
baked_animations: Res<Assets<BakedFighterAnimations>>, baked_animations: Res<Assets<BakedFighterAnimations>>,
attack_scripts: Res<Assets<FighterAttackScript>>,
registry: Res<FighterManifestRegistry>, registry: Res<FighterManifestRegistry>,
stage_registry: Res<StageManifestRegistry>, stage_registry: Res<StageManifestRegistry>,
manifests: Res<Assets<FighterManifest>>, manifests: Res<Assets<FighterManifest>>,
@@ -239,6 +250,89 @@ pub fn prepare_match(
); );
return; return;
}; };
if baked.frame_rate != BAKED_ANIMATION_FPS {
fail_match(
&mut next_state,
&format!(
"{:?} baked animation rate is {}, expected {}",
character.fighter, baked.frame_rate, BAKED_ANIMATION_FPS
),
);
return;
}
if !baked.has_unique_bone_names() {
fail_match(
&mut next_state,
&format!(
"{:?} baked animation contains duplicate bone names",
character.fighter
),
);
return;
}
if let Err(error) = manifest.attributes.validate() {
fail_match(
&mut next_state,
&format!("{:?} has invalid attributes: {error}", character.fighter),
);
return;
}
for (index, hurtbox) in manifest.hurtboxes.iter().enumerate() {
if let Err(error) = hurtbox.validate() {
fail_match(
&mut next_state,
&format!(
"{:?} hurtbox {index} is invalid: {error}",
character.fighter
),
);
return;
}
if !baked.contains_bone(&hurtbox.bone) {
fail_match(
&mut next_state,
&format!(
"{:?} hurtbox {index} references missing bone {:?}",
character.fighter, hurtbox.bone
),
);
return;
}
}
for (kind, handle) in &character.attack_scripts {
let Some(script) = attack_scripts.get(handle) else {
fail_match(
&mut next_state,
&format!(
"{:?} {kind:?} attack script is unavailable",
character.fighter
),
);
return;
};
if let Err(error) = script.validate() {
fail_match(
&mut next_state,
&format!(
"{:?} {kind:?} attack script is invalid: {error}",
character.fighter
),
);
return;
}
for hitbox in &script.hitboxes {
if !baked.contains_bone(&hitbox.bone) {
fail_match(
&mut next_state,
&format!(
"{:?} {kind:?} hitbox {} references missing bone {:?}",
character.fighter, hitbox.id, hitbox.bone
),
);
return;
}
}
}
let Some(scene) = gltf.scenes.first().cloned() else { let Some(scene) = gltf.scenes.first().cloned() else {
fail_match(&mut next_state, "a character GLTF contains no scene"); fail_match(&mut next_state, "a character GLTF contains no scene");
return; return;
@@ -270,7 +364,13 @@ pub fn prepare_match(
scripts: character.attack_scripts.clone(), scripts: character.attack_scripts.clone(),
}; };
prepared.push((scene, animations, attack_scripts, manifest_handle)); prepared.push((
scene,
animations,
attack_scripts,
manifest_handle,
manifest.model_scale,
));
} }
let session = match create_session(&args, request.players.len()) { let session = match create_session(&args, request.players.len()) {
@@ -300,21 +400,24 @@ pub fn prepare_match(
stage_manifest.camera.clone(), stage_manifest.camera.clone(),
); );
for (index, (player, (scene, animations, attack_scripts, manifest_handle))) in let mut fighter_roster = Vec::with_capacity(request.players.len());
for (index, (player, (scene, animations, attack_scripts, manifest_handle, model_scale))) in
request.players.iter().zip(prepared).enumerate() request.players.iter().zip(prepared).enumerate()
{ {
let spawn_x = (index as i32 * 2 + 1 - request.players.len() as i32) * 5; let spawn_x = (index as i32 * 2 + 1 - request.players.len() as i32) * 5;
spawn_fighter( fighter_roster.push(spawn_fighter(
&mut commands, &mut commands,
player.handle, player.handle,
FGVec2::new(FGi32::from_num(spawn_x), FGi32::lit("12.5")), FGVec2::new(FGi32::from_num(spawn_x), FGi32::lit("12.5")),
manifest_handle.clone(), manifest_handle.clone(),
model_scale,
animations, animations,
attack_scripts, attack_scripts,
WorldAssetRoot(scene), WorldAssetRoot(scene),
); ));
} }
commands.insert_resource(FighterRoster(fighter_roster));
commands.insert_resource::<Session<GGRSCfg>>(session); commands.insert_resource::<Session<GGRSCfg>>(session);
next_state.set(AppState::InMatch); next_state.set(AppState::InMatch);
} }
@@ -348,6 +451,7 @@ pub fn cleanup_match(
commands.remove_resource::<stage::line::StageCollision>(); commands.remove_resource::<stage::line::StageCollision>();
commands.remove_resource::<MatchAssets>(); commands.remove_resource::<MatchAssets>();
commands.remove_resource::<PendingMatch>(); commands.remove_resource::<PendingMatch>();
commands.remove_resource::<FighterRoster>();
} }
#[cfg(test)] #[cfg(test)]
+2 -2
View File
@@ -4,7 +4,7 @@ pub type FGWide = fixed::FixedI128<fixed::types::extra::U32>;
/// Angle conversions for the game's Q16.16 fixed-point values. /// Angle conversions for the game's Q16.16 fixed-point values.
pub trait FGi32Ext { pub trait FGi32Ext {
fn to_radians(self) -> FGi32; fn to_radians(self) -> FGi32;
fn sin_cos(self) -> (FGi32, FGi32); fn sin_cos_rads(self) -> (FGi32, FGi32);
} }
impl FGi32Ext for FGi32 { impl FGi32Ext for FGi32 {
@@ -12,7 +12,7 @@ impl FGi32Ext for FGi32 {
FGi32::from_num(FGWide::from_num(self) * FGWide::lit("0.01745329251994329576923690768489")) FGi32::from_num(FGWide::from_num(self) * FGWide::lit("0.01745329251994329576923690768489"))
} }
fn sin_cos(self) -> (FGi32, FGi32) { fn sin_cos_rads(self) -> (FGi32, FGi32) {
const PI: FGi32 = FGi32::lit("3.14159265358979323846"); const PI: FGi32 = FGi32::lit("3.14159265358979323846");
const HALF_PI: FGi32 = FGi32::lit("1.57079632679489661923"); const HALF_PI: FGi32 = FGi32::lit("1.57079632679489661923");
const TWO_PI: FGi32 = FGi32::lit("6.28318530717958647692"); const TWO_PI: FGi32 = FGi32::lit("6.28318530717958647692");
+9 -4
View File
@@ -1,4 +1,3 @@
use bevy::prelude::*; use bevy::prelude::*;
use crate::math::{ use crate::math::{
@@ -131,9 +130,6 @@ impl FGSegment2d {
let t = (s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / denom; let t = (s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / denom;
if s >= FGWide::ZERO && s <= FGWide::ONE && t >= FGWide::ZERO && t <= FGWide::ONE { if s >= FGWide::ZERO && s <= FGWide::ONE && t >= FGWide::ZERO && t <= FGWide::ONE {
if self.left_normal().dot(rhs.point2() - rhs.point1()) >= FGi32::ZERO {
return None;
}
Some(FGVec2::new( Some(FGVec2::new(
FGi32::from_num(p0_x + t * s1_x), FGi32::from_num(p0_x + t * s1_x),
FGi32::from_num(p0_y + t * s1_y), FGi32::from_num(p0_y + t * s1_y),
@@ -142,6 +138,15 @@ impl FGSegment2d {
None None
} }
} }
/// Returns a value representing the normalized position along the segment.
pub fn project_point_normalized(&self, point: FGVec2) -> FGi32 {
let segment_vector = self.point2 - self.point1;
let offset = point - self.point1;
// The signed projection of `offset` onto `segment_vector`, scaled by the length of the segment.
let projection_scaled = segment_vector.dot(offset);
FGi32::from_num(FGWide::from_num(projection_scaled) / segment_vector.length_squared())
}
} }
#[cfg(test)] #[cfg(test)]
+47 -12
View File
@@ -1,11 +1,20 @@
use bevy::{input_focus::InputFocus, picking::{hover::PickingInteraction, Pickable}, prelude::*, text::FontSourceTemplate, ui::auto_directional_navigation::AutoDirectionalNavigation}; use bevy::{
input_focus::InputFocus,
picking::{Pickable, hover::PickingInteraction},
prelude::*,
text::FontSourceTemplate,
ui::auto_directional_navigation::AutoDirectionalNavigation,
};
use crate::{game_settings::CommonAssets, menus::style::{FGUiButtonType, FGUiStyle}}; use crate::{
game_settings::CommonAssets,
menus::style::{FGUiButtonType, FGUiStyle},
};
#[derive(Component, Default, Clone)] #[derive(Component, Default, Clone)]
#[require(Button)] #[require(Button)]
pub struct FGUiButton { pub struct FGUiButton {
pub button_type: FGUiButtonType pub button_type: FGUiButtonType,
} }
pub fn menu_button(label: &str) -> impl Scene { pub fn menu_button(label: &str) -> impl Scene {
@@ -37,15 +46,34 @@ pub fn menu_button(label: &str) -> impl Scene {
} }
} }
pub fn button_setup(query: Query<(Entity, &FGUiButton, &mut Node), Added<FGUiButton>>, common_assets: Res<CommonAssets>, styles: Res<Assets<FGUiStyle>>, mut commands: Commands) { pub fn button_setup(
let styles = styles.get(&common_assets.ui_style).expect("UI styles should be loaded"); query: Query<(Entity, &FGUiButton, &mut Node), Added<FGUiButton>>,
common_assets: Res<CommonAssets>,
styles: Res<Assets<FGUiStyle>>,
mut commands: Commands,
) {
let styles = styles
.get(&common_assets.ui_style)
.expect("UI styles should be loaded");
for (entity, button, mut node) in query { for (entity, button, mut node) in query {
styles.button_styles[&button.button_type].normal.apply(&mut commands, entity, &mut node); styles.button_styles[&button.button_type]
.normal
.apply(&mut commands, entity, &mut node);
} }
} }
pub fn button_style_system(query: Query<(Entity, &FGUiButton, &PickingInteraction, &mut Node), Changed<PickingInteraction>>, common_assets: Res<CommonAssets>, styles: Res<Assets<FGUiStyle>>, mut commands: Commands) { pub fn button_style_system(
let styles = styles.get(&common_assets.ui_style).expect("UI styles should be loaded"); query: Query<
(Entity, &FGUiButton, &PickingInteraction, &mut Node),
Changed<PickingInteraction>,
>,
common_assets: Res<CommonAssets>,
styles: Res<Assets<FGUiStyle>>,
mut commands: Commands,
) {
let styles = styles
.get(&common_assets.ui_style)
.expect("UI styles should be loaded");
for (entity, button, interaction, mut node) in query { for (entity, button, interaction, mut node) in query {
let button_style_to_use = match interaction { let button_style_to_use = match interaction {
@@ -57,14 +85,21 @@ pub fn button_style_system(query: Query<(Entity, &FGUiButton, &PickingInteractio
} }
} }
pub fn button_focus_style_system(query: Query<(Entity, &FGUiButton)>, focus: Res<InputFocus>, mut commands: Commands, common_assets: Res<CommonAssets>, styles: Res<Assets<FGUiStyle>>) { pub fn button_focus_style_system(
query: Query<(Entity, &FGUiButton)>,
focus: Res<InputFocus>,
mut commands: Commands,
common_assets: Res<CommonAssets>,
styles: Res<Assets<FGUiStyle>>,
) {
if let Some(focused_entity) = focus.get() { if let Some(focused_entity) = focus.get() {
if !query.contains(focused_entity) { if !query.contains(focused_entity) {
return; return;
} }
let styles = styles.get(&common_assets.ui_style).expect("UI styles should be loaded"); let styles = styles
.get(&common_assets.ui_style)
.expect("UI styles should be loaded");
for (entity, button) in query { for (entity, button) in query {
if focused_entity == entity { if focused_entity == entity {
@@ -72,7 +107,7 @@ pub fn button_focus_style_system(query: Query<(Entity, &FGUiButton)>, focus: Res
commands.entity(focused_entity).insert(Outline { commands.entity(focused_entity).insert(Outline {
width: px(style.focus_outline_width_px), width: px(style.focus_outline_width_px),
offset: px(style.focus_outline_offset_px), offset: px(style.focus_outline_offset_px),
color: style.focus_outline_color color: style.focus_outline_color,
}); });
} else { } else {
commands.entity(entity).remove::<Outline>(); commands.entity(entity).remove::<Outline>();
+4 -3
View File
@@ -1,13 +1,14 @@
use bevy::{picking::Pickable, prelude::*, text::FontSourceTemplate, ui::widget::ImageNodeSize}; use bevy::{picking::Pickable, prelude::*, text::FontSourceTemplate};
use crate::{ use crate::{
fighter::{FighterId, manifest::FighterManifest}, menus::{button::FGUiButton, style::FGUiButtonType}, fighter::{FighterId, manifest::FighterManifest},
menus::{button::FGUiButton, style::FGUiButtonType},
}; };
#[derive(Component, Clone, FromTemplate)] #[derive(Component, Clone, FromTemplate)]
pub struct CharacterBox { pub struct CharacterBox {
pub fighter_manifest: Handle<FighterManifest>, pub fighter_manifest: Handle<FighterManifest>,
pub fighter_id: FighterId pub fighter_id: FighterId,
} }
impl CharacterBox { impl CharacterBox {
+1 -3
View File
@@ -1,3 +1 @@
pub enum CharacterSelectErrors { pub enum CharacterSelectErrors {}
}
@@ -4,7 +4,7 @@ pub struct FighterPortrait {
} }
impl FighterPortrait { impl FighterPortrait {
pub fn create(player_slot: usize) -> impl Scene { pub fn create(_player_slot: usize) -> impl Scene {
bsn![ bsn![
Node { Node {
max_width: px(300), max_width: px(300),
+70 -59
View File
@@ -1,20 +1,19 @@
use bevy::{ use bevy::{picking::pointer::PointerId, prelude::*};
picking::pointer::{PointerId, PointerLocation},
prelude::*,
};
use bevy_egui::egui::accesskit::TextAlign;
use crate::{ use crate::{
AppState, fighter::manifest::{FighterManifest, FighterManifestRegistry}, game_settings::CommonAssets, input::{LocalInputAssignments, LocalInputSource}, menus::{ AppState,
MenuMarker, build_menu_with_props, fighter::manifest::{FighterManifest, FighterManifestRegistry},
game_settings::CommonAssets,
input::{LocalInputAssignments, LocalInputSource},
menus::{
MenuMarker,
button::FGUiButton, button::FGUiButton,
character_select::character_box::CharacterBox, character_select::{character_box::CharacterBox, token::CharacterSelectToken},
cursor::{FGMenuCursor, MenuCursorInputSource}, cursor::{FGMenuCursor, MenuCursorInputSource},
errors::MenuErrors::{self, FighterManifestNotFound}, errors::MenuErrors::FighterManifestNotFound,
match_config::{MenuMatchConfig, MenuMatchPlayerSlot}, match_config::{MenuMatchConfig, MenuMatchPlayerSlot},
scaling, spawn_menu, scaling, spawn_menu,
style::{FGUiButtonType, FGUiStyle}, style::{FGUiButtonType, FGUiStyle},
wrap_menu,
}, },
}; };
@@ -38,10 +37,10 @@ pub fn setup_character_select(
existing_menu: Option<Single<Entity, With<MenuMarker>>>, existing_menu: Option<Single<Entity, With<MenuMarker>>>,
mut commands: Commands, mut commands: Commands,
manifest_registry: Res<FighterManifestRegistry>, manifest_registry: Res<FighterManifestRegistry>,
assignments: Res<LocalInputAssignments>, _assignments: Res<LocalInputAssignments>,
manifests: Res<Assets<FighterManifest>>, manifests: Res<Assets<FighterManifest>>,
common_assets: Res<CommonAssets>, _common_assets: Res<CommonAssets>,
styles: Res<Assets<FGUiStyle>>, _styles: Res<Assets<FGUiStyle>>,
) { ) {
let character_boxes = manifest_registry let character_boxes = manifest_registry
.iter() .iter()
@@ -67,31 +66,6 @@ pub fn setup_character_select(
} }
Children [ Children [
{character_boxes}, {character_boxes},
(
// Start banner thingy
StartButtonBanner
Node {
position_type: PositionType::Absolute,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
width: percent(100),
}
FGUiButton {
button_type: FGUiButtonType::CharacterSelectStartBanner
}
Text::new("Peenids")
Visibility::Hidden
TextLayout {
justify: Justify::Center
}
TextFont {
font_size: FontSize::Px(48.0),
}
TextColor(Color::WHITE)
BackgroundColor(Color::BLACK)
GlobalZIndex(500)
on(|_ev: On<Pointer<Press>>, mut next_state: ResMut<NextState<AppState>>| next_state.set(AppState::StageSelect))
)
] ]
), ),
( (
@@ -99,9 +73,34 @@ pub fn setup_character_select(
Node { Node {
flex_direction: FlexDirection::Row, flex_direction: FlexDirection::Row,
width: percent(100), width: percent(100),
height: px(400), min_height: px(400),
justify_content: JustifyContent::Center justify_content: JustifyContent::Center
} }
),
(
// Start banner thingy
StartButtonBanner
Node {
position_type: PositionType::Absolute,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
width: percent(100),
}
FGUiButton {
button_type: FGUiButtonType::CharacterSelectStartBanner
}
Text::new("Start poetry")
Visibility::Hidden
TextLayout {
justify: Justify::Center
}
TextFont {
font_size: FontSize::Px(48.0),
}
TextColor(Color::WHITE)
BackgroundColor(Color::BLACK)
GlobalZIndex(500)
on(|_ev: On<Pointer<Press>>, mut next_state: ResMut<NextState<AppState>>| next_state.set(AppState::StageSelect))
) )
] ]
}; };
@@ -113,7 +112,7 @@ pub fn setup_character_select(
pub fn create_portrait( pub fn create_portrait(
player_slot: usize, player_slot: usize,
container: Entity, container: Entity,
mut commands: Commands, commands: &mut Commands,
style: &FGUiStyle, style: &FGUiStyle,
input_source: &LocalInputSource, input_source: &LocalInputSource,
) { ) {
@@ -123,7 +122,7 @@ pub fn create_portrait(
commands.entity(container).add_child(entity); commands.entity(container).add_child(entity);
let cursor = commands let cursor = commands
.spawn(FGMenuCursor::create_cursor( .spawn(FGMenuCursor::create_player_cursor(
player_slot, player_slot,
style, style,
input_source, input_source,
@@ -137,36 +136,38 @@ pub fn create_portrait(
commands.entity(container).add_child(entity); commands.entity(container).add_child(entity);
} }
#[derive(Event)] #[derive(Message)]
pub struct PlayerSlotAssigned { pub struct PlayerSlotAssigned {
pub slot: usize, pub slot: usize,
pub input_source: LocalInputSource, pub input_source: LocalInputSource,
} }
pub fn handle_fighter_slot_addition( pub fn handle_fighter_slot_addition(
addition: On<PlayerSlotAssigned>, mut addition: MessageReader<PlayerSlotAssigned>,
query: Single<&CharacterSelectScreen>, query: Single<&CharacterSelectScreen>,
commands: Commands, mut commands: Commands,
common_assets: Res<CommonAssets>, common_assets: Res<CommonAssets>,
styles: Res<Assets<FGUiStyle>>, styles: Res<Assets<FGUiStyle>>,
) { ) {
let slot = addition.slot; for addition in addition.read() {
create_portrait( let slot = addition.slot;
slot, create_portrait(
query.fighter_portait_container, slot,
commands, query.fighter_portait_container,
styles &mut commands,
.get(&common_assets.ui_style) styles
.expect("UI Style should be loaded by now"), .get(&common_assets.ui_style)
&addition.input_source, .expect("UI Style should be loaded by now"),
); &addition.input_source,
);
}
} }
pub fn css_auto_assign_slots( pub fn css_auto_assign_slots(
menu_inputs: Res<crate::menus::input::MenuInputState>, menu_inputs: Res<crate::menus::input::MenuInputState>,
mut assignments: ResMut<LocalInputAssignments>, mut assignments: ResMut<LocalInputAssignments>,
mut match_config: ResMut<MenuMatchConfig>, mut match_config: ResMut<MenuMatchConfig>,
mut commands: Commands, mut ev_assigned: MessageWriter<PlayerSlotAssigned>,
) { ) {
for (source, input) in &menu_inputs.inputs { for (source, input) in &menu_inputs.inputs {
if input.movement != Vec2::ZERO { if input.movement != Vec2::ZERO {
@@ -178,7 +179,7 @@ pub fn css_auto_assign_slots(
fighter: None, fighter: None,
}); });
info!("New input assignment"); info!("New input assignment");
commands.trigger(PlayerSlotAssigned { ev_assigned.write(PlayerSlotAssigned {
slot: free_idx, slot: free_idx,
input_source: source.clone(), input_source: source.clone(),
}); });
@@ -189,7 +190,7 @@ pub fn css_auto_assign_slots(
#[derive(Event)] #[derive(Event)]
pub struct FighterSelectedEvent { pub struct FighterSelectedEvent {
slot: usize, _slot: usize,
} }
pub fn select_fighter( pub fn select_fighter(
@@ -209,7 +210,7 @@ pub fn select_fighter(
.get(&character_box.fighter_manifest) .get(&character_box.fighter_manifest)
.ok_or(FighterManifestNotFound)?; .ok_or(FighterManifestNotFound)?;
match_config.set_player_fighter(slot, Some(manifest.id))?; match_config.set_player_fighter(slot, Some(manifest.id))?;
commands.trigger(FighterSelectedEvent { slot }); commands.trigger(FighterSelectedEvent { _slot: slot });
} }
} }
} }
@@ -224,7 +225,11 @@ pub fn update_start_banner_visibility(
config: Res<MenuMatchConfig>, config: Res<MenuMatchConfig>,
) { ) {
let match_ready = config.all_players_ready(); let match_ready = config.all_players_ready();
commands.entity(banner.into_inner()).insert(if match_ready {Visibility::Visible} else {Visibility::Hidden}); commands.entity(banner.into_inner()).insert(if match_ready {
Visibility::Visible
} else {
Visibility::Hidden
});
} }
pub fn copy_cursor_transform_to_token( pub fn copy_cursor_transform_to_token(
@@ -268,3 +273,9 @@ pub fn copy_cursor_transform_to_token(
} }
Ok(()) Ok(())
} }
pub fn despawn_tokens(tokens: Query<Entity, With<CharacterSelectToken>>, mut commands: Commands) {
for token in tokens {
commands.entity(token).despawn();
}
}
+8 -6
View File
@@ -7,16 +7,13 @@ use crate::menus::style::FGUiStyle;
#[derive(Component, Clone)] #[derive(Component, Clone)]
pub struct CharacterSelectToken { pub struct CharacterSelectToken {
pub slot: usize, pub slot: usize,
pub cursor: Entity pub cursor: Entity,
} }
impl CharacterSelectToken { impl CharacterSelectToken {
pub fn create(cursor: Entity, slot: usize, style: &FGUiStyle) -> impl Bundle { pub fn create(cursor: Entity, slot: usize, style: &FGUiStyle) -> impl Bundle {
( (
CharacterSelectToken { CharacterSelectToken { slot, cursor },
slot,
cursor
},
Pickable::IGNORE, Pickable::IGNORE,
Node { Node {
position_type: PositionType::Absolute, position_type: PositionType::Absolute,
@@ -26,8 +23,13 @@ impl CharacterSelectToken {
}, },
ImageNode { ImageNode {
image: style.css_token.handle.handle.clone(), image: style.css_token.handle.handle.clone(),
color: style
.player_colors
.get(slot)
.copied()
.unwrap_or(Color::WHITE),
..default() ..default()
} },
) )
} }
} }
+48 -16
View File
@@ -9,7 +9,12 @@ use bevy::{
}; };
use crate::{ use crate::{
input::{LocalInputAssignments, LocalInputSource}, menus::{input::{MenuInput, MenuInputState}, scaling, style::FGUiStyle}, input::{LocalInputAssignments, LocalInputSource},
menus::{
input::{MenuInput, MenuInputState},
scaling,
style::FGUiStyle,
},
}; };
#[derive(Default)] #[derive(Default)]
@@ -28,20 +33,21 @@ pub struct FGMenuCursor {
impl FGMenuCursor { impl FGMenuCursor {
pub fn create_cursor( pub fn create_cursor(
player_slot: usize, input_source: MenuCursorInputSource,
style: &FGUiStyle, style: &FGUiStyle,
input_source: &LocalInputSource, pointer_id: PointerId,
) -> impl Bundle { ) -> impl Bundle {
let pointer_id = if matches!(input_source, LocalInputSource::Keyboard) {PointerId::Mouse} else {PointerId::Custom(Uuid::new_v4())};
let circle_icon = style.cursor.handle().clone(); let circle_icon = style.cursor.handle().clone();
( (
FGMenuCursor { FGMenuCursor {
input_source: super::cursor::MenuCursorInputSource::Player(player_slot), input_source: input_source,
..default() ..default()
}, },
Node { Node {
width: px(64), width: px(64),
height: px(64), height: px(64),
left: percent(50),
top: percent(50),
position_type: PositionType::Absolute, position_type: PositionType::Absolute,
..default() ..default()
}, },
@@ -55,25 +61,42 @@ impl FGMenuCursor {
Pickable::IGNORE, Pickable::IGNORE,
) )
} }
pub fn create_shared_cursor(style: &FGUiStyle) -> impl Bundle {
Self::create_cursor(MenuCursorInputSource::Any, style, PointerId::Mouse)
}
pub fn create_player_cursor(
player_slot: usize,
style: &FGUiStyle,
input_source: &LocalInputSource,
) -> impl Bundle {
let pointer_id = if matches!(input_source, LocalInputSource::Keyboard) {
PointerId::Mouse
} else {
PointerId::Custom(Uuid::new_v4())
};
Self::create_cursor(
MenuCursorInputSource::Player(player_slot),
style,
pointer_id,
)
}
} }
/// The player using the keyboard can input things with the mouse, so we should copy their movement input /// The player using the keyboard can input things with the mouse, so we should copy their movement input
pub fn copy_mouse_input( pub fn copy_mouse_input(
mut query: Query<(&FGMenuCursor, &mut PointerLocation, &PointerId)>, mut query: Query<(&FGMenuCursor, &mut PointerLocation, &PointerId)>,
assignments: Res<LocalInputAssignments>, assignments: Res<LocalInputAssignments>,
mut input_events: MessageReader<Pointer<Move>> mut input_events: MessageReader<Pointer<Move>>,
) { ) {
for event in input_events.read() { for event in input_events.read() {
if let PointerId::Mouse = event.pointer_id { if let PointerId::Mouse = event.pointer_id {
for (cursor, mut location, _) in query.iter_mut() { for (cursor, mut location, _) in query.iter_mut() {
let is_mouse = match cursor.input_source { let is_mouse = match cursor.input_source {
MenuCursorInputSource::Any => true, MenuCursorInputSource::Any => true,
MenuCursorInputSource::Player(slot) => { MenuCursorInputSource::Player(slot) => assignments
assignments.get(slot).map(|(_, source)| { .get(slot)
matches!(source, LocalInputSource::Keyboard) .map(|(_, source)| matches!(source, LocalInputSource::Keyboard))
}).unwrap_or_default() .unwrap_or_default(),
},
}; };
if is_mouse { if is_mouse {
@@ -159,14 +182,23 @@ pub fn cursor_input(
pub fn update_cursor_transform( pub fn update_cursor_transform(
camera: Single<&Camera, With<IsDefaultUiCamera>>, camera: Single<&Camera, With<IsDefaultUiCamera>>,
query: Query<(&mut UiTransform, &PointerLocation), With<FGMenuCursor>>, query: Query<(&mut Node, &PointerLocation), With<FGMenuCursor>>,
ui_scale: Res<UiScale>, ui_scale: Res<UiScale>,
) { ) {
let camera = camera.into_inner(); let camera = camera.into_inner();
for (mut ui_trf, location) in query { for (mut node, location) in query {
let ui_pos = scaling::logical_to_ui_position(location.location.as_ref().map(|d| d.position).unwrap_or_default(), camera, &ui_scale); let ui_pos = scaling::logical_to_ui_position(
ui_trf.translation = Val2::new(px(ui_pos.x), px(ui_pos.y)); location
.location
.as_ref()
.map(|d| d.position)
.unwrap_or_default(),
camera,
&ui_scale,
);
node.left = px(ui_pos.x);
node.top = px(ui_pos.y);
} }
} }
+2 -2
View File
@@ -1,6 +1,6 @@
use bevy::{ecs::query::QueryEntityError, reflect::Reflect}; use bevy::reflect::Reflect;
use crate::{fighter::FighterId, menus::match_config::MenuMatchConfigErrors}; use crate::menus::match_config::MenuMatchConfigErrors;
#[derive(thiserror::Error, Debug, Reflect)] #[derive(thiserror::Error, Debug, Reflect)]
pub enum MenuErrors { pub enum MenuErrors {
+12 -5
View File
@@ -91,10 +91,14 @@ impl MenuInput {
self.accept.accumulate(&other.accept); self.accept.accumulate(&other.accept);
self.back.accumulate(&other.back); self.back.accumulate(&other.back);
self.start.accumulate(&other.start); self.start.accumulate(&other.start);
self.movement_digital_up.accumulate(&other.movement_digital_up); self.movement_digital_up
self.movement_digital_down.accumulate(&other.movement_digital_down); .accumulate(&other.movement_digital_up);
self.movement_digital_left.accumulate(&other.movement_digital_left); self.movement_digital_down
self.movement_digital_right.accumulate(&other.movement_digital_right); .accumulate(&other.movement_digital_down);
self.movement_digital_left
.accumulate(&other.movement_digital_left);
self.movement_digital_right
.accumulate(&other.movement_digital_right);
self.movement = self.movement.clamp_length_max(1.0); self.movement = self.movement.clamp_length_max(1.0);
} }
} }
@@ -249,7 +253,10 @@ pub fn sample_menu_inputs(
.push((LocalInputSource::Keyboard, keyboard_input(&key, &map))); .push((LocalInputSource::Keyboard, keyboard_input(&key, &map)));
let mut prev_joystick_states: Vec<(LocalInputSource, MenuJoystickState)> = vec![]; let mut prev_joystick_states: Vec<(LocalInputSource, MenuJoystickState)> = vec![];
std::mem::swap(&mut prev_joystick_states, &mut state.prev_frame_joystick_state); std::mem::swap(
&mut prev_joystick_states,
&mut state.prev_frame_joystick_state,
);
for (entity, pad) in pads.iter() { for (entity, pad) in pads.iter() {
let local_source = LocalInputSource::Gamepad(entity); let local_source = LocalInputSource::Gamepad(entity);
+3 -6
View File
@@ -1,11 +1,8 @@
use bevy::{ use bevy::{prelude::*, text::FontSourceTemplate};
prelude::*, text::FontSourceTemplate,
ui::auto_directional_navigation::AutoDirectionalNavigation,
};
use crate::{ use crate::{
AppState, AppState,
menus::{MenuMarker, button::menu_button, navigation::NavigationDefaultFocus}, menus::{button::menu_button, navigation::NavigationDefaultFocus},
}; };
#[derive(SceneComponent, Default, Clone)] #[derive(SceneComponent, Default, Clone)]
@@ -58,4 +55,4 @@ impl MainMenu {
} }
} }
pub fn setup_main_menu(mut commands: Commands) {} pub fn setup_main_menu(_commands: Commands) {}
+58 -9
View File
@@ -1,37 +1,86 @@
use bevy::prelude::*; use bevy::prelude::*;
use thiserror::Error; use thiserror::Error;
use crate::fighter::FighterId; use crate::{
fighter::FighterId,
match_loading::{MatchPlayer, PendingMatch},
stage::manifest::StageId,
};
pub struct MenuMatchPlayerSlot { pub struct MenuMatchPlayerSlot {
pub slot: usize, pub slot: usize,
pub fighter: Option<FighterId> pub fighter: Option<FighterId>,
} }
#[derive(Resource, Default)] #[derive(Resource, Default)]
pub struct MenuMatchConfig { pub struct MenuMatchConfig {
pub players: Vec<MenuMatchPlayerSlot> pub stage: Option<StageId>,
pub players: Vec<MenuMatchPlayerSlot>,
} }
#[derive(Error, Debug, Reflect)] #[derive(Error, Debug, Reflect)]
pub enum MenuMatchConfigErrors { pub enum MenuMatchConfigErrors {
#[error("Fighter slot {0} was invalid!")] #[error("Fighter slot {0} was invalid!")]
PlayerSlotInvalid(usize) PlayerSlotInvalid(usize),
#[error("Invalid configuration: Slot {0} doesn't have a fighter selected")]
FighterNotSelectedForSlot(usize),
#[error("Invalid configuration: No stage selected")]
StageNotSelected,
} }
impl MenuMatchConfig { impl MenuMatchConfig {
pub fn set_player_fighter(&mut self, player_slot: usize, fighter_id: Option<FighterId>) -> Result<(), MenuMatchConfigErrors> { pub fn set_player_fighter(
let slot = self.players.get_mut(player_slot).ok_or(MenuMatchConfigErrors::PlayerSlotInvalid(player_slot))?; &mut self,
player_slot: usize,
fighter_id: Option<FighterId>,
) -> Result<(), MenuMatchConfigErrors> {
let slot = self
.players
.get_mut(player_slot)
.ok_or(MenuMatchConfigErrors::PlayerSlotInvalid(player_slot))?;
slot.fighter = fighter_id; slot.fighter = fighter_id;
Ok(()) Ok(())
} }
pub fn get_player_fighter(&self, player_slot: usize) -> Result<Option<FighterId>, MenuMatchConfigErrors> { pub fn get_player_fighter(
let slot = self.players.get(player_slot).ok_or(MenuMatchConfigErrors::PlayerSlotInvalid(player_slot))?; &self,
player_slot: usize,
) -> Result<Option<FighterId>, MenuMatchConfigErrors> {
let slot = self
.players
.get(player_slot)
.ok_or(MenuMatchConfigErrors::PlayerSlotInvalid(player_slot))?;
Ok(slot.fighter) Ok(slot.fighter)
} }
pub fn all_players_ready(&self) -> bool { pub fn all_players_ready(&self) -> bool {
let has_unselected_fighter = self.players.iter().any(|player_slot| player_slot.fighter.is_none()); let has_unselected_fighter = self
.players
.iter()
.any(|player_slot| player_slot.fighter.is_none());
!has_unselected_fighter !has_unselected_fighter
} }
pub fn to_pending_match(&self) -> Result<PendingMatch, MenuMatchConfigErrors> {
let mut match_players = vec![];
let stage = self.stage.ok_or(MenuMatchConfigErrors::StageNotSelected)?;
for player in self.players.iter() {
let fighter_id =
player
.fighter
.ok_or(MenuMatchConfigErrors::FighterNotSelectedForSlot(
player.slot,
))?;
match_players.push(MatchPlayer {
fighter: fighter_id,
handle: player.slot,
});
}
Ok(PendingMatch {
players: match_players,
stage,
})
}
} }
+66 -23
View File
@@ -6,7 +6,6 @@ use bevy::{
prelude::*, prelude::*,
}; };
use bevy::prelude::*;
use ron_asset_manager::RonAssetPlugin; use ron_asset_manager::RonAssetPlugin;
use crate::{ use crate::{
@@ -17,21 +16,21 @@ use crate::{
pub mod button; pub mod button;
pub mod character_select; pub mod character_select;
pub mod cursor; pub mod cursor;
pub mod errors;
pub mod input; pub mod input;
pub mod main_menu; pub mod main_menu;
pub mod match_config;
pub mod navigation; pub mod navigation;
pub mod scaling; pub mod scaling;
pub mod style;
pub mod match_config;
pub mod errors;
pub mod stage_select; pub mod stage_select;
pub mod style;
#[derive(Component, Clone, Default)] #[derive(Component, Clone, Default)]
pub struct MenuMarker {} pub struct MenuMarker {}
pub struct MenuPlugin; pub struct MenuPlugin;
pub fn build_menu_scene<S>(existing_menu: Option<Single<Entity, With<MenuMarker>>>) -> impl Scene pub fn build_menu_scene<S>(_existing_menu: Option<Single<Entity, With<MenuMarker>>>) -> impl Scene
where where
S: SceneComponent + Default + Clone + Send + Sync, S: SceneComponent + Default + Clone + Send + Sync,
{ {
@@ -66,6 +65,19 @@ pub fn wrap_menu(menu: impl Scene) -> impl Scene {
} }
} }
pub fn despawn_menu(
existing_menu: Option<Single<Entity, With<MenuMarker>>>,
mut commands: Commands,
) {
if let Some(entity) = existing_menu {
commands
.entity(entity.into_inner())
.remove::<Camera2d>()
.remove::<Camera>()
.despawn();
}
}
pub fn spawn_menu( pub fn spawn_menu(
existing_menu: Option<Single<Entity, With<MenuMarker>>>, existing_menu: Option<Single<Entity, With<MenuMarker>>>,
mut commands: Commands, mut commands: Commands,
@@ -88,10 +100,8 @@ where
S::scene(props) S::scene(props)
} }
pub fn build_menu<S>( pub fn build_menu<S>(existing_menu: Option<Single<Entity, With<MenuMarker>>>, commands: Commands)
existing_menu: Option<Single<Entity, With<MenuMarker>>>, where
mut commands: Commands,
) where
S: SceneComponent + Default + Clone + Send + Sync, S: SceneComponent + Default + Clone + Send + Sync,
{ {
spawn_menu( spawn_menu(
@@ -116,10 +126,7 @@ impl Plugin for MenuPlugin {
)); ));
}), }),
) )
.add_systems( .add_message::<character_select::PlayerSlotAssigned>()
OnEnter(AppState::CharacterSelect),
character_select::setup_character_select,
)
.init_resource::<navigation::UINavigationActionState>() .init_resource::<navigation::UINavigationActionState>()
.init_resource::<navigation::UINavigationRepeat>() .init_resource::<navigation::UINavigationRepeat>()
.init_resource::<input::MenuInputState>() .init_resource::<input::MenuInputState>()
@@ -150,35 +157,71 @@ impl Plugin for MenuPlugin {
.run_if(resource_exists::<CommonAssets>), .run_if(resource_exists::<CommonAssets>),
) )
.add_systems(Startup, scaling::ui_update_scale_on_startup) .add_systems(Startup, scaling::ui_update_scale_on_startup)
// CURSOR
.add_systems(
PreUpdate,
(cursor::cursor_input).before(bevy::picking::PickingSystems::ProcessInput),
)
.add_systems(
Update,
(cursor::copy_mouse_input, cursor::update_cursor_transform),
)
.add_systems( .add_systems(
PreUpdate, PreUpdate,
input::sample_menu_inputs input::sample_menu_inputs
.before(cursor::cursor_input) .before(cursor::cursor_input)
.run_if(resource_exists::<crate::input::MenuInputMap>), .run_if(resource_exists::<crate::input::MenuInputMap>),
) )
//---------
// CHARACTER SELECT START
//---------
.add_systems( .add_systems(
PreUpdate, OnEnter(AppState::CharacterSelect),
cursor::cursor_input character_select::setup_character_select,
.before(bevy::picking::PickingSystems::ProcessInput) )
.add_systems(
PostUpdate,
character_select::copy_cursor_transform_to_token
.run_if(in_state(AppState::CharacterSelect)) .run_if(in_state(AppState::CharacterSelect))
.run_if(any_with_component::<CharacterSelectScreen>), .run_if(any_with_component::<CharacterSelectScreen>),
) )
.add_systems( .add_systems(
PostUpdate, PreUpdate,
( (
character_select::css_auto_assign_slots, character_select::css_auto_assign_slots,
cursor::copy_mouse_input, character_select::handle_fighter_slot_addition,
cursor::update_cursor_transform,
character_select::copy_cursor_transform_to_token,
) )
.chain() .chain()
.run_if(in_state(AppState::CharacterSelect)) .run_if(in_state(AppState::CharacterSelect))
.run_if(any_with_component::<CharacterSelectScreen>), .run_if(any_with_component::<CharacterSelectScreen>),
) )
.add_systems(OnExit(AppState::CharacterSelect), cursor::despawn_cursors) .add_systems(
.add_observer(character_select::handle_fighter_slot_addition) OnExit(AppState::CharacterSelect),
(cursor::despawn_cursors, character_select::despawn_tokens),
)
.add_observer(character_select::select_fighter.run_if(in_state(AppState::CharacterSelect))) .add_observer(character_select::select_fighter.run_if(in_state(AppState::CharacterSelect)))
.add_observer(character_select::update_start_banner_visibility.run_if(in_state(AppState::CharacterSelect))) .add_observer(
character_select::update_start_banner_visibility
.run_if(in_state(AppState::CharacterSelect)),
)
//---------
// CHARACTER SELECT END
//---------
//---------
// STAGE SELECT START
//---------
.add_systems(
OnEnter(AppState::StageSelect),
stage_select::setup_stage_select,
)
.add_observer(stage_select::stage_selected.run_if(in_state(AppState::StageSelect)))
.add_systems(
OnExit(AppState::StageSelect),
(cursor::despawn_cursors, despawn_menu),
)
//---------
// STAGE SELECT END
//---------
.add_plugins(RonAssetPlugin::<FGUiStyle>::create("stylesheet.ron")) .add_plugins(RonAssetPlugin::<FGUiStyle>::create("stylesheet.ron"))
.add_systems( .add_systems(
Update, Update,
+25 -6
View File
@@ -10,7 +10,6 @@ use bevy::{
prelude::*, prelude::*,
ui::auto_directional_navigation::AutoDirectionalNavigator, ui::auto_directional_navigation::AutoDirectionalNavigator,
}; };
use bevy_egui::egui::IntoAtoms;
use std::collections::HashSet; use std::collections::HashSet;
// Action state and input handling // Action state and input handling
@@ -82,12 +81,32 @@ pub fn process_inputs(
false false
}; };
if curr_dir.is_just_pressed() || repeat_press { if curr_dir.is_just_pressed() || repeat_press {
if input.movement.y > 0.0 { action_state.pressed_actions.insert(DirectionalNavigationAction::Up); } if input.movement.y > 0.0 {
if input.movement.y < 0.0 { action_state.pressed_actions.insert(DirectionalNavigationAction::Down); } action_state
if input.movement.x < 0.0 { action_state.pressed_actions.insert(DirectionalNavigationAction::Left); } .pressed_actions
if input.movement.x > 0.0 { action_state.pressed_actions.insert(DirectionalNavigationAction::Right); } .insert(DirectionalNavigationAction::Up);
}
if input.movement.y < 0.0 {
action_state
.pressed_actions
.insert(DirectionalNavigationAction::Down);
}
if input.movement.x < 0.0 {
action_state
.pressed_actions
.insert(DirectionalNavigationAction::Left);
}
if input.movement.x > 0.0 {
action_state
.pressed_actions
.insert(DirectionalNavigationAction::Right);
}
}
if input.accept.is_pressed() {
action_state
.pressed_actions
.insert(DirectionalNavigationAction::Select);
} }
if input.accept.is_pressed() { action_state.pressed_actions.insert(DirectionalNavigationAction::Select); }
} }
const FOCUSED_BORDER: Srgba = bevy::color::palettes::tailwind::BLUE_50; const FOCUSED_BORDER: Srgba = bevy::color::palettes::tailwind::BLUE_50;
+9 -4
View File
@@ -1,5 +1,3 @@
use bevy::camera::CameraProjection;
use bevy::camera::Projection::Orthographic;
use bevy::prelude::*; use bevy::prelude::*;
use bevy::window::WindowResized; use bevy::window::WindowResized;
@@ -30,8 +28,15 @@ pub fn ui_scaling_system(
} }
} }
pub fn world_to_ui_position(pos: Vec2, camera: &Camera, camera_transform: &GlobalTransform, ui_scale: &UiScale) -> Vec2 { pub fn world_to_ui_position(
let viewport_position = camera.world_to_viewport(camera_transform, Vec3::new(pos.x, pos.y, 0.0)).unwrap(); pos: Vec2,
camera: &Camera,
camera_transform: &GlobalTransform,
ui_scale: &UiScale,
) -> Vec2 {
let viewport_position = camera
.world_to_viewport(camera_transform, Vec3::new(pos.x, pos.y, 0.0))
.unwrap();
let viewport_rect = camera.logical_viewport_rect().unwrap(); let viewport_rect = camera.logical_viewport_rect().unwrap();
+84
View File
@@ -0,0 +1,84 @@
use bevy::prelude::*;
use crate::{
AppState,
game_settings::CommonAssets,
match_loading::initiate_match,
menus::{
MenuMarker, cursor, match_config::MenuMatchConfig, spawn_menu,
stage_select::stage_box::StageBox, style::FGUiStyle,
},
stage::manifest::{StageManifest, StageManifestRegistry},
};
pub mod stage_box;
#[derive(Component, FromTemplate)]
pub struct StageSelectScreen {
pub stage_icons_container: Entity,
}
pub fn setup_stage_select(
existing_menu: Option<Single<Entity, With<MenuMarker>>>,
mut commands: Commands,
manifest_registry: Res<StageManifestRegistry>,
manifests: Res<Assets<StageManifest>>,
common_assets: Res<CommonAssets>,
styles: Res<Assets<FGUiStyle>>,
) {
let style = styles
.get(&common_assets.ui_style)
.expect("UI style should be loaded");
let stage_boxes = manifest_registry
.iter()
.map(|(_, v)| stage_box::StageBox::scene(v.clone(), &manifests))
.collect::<Vec<_>>();
let menu = bsn! {
// Characters
StageSelectScreen {
stage_icons_container: #PortraitContainer
}
Node {
flex_direction: FlexDirection::Column
}
Children [
(
Node {
flex_direction: FlexDirection::Column,
width: percent(100),
height: percent(100),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center
}
Children [
{stage_boxes},
]
)
]
};
commands.spawn(cursor::FGMenuCursor::create_shared_cursor(style));
spawn_menu(existing_menu, commands, menu);
}
pub fn stage_selected(
ev: On<Pointer<Press>>,
query: Query<&StageBox>,
mut commands: Commands,
mut next_state: ResMut<NextState<AppState>>,
mut match_config: ResMut<MenuMatchConfig>,
) -> Result {
let stage_box = query.get(ev.event_target());
if let Ok(stage_box) = stage_box {
match_config.stage = Some(stage_box.stage_id);
initiate_match(
&mut commands,
&mut next_state,
match_config.to_pending_match()?,
);
}
Ok(())
}
+56
View File
@@ -0,0 +1,56 @@
use bevy::{picking::Pickable, prelude::*, text::FontSourceTemplate};
use crate::{
menus::{button::FGUiButton, style::FGUiButtonType},
stage::manifest::{StageId, StageManifest},
};
#[derive(Component, Clone, FromTemplate)]
pub struct StageBox {
pub stage_manifest: Handle<StageManifest>,
pub stage_id: StageId,
}
impl StageBox {
pub fn scene(
manifest_handle: Handle<StageManifest>,
manifests: &Res<Assets<StageManifest>>,
) -> impl Scene {
let manifest = manifests
.get(&manifest_handle)
.expect("Stage manifest should be valid");
let fighter_icon = manifest.icon.handle().clone();
let stage_id = manifest.id;
bsn! {
Node {
width: px(256),
height: px(256),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::FlexEnd
}
ImageNode {
image: fighter_icon
}
FGUiButton {
button_type: FGUiButtonType::StageSelectIcon
}
StageBox {
stage_manifest: manifest_handle,
stage_id: stage_id
}
BackgroundColor(Color::srgb(1.0, 1.0, 1.0))
Children [
Pickable::IGNORE
Node {
width: percent(100)
}
TextFont {
font: FontSourceTemplate::Handle("fonts/roboto.ttf"),
font_size: px(crate::menus::style::TEXT_SIZE),
}
TextColor(Color::srgb(0.9, 0.9, 0.9))
BackgroundColor(Color::srgb(0.0, 0.0, 1.0))
]
}
}
}
+6 -2
View File
@@ -1,8 +1,8 @@
use std::collections::HashMap; use std::collections::HashMap;
use bevy::prelude::*; use bevy::prelude::*;
use serde::{Deserialize, Serialize};
use ron_asset_manager::prelude::*; use ron_asset_manager::prelude::*;
use serde::{Deserialize, Serialize};
use crate::texture_reference::TextureReference; use crate::texture_reference::TextureReference;
@@ -26,6 +26,7 @@ pub struct BoxShadowStyle {
pub struct ButtonStyle { pub struct ButtonStyle {
background_color: Color, background_color: Color,
border_color: Color, border_color: Color,
border_radius: f32,
text_color: Color, text_color: Color,
box_shadow: BoxShadowStyle, box_shadow: BoxShadowStyle,
border_size: i32, border_size: i32,
@@ -44,9 +45,10 @@ pub struct ButtonStyles {
impl ButtonStyle { impl ButtonStyle {
pub fn apply(&self, commands: &mut Commands, entity: Entity, node: &mut Node) { pub fn apply(&self, commands: &mut Commands, entity: Entity, node: &mut Node) {
node.border = UiRect::all(px(self.border_size)); node.border = UiRect::all(px(self.border_size));
node.border_radius = BorderRadius::all(px(self.border_radius));
commands.entity(entity).insert(( commands.entity(entity).insert((
BackgroundColor(self.background_color), BackgroundColor(self.background_color),
BorderColor::all(self.background_color), BorderColor::all(self.border_color),
BoxShadow::new( BoxShadow::new(
self.box_shadow.color, self.box_shadow.color,
px(self.box_shadow.offset_px_x), px(self.box_shadow.offset_px_x),
@@ -64,6 +66,7 @@ pub enum FGUiButtonType {
MainMenu, MainMenu,
CharacterSelectCharacter, CharacterSelectCharacter,
CharacterSelectStartBanner, CharacterSelectStartBanner,
StageSelectIcon,
} }
#[derive(Asset, Resource, Reflect, Deserialize, RonAsset)] #[derive(Asset, Resource, Reflect, Deserialize, RonAsset)]
@@ -77,4 +80,5 @@ pub struct FGUiStyle {
#[dependency] #[dependency]
#[reflect(ignore)] #[reflect(ignore)]
pub css_token: TextureReference, pub css_token: TextureReference,
pub player_colors: Vec<Color>,
} }
+157 -36
View File
@@ -1,13 +1,24 @@
//! Deterministic input recording and playback. //! Deterministic input recording and playback.
use std::{collections::BTreeMap, fs, path::{Path, PathBuf}}; use std::{
collections::BTreeMap,
fs,
path::{Path, PathBuf},
};
use bevy::prelude::*; use bevy::prelude::*;
use bevy_ggrs::{prelude::*, PlayerInputs, RollbackFrameCount, SaveWorld}; use bevy_ggrs::{PlayerInputs, RollbackFrameCount, SaveWorld, prelude::*};
use clap::ValueEnum; use clap::ValueEnum;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{args::Args, input::FighterInputFrame, match_loading::{MatchPlayer, PendingMatch}, netcode::GGRSCfg, schedule::GameplaySet, AppState}; use crate::{
AppState,
args::Args,
input::FighterInputFrame,
match_loading::{MatchPlayer, PendingMatch},
netcode::GGRSCfg,
schedule::GameplaySet,
};
const MAGIC: &[u8; 8] = b"SPRPLY01"; const MAGIC: &[u8; 8] = b"SPRPLY01";
pub const REPLAY_VERSION: u32 = 1; pub const REPLAY_VERSION: u32 = 1;
@@ -79,7 +90,12 @@ impl Plugin for ReplayPlugin {
.in_set(GameplaySet::Input) .in_set(GameplaySet::Input)
.before(crate::input::buffer::postprocess_input), .before(crate::input::buffer::postprocess_input),
) )
.add_systems(SaveWorld, record_checksum.after(SaveWorldSystems::Checksum).before(SaveWorldSystems::Snapshot)) .add_systems(
SaveWorld,
record_checksum
.after(SaveWorldSystems::Checksum)
.before(SaveWorldSystems::Snapshot),
)
.add_systems(OnExit(AppState::InMatch), finish_recording) .add_systems(OnExit(AppState::InMatch), finish_recording)
.add_systems(Update, stop_recording.run_if(in_state(AppState::InMatch))) .add_systems(Update, stop_recording.run_if(in_state(AppState::InMatch)))
.add_systems(Update, finish_playback.run_if(in_state(AppState::InMatch))); .add_systems(Update, finish_playback.run_if(in_state(AppState::InMatch)));
@@ -87,7 +103,8 @@ impl Plugin for ReplayPlugin {
} }
pub fn load(path: &Path) -> Result<Replay, String> { pub fn load(path: &Path) -> Result<Replay, String> {
let bytes = fs::read(path).map_err(|error| format!("cannot read replay {}: {error}", path.display()))?; let bytes = fs::read(path)
.map_err(|error| format!("cannot read replay {}: {error}", path.display()))?;
let replay = if bytes.starts_with(MAGIC) { let replay = if bytes.starts_with(MAGIC) {
if bytes.len() < MAGIC.len() + 4 { if bytes.len() < MAGIC.len() + 4 {
return Err("replay binary header is truncated".into()); return Err("replay binary header is truncated".into());
@@ -96,7 +113,8 @@ pub fn load(path: &Path) -> Result<Replay, String> {
if version != REPLAY_VERSION { if version != REPLAY_VERSION {
return Err(format!("unsupported replay version {version}")); return Err(format!("unsupported replay version {version}"));
} }
bincode::deserialize(&bytes[12..]).map_err(|error| format!("invalid binary replay: {error}"))? bincode::deserialize(&bytes[12..])
.map_err(|error| format!("invalid binary replay: {error}"))?
} else { } else {
serde_json::from_slice(&bytes).map_err(|error| format!("invalid JSON replay: {error}"))? serde_json::from_slice(&bytes).map_err(|error| format!("invalid JSON replay: {error}"))?
}; };
@@ -110,10 +128,14 @@ pub fn save(path: &Path, format: ReplayFormat, replay: &Replay) -> Result<(), St
ReplayFormat::Binary => { ReplayFormat::Binary => {
let mut bytes = MAGIC.to_vec(); let mut bytes = MAGIC.to_vec();
bytes.extend(REPLAY_VERSION.to_le_bytes()); bytes.extend(REPLAY_VERSION.to_le_bytes());
bytes.extend(bincode::serialize(replay).map_err(|error| format!("cannot encode replay: {error}"))?); bytes.extend(
bincode::serialize(replay)
.map_err(|error| format!("cannot encode replay: {error}"))?,
);
bytes bytes
} }
ReplayFormat::Json => serde_json::to_vec_pretty(replay).map_err(|error| format!("cannot encode replay JSON: {error}"))?, ReplayFormat::Json => serde_json::to_vec_pretty(replay)
.map_err(|error| format!("cannot encode replay JSON: {error}"))?,
}; };
let temporary = path.with_extension("replay.tmp"); let temporary = path.with_extension("replay.tmp");
fs::write(&temporary, bytes).map_err(|error| format!("cannot write replay: {error}"))?; fs::write(&temporary, bytes).map_err(|error| format!("cannot write replay: {error}"))?;
@@ -122,7 +144,10 @@ pub fn save(path: &Path, format: ReplayFormat, replay: &Replay) -> Result<(), St
fn validate(replay: &Replay) -> Result<(), String> { fn validate(replay: &Replay) -> Result<(), String> {
if replay.replay_version != REPLAY_VERSION { if replay.replay_version != REPLAY_VERSION {
return Err(format!("unsupported replay version {}", replay.replay_version)); return Err(format!(
"unsupported replay version {}",
replay.replay_version
));
} }
if replay.players_are_invalid() { if replay.players_are_invalid() {
return Err("replay player handles must cover 0..player_count".into()); return Err("replay player handles must cover 0..player_count".into());
@@ -130,10 +155,18 @@ fn validate(replay: &Replay) -> Result<(), String> {
if replay.frames.is_empty() { if replay.frames.is_empty() {
return Err("replay must contain at least one frame".into()); return Err("replay must contain at least one frame".into());
} }
if replay.frames.windows(2).any(|frames| frames[0].frame >= frames[1].frame) { if replay
.frames
.windows(2)
.any(|frames| frames[0].frame >= frames[1].frame)
{
return Err("replay frames must be strictly ordered".into()); return Err("replay frames must be strictly ordered".into());
} }
if replay.frames.iter().any(|frame| frame.inputs.len() != replay.match_config.players.len()) { if replay
.frames
.iter()
.any(|frame| frame.inputs.len() != replay.match_config.players.len())
{
return Err("replay frame input count does not match player count".into()); return Err("replay frame input count does not match player count".into());
} }
Ok(()) Ok(())
@@ -141,7 +174,12 @@ fn validate(replay: &Replay) -> Result<(), String> {
impl Replay { impl Replay {
fn players_are_invalid(&self) -> bool { fn players_are_invalid(&self) -> bool {
let mut handles: Vec<_> = self.match_config.players.iter().map(|player| player.handle).collect(); let mut handles: Vec<_> = self
.match_config
.players
.iter()
.map(|player| player.handle)
.collect();
handles.sort_unstable(); handles.sort_unstable();
handles != (0..handles.len()).collect::<Vec<_>>() handles != (0..handles.len()).collect::<Vec<_>>()
} }
@@ -149,23 +187,44 @@ impl Replay {
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>>) {
let mode = if let Some(replay) = loaded { let mode = if let Some(replay) = loaded {
ReplayMode::Playback { replay: replay.0.clone(), mismatch: false } ReplayMode::Playback {
replay: replay.0.clone(),
mismatch: false,
}
} else if let Some(path) = args.record_replay.clone() { } else if let Some(path) = args.record_replay.clone() {
ReplayMode::Record { path, format: args.replay_format } ReplayMode::Record {
path,
format: args.replay_format,
}
} else { } else {
return; return;
}; };
commands.insert_resource(ReplayRuntime { mode, frames: BTreeMap::new(), checksums: BTreeMap::new(), finished: false }); commands.insert_resource(ReplayRuntime {
mode,
frames: BTreeMap::new(),
checksums: BTreeMap::new(),
finished: false,
});
} }
fn replay_inputs(mut inputs: ResMut<PlayerInputs<GGRSCfg>>, frame: Res<RollbackFrameCount>, runtime: Option<ResMut<ReplayRuntime>>) { fn replay_inputs(
mut inputs: ResMut<PlayerInputs<GGRSCfg>>,
frame: Res<RollbackFrameCount>,
runtime: Option<ResMut<ReplayRuntime>>,
) {
let Some(mut runtime) = runtime else { return }; let Some(mut runtime) = runtime else { return };
match &mut runtime.mode { match &mut runtime.mode {
ReplayMode::Record { .. } => { ReplayMode::Record { .. } => {
runtime.frames.insert(frame.0, inputs.iter().map(|(input, _)| *input).collect()); runtime
.frames
.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.frames.iter().find(|recorded| recorded.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;
@@ -178,14 +237,26 @@ fn replay_inputs(mut inputs: ResMut<PlayerInputs<GGRSCfg>>, frame: Res<RollbackF
} }
} }
fn record_checksum(frame: Res<RollbackFrameCount>, checksum: Res<Checksum>, runtime: Option<ResMut<ReplayRuntime>>) { fn record_checksum(
frame: Res<RollbackFrameCount>,
checksum: Res<Checksum>,
runtime: Option<ResMut<ReplayRuntime>>,
) {
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 {
if let Some(expected) = replay.checksums.iter().find(|value| value.frame == frame.0).map(|value| value.checksum) { if let Some(expected) = replay
.checksums
.iter()
.find(|value| value.frame == frame.0)
.map(|value| value.checksum)
{
if expected != checksum.0 { if expected != checksum.0 {
error!("Replay desync at frame {}: expected {:X}, got {:X}", frame.0, expected, checksum.0); error!(
"Replay desync at frame {}: expected {:X}, got {:X}",
frame.0, expected, checksum.0
);
*mismatch = true; *mismatch = true;
} }
} }
@@ -205,7 +276,11 @@ fn stop_recording(
finish_recording_inner(&mut commands, runtime, request); finish_recording_inner(&mut commands, runtime, request);
} }
fn finish_recording(mut commands: Commands, runtime: Option<ResMut<ReplayRuntime>>, request: Option<Res<PendingMatch>>) { fn finish_recording(
mut commands: Commands,
runtime: Option<ResMut<ReplayRuntime>>,
request: Option<Res<PendingMatch>>,
) {
finish_recording_inner(&mut commands, runtime, request); finish_recording_inner(&mut commands, runtime, request);
} }
@@ -215,38 +290,75 @@ fn finish_recording_inner(
request: Option<Res<PendingMatch>>, request: Option<Res<PendingMatch>>,
) { ) {
let Some(mut runtime) = runtime else { return }; let Some(mut runtime) = runtime else { return };
let ReplayMode::Record { path, format } = &runtime.mode else { return }; let ReplayMode::Record { path, format } = &runtime.mode else {
if runtime.finished || runtime.frames.is_empty() { return; } return;
};
if runtime.finished || runtime.frames.is_empty() {
return;
}
let Some(request) = request else { return }; let Some(request) = request else { return };
let path = path.clone(); let path = path.clone();
let format = *format; let format = *format;
let replay = Replay { let replay = Replay {
replay_version: REPLAY_VERSION, replay_version: REPLAY_VERSION,
game_version: env!("CARGO_PKG_VERSION").into(), game_version: env!("CARGO_PKG_VERSION").into(),
match_config: ReplayMatch { stage: request.stage, players: request.players.clone() }, match_config: ReplayMatch {
frames: runtime.frames.iter().map(|(&frame, inputs)| ReplayFrame { frame, inputs: inputs.clone() }).collect(), stage: request.stage,
checksums: runtime.checksums.iter().map(|(&frame, &checksum)| ReplayChecksum { frame, checksum }).collect(), players: request.players.clone(),
},
frames: runtime
.frames
.iter()
.map(|(&frame, inputs)| ReplayFrame {
frame,
inputs: inputs.clone(),
})
.collect(),
checksums: runtime
.checksums
.iter()
.map(|(&frame, &checksum)| ReplayChecksum { frame, checksum })
.collect(),
}; };
if let Err(error) = save(&path, format, &replay) { error!("Failed to save replay: {error}"); } if let Err(error) = save(&path, format, &replay) {
error!("Failed to save replay: {error}");
}
runtime.finished = true; runtime.finished = true;
commands.remove_resource::<ReplayRuntime>(); commands.remove_resource::<ReplayRuntime>();
} }
fn finish_playback(mut commands: Commands, mut next_state: ResMut<NextState<AppState>>, frame: Res<RollbackFrameCount>, runtime: Option<Res<ReplayRuntime>>) { fn finish_playback(
mut commands: Commands,
mut next_state: ResMut<NextState<AppState>>,
frame: Res<RollbackFrameCount>,
runtime: Option<Res<ReplayRuntime>>,
) {
let Some(runtime) = runtime else { return }; let Some(runtime) = runtime else { return };
let ReplayMode::Playback { replay, mismatch } = &runtime.mode else { return }; let ReplayMode::Playback { replay, mismatch } = &runtime.mode else {
if *mismatch || replay.frames.last().is_some_and(|last| frame.0 >= last.frame) { return;
};
if *mismatch
|| replay
.frames
.last()
.is_some_and(|last| frame.0 >= last.frame)
{
commands.remove_resource::<ReplayRuntime>(); commands.remove_resource::<ReplayRuntime>();
commands.remove_resource::<LoadedReplay>(); commands.remove_resource::<LoadedReplay>();
commands.insert_resource(ReplayComplete); commands.insert_resource(ReplayComplete);
next_state.set(AppState::MainMenu); next_state.set(AppState::PreMainMenu);
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::{fighter::FighterId, math::{int::FGi32, vec::FGVec2}, match_loading::MatchPlayer, stage::manifest::StageId}; use crate::{
fighter::FighterId,
match_loading::MatchPlayer,
math::{int::FGi32, vec::FGVec2},
stage::manifest::StageId,
};
fn sample() -> Replay { fn sample() -> Replay {
Replay { Replay {
@@ -254,13 +366,22 @@ mod tests {
game_version: "test".into(), game_version: "test".into(),
match_config: ReplayMatch { match_config: ReplayMatch {
stage: StageId::TestStage, stage: StageId::TestStage,
players: vec![MatchPlayer { handle: 0, fighter: FighterId::TestFighter }], players: vec![MatchPlayer {
handle: 0,
fighter: FighterId::TestFighter,
}],
}, },
frames: vec![ReplayFrame { frames: vec![ReplayFrame {
frame: 1, frame: 1,
inputs: vec![FighterInputFrame { movement: FGVec2::new(FGi32::from_num(1), FGi32::ZERO), ..default() }], inputs: vec![FighterInputFrame {
movement: FGVec2::new(FGi32::from_num(1), FGi32::ZERO),
..default()
}],
}],
checksums: vec![ReplayChecksum {
frame: 1,
checksum: 42,
}], }],
checksums: vec![ReplayChecksum { frame: 1, checksum: 42 }],
} }
} }
+5 -1
View File
@@ -19,9 +19,12 @@ pub enum GameplaySet {
StateUpdate, StateUpdate,
/// Integrate velocities into positions. /// Integrate velocities into positions.
Physics, Physics,
/// Solve collision boxes
Animation,
/// Resolve the integrated positions against the stage. /// Resolve the integrated positions against the stage.
Collision, Collision,
Animation, /// Resolve attacks
Attacks,
} }
/// Declares the order of [`GameplaySet`] inside [`GgrsSchedule`]. Added by /// Declares the order of [`GameplaySet`] inside [`GgrsSchedule`]. Added by
@@ -39,6 +42,7 @@ impl Plugin for GameplaySchedulePlugin {
GameplaySet::Physics, GameplaySet::Physics,
GameplaySet::Collision, GameplaySet::Collision,
GameplaySet::Animation, GameplaySet::Animation,
GameplaySet::Attacks,
) )
.chain(), .chain(),
); );
+17
View File
@@ -1,5 +1,6 @@
use bevy::prelude::*; use bevy::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use crate::{fighter::attack::AttackHitbox, math::int::FGi32}; use crate::{fighter::attack::AttackHitbox, math::int::FGi32};
@@ -17,3 +18,19 @@ pub struct FighterAttackScript {
pub iasa_frame: u32, pub iasa_frame: u32,
pub wont_autocancel_window: (u32, u32), pub wont_autocancel_window: (u32, u32),
} }
impl FighterAttackScript {
pub fn validate(&self) -> Result<(), String> {
let mut ids = HashSet::with_capacity(self.hitboxes.len());
for hitbox in &self.hitboxes {
hitbox.validate()?;
if !ids.insert(hitbox.id) {
return Err(format!("duplicate hitbox id {}", hitbox.id));
}
}
if self.wont_autocancel_window.0 > self.wont_autocancel_window.1 {
return Err("autocancel window end precedes its start".into());
}
Ok(())
}
}
+114 -23
View File
@@ -3,7 +3,9 @@ use std::{cell::RefCell, collections::HashMap, rc::Rc};
use rhai::EvalAltResult; use rhai::EvalAltResult;
use crate::{ use crate::{
fighter::attack::{self, AttackAngle, FighterDamage, Knockback, KnockbackType}, math::{int::FGi32, vec::FGVec2, vec3::FGVec3}, scripting::FighterAttackScript, fighter::attack::{self, AttackAngle, FighterDamage, Knockback, KnockbackType},
math::{int::FGi32, vec::FGVec2, vec3::FGVec3},
scripting::FighterAttackScript,
}; };
#[derive(Debug, Default)] #[derive(Debug, Default)]
@@ -15,6 +17,16 @@ struct MoveCompiler {
cursor: u32, cursor: u32,
} }
fn rhai_u32(value: i64, parameter: &str) -> Result<u32, Box<EvalAltResult>> {
u32::try_from(value).map_err(|_| {
format!(
"{parameter} must be between 0 and {}, got {value}",
u32::MAX
)
.into()
})
}
impl MoveCompiler { impl MoveCompiler {
fn frame(&mut self, new_frame: u32) -> Result<(), Box<EvalAltResult>> { fn frame(&mut self, new_frame: u32) -> Result<(), Box<EvalAltResult>> {
if new_frame < self.cursor { if new_frame < self.cursor {
@@ -61,9 +73,17 @@ impl MoveCompiler {
Ok(()) Ok(())
} }
fn set_wont_autocancel_window(&mut self, start: u32, end: u32) -> Result<(), Box<EvalAltResult>> { fn set_wont_autocancel_window(
&mut self,
start: u32,
end: u32,
) -> Result<(), Box<EvalAltResult>> {
if end < start { if end < start {
return Err(format!("Couldn't set won't autocancel window, end frame {} is smaller than start frame {}", end, start).into()); return Err(format!(
"Couldn't set won't autocancel window, end frame {} is smaller than start frame {}",
end, start
)
.into());
} }
self.wont_autocancel_window = Some((start, end)); self.wont_autocancel_window = Some((start, end));
@@ -77,13 +97,14 @@ impl MoveCompiler {
fn into_attack_script(mut self) -> Result<FighterAttackScript, String> { fn into_attack_script(mut self) -> Result<FighterAttackScript, String> {
self.remove_all_hitboxes().map_err(|err| err.to_string())?; self.remove_all_hitboxes().map_err(|err| err.to_string())?;
let hitboxes = self.hitboxes.into_iter().map(|(_, hitbox)| hitbox).collect(); let mut hitboxes: Vec<_> = self.hitboxes.into_values().collect();
hitboxes.sort_unstable_by_key(|hitbox| hitbox.id);
let iasa_frame = self.iasa_frame.unwrap_or(100000); let iasa_frame = self.iasa_frame.unwrap_or(100000);
let wont_autocancel_window = self.wont_autocancel_window.unwrap_or((0, 100000)); let wont_autocancel_window = self.wont_autocancel_window.unwrap_or((0, 100000));
Ok(FighterAttackScript { Ok(FighterAttackScript {
hitboxes, hitboxes,
iasa_frame, iasa_frame,
wont_autocancel_window wont_autocancel_window,
}) })
} }
} }
@@ -126,7 +147,7 @@ pub fn compile_script(text: &str) -> Result<FighterAttackScript, String> {
"frame", "frame",
move |frame: i64| -> Result<(), Box<EvalAltResult>> { move |frame: i64| -> Result<(), Box<EvalAltResult>> {
let mut b = mc.borrow_mut(); let mut b = mc.borrow_mut();
b.frame(frame as u32) b.frame(rhai_u32(frame, "frame")?)
}, },
); );
} }
@@ -145,10 +166,10 @@ pub fn compile_script(text: &str) -> Result<FighterAttackScript, String> {
{ {
let mc = mc.clone(); let mc = mc.clone();
engine.register_fn( engine.register_fn(
"remove_all_hitboxes", "remove_hitbox",
move |id: i64| -> Result<(), Box<EvalAltResult>> { move |id: i64| -> Result<(), Box<EvalAltResult>> {
let mut b = mc.borrow_mut(); let mut b = mc.borrow_mut();
b.remove_hitbox(id as u32) b.remove_hitbox(rhai_u32(id, "hitbox id")?)
}, },
); );
} }
@@ -159,7 +180,10 @@ pub fn compile_script(text: &str) -> Result<FighterAttackScript, String> {
"set_wont_autocancel_window", "set_wont_autocancel_window",
move |start: i64, end: i64| -> Result<(), Box<EvalAltResult>> { move |start: i64, end: i64| -> Result<(), Box<EvalAltResult>> {
let mut b = mc.borrow_mut(); let mut b = mc.borrow_mut();
b.set_wont_autocancel_window(start as u32, end as u32) b.set_wont_autocancel_window(
rhai_u32(start, "autocancel start")?,
rhai_u32(end, "autocancel end")?,
)
}, },
); );
} }
@@ -168,9 +192,10 @@ pub fn compile_script(text: &str) -> Result<FighterAttackScript, String> {
let mc = mc.clone(); let mc = mc.clone();
engine.register_fn( engine.register_fn(
"set_iasa_frame", "set_iasa_frame",
move |frame: i64| { move |frame: i64| -> Result<(), Box<EvalAltResult>> {
let mut b = mc.borrow_mut(); let mut b = mc.borrow_mut();
b.set_iasa_frame(frame as u32); b.set_iasa_frame(rhai_u32(frame, "IASA frame")?);
Ok(())
}, },
); );
} }
@@ -180,19 +205,19 @@ pub fn compile_script(text: &str) -> Result<FighterAttackScript, String> {
engine.register_fn( engine.register_fn(
"hitbox", "hitbox",
move |id: i64, move |id: i64,
bone: &str, bone: &str,
damage: FighterDamage, damage: FighterDamage,
offset: FGVec3, offset: FGVec3,
radius: FGi32, radius: FGi32,
angle: AttackAngle, angle: AttackAngle,
knockback_type: KnockbackType, knockback_type: KnockbackType,
knockback: Knockback, knockback: Knockback,
knockback_growth: FGi32| knockback_growth: FGi32|
-> Result<(), Box<EvalAltResult>> { -> Result<(), Box<EvalAltResult>> {
let mut b = mc.borrow_mut(); let mut b = mc.borrow_mut();
// Rhai does not have first class u32 support, so we have to do this. // Rhai does not have first class u32 support, so we have to do this.
let id = id as u32; let id = rhai_u32(id, "hitbox id")?;
if b.hitboxes.contains_key(&id) { if b.hitboxes.contains_key(&id) {
return Err(format!("Hitbox with ID {} already existed!", id).into()); return Err(format!("Hitbox with ID {} already existed!", id).into());
@@ -222,7 +247,73 @@ pub fn compile_script(text: &str) -> Result<FighterAttackScript, String> {
engine.run(&text) engine.run(&text)
}; };
result
result.map(|_| Rc::into_inner(mc).unwrap().into_inner().into_attack_script()) .map(|_| {
Rc::into_inner(mc)
.unwrap()
.into_inner()
.into_attack_script()
})
.map_err(|err| err.to_string())? .map_err(|err| err.to_string())?
} }
#[cfg(test)]
mod tests {
use super::*;
const HITBOX: &str = "hitbox(0, \"hand_l\", damage(\"1\"), vec3(\"0\", \"0\", \"0\"), fg32(\"1\"), angle(fg32(\"0\")), knockback_normal(), knockback(\"1\"), fg32(\"1\"));";
#[test]
fn compiled_hitboxes_are_sorted_by_authored_id() {
let script = compile_script(
r#"
frame(1);
hitbox(20, "hand_l", damage("1"), vec3("0", "0", "0"), fg32("1"), angle(fg32("0")), knockback_normal(), knockback("1"), fg32("1"));
frame(2);
hitbox(3, "hand_l", damage("2"), vec3("0", "0", "0"), fg32("1"), angle(fg32("0")), knockback_normal(), knockback("1"), fg32("1"));
frame(3);
hitbox(10, "hand_l", damage("3"), vec3("0", "0", "0"), fg32("1"), angle(fg32("0")), knockback_normal(), knockback("1"), fg32("1"));
frame(4);
"#,
)
.unwrap();
assert_eq!(
script
.hitboxes
.iter()
.map(|hitbox| hitbox.id)
.collect::<Vec<_>>(),
vec![3, 10, 20]
);
assert_eq!(
script
.hitboxes
.iter()
.map(|hitbox| hitbox.start_frame)
.collect::<Vec<_>>(),
vec![2, 3, 1]
);
}
#[test]
fn negative_and_overflowing_frames_are_rejected() {
for source in ["frame(-1);", "frame(4294967296);"] {
let error = match compile_script(source) {
Ok(_) => panic!("invalid frame was accepted"),
Err(error) => error,
};
assert!(error.contains("frame"));
}
}
#[test]
fn remove_hitbox_ends_only_the_named_hitbox() {
let script =
compile_script(&format!("frame(1); {HITBOX} frame(2); remove_hitbox(0);")).unwrap();
assert_eq!(script.hitboxes.len(), 1);
assert_eq!(script.hitboxes[0].start_frame, 1);
assert_eq!(script.hitboxes[0].end_frame, 2);
}
}
+7 -1
View File
@@ -1,6 +1,5 @@
//! Stage collision geometry. //! Stage collision geometry.
use bevy::prelude::*; use bevy::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -59,6 +58,13 @@ impl StagePoly {
.iter() .iter()
.enumerate() .enumerate()
.filter_map(|(segment_idx, segment)| { .filter_map(|(segment_idx, segment)| {
if segment
.normal
.dot(ray_segment.point2() - ray_segment.point1())
>= crate::math::int::FGWide::ZERO
{
return None;
}
segment segment
.segment .segment
.segment_intersection(&ray_segment) .segment_intersection(&ray_segment)
+13 -4
View File
@@ -1,6 +1,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use bevy_asset_loader::asset_collection::AssetCollection; use bevy_asset_loader::asset_collection::AssetCollection;
use ron_asset_manager::prelude::RonAsset;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator; use strum::IntoEnumIterator;
use strum_macros::EnumIter; use strum_macros::EnumIter;
@@ -13,6 +14,7 @@ use crate::{
StagePoly, StagePoly,
line::{StageCollision, StagePolyLineSegmentType, StagePolyType}, line::{StageCollision, StagePolyLineSegmentType, StagePolyType},
}, },
texture_reference::TextureReference,
}; };
use bevy::prelude::*; use bevy::prelude::*;
@@ -60,8 +62,11 @@ pub struct StageCameraProfile {
pub max_downward_pan_degrees: f32, pub max_downward_pan_degrees: f32,
} }
#[derive(Reflect, Serialize, Deserialize, Copy, Clone, Eq, PartialEq, Hash, Debug, EnumIter)] #[derive(
Reflect, Serialize, Deserialize, Copy, Clone, Eq, PartialEq, Hash, Debug, EnumIter, Default,
)]
pub enum StageId { pub enum StageId {
#[default]
TestStage, TestStage,
} }
@@ -72,10 +77,14 @@ pub struct StagePolyDefinition {
lines: Vec<(FGVec2, StagePolyLineSegmentType)>, lines: Vec<(FGVec2, StagePolyLineSegmentType)>,
} }
#[derive(Serialize, Deserialize, Clone, Asset, Reflect)] #[derive(Deserialize, Clone, Asset, Reflect, RonAsset)]
pub struct StageManifest { pub struct StageManifest {
pub id: StageId, pub id: StageId,
pub model_path: String, pub model_path: String,
#[asset]
#[dependency]
#[reflect(ignore)]
pub icon: TextureReference,
pub camera: StageCameraProfile, pub camera: StageCameraProfile,
pub polygons: Vec<StagePolyDefinition>, pub polygons: Vec<StagePolyDefinition>,
} }
@@ -112,7 +121,7 @@ impl AssetCollection for StageManifestAssets {
} }
} }
#[derive(Resource)] #[derive(Resource, Deref)]
pub struct StageManifestRegistry(HashMap<StageId, Handle<StageManifest>>); pub struct StageManifestRegistry(HashMap<StageId, Handle<StageManifest>>);
impl StageManifestRegistry { impl StageManifestRegistry {
@@ -173,7 +182,7 @@ pub fn prepare_stage_manifests(
} }
commands.insert_resource(StageManifestRegistry(registry)); commands.insert_resource(StageManifestRegistry(registry));
next_state.set(AppState::MainMenu); next_state.set(AppState::PreMainMenu);
} }
impl StageManifest { impl StageManifest {
+2 -2
View File
@@ -5,12 +5,12 @@ use bevy::prelude::*;
pub mod debug; pub mod debug;
pub mod line; pub mod line;
pub mod scene;
pub mod manifest; pub mod manifest;
pub mod scene;
pub use line::{StagePlaneIntersectResult, StagePoly}; pub use line::{StagePlaneIntersectResult, StagePoly};
use crate::{stage::{line::StageCollision, manifest::StageCameraProfile}}; use crate::stage::{line::StageCollision, manifest::StageCameraProfile};
/// Owns the stage geometry: which scene gets spawned and how it is drawn. /// Owns the stage geometry: which scene gets spawned and how it is drawn.
#[derive(Default)] #[derive(Default)]
+1 -3
View File
@@ -4,9 +4,7 @@ use std::f32::consts::PI;
use bevy::prelude::*; use bevy::prelude::*;
use crate::{ use crate::{camera::MatchCamera, stage::line::StageCollision};
camera::MatchCamera, stage::line::StageCollision,
};
pub fn spawn_stage_support( pub fn spawn_stage_support(
commands: &mut Commands, commands: &mut Commands,