WIP: Refactor to Avian.
This commit is contained in:
parent
fb34f6ef12
commit
7c7504834f
|
@ -14,8 +14,8 @@ speech_dispatcher_0_10 = ["bevy_tts/speech_dispatcher_0_10"]
|
|||
speech_dispatcher_0_11 = ["bevy_tts/speech_dispatcher_0_11"]
|
||||
|
||||
[dependencies]
|
||||
avian2d = "0.1"
|
||||
bevy = "0.14"
|
||||
bevy_rapier2d = "0.27"
|
||||
bevy_synthizer = "0.7"
|
||||
bevy_tts = { version = "0.9", default-features = false, features = ["tolk"] }
|
||||
coord_2d = "0.3"
|
||||
|
|
34
src/core.rs
34
src/core.rs
|
@ -6,12 +6,14 @@ use std::{
|
|||
sync::RwLock,
|
||||
};
|
||||
|
||||
use bevy::{app::PluginGroupBuilder, math::FloatOrd, prelude::*};
|
||||
use bevy_rapier2d::{
|
||||
parry::query::{closest_points, distance, ClosestPoints},
|
||||
use avian2d::{
|
||||
parry::{
|
||||
math::Isometry,
|
||||
query::{closest_points, distance, ClosestPoints},
|
||||
},
|
||||
prelude::*,
|
||||
rapier::{math::Isometry, prelude::Aabb},
|
||||
};
|
||||
use bevy::{app::PluginGroupBuilder, math::FloatOrd, prelude::*};
|
||||
use once_cell::sync::Lazy;
|
||||
use rand::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
@ -530,7 +532,14 @@ impl GlobalTransformExt for GlobalTransform {
|
|||
(other.translation() / *scale).xy().into(),
|
||||
other.yaw().radians(),
|
||||
);
|
||||
closest_points(&pos1, &*collider.raw, &pos2, &*other_collider.raw, f32::MAX).unwrap()
|
||||
closest_points(
|
||||
&pos1,
|
||||
collider.shape().as_ref(),
|
||||
&pos2,
|
||||
other_collider.shape().as_ref(),
|
||||
f32::MAX,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn collider_direction_and_distance(
|
||||
|
@ -549,7 +558,13 @@ impl GlobalTransformExt for GlobalTransform {
|
|||
other.yaw().radians(),
|
||||
);
|
||||
let closest = self.closest_points(collider, other, other_collider);
|
||||
let distance = distance(&pos1, &*collider.raw, &pos2, &*other_collider.raw).unwrap() as u32;
|
||||
let distance = distance(
|
||||
&pos1,
|
||||
collider.shape().as_ref(),
|
||||
&pos2,
|
||||
other_collider.shape().as_ref(),
|
||||
)
|
||||
.unwrap() as u32;
|
||||
let tile_or_tiles = if distance == 1 { "tile" } else { "tiles" };
|
||||
if distance > 0 {
|
||||
if let ClosestPoints::WithinMargin(p1, p2) = closest {
|
||||
|
@ -568,9 +583,6 @@ impl GlobalTransformExt for GlobalTransform {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Component, Copy, Clone, Debug, Deref, DerefMut, PartialEq)]
|
||||
pub struct Area(pub Aabb);
|
||||
|
||||
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
|
||||
#[reflect(Component)]
|
||||
pub struct Player;
|
||||
|
@ -676,9 +688,7 @@ impl Plugin for CorePlugin {
|
|||
};
|
||||
app.insert_resource(config)
|
||||
.register_type::<CardinalDirection>()
|
||||
.add_plugins(RapierPhysicsPlugin::<NoUserData>::pixels_per_meter(
|
||||
config.pixels_per_unit as f32,
|
||||
))
|
||||
.add_plugins(PhysicsPlugins::default().with_length_unit(config.pixels_per_unit as f32))
|
||||
.add_systems(Startup, setup)
|
||||
.add_systems(Update, sync_config);
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
use std::{error::Error, fmt::Debug, hash::Hash, marker::PhantomData};
|
||||
|
||||
use avian2d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
use bevy_rapier2d::prelude::*;
|
||||
use bevy_tts::Tts;
|
||||
use leafwing_input_manager::prelude::*;
|
||||
|
||||
|
@ -281,7 +281,7 @@ fn exploration_changed_announcement<ExplorationType, MapData>(
|
|||
names: Query<&Name>,
|
||||
types: Query<&ExplorationType>,
|
||||
mappables: Query<&Mappable>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
spatial_query: SpatialQuery,
|
||||
) -> Result<(), Box<dyn Error>>
|
||||
where
|
||||
ExplorationType: Component + Copy + Into<String>,
|
||||
|
@ -290,7 +290,7 @@ where
|
|||
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
|
||||
let coordinates = coordinates.trunc();
|
||||
let point = **exploring;
|
||||
let shape = Collider::cuboid(0.5 - f32::EPSILON, 0.5 - f32::EPSILON);
|
||||
let shape = Collider::rectangle(0.5 - f32::EPSILON, 0.5 - f32::EPSILON);
|
||||
let (known, idx) = if let Ok((map, revealed_tiles)) = map.get_single() {
|
||||
let idx = point.to_index(map.width);
|
||||
(revealed_tiles[idx], Some(idx))
|
||||
|
@ -305,20 +305,22 @@ where
|
|||
commands.entity(entity).remove::<ExplorationFocused>();
|
||||
}
|
||||
let exploring = Vec2::new(exploring.x(), exploring.y());
|
||||
rapier_context.intersections_with_shape(
|
||||
spatial_query.shape_intersections_callback(
|
||||
&shape,
|
||||
exploring,
|
||||
0.,
|
||||
&shape,
|
||||
QueryFilter::new().predicate(&|v| explorable.get(v).is_ok()),
|
||||
SpatialQueryFilter::default(),
|
||||
|entity| {
|
||||
commands.entity(entity).insert(ExplorationFocused);
|
||||
if visible || mappables.get(entity).is_ok() {
|
||||
if let Ok(name) = names.get(entity) {
|
||||
tokens.push(name.to_string());
|
||||
}
|
||||
if tokens.is_empty() {
|
||||
if let Ok(t) = types.get(entity) {
|
||||
tokens.push((*t).into());
|
||||
if explorable.contains(entity) {
|
||||
commands.entity(entity).insert(ExplorationFocused);
|
||||
if visible || mappables.get(entity).is_ok() {
|
||||
if let Ok(name) = names.get(entity) {
|
||||
tokens.push(name.to_string());
|
||||
}
|
||||
if tokens.is_empty() {
|
||||
if let Ok(t) = types.get(entity) {
|
||||
tokens.push((*t).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -2,8 +2,8 @@
|
|||
#![allow(clippy::too_many_arguments)]
|
||||
#![allow(clippy::type_complexity)]
|
||||
|
||||
pub use avian2d;
|
||||
pub use bevy;
|
||||
pub use bevy_rapier2d;
|
||||
pub use bevy_synthizer;
|
||||
pub use bevy_tts;
|
||||
pub use coord_2d;
|
||||
|
|
39
src/map.rs
39
src/map.rs
|
@ -1,20 +1,13 @@
|
|||
use std::marker::PhantomData;
|
||||
|
||||
use avian2d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
use bevy_rapier2d::{
|
||||
na::{Isometry2, Vector2},
|
||||
prelude::*,
|
||||
};
|
||||
pub use here_be_dragons::Map as MapgenMap;
|
||||
use here_be_dragons::{geometry::Rect as MRect, MapFilter, Tile};
|
||||
use maze_generator::{prelude::*, recursive_backtracking::RbGenerator};
|
||||
use rand::prelude::StdRng;
|
||||
|
||||
use crate::{
|
||||
core::{Area, PointLike},
|
||||
exploration::Mappable,
|
||||
visibility::Visible,
|
||||
};
|
||||
use crate::{core::PointLike, exploration::Mappable, visibility::Visible};
|
||||
|
||||
#[derive(Component, Clone, Default, Deref, DerefMut)]
|
||||
pub struct Map<D: 'static + Clone + Default + Send + Sync>(pub MapgenMap<D>);
|
||||
|
@ -80,9 +73,9 @@ impl ITileType for Tile {
|
|||
|
||||
#[derive(Bundle, Default)]
|
||||
pub struct PortalBundle {
|
||||
pub transform: TransformBundle,
|
||||
pub portal: Portal,
|
||||
pub mappable: Mappable,
|
||||
pub transform: TransformBundle,
|
||||
}
|
||||
|
||||
#[derive(Bundle, Clone, Default)]
|
||||
|
@ -98,7 +91,6 @@ pub struct TileBundle {
|
|||
pub transform: TransformBundle,
|
||||
pub collider: Collider,
|
||||
pub rigid_body: RigidBody,
|
||||
pub active_collision_types: ActiveCollisionTypes,
|
||||
pub map_obstruction: MapObstruction,
|
||||
}
|
||||
|
||||
|
@ -106,12 +98,9 @@ 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,
|
||||
collider: Collider::rectangle(0.5, 0.5),
|
||||
rigid_body: RigidBody::Static,
|
||||
map_obstruction: default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -129,34 +118,28 @@ impl TileBundle {
|
|||
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);
|
||||
fn new(collider: Collider, position: Vec2) -> Self {
|
||||
Self {
|
||||
collider,
|
||||
area: Area(aabb),
|
||||
transform: Transform::from_translation(Vec3::new(position.0, position.1, 0.)).into(),
|
||||
transform: Transform::from_translation(position.extend(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(
|
||||
let collider = Collider::rectangle(
|
||||
rect.width() as f32 / 2. + 0.5,
|
||||
rect.height() as f32 / 2. + 0.5,
|
||||
);
|
||||
let position = (rect.center().x(), rect.center().y());
|
||||
let position = Vec2::new(rect.center().x(), rect.center().y());
|
||||
Self::new(collider, position)
|
||||
}
|
||||
}
|
||||
|
@ -332,7 +315,7 @@ fn spawn_portal_colliders<D: 'static + Clone + Default + Send + Sync>(
|
|||
for portal_entity in &portals {
|
||||
commands
|
||||
.entity(portal_entity)
|
||||
.insert((Collider::cuboid(0.5, 0.5), Sensor));
|
||||
.insert((Collider::rectangle(0.5, 0.5), Sensor));
|
||||
}
|
||||
commands.entity(entity).remove::<SpawnColliders>();
|
||||
}
|
||||
|
|
|
@ -1,14 +1,17 @@
|
|||
#![allow(clippy::map_entry)]
|
||||
|
||||
use std::{collections::HashMap, error::Error, f32::consts::PI, fmt::Debug, hash::Hash};
|
||||
|
||||
use avian2d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
use bevy_rapier2d::prelude::*;
|
||||
use bevy_tts::Tts;
|
||||
use leafwing_input_manager::prelude::*;
|
||||
|
||||
use crate::{
|
||||
core::{Angle, Area, CardinalDirection, GlobalTransformExt, Player, TransformExt},
|
||||
core::{Angle, CardinalDirection, GlobalTransformExt, Player, TransformExt},
|
||||
error::error_handler,
|
||||
log::Log,
|
||||
map::Zone,
|
||||
utils::target_and_other,
|
||||
};
|
||||
|
||||
|
@ -151,13 +154,14 @@ fn tick_snap_timers(time: Res<Time>, mut snap_timers: ResMut<SnapTimers>) {
|
|||
}
|
||||
|
||||
fn controls(
|
||||
rapier_context: Res<RapierContext>,
|
||||
spatial_query: SpatialQuery,
|
||||
time: Res<Time>,
|
||||
snap_timers: Res<SnapTimers>,
|
||||
sensors: Query<Entity, With<Sensor>>,
|
||||
mut query: Query<(
|
||||
Entity,
|
||||
&mut ActionState<NavigationAction>,
|
||||
&mut Velocity,
|
||||
&mut LinearVelocity,
|
||||
&Speed,
|
||||
Option<&RotationSpeed>,
|
||||
Option<&BackwardMovementFactor>,
|
||||
|
@ -212,24 +216,21 @@ fn controls(
|
|||
// println!("{entity:?}: SetLinearVelocity: {velocity:?}");
|
||||
actions.set_axis_pair(&NavigationAction::SetLinearVelocity, move_velocity);
|
||||
}
|
||||
if velocity.linvel != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
|
||||
velocity.linvel = actions.axis_pair(&NavigationAction::SetLinearVelocity);
|
||||
if velocity.0 != actions.axis_pair(&NavigationAction::SetLinearVelocity) {
|
||||
**velocity = actions.axis_pair(&NavigationAction::SetLinearVelocity);
|
||||
}
|
||||
if actions.axis_pair(&NavigationAction::Translate) != Vec2::ZERO {
|
||||
let pair = actions.axis_pair(&NavigationAction::Translate);
|
||||
if rapier_context
|
||||
let dir = Dir2::new_unchecked(pair.normalize());
|
||||
if spatial_query
|
||||
.cast_shape(
|
||||
collider,
|
||||
transform.translation.truncate(),
|
||||
transform.yaw().radians(),
|
||||
pair,
|
||||
collider,
|
||||
ShapeCastOptions {
|
||||
max_time_of_impact: 1.,
|
||||
..default()
|
||||
},
|
||||
QueryFilter::new()
|
||||
.exclude_sensors()
|
||||
.exclude_collider(entity),
|
||||
dir,
|
||||
1.,
|
||||
true,
|
||||
SpatialQueryFilter::from_excluded_entities(&sensors),
|
||||
)
|
||||
.is_none()
|
||||
{
|
||||
|
@ -302,18 +303,18 @@ fn speak_direction(
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn add_speed(mut commands: Commands, query: Query<Entity, (Added<Speed>, Without<Velocity>)>) {
|
||||
fn add_speed(
|
||||
mut commands: Commands,
|
||||
query: Query<Entity, (Added<Speed>, Without<LinearVelocity>)>,
|
||||
) {
|
||||
for entity in &query {
|
||||
commands.entity(entity).insert(Velocity {
|
||||
linvel: Vec2::ZERO,
|
||||
..default()
|
||||
});
|
||||
commands.entity(entity).insert(LinearVelocity::default());
|
||||
}
|
||||
}
|
||||
|
||||
fn log_area_descriptions<State>(
|
||||
mut events: EventReader<CollisionEvent>,
|
||||
areas: Query<(&Area, Option<&Name>)>,
|
||||
fn log_zone_descriptions<State>(
|
||||
mut events: EventReader<Collision>,
|
||||
zones: Query<(&ColliderAabb, Option<&Name>), With<Zone>>,
|
||||
players: Query<&Player>,
|
||||
config: Res<NavigationPlugin<State>>,
|
||||
mut log: Query<&mut Log>,
|
||||
|
@ -323,19 +324,21 @@ fn log_area_descriptions<State>(
|
|||
if !config.log_area_descriptions {
|
||||
return;
|
||||
}
|
||||
for event in events.read() {
|
||||
let (entity1, entity2, started) = match event {
|
||||
CollisionEvent::Started(collider1, collider2, _) => (collider1, collider2, true),
|
||||
CollisionEvent::Stopped(collider1, collider2, _) => (collider1, collider2, false),
|
||||
};
|
||||
if let Some((area, other)) = target_and_other(*entity1, *entity2, &|v| areas.get(v).is_ok())
|
||||
for Collision(contacts) in events.read() {
|
||||
let started = contacts.during_current_frame && !contacts.during_previous_frame;
|
||||
let stopped = !contacts.during_current_frame && contacts.during_previous_frame;
|
||||
if !started && !stopped {
|
||||
continue;
|
||||
}
|
||||
if let Some((area, other)) =
|
||||
target_and_other(contacts.entity1, contacts.entity2, &|v| zones.contains(v))
|
||||
{
|
||||
if players.get(other).is_ok() {
|
||||
if let Ok((aabb, area_name)) = areas.get(area) {
|
||||
if players.contains(other) {
|
||||
if let Ok((aabb, area_name)) = zones.get(area) {
|
||||
let name = if let Some(name) = area_name {
|
||||
Some(name.to_string())
|
||||
} else if config.describe_undescribed_areas {
|
||||
Some(format!("{}-by-{} area", aabb.extents().x, aabb.extents().y))
|
||||
Some(format!("{}-by-{} area", aabb.size().x, aabb.size().y))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
@ -400,7 +403,7 @@ where
|
|||
)
|
||||
.add_systems(
|
||||
PostUpdate,
|
||||
(remove_direction, log_area_descriptions::<State>),
|
||||
(remove_direction, log_zone_descriptions::<State>),
|
||||
);
|
||||
if !self.states.is_empty() {
|
||||
for state in &self.states {
|
||||
|
|
|
@ -1,19 +1,11 @@
|
|||
use bevy::{
|
||||
prelude::*,
|
||||
tasks::{futures_lite::future, prelude::*, Task},
|
||||
utils::HashMap,
|
||||
};
|
||||
use bevy_rapier2d::{
|
||||
na::{Isometry2, Vector2},
|
||||
prelude::*,
|
||||
rapier::prelude::{ColliderHandle, ColliderSet, QueryPipeline, RigidBodySet},
|
||||
};
|
||||
use avian2d::prelude::*;
|
||||
use bevy::{prelude::*, utils::HashMap};
|
||||
use leafwing_input_manager::{plugin::InputManagerSystem, prelude::*};
|
||||
use pathfinding::prelude::*;
|
||||
|
||||
use crate::{
|
||||
core::{PointLike, TransformExt},
|
||||
map::{Map, MapObstruction},
|
||||
map::Map,
|
||||
navigation::{NavigationAction, RotationSpeed, Speed},
|
||||
};
|
||||
|
||||
|
@ -26,9 +18,6 @@ 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)]
|
||||
#[reflect(Component)]
|
||||
pub struct Destination(pub (i32, i32));
|
||||
|
@ -93,182 +82,94 @@ pub fn find_path<D: 'static + Clone + Default + Send + Sync>(
|
|||
)
|
||||
}
|
||||
|
||||
fn find_path_for_shape(
|
||||
initiator: ColliderHandle,
|
||||
start: Transform,
|
||||
destination: Destination,
|
||||
cost_map: &Option<CostMap>,
|
||||
query_pipeline: QueryPipeline,
|
||||
collider_set: ColliderSet,
|
||||
rigid_body_set: RigidBodySet,
|
||||
shape: Collider,
|
||||
) -> Option<Path> {
|
||||
let path = astar(
|
||||
&start.i32(),
|
||||
|p| {
|
||||
let mut successors: Vec<((i32, i32), u32)> = vec![];
|
||||
let x = p.0;
|
||||
let y = p.1;
|
||||
let exits = vec![
|
||||
((x - 1, y), 1.),
|
||||
((x + 1, y), 1.),
|
||||
((x, y - 1), 1.),
|
||||
((x, y + 1), 1.),
|
||||
((x - 1, y - 1), 1.5),
|
||||
((x + 1, y - 1), 1.5),
|
||||
((x - 1, y + 1), 1.5),
|
||||
((x + 1, y + 1), 1.5),
|
||||
];
|
||||
for exit in &exits {
|
||||
let mut should_push = true;
|
||||
let dest = Isometry2::new(Vector2::new(exit.0 .0 as f32, exit.0 .1 as f32), 0.);
|
||||
if query_pipeline
|
||||
.intersection_with_shape(
|
||||
&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 should_push {
|
||||
let mut cost = exit.1 * 100.;
|
||||
if let Some(cost_map) = cost_map {
|
||||
if let Some(modifier) = cost_map.get(&(exit.0 .0, exit.0 .1)) {
|
||||
cost *= modifier;
|
||||
}
|
||||
}
|
||||
successors.push((exit.0, cost as u32));
|
||||
}
|
||||
}
|
||||
successors
|
||||
},
|
||||
|p| (p.distance_squared(&destination) * 100.) as u32,
|
||||
|p| *p == destination.i32(),
|
||||
);
|
||||
if let Some(path) = path {
|
||||
Some(Path(path.0))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn calculate_path(
|
||||
mut commands: Commands,
|
||||
rapier_context: Res<RapierContext>,
|
||||
obstructions: Query<&RapierColliderHandle, With<MapObstruction>>,
|
||||
query: Query<
|
||||
spatial_query: SpatialQuery,
|
||||
mut query: Query<
|
||||
(
|
||||
Entity,
|
||||
&RapierColliderHandle,
|
||||
&Destination,
|
||||
&Transform,
|
||||
&Collider,
|
||||
Option<&CostMap>,
|
||||
Option<&mut ActionState<NegotiatePathAction>>,
|
||||
),
|
||||
Changed<Destination>,
|
||||
>,
|
||||
) {
|
||||
for (entity, handle, destination, coordinates, shape, cost_map) in &query {
|
||||
trace
|
||||
!("{entity}: destination: {destination:?}");
|
||||
if coordinates.i32() == **destination {
|
||||
trace
|
||||
!("{entity}: remove1");
|
||||
for (entity, destination, start, collider, cost_map, actions) in &mut query {
|
||||
trace!("{entity}: destination: {destination:?}");
|
||||
if start.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()
|
||||
start.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(),
|
||||
start.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);
|
||||
if let Some(mut actions) = actions {
|
||||
trace!("{entity:?}: Disabling and resetting because no path");
|
||||
actions.disable();
|
||||
actions.reset_all();
|
||||
commands.entity(entity).remove::<Path>().remove::<NoPath>();
|
||||
let path = astar(
|
||||
&start.i32(),
|
||||
|p| {
|
||||
let mut successors: Vec<((i32, i32), u32)> = vec![];
|
||||
let x = p.0;
|
||||
let y = p.1;
|
||||
let exits = vec![
|
||||
((x - 1, y), 1.),
|
||||
((x + 1, y), 1.),
|
||||
((x, y - 1), 1.),
|
||||
((x, y + 1), 1.),
|
||||
((x - 1, y - 1), 1.5),
|
||||
((x + 1, y - 1), 1.5),
|
||||
((x - 1, y + 1), 1.5),
|
||||
((x + 1, y + 1), 1.5),
|
||||
];
|
||||
for exit in &exits {
|
||||
let mut should_push = true;
|
||||
if !spatial_query
|
||||
.shape_intersections(
|
||||
collider,
|
||||
start.translation.truncate(),
|
||||
start.yaw().radians(),
|
||||
SpatialQueryFilter::default(),
|
||||
)
|
||||
.is_empty()
|
||||
{
|
||||
should_push = false;
|
||||
}
|
||||
if should_push {
|
||||
let mut cost = exit.1 * 100.;
|
||||
if let Some(cost_map) = cost_map {
|
||||
if let Some(modifier) = cost_map.get(&(exit.0 .0, exit.0 .1)) {
|
||||
cost *= modifier;
|
||||
}
|
||||
}
|
||||
successors.push((exit.0, cost as u32));
|
||||
}
|
||||
}
|
||||
successors
|
||||
},
|
||||
|p| (p.distance_squared(&destination) * 100.) as u32,
|
||||
|p| *p == destination.i32(),
|
||||
);
|
||||
if let Some(path) = path {
|
||||
commands.entity(entity).insert(Path(path.0));
|
||||
} else {
|
||||
commands.entity(entity).insert(NoPath);
|
||||
if let Some(mut actions) = actions {
|
||||
trace!("{entity:?}: Disabling and resetting because no path");
|
||||
actions.disable();
|
||||
actions.reset_all();
|
||||
}
|
||||
commands.entity(entity).remove::<Calculating>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -276,10 +177,7 @@ fn poll_tasks(
|
|||
fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Destination>) {
|
||||
for entity in removed.read() {
|
||||
if let Some(mut commands) = commands.get_entity(entity) {
|
||||
commands
|
||||
.remove::<Calculating>()
|
||||
.remove::<Path>()
|
||||
.remove::<NoPath>();
|
||||
commands.remove::<Path>().remove::<NoPath>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -287,7 +185,7 @@ fn remove_destination(mut commands: Commands, mut removed: RemovedComponents<Des
|
|||
fn negotiate_path(
|
||||
mut commands: Commands,
|
||||
time: Res<Time>,
|
||||
physics_config: Res<RapierConfiguration>,
|
||||
spatial_query: SpatialQuery,
|
||||
mut query: Query<(
|
||||
Entity,
|
||||
Option<&mut ActionState<NegotiatePathAction>>,
|
||||
|
@ -298,11 +196,7 @@ fn negotiate_path(
|
|||
&Speed,
|
||||
Option<&RotationSpeed>,
|
||||
)>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
) {
|
||||
if !physics_config.physics_pipeline_active || !physics_config.query_pipeline_active {
|
||||
return;
|
||||
}
|
||||
for (
|
||||
entity,
|
||||
actions,
|
||||
|
@ -346,24 +240,19 @@ fn negotiate_path(
|
|||
"{entity:?}: Direction: {direction:?}, Distance: {}",
|
||||
(next - start).length()
|
||||
);
|
||||
if rapier_context
|
||||
if spatial_query
|
||||
.cast_shape(
|
||||
collider,
|
||||
start,
|
||||
transform.yaw().radians(),
|
||||
direction,
|
||||
collider,
|
||||
ShapeCastOptions {
|
||||
max_time_of_impact: 1.,
|
||||
..default()
|
||||
},
|
||||
QueryFilter::new()
|
||||
.exclude_sensors()
|
||||
.exclude_collider(entity),
|
||||
Dir2::new_unchecked(direction.normalize()),
|
||||
direction.length(),
|
||||
true,
|
||||
SpatialQueryFilter::default(),
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
trace
|
||||
!("{entity:?} is stuck");
|
||||
trace!("{entity:?} is stuck");
|
||||
// TODO: Remove when we have an actual character controller.
|
||||
next.x = next.x.trunc();
|
||||
next.y = next.y.trunc();
|
||||
|
@ -376,8 +265,7 @@ fn negotiate_path(
|
|||
transform.rotation = Quat::from_rotation_z(angle);
|
||||
}
|
||||
} else {
|
||||
trace
|
||||
!("{entity:?}: empty path, cleaning");
|
||||
trace!("{entity:?}: empty path, cleaning");
|
||||
if let Some(mut actions) = actions {
|
||||
trace!("{entity:?}: Disabling pathfind because at destination");
|
||||
actions.reset_all();
|
||||
|
@ -421,8 +309,7 @@ fn actions(
|
|||
*current_dest = dest;
|
||||
}
|
||||
} else {
|
||||
trace
|
||||
!("{entity:?}: Adding destination, zeroing velocity");
|
||||
trace!("{entity:?}: Adding destination, zeroing velocity");
|
||||
navigation_action.set_axis_pair(&NavigationAction::SetLinearVelocity, Vec2::ZERO);
|
||||
commands.entity(entity).insert(dest);
|
||||
}
|
||||
|
@ -439,7 +326,7 @@ impl Plugin for PathfindingPlugin {
|
|||
.register_type::<NoPath>()
|
||||
.register_type::<Path>()
|
||||
.register_type::<CostMap>()
|
||||
.add_systems(PreUpdate, (poll_tasks, negotiate_path).chain())
|
||||
.add_systems(PreUpdate, negotiate_path)
|
||||
.add_systems(
|
||||
PreUpdate,
|
||||
(actions, calculate_path)
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
use avian2d::{parry::query::ClosestPoints, prelude::*};
|
||||
use bevy::{prelude::*, transform::TransformSystem};
|
||||
use bevy_rapier2d::{parry::query::ClosestPoints, prelude::*};
|
||||
use bevy_synthizer::{Listener, Sound};
|
||||
|
||||
use crate::core::GlobalTransformExt;
|
||||
|
|
|
@ -4,14 +4,12 @@ use std::{
|
|||
marker::PhantomData,
|
||||
};
|
||||
|
||||
use avian2d::prelude::*;
|
||||
use bevy::prelude::*;
|
||||
|
||||
use bevy_rapier2d::{na::Isometry2, parry::bounding_volume::BoundingVolume};
|
||||
use coord_2d::{Coord, Size};
|
||||
use shadowcast::{vision_distance, Context, InputGrid};
|
||||
|
||||
use crate::{
|
||||
bevy_rapier2d::prelude::*,
|
||||
core::{GlobalTransformExt, Player, PointLike},
|
||||
log::Log,
|
||||
map::{Map, MapPlugin},
|
||||
|
@ -51,29 +49,22 @@ impl Viewshed {
|
|||
viewer_entity: &Entity,
|
||||
visible_entities: &mut VisibleEntities,
|
||||
start: &Vec2,
|
||||
rapier_context: &RapierContext,
|
||||
spatial_query: &SpatialQuery,
|
||||
visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
cache: &mut RefCell<HashMap<(i32, i32), (u8, HashSet<Entity>)>>,
|
||||
) {
|
||||
// println!("Start");
|
||||
let mut boxes = vec![];
|
||||
let shape = Collider::cuboid(self.range as f32, self.range as f32);
|
||||
rapier_context.intersections_with_shape(*start, 0., &shape, default(), |entity| {
|
||||
let shape = Collider::rectangle(self.range as f32, self.range as f32);
|
||||
spatial_query.shape_intersections_callback(&shape, *start, 0., default(), |entity| {
|
||||
if let Ok((_, collider, transform)) = visible_query.get(entity) {
|
||||
let position =
|
||||
Isometry2::translation(transform.translation().x, transform.translation().y);
|
||||
// println!(
|
||||
// "Hit {:?}, pushing {:?}",
|
||||
// entity,
|
||||
// collider.raw.compute_aabb(&position)
|
||||
// );
|
||||
boxes.push(collider.raw.compute_aabb(&position));
|
||||
boxes.push(collider.aabb(transform.translation().truncate(), 0.));
|
||||
}
|
||||
true
|
||||
});
|
||||
let mut context: Context<u8> = Context::default();
|
||||
let vision_distance = vision_distance::Circle::new(self.range);
|
||||
let shape = Collider::cuboid(0.49, 0.49);
|
||||
let shape = Collider::rectangle(0.49, 0.49);
|
||||
let size = (
|
||||
(start.x.abs() + self.range as f32 * 2.) as u32,
|
||||
(start.y.abs() + self.range as f32 * 2.) as u32,
|
||||
|
@ -96,15 +87,14 @@ impl Viewshed {
|
|||
coord_entities = entities.clone();
|
||||
*opacity
|
||||
} else {
|
||||
let position = Isometry2::translation(shape_pos.x, shape_pos.y);
|
||||
let aabb = shape.raw.compute_aabb(&position);
|
||||
let aabb = shape.aabb(shape_pos, 0.);
|
||||
if boxes.iter().any(|b| b.intersects(&aabb)) {
|
||||
// println!("Hit");
|
||||
let mut opacity = 0;
|
||||
rapier_context.intersections_with_shape(
|
||||
spatial_query.shape_intersections_callback(
|
||||
&shape,
|
||||
shape_pos,
|
||||
0.,
|
||||
&shape,
|
||||
default(),
|
||||
|entity| {
|
||||
if let Ok((visible, _, _)) = visible_query.get(entity) {
|
||||
|
@ -130,7 +120,7 @@ impl Viewshed {
|
|||
if let Some((k, v)) = to_insert {
|
||||
cache.borrow_mut().insert(k, v);
|
||||
}
|
||||
if coord_entities.contains(&viewer_entity) {
|
||||
if coord_entities.contains(viewer_entity) {
|
||||
let mut coord_entities = coord_entities.clone();
|
||||
coord_entities.retain(|e| e != viewer_entity);
|
||||
let opacity = coord_entities
|
||||
|
@ -282,7 +272,6 @@ where
|
|||
|
||||
fn update_viewshed(
|
||||
mut commands: Commands,
|
||||
config: Res<RapierConfiguration>,
|
||||
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
mut viewers: Query<(
|
||||
Entity,
|
||||
|
@ -290,11 +279,8 @@ fn update_viewshed(
|
|||
&mut VisibleEntities,
|
||||
&GlobalTransform,
|
||||
)>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
spatial_query: SpatialQuery,
|
||||
) {
|
||||
if !config.query_pipeline_active {
|
||||
return;
|
||||
}
|
||||
let mut cache = default();
|
||||
for (viewer_entity, mut viewshed, mut visible_entities, viewer_transform) in &mut viewers {
|
||||
viewshed.update(
|
||||
|
@ -302,7 +288,7 @@ fn update_viewshed(
|
|||
&viewer_entity,
|
||||
&mut visible_entities,
|
||||
&viewer_transform.translation().truncate(),
|
||||
&rapier_context,
|
||||
&spatial_query,
|
||||
&visible,
|
||||
&mut cache,
|
||||
);
|
||||
|
@ -318,7 +304,7 @@ fn remove_visible(
|
|||
&mut VisibleEntities,
|
||||
&GlobalTransform,
|
||||
)>,
|
||||
rapier_context: Res<RapierContext>,
|
||||
spatial_query: SpatialQuery,
|
||||
visible: Query<(&Visible, &Collider, &GlobalTransform)>,
|
||||
) {
|
||||
if !removed.is_empty() {
|
||||
|
@ -333,7 +319,7 @@ fn remove_visible(
|
|||
&viewer_entity,
|
||||
&mut visible_entities,
|
||||
&start.translation().truncate(),
|
||||
&rapier_context,
|
||||
&spatial_query,
|
||||
&visible,
|
||||
&mut cache,
|
||||
);
|
||||
|
|
Loading…
Reference in New Issue
Block a user