blackout/src/visibility.rs

328 lines
10 KiB
Rust

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::*,
core::{Angle, Coordinates, Player, PointLike},
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;
#[derive(Clone, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct RevealedTiles(pub Vec<bool>);
#[derive(Clone, Debug, Eq, PartialEq)]
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>);
impl PointLike for Coord {
fn x(&self) -> f32 {
self.x as f32
}
fn y(&self) -> f32 {
self.y as f32
}
}
fn add_visibility_indices(
mut commands: Commands,
query: Query<(Entity, &Map), (Added<Map>, Without<VisibleTiles>, Without<RevealedTiles>)>,
map_config: Res<MapConfig>,
) {
for (entity, map) in query.iter() {
let count = map.width * map.height;
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);
impl<'a, F> InputGrid for VisibilityGrid<'a, F>
where
F: Fn(Coord) -> u8,
{
type Grid = VisibilityGrid<'a, F>;
type Opacity = u8;
fn size(&self, grid: &Self::Grid) -> Size {
Size::new(grid.0.width as u32, grid.0.height as u32)
}
fn get_opacity(&self, _grid: &Self::Grid, coord: Coord) -> Self::Opacity {
self.1(coord)
}
}
fn update_viewshed(
viewer_entity: &Entity,
viewshed: &mut Viewshed,
start: &dyn PointLike,
query_pipeline: &QueryPipeline,
collider_query: &QueryPipelineColliderComponentsQuery,
map: &Map,
blocks_visibility: &Query<&BlocksVisibility>,
) {
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 shape = Cuboid::new(Vec2::new(0.49, 0.49).into());
let range = viewshed.range as f32;
let collider_set = QueryPipelineColliderComponentsSet(&collider_query);
let visibility_grid = VisibilityGrid(map, |coord: Coord| {
if coord.distance(start) > range {
return 255;
}
let shape_pos = (Vec2::new(coord.x as f32 + 0.5, coord.y as f32 + 0.5), 0.);
let mut opacity = 0;
query_pipeline.intersections_with_shape(
&collider_set,
&shape_pos.into(),
&shape,
InteractionGroups::all(),
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));
},
);
}
fn update_viewshed_for_coordinates<'a>(
visible: Query<(&Coordinates, &BlocksVisibility), Changed<Coordinates>>,
mut viewers: Query<(Entity, &mut Viewshed, &Coordinates)>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
blocks_visibility: Query<&BlocksVisibility>,
) {
for (coordinates, _) in visible.iter() {
for (viewer_entity, mut viewshed, start) in viewers.iter_mut() {
if coordinates.distance(start) > viewshed.range as f32 {
continue;
}
if let Ok(map) = map.single() {
update_viewshed(
&viewer_entity,
&mut viewshed,
start,
&*query_pipeline,
&collider_query,
map,
&blocks_visibility,
);
}
}
}
}
fn update_viewshed_for_start<'a>(
mut viewers: Query<(Entity, &mut Viewshed, &Coordinates), Changed<Coordinates>>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
blocks_visibility: Query<&BlocksVisibility>,
) {
for (viewer_entity, mut viewshed, start) in viewers.iter_mut() {
if let Ok(map) = map.single() {
update_viewshed(
&viewer_entity,
&mut viewshed,
start,
&*query_pipeline,
&collider_query,
map,
&blocks_visibility,
);
}
}
}
fn remove_blocks_visibility<'a>(
removed: RemovedComponents<BlocksVisibility>,
mut viewers: Query<(Entity, &mut Viewshed, &Coordinates)>,
map: Query<&Map>,
query_pipeline: Res<QueryPipeline>,
collider_query: QueryPipelineColliderComponentsQuery,
blocks_visibility: Query<&BlocksVisibility>,
) {
for _ in removed.iter() {
for (viewer_entity, mut viewshed, start) in viewers.iter_mut() {
if let Ok(map) = map.single() {
update_viewshed(
&viewer_entity,
&mut viewshed,
start,
&*query_pipeline,
&collider_query,
map,
&blocks_visibility,
);
}
}
}
}
fn update_visible_and_revealed_tiles(
mut map: Query<(&Map, &mut RevealedTiles, &mut VisibleTiles)>,
viewers: Query<&Viewshed, With<Player>>,
) {
for (map, mut revealed_tiles, mut visible_tiles) in map.iter_mut() {
for viewshed in viewers.iter() {
for t in visible_tiles.iter_mut() {
*t = false
}
for v in viewshed.visible.iter() {
let idx = v.to_index(map.width);
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,
mut log: Query<&mut Log>,
viewers: Query<(Entity, &Viewshed, &Coordinates, &Transform), With<Player>>,
names: Query<&Name>,
dont_log_when_visible: Query<&DontLogWhenVisible>,
) {
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() {
for (viewer_entity, viewshed, coordinates, transform) in viewers.iter() {
let collider_set = QueryPipelineColliderComponentsSet(&collider_query);
let shape = Cuboid::new(Vec2::new(0.49, 0.49).into());
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(),
Some(&|v| v.entity() != viewer_entity),
|handle| {
let entity = handle.entity();
if recently_lost.contains_key(&entity) {
new_seen.insert(entity);
recently_lost.remove(&entity);
return true;
}
if let Ok(name) = names.get(entity) {
if !seen.contains(&entity)
&& !new_seen.contains(&entity)
&& dont_log_when_visible.get(entity).is_err()
{
let name = name.to_string();
let forward = transform.local_x();
let yaw = Angle::Radians(forward.y.atan2(forward.x));
let location = coordinates
.direction_and_distance(viewed_coordinates, Some(yaw));
log.push(format!("{}: {}", name, location));
}
new_seen.insert(entity);
}
true
},
);
}
}
}
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_for_coordinates.system(),
)
.add_system_to_stage(CoreStage::PostUpdate, update_viewshed_for_start.system())
.add_system_to_stage(CoreStage::PostUpdate, remove_blocks_visibility.system())
.add_system_to_stage(
CoreStage::PostUpdate,
update_visible_and_revealed_tiles.system(),
)
.add_system_to_stage(CoreStage::PostUpdate, log_visible.system());
}
}