use bevy::{prelude::*, type_registry::TypeRegistry};
fn main() {
App::build()
.add_default_plugins()
.register_component::<ComponentA>()
.register_component::<ComponentB>()
.add_startup_system(save_scene_system.thread_local_system())
.add_startup_system(load_scene_system.system())
.add_startup_system(infotext_system.system())
.add_system(print_system.system())
.run();
}
#[derive(Properties, Default)]
struct ComponentA {
pub x: f32,
pub y: f32,
}
#[derive(Properties)]
struct ComponentB {
pub value: String,
#[property(ignore)]
pub time_since_startup: std::time::Duration,
}
impl FromResources for ComponentB {
fn from_resources(resources: &Resources) -> Self {
let time = resources.get::<Time>().unwrap();
ComponentB {
time_since_startup: time.time_since_startup(),
value: "Default Value".to_string(),
}
}
}
fn load_scene_system(asset_server: Res<AssetServer>, mut scene_spawner: ResMut<SceneSpawner>) {
let scene_handle: Handle<Scene> = asset_server
.load("assets/scenes/load_scene_example.scn")
.unwrap();
scene_spawner.spawn(scene_handle);
asset_server.watch_for_changes().unwrap();
}
#[allow(dead_code)]
fn load_scene_right_now_system(world: &mut World, resources: &mut Resources) {
let scene_handle: Handle<Scene> = {
let asset_server = resources.get::<AssetServer>().unwrap();
let mut scenes = resources.get_mut::<Assets<Scene>>().unwrap();
asset_server
.load_sync(&mut scenes, "assets/scenes/load_scene_example.scn")
.unwrap()
};
let mut scene_spawner = resources.get_mut::<SceneSpawner>().unwrap();
scene_spawner
.spawn_sync(world, resources, scene_handle)
.unwrap();
}
fn print_system(mut query: Query<(Entity, Changed<ComponentA>)>) {
for (entity, component_a) in &mut query.iter() {
println!(" Entity({})", entity.id());
println!(
" ComponentA: {{ x: {} y: {} }}\n",
component_a.x, component_a.y
);
}
}
fn save_scene_system(_world: &mut World, resources: &mut Resources) {
let mut world = World::new();
world.spawn((
ComponentA { x: 1.0, y: 2.0 },
ComponentB {
value: "hello".to_string(),
..ComponentB::from_resources(resources)
},
));
world.spawn((ComponentA { x: 3.0, y: 4.0 },));
let type_registry = resources.get::<TypeRegistry>().unwrap();
let scene = Scene::from_world(&world, &type_registry.component.read());
println!(
"{}",
scene.serialize_ron(&type_registry.property.read()).unwrap()
);
}
fn infotext_system(mut commands: Commands, asset_server: Res<AssetServer>) {
let font_handle = asset_server.load("assets/fonts/FiraSans-Bold.ttf").unwrap();
commands
.spawn(UiCameraComponents::default())
.spawn(TextComponents {
style: Style {
align_self: AlignSelf::FlexEnd,
..Default::default()
},
text: Text {
value: "Nothing to see in this window! Check the console output!".to_string(),
font: font_handle,
style: TextStyle {
font_size: 50.0,
color: Color::WHITE,
},
},
..Default::default()
});
}