Skip to content

Commit

Permalink
Merge branch 'bevyengine:main' into fix-color-add
Browse files Browse the repository at this point in the history
  • Loading branch information
vertesians committed Aug 17, 2022
2 parents b7a1fcc + aed3232 commit 38ce90d
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 54 deletions.
4 changes: 3 additions & 1 deletion crates/bevy_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub mod prelude {
use bevy_app::prelude::*;
use bevy_ecs::entity::Entity;
use bevy_utils::HashSet;
use std::borrow::Cow;
use std::ops::Range;

/// Adds core functionality to Apps.
Expand All @@ -43,7 +44,8 @@ fn register_rust_types(app: &mut App) {
app.register_type::<Range<f32>>()
.register_type::<String>()
.register_type::<HashSet<String>>()
.register_type::<Option<String>>();
.register_type::<Option<String>>()
.register_type::<Cow<'static, str>>();
}

fn register_math_types(app: &mut App) {
Expand Down
29 changes: 15 additions & 14 deletions crates/bevy_ecs/src/schedule/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,10 @@ impl Schedule {
)
}

let label = stage_label.as_label();
let stage = self
.get_stage_mut::<SystemStage>(&stage_label)
.unwrap_or_else(move || stage_not_found(&stage_label.as_label()));
.get_stage_mut::<SystemStage>(label)
.unwrap_or_else(move || stage_not_found(&label));
stage.add_system(system);
self
}
Expand Down Expand Up @@ -278,14 +279,12 @@ impl Schedule {
/// Panics if `label` refers to a non-existing stage, or if it's not of type `T`.
pub fn stage<T: Stage, F: FnOnce(&mut T) -> &mut T>(
&mut self,
label: impl StageLabel,
stage_label: impl StageLabel,
func: F,
) -> &mut Self {
let stage = self.get_stage_mut::<T>(&label).unwrap_or_else(move || {
panic!(
"stage '{:?}' does not exist or is the wrong type",
label.as_label()
)
let label = stage_label.as_label();
let stage = self.get_stage_mut::<T>(label).unwrap_or_else(move || {
panic!("stage '{label:?}' does not exist or is the wrong type",)
});
func(stage);
self
Expand All @@ -304,11 +303,12 @@ impl Schedule {
/// # let mut schedule = Schedule::default();
/// # schedule.add_stage("my_stage", SystemStage::parallel());
/// #
/// let stage = schedule.get_stage::<SystemStage>(&"my_stage").unwrap();
/// let stage = schedule.get_stage::<SystemStage>("my_stage").unwrap();
/// ```
pub fn get_stage<T: Stage>(&self, label: &dyn StageLabel) -> Option<&T> {
pub fn get_stage<T: Stage>(&self, stage_label: impl StageLabel) -> Option<&T> {
let label = stage_label.as_label();
self.stages
.get(&label.as_label())
.get(&label)
.and_then(|stage| stage.downcast_ref::<T>())
}

Expand All @@ -325,11 +325,12 @@ impl Schedule {
/// # let mut schedule = Schedule::default();
/// # schedule.add_stage("my_stage", SystemStage::parallel());
/// #
/// let stage = schedule.get_stage_mut::<SystemStage>(&"my_stage").unwrap();
/// let stage = schedule.get_stage_mut::<SystemStage>("my_stage").unwrap();
/// ```
pub fn get_stage_mut<T: Stage>(&mut self, label: &dyn StageLabel) -> Option<&mut T> {
pub fn get_stage_mut<T: Stage>(&mut self, stage_label: impl StageLabel) -> Option<&mut T> {
let label = stage_label.as_label();
self.stages
.get_mut(&label.as_label())
.get_mut(&label)
.and_then(|stage| stage.downcast_mut::<T>())
}

Expand Down
39 changes: 30 additions & 9 deletions crates/bevy_reflect/src/impls/std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ impl_from_reflect_value!(String);
impl_from_reflect_value!(HashSet<T: Hash + Eq + Clone + Send + Sync + 'static>);
impl_from_reflect_value!(Range<T: Clone + Send + Sync + 'static>);
impl_from_reflect_value!(Duration);
impl_from_reflect_value!(Instant);
impl_from_reflect_value!(NonZeroI128);
impl_from_reflect_value!(NonZeroU128);
impl_from_reflect_value!(NonZeroIsize);
Expand Down Expand Up @@ -585,13 +586,13 @@ impl Reflect for Cow<'static, str> {
}
}

impl<T: Reflect + Clone> GetTypeRegistration for Option<T> {
impl<T: FromReflect> GetTypeRegistration for Option<T> {
fn get_type_registration() -> TypeRegistration {
TypeRegistration::of::<Option<T>>()
}
}

impl<T: Reflect + Clone> Enum for Option<T> {
impl<T: FromReflect> Enum for Option<T> {
fn field(&self, _name: &str) -> Option<&dyn Reflect> {
None
}
Expand Down Expand Up @@ -655,7 +656,7 @@ impl<T: Reflect + Clone> Enum for Option<T> {
}
}

impl<T: Reflect + Clone> Reflect for Option<T> {
impl<T: FromReflect> Reflect for Option<T> {
#[inline]
fn type_name(&self) -> &str {
std::any::type_name::<Self>()
Expand Down Expand Up @@ -741,7 +742,7 @@ impl<T: Reflect + Clone> Reflect for Option<T> {

#[inline]
fn clone_value(&self) -> Box<dyn Reflect> {
Box::new(self.clone())
Box::new(Enum::clone_dynamic(self))
}

fn reflect_hash(&self) -> Option<u64> {
Expand All @@ -753,7 +754,7 @@ impl<T: Reflect + Clone> Reflect for Option<T> {
}
}

impl<T: Reflect + Clone> FromReflect for Option<T> {
impl<T: FromReflect> FromReflect for Option<T> {
fn from_reflect(reflect: &dyn Reflect) -> Option<Self> {
if let ReflectRef::Enum(dyn_enum) = reflect.reflect_ref() {
match dyn_enum.variant_name() {
Expand All @@ -762,7 +763,7 @@ impl<T: Reflect + Clone> FromReflect for Option<T> {
.field_at(0)
.expect("Field at index 0 should exist")
.clone_value();
let field = field.take::<T>().unwrap_or_else(|_| {
let field = T::from_reflect(field.as_ref()).unwrap_or_else(|| {
panic!(
"Field at index 0 should be of type {}",
std::any::type_name::<T>()
Expand All @@ -783,7 +784,7 @@ impl<T: Reflect + Clone> FromReflect for Option<T> {
}
}

impl<T: Reflect + Clone> Typed for Option<T> {
impl<T: FromReflect> Typed for Option<T> {
fn type_info() -> &'static TypeInfo {
static CELL: GenericTypeInfoCell = GenericTypeInfoCell::new();
CELL.get_or_insert::<Self, _>(|| {
Expand Down Expand Up @@ -827,10 +828,12 @@ impl FromReflect for Cow<'static, str> {

#[cfg(test)]
mod tests {
use crate as bevy_reflect;
use crate::{
Enum, Reflect, ReflectSerialize, TypeInfo, TypeRegistry, Typed, VariantInfo, VariantType,
Enum, FromReflect, Reflect, ReflectSerialize, TypeInfo, TypeRegistry, Typed, VariantInfo,
VariantType,
};
use bevy_utils::HashMap;
use bevy_utils::{HashMap, Instant};
use std::f32::consts::{PI, TAU};

#[test]
Expand Down Expand Up @@ -939,6 +942,17 @@ mod tests {
assert_eq!(Some(321), value);
}

#[test]
fn option_should_from_reflect() {
#[derive(Reflect, FromReflect, PartialEq, Debug)]
struct Foo(usize);

let expected = Some(Foo(123));
let output = <Option<Foo> as FromReflect>::from_reflect(&expected).unwrap();

assert_eq!(expected, output);
}

#[test]
fn option_should_impl_typed() {
type MyOption = Option<i32>;
Expand Down Expand Up @@ -979,4 +993,11 @@ mod tests {
let forty_two: std::num::NonZeroUsize = crate::FromReflect::from_reflect(a).unwrap();
assert_eq!(forty_two, std::num::NonZeroUsize::new(42).unwrap());
}

#[test]
fn instant_should_from_reflect() {
let expected = Instant::now();
let output = <Instant as FromReflect>::from_reflect(&expected).unwrap();
assert_eq!(expected, output);
}
}
5 changes: 3 additions & 2 deletions crates/bevy_render/src/camera/camera.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use bevy_ecs::{
};
use bevy_math::{Mat4, UVec2, Vec2, Vec3};
use bevy_reflect::prelude::*;
use bevy_reflect::FromReflect;
use bevy_transform::components::GlobalTransform;
use bevy_utils::HashSet;
use bevy_window::{WindowCreated, WindowId, WindowResized, Windows};
Expand All @@ -32,7 +33,7 @@ use wgpu::Extent3d;
/// You can overlay multiple cameras in a single window using viewports to create effects like
/// split screen, minimaps, and character viewers.
// TODO: remove reflect_value when possible
#[derive(Reflect, Debug, Clone, Serialize, Deserialize)]
#[derive(Reflect, FromReflect, Debug, Clone, Serialize, Deserialize)]
#[reflect_value(Default, Serialize, Deserialize)]
pub struct Viewport {
/// The physical position to render this viewport to within the [`RenderTarget`] of this [`Camera`].
Expand Down Expand Up @@ -71,7 +72,7 @@ pub struct ComputedCameraValues {
target_info: Option<RenderTargetInfo>,
}

#[derive(Component, Debug, Reflect, Clone)]
#[derive(Component, Debug, Reflect, FromReflect, Clone)]
#[reflect(Component)]
pub struct Camera {
/// If set, this camera will render to the given [`Viewport`] rectangle within the configured [`RenderTarget`].
Expand Down
12 changes: 6 additions & 6 deletions crates/bevy_render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ impl Plugin for RenderPlugin {
// prepare
let prepare = render_app
.schedule
.get_stage_mut::<SystemStage>(&RenderStage::Prepare)
.get_stage_mut::<SystemStage>(RenderStage::Prepare)
.unwrap();
prepare.run(&mut render_app.world);
}
Expand All @@ -262,7 +262,7 @@ impl Plugin for RenderPlugin {
// queue
let queue = render_app
.schedule
.get_stage_mut::<SystemStage>(&RenderStage::Queue)
.get_stage_mut::<SystemStage>(RenderStage::Queue)
.unwrap();
queue.run(&mut render_app.world);
}
Expand All @@ -275,7 +275,7 @@ impl Plugin for RenderPlugin {
// phase sort
let phase_sort = render_app
.schedule
.get_stage_mut::<SystemStage>(&RenderStage::PhaseSort)
.get_stage_mut::<SystemStage>(RenderStage::PhaseSort)
.unwrap();
phase_sort.run(&mut render_app.world);
}
Expand All @@ -288,7 +288,7 @@ impl Plugin for RenderPlugin {
// render
let render = render_app
.schedule
.get_stage_mut::<SystemStage>(&RenderStage::Render)
.get_stage_mut::<SystemStage>(RenderStage::Render)
.unwrap();
render.run(&mut render_app.world);
}
Expand All @@ -301,7 +301,7 @@ impl Plugin for RenderPlugin {
// cleanup
let cleanup = render_app
.schedule
.get_stage_mut::<SystemStage>(&RenderStage::Cleanup)
.get_stage_mut::<SystemStage>(RenderStage::Cleanup)
.unwrap();
cleanup.run(&mut render_app.world);
}
Expand Down Expand Up @@ -335,7 +335,7 @@ struct ScratchMainWorld(World);
fn extract(app_world: &mut World, render_app: &mut App) {
let extract = render_app
.schedule
.get_stage_mut::<SystemStage>(&RenderStage::Extract)
.get_stage_mut::<SystemStage>(RenderStage::Extract)
.unwrap();

// temporarily add the app world to the render world as a resource
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_render/src/render_graph/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::{borrow::Cow, fmt::Debug};
use super::EdgeExistence;

/// The render graph configures the modular, parallel and re-usable render logic.
/// It is a retained and stateless (nodes themselves may have internal state) structure,
/// It is a retained and stateless (nodes themselves may have their own internal state) structure,
/// which can not be modified while it is executed by the graph runner.
///
/// The `RenderGraphRunner` is responsible for executing the entire graph each frame.
Expand Down
7 changes: 3 additions & 4 deletions crates/bevy_sprite/src/mesh2d/color_material.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@ struct FragmentInput {
@fragment
fn fragment(in: FragmentInput) -> @location(0) vec4<f32> {
var output_color: vec4<f32> = material.color;
if ((material.flags & COLOR_MATERIAL_FLAGS_TEXTURE_BIT) != 0u) {
#ifdef VERTEX_COLORS
output_color = output_color * textureSample(texture, texture_sampler, in.uv) * in.color;
#else
output_color = output_color * textureSample(texture, texture_sampler, in.uv);
output_color = output_color * in.color;
#endif
if ((material.flags & COLOR_MATERIAL_FLAGS_TEXTURE_BIT) != 0u) {
output_color = output_color * textureSample(texture, texture_sampler, in.uv);
}
return output_color;
}
4 changes: 2 additions & 2 deletions crates/bevy_time/src/time.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use bevy_ecs::{reflect::ReflectResource, system::Resource};
use bevy_reflect::Reflect;
use bevy_reflect::{FromReflect, Reflect};
use bevy_utils::{Duration, Instant};

/// Tracks elapsed time since the last update and since the App has started
#[derive(Resource, Reflect, Debug, Clone)]
#[derive(Resource, Reflect, FromReflect, Debug, Clone)]
#[reflect(Resource)]
pub struct Time {
delta: Duration,
Expand Down
26 changes: 22 additions & 4 deletions examples/2d/mesh2d_vertex_color_texture.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
//! Shows how to render a polygonal [`Mesh`], generated from a [`Quad`] primitive, in a 2D scene.
//! Adds a texture and colored vertices, giving per-vertex tinting.

use bevy::{prelude::*, sprite::MaterialMesh2dBundle};
use bevy::{
prelude::*,
sprite::{MaterialMesh2dBundle, Mesh2dHandle},
};

fn main() {
App::new()
Expand Down Expand Up @@ -29,11 +32,26 @@ fn setup(
];
// Insert the vertex colors as an attribute
mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, vertex_colors);
// Spawn

let mesh_handle: Mesh2dHandle = meshes.add(mesh).into();

// Spawn camera
commands.spawn_bundle(Camera2dBundle::default());

// Spawn the quad with vertex colors
commands.spawn_bundle(MaterialMesh2dBundle {
mesh: mesh_handle.clone(),
transform: Transform::from_translation(Vec3::new(-96., 0., 0.))
.with_scale(Vec3::splat(128.)),
material: materials.add(ColorMaterial::default()),
..default()
});

// Spawning the quad with vertex colors and a texture results in tinting
commands.spawn_bundle(MaterialMesh2dBundle {
mesh: meshes.add(mesh).into(),
transform: Transform::default().with_scale(Vec3::splat(128.)),
mesh: mesh_handle,
transform: Transform::from_translation(Vec3::new(96., 0., 0.))
.with_scale(Vec3::splat(128.)),
material: materials.add(ColorMaterial::from(texture_handle)),
..default()
});
Expand Down
22 changes: 11 additions & 11 deletions examples/games/breakout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use bevy::{
prelude::*,
sprite::collide_aabb::{collide, Collision},
sprite::MaterialMesh2dBundle,
time::FixedTimestep,
};

Expand Down Expand Up @@ -171,7 +172,12 @@ struct Scoreboard {
}

// Add the game's entities to our world
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
asset_server: Res<AssetServer>,
) {
// Camera
commands.spawn_bundle(Camera2dBundle::default());

Expand Down Expand Up @@ -203,16 +209,10 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands
.spawn()
.insert(Ball)
.insert_bundle(SpriteBundle {
transform: Transform {
scale: BALL_SIZE,
translation: BALL_STARTING_POSITION,
..default()
},
sprite: Sprite {
color: BALL_COLOR,
..default()
},
.insert_bundle(MaterialMesh2dBundle {
mesh: meshes.add(shape::Circle::default().into()).into(),
material: materials.add(ColorMaterial::from(BALL_COLOR)),
transform: Transform::from_translation(BALL_STARTING_POSITION).with_scale(BALL_SIZE),
..default()
})
.insert(Velocity(INITIAL_BALL_DIRECTION.normalize() * BALL_SPEED));
Expand Down

0 comments on commit 38ce90d

Please sign in to comment.