mgd2-tram-championships/src/game/debug.rs

76 lines
2.1 KiB
Rust

use std::path::PathBuf;
use bevy::{
asset::{AssetPath, io::AssetSourceEvent},
prelude::*,
};
use crate::debug::{ConsoleLog, DebugEvent, DebugMode};
pub fn plugin(app: &mut App) {
app.add_systems(
Update,
(
handle_load_gltf.run_if(in_state(DebugMode::Enabled)),
handle_despawn,
),
);
}
#[derive(Component, Clone)]
struct Id(String);
#[derive(Component)]
struct HasPath(String);
fn handle_load_gltf(
mut c: Commands,
mut dbg_reader: EventReader<DebugEvent>,
mut logger: ResMut<ConsoleLog>,
asset_server: Res<AssetServer>,
) {
for ev in dbg_reader.read() {
if let DebugEvent::LoadGltf { asset_path, id } = ev {
logger.write(&format!("Loading {asset_path}..."));
let scene_handle = asset_server
.load(GltfAssetLabel::Scene(0).from_asset(AssetPath::from(asset_path.clone())));
let mut scene = c.spawn((SceneRoot(scene_handle), HasPath(asset_path.clone())));
if let Some(id) = id {
scene.insert(Id(id.clone()));
}
logger.write(
"Should be loaded now. If nothing happened, check if you might've typoed the path.",
);
}
}
}
fn handle_despawn(
mut c: Commands,
mut dbg_reader: EventReader<DebugEvent>,
mut logger: ResMut<ConsoleLog>,
entities: Query<(Entity, &Id)>,
) {
for ev in dbg_reader.read() {
if let DebugEvent::Despawn { id: target_id } = ev {
let mut count = 0;
entities
.iter()
.filter_map(|(entity, Id(id))| (id == target_id).then_some(entity))
.for_each(|entity| {
count += 1;
c.entity(entity).despawn()
});
if count > 0 {
logger.write(&format!("Despawned {count} entities."));
} else {
logger.err(&format!(
"Couldn't find any entities to despawn with id {target_id:?}."
))
}
}
}
}