outfly/src/actor.rs

346 lines
10 KiB
Rust

use bevy::prelude::*;
use crate::{nature, settings, actor, audio, hud};
const MIN_INTERACT_DISTANCE: f32 = 30.0;
pub struct ActorPlugin;
impl Plugin for ActorPlugin {
fn build(&self, app: &mut App) {
app.register_type::<ChatBranch>();
app.add_systems(FixedUpdate, (
update_physics_lifeforms,
update_physics_actors,
));
app.add_systems(Update, (
handle_new_conversations,
handle_send_messages,
handle_conversations,
handle_input,
));
app.add_event::<StartConversationEvent>();
app.add_event::<SendMessageEvent>();
}
}
#[derive(Event)]
pub struct StartConversationEvent {
pub talker: Talker,
}
#[derive(Event)]
pub struct SendMessageEvent {
pub conv_id: String,
pub conv_label: String,
pub text: String,
}
#[derive(Component)]
pub struct Actor {
pub hp: f32,
pub m: f32, // mass
pub v: Vec3, // velocity
pub angular_momentum: Quat,
}
impl Default for Actor {
fn default() -> Self {
Self {
hp: 100.0,
m: 100.0,
v: Vec3::ZERO,
angular_momentum: Quat::from_euler(EulerRot::XYZ, 0.001, 0.01, 0.003),
}
}
}
#[derive(Component)] pub struct Player;
#[derive(Component)] pub struct PlayerInConversation;
#[derive(Component)] pub struct InConversationWithPlayer;
#[derive(Debug)]
#[derive(Component, Reflect, Default)]
#[reflect(Component)]
pub struct ChatBranch {
pub id: String,
pub name: String,
pub label: String,
pub delay: f64,
pub sound: String,
pub level: String,
pub reply: String,
pub goto: String,
pub choice: String,
}
#[derive(Component)]
pub struct Chat {
pub id: String,
pub label: String,
pub timer: f64,
}
#[derive(Component)]
#[derive(Clone)]
pub struct Talker {
pub conv_id: String,
}
#[derive(Component)]
pub struct LifeForm {
pub adrenaline: f32,
pub adrenaline_baseline: f32,
pub adrenaline_jolt: f32,
}
impl Default for LifeForm { fn default() -> Self { Self {
adrenaline: 0.3,
adrenaline_baseline: 0.3,
adrenaline_jolt: 0.0,
}}}
#[derive(Component)]
pub struct Suit {
pub oxygen: f32,
pub power: f32,
pub oxygen_max: f32,
pub power_max: f32,
pub integrity: f32, // [0.0 - 1.0]
}
impl Default for Suit { fn default() -> Self { SUIT_SIMPLE } }
const SUIT_SIMPLE: Suit = Suit {
power: 1e5,
power_max: 1e5,
oxygen: nature::OXY_D,
oxygen_max: nature::OXY_D,
integrity: 1e5,
};
pub fn update_physics_actors(
time: Res<Time>,
mut q_actors: Query<(&mut Actor, &mut Transform)>,
) {
let d = time.delta_seconds();
for (actor, mut transform) in q_actors.iter_mut() {
transform.rotate(actor.angular_momentum);
// TODO: animate only a step based on time between update:
//transform.rotate(actor.angular_momentum.slerp(Quat::IDENTITY, d)); // not working
transform.translation += d * actor.v;
}
}
pub fn update_physics_lifeforms(
time: Res<Time>,
mut query: Query<(&mut LifeForm, &mut Suit)>,
) {
let d = time.delta_seconds();
for (mut lifeform, mut suit) in query.iter_mut() {
if lifeform.adrenaline_jolt.abs() > 1e-3 {
lifeform.adrenaline_jolt *= 0.99;
}
else {
lifeform.adrenaline_jolt = 0.0
}
lifeform.adrenaline = (lifeform.adrenaline - 0.0001 + lifeform.adrenaline_jolt * 0.01).clamp(0.0, 1.0);
let mut oxygen_drain = nature::OXY_S;
let integr_threshold = 0.5;
if suit.integrity < integr_threshold {
// The oxygen drain from suit integrity scales with (2 - 2x)^4,
// which is a function with ~16 at x=0 and 0 at x=1.
// Furthermore, x is divided by the integrity threshold (e.g. 0.5)
// to squeeze the function horizontally, and change the range for
// the x parameter from [0-1] to [0-integritythreshold]
//
// 16 |.
// |.
// |'.
// | '.
// | '..
// |______''....
// x=0 x=1
let drain_scaling = (2.0 - 2.0 * suit.integrity / integr_threshold).powf(4.0);
oxygen_drain += suit.oxygen * 0.01 * drain_scaling;
}
suit.oxygen = (suit.oxygen - oxygen_drain*d).clamp(0.0, suit.oxygen_max);
}
}
pub fn handle_input(
keyboard_input: Res<ButtonInput<KeyCode>>,
settings: ResMut<settings::Settings>,
query: Query<(&Talker, &Transform)>,
player: Query<&Transform, With<actor::Player>>,
mut ew_conv: EventWriter<StartConversationEvent>,
)
{
if keyboard_input.just_pressed(settings.key_interact) {
let mindist = MIN_INTERACT_DISTANCE * MIN_INTERACT_DISTANCE;
if let Ok(player) = player.get_single() {
for (talker, transform) in &query {
if transform.translation.distance_squared(player.translation) <= mindist {
ew_conv.send(StartConversationEvent{talker: talker.clone()});
break;
}
}
}
}
}
pub fn handle_new_conversations(
mut commands: Commands,
mut er_conv: EventReader<StartConversationEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
q_conv: Query<&Chat>,
time: Res<Time>,
) {
let label = "INIT";
for event in er_conv.read() {
// check for existing chats with this id
let id = &event.talker.conv_id;
let chats: Vec<&Chat> = q_conv.iter().filter(|c| c.id == *id).collect();
if chats.len() > 0 {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Ping));
continue;
}
// no existing chats yet, let's create a new one
commands.spawn(Chat {
id: id.to_string(),
label: label.to_string(),
timer: time.elapsed_seconds_f64(),
});
break;
}
}
pub fn handle_send_messages(
mut commands: Commands,
mut er_sendmsg: EventReader<SendMessageEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
mut q_conv: Query<(Entity, &mut Chat)>,
time: Res<Time>,
chat_branches: Query<&ChatBranch>,
mut log: ResMut<hud::Log>,
) {
let now = time.elapsed_seconds_f64();
for event in er_sendmsg.read() {
for (entity, mut chat) in &mut q_conv {
if chat.id != event.conv_id {
continue;
}
if event.conv_label == "EXIT" {
info!("Despawning chat.");
commands.entity(entity).despawn();
continue;
}
let branches: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == event.conv_id
&& branch.label == event.conv_label
&& branch.choice == event.text)
.collect();
if branches.len() != 1 {
error!("Expected 1 branch with ID '{}' and label '{}', but got {}! Aborting conversation.", chat.id, chat.label, branches.len());
continue;
}
let branch = branches[0];
// TODO despawn the choices
if !branch.reply.is_empty() {
match branch.level.as_str() {
"chat" => log.chat(branch.reply.clone(), branch.name.clone()),
"info" => log.info(branch.reply.clone()),
_ => (),
}
}
chat.label = branch.goto.clone();
chat.timer = now + branch.delay;
if branch.sound != "" {
let sfx = audio::str2sfx(branch.sound.as_str());
ew_sfx.send(audio::PlaySfxEvent(sfx));
}
let choices: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == chat.id && branch.label == chat.label)
.collect();
for choice in choices {
if choice.choice.as_str() != hud::CHOICE_NONE {
commands.spawn(hud::ChoiceAvailable {
conv_id: choice.id.clone(),
conv_label: choice.label.clone(),
recipient: choice.name.clone(),
text: choice.choice.clone(),
});
}
}
}
break; // let's only handle one of these per frame
}
}
pub fn handle_conversations(
mut commands: Commands,
mut log: ResMut<hud::Log>,
mut q_conv: Query<(Entity, &mut Chat)>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
time: Res<Time>,
chat_branches: Query<&ChatBranch>, // TODO: use Table for faster iteration?
) {
let now = time.elapsed_seconds_f64();
for (entity, mut chat) in &mut q_conv {
if chat.label == "EXIT" {
info!("Despawning chat.");
commands.entity(entity).despawn();
continue;
}
if now < chat.timer {
continue;
}
let branches: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == chat.id
&& branch.label == chat.label
&& branch.choice == "")
.collect();
if branches.len() != 1 {
error!("Expected 1 branch with ID '{}' and label '{}', but got {}! Aborting conversation.", chat.id, chat.label, branches.len());
continue;
}
let branch = branches[0];
if !branch.reply.is_empty() {
match branch.level.as_str() {
"chat" => log.chat(branch.reply.clone(), branch.name.clone()),
"info" => log.info(branch.reply.clone()),
_ => (),
}
}
if chat.label == "EXIT" {
// TODO: isn't this dead code?
continue;
}
chat.label = branch.goto.clone();
if branch.sound != "" {
let sfx = audio::str2sfx(branch.sound.as_str());
ew_sfx.send(audio::PlaySfxEvent(sfx));
}
chat.timer = now + branch.delay;
let choices: Vec<&ChatBranch> = chat_branches.iter()
.filter(|branch| branch.id == chat.id && branch.label == chat.label)
.collect();
for choice in choices {
if choice.choice.as_str() != hud::CHOICE_NONE {
commands.spawn(hud::ChoiceAvailable {
conv_id: choice.id.clone(),
conv_label: choice.label.clone(),
recipient: choice.name.clone(),
text: choice.choice.clone(),
});
}
}
}
}