Compare commits

..

No commits in common. "fb34f6ef122decea4bafe2a0ca3afb4b98df9152" and "8eb050d10ad0e3f732cb0b95b7f03632e420113e" have entirely different histories.

2 changed files with 175 additions and 125 deletions

View File

@ -31,12 +31,11 @@ impl Default for SoundIcon {
fn added(mut commands: Commands, icons: Query<(Entity, &SoundIcon), Added<SoundIcon>>) { fn added(mut commands: Commands, icons: Query<(Entity, &SoundIcon), Added<SoundIcon>>) {
for (entity, icon) in &icons { for (entity, icon) in &icons {
if let Some(mut commands) = commands.get_entity(entity) {
let buffer = icon.audio.clone(); let buffer = icon.audio.clone();
let gain = icon.gain; let gain = icon.gain;
let pitch = icon.pitch; let pitch = icon.pitch;
let looping = icon.interval.is_none(); let looping = icon.interval.is_none();
commands.insert(Sound { commands.entity(entity).insert(Sound {
audio: buffer, audio: buffer,
gain, gain,
pitch, pitch,
@ -45,7 +44,6 @@ fn added(mut commands: Commands, icons: Query<(Entity, &SoundIcon), Added<SoundI
..default() ..default()
}); });
} }
}
} }
fn update<S>( fn update<S>(

View File

@ -6,7 +6,10 @@ use std::{
use bevy::prelude::*; use bevy::prelude::*;
use bevy_rapier2d::{na::Isometry2, parry::bounding_volume::BoundingVolume}; use bevy_rapier2d::{
na::{Isometry2, Vector2},
parry::bounding_volume::BoundingVolume,
};
use coord_2d::{Coord, Size}; use coord_2d::{Coord, Size};
use shadowcast::{vision_distance, Context, InputGrid}; use shadowcast::{vision_distance, Context, InputGrid};
@ -47,21 +50,30 @@ impl Viewshed {
fn update( fn update(
&mut self, &mut self,
commands: &mut Commands,
viewer_entity: &Entity, viewer_entity: &Entity,
visible_entities: &mut VisibleEntities, visible_entities: &mut VisibleEntities,
start: &Vec2, start: &GlobalTransform,
rapier_context: &RapierContext, rapier_context: &RapierContext,
visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>, visible_query: &Query<(&Visible, &Collider, &GlobalTransform)>,
cache: &mut RefCell<HashMap<(i32, i32), (u8, HashSet<Entity>)>>, events: &mut EventWriter<VisibilityChanged>,
cache: &mut HashMap<(i32, i32), (u8, HashSet<Entity>)>,
) { ) {
// println!("Start"); // println!("Start");
let mut boxes = vec![]; let mut boxes = vec![];
let shape = Collider::cuboid(self.range as f32, self.range as f32); let shape = Collider::cuboid(self.range as f32, self.range as f32);
rapier_context.intersections_with_shape(*start, 0., &shape, default(), |entity| { rapier_context.intersections_with_shape(
start.translation().truncate(),
0.,
&shape,
QueryFilter::new()
.exclude_collider(*viewer_entity)
.predicate(&|e| visible_query.contains(e)),
|entity| {
if let Ok((_, collider, transform)) = visible_query.get(entity) { if let Ok((_, collider, transform)) = visible_query.get(entity) {
let position = let position = Isometry2::new(
Isometry2::translation(transform.translation().x, transform.translation().y); Vector2::new(transform.translation().x, transform.translation().y),
0.,
);
// println!( // println!(
// "Hit {:?}, pushing {:?}", // "Hit {:?}, pushing {:?}",
// entity, // entity,
@ -70,84 +82,102 @@ impl Viewshed {
boxes.push(collider.raw.compute_aabb(&position)); boxes.push(collider.raw.compute_aabb(&position));
} }
true true
}); },
);
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);
let shape = Collider::cuboid(0.49, 0.49); let shape = Collider::cuboid(0.49, 0.49);
let mut new_visible_entities = HashSet::new();
let size = ( let size = (
(start.x.abs() + self.range as f32 * 2.) as u32, (start.translation().x.abs() + self.range as f32) as u32,
(start.y.abs() + self.range as f32 * 2.) as u32, (start.translation().y.abs() + self.range as f32) as u32,
); );
let visibility_grid = VisibilityGrid( let visibility_grid = VisibilityGrid(
size, size,
RefCell::new(Box::new(|coord: Coord| { RefCell::new(Box::new(|coord: Coord| {
let shape_pos = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5); let shape_pos = Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5);
// println!("Checking {coord:?}: {shape_pos:?}"); // println!("Checking {:?}", shape_pos);
if start.distance(&shape_pos) > self.range as f32 { if start.distance(&shape_pos) > self.range as f32 {
// println!("Out of range"); // println!("Out of range");
return u8::MAX; return u8::MAX;
} }
let mut coord_entities = HashSet::new(); let result = if let Some((opacity, coord_entities)) = cache.get(&(coord.x, coord.y))
let mut to_insert = None;
let opacity = if let Some((opacity, entities)) =
cache.borrow().get(&(coord.x, coord.y))
{ {
// println!("Cache hit: {opacity:?}: {entities:?}"); Some((*opacity, coord_entities.clone()))
coord_entities = entities.clone();
*opacity
} else { } else {
let position = Isometry2::translation(shape_pos.x, shape_pos.y); let position = Isometry2::new(Vector2::new(shape_pos.x, shape_pos.y), 0.);
let aabb = shape.raw.compute_aabb(&position); let aabb = shape.raw.compute_aabb(&position);
if boxes.iter().any(|b| b.intersects(&aabb)) { let mut hit = false;
// println!("Hit"); for b in &boxes {
if b.intersects(&aabb) {
// println!("Hit at {:?}", b);
hit = true;
break;
}
}
if hit {
// println!("Hit test");
let mut opacity = 0; let mut opacity = 0;
let mut coord_entities = HashSet::new();
rapier_context.intersections_with_shape( rapier_context.intersections_with_shape(
shape_pos, shape_pos,
0., 0.,
&shape, &shape,
default(), QueryFilter::new()
.exclude_collider(*viewer_entity)
.predicate(&|v| visible_query.contains(v)),
|entity| { |entity| {
if let Ok((visible, _, _)) = visible_query.get(entity) { // println!("{:?}", entity);
// println!(
// "{entity:?}: {visible:?}: {:?}",
// transform.translation().truncate()
// );
coord_entities.insert(entity); coord_entities.insert(entity);
if let Ok((visible, _, _)) = visible_query.get(entity) {
opacity = opacity.max(**visible); opacity = opacity.max(**visible);
} }
true true
}, },
); );
to_insert = Some(((coord.x, coord.y), (opacity, coord_entities.clone()))); cache.insert((coord.x, coord.y), (opacity, coord_entities.clone()));
// println!("New opacity: {opacity}"); Some((opacity, coord_entities))
opacity
} else { } else {
// println!("No hits, 0"); // println!("No hits, 0");
to_insert = Some(((coord.x, coord.y), default())); let coord_entities = HashSet::new();
0 cache.insert((coord.x, coord.y), (0, coord_entities.clone()));
Some((0, coord_entities))
} }
}; };
if let Some((k, v)) = to_insert { if let Some((opacity, coord_entities)) = result {
cache.borrow_mut().insert(k, v); for e in &coord_entities {
let mut should_insert = true;
if coord_entities.len() > 1 {
let start = start.translation().truncate();
let dest = Vec2::new(coord.x as f32, coord.y as f32);
let dir = dest - start;
rapier_context.intersections_with_ray(
start,
dir,
1.,
true,
QueryFilter::new()
.exclude_sensors()
.exclude_collider(*viewer_entity)
.exclude_collider(*e)
.predicate(&|e| visible_query.contains(e)),
|_, _| {
should_insert = false;
false
},
);
}
if should_insert {
new_visible_entities.insert(*e);
}
} }
if coord_entities.contains(&viewer_entity) {
let mut coord_entities = coord_entities.clone();
coord_entities.retain(|e| e != viewer_entity);
let opacity = coord_entities
.iter()
.map(|v| visible_query.get(*v).unwrap().0 .0)
.max()
.unwrap_or(0);
// println!("Viewer hit, removing viewer opacity: {opacity}");
opacity opacity
} else { } else {
opacity 0
} }
})), })),
); );
let mut new_visible = HashSet::new(); let mut new_visible = HashSet::new();
let mut new_visible_entities = HashSet::new();
// println!("Start: {viewer_entity}");
context.for_each_visible( context.for_each_visible(
Coord::new(start.x_i32(), start.y_i32()), Coord::new(start.x_i32(), start.y_i32()),
&visibility_grid, &visibility_grid,
@ -156,11 +186,6 @@ impl Viewshed {
u8::MAX, u8::MAX,
|coord, _directions, _visibility| { |coord, _directions, _visibility| {
new_visible.insert((coord.x, coord.y)); new_visible.insert((coord.x, coord.y));
if let Some((_, entities)) = cache.borrow().get(&(coord.x, coord.y)) {
for e in entities {
new_visible_entities.insert(*e);
}
}
}, },
); );
if self.visible_points != new_visible { if self.visible_points != new_visible {
@ -168,12 +193,17 @@ 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) {
commands.trigger_targets(VisibilityChanged::Lost(*lost), *viewer_entity); events.send(VisibilityChanged::Lost {
viewer: *viewer_entity,
viewed: *lost,
});
} }
for gained in new_visible_entities.difference(visible_entities) { for gained in new_visible_entities.difference(visible_entities) {
// println!("transition: {:?} gains {:?}", viewer_entity, // println!("transition: {:?} gains {:?}", viewer_entity, gained);
// gained); events.send(VisibilityChanged::Gained {
commands.trigger_targets(VisibilityChanged::Gained(*gained), *viewer_entity); viewer: *viewer_entity,
viewed: *gained,
});
} }
**visible_entities = new_visible_entities; **visible_entities = new_visible_entities;
} }
@ -220,8 +250,8 @@ impl ViewshedBundle {
#[derive(Event)] #[derive(Event)]
pub enum VisibilityChanged { pub enum VisibilityChanged {
Gained(Entity), Gained { viewer: Entity, viewed: Entity },
Lost(Entity), Lost { viewer: Entity, viewed: Entity },
} }
impl PointLike for Coord { impl PointLike for Coord {
@ -248,14 +278,17 @@ fn add_visibility_indices<MapData: 'static + Clone + Default + Send + Sync>(
} }
fn viewshed_removed( fn viewshed_removed(
mut commands: Commands,
mut query: RemovedComponents<Viewshed>, mut query: RemovedComponents<Viewshed>,
visible_entities: Query<&VisibleEntities>, visible_entities: Query<&VisibleEntities>,
mut events: EventWriter<VisibilityChanged>,
) { ) {
for entity in query.read() { for entity in query.read() {
if let Ok(visible) = visible_entities.get(entity) { if let Ok(visible) = visible_entities.get(entity) {
for e in visible.iter() { for e in visible.iter() {
commands.trigger_targets(VisibilityChanged::Lost(*e), entity); events.send(VisibilityChanged::Lost {
viewer: entity,
viewed: *e,
});
} }
} }
} }
@ -281,7 +314,6 @@ where
} }
fn update_viewshed( fn update_viewshed(
mut commands: Commands,
config: Res<RapierConfiguration>, config: Res<RapierConfiguration>,
visible: Query<(&Visible, &Collider, &GlobalTransform)>, visible: Query<(&Visible, &Collider, &GlobalTransform)>,
mut viewers: Query<( mut viewers: Query<(
@ -291,26 +323,26 @@ fn update_viewshed(
&GlobalTransform, &GlobalTransform,
)>, )>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
mut changed: EventWriter<VisibilityChanged>,
) { ) {
if !config.query_pipeline_active { if !config.query_pipeline_active {
return; return;
} }
let mut cache = default(); let mut cache = HashMap::new();
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 {
viewshed.update( viewshed.update(
&mut commands,
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&viewer_transform.translation().truncate(), viewer_transform,
&rapier_context, &rapier_context,
&visible, &visible,
&mut changed,
&mut cache, &mut cache,
); );
} }
} }
fn remove_visible( fn remove_visible(
mut commands: Commands,
mut removed: RemovedComponents<Visible>, mut removed: RemovedComponents<Visible>,
mut viewers: Query<( mut viewers: Query<(
Entity, Entity,
@ -320,21 +352,23 @@ fn remove_visible(
)>, )>,
rapier_context: Res<RapierContext>, rapier_context: Res<RapierContext>,
visible: Query<(&Visible, &Collider, &GlobalTransform)>, visible: Query<(&Visible, &Collider, &GlobalTransform)>,
mut changed: EventWriter<VisibilityChanged>,
) { ) {
if !removed.is_empty() { if !removed.is_empty() {
let mut cache = default(); let mut cache = HashMap::new();
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) {
continue; continue;
} }
visible_entities.remove(&removed);
viewshed.update( viewshed.update(
&mut commands,
&viewer_entity, &viewer_entity,
&mut visible_entities, &mut visible_entities,
&start.translation().truncate(), start,
&rapier_context, &rapier_context,
&visible, &visible,
&mut changed,
&mut cache, &mut cache,
); );
} }
@ -360,18 +394,28 @@ fn update_revealed_tiles<D: 'static + Clone + Default + Send + Sync>(
} }
fn log_visible( fn log_visible(
trigger: Trigger<VisibilityChanged>, time: Res<Time>,
viewers: Query<(&GlobalTransform, Option<&Collider>), (With<Player>, With<Viewshed>)>, mut recently_lost: Local<HashMap<Entity, Timer>>,
visible: Query<(&Name, &GlobalTransform, Option<&Collider>), Without<DontLogWhenVisible>>, mut events: EventReader<VisibilityChanged>,
mut log: Query<&mut Log>, mut log: Query<&mut Log>,
viewers: Query<(Entity, &GlobalTransform, Option<&Collider>), (With<Player>, With<Viewshed>)>,
visible: Query<(&Name, &GlobalTransform, Option<&Collider>), Without<DontLogWhenVisible>>,
) { ) {
if let VisibilityChanged::Gained(entity) = trigger.event() { for timer in recently_lost.values_mut() {
if *entity == trigger.entity() { timer.tick(time.delta());
return;
} }
if let Ok((viewer_transform, viewer_collider)) = viewers.get(trigger.entity()) { recently_lost.retain(|_entity, timer| !timer.finished());
if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*entity) { for event in events.read() {
// println!("Gain {name}: {entity}"); let viewer = match event {
VisibilityChanged::Gained { viewer, .. } => viewer,
VisibilityChanged::Lost { viewer, .. } => viewer,
};
if let Ok((viewer_entity, viewer_transform, viewer_collider)) = viewers.get(*viewer) {
if let VisibilityChanged::Gained { viewed, .. } = event {
if *viewed == viewer_entity || recently_lost.contains_key(viewed) {
continue;
}
if let Ok((name, viewed_transform, viewed_collider)) = visible.get(*viewed) {
let location = if let (Some(viewer_collider), Some(viewed_collider)) = let location = if let (Some(viewer_collider), Some(viewed_collider)) =
(viewer_collider, viewed_collider) (viewer_collider, viewed_collider)
{ {
@ -388,10 +432,15 @@ fn log_visible(
log.push(format!("{}: {location}", name)); log.push(format!("{}: {location}", name));
} }
} }
} else if let VisibilityChanged::Lost { viewed, .. } = event {
recently_lost.insert(*viewed, Timer::from_seconds(2., TimerMode::Once));
}
} }
} }
} }
pub const LOG_VISIBLE_LABEL: &str = "LOG_VISIBLE";
pub struct VisibilityPlugin<MapData: 'static + Clone + Default + Send + Sync>(PhantomData<MapData>); pub struct VisibilityPlugin<MapData: 'static + Clone + Default + Send + Sync>(PhantomData<MapData>);
impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlugin<MapData> { impl<MapData: 'static + Clone + Default + Send + Sync> Default for VisibilityPlugin<MapData> {
@ -402,7 +451,8 @@ 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.add_systems( app.add_event::<VisibilityChanged>()
.add_systems(
FixedPreUpdate, FixedPreUpdate,
( (
add_visibility_indices::<MapData>, add_visibility_indices::<MapData>,
@ -410,7 +460,9 @@ impl<MapData: 'static + Clone + Default + Send + Sync> Plugin for VisibilityPlug
update_revealed_tiles::<MapData>, update_revealed_tiles::<MapData>,
), ),
) )
.add_systems(FixedPostUpdate, (viewshed_removed, remove_visible)) .add_systems(
.observe(log_visible); FixedPostUpdate,
(log_visible, viewshed_removed, remove_visible),
);
} }
} }