Files
smart-rgb/crates/borders-core/src/ui/plugin.rs
2025-10-16 00:02:34 -05:00

54 lines
2.2 KiB
Rust

//! Frontend plugin for UI/rendering integration
//!
//! This module provides the FrontendPlugin which handles all frontend communication
//! including rendering, input, and UI updates.
use bevy_ecs::prelude::*;
use bevy_ecs::schedule::common_conditions::resource_exists;
use crate::TerrainData;
use crate::app::{App, Plugin, Update};
use crate::networking::GameView;
use crate::ui::protocol::{BackendMessage, FrontendMessage};
use crate::ui::transport::{FrontendTransport, RenderBridge, emit_backend_messages_system, ingest_frontend_messages_system, send_initial_render_data, stream_territory_deltas};
/// Plugin to add frontend communication and UI systems to Bevy
pub struct FrontendPlugin<T: FrontendTransport> {
transport: T,
}
impl<T: FrontendTransport> FrontendPlugin<T> {
pub fn new(transport: T) -> Self {
Self { transport }
}
}
impl<T: FrontendTransport> Plugin for FrontendPlugin<T> {
fn build(&self, app: &mut App) {
let _guard = tracing::trace_span!("frontend_plugin_build").entered();
// Register message event types
app.add_message::<BackendMessage>();
app.add_message::<FrontendMessage>();
// Insert the bridge resource
app.insert_resource(RenderBridge::new(self.transport.clone()));
// Add render systems
app.add_systems(Update, (send_initial_render_data::<T>.run_if(resource_exists::<GameView>).run_if(resource_exists::<TerrainData>).run_if(resource_exists::<RenderBridge<T>>), stream_territory_deltas::<T>.run_if(resource_exists::<GameView>).run_if(resource_exists::<RenderBridge<T>>)).chain());
// Add communication systems
app.add_systems(Update, (emit_backend_messages_system::<T>, ingest_frontend_messages_system::<T>, reset_bridge_on_quit_system::<T>));
}
}
/// System to reset the render bridge when a game is quit
/// This ensures fresh initialization data is sent when starting a new game
fn reset_bridge_on_quit_system<T: FrontendTransport>(game_view: Option<Res<GameView>>, mut bridge: ResMut<RenderBridge<T>>) {
// If GameView doesn't exist but bridge is initialized, reset it
if game_view.is_none() && bridge.initialized {
bridge.reset();
tracing::debug!("RenderBridge reset - ready for next game initialization");
}
}