outfly/src/chat.rs

278 lines
8.3 KiB
Rust

extern crate yaml_rust;
use bevy::prelude::*;
use yaml_rust::{Yaml, YamlLoader};
use crate::{audio, hud, settings, world};
pub const CHATS: &[&str] = &[
include_str!("chats/serenity.yaml"),
include_str!("chats/startrans.yaml"),
];
pub const TOKEN_CHAT: &str = "chat";
pub const TOKEN_SYSTEM: &str = "system";
pub const TOKEN_WARN: &str = "warn";
pub const TOKEN_SET: &str = "set";
pub const TOKEN_IF: &str = "if";
pub const TOKEN_GOTO: &str = "goto";
pub const TOKEN_LABEL: &str = "label";
pub const TOKEN_SCRIPT: &str = "script";
pub const NAME_FALLBACK: &str = "Unknown";
pub const CHOICE_TIMER: f64 = 40.0 * settings::DEFAULT_CHAT_SPEED as f64;
pub const LETTERS_PER_SECOND: f32 = 17.0;
pub const TALKER_SPEED_FACTOR: f32 = settings::DEFAULT_CHAT_SPEED / LETTERS_PER_SECOND;
pub const CHAT_SPEED_MIN_LEN: f32 = 40.0;
pub const NON_CHOICE_TOKENS: &[&str] = &[
TOKEN_CHAT,
TOKEN_SYSTEM,
TOKEN_WARN,
TOKEN_SET,
TOKEN_IF,
TOKEN_GOTO,
TOKEN_LABEL,
TOKEN_SCRIPT,
];
pub struct ChatPlugin;
impl Plugin for ChatPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, load_chats);
app.add_systems(Update, (
handle_new_conversations.before(handle_chat_events),
handle_chat_events,
handle_chat_timer.before(handle_chat_events),
));
app.add_event::<StartConversationEvent>();
app.add_event::<ChatEvent>();
app.insert_resource(ChatDB(Vec::new()));
}
}
#[derive(Component)]
pub struct Chat {
pub id: usize,
pub position: usize,
pub timer: f64,
pub talker: Talker,
}
#[derive(Component)]
pub struct Choice {
pub text: String,
pub key: usize,
}
// This is the only place where any YAML interaction should be happening.
#[derive(Resource)]
pub struct ChatDB(Vec<Yaml>);
impl ChatDB {
pub fn load_from_str(&mut self, yaml_string: &str) -> Result<(), ()> {
if let Ok(mut yaml_data) = YamlLoader::load_from_str(yaml_string) {
self.0.append(&mut yaml_data);
return Ok(());
}
return Err(());
}
pub fn get_chat_by_id(&self, id: &String) -> Result<usize, String> {
let mut found: Option<usize> = None;
for (index, object_yaml) in self.0.iter().enumerate() {
if let Some(chat_id) = object_yaml[0][TOKEN_CHAT].as_str() {
if chat_id == id {
if found.is_some() {
return Err("Found multiple chats with the same id!".to_string());
}
found = Some(index);
}
}
}
if let Some(result) = found {
return Ok(result);
}
return Err(format!("No chat with the conversation ID `{id}` was found."));
}
fn search_choice(&self, yaml: &Yaml) -> Option<String> {
let non_choice_tokens = NON_CHOICE_TOKENS.to_vec();
if let Some(hash) = yaml.as_hash() {
for key in hash.keys() {
if let Yaml::String(key) = key {
if non_choice_tokens.contains(&key.as_str()) {
continue;
}
return Some(key.into());
}
}
}
return None;
}
pub fn advance_chat(&self, chat: &mut Chat, event: &mut EventWriter<ChatEvent>) {
event.send(ChatEvent::DespawnAllChoices);
let conv = &self.0[chat.id].as_vec();
if conv.is_none() {
return;
}
let conv = conv.unwrap();
// Handle next entry in the chat list
let mut is_skipping_through = false;
chat.position += 1;
if chat.position >= conv.len() {
event.send(ChatEvent::SpawnMessage("Disconnected.".to_string()));
event.send(ChatEvent::DespawnAllChats);
return;
}
else if let Some(_) = self.search_choice(&conv[chat.position]) {
is_skipping_through = true;
}
else if let Some(message) = conv[chat.position].as_str() {
event.send(ChatEvent::SpawnMessage(message.to_string()));
}
// Check if the immediately following entries are choices
let mut pos = chat.position + 1;
let mut key: usize = 0;
loop {
if is_skipping_through || pos >= conv.len() {
break;
}
if let Some(choice) = self.search_choice(&conv[pos]) {
event.send(ChatEvent::SpawnChoice(choice, key));
key += 1;
}
else {
break;
}
pos += 1;
}
}
}
#[derive(Component)]
#[derive(Clone)]
pub struct Talker {
pub conv_id: String,
pub name: Option<String>,
pub pronoun: Option<String>,
pub talking_speed: f32,
}
#[derive(Event)]
pub struct StartConversationEvent {
pub talker: Talker,
}
#[derive(Event)]
pub enum ChatEvent {
DespawnAllChoices,
DespawnAllChats,
SpawnMessage(String),
SpawnChoice(String, usize),
//Script(String, String, String),
}
pub fn load_chats(mut chatdb: ResMut<ChatDB>) {
for chat_yaml in CHATS {
if chatdb.load_from_str(chat_yaml).is_err() {
error!("Could not load chat definitions. Validate files in `src/chats/` path.");
}
}
}
pub fn handle_new_conversations(
mut commands: Commands,
mut er_conv: EventReader<StartConversationEvent>,
mut ew_sfx: EventWriter<audio::PlaySfxEvent>,
mut ew_chatevent: EventWriter<ChatEvent>,
chatdb: Res<ChatDB>,
q_chats: Query<&Chat>,
time: Res<Time>,
) {
for event in er_conv.read() {
if !q_chats.is_empty() {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Ping));
return;
}
match (*chatdb).get_chat_by_id(&event.talker.conv_id) {
Ok(chat_id) => {
ew_sfx.send(audio::PlaySfxEvent(audio::Sfx::Ping));
let mut chat = Chat {
id: chat_id,
position: 0,
timer: time.elapsed_seconds_f64(),
talker: event.talker.clone(),
};
chatdb.advance_chat(&mut chat, &mut ew_chatevent);
commands.spawn((
chat,
world::DespawnOnPlayerDeath,
));
}
Err(error) => {
error!("Error while looking for chat ID: {error}");
}
}
}
}
pub fn handle_chat_timer(
time: Res<Time>,
chatdb: Res<ChatDB>,
mut q_chats: Query<&mut Chat>,
mut ew_chatevent: EventWriter<ChatEvent>,
) {
let now = time.elapsed_seconds_f64();
for mut chat in &mut q_chats {
if now >= chat.timer {
chatdb.advance_chat(&mut chat, &mut ew_chatevent);
}
}
}
pub fn handle_chat_events(
mut commands: Commands,
mut er_chatevent: EventReader<ChatEvent>,
mut log: ResMut<hud::Log>,
q_choices: Query<Entity, With<Choice>>,
mut q_chats: Query<(Entity, &mut Chat)>,
time: Res<Time>,
settings: Res<settings::Settings>,
) {
for event in er_chatevent.read() {
let now = time.elapsed_seconds_f64();
let chat_maybe = q_chats.get_single_mut();
if chat_maybe.is_err() {
return;
}
let (chat_entity, mut chat) = chat_maybe.unwrap();
match event {
ChatEvent::DespawnAllChoices => {
for entity in &q_choices {
commands.entity(entity).despawn();
}
}
ChatEvent::DespawnAllChats => {
commands.entity(chat_entity).despawn();
}
ChatEvent::SpawnMessage(message) => {
log.chat(message.into(), chat.talker.name.clone().unwrap_or(NAME_FALLBACK.to_string()));
chat.timer = now + ((message.len() as f32).max(CHAT_SPEED_MIN_LEN) * TALKER_SPEED_FACTOR * chat.talker.talking_speed / settings.chat_speed) as f64;
}
ChatEvent::SpawnChoice(replytext, key) => {
commands.spawn((
world::DespawnOnPlayerDeath,
Choice {
text: replytext.into(),
key: *key,
}
));
chat.timer = now + CHOICE_TIMER / settings.chat_speed as f64;
}
}
}
}