blackout/src/exploration.rs

448 lines
14 KiB
Rust

use std::{
error::Error,
fmt::{Debug, Display},
hash::Hash,
marker::PhantomData,
};
use avian2d::prelude::*;
use bevy::prelude::*;
use bevy_tts::Tts;
use leafwing_input_manager::prelude::*;
use crate::{
core::{Player, PointLike},
error::error_handler,
map::Map,
navigation::NavigationAction,
pathfinding::Destination,
visibility::{RevealedTiles, Viewshed, Visible, VisibleEntities},
};
#[derive(Actionlike, PartialEq, Eq, Clone, Copy, Hash, Debug, Reflect)]
pub enum ExplorationAction {
Forward,
Backward,
Left,
Right,
FocusNext,
FocusPrev,
SelectNextType,
SelectPrevType,
NavigateTo,
}
#[derive(Component, Clone, Copy, Debug, Default, PartialEq, Reflect)]
#[reflect(Component)]
pub struct Explorable;
#[derive(Component, Clone, Copy, Debug, Default, PartialEq, Reflect)]
#[reflect(Component)]
pub struct ExplorationFocused;
#[derive(Component, Clone, Copy, Debug, Default, Deref, DerefMut, Reflect)]
#[reflect(Component)]
pub struct Exploring(pub Vec2);
impl PointLike for Exploring {
fn x(&self) -> f32 {
self.0.x
}
fn y(&self) -> f32 {
self.0.y
}
}
#[derive(Component, Clone, Debug, Default, Deref, DerefMut)]
pub struct FocusedExplorationType<T>(pub Option<T>)
where
T: Component + Default;
#[derive(Component, Clone, Copy, Debug, Default, Reflect)]
#[reflect(Component)]
pub struct Mappable;
fn exploration_type_change<ExplorationType>(
mut tts: ResMut<Tts>,
mut explorers: Query<(
&ActionState<ExplorationAction>,
&VisibleEntities,
&mut FocusedExplorationType<ExplorationType>,
)>,
features: Query<&ExplorationType>,
) -> Result<(), Box<dyn Error>>
where
ExplorationType: Component + Default + Copy + Ord,
{
for (actions, visible, mut focused) in &mut explorers {
let mut types: Vec<ExplorationType> = vec![];
for e in visible.iter() {
if let Ok(t) = features.get(*e) {
types.push(*t);
}
}
types.sort();
types.dedup();
if types.is_empty() {
tts.speak("Nothing visible.", true)?;
} else if actions.just_pressed(&ExplorationAction::SelectPrevType) {
if let Some(t) = &focused.0 {
if let Some(i) = types.iter().position(|v| *v == *t) {
if i == 0 {
focused.0 = None;
} else {
let t = &types[i - 1];
focused.0 = Some(*t);
}
} else {
let t = types.last().unwrap();
focused.0 = Some(*t);
}
} else {
let t = types.last().unwrap();
focused.0 = Some(*t);
}
} else if actions.just_pressed(&ExplorationAction::SelectNextType) {
if let Some(t) = &focused.0 {
if let Some(i) = types.iter().position(|v| *v == *t) {
if i == types.len() - 1 {
focused.0 = None;
} else {
let t = &types[i + 1];
focused.0 = Some(*t);
}
} else {
let t = types.first().unwrap();
focused.0 = Some(*t);
}
} else {
let t = types.first().unwrap();
focused.0 = Some(*t)
}
}
}
Ok(())
}
fn exploration_type_focus<ExplorationType>(
mut commands: Commands,
mut tts: ResMut<Tts>,
explorers: Query<(
Entity,
&GlobalTransform,
&ActionState<ExplorationAction>,
&VisibleEntities,
&FocusedExplorationType<ExplorationType>,
Option<&Exploring>,
)>,
features: Query<(Entity, &GlobalTransform, &ExplorationType)>,
) -> Result<(), Box<dyn Error>>
where
ExplorationType: Component + Default + PartialEq,
{
for (entity, transform, actions, visible_entities, focused_type, exploring) in &explorers {
let mut features = features
.iter()
.filter(|v| visible_entities.contains(&v.0))
.map(|v| (v.1.translation().truncate(), v.2))
.collect::<Vec<(Vec2, &ExplorationType)>>();
if features.is_empty() {
tts.speak("Nothing visible.", true)?;
return Ok(());
}
features.sort_by(|(c1, _), (c2, _)| {
transform
.translation()
.truncate()
.distance(*c1)
.partial_cmp(&transform.translation().truncate().distance(*c2))
.unwrap()
});
if let Some(focused) = &focused_type.0 {
features.retain(|(_, t)| **t == *focused);
}
let mut target = None;
if actions.just_pressed(&ExplorationAction::FocusNext) {
if let Some(exploring) = exploring {
target = features.iter().find(|(c, _)| {
transform.translation().truncate().distance(*c)
> transform.translation().truncate().distance(**exploring)
});
if target.is_none() {
target = features.first();
}
} else {
target = features.first();
}
} else if actions.just_pressed(&ExplorationAction::FocusPrev) {
if let Some(exploring) = exploring {
features.reverse();
target = features.iter().find(|(c, _)| {
transform.translation().truncate().distance(*c)
< transform.translation().truncate().distance(**exploring)
});
if target.is_none() {
target = features.first();
}
} else {
target = features.last();
}
}
if let Some((coordinates, _)) = target {
commands
.entity(entity)
.insert(Exploring(*coordinates));
}
}
Ok(())
}
fn exploration_type_changed_announcement<ExplorationType>(
mut tts: ResMut<Tts>,
focused: Query<
(
&FocusedExplorationType<ExplorationType>,
Ref<FocusedExplorationType<ExplorationType>>,
),
Changed<FocusedExplorationType<ExplorationType>>,
>,
) -> Result<(), Box<dyn Error>>
where
ExplorationType: Component + Default + Copy + Display,
{
for (focused, changed) in &focused {
if changed.is_added() {
return Ok(());
}
match &focused.0 {
Some(v) => {
tts.speak(format!("{v}"), true)?;
}
None => {
tts.speak("Everything", true)?;
}
};
}
Ok(())
}
fn exploration_focus<MapData>(
mut commands: Commands,
map: Query<&Map<MapData>>,
explorers: Query<
(
Entity,
&ActionState<ExplorationAction>,
&GlobalTransform,
Option<&Exploring>,
),
With<Player>,
>,
) where
MapData: 'static + Clone + Default + Send + Sync,
{
for (entity, actions, transform, exploring) in &explorers {
let mut exploring = if let Some(exploring) = exploring {
**exploring
} else {
transform.translation().truncate()
};
let orig = exploring;
if actions.just_pressed(&ExplorationAction::Forward) {
exploring.y += 1.;
} else if actions.just_pressed(&ExplorationAction::Backward) {
exploring.y -= 1.;
} else if actions.just_pressed(&ExplorationAction::Left) {
exploring.x -= 1.;
} else if actions.just_pressed(&ExplorationAction::Right) {
exploring.x += 1.;
}
let dimensions = if let Ok(map) = map.get_single() {
Some((map.width as f32, map.height as f32))
} else {
None
};
if let Some((width, height)) = dimensions {
if exploring.x >= width || exploring.y >= height {
return;
}
}
if orig != exploring && exploring.x >= 0. && exploring.y >= 0. {
commands.entity(entity).insert(Exploring(exploring));
}
}
}
fn navigate_to_explored<MapData>(
mut commands: Commands,
map: Query<(&Map<MapData>, &RevealedTiles)>,
explorers: Query<(Entity, &ActionState<ExplorationAction>, &Exploring)>,
) where
MapData: 'static + Clone + Default + Send + Sync,
{
for (entity, actions, exploring) in &explorers {
for (map, revealed_tiles) in &map {
let point = **exploring;
let idx = point.to_index(map.width);
let known = revealed_tiles[idx];
if actions.just_pressed(&ExplorationAction::NavigateTo) && known {
commands
.entity(entity)
.insert(Destination(point.as_ivec2()));
}
}
}
}
fn exploration_changed_announcement<ExplorationType, MapData>(
mut commands: Commands,
mut tts: ResMut<Tts>,
map: Query<(&Map<MapData>, &RevealedTiles)>,
explorer: Query<(&Transform, &Exploring, &Viewshed), Changed<Exploring>>,
focused: Query<Entity, With<ExplorationFocused>>,
explorable: Query<Entity, Or<(With<Visible>, With<Explorable>)>>,
names: Query<&Name>,
types: Query<&ExplorationType>,
mappables: Query<&Mappable>,
spatial_query: SpatialQuery,
) -> Result<(), Box<dyn Error>>
where
ExplorationType: Component + Copy + Display,
MapData: 'static + Clone + Default + Send + Sync,
{
if let Ok((coordinates, exploring, viewshed)) = explorer.get_single() {
let coordinates = coordinates.trunc();
let point = **exploring;
let shape = Collider::rectangle(1. - f32::EPSILON, 1. - 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))
} else {
(false, None)
};
let visible = viewshed.is_point_visible(exploring.as_ivec2());
let fog_of_war = !visible && known;
let description: String = if known || visible {
let mut tokens: Vec<String> = vec![];
for entity in focused.iter() {
commands.entity(entity).remove::<ExplorationFocused>();
}
let exploring = Vec2::new(exploring.x(), exploring.y());
spatial_query.shape_intersections_callback(
&shape,
exploring,
0.,
&default(),
|entity| {
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(format!("{t}"));
}
}
}
}
true
},
);
if tokens.is_empty() {
if let Some(idx) = idx {
if let Ok((map, _)) = map.get_single() {
let tile = map.tiles[idx];
if tile.is_blocked() {
tokens.push("wall".to_string());
} else {
tokens.push("floor".to_string());
}
}
}
tokens.first().cloned().unwrap_or_default()
} else {
tokens.join(": ")
}
} else {
"Unknown".to_string()
};
let mut tokens = vec![
description,
coordinates.direction_and_distance(exploring, None),
];
if fog_of_war {
tokens.push("in the fog of war".to_string());
}
tts.speak(tokens.join(", "), true)?;
}
Ok(())
}
fn cancel_on_navigate(
mut commands: Commands,
explorers: Query<
Entity,
(
With<ActionState<ExplorationAction>>,
Changed<ActionState<NavigationAction>>,
),
>,
focused: Query<Entity, With<ExplorationFocused>>,
) {
if !explorers.is_empty() {
for entity in &focused {
println!("Clearing focus");
commands.entity(entity).remove::<ExplorationFocused>();
}
}
}
#[derive(Resource, Clone, Default)]
pub struct ExplorationPlugin<ExplorationType, MapData> {
pub exploration_type: PhantomData<ExplorationType>,
pub map_data: PhantomData<MapData>,
}
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub struct Exploration;
impl<ExplorationType, MapData> Plugin for ExplorationPlugin<ExplorationType, MapData>
where
ExplorationType: 'static + Component + Default + Copy + Ord + PartialEq + Display,
MapData: 'static + Clone + Default + Send + Sync,
{
fn build(&self, app: &mut App) {
app.register_type::<ExplorationFocused>()
.register_type::<Mappable>()
.register_type::<Explorable>()
.add_plugins(InputManagerPlugin::<ExplorationAction>::default())
.add_systems(
FixedUpdate,
(
exploration_type_change::<ExplorationType>.pipe(error_handler),
exploration_type_changed_announcement::<ExplorationType>.pipe(error_handler),
)
.chain()
.in_set(Exploration),
)
.add_systems(
FixedUpdate,
(
exploration_focus::<MapData>,
exploration_type_focus::<ExplorationType>.pipe(error_handler),
exploration_changed_announcement::<ExplorationType, MapData>
.pipe(error_handler),
)
.chain()
.in_set(Exploration),
)
.add_systems(
FixedUpdate,
(navigate_to_explored::<MapData>, cancel_on_navigate).in_set(Exploration),
);
}
}