Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_render/src/extract_resource.rs
9550 views
1
use core::marker::PhantomData;
2
3
use bevy_app::{App, Plugin};
4
use bevy_ecs::prelude::*;
5
pub use bevy_render_macros::ExtractResource;
6
use bevy_utils::once;
7
8
use crate::{Extract, ExtractSchedule, RenderApp};
9
10
/// Describes how a resource gets extracted for rendering.
11
///
12
/// Therefore the resource is transferred from the "main world" into the "render world"
13
/// in the [`ExtractSchedule`] step.
14
///
15
/// The marker type `F` is only used as a way to bypass the orphan rules. To
16
/// implement the trait for a foreign type you can use a local type as the
17
/// marker, e.g. the type of the plugin that calls [`ExtractResourcePlugin`].
18
pub trait ExtractResource<F = ()>: Resource {
19
type Source: Resource;
20
21
/// Defines how the resource is transferred into the "render world".
22
fn extract_resource(source: &Self::Source) -> Self;
23
}
24
25
/// This plugin extracts the resources into the "render world".
26
///
27
/// Therefore it sets up the[`ExtractSchedule`] step
28
/// for the specified [`Resource`].
29
///
30
/// The marker type `F` is only used as a way to bypass the orphan rules. To
31
/// implement the trait for a foreign type you can use a local type as the
32
/// marker, e.g. the type of the plugin that calls [`ExtractResourcePlugin`].
33
pub struct ExtractResourcePlugin<R: ExtractResource<F>, F = ()>(PhantomData<(R, F)>);
34
35
impl<R: ExtractResource<F>, F> Default for ExtractResourcePlugin<R, F> {
36
fn default() -> Self {
37
Self(PhantomData)
38
}
39
}
40
41
impl<R: ExtractResource<F>, F: 'static + Send + Sync> Plugin for ExtractResourcePlugin<R, F> {
42
fn build(&self, app: &mut App) {
43
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
44
render_app.add_systems(ExtractSchedule, extract_resource::<R, F>);
45
} else {
46
once!(bevy_log::error!(
47
"Render app did not exist when trying to add `extract_resource` for <{}>.",
48
core::any::type_name::<R>()
49
));
50
}
51
}
52
}
53
54
/// This system extracts the resource of the corresponding [`Resource`] type
55
pub fn extract_resource<R: ExtractResource<F>, F>(
56
mut commands: Commands,
57
main_resource: Extract<Option<Res<R::Source>>>,
58
target_resource: Option<ResMut<R>>,
59
) {
60
if let Some(main_resource) = main_resource.as_ref() {
61
if let Some(mut target_resource) = target_resource {
62
if main_resource.is_changed() {
63
*target_resource = R::extract_resource(main_resource);
64
}
65
} else {
66
#[cfg(debug_assertions)]
67
if !main_resource.is_added() {
68
once!(bevy_log::warn!(
69
"Removing resource {} from render world not expected, adding using `Commands`.
70
This may decrease performance",
71
core::any::type_name::<R>()
72
));
73
}
74
75
commands.insert_resource(R::extract_resource(main_resource));
76
}
77
}
78
}
79
80