Compare commits

...

5 Commits

Author SHA1 Message Date
Mark Moissette d83b281c0b
Merge f5b063cd34 into 1353e14802 2024-03-13 01:46:11 +00:00
kaosat.dev f5b063cd34 chore(testing): updated the testing bevy project 2024-03-12 23:46:08 +01:00
kaosat.dev 5192518b12 refactor(): made the various gltf assets loaded by bevy_asset_loader optional (to handle the case where they are not present)
* updated all examples accordingly
2024-03-12 23:43:56 +01:00
kaosat.dev ea41c3c9cb refactor(): further cleanups 2024-03-12 23:41:05 +01:00
kaosat.dev bb0975bbe8 refactor(): minor cleanups 2024-03-12 10:10:23 +01:00
16 changed files with 60 additions and 71 deletions

View File

@ -144,14 +144,29 @@ impl Plugin for BlueprintsPlugin {
.add_systems( .add_systems(
Update, Update,
( (
(spawn_from_blueprints, (
check_for_loaded, prepare_blueprints,
actually_spawn_stuff, apply_deferred).chain(), check_for_loaded,
spawn_from_blueprints,
apply_deferred
)
.chain(),
(
compute_scene_aabbs,
apply_deferred
)
.chain()
.run_if(aabbs_enabled),
compute_scene_aabbs.run_if(aabbs_enabled),
apply_deferred.run_if(aabbs_enabled),
apply_deferred, apply_deferred,
(materials_inject, check_for_material_loaded, materials_inject2).chain().run_if(materials_library_enabled),
(
materials_inject,
check_for_material_loaded,
materials_inject2
)
.chain()
.run_if(materials_library_enabled),
) )
.chain() .chain()
.in_set(GltfBlueprintsSet::Spawn), .in_set(GltfBlueprintsSet::Spawn),

View File

@ -30,8 +30,6 @@ pub(crate) struct BlueprintMaterialAssetsLoaded;
#[derive(Component)] #[derive(Component)]
pub(crate) struct BlueprintMaterialAssetsNotLoaded; pub(crate) struct BlueprintMaterialAssetsNotLoaded;
/// system that injects / replaces materials from material library /// system that injects / replaces materials from material library
pub(crate) fn materials_inject( pub(crate) fn materials_inject(
blueprints_config: ResMut<BluePrintsConfig>, blueprints_config: ResMut<BluePrintsConfig>,
@ -65,7 +63,6 @@ pub(crate) fn materials_inject(
} else { } else {
let material_file_handle: Handle<Gltf> = asset_server.load(materials_path.clone()); let material_file_handle: Handle<Gltf> = asset_server.load(materials_path.clone());
let material_file_id = material_file_handle.id(); let material_file_id = material_file_handle.id();
println!("loading material {} {}", material_full_path, material_file_id);
let mut asset_infos:Vec<AssetLoadTracker<Gltf>> = vec![]; let mut asset_infos:Vec<AssetLoadTracker<Gltf>> = vec![];
asset_infos.push(AssetLoadTracker { asset_infos.push(AssetLoadTracker {
@ -103,14 +100,12 @@ pub(crate) fn check_for_material_loaded(
let loaded = asset_server.is_loaded_with_dependencies(asset_id); let loaded = asset_server.is_loaded_with_dependencies(asset_id);
tracker.loaded = loaded; tracker.loaded = loaded;
if loaded { if loaded {
println!("loaded {} {}", tracker.name, tracker.id);
loaded_amount += 1; loaded_amount += 1;
}else{ }else{
all_loaded = false; all_loaded = false;
} }
} }
let progress:f32 = loaded_amount as f32 / total as f32; let progress:f32 = loaded_amount as f32 / total as f32;
println!("progress (materials): {}",progress);
assets_to_load.progress = progress; assets_to_load.progress = progress;
if all_loaded { if all_loaded {
@ -141,7 +136,6 @@ pub(crate) fn materials_inject2(
mut commands: Commands, mut commands: Commands,
) { ) {
for (material_info, children) in material_infos.iter() { for (material_info, children) in material_infos.iter() {
println!("here");
let model_file_name = format!( let model_file_name = format!(
"{}_materials_library.{}", "{}_materials_library.{}",
&material_info.source, &blueprints_config.format &material_info.source, &blueprints_config.format
@ -157,7 +151,7 @@ pub(crate) fn materials_inject2(
.material_library_cache .material_library_cache
.contains_key(&material_full_path) .contains_key(&material_full_path)
{ {
info!("material is cached, retrieving"); debug!("material is cached, retrieving");
let material = blueprints_config let material = blueprints_config
.material_library_cache .material_library_cache
.get(&material_full_path) .get(&material_full_path)
@ -165,8 +159,6 @@ pub(crate) fn materials_inject2(
material_found = Some(material); material_found = Some(material);
}else { }else {
let model_handle: Handle<Gltf> = asset_server.load(materials_path.clone());// FIXME: kinda weird now let model_handle: Handle<Gltf> = asset_server.load(materials_path.clone());// FIXME: kinda weird now
println!("loading material {:?} {}", materials_path, model_handle.id());
let mat_gltf = assets_gltf let mat_gltf = assets_gltf
.get(model_handle.id()) .get(model_handle.id())
.expect("material should have been preloaded"); .expect("material should have been preloaded");

View File

@ -46,25 +46,10 @@ pub struct AddToGameWorld;
/// helper component, just to transfer child data /// helper component, just to transfer child data
pub(crate) struct OriginalChildren(pub Vec<Entity>); pub(crate) struct OriginalChildren(pub Vec<Entity>);
#[derive(Component, Reflect, Default, Debug)] #[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)] #[reflect(Component)]
pub struct BlueprintsList(pub HashMap<String,Vec<String>>); pub struct BlueprintsList(pub HashMap<String,Vec<String>>);
#[derive(Reflect, Default, Debug)]
pub(crate) struct BlueprintLoadTracker{
pub name: String,
pub id: AssetId<Gltf>,
pub loaded: bool,
pub handle: Handle<Gltf>
}
#[derive(Component, Default, Debug)]
pub(crate) struct BlueprintAssetsToLoad{
pub all_loaded: bool,
pub asset_infos: Vec<BlueprintLoadTracker>,
pub progress: f32
}
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub(crate) struct AssetLoadTracker<T:bevy::prelude::Asset>{ pub(crate) struct AssetLoadTracker<T:bevy::prelude::Asset>{
pub name: String, pub name: String,
@ -89,7 +74,7 @@ pub(crate) struct BlueprintAssetsNotLoaded;
/// spawning prepare function, /// spawning prepare function,
/// * also takes into account the already exisiting "override" components, ie "override components" > components from blueprint /// * also takes into account the already exisiting "override" components, ie "override components" > components from blueprint
pub(crate) fn spawn_from_blueprints( pub(crate) fn prepare_blueprints(
spawn_placeholders: Query< spawn_placeholders: Query<
( (
Entity, Entity,
@ -117,7 +102,7 @@ pub(crate) fn spawn_from_blueprints(
) in spawn_placeholders.iter() ) in spawn_placeholders.iter()
{ {
debug!( debug!(
"preparing to spawn {:?} for entity {:?}, id: {:?}, parent:{:?}", "requesting to spawn {:?} for entity {:?}, id: {:?}, parent:{:?}",
blupeprint_name.0, name, entity, original_parent blupeprint_name.0, name, entity, original_parent
); );
@ -170,10 +155,14 @@ pub(crate) fn spawn_from_blueprints(
.insert(BlueprintAssetsLoaded); .insert(BlueprintAssetsLoaded);
} }
} }
else { // in case there are no blueprintsList
commands
.entity(entity)
.insert(BlueprintAssetsLoaded);
}
} }
} }
pub(crate) fn check_for_loaded( pub(crate) fn check_for_loaded(
mut blueprint_assets_to_load: Query<(Entity, &mut AssetsToLoad<Gltf>), With<BlueprintAssetsNotLoaded>>, mut blueprint_assets_to_load: Query<(Entity, &mut AssetsToLoad<Gltf>), With<BlueprintAssetsNotLoaded>>,
asset_server: Res<AssetServer>, asset_server: Res<AssetServer>,
@ -194,7 +183,7 @@ pub(crate) fn check_for_loaded(
} }
} }
let progress:f32 = loaded_amount as f32 / total as f32; let progress:f32 = loaded_amount as f32 / total as f32;
println!("progress: {}",progress); // println!("progress: {}",progress);
assets_to_load.progress = progress; assets_to_load.progress = progress;
if all_loaded { if all_loaded {
@ -206,7 +195,7 @@ pub(crate) fn check_for_loaded(
} }
} }
pub(crate) fn actually_spawn_stuff( pub(crate) fn spawn_from_blueprints(
spawn_placeholders: Query< spawn_placeholders: Query<
( (
Entity, Entity,
@ -242,7 +231,7 @@ pub(crate) fn actually_spawn_stuff(
) in spawn_placeholders.iter() ) in spawn_placeholders.iter()
{ {
info!( info!(
"need to spawn {:?} for entity {:?}, id: {:?}, parent:{:?}", "attempting to spawn {:?} for entity {:?}, id: {:?}, parent:{:?}",
blupeprint_name.0, name, entity, original_parent blupeprint_name.0, name, entity, original_parent
); );
@ -254,7 +243,7 @@ pub(crate) fn actually_spawn_stuff(
library_override.map_or_else(|| &blueprints_config.library_folder, |l| &l.0); library_override.map_or_else(|| &blueprints_config.library_folder, |l| &l.0);
let model_path = Path::new(&library_path).join(Path::new(model_file_name.as_str())); let model_path = Path::new(&library_path).join(Path::new(model_file_name.as_str()));
info!("attempting to spawn {:?}", model_path); // info!("attempting to spawn {:?}", model_path);
let model_handle: Handle<Gltf> = asset_server.load(model_path);// FIXME: kinda weird now let model_handle: Handle<Gltf> = asset_server.load(model_path);// FIXME: kinda weird now
let gltf = assets_gltf let gltf = assets_gltf

View File

@ -1,12 +1,13 @@
use std::any::TypeId; use std::any::TypeId;
use bevy::gltf::Gltf;
use bevy::prelude::*; use bevy::prelude::*;
use bevy::scene::SceneInstance; use bevy::scene::SceneInstance;
// use bevy::utils::hashbrown::HashSet; // use bevy::utils::hashbrown::HashSet;
use super::{AnimationPlayerLink, Animations}; use super::{AnimationPlayerLink, Animations};
use super::{SpawnHere, Spawned}; use super::{SpawnHere, Spawned};
use crate::{BlueprintAssetsToLoad, CopyComponents, InBlueprint, NoInBlueprint, OriginalChildren}; use crate::{AssetsToLoad, BlueprintAssetsLoaded, CopyComponents, InBlueprint, NoInBlueprint, OriginalChildren};
/// this system is in charge of doing any necessary post processing after a blueprint scene has been spawned /// this system is in charge of doing any necessary post processing after a blueprint scene has been spawned
/// - it removes one level of useless nesting /// - it removes one level of useless nesting
@ -89,7 +90,8 @@ pub(crate) fn spawned_blueprint_post_process(
commands.entity(original).remove::<SpawnHere>(); commands.entity(original).remove::<SpawnHere>();
commands.entity(original).remove::<Spawned>(); commands.entity(original).remove::<Spawned>();
commands.entity(original).remove::<Handle<Scene>>(); commands.entity(original).remove::<Handle<Scene>>();
commands.entity(original).remove::<BlueprintAssetsToLoad>();// also clear the sub assets tracker to free up handles, perhaps just freeing up the handles and leave the rest would be better ? commands.entity(original).remove::<AssetsToLoad<Gltf>>();// also clear the sub assets tracker to free up handles, perhaps just freeing up the handles and leave the rest would be better ?
commands.entity(original).remove::<BlueprintAssetsLoaded>();
commands.entity(root_entity).despawn_recursive(); commands.entity(root_entity).despawn_recursive();
} }
} }

View File

@ -30,7 +30,7 @@ pub fn setup_game(
SceneBundle { SceneBundle {
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene // note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene
scene: models scene: models
.get(game_assets.world.id()) .get(game_assets.world.clone().unwrap().id())
.expect("main level should have been loaded") .expect("main level should have been loaded")
.scenes[0] .scenes[0]
.clone(), .clone(),

View File

@ -20,7 +20,7 @@ pub fn setup_game(
SceneBundle { SceneBundle {
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene // note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene
scene: models scene: models
.get(game_assets.world.id()) .get(game_assets.world.clone().unwrap().id())
.expect("main level should have been loaded") .expect("main level should have been loaded")
.scenes[0] .scenes[0]
.clone(), .clone(),

View File

@ -20,7 +20,7 @@ pub fn setup_game(
SceneBundle { SceneBundle {
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene // note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene
scene: models scene: models
.get(game_assets.world.id()) .get(game_assets.world.clone().unwrap().id())
.expect("main level should have been loaded") .expect("main level should have been loaded")
.scenes[0] .scenes[0]
.clone(), .clone(),

View File

@ -21,7 +21,7 @@ pub fn setup_game(
SceneBundle { SceneBundle {
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene // note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene
scene: models scene: models
.get(game_assets.world.id()) .get(game_assets.world.clone().unwrap().id())
.expect("main level should have been loaded") .expect("main level should have been loaded")
.scenes[0] .scenes[0]
.clone(), .clone(),

View File

@ -21,7 +21,7 @@ pub fn setup_game(
SceneBundle { SceneBundle {
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene // note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene
scene: models scene: models
.get(game_assets.world.id()) .get(game_assets.world.clone().unwrap().id())
.expect("main level should have been loaded") .expect("main level should have been loaded")
.scenes[0] .scenes[0]
.clone(), .clone(),

View File

@ -76,7 +76,7 @@ pub fn trigger_level_transition(
} else if target_level == "Level2" { } else if target_level == "Level2" {
level = game_assets.level2.clone().unwrap(); level = game_assets.level2.clone().unwrap();
} else { } else {
level = game_assets.world.clone(); level = game_assets.world.clone().unwrap();
} }
info!("spawning new level"); info!("spawning new level");
commands.spawn(( commands.spawn((

View File

@ -21,7 +21,7 @@ pub fn setup_game(
SceneBundle { SceneBundle {
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene // note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene
scene: models scene: models
.get(game_assets.world.id()) .get(game_assets.world.clone().unwrap().id())
.expect("main level should have been loaded") .expect("main level should have been loaded")
.scenes[0] .scenes[0]
.clone(), .clone(),

View File

@ -5,8 +5,8 @@ use bevy_asset_loader::prelude::*;
#[derive(AssetCollection, Resource)] #[derive(AssetCollection, Resource)]
pub struct GameAssets { pub struct GameAssets {
#[asset(key = "world")] #[asset(key = "world", optional)]
pub world: Handle<Gltf>, pub world: Option<Handle<Gltf>>,
#[asset(key = "world_dynamic", optional)] #[asset(key = "world_dynamic", optional)]
pub world_dynamic: Option<Handle<Gltf>>, pub world_dynamic: Option<Handle<Gltf>>,
@ -16,8 +16,8 @@ pub struct GameAssets {
#[asset(key = "level2", optional)] #[asset(key = "level2", optional)]
pub level2: Option<Handle<Gltf>>, pub level2: Option<Handle<Gltf>>,
#[asset(key = "models", collection(typed, mapped))] #[asset(key = "models", collection(typed, mapped), optional)]
pub models: HashMap<String, Handle<Gltf>>, pub models: Option<HashMap<String, Handle<Gltf>>>,
#[asset(key = "materials", collection(typed, mapped), optional)] #[asset(key = "materials", collection(typed, mapped), optional)]
pub materials: Option<HashMap<String, Handle<Gltf>>>, pub materials: Option<HashMap<String, Handle<Gltf>>>,

View File

@ -1,6 +1,6 @@
({ ({
"world":File (path: "models/World.glb"), /*"world":File (path: "models/World.glb"),
"models": Folder ( "models": Folder (
path: "models/library", path: "models/library",
), ),*/
}) })

View File

@ -11,6 +11,7 @@ impl Plugin for CorePlugin {
legacy_mode: false, legacy_mode: false,
library_folder: "models/library".into(), library_folder: "models/library".into(),
format: GltfFormat::GLB, format: GltfFormat::GLB,
material_library:true,
aabbs: true, aabbs: true,
..Default::default() ..Default::default()
}, },

View File

@ -1,5 +1,5 @@
use bevy::prelude::*; use bevy::{prelude::*, utils::hashbrown::HashMap};
use bevy_gltf_blueprints::{BluePrintBundle, BlueprintName, GameWorldTag}; use bevy_gltf_blueprints::{BluePrintBundle, BlueprintName, BlueprintsList, GameWorldTag, Library, SpawnHere};
use bevy_gltf_worlflow_examples_common_rapier::{assets::GameAssets, GameState, InAppRunning}; use bevy_gltf_worlflow_examples_common_rapier::{assets::GameAssets, GameState, InAppRunning};
use bevy_rapier3d::prelude::Velocity; use bevy_rapier3d::prelude::Velocity;
@ -7,31 +7,19 @@ use rand::Rng;
pub fn setup_game( pub fn setup_game(
mut commands: Commands, mut commands: Commands,
game_assets: Res<GameAssets>, asset_server: Res<AssetServer>,
models: Res<Assets<bevy::gltf::Gltf>>,
mut next_game_state: ResMut<NextState<GameState>>, mut next_game_state: ResMut<NextState<GameState>>,
) { ) {
commands.insert_resource(AmbientLight {
color: Color::WHITE,
brightness: 0.2,
});
// here we actually spawn our game world/level // here we actually spawn our game world/level
commands.spawn(( commands.spawn((
SceneBundle { SceneBundle{
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene scene: asset_server.load("models/World.glb#Scene0"),
scene: models
.get(game_assets.world.id())
.expect("main level should have been loaded")
.scenes[0]
.clone(),
..default() ..default()
}, },
bevy::prelude::Name::from("world"), bevy::prelude::Name::from("world"),
GameWorldTag, GameWorldTag,
InAppRunning, InAppRunning,
)); ));
next_game_state.set(GameState::InGame) next_game_state.set(GameState::InGame)
} }

View File

@ -97,13 +97,15 @@ impl Plugin for GamePlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.add_systems(Update, (spawn_test).run_if(in_state(GameState::InGame))) app.add_systems(Update, (spawn_test).run_if(in_state(GameState::InGame)))
.add_systems(Update, validate_export) .add_systems(Update, validate_export)
.add_systems(Update, generate_screenshot.run_if(on_timer(Duration::from_secs_f32(0.2)))) // TODO: run once
.add_systems(OnEnter(AppState::MenuRunning), start_game) .add_systems(OnEnter(AppState::MenuRunning), start_game)
.add_systems(OnEnter(AppState::AppRunning), setup_game) .add_systems(OnEnter(AppState::AppRunning), setup_game)
/* .add_systems(Update, generate_screenshot.run_if(on_timer(Duration::from_secs_f32(0.2)))) // TODO: run once
.add_systems( .add_systems(
Update, Update,
exit_game.run_if(on_timer(Duration::from_secs_f32(0.5))), exit_game.run_if(on_timer(Duration::from_secs_f32(0.5))),
) // shut down the app after this time ) // shut down the app after this time*/
; ;
} }
} }