use std::fs::File;
use std::io::Write;
use bevy::{prelude::*, tasks::IoTaskPool, utils::Duration};
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(AssetPlugin {
watch_for_changes: true,
..default()
}))
.register_type::<ComponentA>()
.register_type::<ComponentB>()
.add_startup_system(save_scene_system)
.add_startup_system(load_scene_system)
.add_startup_system(infotext_system)
.add_system(log_system)
.run();
}
#[derive(Component, Reflect, Default)]
#[reflect(Component)] struct ComponentA {
pub x: f32,
pub y: f32,
}
#[derive(Component, Reflect)]
#[reflect(Component)]
struct ComponentB {
pub value: String,
#[reflect(skip_serializing)]
pub _time_since_startup: Duration,
}
impl FromWorld for ComponentB {
fn from_world(world: &mut World) -> Self {
let time = world.resource::<Time>();
ComponentB {
_time_since_startup: time.elapsed(),
value: "Default Value".to_string(),
}
}
}
const SCENE_FILE_PATH: &str = "scenes/load_scene_example.scn.ron";
const NEW_SCENE_FILE_PATH: &str = "scenes/load_scene_example-new.scn.ron";
fn load_scene_system(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(DynamicSceneBundle {
scene: asset_server.load(SCENE_FILE_PATH),
..default()
});
}
fn log_system(query: Query<(Entity, &ComponentA), Changed<ComponentA>>) {
for (entity, component_a) in &query {
info!(" Entity({})", entity.index());
info!(
" ComponentA: {{ x: {} y: {} }}\n",
component_a.x, component_a.y
);
}
}
fn save_scene_system(world: &mut World) {
let mut scene_world = World::new();
let mut component_b = ComponentB::from_world(world);
component_b.value = "hello".to_string();
scene_world.spawn((
component_b,
ComponentA { x: 1.0, y: 2.0 },
Transform::IDENTITY,
));
scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
let type_registry = world.resource::<AppTypeRegistry>();
let scene = DynamicScene::from_world(&scene_world, type_registry);
let serialized_scene = scene.serialize_ron(type_registry).unwrap();
info!("{}", serialized_scene);
#[cfg(not(target_arch = "wasm32"))]
IoTaskPool::get()
.spawn(async move {
File::create(format!("assets/{NEW_SCENE_FILE_PATH}"))
.and_then(|mut file| file.write(serialized_scene.as_bytes()))
.expect("Error while writing scene to file");
})
.detach();
}
fn infotext_system(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
commands.spawn(
TextBundle::from_section(
"Nothing to see in this window! Check the console output!",
TextStyle {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 50.0,
color: Color::WHITE,
},
)
.with_style(Style {
align_self: AlignSelf::FlexEnd,
..default()
}),
);
}