bevy/examples/scene/scene.rs
ira 992681b59b Make Resource trait opt-in, requiring #[derive(Resource)] V2 (#5577)
*This PR description is an edited copy of #5007, written by @alice-i-cecile.*
# Objective
Follow-up to https://github.com/bevyengine/bevy/pull/2254. The `Resource` trait currently has a blanket implementation for all types that meet its bounds.

While ergonomic, this results in several drawbacks:

* it is possible to make confusing, silent mistakes such as inserting a function pointer (Foo) rather than a value (Foo::Bar) as a resource
* it is challenging to discover if a type is intended to be used as a resource
* we cannot later add customization options (see the [RFC](https://github.com/bevyengine/rfcs/blob/main/rfcs/27-derive-component.md) for the equivalent choice for Component).
* dependencies can use the same Rust type as a resource in invisibly conflicting ways
* raw Rust types used as resources cannot preserve privacy appropriately, as anyone able to access that type can read and write to internal values
* we cannot capture a definitive list of possible resources to display to users in an editor
## Notes to reviewers
 * Review this commit-by-commit; there's effectively no back-tracking and there's a lot of churn in some of these commits.
   *ira: My commits are not as well organized :')*
 * I've relaxed the bound on Local to Send + Sync + 'static: I don't think these concerns apply there, so this can keep things simple. Storing e.g. a u32 in a Local is fine, because there's a variable name attached explaining what it does.
 * I think this is a bad place for the Resource trait to live, but I've left it in place to make reviewing easier. IMO that's best tackled with https://github.com/bevyengine/bevy/issues/4981.

## Changelog
`Resource` is no longer automatically implemented for all matching types. Instead, use the new `#[derive(Resource)]` macro.

## Migration Guide
Add `#[derive(Resource)]` to all types you are using as a resource.

If you are using a third party type as a resource, wrap it in a tuple struct to bypass orphan rules. Consider deriving `Deref` and `DerefMut` to improve ergonomics.

`ClearColor` no longer implements `Component`. Using `ClearColor` as a component in 0.8 did nothing.
Use the `ClearColorConfig` in the `Camera3d` and `Camera2d` components instead.


Co-authored-by: Alice <alice.i.cecile@gmail.com>
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
Co-authored-by: devil-ira <justthecooldude@gmail.com>
Co-authored-by: Carter Anderson <mcanders1@gmail.com>
2022-08-08 21:36:35 +00:00

122 lines
4.6 KiB
Rust

//! This example illustrates loading scenes from files.
use bevy::{prelude::*, utils::Duration};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.register_type::<ComponentA>()
.register_type::<ComponentB>()
.add_startup_system(save_scene_system.exclusive_system())
.add_startup_system(load_scene_system)
.add_startup_system(infotext_system)
.add_system(log_system)
.run();
}
// Registered components must implement the `Reflect` and `FromWorld` traits.
// The `Reflect` trait enables serialization, deserialization, and dynamic property access.
// `Reflect` enable a bunch of cool behaviors, so its worth checking out the dedicated `reflect.rs`
// example. The `FromWorld` trait determines how your component is constructed when it loads.
// For simple use cases you can just implement the `Default` trait (which automatically implements
// FromResources). The simplest registered component just needs these two derives:
#[derive(Component, Reflect, Default)]
#[reflect(Component)] // this tells the reflect derive to also reflect component behaviors
struct ComponentA {
pub x: f32,
pub y: f32,
}
// Some components have fields that cannot (or should not) be written to scene files. These can be
// ignored with the #[reflect(ignore)] attribute. This is also generally where the `FromWorld`
// trait comes into play. `FromWorld` gives you access to your App's current ECS `Resources`
// when you construct your component.
#[derive(Component, Reflect)]
#[reflect(Component)]
struct ComponentB {
pub value: String,
#[reflect(ignore)]
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.time_since_startup(),
value: "Default Value".to_string(),
}
}
}
fn load_scene_system(mut commands: Commands, asset_server: Res<AssetServer>) {
// "Spawning" a scene bundle creates a new entity and spawns new instances
// of the given scene's entities as children of that entity.
commands.spawn_bundle(DynamicSceneBundle {
// Scenes are loaded just like any other asset.
scene: asset_server.load("scenes/load_scene_example.scn.ron"),
..default()
});
// This tells the AssetServer to watch for changes to assets.
// It enables our scenes to automatically reload in game when we modify their files
asset_server.watch_for_changes().unwrap();
}
// This system logs all ComponentA components in our world. Try making a change to a ComponentA in
// load_scene_example.scn. You should immediately see the changes appear in the console.
fn log_system(query: Query<(Entity, &ComponentA), Changed<ComponentA>>) {
for (entity, component_a) in &query {
info!(" Entity({})", entity.id());
info!(
" ComponentA: {{ x: {} y: {} }}\n",
component_a.x, component_a.y
);
}
}
fn save_scene_system(world: &mut World) {
// Scenes can be created from any ECS World. You can either create a new one for the scene or
// use the current World.
let mut scene_world = World::new();
let mut component_b = ComponentB::from_world(world);
component_b.value = "hello".to_string();
scene_world.spawn().insert_bundle((
component_b,
ComponentA { x: 1.0, y: 2.0 },
Transform::identity(),
));
scene_world
.spawn()
.insert_bundle((ComponentA { x: 3.0, y: 4.0 },));
// The TypeRegistry resource contains information about all registered types (including
// components). This is used to construct scenes.
let type_registry = world.resource::<AppTypeRegistry>();
let scene = DynamicScene::from_world(&scene_world, type_registry);
// Scenes can be serialized like this:
info!("{}", scene.serialize_ron(type_registry).unwrap());
// TODO: save scene
}
// This is only necessary for the info message in the UI. See examples/ui/text.rs for a standalone
// text example.
fn infotext_system(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn_bundle(Camera2dBundle::default());
commands.spawn_bundle(
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()
}),
);
}