chore(Bevy side): making clippy happy + started cleaning up demo code (non functional at this point)

This commit is contained in:
kaosat.dev 2024-08-13 02:03:40 +02:00
parent e3cec403a2
commit 792672c2ef
24 changed files with 174 additions and 439 deletions

View File

@ -191,7 +191,7 @@ pub fn trigger_instance_animation_markers_events(
animations.named_animations.get(animation_name) animations.named_animations.get(animation_name)
{ {
if let Some(__animation_clip) = animation_clips.get(animation_clip_handle) { if let Some(__animation_clip) = animation_clips.get(animation_clip_handle) {
println!("helooo") println!("found the animation clip");
} }
} }
} }

View File

@ -59,21 +59,12 @@ pub struct AssetLoadTracker {
} }
/// helper component, for tracking loaded assets /// helper component, for tracking loaded assets
#[derive(Component, Debug)] #[derive(Component, Default, Debug)]
pub(crate) struct BlueprintAssetsLoadState { pub(crate) struct BlueprintAssetsLoadState {
pub all_loaded: bool, pub all_loaded: bool,
pub asset_infos: Vec<AssetLoadTracker>, pub asset_infos: Vec<AssetLoadTracker>,
pub progress: f32, pub progress: f32,
} }
impl Default for BlueprintAssetsLoadState {
fn default() -> Self {
Self {
all_loaded: Default::default(),
asset_infos: Default::default(),
progress: Default::default(),
}
}
}
// for preloading asset files // for preloading asset files
#[derive(serde::Deserialize, bevy::asset::Asset, bevy::reflect::TypePath, Debug)] #[derive(serde::Deserialize, bevy::asset::Asset, bevy::reflect::TypePath, Debug)]

View File

@ -14,6 +14,7 @@ pub(crate) struct AssetToBlueprintInstancesMapper {
pub(crate) untyped_id_to_blueprint_entity_ids: HashMap<String, Vec<Entity>>, pub(crate) untyped_id_to_blueprint_entity_ids: HashMap<String, Vec<Entity>>,
} }
#[allow(clippy::too_many_arguments)]
pub(crate) fn react_to_asset_changes( pub(crate) fn react_to_asset_changes(
mut gltf_events: EventReader<AssetEvent<Gltf>>, // FIXME: Problem: we need to react to any asset change, not just gltf files ! mut gltf_events: EventReader<AssetEvent<Gltf>>, // FIXME: Problem: we need to react to any asset change, not just gltf files !
// mut untyped_events: EventReader<AssetEvent<LoadedUntypedAsset>>, // mut untyped_events: EventReader<AssetEvent<LoadedUntypedAsset>>,
@ -30,34 +31,32 @@ pub(crate) fn react_to_asset_changes(
for event in gltf_events.read() { for event in gltf_events.read() {
// LoadedUntypedAsset // LoadedUntypedAsset
match event {
AssetEvent::Modified { id } => { if let AssetEvent::Modified { id } = event {
// React to the gltf file being modified // React to the gltf file being modified
// println!("Modified gltf {:?}", asset_server.get_path(*id)); // println!("Modified gltf {:?}", asset_server.get_path(*id));
if let Some(asset_path) = asset_server.get_path(*id) { if let Some(asset_path) = asset_server.get_path(*id) {
// let untyped = asset_server.get_handle_untyped(asset_path.clone()); // let untyped = asset_server.get_handle_untyped(asset_path.clone());
// println!("matching untyped handle {:?}", untyped); // println!("matching untyped handle {:?}", untyped);
// let bla = untyped.unwrap().id(); // let bla = untyped.unwrap().id();
// asset_server.get // asset_server.get
// in order to avoid respawn both a parent & a child , which would crash Bevy, we do things in two steps // in order to avoid respawn both a parent & a child , which would crash Bevy, we do things in two steps
if let Some(entities) = assets_to_blueprint_instances if let Some(entities) = assets_to_blueprint_instances
.untyped_id_to_blueprint_entity_ids .untyped_id_to_blueprint_entity_ids
.get(&asset_path.to_string()) .get(&asset_path.to_string())
{ {
for entity in entities.iter() { for entity in entities.iter() {
// println!("matching blueprint instance {}", entity); // println!("matching blueprint instance {}", entity);
// disregard entities that are already (re) spawning // disregard entities that are already (re) spawning
if !respawn_candidates.contains(&entity) if !respawn_candidates.contains(&entity)
&& blueprint_assets.get(*entity).is_ok() && blueprint_assets.get(*entity).is_ok()
&& spawning_blueprints.get(*entity).is_err() && spawning_blueprints.get(*entity).is_err()
{ {
respawn_candidates.push(entity); respawn_candidates.push(entity);
}
} }
} }
} }
} }
_ => {}
} }
} }
// we process all candidates here to deal with the case where multiple assets have changed in a single frame, which could cause respawn chaos // we process all candidates here to deal with the case where multiple assets have changed in a single frame, which could cause respawn chaos

View File

@ -11,13 +11,13 @@ pub struct MaterialInfo {
#[derive(Component, Reflect, Default, Debug)] #[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)] #[reflect(Component)]
/// component containing the full list of MaterialInfos for a given entity/object /// component containing the full list of `MaterialInfos` for a given entity/object
pub struct MaterialInfos(Vec<MaterialInfo>); pub struct MaterialInfos(Vec<MaterialInfo>);
#[derive(Component, Default, Debug)] #[derive(Component, Default, Debug)]
pub struct MaterialProcessed; pub struct MaterialProcessed;
/// system that injects / replaces materials from material library /// system that injects / replaces materials from materials library
pub(crate) fn inject_materials( pub(crate) fn inject_materials(
mut blenvy_config: ResMut<BlenvyConfig>, mut blenvy_config: ResMut<BlenvyConfig>,
material_infos_query: Query< material_infos_query: Query<
@ -88,16 +88,14 @@ pub(crate) fn inject_materials(
if let Some(material) = material_found { if let Some(material) = material_found {
info!("Step 6: injecting/replacing materials"); info!("Step 6: injecting/replacing materials");
for (child_index, child) in children.iter().enumerate() { for (child_index, child) in children.iter().enumerate() {
if child_index == material_index { if child_index == material_index && with_materials_and_meshes.contains(*child) {
if with_materials_and_meshes.contains(*child) { info!(
info!( "injecting material {}, path: {:?}",
"injecting material {}, path: {:?}", material_info.name,
material_info.name, material_info.path.clone()
material_info.path.clone() );
);
commands.entity(*child).insert(material.clone()); commands.entity(*child).insert(material.clone());
}
} }
} }
} }

View File

@ -48,16 +48,10 @@ impl Default for BluePrintBundle {
} }
} }
#[derive(Debug, Clone)] #[derive(Debug, Default, Clone)]
/// Plugin for gltf blueprints /// Plugin for gltf blueprints
pub struct BlueprintsPlugin {} pub struct BlueprintsPlugin {}
impl Default for BlueprintsPlugin {
fn default() -> Self {
Self {}
}
}
fn hot_reload(watching_for_changes: Res<WatchingForChanges>) -> bool { fn hot_reload(watching_for_changes: Res<WatchingForChanges>) -> bool {
// println!("hot reload ? {}", watching_for_changes.0); // println!("hot reload ? {}", watching_for_changes.0);
watching_for_changes.0 watching_for_changes.0

View File

@ -226,7 +226,7 @@ pub(crate) fn blueprints_check_assets_metadata_files_loading(
let mut failed = false; let mut failed = false;
if let bevy::asset::LoadState::Failed(_) = asset_server.load_state(asset_id) { if let bevy::asset::LoadState::Failed(_) = asset_server.load_state(asset_id) {
failed = true failed = true;
} }
tracker.loaded = loaded || failed; tracker.loaded = loaded || failed;
if loaded || failed { if loaded || failed {
@ -408,7 +408,7 @@ pub(crate) fn blueprints_check_assets_loading(
let mut failed = false; let mut failed = false;
if let bevy::asset::LoadState::Failed(_) = asset_server.load_state(asset_id) { if let bevy::asset::LoadState::Failed(_) = asset_server.load_state(asset_id) {
warn!("FAILED TO LOAD {}", tracker.path.clone()); warn!("FAILED TO LOAD {}", tracker.path.clone());
failed = true failed = true;
} }
tracker.loaded = loaded || failed; tracker.loaded = loaded || failed;
if loaded || failed { if loaded || failed {
@ -660,6 +660,7 @@ pub struct BlueprintReadyForPostProcess;
/// - it copies the blueprint's root components to the entity it was spawned on (original entity) /// - it copies the blueprint's root components to the entity it was spawned on (original entity)
/// - it copies the children of the blueprint scene into the original entity /// - it copies the children of the blueprint scene into the original entity
/// - it adds an `AnimationLink` component containing the entity that has the `AnimationPlayer` so that animations can be controlled from the original entity /// - it adds an `AnimationLink` component containing the entity that has the `AnimationPlayer` so that animations can be controlled from the original entity
#[allow(clippy::too_many_arguments)]
pub(crate) fn blueprints_cleanup_spawned_scene( pub(crate) fn blueprints_cleanup_spawned_scene(
blueprint_scenes: Query< blueprint_scenes: Query<
( (

View File

@ -173,8 +173,6 @@ fn process_colorgrading(
gamma: blender_colorgrading.gamma, gamma: blender_colorgrading.gamma,
..Default::default() ..Default::default()
}, },
..Default::default()
}); });
commands.entity(scene_id).remove::<ColorGrading>(); commands.entity(scene_id).remove::<ColorGrading>();
} }

View File

@ -45,7 +45,7 @@ pub fn process_load_requests(
} }
pub fn should_load(loading_requests: Option<Res<LoadingRequested>>) -> bool { pub fn should_load(loading_requests: Option<Res<LoadingRequested>>) -> bool {
return resource_exists::<LoadingRequested>(loading_requests); resource_exists::<LoadingRequested>(loading_requests)
} }
// TODO: replace with generic despawner ? // TODO: replace with generic despawner ?

View File

@ -45,10 +45,10 @@ pub struct BlueprintWorld {
impl BlueprintWorld { impl BlueprintWorld {
pub fn from_path(path: &str) -> BlueprintWorld { pub fn from_path(path: &str) -> BlueprintWorld {
// let p = Path::new(&path); // let p = Path::new(&path);
return BlueprintWorld { BlueprintWorld {
// name: p.file_stem().unwrap().to_os_string().into_string().unwrap(), // seriously ? , also unwraps !! // name: p.file_stem().unwrap().to_os_string().into_string().unwrap(), // seriously ? , also unwraps !!
path: path.into(), path: path.into(),
}; }
} }
} }

View File

@ -38,7 +38,7 @@ pub fn process_save_requests(
} }
pub fn should_save(saving_requests: Option<Res<SavingRequested>>) -> bool { pub fn should_save(saving_requests: Option<Res<SavingRequested>>) -> bool {
return resource_exists::<SavingRequested>(saving_requests); resource_exists::<SavingRequested>(saving_requests)
} }
// any child of dynamic/ saveable entities that is not saveable itself should be removed from the list of children // any child of dynamic/ saveable entities that is not saveable itself should be removed from the list of children

View File

@ -73,11 +73,10 @@ pub fn animation_control(
animation_transitions animation_transitions
.play( .play(
&mut animation_player, &mut animation_player,
animations *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list"),
.clone(),
Duration::from_secs(5), Duration::from_secs(5),
) )
.repeat(); .repeat();
@ -94,11 +93,10 @@ pub fn animation_control(
animation_transitions animation_transitions
.play( .play(
&mut animation_player, &mut animation_player,
animations *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list"),
.clone(),
Duration::from_secs(5), Duration::from_secs(5),
) )
.repeat(); .repeat();
@ -114,11 +112,10 @@ pub fn animation_control(
animation_transitions animation_transitions
.play( .play(
&mut animation_player, &mut animation_player,
animations *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list"),
.clone(),
Duration::from_secs(5), Duration::from_secs(5),
) )
.repeat(); .repeat();
@ -134,11 +131,10 @@ pub fn animation_control(
animation_transitions animation_transitions
.play( .play(
&mut animation_player, &mut animation_player,
animations *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list"),
.clone(),
Duration::from_secs(5), Duration::from_secs(5),
) )
.repeat(); .repeat();

View File

@ -7,5 +7,5 @@ license = "MIT OR Apache-2.0"
[dependencies] [dependencies]
bevy = { version = "0.14", features = ["dynamic_linking"] } bevy = { version = "0.14", features = ["dynamic_linking"] }
blenvy = { path = "../../crates/blenvy" } blenvy = { path = "../../crates/blenvy" }
bevy_rapier3d = { version = "0.25.0", features = ["serde-serialize", "debug-render-3d", "enhanced-determinism"] }
rand = "0.8.5" rand = "0.8.5"
avian3d = "0.1.2"

View File

@ -1,83 +0,0 @@
use bevy::prelude::*;
use bevy_gltf_worlflow_examples_common_rapier::{assets::GameAssets, GameState, InAppRunning};
use blenvy::{BluePrintBundle, BlueprintName, GameWorldTag};
use bevy_rapier3d::prelude::Velocity;
use rand::Rng;
pub fn setup_game(
mut commands: Commands,
game_assets: Res<GameAssets>,
models: Res<Assets<bevy::gltf::Gltf>>,
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
commands.spawn((
SceneBundle {
// note: because of this issue https://github.com/bevyengine/bevy/issues/10436, "world" is now a gltf file instead of a scene
scene: models
.get(game_assets.world.clone().unwrap().id())
.expect("main level should have been loaded")
.scenes[0]
.clone(),
..default()
},
bevy::prelude::Name::from("world"),
GameWorldTag,
InAppRunning,
));
next_game_state.set(GameState::InGame)
}
#[derive(Component, Reflect, Default, Debug)]
#[reflect(Component)]
struct UnregisteredComponent;
pub fn spawn_test(
keycode: Res<ButtonInput<KeyCode>>,
mut commands: Commands,
mut game_world: Query<(Entity, &Children), With<GameWorldTag>>,
) {
if keycode.just_pressed(KeyCode::KeyT) {
let world = game_world.single_mut();
let world = world.1[0];
let mut rng = rand::thread_rng();
let range = 5.5;
let x: f32 = rng.gen_range(-range..range);
let y: f32 = rng.gen_range(-range..range);
let mut rng = rand::thread_rng();
let range = 0.8;
let vel_x: f32 = rng.gen_range(-range..range);
let vel_y: f32 = rng.gen_range(2.0..2.5);
let vel_z: f32 = rng.gen_range(-range..range);
let name_index: u64 = rng.gen();
let new_entity = commands
.spawn((
BluePrintBundle {
blueprint: BlueprintName("Health_Pickup".to_string()),
..Default::default()
},
bevy::prelude::Name::from(format!("test{}", name_index)),
// BlueprintName("Health_Pickup".to_string()),
// SpawnHere,
TransformBundle::from_transform(Transform::from_xyz(x, 2.0, y)),
Velocity {
linvel: Vec3::new(vel_x, vel_y, vel_z),
angvel: Vec3::new(0.0, 0.0, 0.0),
},
))
.id();
commands.entity(world).add_child(new_entity);
}
}

View File

@ -1,107 +0,0 @@
use bevy::prelude::*;
use bevy_gltf_worlflow_examples_common_rapier::{AppState, InMainMenu};
pub fn setup_main_menu(mut commands: Commands) {
commands.spawn((
Camera2dBundle {
camera: Camera {
order: 102, // needed because of this: https://github.com/jakobhellermann/bevy_editor_pls/blob/crates/bevy_editor_pls_default_windows/src/cameras/mod.rs#L213C9-L213C28
..default()
},
..Default::default()
},
InMainMenu,
));
commands.spawn((
TextBundle::from_section(
"SOME GAME TITLE !!",
TextStyle {
//font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 18.0,
color: Color::WHITE,
..Default::default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
top: Val::Px(100.0),
left: Val::Px(200.0),
..default()
}),
InMainMenu,
));
commands.spawn((
TextBundle::from_section(
"New Game (press Enter to start, press T once the game is started for demo spawning)",
TextStyle {
//font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 18.0,
color: Color::WHITE,
..Default::default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
top: Val::Px(200.0),
left: Val::Px(200.0),
..default()
}),
InMainMenu,
));
/*
commands.spawn((
TextBundle::from_section(
"Load Game",
TextStyle {
//font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 18.0,
color: Color::WHITE,
..Default::default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
top: Val::Px(250.0),
left: Val::Px(200.0),
..default()
}),
InMainMenu
));
commands.spawn((
TextBundle::from_section(
"Exit Game",
TextStyle {
//font: asset_server.load("fonts/FiraMono-Medium.ttf"),
font_size: 18.0,
color: Color::WHITE,
..Default::default()
},
)
.with_style(Style {
position_type: PositionType::Absolute,
top: Val::Px(300.0),
left: Val::Px(200.0),
..default()
}),
InMainMenu
));*/
}
pub fn teardown_main_menu(bla: Query<Entity, With<InMainMenu>>, mut commands: Commands) {
for bli in bla.iter() {
commands.entity(bli).despawn_recursive();
}
}
pub fn main_menu(
keycode: Res<ButtonInput<KeyCode>>,
mut next_app_state: ResMut<NextState<AppState>>,
) {
if keycode.just_pressed(KeyCode::Enter) {
next_app_state.set(AppState::AppLoading);
}
}

View File

@ -1,8 +1,4 @@
use bevy::{gltf::Gltf, prelude::*}; use bevy::{gltf::Gltf, prelude::*};
use bevy_gltf_worlflow_examples_common_rapier::{
assets::GameAssets, GameState, InAppRunning, Player,
};
use bevy_rapier3d::prelude::*;
use blenvy::GameWorldTag; use blenvy::GameWorldTag;
#[derive(Component, Reflect, Default, Debug)] #[derive(Component, Reflect, Default, Debug)]

View File

@ -1,22 +1,11 @@
pub mod in_game; // pub mod level_transitions;
pub use in_game::*; // pub use level_transitions::*;
pub mod in_main_menu;
pub use in_main_menu::*;
pub mod level_transitions;
pub use level_transitions::*;
use bevy::prelude::*; use bevy::prelude::*;
pub struct GamePlugin; pub struct GamePlugin;
impl Plugin for GamePlugin { impl Plugin for GamePlugin {
fn build(&self, app: &mut App) { fn build(&self, __app: &mut App) {
app.add_plugins(LevelsPlugin) //app.add_plugins(LevelsPlugin);
.add_systems(Update, (spawn_test).run_if(in_state(GameState::InGame)))
.add_systems(OnEnter(AppState::MenuRunning), setup_main_menu)
.add_systems(OnExit(AppState::MenuRunning), teardown_main_menu)
.add_systems(Update, main_menu.run_if(in_state(AppState::MenuRunning)))
.add_systems(OnEnter(AppState::AppRunning), setup_game);
} }
} }

View File

@ -1,12 +1,15 @@
use avian3d::prelude::*;
use bevy::prelude::*; use bevy::prelude::*;
use blenvy::{
mod core; AddToGameWorld, BlenvyPlugin, BluePrintBundle, BlueprintInfo, Dynamic, GameWorldTag,
use crate::core::*; HideUntilReady, SpawnBlueprint,
};
mod game; mod game;
use game::*; use game::*;
mod test_components; mod test_components;
use rand::Rng;
use test_components::*; use test_components::*;
fn main() { fn main() {
@ -14,9 +17,56 @@ fn main() {
.add_plugins(( .add_plugins((
DefaultPlugins.set(AssetPlugin::default()), DefaultPlugins.set(AssetPlugin::default()),
// our custom plugins // our custom plugins
CorePlugin, // reusable plugins ComponentsExamplesPlugin, // Showcases different type of components /structs
GamePlugin, // specific to our game BlenvyPlugin::default(),
ComponentsTestPlugin, // Showcases different type of components /structs GamePlugin,
)) ))
.add_systems(Startup, setup_game)
.add_systems(Update, spawn_blueprint_instance)
.run(); .run();
} }
// this is how you setup & spawn a level from a blueprint
fn setup_game(mut commands: Commands) {
// here we actually spawn our game world/level
commands.spawn((
BlueprintInfo::from_path("levels/World.glb"), // all we need is a Blueprint info...
SpawnBlueprint, // and spawnblueprint to tell blenvy to spawn the blueprint now
HideUntilReady, // only reveal the level once it is ready
GameWorldTag,
));
}
// you can also spawn blueprint instances at runtime
pub fn spawn_blueprint_instance(keycode: Res<ButtonInput<KeyCode>>, mut commands: Commands) {
if keycode.just_pressed(KeyCode::KeyS) {
let mut rng = rand::thread_rng();
let range = 5.5;
let x: f32 = rng.gen_range(-range..range);
let y: f32 = rng.gen_range(-range..range);
let mut rng = rand::thread_rng();
let range = 0.8;
let vel_x: f32 = rng.gen_range(-range..range);
let vel_y: f32 = rng.gen_range(2.0..2.5);
let vel_z: f32 = rng.gen_range(-range..range);
let name_index: u64 = rng.gen();
let __new_entity = commands
.spawn((
BluePrintBundle {
blueprint: BlueprintInfo::from_path("blueprints/Health_Pickup.glb"),
..Default::default()
},
Dynamic,
bevy::prelude::Name::from(format!("test{}", name_index)),
HideUntilReady,
AddToGameWorld,
TransformBundle::from_transform(Transform::from_xyz(x, 2.0, y)),
LinearVelocity(Vec3::new(vel_x, vel_y, vel_z)),
))
.id();
// commands.entity(world).add_child(new_entity);
}
}

View File

@ -60,8 +60,8 @@ pub enum EnumTest {
None, None,
} }
pub struct ComponentsTestPlugin; pub struct ComponentsExamplesPlugin;
impl Plugin for ComponentsTestPlugin { impl Plugin for ComponentsExamplesPlugin {
fn build(&self, app: &mut App) { fn build(&self, app: &mut App) {
app.register_type::<BasicTest>() app.register_type::<BasicTest>()
.register_type::<UnitTest>() .register_type::<UnitTest>()

View File

@ -2,8 +2,8 @@ use std::any::TypeId;
use bevy::{prelude::*, utils::hashbrown::HashSet}; use bevy::{prelude::*, utils::hashbrown::HashSet};
use blenvy::{ use blenvy::{
AddToGameWorld, BlenvyPlugin, BlueprintInfo, BlueprintWorld, Dynamic, GameWorldTag, AddToGameWorld, BlenvyPlugin, BlueprintInfo, BlueprintWorld, Dynamic, HideUntilReady,
HideUntilReady, LoadingRequest, SavingRequest, SpawnBlueprint, LoadingRequest, SavingRequest, SpawnBlueprint,
}; };
use rand::Rng; use rand::Rng;
@ -82,7 +82,7 @@ fn spawn_blueprint_instance(keycode: Res<ButtonInput<KeyCode>>, mut commands: Co
} }
} }
fn move_movers(mut movers: Query<(&mut Transform), With<Dynamic>>) { fn move_movers(mut movers: Query<&mut Transform, With<Dynamic>>) {
for mut transform in movers.iter_mut() { for mut transform in movers.iter_mut() {
// println!("moving dynamic entity"); // println!("moving dynamic entity");
transform.translation.x += 0.005; transform.translation.x += 0.005;

View File

@ -5,11 +5,11 @@ use std::time::Duration;
InstanceAnimationPlayerLink, InstanceAnimations, InstanceAnimationPlayerLink, InstanceAnimations,
};*/ };*/
use bevy::{animation::RepeatAnimation, gltf::Gltf, prelude::*}; use bevy::prelude::*;
use blenvy::{ use blenvy::{
AnimationInfos, AnimationMarkerReached, BlueprintAnimationPlayerLink, BlueprintAnimations, AnimationInfos, AnimationMarkerReached, BlueprintAnimationPlayerLink, BlueprintAnimations,
BlueprintInstanceDisabled, InstanceAnimationPlayerLink, InstanceAnimations, InstanceAnimationPlayerLink, InstanceAnimations,
}; };
#[derive(Component, Reflect, Default, Debug)] #[derive(Component, Reflect, Default, Debug)]
@ -79,68 +79,6 @@ pub fn animations(
} }
}*/ }*/
pub fn check_animations(
// (&BlueprintAnimationPlayerLink, &BlueprintAnimations)
foxes: Query<
(
Entity,
Option<&BlueprintAnimationPlayerLink>,
Option<&InstanceAnimationPlayerLink>,
),
(With<MarkerAllFoxes>, Without<BlueprintInstanceDisabled>),
>,
foo: Query<
(
Entity,
Option<&BlueprintAnimationPlayerLink>,
Option<&InstanceAnimationPlayerLink>,
),
(With<Marker1>, Without<BlueprintInstanceDisabled>),
>,
bar: Query<
(
Entity,
Option<&BlueprintAnimationPlayerLink>,
Option<&InstanceAnimationPlayerLink>,
),
(With<Marker2>, Without<BlueprintInstanceDisabled>),
>,
baz: Query<
(
Entity,
Option<&BlueprintAnimationPlayerLink>,
Option<&InstanceAnimationPlayerLink>,
),
(With<Marker3>, Without<BlueprintInstanceDisabled>),
>,
bli: Query<(Entity, &AnimationInfos)>,
anim_players: Query<(Entity, &AnimationPlayer)>,
all_names: Query<&Name>,
) {
/*for bla in foxes.iter() {
println!("MarkerAllFoxes {:?} {:?} {:?}", all_names.get(bla.0), bla.1, bla.2)
}
for bla in foo.iter() {
println!("Marker1 {:?} {:?} {:?}", all_names.get(bla.0), bla.1, bla.2)
}
for bla in bar.iter() {
println!("Marker2 {:?} {:?} {:?}", all_names.get(bla.0), bla.1, bla.2)
}
for bla in baz.iter() {
println!("Marker3 {:?} {:?} {:?}", all_names.get(bla.0), bla.1, bla.2)
}
println!(""); */
/*for blo in bli.iter() {
println!("YOOOOO {:?}", all_names.get(blo.0))
}
for anim in anim_players.iter() {
println!("Players {:?}", all_names.get(anim.0))
}*/
}
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
pub fn play_animations( pub fn play_animations(
animated_foxes: Query< animated_foxes: Query<
@ -183,11 +121,10 @@ pub fn play_animations(
let (mut animation_player, mut animation_transitions) = let (mut animation_player, mut animation_transitions) =
animation_players.get_mut(link.0).unwrap(); animation_players.get_mut(link.0).unwrap();
let anim_name = "Survey"; let anim_name = "Survey";
let animation_index = animations let animation_index = *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list");
.clone();
animation_transitions animation_transitions
.play( .play(
@ -204,23 +141,19 @@ pub fn play_animations(
println!("Playing animation {:?}", playing_animation); println!("Playing animation {:?}", playing_animation);
playing_animation.set_repeat(RepeatAnimation::Forever);*/ playing_animation.set_repeat(RepeatAnimation::Forever);*/
} }
println!("");
} }
if keycode.just_pressed(KeyCode::KeyP) { if keycode.just_pressed(KeyCode::KeyP) {
println!("playing fox blueprint animation requested"); println!("playing fox blueprint animation requested");
for (link, animations) in animated_foxes.iter() { for (link, animations) in animated_foxes.iter() {
println!("FOO");
// println!("animations {:?}", animations.named_animations); // println!("animations {:?}", animations.named_animations);
let (mut animation_player, mut animation_transitions) = let (mut animation_player, mut animation_transitions) =
animation_players.get_mut(link.0).unwrap(); animation_players.get_mut(link.0).unwrap();
let anim_name = "Run"; let anim_name = "Run";
let animation_index = animations let animation_index = *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list");
.clone();
animation_transitions animation_transitions
.play( .play(
@ -237,7 +170,7 @@ pub fn play_animations(
println!("Playing animation {:?}", playing_animation); println!("Playing animation {:?}", playing_animation);
playing_animation.set_repeat(RepeatAnimation::Forever);*/ playing_animation.set_repeat(RepeatAnimation::Forever);*/
} }
println!(""); println!(" ");
} }
if keycode.just_pressed(KeyCode::KeyO) { if keycode.just_pressed(KeyCode::KeyO) {
@ -248,11 +181,10 @@ pub fn play_animations(
let (mut animation_player, mut animation_transitions) = let (mut animation_player, mut animation_transitions) =
animation_players.get_mut(link.0).unwrap(); animation_players.get_mut(link.0).unwrap();
let anim_name = "Walk"; let anim_name = "Walk";
let animation_index = animations let animation_index = *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list");
.clone();
animation_transitions animation_transitions
.play( .play(
@ -271,11 +203,10 @@ pub fn play_animations(
let (mut animation_player, mut animation_transitions) = let (mut animation_player, mut animation_transitions) =
animation_players.get_mut(link.0).unwrap(); animation_players.get_mut(link.0).unwrap();
let anim_name = "Blueprint8_move"; let anim_name = "Blueprint8_move";
let animation_index = animations let animation_index = *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list");
.clone();
animation_transitions animation_transitions
.play( .play(
@ -294,11 +225,10 @@ pub fn play_animations(
animation_players.get_mut(link.0).unwrap(); animation_players.get_mut(link.0).unwrap();
let anim_name = "Blueprint1_move"; let anim_name = "Blueprint1_move";
let animation_index = animations let animation_index = *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list");
.clone();
animation_transitions animation_transitions
.play( .play(
@ -316,11 +246,10 @@ pub fn play_animations(
animation_players.get_mut(link.0).unwrap(); animation_players.get_mut(link.0).unwrap();
let anim_name = "Blueprint1_jump"; let anim_name = "Blueprint1_jump";
let animation_index = animations let animation_index = *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list");
.clone();
animation_transitions animation_transitions
.play( .play(
@ -338,11 +267,10 @@ pub fn play_animations(
animation_players.get_mut(link.0).unwrap(); animation_players.get_mut(link.0).unwrap();
let anim_name = "Blueprint1_move"; let anim_name = "Blueprint1_move";
let animation_index = animations let animation_index = *animations
.named_indices .named_indices
.get(anim_name) .get(anim_name)
.expect("animation name should be in the list") .expect("animation name should be in the list");
.clone();
animation_transitions animation_transitions
.play( .play(
@ -355,7 +283,7 @@ pub fn play_animations(
} }
} }
pub fn react_to_animation_markers( pub fn __react_to_animation_markers(
mut animation_marker_events: EventReader<AnimationMarkerReached>, mut animation_marker_events: EventReader<AnimationMarkerReached>,
) { ) {
for event in animation_marker_events.read() { for event in animation_marker_events.read() {

View File

@ -8,11 +8,7 @@ use blenvy::{
//use bevy_rapier3d::prelude::Velocity; //use bevy_rapier3d::prelude::Velocity;
use rand::Rng; use rand::Rng;
pub fn setup_game( pub fn setup_game(mut commands: Commands, mut next_game_state: ResMut<NextState<GameState>>) {
mut commands: Commands,
asset_server: Res<AssetServer>,
mut next_game_state: ResMut<NextState<GameState>>,
) {
// here we actually spawn our game world/level // here we actually spawn our game world/level
commands.spawn(( commands.spawn((
BlueprintInfo::from_path("levels/World.glb"), BlueprintInfo::from_path("levels/World.glb"),
@ -29,30 +25,22 @@ pub fn setup_game(
#[reflect(Component)] #[reflect(Component)]
struct UnregisteredComponent; struct UnregisteredComponent;
pub fn spawn_test( pub fn spawn_test(keycode: Res<ButtonInput<KeyCode>>, mut commands: Commands) {
keycode: Res<ButtonInput<KeyCode>>,
mut commands: Commands,
mut game_world: Query<(Entity, &Children), With<GameWorldTag>>,
) {
if keycode.just_pressed(KeyCode::KeyS) { if keycode.just_pressed(KeyCode::KeyS) {
let world = game_world.single_mut();
let world = world.1[0];
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let range = 5.5; let range = 5.5;
let x: f32 = rng.gen_range(-range..range); let x: f32 = rng.gen_range(-range..range);
let y: f32 = rng.gen_range(-range..range); let y: f32 = rng.gen_range(-range..range);
let mut rng = rand::thread_rng(); /*let mut rng = rand::thread_rng();
let range = 0.8; let range = 0.8;
let vel_x: f32 = rng.gen_range(-range..range); let vel_x: f32 = rng.gen_range(-range..range);
let vel_y: f32 = rng.gen_range(2.0..2.5); let vel_y: f32 = rng.gen_range(2.0..2.5);
let vel_z: f32 = rng.gen_range(-range..range); let vel_z: f32 = rng.gen_range(-range..range);*/
let name_index: u64 = rng.gen(); let name_index: u64 = rng.gen();
let new_entity = commands let __new_entity = commands
.spawn(( .spawn((
BluePrintBundle { BluePrintBundle {
blueprint: BlueprintInfo { blueprint: BlueprintInfo {

View File

@ -8,7 +8,7 @@ use std::{collections::HashMap, fs, time::Duration};
use blenvy::{ use blenvy::{
BlueprintAnimationPlayerLink, BlueprintAssets, BlueprintEvent, BlueprintInfo, BlueprintAnimationPlayerLink, BlueprintAssets, BlueprintEvent, BlueprintInfo,
GltfBlueprintsSet, InstanceAnimations, InstanceAnimations,
}; };
use crate::{AppState, GameState}; use crate::{AppState, GameState};
@ -136,8 +136,8 @@ fn check_for_gltf_events(
match event { match event {
BlueprintEvent::InstanceReady { BlueprintEvent::InstanceReady {
entity, entity,
blueprint_name, blueprint_name: _,
blueprint_path, blueprint_path: _,
} => { } => {
info!( info!(
"BLUEPRINT EVENT: {:?} for {:?}", "BLUEPRINT EVENT: {:?} for {:?}",
@ -147,8 +147,8 @@ fn check_for_gltf_events(
} }
BlueprintEvent::AssetsLoaded { BlueprintEvent::AssetsLoaded {
entity, entity,
blueprint_name, blueprint_name: _,
blueprint_path, blueprint_path: _,
} => { } => {
info!( info!(
"BLUEPRINT EVENT: {:?} for {:?}", "BLUEPRINT EVENT: {:?} for {:?}",
@ -156,9 +156,6 @@ fn check_for_gltf_events(
all_names.get(*entity) all_names.get(*entity)
); );
} }
_ => {
info!("BLUEPRINT EVENT: {:?}", event);
}
} }
} }
} }
@ -183,14 +180,14 @@ impl Plugin for GamePlugin {
.run_if(in_state(AppState::AppRunning)) .run_if(in_state(AppState::AppRunning))
.after(GltfBlueprintsSet::AfterSpawn) .after(GltfBlueprintsSet::AfterSpawn)
)*/ )*/
.add_systems(Update, (play_animations, check_animations)) .add_systems(Update, play_animations) // check_animations
//.add_systems(Update, react_to_animation_markers) //.add_systems(Update, react_to_animation_markers)
/*.add_systems(Update, generate_screenshot.run_if(on_timer(Duration::from_secs_f32(0.2)))) // TODO: run once .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
; ;
} }
} }

View File

@ -2,14 +2,13 @@ use bevy::{
gltf::{GltfMaterialExtras, GltfMeshExtras, GltfSceneExtras}, gltf::{GltfMaterialExtras, GltfMeshExtras, GltfSceneExtras},
prelude::*, prelude::*,
}; };
use blenvy::{BlueprintAssets, BlueprintInstanceReady};
use crate::{BasicTest, EnumComplex, EnumTest, RedirectPropHitImpulse}; use crate::{EnumTest, RedirectPropHitImpulse};
#[derive(Component)] #[derive(Component)]
pub struct HiearchyDebugTag; pub struct HiearchyDebugTag;
pub fn setup_hierarchy_debug(mut commands: Commands, asset_server: Res<AssetServer>) { pub fn setup_hierarchy_debug(mut commands: Commands) {
// a place to display the extras on screen // a place to display the extras on screen
commands.spawn(( commands.spawn((
TextBundle::from_section( TextBundle::from_section(
@ -40,25 +39,25 @@ pub fn get_descendants(
all_children: &Query<&Children>, all_children: &Query<&Children>,
all_names: &Query<&Name>, all_names: &Query<&Name>,
root: &Entity, root: &Entity,
all_transforms: &Query<&Transform>, __all_transforms: &Query<&Transform>,
all_global_transforms: &Query<&GlobalTransform>, __all_global_transforms: &Query<&GlobalTransform>,
nesting: usize, nesting: usize,
to_check: &Query<&EnumTest>, //&Query<(&BlueprintInstanceReady, &BlueprintAssets)>, to_check: &Query<&EnumTest>, //&Query<(&BlueprintInstanceReady, &BlueprintAssets)>,
) -> String { ) -> String {
let mut hierarchy_display: Vec<String> = vec![]; let mut hierarchy_display: Vec<String> = vec![];
let root_name = all_names.get(*root); let root_name = all_names.get(*root);
let name; let name;
if root_name.is_ok() { if let Ok(root_name) = root_name {
name = root_name.unwrap().to_string(); name = root_name.to_string();
} else { } else {
name = "no_name".to_string() name = "no_name".to_string();
} }
let mut component_display: String = "".into(); let mut component_display: String = "".into();
let components_to_check = to_check.get(*root); let __components_to_check = to_check.get(*root);
if let Ok(compo) = to_check.get(*root) { if let Ok(compo) = to_check.get(*root) {
component_display = format!("{:?}", compo).clone(); component_display = format!("{:?}", compo);
} }
hierarchy_display.push(format!( hierarchy_display.push(format!(
@ -72,22 +71,22 @@ pub fn get_descendants(
if let Ok(children) = all_children.get(*root) { if let Ok(children) = all_children.get(*root) {
for child in children.iter() { for child in children.iter() {
let child_descendants_display = get_descendants( let child_descendants_display = get_descendants(
&all_children, all_children,
&all_names, all_names,
&child, child,
&all_transforms, __all_transforms,
&all_global_transforms, __all_global_transforms,
nesting + 4, nesting + 4,
&to_check, to_check,
); );
hierarchy_display.push(child_descendants_display); hierarchy_display.push(child_descendants_display);
} }
} }
return hierarchy_display.join("\n"); hierarchy_display.join("\n")
} }
pub fn draw_hierarchy_debug( pub fn draw_hierarchy_debug(
root: Query<(Entity, Option<&Name>, &Children), (Without<Parent>)>, root: Query<Entity, Without<Parent>>,
all_children: Query<&Children>, all_children: Query<&Children>,
all_names: Query<&Name>, all_names: Query<&Name>,
all_transforms: Query<&Transform>, all_transforms: Query<&Transform>,
@ -98,7 +97,7 @@ pub fn draw_hierarchy_debug(
) { ) {
let mut hierarchy_display: Vec<String> = vec![]; let mut hierarchy_display: Vec<String> = vec![];
for (root_entity, name, children) in root.iter() { for root_entity in root.iter() {
// hierarchy_display.push( format!("Hierarchy root{:?}", name) ); // hierarchy_display.push( format!("Hierarchy root{:?}", name) );
hierarchy_display.push(get_descendants( hierarchy_display.push(get_descendants(
@ -124,7 +123,8 @@ pub fn draw_hierarchy_debug(
} }
////////:just some testing for gltf extras ////////:just some testing for gltf extras
fn check_for_gltf_extras( #[allow(clippy::type_complexity)]
fn __check_for_gltf_extras(
gltf_extras_per_entity: Query<( gltf_extras_per_entity: Query<(
Entity, Entity,
Option<&Name>, Option<&Name>,
@ -137,7 +137,7 @@ fn check_for_gltf_extras(
) { ) {
let mut gltf_extra_infos_lines: Vec<String> = vec![]; let mut gltf_extra_infos_lines: Vec<String> = vec![];
for (id, name, scene_extras, extras, mesh_extras, material_extras) in for (id, name, scene_extras, __extras, mesh_extras, material_extras) in
gltf_extras_per_entity.iter() gltf_extras_per_entity.iter()
{ {
if scene_extras.is_some() if scene_extras.is_some()
@ -165,12 +165,12 @@ fn check_for_gltf_extras(
} }
} }
fn check_for_component( fn __check_for_component(
foo: Query<(Entity, Option<&Name>, &RedirectPropHitImpulse)>, specific_components: Query<(Entity, Option<&Name>, &RedirectPropHitImpulse)>,
mut display: Query<&mut Text, With<HiearchyDebugTag>>, mut display: Query<&mut Text, With<HiearchyDebugTag>>,
) { ) {
let mut info_lines: Vec<String> = vec![]; let mut info_lines: Vec<String> = vec![];
for (entiity, name, enum_complex) in foo.iter() { for (__entiity, name, enum_complex) in specific_components.iter() {
let data = format!( let data = format!(
" We have a matching component: {:?} (on {:?})", " We have a matching component: {:?} (on {:?})",
enum_complex, name enum_complex, name

View File

@ -1,5 +1,6 @@
use bevy::prelude::*; use bevy::prelude::*;
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default, States)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default, States)]
pub enum AppState { pub enum AppState {
CoreLoading, CoreLoading,
@ -10,6 +11,7 @@ pub enum AppState {
AppEnding, AppEnding,
} }
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default, States)] #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default, States)]
pub enum GameState { pub enum GameState {
#[default] #[default]
@ -25,8 +27,6 @@ pub enum GameState {
} }
// tag components for all entities within a certain state (for despawning them if needed) , FIXME: seems kinda hack-ish // tag components for all entities within a certain state (for despawning them if needed) , FIXME: seems kinda hack-ish
#[derive(Component)]
pub struct InCoreLoading;
#[derive(Component, Default)] #[derive(Component, Default)]
pub struct InMenuRunning; pub struct InMenuRunning;
#[derive(Component)] #[derive(Component)]