blackout/src/visibility.rs

254 lines
8.2 KiB
Rust
Raw Normal View History

2021-05-13 17:25:45 +00:00
use std::collections::{HashMap, HashSet};
use bevy::prelude::*;
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},
};
#[derive(Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct BlocksVisibility;
#[derive(Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct DontLogWhenVisible;
2021-05-13 17:25:45 +00:00
#[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct RevealedTiles(pub Vec<bool>);
#[derive(Clone, Debug, Eq, PartialEq)]
2021-05-13 17:25:45 +00:00
pub struct Viewshed {
pub visible: HashSet<(i32, i32)>,
pub range: u32,
}
impl Default for Viewshed {
fn default() -> Self {
Self {
range: 15,
visible: HashSet::new(),
}
}
}
impl Viewshed {
pub fn is_visible(&self, point: &dyn PointLike) -> bool {
self.visible.contains(&point.into())
}
}
#[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct VisibleTiles(pub Vec<bool>);
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<VisibleTiles>, 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(VisibleTiles(vec![false; count]));
commands
.entity(entity)
.insert(RevealedTiles(vec![map_config.start_revealed; count]));
}
}
struct VisibilityGrid<'a, F>(&'a Map, F);
2021-05-13 17:25:45 +00:00
impl<'a, F> InputGrid for VisibilityGrid<'a, F>
where
F: Fn(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 {
self.1(coord)
2021-05-13 17:25:45 +00:00
}
}
fn update_viewshed<'a>(
2021-06-09 22:42:04 +00:00
mut viewers: Query<(Entity, &mut Viewshed, &Coordinates), Changed<Coordinates>>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
blocks_visibility: Query<&BlocksVisibility>,
2021-05-13 17:25:45 +00:00
) {
2021-06-09 22:42:04 +00:00
for (viewer_entity, mut viewshed, start) in viewers.iter_mut() {
for map in map.iter() {
let mut context: Context<u8> = Context::default();
let vision_distance = vision_distance::Circle::new(viewshed.range);
let coord = Coord::new(start.x_i32(), start.y_i32());
viewshed.visible.clear();
let collider_set = QueryPipelineColliderComponentsSet(&collider_query);
let shape = Cuboid::new(Vec2::new(0.5, 0.5).into());
2021-06-09 22:42:04 +00:00
let range = viewshed.range as f32;
let visibility_grid = VisibilityGrid(map, |coord: Coord| {
2021-06-09 22:42:04 +00:00
if start.x_i32() == coord.x && start.y_i32() == coord.y {
return 0;
} else if coord.distance(start) > range {
return 255;
}
let shape_pos = (Vec2::new(coord.x as f32, coord.y as f32), 0.);
let mut opacity = 0;
query_pipeline.intersections_with_shape(
&collider_set,
&shape_pos.into(),
&shape,
InteractionGroups::all(),
2021-06-09 22:42:04 +00:00
Some(&|v| {
v.entity() != viewer_entity && blocks_visibility.get(v.entity()).is_ok()
}),
|_| {
opacity = 255;
false
},
);
opacity
});
context.for_each_visible(
coord,
&visibility_grid,
&visibility_grid,
vision_distance,
255,
|coord, _directions, _visibility| {
viewshed.visible.insert((coord.x, coord.y));
},
);
}
}
}
2021-05-21 17:04:10 +00:00
fn update_visible_and_revealed_tiles(
mut map: Query<(&Map, &mut RevealedTiles, &mut VisibleTiles)>,
2021-05-21 17:04:10 +00:00
viewers: Query<&Viewshed, With<Player>>,
2021-05-13 17:25:45 +00:00
) {
2021-05-21 17:04:10 +00:00
for (map, mut revealed_tiles, mut visible_tiles) in map.iter_mut() {
for viewshed in viewers.iter() {
2021-05-13 17:25:45 +00:00
for t in visible_tiles.iter_mut() {
*t = false
}
for v in viewshed.visible.iter() {
2021-06-09 19:53:48 +00:00
let idx = v.to_index(map.width);
2021-05-13 17:25:45 +00:00
revealed_tiles[idx] = true;
visible_tiles[idx] = true;
}
}
}
}
fn log_visible(
time: Res<Time>,
mut seen: Local<HashSet<Entity>>,
mut recently_lost: Local<HashMap<Entity, Timer>>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
2021-05-13 17:25:45 +00:00
mut log: Query<&mut Log>,
2021-05-16 22:24:26 +00:00
viewers: Query<(&Viewshed, &Coordinates, &Transform), With<Player>>,
2021-05-13 17:25:45 +00:00
names: Query<&Name>,
players: Query<&Player>,
dont_log_when_visible: Query<&DontLogWhenVisible>,
2021-05-13 17:25:45 +00:00
) {
for timer in recently_lost.values_mut() {
timer.tick(time.delta());
}
let recently_lost_clone = recently_lost.clone();
for (entity, timer) in recently_lost_clone.iter() {
if timer.finished() {
recently_lost.remove(&entity);
}
}
let mut new_seen = HashSet::new();
if let Ok(mut log) = log.single_mut() {
2021-05-16 22:24:26 +00:00
for (viewshed, coordinates, transform) in viewers.iter() {
let collider_set = QueryPipelineColliderComponentsSet(&collider_query);
let shape = Cuboid::new(Vec2::new(0.5, 0.5).into());
2021-05-13 17:25:45 +00:00
for viewed_coordinates in &viewshed.visible {
let shape_pos = (
Vec2::new(viewed_coordinates.x() + 0.5, viewed_coordinates.y() + 0.5),
0.0,
)
.into();
query_pipeline.intersections_with_shape(
&collider_set,
&shape_pos,
&shape,
InteractionGroups::all(),
None,
|handle| {
let entity = handle.entity();
2021-05-13 17:25:45 +00:00
if recently_lost.contains_key(&entity) {
return true;
2021-05-13 17:25:45 +00:00
}
if let Ok(name) = names.get(entity) {
if players.get(entity).is_err() {
if !seen.contains(&entity)
&& dont_log_when_visible.get(entity).is_err()
{
2021-05-13 17:25:45 +00:00
let name = name.to_string();
2021-05-16 22:24:26 +00:00
let forward = transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x));
let location = coordinates
.direction_and_distance(viewed_coordinates, Some(yaw));
2021-05-13 17:25:45 +00:00
log.push(format!("{}: {}", name, location));
}
new_seen.insert(entity);
2021-05-13 17:25:45 +00:00
}
}
true
},
);
2021-05-13 17:25:45 +00:00
}
}
}
let recently_lost_entities = seen.difference(&new_seen);
for entity in recently_lost_entities {
recently_lost.insert(*entity, Timer::from_seconds(2., false));
}
*seen = new_seen;
}
pub const LOG_VISIBLE_LABEL: &str = "LOG_VISIBLE";
pub struct VisibilityPlugin;
impl Plugin for VisibilityPlugin {
fn build(&self, app: &mut AppBuilder) {
app.add_system(add_visibility_indices.system())
.add_system_to_stage(CoreStage::PostUpdate, update_viewshed.system())
2021-05-13 17:25:45 +00:00
.add_system_to_stage(
CoreStage::PostUpdate,
update_visible_and_revealed_tiles.system(),
2021-05-13 17:25:45 +00:00
)
.add_system_to_stage(CoreStage::PostUpdate, log_visible.system());
2021-05-13 17:25:45 +00:00
}
}