use bevy::gltf::{Gltf, GltfNode};
use bevy::platform::collections::HashMap;
use bevy::prelude::*;
use bevy::world_serialization::{WorldAssetRoot, WorldInstance, WorldInstanceSpawner};
use super::anchor::{align_stage_to, AnchorAlignment};
use super::scan::{find_all_anchors, find_anchor};
use crate::plugin::StageTagConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Reflect)]
pub struct StageId(pub u32);
#[derive(Debug, Clone, PartialEq, Eq, Reflect)]
pub enum StageStatus {
Loading,
Spawning,
Ready,
Failed(String),
}
impl StageStatus {
pub fn is_ready(&self) -> bool {
matches!(self, Self::Ready)
}
}
#[derive(Debug, Clone)]
pub enum Placement {
Fixed(Transform),
Anchored {
anchor: String,
target: GlobalTransform,
alignment: AnchorAlignment,
},
}
#[derive(Component, Debug, Clone, Reflect)]
#[require(Transform, Visibility)]
pub struct StageRoot {
pub id: StageId,
pub path: String,
pub status: StageStatus,
}
#[derive(Component, Debug, Clone, Default)]
pub struct StageAnchors(HashMap<String, GlobalTransform>);
impl StageAnchors {
pub fn local(&self, id: &str) -> Option<GlobalTransform> {
self.0.get(id).copied()
}
pub fn ids(&self) -> impl Iterator<Item = &String> {
self.0.keys()
}
}
#[derive(Component)]
pub struct PendingStage {
handle: Handle<Gltf>,
placement: Placement,
}
struct StageRequest {
id: StageId,
path: String,
placement: Placement,
}
#[derive(Resource)]
pub struct StageManager {
next_id: u32,
requests: Vec<StageRequest>,
unloads: Vec<StageId>,
resident: HashMap<StageId, Entity>,
active: Option<StageId>,
pub max_resident: usize,
}
impl Default for StageManager {
fn default() -> Self {
Self {
next_id: 0,
requests: Vec::new(),
unloads: Vec::new(),
resident: HashMap::new(),
active: None,
max_resident: 8,
}
}
}
impl StageManager {
pub fn load(&mut self, path: impl Into<String>) -> StageId {
self.request(path, Placement::Fixed(Transform::IDENTITY))
}
pub fn load_at(&mut self, path: impl Into<String>, transform: Transform) -> StageId {
self.request(path, Placement::Fixed(transform))
}
pub fn load_connected(
&mut self,
path: impl Into<String>,
anchor: impl Into<String>,
target: GlobalTransform,
alignment: AnchorAlignment,
) -> StageId {
self.request(
path,
Placement::Anchored {
anchor: anchor.into(),
target,
alignment,
},
)
}
fn request(&mut self, path: impl Into<String>, placement: Placement) -> StageId {
let id = StageId(self.next_id);
self.next_id += 1;
self.requests.push(StageRequest {
id,
path: path.into(),
placement,
});
id
}
pub fn unload(&mut self, id: StageId) {
self.unloads.push(id);
}
pub fn activate(&mut self, id: StageId) {
self.active = Some(id);
}
pub fn active(&self) -> Option<StageId> {
self.active
}
pub fn entity(&self, id: StageId) -> Option<Entity> {
self.resident.get(&id).copied()
}
pub fn is_resident(&self, id: StageId) -> bool {
self.resident.contains_key(&id)
}
pub fn pending_unloads(&self) -> &[StageId] {
&self.unloads
}
pub fn resident(&self) -> impl Iterator<Item = (&StageId, &Entity)> {
self.resident.iter()
}
pub fn len(&self) -> usize {
self.resident.len()
}
pub fn is_empty(&self) -> bool {
self.resident.is_empty()
}
}
pub fn begin_stage_loads(
mut manager: ResMut<StageManager>,
mut commands: Commands,
assets: Res<AssetServer>,
) {
let requests = core::mem::take(&mut manager.requests);
for request in requests {
if manager.resident.len() >= manager.max_resident {
error!(
"bevy_stage: refusing to load `{}` — already holding {} levels. \
Check that connected levels have matching anchors, or raise \
`StageManager::max_resident`.",
request.path, manager.max_resident
);
let entity = commands
.spawn((
StageRoot {
id: request.id,
path: request.path.clone(),
status: StageStatus::Failed(format!(
"refused: already holding {} levels",
manager.max_resident
)),
},
Name::new(format!("Stage({}) [refused]", request.path)),
))
.id();
manager.resident.insert(request.id, entity);
continue;
}
let handle: Handle<Gltf> = assets.load(request.path.clone());
let entity = commands
.spawn((
StageRoot {
id: request.id,
path: request.path.clone(),
status: StageStatus::Loading,
},
Name::new(format!("Stage({})", request.path)),
Visibility::Hidden,
PendingStage {
handle,
placement: request.placement,
},
))
.id();
manager.resident.insert(request.id, entity);
}
}
pub fn spawn_loaded_stages(
mut stages: Query<(Entity, &mut StageRoot, &PendingStage)>,
gltfs: Res<Assets<Gltf>>,
nodes: Res<Assets<GltfNode>>,
assets: Res<AssetServer>,
config: Res<StageTagConfig>,
mut commands: Commands,
) {
for (entity, mut root, pending) in &mut stages {
if !matches!(root.status, StageStatus::Loading) {
continue;
}
if let bevy::asset::LoadState::Failed(error) = assets.load_state(&pending.handle) {
root.status = StageStatus::Failed(error.to_string());
commands.entity(entity).remove::<PendingStage>();
continue;
}
let Some(gltf) = gltfs.get(&pending.handle) else {
continue;
};
let Some(scene) = gltf.default_scene.clone() else {
root.status =
StageStatus::Failed(format!("`{}` declares no default scene", root.path));
commands.entity(entity).remove::<PendingStage>();
continue;
};
let anchors: HashMap<String, GlobalTransform> =
find_all_anchors(gltf, &nodes, &config.discriminator)
.into_iter()
.collect();
let transform = match &pending.placement {
Placement::Fixed(transform) => *transform,
Placement::Anchored {
anchor,
target,
alignment,
} => {
let Some(local) = find_anchor(gltf, &nodes, anchor, &config.discriminator) else {
root.status = StageStatus::Failed(format!(
"`{}` has no anchor named `{}` (found: {})",
root.path,
anchor,
anchors
.keys()
.map(String::as_str)
.collect::<Vec<_>>()
.join(", ")
));
commands.entity(entity).remove::<PendingStage>();
continue;
};
align_stage_to(target, &local, *alignment)
}
};
root.status = StageStatus::Spawning;
commands
.entity(entity)
.remove::<PendingStage>()
.insert((
transform,
Visibility::Inherited,
StageAnchors(anchors),
WorldAssetRoot(scene),
));
}
}
pub fn finish_stage_spawns(
mut stages: Query<(&mut StageRoot, &WorldInstance)>,
spawner: Res<WorldInstanceSpawner>,
) {
for (mut root, instance) in &mut stages {
if matches!(root.status, StageStatus::Spawning) && spawner.instance_is_ready(**instance) {
root.status = StageStatus::Ready;
}
}
}
pub fn process_stage_unloads(mut manager: ResMut<StageManager>, mut commands: Commands) {
let unloads = core::mem::take(&mut manager.unloads);
for id in unloads {
if let Some(entity) = manager.resident.remove(&id) {
commands.entity(entity).despawn();
}
if manager.active == Some(id) {
manager.active = None;
}
}
}