Compare commits

..

No commits in common. "8db8b72824ee1e9f37d0a891b6cc1e01c268fd49" and "d268ed2b0cf82d771c00f524d5f852279e3b73ae" have entirely different histories.

10 changed files with 560 additions and 401 deletions

View File

@ -14,7 +14,7 @@ speech_dispatcher_0_10 = ["bevy_tts/speech_dispatcher_0_10"]
speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"] speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"]
[dependencies.bevy] [dependencies.bevy]
version = "0.15" version = "0.14"
default-features = false default-features = false
features = [ features = [
"android_shared_stdcxx", "android_shared_stdcxx",
@ -48,12 +48,12 @@ features = [
] ]
[dependencies] [dependencies]
avian2d = "0.2" bevy_rapier2d = "0.27"
bevy_synthizer = "0.9" bevy_synthizer = "0.8"
bevy_tts = { version = "0.10", default-features = false, features = ["tolk"] } bevy_tts = { version = "0.9", default-features = false, features = ["tolk"] }
coord_2d = "0.3" coord_2d = "0.3"
here_be_dragons = { version = "0.3", features = ["serde"] } here_be_dragons = { version = "0.3", features = ["serde"] }
leafwing-input-manager = "0.16" leafwing-input-manager = "0.15"
maze_generator = "2" maze_generator = "2"
once_cell = "1" once_cell = "1"
pathfinding = "4" pathfinding = "4"

View File

@ -5,32 +5,20 @@ use std::{
sync::RwLock, sync::RwLock,
}; };
use avian2d::{
parry::{
math::Isometry,
query::{closest_points, distance, ClosestPoints},
},
prelude::*,
};
use bevy::{ use bevy::{
app::PluginGroupBuilder, app::PluginGroupBuilder,
math::{CompassOctant, CompassQuadrant, FloatOrd}, math::{CompassOctant, CompassQuadrant, FloatOrd},
prelude::*, prelude::*,
}; };
use bevy_rapier2d::{
parry::query::{closest_points, distance, ClosestPoints},
prelude::*,
rapier::{math::Isometry, prelude::Aabb},
};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use rand::prelude::*; use rand::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)]
#[require(Transform, Collider(||Collider::rectangle(1., 1.)), RigidBody(|| RigidBody::Static))]
pub struct Obstacle;
#[derive(Default, Component, Clone, Debug, Reflect)]
#[reflect(Component)]
#[require(Transform, Collider, Sensor)]
pub struct Zone;
fn relative_desc(rot: &Rot2) -> String { fn relative_desc(rot: &Rot2) -> String {
let mode = RELATIVE_DIRECTION_MODE.read().unwrap(); let mode = RELATIVE_DIRECTION_MODE.read().unwrap();
match rot.as_radians() { match rot.as_radians() {
@ -343,16 +331,6 @@ impl PointLike for Vec2 {
} }
} }
impl PointLike for IVec2 {
fn x(&self) -> f32 {
self.x as f32
}
fn y(&self) -> f32 {
self.y as f32
}
}
impl PointLike for (i32, i32) { impl PointLike for (i32, i32) {
fn x(&self) -> f32 { fn x(&self) -> f32 {
self.0 as f32 self.0 as f32
@ -393,6 +371,27 @@ impl PointLike for here_be_dragons::geometry::Point {
} }
} }
#[macro_export]
macro_rules! impl_pointlike_for_tuple_component {
($source:ty) => {
impl PointLike for $source {
fn x(&self) -> f32 {
self.0 .0 as f32
}
fn y(&self) -> f32 {
self.0 .1 as f32
}
}
};
}
impl From<&dyn PointLike> for (i32, i32) {
fn from(val: &dyn PointLike) -> Self {
val.i32()
}
}
pub trait TransformExt { pub trait TransformExt {
fn yaw(&self) -> Rot2; fn yaw(&self) -> Rot2;
} }
@ -443,14 +442,7 @@ impl GlobalTransformExt for GlobalTransform {
(other.translation() / *scale).xy().into(), (other.translation() / *scale).xy().into(),
other.yaw().as_radians(), other.yaw().as_radians(),
); );
closest_points( closest_points(&pos1, &*collider.raw, &pos2, &*other_collider.raw, f32::MAX).unwrap()
&pos1,
collider.shape().as_ref(),
&pos2,
other_collider.shape().as_ref(),
f32::MAX,
)
.unwrap()
} }
fn collider_direction_and_distance( fn collider_direction_and_distance(
@ -469,13 +461,7 @@ impl GlobalTransformExt for GlobalTransform {
other.yaw().as_radians(), other.yaw().as_radians(),
); );
let closest = self.closest_points(collider, other, other_collider); let closest = self.closest_points(collider, other, other_collider);
let distance = distance( let distance = distance(&pos1, &*collider.raw, &pos2, &*other_collider.raw).unwrap() as u32;
&pos1,
collider.shape().as_ref(),
&pos2,
other_collider.shape().as_ref(),
)
.unwrap() as u32;
let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" }; let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
if distance > 0 { if distance > 0 {
if let ClosestPoints::WithinMargin(p1, p2) = closest { if let ClosestPoints::WithinMargin(p1, p2) = closest {
@ -495,6 +481,9 @@ impl GlobalTransformExt for GlobalTransform {
} }
} }
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, PartialEq)]
pub struct Area(pub Aabb);
#[derive(Component, Clone, Copy, Debug, Default, Reflect)] #[derive(Component, Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct Player; pub struct Player;
@ -600,8 +589,9 @@ impl Plugin for CorePlugin {
}; };
app.insert_resource(config) app.insert_resource(config)
.register_type::<CardinalDirection>() .register_type::<CardinalDirection>()
.add_plugins(PhysicsPlugins::default().with_length_unit(config.pixels_per_unit as f32)) .add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(
.insert_resource(Gravity(Vec2::ZERO)) config.pixels_per_unit as f32,
))
.add_systems(Startup, setup) .add_systems(Startup, setup)
.add_systems(Update, sync_config); .add_systems(Update, sync_config);
} }

View File

@ -5,8 +5,8 @@ use std::{
marker::PhantomData, marker::PhantomData,
}; };
use avian2d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts; use bevy_tts::Tts;
use leafwing_input_manager::prelude::*; use leafwing_input_manager::prelude::*;
@ -42,17 +42,9 @@ pub struct ExplorationFocused;
#[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)] #[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct Exploring(pub Vec2); pub struct Exploring(pub (f32, f32));
impl PointLike for Exploring { impl_pointlike_for_tuple_component!(Exploring);
fn x(&self) -> f32 {
self.0.x
}
fn y(&self) -> f32 {
self.0.y
}
}
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)] #[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct FocusedExplorationType<T>(pub Option<T>) pub struct FocusedExplorationType<T>(pub Option<T>)
@ -130,45 +122,34 @@ fn exploration_type_focus<ExplorationType>(
mut tts: ResMut<Tts>, mut tts: ResMut<Tts>,
explorers: Query<( explorers: Query<(
Entity, Entity,
&GlobalTransform,
&ActionState<ExplorationAction>, &ActionState<ExplorationAction>,
&VisibleEntities, &VisibleEntities,
&FocusedExplorationType<ExplorationType>, &FocusedExplorationType<ExplorationType>,
Option<&Exploring>, Option<&Exploring>,
)>, )>,
features: Query<(Entity, &GlobalTransform, &ExplorationType)>, features: Query<(Entity, &Transform, &ExplorationType)>,
) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where where
ExplorationType: Component + Default + PartialEq, ExplorationType: Component + Default + PartialEq,
{ {
for (entity, transform, actions, visible_entities, focused_type, exploring) in &explorers { for (entity, actions, visible_entities, focused_type, exploring) in &explorers {
let mut features = features let mut features = features
.iter() .iter()
.filter(|v| visible_entities.contains(&v.0)) .filter(|v| visible_entities.contains(&v.0))
.map(|v| (v.1.translation().truncate(), v.2)) .map(|v| (v.1.trunc(), v.2))
.collect::<Vec<(Vec2, &ExplorationType)>>(); .collect::<Vec<((f32, f32), &ExplorationType)>>();
if features.is_empty() { if features.is_empty() {
tts.speak("Nothing visible.", true)?; tts.speak("Nothing visible.", true)?;
return Ok(()); return Ok(());
} }
features.sort_by(|(c1, _), (c2, _)| { features.sort_by(|(c1, _), (c2, _)| c1.partial_cmp(c2).unwrap());
transform
.translation()
.truncate()
.distance(*c1)
.partial_cmp(&transform.translation().truncate().distance(*c2))
.unwrap()
});
if let Some(focused) = &focused_type.0 { if let Some(focused) = &focused_type.0 {
features.retain(|(_, t)| **t == *focused); features.retain(|(_, t)| **t == *focused);
} }
let mut target = None; let mut target: Option<&((f32, f32), &ExplorationType)> = None;
if actions.just_pressed(&ExplorationAction::FocusNext) { if actions.just_pressed(&ExplorationAction::FocusNext) {
if let Some(exploring) = exploring { if let Some(exploring) = exploring {
target = features.iter().find(|(c, _)| { target = features.iter().find(|(c, _)| *c > **exploring);
transform.translation().truncate().distance(*c)
> transform.translation().truncate().distance(**exploring)
});
if target.is_none() { if target.is_none() {
target = features.first(); target = features.first();
} }
@ -178,10 +159,7 @@ where
} else if actions.just_pressed(&ExplorationAction::FocusPrev) { } else if actions.just_pressed(&ExplorationAction::FocusPrev) {
if let Some(exploring) = exploring { if let Some(exploring) = exploring {
features.reverse(); features.reverse();
target = features.iter().find(|(c, _)| { target = features.iter().find(|(c, _)| *c < **exploring);
transform.translation().truncate().distance(*c)
< transform.translation().truncate().distance(**exploring)
});
if target.is_none() { if target.is_none() {
target = features.first(); target = features.first();
} }
@ -192,7 +170,7 @@ where
if let Some((coordinates, _)) = target { if let Some((coordinates, _)) = target {
commands commands
.entity(entity) .entity(entity)
.insert(Exploring(*coordinates)); .insert(Exploring(coordinates.trunc()));
} }
} }
Ok(()) Ok(())
@ -234,7 +212,7 @@ fn exploration_focus<MapData>(
( (
Entity, Entity,
&ActionState<ExplorationAction>, &ActionState<ExplorationAction>,
&GlobalTransform, &Transform,
Option<&Exploring>, Option<&Exploring>,
), ),
With<Player>, With<Player>,
@ -243,20 +221,22 @@ fn exploration_focus<MapData>(
MapData: 'static + Clone + Default + Send + Sync, MapData: 'static + Clone + Default + Send + Sync,
{ {
for (entity, actions, transform, exploring) in &explorers { for (entity, actions, transform, exploring) in &explorers {
let coordinates = transform.translation;
let mut exploring = if let Some(exploring) = exploring { let mut exploring = if let Some(exploring) = exploring {
**exploring **exploring
} else { } else {
transform.translation().truncate() let floor = coordinates.floor();
(floor.x, floor.y)
}; };
let orig = exploring; let orig = exploring;
if actions.just_pressed(&ExplorationAction::Forward) { if actions.just_pressed(&ExplorationAction::Forward) {
exploring.y += 1.; exploring.1 += 1.;
} else if actions.just_pressed(&ExplorationAction::Backward) { } else if actions.just_pressed(&ExplorationAction::Backward) {
exploring.y -= 1.; exploring.1 -= 1.;
} else if actions.just_pressed(&ExplorationAction::Left) { } else if actions.just_pressed(&ExplorationAction::Left) {
exploring.x -= 1.; exploring.0 -= 1.;
} else if actions.just_pressed(&ExplorationAction::Right) { } else if actions.just_pressed(&ExplorationAction::Right) {
exploring.x += 1.; exploring.0 += 1.;
} }
let dimensions = if let Ok(map) = map.get_single() { let dimensions = if let Ok(map) = map.get_single() {
Some((map.width as f32, map.height as f32)) Some((map.width as f32, map.height as f32))
@ -264,11 +244,11 @@ fn exploration_focus<MapData>(
None None
}; };
if let Some((width, height)) = dimensions { if let Some((width, height)) = dimensions {
if exploring.x >= width || exploring.y >= height { if exploring.0 >= width || exploring.1 >= height {
return; return;
} }
} }
if orig != exploring && exploring.x >= 0. && exploring.y >= 0. { if orig != exploring && exploring.0 >= 0. && exploring.1 >= 0. {
commands.entity(entity).insert(Exploring(exploring)); commands.entity(entity).insert(Exploring(exploring));
} }
} }
@ -289,7 +269,7 @@ fn navigate_to_explored<MapData>(
if actions.just_pressed(&ExplorationAction::NavigateTo) && known { if actions.just_pressed(&ExplorationAction::NavigateTo) && known {
commands commands
.entity(entity) .entity(entity)
.insert(Destination(point.as_ivec2())); .insert(Destination((point.x_i32(), point.y_i32())));
} }
} }
} }
@ -305,7 +285,7 @@ fn exploration_changed_announcement<ExplorationType, MapData>(
names: Query<&Name>, names: Query<&Name>,
types: Query<&ExplorationType>, types: Query<&ExplorationType>,
mappables: Query<&Mappable>, mappables: Query<&Mappable>,
spatial_query: SpatialQuery, rapier_context: Res<RapierContext>,
) -> Result<(), Box<dyn Error>> ) -> Result<(), Box<dyn Error>>
where where
ExplorationType: Component + Copy + Display, ExplorationType: Component + Copy + Display,
@ -314,14 +294,14 @@ where
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() { if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
let coordinates = coordinates.trunc(); let coordinates = coordinates.trunc();
let point = **exploring; let point = **exploring;
let shape = Collider::rectangle(1. - f32::EPSILON, 1. - f32::EPSILON); let shape = Collider::cuboid(0.5 - f32::EPSILON, 0.5 - f32::EPSILON);
let (known, idx) = if let Ok((map, revealed_tiles)) = map.get_single() { let (known, idx) = if let Ok((map, revealed_tiles)) = map.get_single() {
let idx = point.to_index(map.width); let idx = point.to_index(map.width);
(revealed_tiles[idx], Some(idx)) (revealed_tiles[idx], Some(idx))
} else { } else {
(false, None) (false, None)
}; };
let visible = viewshed.is_point_visible(exploring.as_ivec2()); let visible = viewshed.is_point_visible(exploring);
let fog_of_war = !visible && known; let fog_of_war = !visible && known;
let description: String = if known || visible { let description: String = if known || visible {
let mut tokens: Vec<String> = vec![]; let mut tokens: Vec<String> = vec![];
@ -329,13 +309,12 @@ where
commands.entity(entity).remove::<ExplorationFocused>(); commands.entity(entity).remove::<ExplorationFocused>();
} }
let exploring = Vec2::new(exploring.x(), exploring.y()); let exploring = Vec2::new(exploring.x(), exploring.y());
spatial_query.shape_intersections_callback( rapier_context.intersections_with_shape(
&shape,
exploring, exploring,
0., 0.,
&default(), &shape,
QueryFilter::new().predicate(&|v| explorable.get(v).is_ok()),
|entity| { |entity| {
if explorable.contains(entity) {
commands.entity(entity).insert(ExplorationFocused); commands.entity(entity).insert(ExplorationFocused);
if visible || mappables.get(entity).is_ok() { if visible || mappables.get(entity).is_ok() {
if let Ok(name) = names.get(entity) { if let Ok(name) = names.get(entity) {
@ -347,7 +326,6 @@ where
} }
} }
} }
}
true true
}, },
); );

View File

@ -2,8 +2,8 @@
#![allow(clippy::too_many_arguments)] #![allow(clippy::too_many_arguments)]
#![allow(clippy::type_complexity)] #![allow(clippy::type_complexity)]
pub use avian2d;
pub use bevy; pub use bevy;
pub use bevy_rapier2d;
pub use bevy_synthizer; pub use bevy_synthizer;
pub use bevy_tts; pub use bevy_tts;
pub use coord_2d; pub use coord_2d;

View File

@ -1,20 +1,22 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use avian2d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::{
na::{Isometry2, Vector2},
prelude::*,
};
pub use here_be_dragons::Map as MapgenMap; pub use here_be_dragons::Map as MapgenMap;
use here_be_dragons::{geometry::Rect as MRect, MapFilter, Tile}; use here_be_dragons::{geometry::Rect as MRect, MapFilter, Tile};
use maze_generator::{prelude::*, recursive_backtracking::RbGenerator}; use maze_generator::{prelude::*, recursive_backtracking::RbGenerator};
use rand::prelude::StdRng; use rand::prelude::StdRng;
use crate::{ use crate::{
core::{Obstacle, PointLike, Zone}, core::{Area, PointLike},
exploration::Mappable, exploration::Mappable,
visibility::Visible, visibility::Visible,
}; };
#[derive(Component, Clone, Default, Deref, DerefMut)] #[derive(Component, Clone, Default, Deref, DerefMut)]
#[require(Transform, SpawnColliders, SpawnPortals)]
pub struct Map<D: 'static + Clone + Default + Send + Sync>(pub MapgenMap<D>); pub struct Map<D: 'static + Clone + Default + Send + Sync>(pub MapgenMap<D>);
impl<D: Clone + Default + Send + Sync> From<MapgenMap<D>> for Map<D> { impl<D: Clone + Default + Send + Sync> From<MapgenMap<D>> for Map<D> {
@ -25,7 +27,10 @@ impl<D: Clone + Default + Send + Sync> From<MapgenMap<D>> for Map<D> {
#[derive(Component, Clone, Debug, Default, Reflect)] #[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)] #[reflect(Component)]
#[require(Transform, Mappable)] pub struct MapObstruction;
#[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct Portal; pub struct Portal;
#[derive(Component, Clone, Debug, Deref, DerefMut, Reflect)] #[derive(Component, Clone, Debug, Deref, DerefMut, Reflect)]
@ -38,6 +43,12 @@ impl Default for SpawnColliders {
} }
} }
impl From<bool> for SpawnColliders {
fn from(v: bool) -> Self {
Self(v)
}
}
#[derive(Component, Clone, Debug, Deref, DerefMut, Reflect)] #[derive(Component, Clone, Debug, Deref, DerefMut, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct SpawnPortals(pub bool); pub struct SpawnPortals(pub bool);
@ -48,6 +59,10 @@ impl Default for SpawnPortals {
} }
} }
#[derive(Default, Component, Clone, Debug, Reflect)]
#[reflect(Component)]
pub struct Zone;
pub trait ITileType { pub trait ITileType {
fn blocks_motion(&self) -> bool; fn blocks_motion(&self) -> bool;
fn blocks_visibility(&self) -> bool; fn blocks_visibility(&self) -> bool;
@ -63,6 +78,89 @@ impl ITileType for Tile {
} }
} }
#[derive(Bundle, Default)]
pub struct PortalBundle {
pub portal: Portal,
pub mappable: Mappable,
pub transform: TransformBundle,
}
#[derive(Bundle, Clone, Default)]
pub struct MapBundle<D: 'static + Clone + Default + Send + Sync> {
pub map: Map<D>,
pub spawn_colliders: SpawnColliders,
pub spawn_portals: SpawnPortals,
pub transform: TransformBundle,
}
#[derive(Bundle, Clone, Debug)]
pub struct TileBundle {
pub transform: TransformBundle,
pub collider: Collider,
pub rigid_body: RigidBody,
pub active_collision_types: ActiveCollisionTypes,
pub map_obstruction: MapObstruction,
}
impl Default for TileBundle {
fn default() -> Self {
Self {
transform: default(),
collider: Collider::cuboid(0.5, 0.5),
rigid_body: RigidBody::Fixed,
active_collision_types: ActiveCollisionTypes::default()
| ActiveCollisionTypes::KINEMATIC_STATIC
| ActiveCollisionTypes::DYNAMIC_STATIC,
map_obstruction: MapObstruction,
}
}
}
impl TileBundle {
pub fn new(x: i32, y: i32) -> Self {
Self {
transform: Transform::from_xyz(x as f32 + 0.5, y as f32 + 0.5, 0.).into(),
..default()
}
}
}
#[derive(Bundle, Clone, Debug)]
pub struct ZoneBundle {
pub collider: Collider,
pub transform: TransformBundle,
pub area: Area,
pub zone: Zone,
pub sensor: Sensor,
pub active_events: ActiveEvents,
}
impl ZoneBundle {
fn new(collider: Collider, position: (f32, f32)) -> Self {
let point = Isometry2::new(Vector2::new(position.0, position.1), 0.);
let aabb = collider.raw.compute_aabb(&point);
Self {
collider,
area: Area(aabb),
transform: Transform::from_translation(Vec3::new(position.0, position.1, 0.)).into(),
zone: default(),
sensor: default(),
active_events: ActiveEvents::COLLISION_EVENTS,
}
}
}
impl From<&MRect> for ZoneBundle {
fn from(rect: &MRect) -> Self {
let collider = Collider::cuboid(
rect.width() as f32 / 2. + 0.5,
rect.height() as f32 / 2. + 0.5,
);
let position = (rect.center().x(), rect.center().y());
Self::new(collider, position)
}
}
pub struct GridBuilder { pub struct GridBuilder {
width_in_rooms: usize, width_in_rooms: usize,
height_in_rooms: usize, height_in_rooms: usize,
@ -98,24 +196,21 @@ impl<D: Clone + Default> MapFilter<D> for GridBuilder {
let half_height = self.room_height / 2; let half_height = self.room_height / 2;
for y in 0..self.height_in_rooms { for y in 0..self.height_in_rooms {
for x in 0..self.width_in_rooms { for x in 0..self.width_in_rooms {
// println!("({x}, {y}): ");
let x_offset = x * (self.room_width + 1); let x_offset = x * (self.room_width + 1);
let y_offset = total_height - (y + 1) * (self.room_height + 1) - 1; let y_offset = total_height - (y + 1) * (self.room_height + 1) - 1;
// println!("Offsets: {x_offset}, {y_offset}");
let room = MRect::new_i32( let room = MRect::new_i32(
x_offset as i32 + 1, x_offset as i32 + 1,
y_offset as i32 + 1, y_offset as i32 + 1,
self.room_width as i32, self.room_width as i32,
self.room_height as i32, self.room_height as i32,
); );
// println!("{room:?}");
map.add_room(room); map.add_room(room);
let coords = maze_generator::prelude::Coordinates::new(x as i32, y as i32); let coords = maze_generator::prelude::Coordinates::new(x as i32, y as i32);
if let Some(field) = maze.get_field(&coords) { if let Some(field) = maze.get_field(&coords) {
use maze_generator::prelude::Direction::*; use maze_generator::prelude::Direction::*;
if field.has_passage(&North) { if field.has_passage(&North) {
let x = x_offset + half_width; let x = x_offset + half_width;
let y = y_offset + self.room_height + 1; let y = y_offset + self.room_height;
map.set_tile(x, y, Tile::floor()); map.set_tile(x, y, Tile::floor());
} }
if field.has_passage(&South) { if field.has_passage(&South) {
@ -124,7 +219,7 @@ impl<D: Clone + Default> MapFilter<D> for GridBuilder {
map.set_tile(x, y, Tile::floor()); map.set_tile(x, y, Tile::floor());
} }
if field.has_passage(&East) { if field.has_passage(&East) {
let x = x_offset + self.room_width + 1; let x = x_offset + self.room_width;
let y = y_offset + half_height; let y = y_offset + half_height;
map.set_tile(x, y, Tile::floor()); map.set_tile(x, y, Tile::floor());
} }
@ -160,27 +255,18 @@ fn spawn_colliders<D: 'static + Clone + Default + Send + Sync>(
for x in 0..map.width { for x in 0..map.width {
if let Some(tile) = map.at(x, y) { if let Some(tile) = map.at(x, y) {
if tile.blocks_motion() { if tile.blocks_motion() {
let id = commands let id = commands.spawn(TileBundle::new(x as i32, y as i32)).id();
.spawn((
Obstacle,
Transform::from_xyz(x as f32 + 0.5, y as f32 + 0.5, 0.),
))
.id();
if tile.blocks_visibility() { if tile.blocks_visibility() {
commands.entity(id).insert(Visible::opaque()); commands.entity(id).insert(Visible::opaque());
} }
commands.entity(map_entity).add_children(&[id]); commands.entity(map_entity).push_children(&[id]);
} }
} }
} }
} }
for room in &map.rooms { for room in &map.rooms {
commands.entity(map_entity).with_children(|parent| { commands.entity(map_entity).with_children(|parent| {
parent.spawn(( parent.spawn(ZoneBundle::from(room));
Zone,
Transform::from_xyz(room.center().x as f32, room.center().y as f32, 0.),
Collider::rectangle(room.width() as f32 + 1., room.height() as f32 + 1.),
));
}); });
} }
} }
@ -226,7 +312,10 @@ fn spawn_portals<D: 'static + Clone + Default + Send + Sync>(
} }
for (x, y) in portals { for (x, y) in portals {
commands.entity(map_entity).with_children(|parent| { commands.entity(map_entity).with_children(|parent| {
parent.spawn((Portal, Transform::from_xyz(x, y, 0.))); parent.spawn(PortalBundle {
transform: Transform::from_translation(Vec3::new(x, y, 0.)).into(),
..default()
});
}); });
} }
} }
@ -243,7 +332,7 @@ fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>(
for portal_entity in &portals { for portal_entity in &portals {
commands commands
.entity(portal_entity) .entity(portal_entity)
.insert((Collider::rectangle(1., 1.), Sensor)); .insert((Collider::cuboid(0.5, 0.5), Sensor));
} }
commands.entity(entity).remove::<SpawnColliders>(); commands.entity(entity).remove::<SpawnColliders>();
} }

View File

@ -1,14 +1,12 @@
#![allow(clippy::map_entry)]
use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash::Hash}; use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash::Hash};
use avian2d::prelude::*;
use bevy::{math::CompassQuadrant, prelude::*}; use bevy::{math::CompassQuadrant, prelude::*};
use bevy_rapier2d::prelude::*;
use bevy_tts::Tts; use bevy_tts::Tts;
use leafwing_input_manager::prelude::*; use leafwing_input_manager::prelude::*;
use crate::{ use crate::{
core::{CardinalDirection, GlobalTransformExt, Player, Zone}, core::{Area, CardinalDirection, GlobalTransformExt, Player, TransformExt},
error::error_handler, error::error_handler,
log::Log, log::Log,
utils::target_and_other, utils::target_and_other,
@ -135,8 +133,10 @@ fn snap(
snap_timers.insert(entity, SnapTimer::default()); snap_timers.insert(entity, SnapTimer::default());
transform.rotate(Quat::from_rotation_z(PI)); transform.rotate(Quat::from_rotation_z(PI));
} else if actions.just_pressed(&NavigationAction::SnapCardinal) { } else if actions.just_pressed(&NavigationAction::SnapCardinal) {
println!("Direction: {direction:?}");
let yaw: Rot2 = direction.into(); let yaw: Rot2 = direction.into();
let yaw = yaw.as_radians(); let yaw = yaw.as_radians();
println!("Yaw: {yaw}");
let rotation = Quat::from_rotation_z(yaw); let rotation = Quat::from_rotation_z(yaw);
if transform.rotation != rotation { if transform.rotation != rotation {
transform.rotation = rotation; transform.rotation = rotation;
@ -153,22 +153,19 @@ fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
} }
fn controls( fn controls(
mut commands: Commands, rapier_context: Res<RapierContext>,
spatial_query: SpatialQuery,
time: Res<Time>, time: Res<Time>,
snap_timers: Res<SnapTimers>, snap_timers: Res<SnapTimers>,
sensors: Query<Entity, With<Sensor>>,
mut query: Query<( mut query: Query<(
Entity, Entity,
&mut ActionState<NavigationAction>, &mut ActionState<NavigationAction>,
&mut LinearVelocity, &mut Velocity,
&Speed, &Speed,
Option<&RotationSpeed>, Option<&RotationSpeed>,
Option<&BackwardMovementFactor>, Option<&BackwardMovementFactor>,
Option<&ForwardMovementFactor>, Option<&ForwardMovementFactor>,
Option<&StrafeMovementFactor>, Option<&StrafeMovementFactor>,
&mut Transform, &mut Transform,
&GlobalTransform,
&Collider, &Collider,
)>, )>,
) { ) {
@ -182,7 +179,6 @@ fn controls(
forward_movement_factor, forward_movement_factor,
strafe_movement_factor, strafe_movement_factor,
mut transform, mut transform,
global_transform,
collider, collider,
) in &mut query ) in &mut query
{ {
@ -215,34 +211,31 @@ fn controls(
let mut speed = **speed; let mut speed = **speed;
speed *= movement_factor; speed *= movement_factor;
let move_velocity = direction * speed; let move_velocity = direction * speed;
// println!("{entity:?}: SetLinearVelocity: {velocity:?}");
actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity); actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity);
} }
if velocity.0 != actions.axis_pair(&NavigationAction::SetLinearVelocity) { if velocity.linvel != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
**velocity = actions.axis_pair(&NavigationAction::SetLinearVelocity); velocity.linvel = actions.axis_pair(&NavigationAction::SetLinearVelocity);
} }
if actions.axis_pair(&NavigationAction::Translate) != Vec2::ZERO { if actions.axis_pair(&NavigationAction::Translate) != Vec2::ZERO {
let pair = actions.axis_pair(&NavigationAction::Translate); let pair = actions.axis_pair(&NavigationAction::Translate);
let dir = Dir2::new_unchecked(pair.normalize()); if rapier_context
let hit = spatial_query.cast_shape( .cast_shape(
transform.translation.truncate(),
transform.yaw().as_radians(),
pair,
collider, collider,
global_transform.translation().truncate(), ShapeCastOptions {
global_transform.yaw().as_radians(), max_time_of_impact: 1.,
dir,
&ShapeCastConfig {
max_distance: pair.length(),
ignore_origin_penetration: true,
..default() ..default()
}, },
&SpatialQueryFilter::from_excluded_entities(&sensors), QueryFilter::new()
); .exclude_sensors()
if hit.is_none() { .exclude_collider(entity),
)
.is_none()
{
transform.translation += pair.extend(0.); transform.translation += pair.extend(0.);
} else {
// println!("Can't translate: {:?}", pair.extend(0.));
// println!("Delta: {}", pair.length());
if let Some(hit) = hit {
commands.entity(hit.entity).log_components();
}
} }
actions.set_axis_pair(&NavigationAction::Translate, Vec2::ZERO); actions.set_axis_pair(&NavigationAction::Translate, Vec2::ZERO);
} }
@ -254,8 +247,10 @@ fn controls(
} }
} }
if actions.value(&NavigationAction::SetAngularVelocity) != 0. { if actions.value(&NavigationAction::SetAngularVelocity) != 0. {
// velocity.angvel =
// actions.value(&NavigationAction::SetAngularVelocity);
transform.rotation *= Quat::from_rotation_z( transform.rotation *= Quat::from_rotation_z(
actions.value(&NavigationAction::SetAngularVelocity) * time.delta_secs(), actions.value(&NavigationAction::SetAngularVelocity) * time.delta_seconds(),
); );
} }
} }
@ -304,18 +299,18 @@ fn speak_direction(
Ok(()) Ok(())
} }
fn add_speed( fn add_speed(mut commands: Commands, query: Query<Entity, (Added<Speed>, Without<Velocity>)>) {
mut commands: Commands,
query: Query<Entity, (Added<Speed>, Without<LinearVelocity>)>,
) {
for entity in &query { for entity in &query {
commands.entity(entity).insert(LinearVelocity::default()); commands.entity(entity).insert(Velocity {
linvel: Vec2::ZERO,
..default()
});
} }
} }
fn log_zone_descriptions( fn log_area_descriptions(
mut events: EventReader<Collision>, mut events: EventReader<CollisionEvent>,
zones: Query<(&ColliderAabb, Option<&Name>), With<Zone>>, areas: Query<(&Area, Option<&Name>)>,
players: Query<&Player>, players: Query<&Player>,
config: Res<NavigationPlugin>, config: Res<NavigationPlugin>,
mut log: Query<&mut Log>, mut log: Query<&mut Log>,
@ -323,21 +318,19 @@ fn log_zone_descriptions(
if !config.log_area_descriptions { if !config.log_area_descriptions {
return; return;
} }
for Collision(contacts) in events.read() { for event in events.read() {
let started = contacts.during_current_frame && !contacts.during_previous_frame; let (entity1, entity2, started) = match event {
let stopped = !contacts.during_current_frame && contacts.during_previous_frame; CollisionEvent::Started(collider1, collider2, _) => (collider1, collider2, true),
if !started && !stopped { CollisionEvent::Stopped(collider1, collider2, _) => (collider1, collider2, false),
continue; };
} if let Some((area, other)) = target_and_other(*entity1, *entity2, &|v| areas.get(v).is_ok())
if let Some((area, other)) =
target_and_other(contacts.entity1, contacts.entity2, &|v| zones.contains(v))
{ {
if players.contains(other) { if players.get(other).is_ok() {
if let Ok((aabb, area_name)) = zones.get(area) { if let Ok((aabb, area_name)) = areas.get(area) {
let name = if let Some(name) = area_name { let name = if let Some(name) = area_name {
Some(name.to_string()) Some(name.to_string())
} else if config.describe_undescribed_areas { } else if config.describe_undescribed_areas {
Some(format!("{}-by-{} area", aabb.size().x, aabb.size().y)) Some(format!("{}-by-{} area", aabb.extents().x, aabb.extents().y))
} else { } else {
None None
}; };
@ -384,12 +377,17 @@ impl Plugin for NavigationPlugin {
.register_type::<RotationSpeed>() .register_type::<RotationSpeed>()
.register_type::<Speed>() .register_type::<Speed>()
.add_plugins(InputManagerPlugin::<NavigationAction>::default()) .add_plugins(InputManagerPlugin::<NavigationAction>::default())
.add_systems(FixedPreUpdate, (update_direction, add_speed)) .add_systems(PreUpdate, (update_direction, add_speed))
.add_systems(FixedUpdate, (snap, controls).chain().in_set(Movement)) .add_systems(
Update,
(snap, controls)
.chain()
.in_set(Movement),
)
.add_systems( .add_systems(
FixedUpdate, FixedUpdate,
(tick_snap_timers, speak_direction.pipe(error_handler)), (tick_snap_timers, speak_direction.pipe(error_handler)),
) )
.add_systems(PostUpdate, (remove_direction, log_zone_descriptions)); .add_systems(PostUpdate, (remove_direction, log_area_descriptions));
} }
} }

View File

@ -1,11 +1,19 @@
use avian2d::prelude::*; use bevy::{
use bevy::{prelude::*, utils::HashMap}; prelude::*,
tasks::{futures_lite::future, prelude::*, Task},
utils::HashMap,
};
use bevy_rapier2d::{
na::{Isometry2, Vector2},
prelude::*,
rapier::prelude::{ColliderHandle, ColliderSet, QueryPipeline, RigidBodySet},
};
use leafwing_input_manager::{plugin::InputManagerSystem, prelude::*}; use leafwing_input_manager::{plugin::InputManagerSystem, prelude::*};
use pathfinding::prelude::*; use pathfinding::prelude::*;
use crate::{ use crate::{
core::{GlobalTransformExt, Obstacle}, core::{PointLike, TransformExt},
map::Map, map::{Map, MapObstruction},
navigation::{NavigationAction, RotationSpeed, Speed}, navigation::{NavigationAction, RotationSpeed, Speed},
}; };
@ -18,9 +26,15 @@ impl Actionlike for NegotiatePathAction {
} }
} }
#[derive(Component, Debug, Deref, DerefMut)]
struct Calculating(Task<Option<Path>>);
#[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Eq, Hash, PartialEq, Reflect)] #[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Eq, Hash, PartialEq, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct Destination(pub IVec2); pub struct Destination(pub (i32, i32));
impl_pointlike_for_tuple_component!(Destination);
impl_pointlike_for_tuple_component!(&Destination);
#[derive(Component, Clone, Debug, Default, Reflect)] #[derive(Component, Clone, Debug, Default, Reflect)]
#[reflect(Component)] #[reflect(Component)]
@ -28,11 +42,11 @@ pub struct NoPath;
#[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect)] #[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)] #[reflect(Component)]
pub struct Path(pub Vec<IVec2>); pub struct Path(pub Vec<(i32, i32)>);
#[derive(Component, Clone, Debug, Default, Reflect, Deref, DerefMut)] #[derive(Component, Clone, Debug, Default, Reflect, Deref, DerefMut)]
#[reflect(Component)] #[reflect(Component)]
pub struct CostMap(pub HashMap<IVec2, f32>); pub struct CostMap(pub HashMap<(i32, i32), f32>);
#[derive(Bundle, Deref, DerefMut)] #[derive(Bundle, Deref, DerefMut)]
pub struct PathfindingControlsBundle(pub ActionState<NegotiatePathAction>); pub struct PathfindingControlsBundle(pub ActionState<NegotiatePathAction>);
@ -46,121 +60,86 @@ impl Default for PathfindingControlsBundle {
} }
pub fn find_path<D: 'static + Clone + Default + Send + Sync>( pub fn find_path<D: 'static + Clone + Default + Send + Sync>(
start: IVec2, start: &dyn PointLike,
destination: IVec2, destination: &dyn PointLike,
map: &Map<D>, map: &Map<D>,
cost_map: &Option<CostMap>, cost_map: &Option<CostMap>,
) -> Option<(Vec<IVec2>, u32)> { ) -> Option<(Vec<(i32, i32)>, u32)> {
astar( astar(
&start, &start.into(),
|p| { |p| {
let mut successors: Vec<(IVec2, u32)> = vec![]; let mut successors: Vec<((i32, i32), u32)> = vec![];
if p.x >= 0 && p.y >= 0 { if p.0 >= 0 && p.1 >= 0 {
if let Some(tile) = map.at(p.x as usize, p.y as usize) { if let Some(tile) = map.at(p.0 as usize, p.1 as usize) {
if tile.is_walkable() { if tile.is_walkable() {
for tile in map.get_available_exits(p.x as usize, p.y as usize) { for tile in map.get_available_exits(p.0 as usize, p.1 as usize) {
let mut cost = tile.2 * 100.; let mut cost = tile.2 * 100.;
if let Some(cost_map) = cost_map { if let Some(cost_map) = cost_map {
if let Some(modifier) = cost_map.get(p) { if let Some(modifier) =
cost_map.get(&(tile.0 as i32, tile.1 as i32))
{
cost *= modifier; cost *= modifier;
} }
} }
successors successors.push(((tile.0 as i32, tile.1 as i32), cost as u32));
.push((IVec2::new(tile.0 as i32, tile.1 as i32), cost as u32));
} }
} }
} }
} }
successors successors
}, },
|p| (p.distance_squared(destination) * 100) as u32, |p| (p.distance_squared(destination) * 100.) as u32,
|p| *p == destination, |p| *p == destination.into(),
) )
} }
fn calculate_path( fn find_path_for_shape(
mut commands: Commands, initiator: ColliderHandle,
spatial_query: SpatialQuery, start: Transform,
mut query: Query< destination: Destination,
( cost_map: &Option<CostMap>,
Entity, query_pipeline: QueryPipeline,
&Destination, collider_set: ColliderSet,
&GlobalTransform, rigid_body_set: RigidBodySet,
&Collider, shape: Collider,
Option<&CostMap>, ) -> Option<Path> {
Option<&mut ActionState<NegotiatePathAction>>,
),
Changed<Destination>,
>,
obstacles: Query<Entity, With<Obstacle>>,
sensors: Query<Entity, With<Sensor>>,
) {
for (entity, destination, transform, collider, cost_map, actions) in &mut query {
trace!("{entity}: destination: {destination:?}");
commands.entity(entity).remove::<Path>().remove::<NoPath>();
if transform.translation().truncate().as_ivec2() == **destination {
commands.entity(entity).remove::<Destination>();
continue;
}
let path = astar( let path = astar(
&transform.translation().truncate().as_ivec2(), &start.i32(),
|p| { |p| {
let mut start = Vec2::new(p.x as f32, p.y as f32); let mut successors: Vec<((i32, i32), u32)> = vec![];
if start.x >= 0. { let x = p.0;
start.x += 0.5; let y = p.1;
} else {
start.x -= 0.5;
}
if start.y >= 0. {
start.y += 0.5;
} else {
start.y -= 0.5;
}
let mut successors: Vec<(IVec2, u32)> = vec![];
let x = p.x;
let y = p.y;
let exits = vec![ let exits = vec![
(IVec2::new(x - 1, y), 1.), ((x - 1, y), 1.),
(IVec2::new(x + 1, y), 1.), ((x + 1, y), 1.),
(IVec2::new(x, y - 1), 1.), ((x, y - 1), 1.),
(IVec2::new(x, y + 1), 1.), ((x, y + 1), 1.),
(IVec2::new(x - 1, y - 1), 1.5), ((x - 1, y - 1), 1.5),
(IVec2::new(x + 1, y - 1), 1.5), ((x + 1, y - 1), 1.5),
(IVec2::new(x - 1, y + 1), 1.5), ((x - 1, y + 1), 1.5),
(IVec2::new(x + 1, y + 1), 1.5), ((x + 1, y + 1), 1.5),
]; ];
for exit in &exits { for exit in &exits {
let mut check = exit.0.as_vec2(); let mut should_push = true;
if check.x >= 0. { let dest = Isometry2::new(Vector2::new(exit.0 .0 as f32, exit.0 .1 as f32), 0.);
check.x += 0.5; if query_pipeline
} else { .intersection_with_shape(
check.x -= 0.5; &rigid_body_set,
&collider_set,
&dest,
&*shape.raw,
bevy_rapier2d::rapier::pipeline::QueryFilter::new()
.exclude_sensors()
.exclude_collider(initiator),
)
.is_some()
{
should_push = false;
} }
if check.y >= 0. { if should_push {
check.y += 0.5;
} else {
check.y -= 0.5;
}
let dir = (check - start).normalize();
let dir = Dir2::new_unchecked(dir);
let delta = (check - start).length();
let hits = spatial_query.cast_shape_predicate(
collider,
start,
transform.yaw().as_radians(),
dir,
&ShapeCastConfig {
max_distance: delta,
ignore_origin_penetration: true,
..default()
},
&SpatialQueryFilter::from_excluded_entities(&sensors),
&|entity| obstacles.contains(entity),
);
if hits.is_none() {
let mut cost = exit.1 * 100.; let mut cost = exit.1 * 100.;
if let Some(cost_map) = cost_map { if let Some(cost_map) = cost_map {
if let Some(modifier) = cost_map.get(&exit.0) { if let Some(modifier) = cost_map.get(&(exit.0 .0, exit.0 .1)) {
cost *= modifier; cost *= modifier;
} }
} }
@ -169,12 +148,115 @@ fn calculate_path(
} }
successors successors
}, },
|p| (p.distance_squared(**destination) * 100) as u32, |p| (p.distance_squared(&destination) * 100.) as u32,
|p| *p == **destination, |p| *p == destination.i32(),
); );
if let Some(path) = path { if let Some(path) = path {
commands.entity(entity).insert(Path(path.0)); Some(Path(path.0))
} else { } else {
None
}
}
fn calculate_path(
mut commands: Commands,
rapier_context: Res<RapierContext>,
obstructions: Query<&RapierColliderHandle, With<MapObstruction>>,
query: Query<
(
Entity,
&RapierColliderHandle,
&Destination,
&Transform,
&Collider,
Option<&CostMap>,
),
Changed<Destination>,
>,
) {
for (entity, handle, destination, coordinates, shape, cost_map) in &query {
trace!("{entity}: destination: {destination:?}");
if coordinates.i32() == **destination {
trace!("{entity}: remove1");
commands
.entity(entity)
.remove::<Path>()
.remove::<NoPath>()
.remove::<Calculating>()
.remove::<Destination>();
continue;
}
trace!(
"{entity:?}: Calculating path from {:?} to {destination:?}",
coordinates.translation.truncate().i32()
);
let coordinates_clone = *coordinates;
let destination_clone = *destination;
let query_pipeline = rapier_context.query_pipeline.clone();
let cost_map_clone = cost_map.cloned();
let handle_clone = *handle;
let mut collider_set = rapier_context.colliders.clone();
let mut to_remove = vec![handle.0];
for handle in collider_set.iter() {
if !obstructions.iter().map(|v| v.0).any(|x| x == handle.0) {
to_remove.push(handle.0);
}
}
let mut bodies = rapier_context.bodies.clone();
if !to_remove.is_empty() {
let mut islands = rapier_context.islands.clone();
for handle in to_remove {
collider_set.remove(handle, &mut islands, &mut bodies, false);
}
}
let shape_clone = (*shape).clone();
trace!(
"{entity:?}: path: calculating from {:?} to {destination:?}",
coordinates.i32(),
);
let pool = AsyncComputeTaskPool::get();
let task = pool.spawn(async move {
find_path_for_shape(
handle_clone.0,
coordinates_clone,
destination_clone,
&cost_map_clone,
query_pipeline,
collider_set,
bodies,
shape_clone,
)
});
trace!("{entity}: remove2");
commands
.entity(entity)
.insert(Calculating(task))
.remove::<Path>()
.remove::<NoPath>();
}
}
fn poll_tasks(
mut commands: Commands,
mut query: Query<(
Entity,
&mut Calculating,
&Transform,
&Destination,
Option<&mut ActionState<NegotiatePathAction>>,
)>,
) {
for (entity, mut calculating, transform, destination, actions) in &mut query {
if let Some(result) = future::block_on(future::poll_once(&mut **calculating)) {
if let Some(path) = result {
trace!("{entity:?}: Path: {path:?}");
commands.entity(entity).insert(path);
} else {
trace!(
"{entity:?}: path: no path from {:?} to {:?}",
transform.translation.truncate().i32(),
**destination
);
commands.entity(entity).insert(NoPath); commands.entity(entity).insert(NoPath);
if let Some(mut actions) = actions { if let Some(mut actions) = actions {
trace!("{entity:?}: Disabling and resetting because no path"); trace!("{entity:?}: Disabling and resetting because no path");
@ -182,13 +264,18 @@ fn calculate_path(
actions.reset_all(); actions.reset_all();
} }
} }
commands.entity(entity).remove::<Calculating>();
}
} }
} }
fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Destination>) { fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Destination>) {
for entity in removed.read() { for entity in removed.read() {
if let Some(mut commands) = commands.get_entity(entity) { if let Some(mut commands) = commands.get_entity(entity) {
commands.remove::<Path>().remove::<NoPath>(); commands
.remove::<Calculating>()
.remove::<Path>()
.remove::<NoPath>();
} }
} }
} }
@ -196,22 +283,20 @@ fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Des
fn negotiate_path( fn negotiate_path(
mut commands: Commands, mut commands: Commands,
time: Res<Time>, time: Res<Time>,
physics_time: Res<Time<Physics>>, physics_config: Res<RapierConfiguration>,
spatial_query: SpatialQuery,
mut query: Query<( mut query: Query<(
Entity, Entity,
Option<&mut ActionState<NegotiatePathAction>>, Option<&mut ActionState<NegotiatePathAction>>,
&mut ActionState<NavigationAction>, &mut ActionState<NavigationAction>,
&mut Path, &mut Path,
&mut Transform, &mut Transform,
&GlobalTransform,
&Collider, &Collider,
&Speed, &Speed,
Option<&RotationSpeed>, Option<&RotationSpeed>,
)>, )>,
sensors: Query<Entity, With<Sensor>>, rapier_context: Res<RapierContext>,
) { ) {
if physics_time.is_paused() { if !physics_config.physics_pipeline_active || !physics_config.query_pipeline_active {
return; return;
} }
for ( for (
@ -220,21 +305,25 @@ fn negotiate_path(
mut navigation_actions, mut navigation_actions,
mut path, mut path,
mut transform, mut transform,
global_transform,
collider, collider,
speed, speed,
rotation_speed, rotation_speed,
) in &mut query ) in &mut query
{ {
trace!("{entity:?}: negotiating path"); trace!("{entity:?}: negotiating path");
let start = global_transform.translation().truncate().as_ivec2(); let start_i32 = transform.translation.truncate().i32();
if path.len() > 0 && path[0] == start { trace!(
"{entity:?}: start pathfinding from {start_i32:?} to {:?}: at {:?}",
path.last(),
transform.translation.truncate().i32()
);
if path.len() > 0 && path[0] == start_i32 {
trace!("At start, removing"); trace!("At start, removing");
path.remove(0); path.remove(0);
} }
if let Some(next) = path.first() { if let Some(next) = path.first() {
let start = global_transform.translation().truncate(); let start = transform.translation.truncate();
let mut next = next.as_vec2(); let mut next = Vec2::new(next.0 as f32, next.1 as f32);
if next.x >= 0. { if next.x >= 0. {
next.x += 0.5; next.x += 0.5;
} else { } else {
@ -245,30 +334,37 @@ fn negotiate_path(
} else { } else {
next.y -= 0.5; next.y -= 0.5;
} }
let direction = (next - start).normalize(); let mut direction = next - start;
let delta = time.delta_secs() * **speed; direction = direction.normalize();
let dir = Dir2::new_unchecked(direction); direction *= **speed;
let hit = spatial_query.cast_shape( direction *= time.delta_seconds();
collider, trace!(
"{entity:?}: Direction: {direction:?}, Distance: {}",
(next - start).length()
);
if rapier_context
.cast_shape(
start, start,
global_transform.yaw().as_radians(), transform.yaw().as_radians(),
dir, direction,
&ShapeCastConfig { collider,
max_distance: delta, ShapeCastOptions {
ignore_origin_penetration: true, max_time_of_impact: 1.,
..default() ..default()
}, },
&SpatialQueryFilter::from_excluded_entities(&sensors), QueryFilter::new()
); .exclude_sensors()
if hit.is_some() { .exclude_collider(entity),
// println!("{entity} is stuck"); )
.is_some()
{
trace!("{entity:?} is stuck");
// TODO: Remove when we have an actual character controller. // TODO: Remove when we have an actual character controller.
next.x = next.x.trunc(); next.x = next.x.trunc();
next.y = next.y.trunc(); next.y = next.y.trunc();
transform.translation = next.extend(0.); transform.translation = next.extend(0.);
} else { } else {
// println!("Translating: {:?}", direction * delta); navigation_actions.set_axis_pair(&NavigationAction::Translate, direction);
navigation_actions.set_axis_pair(&NavigationAction::Translate, direction * delta);
} }
if rotation_speed.is_some() { if rotation_speed.is_some() {
let angle = direction.y.atan2(direction.x); let angle = direction.y.atan2(direction.x);
@ -308,11 +404,12 @@ fn actions(
} else { } else {
let pair = actions.axis_pair(&NegotiatePathAction); let pair = actions.axis_pair(&NegotiatePathAction);
trace!("{entity:?}: Negotiating path to {pair:?}"); trace!("{entity:?}: Negotiating path to {pair:?}");
let dest = Destination(pair.as_ivec2()); let dest = Destination(pair.xy().i32());
if let Some(mut current_dest) = destination { if let Some(mut current_dest) = destination {
trace!("Got a destination"); trace!("Got a destination");
if *current_dest != dest { if *current_dest != dest {
trace!("{entity:?}: New destination {dest:?} differs from {current_dest:?}, zeroing velocity"); trace
!("{entity:?}: New destination {dest:?} differs from {current_dest:?}, zeroing velocity");
navigation_action navigation_action
.set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO); .set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO);
*current_dest = dest; *current_dest = dest;
@ -330,14 +427,15 @@ pub struct PathfindingPlugin;
impl Plugin for PathfindingPlugin { impl Plugin for PathfindingPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_plugins((InputManagerPlugin::<NegotiatePathAction>::default(),)) app.add_plugins(InputManagerPlugin::<NegotiatePathAction>::default())
.register_type::<Destination>() .register_type::<Destination>()
.register_type::<NoPath>() .register_type::<NoPath>()
.register_type::<Path>() .register_type::<Path>()
.register_type::<CostMap>() .register_type::<CostMap>()
.add_systems(PreUpdate, (poll_tasks, negotiate_path).chain())
.add_systems( .add_systems(
FixedPreUpdate, PreUpdate,
(actions, calculate_path, negotiate_path) (actions, calculate_path)
.chain() .chain()
.after(InputManagerSystem::Tick), .after(InputManagerSystem::Tick),
) )

View File

@ -22,7 +22,7 @@ pub use volumetric::Volumetric;
pub struct SoundPlugins<'a, S>(std::marker::PhantomData<&'a S>); pub struct SoundPlugins<'a, S>(std::marker::PhantomData<&'a S>);
impl<S> Default for SoundPlugins<'_, S> { impl<'a, S> Default for SoundPlugins<'a, S> {
fn default() -> Self { fn default() -> Self {
Self(std::marker::PhantomData) Self(std::marker::PhantomData)
} }

View File

@ -1,5 +1,5 @@
use avian2d::{parry::query::ClosestPoints, prelude::*};
use bevy::{prelude::*, transform::TransformSystem}; use bevy::{prelude::*, transform::TransformSystem};
use bevy_rapier2d::{parry::query::ClosestPoints, prelude::*};
use bevy_synthizer::{Listener, Sound}; use bevy_synthizer::{Listener, Sound};
use crate::core::GlobalTransformExt; use crate::core::GlobalTransformExt;
@ -39,9 +39,12 @@ fn update(
); );
commands commands
.entity(sound_entity) .entity(sound_entity)
.insert(Transform::from_translation(sound_translation)); .insert(TransformBundle::from_transform(
Transform::from_translation(sound_translation),
));
} }
} else if closest == ClosestPoints::Intersecting && sound_transform.is_some() { } else if closest == ClosestPoints::Intersecting && sound_transform.is_some() {
println!("Clearing volumetric");
commands commands
.entity(sound_entity) .entity(sound_entity)
.remove::<Transform>() .remove::<Transform>()
@ -58,7 +61,7 @@ fn removed(
) { ) {
for entity in removed.read() { for entity in removed.read() {
if transforms.get(entity).is_ok() { if transforms.get(entity).is_ok() {
commands.entity(entity).insert(Transform::default()); commands.entity(entity).insert(TransformBundle::default());
} }
} }
} }

View File

@ -3,12 +3,14 @@ use std::{
marker::PhantomData, marker::PhantomData,
}; };
use avian2d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::na::Isometry2;
use coord_2d::{Coord, Size}; use coord_2d::{Coord, Size};
use shadowcast::{vision_distance, Context, InputGrid}; use shadowcast::{vision_distance, Context, InputGrid};
use crate::{ use crate::{
bevy_rapier2d::prelude::*,
core::{GlobalTransformExt, Player, PointLike}, core::{GlobalTransformExt, Player, PointLike},
log::Log, log::Log,
map::{Map, MapPlugin}, map::{Map, MapPlugin},
@ -23,10 +25,9 @@ pub struct DontLogWhenVisible;
pub struct RevealedTiles(pub Vec<bool>); pub struct RevealedTiles(pub Vec<bool>);
#[derive(Component, Clone, Debug, Eq, PartialEq)] #[derive(Component, Clone, Debug, Eq, PartialEq)]
#[require(VisibleEntities)]
pub struct Viewshed { pub struct Viewshed {
pub range: u32, pub range: u32,
pub visible_points: HashSet<IVec2>, pub visible_points: HashSet<(i32, i32)>,
} }
impl Default for Viewshed { impl Default for Viewshed {
@ -39,8 +40,8 @@ impl Default for Viewshed {
} }
impl Viewshed { impl Viewshed {
pub fn is_point_visible(&self, point: IVec2) -> bool { pub fn is_point_visible(&self, point: &dyn PointLike) -> bool {
self.visible_points.contains(&point) self.visible_points.contains(&point.into())
} }
fn update( fn update(
@ -51,7 +52,7 @@ impl Viewshed {
start: &Vec2, start: &Vec2,
opacity_map: &OpacityMap, opacity_map: &OpacityMap,
sensors: &Query<&Sensor>, sensors: &Query<&Sensor>,
spatial_query: &SpatialQuery, rapier_context: &RapierContext,
) { ) {
let mut context: Context<u8> = Context::default(); let mut context: Context<u8> = Context::default();
let vision_distance = vision_distance::Circle::new(self.range); let vision_distance = vision_distance::Circle::new(self.range);
@ -59,12 +60,7 @@ impl Viewshed {
(start.x.abs() + self.range as f32 * 2.) as u32, (start.x.abs() + self.range as f32 * 2.) as u32,
(start.y.abs() + self.range as f32 * 2.) as u32, (start.y.abs() + self.range as f32 * 2.) as u32,
); );
let visibility_grid = VisibilityGrid( let visibility_grid = VisibilityGrid(size, *viewer_entity, opacity_map.clone());
*viewer_entity,
start.as_ivec2(),
self.range,
opacity_map.clone(),
);
let mut new_visible = HashSet::new(); let mut new_visible = HashSet::new();
let mut new_visible_entities = HashSet::new(); let mut new_visible_entities = HashSet::new();
// println!("Start: {viewer_entity}"); // println!("Start: {viewer_entity}");
@ -75,34 +71,34 @@ impl Viewshed {
vision_distance, vision_distance,
u8::MAX, u8::MAX,
|coord, _directions, _visibility| { |coord, _directions, _visibility| {
new_visible.insert((coord.x, coord.y));
let coord = IVec2::new(coord.x, coord.y); let coord = IVec2::new(coord.x, coord.y);
new_visible.insert(coord);
// println!("Checking {coord:?}"); // println!("Checking {coord:?}");
if let Some((_, entities)) = opacity_map.get(&coord) { if let Some((_, entities)) = opacity_map.get(&coord) {
for e in entities { for e in entities {
if entities.len() == 1 || sensors.contains(*e) { if entities.len() == 1 || sensors.contains(*e) {
// println!("Spotted {e:?}");
new_visible_entities.insert(*e); new_visible_entities.insert(*e);
} else { } else {
let should_push = std::cell::RefCell::new(true); let mut should_push = true;
let coord = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5); let coord = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5);
let dir = Dir2::new_unchecked((coord - *start).normalize()); let dir = (coord - *start).normalize();
// println!("Casting from {coord} to {dir:?}"); // println!("Casting from {coord}");
spatial_query.cast_ray_predicate( rapier_context.intersections_with_ray(
*start, *start,
dir, dir,
dir.distance(*start), dir.distance(*start),
true, true,
&default(), default(),
&|entity| { |entity, _hit| {
if *e != entity && entities.contains(e) { if *e != entity && entities.contains(&e) {
// println!("{entities:?} contains {e}"); // println!("{entities:?} contains {e} and hits at {:?}", hit.point);
*should_push.borrow_mut() = false; // commands.entity(*e).log_components();
should_push = false;
} }
true true
}, },
); );
if *should_push.borrow() { if should_push {
new_visible_entities.insert(*e); new_visible_entities.insert(*e);
} }
} }
@ -115,11 +111,9 @@ impl Viewshed {
} }
if new_visible_entities != **visible_entities { if new_visible_entities != **visible_entities {
for lost in visible_entities.difference(&new_visible_entities) { for lost in visible_entities.difference(&new_visible_entities) {
// println!("Lost {lost}");
commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity); commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity);
} }
for gained in new_visible_entities.difference(visible_entities) { for gained in new_visible_entities.difference(visible_entities) {
// println!("Gained {gained}");
commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity); commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity);
} }
**visible_entities = new_visible_entities; **visible_entities = new_visible_entities;
@ -153,29 +147,23 @@ pub struct OpacityMap(HashMap<IVec2, (u8, HashSet<Entity>)>);
impl OpacityMap { impl OpacityMap {
fn update( fn update(
&mut self, &mut self,
spatial_query: &SpatialQuery, rapier_context: &RapierContext,
coordinates: HashSet<IVec2>, coordinates: HashSet<IVec2>,
visible: &Query<(Entity, &GlobalTransform, &Collider, &Visible)>, visible: &Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) { ) {
self.retain(|k, _| !coordinates.contains(k)); self.retain(|k, _| !coordinates.contains(k));
let shape = Collider::rectangle(0.98, 0.98); let shape = Collider::cuboid(0.49, 0.49);
for coords in &coordinates { for coords in &coordinates {
let shape_pos = Vec2::new(coords.x as f32 + 0.5, coords.y as f32 + 0.5); let shape_pos = Vec2::new(coords.x as f32 + 0.5, coords.y as f32 + 0.5);
let mut opacity = 0; let mut opacity = 0;
let mut coord_entities = HashSet::new(); let mut coord_entities = HashSet::new();
spatial_query.shape_intersections_callback( rapier_context.intersections_with_shape(shape_pos, 0., &shape, default(), |entity| {
&shape,
shape_pos,
0.,
&default(),
|entity| {
if let Ok((_, _, _, visible)) = visible.get(entity) { if let Ok((_, _, _, visible)) = visible.get(entity) {
coord_entities.insert(entity); coord_entities.insert(entity);
opacity = opacity.max(**visible); opacity = opacity.max(**visible);
} }
true true
}, });
);
self.insert(*coords, (opacity, coord_entities)); self.insert(*coords, (opacity, coord_entities));
} }
} }
@ -183,19 +171,15 @@ impl OpacityMap {
fn update_opacity_map( fn update_opacity_map(
mut opacity_map: ResMut<OpacityMap>, mut opacity_map: ResMut<OpacityMap>,
spatial_query: SpatialQuery, rapier_context: Res<RapierContext>,
query: Query< query: Query<
(Entity, &GlobalTransform, &ColliderAabb, &Visible), (Entity, &GlobalTransform, &Collider, &Visible),
Or<( Or<(Changed<GlobalTransform>, Changed<Visible>)>,
Changed<GlobalTransform>,
Changed<ColliderAabb>,
Changed<Visible>,
)>,
>, >,
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>, visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) { ) {
let mut to_update = HashSet::new(); let mut to_update = HashSet::new();
for (entity, transform, aabb, _) in &query { for (entity, transform, collider, _) in &query {
// println!( // println!(
// "Updating {entity} at {:?}", // "Updating {entity} at {:?}",
// transform.translation().truncate().as_ivec2() // transform.translation().truncate().as_ivec2()
@ -209,13 +193,18 @@ fn update_opacity_map(
} }
let mut current = HashSet::new(); let mut current = HashSet::new();
current.insert(transform.translation().truncate().as_ivec2()); current.insert(transform.translation().truncate().as_ivec2());
for x in aabb.min.x as i32..aabb.max.x as i32 { let position = Isometry2::new(
for y in aabb.min.y as i32..aabb.max.y as i32 { transform.translation().truncate().into(),
transform.yaw().as_radians(),
);
let aabb = collider.raw.compute_aabb(&position);
for x in aabb.mins.x as i32..aabb.maxs.x as i32 {
for y in aabb.mins.y as i32..aabb.maxs.y as i32 {
// println!( // println!(
// "Also updating coordinates at {:?}", // "Also updating coordinates at {:?}",
// IVec2::new(x as i32, y as i32) // IVec2::new(x as i32, y as i32)
// ); // );
current.insert(IVec2::new(x, y)); current.insert(IVec2::new(x as i32, y as i32));
} }
} }
if prev != current { if prev != current {
@ -223,12 +212,27 @@ fn update_opacity_map(
to_update.extend(current); to_update.extend(current);
} }
} }
opacity_map.update(&spatial_query, to_update, &visible); opacity_map.update(&rapier_context, to_update, &visible);
} }
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)] #[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct VisibleEntities(HashSet<Entity>); pub struct VisibleEntities(HashSet<Entity>);
#[derive(Bundle, Default)]
pub struct ViewshedBundle {
pub viewshed: Viewshed,
pub visible_entities: VisibleEntities,
}
impl ViewshedBundle {
pub fn new(range: u32) -> Self {
Self {
viewshed: Viewshed { range, ..default() },
..default()
}
}
}
#[derive(Event)] #[derive(Event)]
pub enum VisibilityChanged { pub enum VisibilityChanged {
Gained(Entity), Gained(Entity),
@ -272,7 +276,7 @@ fn viewshed_removed(
} }
} }
struct VisibilityGrid(Entity, IVec2, u32, OpacityMap); pub struct VisibilityGrid(pub (u32, u32), pub Entity, pub OpacityMap);
impl InputGrid for VisibilityGrid { impl InputGrid for VisibilityGrid {
type Grid = (u32, u32); type Grid = (u32, u32);
@ -285,12 +289,8 @@ impl InputGrid for VisibilityGrid {
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity { fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
// println!("Checking {coord:?}"); // println!("Checking {coord:?}");
let coord = IVec2::new(coord.x, coord.y); if let Some((opacity, entities)) = self.2.get(&IVec2::new(coord.x, coord.y)) {
if coord.distance(&self.1) > self.2 as f32 { if entities.len() == 1 && entities.contains(&self.1) {
return 0;
}
if let Some((opacity, entities)) = self.3.get(&coord) {
if entities.contains(&self.0) {
// println!("Hit viewer, 0"); // println!("Hit viewer, 0");
0 0
} else { } else {
@ -306,7 +306,7 @@ impl InputGrid for VisibilityGrid {
fn update_viewshed( fn update_viewshed(
mut commands: Commands, mut commands: Commands,
physics_time: Res<Time<Physics>>, config: Res<RapierConfiguration>,
mut viewers: Query<( mut viewers: Query<(
Entity, Entity,
&mut Viewshed, &mut Viewshed,
@ -315,9 +315,9 @@ fn update_viewshed(
)>, )>,
opacity_map: Res<OpacityMap>, opacity_map: Res<OpacityMap>,
sensors: Query<&Sensor>, sensors: Query<&Sensor>,
spatial_query: SpatialQuery, rapier_context: Res<RapierContext>,
) { ) {
if physics_time.is_paused() { if !config.query_pipeline_active {
return; return;
} }
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers { for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
@ -328,7 +328,7 @@ fn update_viewshed(
&viewer_transform.translation().truncate(), &viewer_transform.translation().truncate(),
&opacity_map, &opacity_map,
&sensors, &sensors,
&spatial_query, &*rapier_context,
); );
} }
} }
@ -343,7 +343,7 @@ fn remove_visible(
&GlobalTransform, &GlobalTransform,
)>, )>,
sensors: Query<&Sensor>, sensors: Query<&Sensor>,
spatial_query: SpatialQuery, rapier_context: Res<RapierContext>,
mut opacity_map: ResMut<OpacityMap>, mut opacity_map: ResMut<OpacityMap>,
visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>, visible: Query<(Entity, &GlobalTransform, &Collider, &Visible)>,
) { ) {
@ -356,7 +356,7 @@ fn remove_visible(
} }
} }
} }
opacity_map.update(&spatial_query, to_update, &visible); opacity_map.update(&rapier_context, to_update, &visible);
for removed in removed.read() { for removed in removed.read() {
for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers { for (viewer_entity, mut viewshed, mut visible_entities, start) in &mut viewers {
if !visible_entities.contains(&removed) { if !visible_entities.contains(&removed) {
@ -369,7 +369,7 @@ fn remove_visible(
&start.translation().truncate(), &start.translation().truncate(),
&opacity_map, &opacity_map,
&sensors, &sensors,
&spatial_query, &*rapier_context,
); );
} }
} }
@ -436,7 +436,10 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlu
impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> { impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlugin<MapData> {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.init_resource::<OpacityMap>() app.init_resource::<OpacityMap>()
.add_systems(FixedPreUpdate, update_opacity_map.before(update_viewshed)) .add_systems(
FixedPreUpdate,
update_opacity_map.before(update_viewshed),
)
.add_systems( .add_systems(
FixedPreUpdate, FixedPreUpdate,
( (
@ -446,6 +449,6 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlug
), ),
) )
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible)) .add_systems(FixedPostUpdate, (viewshed_removed, remove_visible))
.add_observer(log_visible); .observe(log_visible);
} }
} }