blackout/src/visibility.rs

421 lines
13 KiB
Rust
Raw Normal View History

2021-09-28 17:49:44 +00:00
use std::{
cell::RefCell,
collections::{HashMap, HashSet},
};
2021-05-13 17:25:45 +00:00
2021-09-28 19:36:21 +00:00
use bevy::{core::FixedTimestep, prelude::*};
2021-09-28 17:49:44 +00:00
use bevy_rapier2d::{na, na::UnitComplex};
2021-05-13 17:25:45 +00:00
use coord_2d::{Coord, Size};
use derive_more::{Deref, DerefMut};
use shadowcast::{vision_distance, Context, InputGrid};
use crate::{
bevy_rapier2d::prelude::*,
2021-05-16 22:24:26 +00:00
core::{Angle, Coordinates, Player, PointLike},
2021-05-13 17:25:45 +00:00
log::Log,
map::{ITileType, Map, MapConfig},
utils::target_and_other,
2021-05-13 17:25:45 +00:00
};
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct DontLogWhenVisible;
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Debug, Default, Deref, DerefMut, Reflect)]
2021-05-13 17:25:45 +00:00
#[reflect(Component)]
pub struct RevealedTiles(pub Vec<bool>);
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Debug, Eq, PartialEq)]
2021-05-13 17:25:45 +00:00
pub struct Viewshed {
pub range: u32,
pub visible_points: HashSet<(i32, i32)>,
2021-05-13 17:25:45 +00:00
}
impl Default for Viewshed {
fn default() -> Self {
Self {
range: 15,
visible_points: HashSet::new(),
2021-05-13 17:25:45 +00:00
}
}
}
impl Viewshed {
pub fn is_point_visible(&self, point: &dyn PointLike) -> bool {
self.visible_points.contains(&point.into())
2021-05-13 17:25:45 +00:00
}
fn update(
&mut self,
viewer_entity: &Entity,
visible_entities: &mut VisibleEntities,
start: &dyn PointLike,
query_pipeline: &QueryPipeline,
collider_query: &QueryPipelineColliderComponentsQuery,
map: &Map,
visible_query: &Query<&Visible>,
cache: &mut HashMap<(i32, i32), (HashSet<Entity>, u8)>,
events: &mut EventWriter<VisibilityChanged>,
) {
let mut context: Context<u8> = Context::default();
let vision_distance = vision_distance::Circle::new(self.range);
let shape = ColliderShape::cuboid(0.49, 0.49);
let origin = point!(start.x(), start.y());
let coord = Coord::new(start.x_i32(), start.y_i32());
2022-01-12 17:05:12 +00:00
let collider_set = QueryPipelineColliderComponentsSet(collider_query);
let mut new_visible_entities = HashSet::<Entity>::new();
let visibility_grid = VisibilityGrid(
map,
RefCell::new(Box::new(|coord: Coord| {
if let Some((entities, opacity)) = cache.get(&(coord.x, coord.y)) {
for e in entities {
new_visible_entities.insert(*e);
}
return *opacity;
}
let tile = map.at(coord.x as usize, coord.y as usize);
if tile.blocks_visibility() {
return u8::MAX;
}
let mut entities = HashSet::new();
let shape_pos = (Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5), 0.);
let dest = point!(coord.x as f32 + 0.5, coord.y as f32 + 0.5);
if na::distance(&origin, &dest) >= self.range as f32 {
return u8::MAX;
}
let mut opacity = 0;
query_pipeline.intersections_with_shape(
&collider_set,
&shape_pos.into(),
&*shape,
InteractionGroups::all(),
Some(&|v| {
v.entity() != *viewer_entity && visible_query.get(v.entity()).is_ok()
}),
|handle| {
let entity = handle.entity();
entities.insert(entity);
if let Ok(visible) = visible_query.get(entity) {
opacity = **visible;
}
true
},
);
for e in &entities {
new_visible_entities.insert(*e);
}
cache.insert((coord.x, coord.y), (entities, opacity));
opacity
})),
);
let mut new_visible = HashSet::new();
context.for_each_visible(
coord,
&visibility_grid,
&visibility_grid,
vision_distance,
255,
|coord, _directions, _visibility| {
new_visible.insert((coord.x, coord.y));
},
);
if self.visible_points != new_visible {
self.visible_points = new_visible;
}
if new_visible_entities != **visible_entities {
for lost in visible_entities.difference(&new_visible_entities) {
events.send(VisibilityChanged::Lost {
viewer: *viewer_entity,
viewed: *lost,
});
}
for gained in new_visible_entities.difference(visible_entities) {
events.send(VisibilityChanged::Gained {
viewer: *viewer_entity,
viewed: *gained,
});
}
**visible_entities = new_visible_entities;
}
}
2021-05-13 17:25:45 +00:00
}
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Copy, Debug, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Visible(pub u8);
impl Default for Visible {
fn default() -> Self {
Self::opaque()
}
}
impl Visible {
pub fn transparent() -> Self {
Self(0)
}
pub fn opaque() -> Self {
Self(u8::MAX)
}
}
2022-01-10 19:50:52 +00:00
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
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()
},
..Default::default()
}
}
}
pub enum VisibilityChanged {
Gained { viewer: Entity, viewed: Entity },
Lost { viewer: Entity, viewed: Entity },
}
2021-06-09 22:42:04 +00:00
impl PointLike for Coord {
fn x(&self) -> f32 {
self.x as f32
}
fn y(&self) -> f32 {
self.y as f32
}
}
2021-05-13 17:25:45 +00:00
fn add_visibility_indices(
mut commands: Commands,
query: Query<(Entity, &Map), (Added<Map>, Without<RevealedTiles>)>,
2021-05-13 17:25:45 +00:00
map_config: Res<MapConfig>,
) {
for (entity, map) in query.iter() {
2021-06-09 19:53:48 +00:00
let count = map.width * map.height;
2021-05-13 17:25:45 +00:00
commands
.entity(entity)
.insert(RevealedTiles(vec![map_config.start_revealed; count]));
}
}
fn viewshed_removed(
query: RemovedComponents<Viewshed>,
2021-09-28 17:49:44 +00:00
visible_entities: Query<&VisibleEntities>,
mut events: EventWriter<VisibilityChanged>,
) {
for entity in query.iter() {
2021-09-28 17:49:44 +00:00
if let Ok(visible) = visible_entities.get(entity) {
for e in visible.iter() {
events.send(VisibilityChanged::Lost {
viewer: entity,
viewed: *e,
})
}
}
}
}
2021-09-28 17:49:44 +00:00
pub struct VisibilityGrid<'a, F>(pub &'a Map, pub RefCell<Box<F>>);
2021-05-13 17:25:45 +00:00
impl<'a, F> InputGrid for VisibilityGrid<'a, F>
where
2021-09-28 17:49:44 +00:00
F: FnMut(Coord) -> u8,
{
type Grid = VisibilityGrid<'a, F>;
2021-05-13 17:25:45 +00:00
type Opacity = u8;
fn size(&self, grid: &Self::Grid) -> Size {
2021-06-09 19:53:48 +00:00
Size::new(grid.0.width as u32, grid.0.height as u32)
2021-05-13 17:25:45 +00:00
}
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
2021-09-28 17:49:44 +00:00
(self.1.borrow_mut())(coord)
2021-05-13 17:25:45 +00:00
}
}
fn update_viewshed(
config: Res<RapierConfiguration>,
coordinates: Query<(Entity, &Coordinates), Changed<Coordinates>>,
visible: Query<&Visible>,
2021-09-28 17:49:44 +00:00
mut viewers: Query<(Entity, &mut Viewshed, &mut VisibleEntities, &Coordinates)>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
2021-09-28 17:49:44 +00:00
mut changed: EventWriter<VisibilityChanged>,
) {
if !config.query_pipeline_active {
return;
}
let mut to_update = HashSet::new();
for (entity, coordinates) in coordinates.iter() {
if to_update.contains(&entity) {
continue;
}
if viewers.get_mut(entity).is_ok() {
to_update.insert(entity);
}
if visible.get(entity).is_err() {
continue;
}
for (viewer_entity, viewshed, _, viewer_coordinates) in viewers.iter_mut() {
if viewer_entity != entity
&& viewer_coordinates.distance(&coordinates) <= viewshed.range as f32
2021-08-23 15:14:03 +00:00
{
to_update.insert(viewer_entity);
continue;
}
}
}
for entity in to_update.iter() {
if let Ok((viewer_entity, mut viewshed, mut visible_entities, viewer_coordinates)) =
viewers.get_mut(*entity)
{
2022-01-13 20:43:02 +00:00
if let Ok(map) = map.get_single() {
let mut cache = HashMap::new();
viewshed.update(
&viewer_entity,
&mut visible_entities,
viewer_coordinates,
&*query_pipeline,
&collider_query,
map,
&visible,
&mut cache,
&mut changed,
);
}
}
}
}
fn remove_visible(
removed: RemovedComponents<Visible>,
mut viewers: Query<(Entity, &mut Viewshed, &mut VisibleEntities, &Coordinates)>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
visible: Query<&Visible>,
2021-09-28 17:49:44 +00:00
mut changed: EventWriter<VisibilityChanged>,
) {
for removed in removed.iter() {
for (viewer_entity, mut viewshed, mut visible_entities, start) in viewers.iter_mut() {
if !visible_entities.contains(&removed) {
continue;
}
visible_entities.remove(&removed);
2022-01-12 17:05:12 +00:00
let map = map.single();
let mut cache = HashMap::new();
viewshed.update(
&viewer_entity,
&mut visible_entities,
start,
&*query_pipeline,
&collider_query,
map,
&visible,
&mut cache,
&mut changed,
);
}
}
}
2021-09-28 17:49:44 +00:00
fn update_revealed_tiles(
mut map: Query<(&Map, &mut RevealedTiles)>,
2021-05-21 17:04:10 +00:00
viewers: Query<&Viewshed, With<Player>>,
2021-05-13 17:25:45 +00:00
) {
for (map, mut revealed_tiles) in map.iter_mut() {
2021-05-21 17:04:10 +00:00
for viewshed in viewers.iter() {
for v in viewshed.visible_points.iter() {
2021-06-09 19:53:48 +00:00
let idx = v.to_index(map.width);
if idx >= revealed_tiles.len() {
2021-09-01 16:34:38 +00:00
continue;
}
2021-05-13 17:25:45 +00:00
revealed_tiles[idx] = true;
}
}
}
}
fn log_visible(
time: Res<Time>,
mut recently_lost: Local<HashMap<Entity, Timer>>,
2021-09-21 17:58:57 +00:00
mut events: EventReader<VisibilityChanged>,
2021-05-13 17:25:45 +00:00
mut log: Query<&mut Log>,
viewers: Query<(Entity, &Coordinates, &Transform), (With<Player>, With<Viewshed>)>,
visible: Query<
2022-01-12 17:05:12 +00:00
(
&Name,
Option<&RigidBodyPositionComponent>,
Option<&ColliderPositionComponent>,
),
Without<DontLogWhenVisible>,
>,
2021-05-13 17:25:45 +00:00
) {
for timer in recently_lost.values_mut() {
2021-05-13 17:25:45 +00:00
timer.tick(time.delta());
}
recently_lost.retain(|_entity, timer| !timer.finished());
for event in events.iter() {
let viewer = match event {
VisibilityChanged::Gained { viewer, .. } => viewer,
VisibilityChanged::Lost { viewer, .. } => viewer,
};
if let Ok((viewer_entity, viewer_coordinates, viewer_transform)) = viewers.get(*viewer) {
if let VisibilityChanged::Gained { viewed, .. } = event {
if *viewed == viewer_entity || recently_lost.contains_key(viewed) {
2021-09-21 17:58:57 +00:00
continue;
}
if let Ok((name, body_position, collider_position)) = visible.get(*viewed) {
2022-01-12 17:05:12 +00:00
let mut log = log.single_mut();
let viewed_coordinates = if let Some(p) = body_position {
(p.position.translation.x, p.position.translation.y)
} else if let Some(p) = collider_position {
(p.translation.x, p.translation.y)
} else {
(0., 0.)
};
let forward = viewer_transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x));
let location =
viewer_coordinates.direction_and_distance(&viewed_coordinates, Some(yaw));
2022-01-19 22:38:32 +00:00
log.push(format!("{}: {location}", **name));
}
} else if let VisibilityChanged::Lost { viewed, .. } = event {
recently_lost.insert(*viewed, Timer::from_seconds(2., false));
2021-05-13 17:25:45 +00:00
}
}
}
}
pub const LOG_VISIBLE_LABEL: &str = "LOG_VISIBLE";
pub struct VisibilityPlugin;
impl Plugin for VisibilityPlugin {
2022-01-10 19:50:52 +00:00
fn build(&self, app: &mut App) {
2021-09-28 17:49:44 +00:00
app.add_event::<VisibilityChanged>()
2022-01-10 19:50:52 +00:00
.add_system(add_visibility_indices)
.add_system_to_stage(CoreStage::PostUpdate, viewshed_removed)
2021-09-28 19:36:21 +00:00
.add_system_set(
SystemSet::new()
2021-12-20 14:41:33 +00:00
.with_run_criteria(FixedTimestep::step(0.1))
2022-01-10 19:50:52 +00:00
.with_system(update_viewshed),
2021-09-28 19:36:21 +00:00
)
2022-01-10 19:50:52 +00:00
.add_system_to_stage(CoreStage::PostUpdate, remove_visible)
.add_system_to_stage(CoreStage::PostUpdate, update_revealed_tiles)
.add_system_to_stage(CoreStage::PostUpdate, log_visible);
2021-05-13 17:25:45 +00:00
}
}