## Summary - resolve each ledge action to the walkable segment on the stage-interior side - preserve repeating root-motion displacement across every animation cycle - add regression coverage for left/right ledge segments and multiple root-motion wraps - Implement ledge intangibility Reviewed-on: #91 Co-authored-by: Álex Román Núñez <eirexe@eirteam.moe>
539 lines
18 KiB
Rust
539 lines
18 KiB
Rust
use std::collections::{HashMap, HashSet};
|
|
|
|
use bevy_asset_loader::asset_collection::AssetCollection;
|
|
use ron_asset_manager::prelude::RonAsset;
|
|
use serde::{Deserialize, Serialize};
|
|
use strum::IntoEnumIterator;
|
|
use strum_macros::EnumIter;
|
|
|
|
use crate::{
|
|
AppState, game_settings::GameSettings, math::{vec::FGVec2}, stage::{
|
|
StagePoly,
|
|
line::{
|
|
StageCollision, StageLedge, StageLedgeSide, StagePolyLineSegment,
|
|
StagePolyLineSegmentType, StagePolyType, StageVertexID,
|
|
},
|
|
}, texture_reference::TextureReference,
|
|
};
|
|
use bevy::prelude::*;
|
|
|
|
/// Per-stage presentation tuning for the standard match camera.
|
|
///
|
|
/// Spatial values use gameplay world units on the XY plane. Angle values use
|
|
/// degrees
|
|
#[derive(Component, Serialize, Deserialize, Clone, Reflect)]
|
|
#[reflect(opaque)]
|
|
pub struct StageCameraProfile {
|
|
/// World-space left edge of the camera range.
|
|
pub left: f32,
|
|
/// World-space right edge of the camera range.
|
|
pub right: f32,
|
|
/// World-space bottom edge of the camera range.
|
|
pub bottom: f32,
|
|
/// World-space top edge of the camera range.
|
|
pub top: f32,
|
|
/// Neutral focus point used for empty framing and dynamic pan calculations.
|
|
pub origin: Vec2,
|
|
/// Vertical perspective field of view for the standard match camera.
|
|
pub vertical_fov_degrees: f32,
|
|
/// Nearest allowed positive Z distance from the gameplay plane.
|
|
pub min_depth: f32,
|
|
/// Farthest allowed positive Z distance from the gameplay plane.
|
|
pub max_depth: f32,
|
|
/// Multiplies fighter camera extents after the player-count scale.
|
|
pub subject_scale: f32,
|
|
/// Multiplies the facing-forward horizontal fighter camera extent.
|
|
pub fighter_forward_extent_scale: f32,
|
|
/// Multiplies the standard camera's interest and eye follow speeds.
|
|
pub tracking_smoothness: f32,
|
|
/// Constant vertical pitch added after dynamic vertical pan is clamped.
|
|
pub vertical_pan_degrees: f32,
|
|
/// Dynamic horizontal pan in degrees for every world unit from 0,0
|
|
pub horizontal_pan_degrees_per_unit: f32,
|
|
/// Dynamic vertical pan in degrees for every world unit from the vertical reference line
|
|
pub vertical_pan_degrees_per_unit: f32,
|
|
/// Symmetric limit on dynamic horizontal pan, before any other adjustment.
|
|
pub max_horizontal_pan_degrees: f32,
|
|
/// Maximum upward dynamic vertical pan, before constant pitch is added.
|
|
pub max_upward_pan_degrees: f32,
|
|
/// Magnitude of the maximum downward dynamic vertical pan, before constant
|
|
/// pitch is added.
|
|
pub max_downward_pan_degrees: f32,
|
|
}
|
|
|
|
#[derive(
|
|
Reflect, Serialize, Deserialize, Copy, Clone, Eq, PartialEq, Hash, Debug, EnumIter, Default,
|
|
)]
|
|
pub enum StageId {
|
|
#[default]
|
|
TestStage,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize, Clone, Reflect)]
|
|
#[reflect(opaque)]
|
|
pub struct StagePolyDefinition {
|
|
poly_type: StagePolyType,
|
|
lines: Vec<(FGVec2, StagePolyLineSegmentType)>,
|
|
#[serde(default)]
|
|
ledges: Vec<StageLedgeDefinition>,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize, Clone, Copy, Reflect)]
|
|
pub struct StageLedgeDefinition {
|
|
/// Index into the polygon's `lines`, identifying the corner position.
|
|
vertex: usize,
|
|
/// Side of the corner on which a grabbing fighter will hang.
|
|
hang_side: StageLedgeSide,
|
|
}
|
|
|
|
#[derive(Deserialize, Clone, Asset, Reflect, RonAsset)]
|
|
pub struct StageManifest {
|
|
pub id: StageId,
|
|
pub model_path: String,
|
|
#[asset]
|
|
#[dependency]
|
|
#[reflect(ignore)]
|
|
pub icon: TextureReference,
|
|
pub camera: StageCameraProfile,
|
|
pub polygons: Vec<StagePolyDefinition>,
|
|
|
|
#[reflect(ignore)]
|
|
pub blast_zone_top_left: FGVec2,
|
|
#[reflect(ignore)]
|
|
pub blast_zone_bottom_right: FGVec2,
|
|
|
|
#[reflect(ignore)]
|
|
pub spawn_points: Vec<FGVec2>,
|
|
pub neutral_spawn_point_sets: Vec<Vec<usize>>,
|
|
#[reflect(ignore)]
|
|
pub respawn_points: Vec<FGVec2>,
|
|
}
|
|
|
|
#[derive(Resource)]
|
|
pub struct StageManifestAssets(pub Vec<Handle<StageManifest>>);
|
|
|
|
impl StageManifestAssets {
|
|
fn requested(world: &World) -> Self {
|
|
let settings = world.resource::<GameSettings>();
|
|
let asset_server = world.resource::<AssetServer>();
|
|
|
|
Self(
|
|
settings
|
|
.stage_manifest_paths
|
|
.iter()
|
|
.map(|path| asset_server.load(path.clone()))
|
|
.collect(),
|
|
)
|
|
}
|
|
}
|
|
|
|
impl AssetCollection for StageManifestAssets {
|
|
fn create(world: &mut World) -> Self {
|
|
Self::requested(world)
|
|
}
|
|
|
|
fn load(world: &mut World) -> Vec<UntypedHandle> {
|
|
Self::requested(world)
|
|
.0
|
|
.into_iter()
|
|
.map(Handle::untyped)
|
|
.collect()
|
|
}
|
|
}
|
|
|
|
#[derive(Resource, Deref)]
|
|
pub struct StageManifestRegistry(HashMap<StageId, Handle<StageManifest>>);
|
|
|
|
impl StageManifestRegistry {
|
|
pub fn get(&self, stage: StageId) -> Option<Handle<StageManifest>> {
|
|
self.0.get(&stage).cloned()
|
|
}
|
|
}
|
|
|
|
fn fail(next_state: &mut NextState<AppState>, message: &str) {
|
|
error!("Stage manifest preparation failed: {message}");
|
|
next_state.set(AppState::CommonAssetLoadFailed);
|
|
}
|
|
|
|
pub fn prepare_stage_manifests(
|
|
mut commands: Commands,
|
|
handles: Res<StageManifestAssets>,
|
|
manifests: Res<Assets<StageManifest>>,
|
|
mut next_state: ResMut<NextState<AppState>>,
|
|
) {
|
|
let mut registry = HashMap::with_capacity(handles.0.len());
|
|
|
|
for handle in &handles.0 {
|
|
let Some(manifest) = manifests.get(handle) else {
|
|
fail(&mut next_state, "a loaded fighter manifest is unavailable");
|
|
return;
|
|
};
|
|
if manifest.model_path.is_empty() {
|
|
fail(
|
|
&mut next_state,
|
|
&format!("{:?} has an empty model path", manifest.id),
|
|
);
|
|
return;
|
|
}
|
|
if !manifest.camera.is_valid() {
|
|
fail(
|
|
&mut next_state,
|
|
&format!("{:?} has an invalid camera profile", manifest.id),
|
|
);
|
|
return;
|
|
}
|
|
if let Err(error) = manifest.validate_spawn_points() {
|
|
fail(
|
|
&mut next_state,
|
|
&format!("{:?} has invalid spawn points: {error}", manifest.id),
|
|
);
|
|
return;
|
|
}
|
|
if let Err(error) = manifest.validate_ledges() {
|
|
fail(
|
|
&mut next_state,
|
|
&format!("{:?} has invalid ledges: {error}", manifest.id),
|
|
);
|
|
return;
|
|
}
|
|
if registry.insert(manifest.id, handle.clone()).is_some() {
|
|
fail(
|
|
&mut next_state,
|
|
&format!("duplicate manifest for stage {:?}", manifest.id),
|
|
);
|
|
return;
|
|
}
|
|
}
|
|
|
|
for stage in StageId::iter() {
|
|
if !registry.contains_key(&stage) {
|
|
fail(
|
|
&mut next_state,
|
|
&format!("no manifest configured for stage {stage:?}"),
|
|
);
|
|
return;
|
|
}
|
|
}
|
|
|
|
commands.insert_resource(StageManifestRegistry(registry));
|
|
next_state.set(AppState::PreMainMenu);
|
|
}
|
|
|
|
impl StageManifest {
|
|
pub fn neutral_spawn_positions(&self, player_count: usize) -> Result<Vec<FGVec2>, String> {
|
|
if player_count == 0 {
|
|
return Err("a match must contain at least one player".to_owned());
|
|
}
|
|
|
|
let layout = self
|
|
.neutral_spawn_point_sets
|
|
.get(player_count - 1)
|
|
.ok_or_else(|| format!("no spawn layout for {player_count} players"))?;
|
|
|
|
if layout.len() != player_count {
|
|
return Err(format!(
|
|
"the {player_count}-player layout contains {} positions",
|
|
layout.len()
|
|
));
|
|
}
|
|
|
|
layout
|
|
.iter()
|
|
.map(|&index| {
|
|
self.spawn_points.get(index).copied().ok_or_else(|| {
|
|
format!("the {player_count}-player layout references spawn point {index}")
|
|
})
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn validate_spawn_points(&self) -> Result<(), String> {
|
|
if self.spawn_points.is_empty() {
|
|
return Err("no spawn points are configured".to_owned());
|
|
}
|
|
|
|
if self.respawn_points.is_empty() {
|
|
return Err("no respawn points are configured".to_owned());
|
|
}
|
|
|
|
if self.neutral_spawn_point_sets.is_empty() {
|
|
return Err("no neutral spawn layouts are configured".to_owned());
|
|
}
|
|
|
|
for (layout_index, layout) in self.neutral_spawn_point_sets.iter().enumerate() {
|
|
let player_count = layout_index + 1;
|
|
if layout.len() != player_count {
|
|
return Err(format!(
|
|
"the {player_count}-player layout contains {} positions",
|
|
layout.len()
|
|
));
|
|
}
|
|
|
|
let mut unique_indices = HashSet::with_capacity(layout.len());
|
|
for &spawn_point_index in layout {
|
|
if spawn_point_index >= self.spawn_points.len() {
|
|
return Err(format!(
|
|
"the {player_count}-player layout references spawn point {spawn_point_index}"
|
|
));
|
|
}
|
|
if !unique_indices.insert(spawn_point_index) {
|
|
return Err(format!(
|
|
"the {player_count}-player layout uses spawn point {spawn_point_index} more than once"
|
|
));
|
|
}
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn validate_ledges(&self) -> Result<(), String> {
|
|
for (polygon_index, definition) in self.polygons.iter().enumerate() {
|
|
definition.validate_ledges(polygon_index)?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub fn to_collision(&self) -> StageCollision {
|
|
let stage_polys: Vec<StagePoly> = self
|
|
.polygons
|
|
.iter()
|
|
.map(|def| StagePoly::build(def.poly_type, &def.lines))
|
|
.collect();
|
|
|
|
let ledges = self
|
|
.polygons
|
|
.iter()
|
|
.enumerate()
|
|
.flat_map(|(polygon, definition)| definition.resolved_ledges(polygon))
|
|
.collect();
|
|
|
|
StageCollision {
|
|
stage_polys,
|
|
ledges,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl StagePolyDefinition {
|
|
fn validate_ledges(&self, polygon_index: usize) -> Result<(), String> {
|
|
let polygon = StagePoly::build(self.poly_type, &self.lines);
|
|
let mut vertices = HashSet::with_capacity(self.ledges.len());
|
|
|
|
for ledge in &self.ledges {
|
|
if ledge.vertex >= self.lines.len() {
|
|
return Err(format!(
|
|
"polygon {polygon_index} references missing vertex {}",
|
|
ledge.vertex
|
|
));
|
|
}
|
|
if !vertices.insert(ledge.vertex) {
|
|
return Err(format!(
|
|
"polygon {polygon_index} defines vertex {} as a ledge more than once",
|
|
ledge.vertex
|
|
));
|
|
}
|
|
|
|
let outgoing = polygon.get_segment(ledge.vertex);
|
|
let incoming_index = if ledge.vertex > 0 {
|
|
Some(ledge.vertex - 1)
|
|
} else if matches!(self.poly_type, StagePolyType::Closed) {
|
|
polygon.segments.len().checked_sub(1)
|
|
} else {
|
|
None
|
|
};
|
|
let incoming = incoming_index.and_then(|index| polygon.get_segment(index));
|
|
let is_walkable_floor = |segment: Option<&StagePolyLineSegment>| {
|
|
segment.is_some_and(|segment| {
|
|
segment.segment_type == StagePolyLineSegmentType::Floor
|
|
&& segment.normal.y > crate::math::int::FGi32::ZERO
|
|
})
|
|
};
|
|
let (interior, exterior) = match ledge.hang_side {
|
|
StageLedgeSide::Left => (outgoing, incoming),
|
|
StageLedgeSide::Right => (incoming, outgoing),
|
|
};
|
|
if !is_walkable_floor(interior) {
|
|
return Err(format!(
|
|
"polygon {polygon_index} vertex {} has no upward-facing floor opposite its {:?} hang side",
|
|
ledge.vertex, ledge.hang_side
|
|
));
|
|
}
|
|
if is_walkable_floor(exterior) {
|
|
return Err(format!(
|
|
"polygon {polygon_index} vertex {} is between two walkable floors rather than at an exposed corner",
|
|
ledge.vertex
|
|
));
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn resolved_ledges(&self, polygon: usize) -> impl Iterator<Item = StageLedge> + '_ {
|
|
self.ledges.iter().map(move |ledge| StageLedge {
|
|
id: StageVertexID {
|
|
polygon,
|
|
vertex: ledge.vertex,
|
|
},
|
|
position: self.lines[ledge.vertex].0,
|
|
hang_side: ledge.hang_side,
|
|
})
|
|
}
|
|
}
|
|
|
|
impl StageCameraProfile {
|
|
fn is_valid(&self) -> bool {
|
|
self.left.is_finite()
|
|
&& self.right.is_finite()
|
|
&& self.bottom.is_finite()
|
|
&& self.top.is_finite()
|
|
&& self.origin.is_finite()
|
|
&& self.vertical_fov_degrees.is_finite()
|
|
&& self.min_depth.is_finite()
|
|
&& self.max_depth.is_finite()
|
|
&& self.subject_scale.is_finite()
|
|
&& self.fighter_forward_extent_scale.is_finite()
|
|
&& self.tracking_smoothness.is_finite()
|
|
&& self.vertical_pan_degrees.is_finite()
|
|
&& self.horizontal_pan_degrees_per_unit.is_finite()
|
|
&& self.vertical_pan_degrees_per_unit.is_finite()
|
|
&& self.max_horizontal_pan_degrees.is_finite()
|
|
&& self.max_upward_pan_degrees.is_finite()
|
|
&& self.max_downward_pan_degrees.is_finite()
|
|
&& self.left < self.right
|
|
&& self.bottom < self.top
|
|
&& (self.left..=self.right).contains(&self.origin.x)
|
|
&& (self.bottom..=self.top).contains(&self.origin.y)
|
|
&& (0.0..180.0).contains(&self.vertical_fov_degrees)
|
|
&& self.min_depth > 0.0
|
|
&& self.min_depth <= self.max_depth
|
|
&& self.subject_scale > 0.0
|
|
&& self.fighter_forward_extent_scale > 0.0
|
|
&& self.tracking_smoothness >= 0.0
|
|
&& self.max_horizontal_pan_degrees >= 0.0
|
|
&& self.max_upward_pan_degrees >= 0.0
|
|
&& self.max_downward_pan_degrees >= 0.0
|
|
&& self.vertical_fov_degrees * 0.5 + self.max_horizontal_pan_degrees < 90.0
|
|
&& self.vertical_fov_degrees * 0.5
|
|
+ self.vertical_pan_degrees.abs()
|
|
+ self
|
|
.max_upward_pan_degrees
|
|
.max(self.max_downward_pan_degrees)
|
|
< 90.0
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::stage::line::StageLineID;
|
|
|
|
fn platform(ledges: Vec<StageLedgeDefinition>) -> StagePolyDefinition {
|
|
StagePolyDefinition {
|
|
poly_type: StagePolyType::Platform,
|
|
lines: vec![
|
|
(FGVec2::lit("-5", "0"), StagePolyLineSegmentType::Floor),
|
|
(FGVec2::lit("5", "0"), StagePolyLineSegmentType::Floor),
|
|
],
|
|
ledges,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn platform_endpoints_can_be_defined_as_ledges() {
|
|
let definition = platform(vec![
|
|
StageLedgeDefinition {
|
|
vertex: 0,
|
|
hang_side: StageLedgeSide::Left,
|
|
},
|
|
StageLedgeDefinition {
|
|
vertex: 1,
|
|
hang_side: StageLedgeSide::Right,
|
|
},
|
|
]);
|
|
|
|
assert_eq!(definition.validate_ledges(3), Ok(()));
|
|
let ledges = definition.resolved_ledges(3).collect::<Vec<_>>();
|
|
assert_eq!(ledges[0].id, StageVertexID { polygon: 3, vertex: 0 });
|
|
assert_eq!(ledges[0].position, FGVec2::lit("-5", "0"));
|
|
assert_eq!(ledges[1].id, StageVertexID { polygon: 3, vertex: 1 });
|
|
assert_eq!(ledges[1].position, FGVec2::lit("5", "0"));
|
|
}
|
|
|
|
#[test]
|
|
fn ledge_ground_segments_point_toward_the_stage_interior() {
|
|
let definition = platform(vec![
|
|
StageLedgeDefinition {
|
|
vertex: 0,
|
|
hang_side: StageLedgeSide::Left,
|
|
},
|
|
StageLedgeDefinition {
|
|
vertex: 1,
|
|
hang_side: StageLedgeSide::Right,
|
|
},
|
|
]);
|
|
let collision = StageCollision {
|
|
stage_polys: vec![StagePoly::build(definition.poly_type, &definition.lines)],
|
|
ledges: definition.resolved_ledges(0).collect(),
|
|
};
|
|
|
|
for vertex in [0, 1] {
|
|
let (line_id, segment) = collision
|
|
.find_ledge_ground_segment(StageVertexID { polygon: 0, vertex })
|
|
.unwrap();
|
|
assert_eq!(line_id, StageLineID { polygon: 0, segment: 0 });
|
|
assert!(matches!(
|
|
segment.segment_type,
|
|
StagePolyLineSegmentType::Floor
|
|
));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_and_duplicate_ledge_vertices_are_rejected() {
|
|
let missing = platform(vec![StageLedgeDefinition {
|
|
vertex: 2,
|
|
hang_side: StageLedgeSide::Right,
|
|
}]);
|
|
assert!(missing.validate_ledges(0).is_err());
|
|
|
|
let duplicate = platform(vec![
|
|
StageLedgeDefinition {
|
|
vertex: 0,
|
|
hang_side: StageLedgeSide::Left,
|
|
},
|
|
StageLedgeDefinition {
|
|
vertex: 0,
|
|
hang_side: StageLedgeSide::Right,
|
|
},
|
|
]);
|
|
assert!(duplicate.validate_ledges(0).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn ledge_must_border_an_upward_facing_floor() {
|
|
let definition = StagePolyDefinition {
|
|
poly_type: StagePolyType::Platform,
|
|
lines: vec![
|
|
(FGVec2::lit("0", "0"), StagePolyLineSegmentType::Wall),
|
|
(FGVec2::lit("0", "5"), StagePolyLineSegmentType::Wall),
|
|
],
|
|
ledges: vec![StageLedgeDefinition {
|
|
vertex: 0,
|
|
hang_side: StageLedgeSide::Left,
|
|
}],
|
|
};
|
|
|
|
assert!(definition.validate_ledges(0).is_err());
|
|
|
|
let wrong_side = platform(vec![StageLedgeDefinition {
|
|
vertex: 0,
|
|
hang_side: StageLedgeSide::Right,
|
|
}]);
|
|
assert!(wrong_side.validate_ledges(0).is_err());
|
|
}
|
|
|
|
}
|