Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 10:29:08 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions

View File

@@ -0,0 +1,409 @@
//! Eat the cakes. Eat them all. An example 3D game.
use std::f32::consts::PI;
use bevy::prelude::*;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default, States)]
enum GameState {
#[default]
Playing,
GameOver,
}
#[derive(Resource)]
struct BonusSpawnTimer(Timer);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<Game>()
.insert_resource(BonusSpawnTimer(Timer::from_seconds(
5.0,
TimerMode::Repeating,
)))
.init_state::<GameState>()
.enable_state_scoped_entities::<GameState>()
.add_systems(Startup, setup_cameras)
.add_systems(OnEnter(GameState::Playing), setup)
.add_systems(
Update,
(
move_player,
focus_camera,
rotate_bonus,
scoreboard_system,
spawn_bonus,
)
.run_if(in_state(GameState::Playing)),
)
.add_systems(OnEnter(GameState::GameOver), display_score)
.add_systems(
Update,
game_over_keyboard.run_if(in_state(GameState::GameOver)),
)
.run();
}
struct Cell {
height: f32,
}
#[derive(Default)]
struct Player {
entity: Option<Entity>,
i: usize,
j: usize,
move_cooldown: Timer,
}
#[derive(Default)]
struct Bonus {
entity: Option<Entity>,
i: usize,
j: usize,
handle: Handle<Scene>,
}
#[derive(Resource, Default)]
struct Game {
board: Vec<Vec<Cell>>,
player: Player,
bonus: Bonus,
score: i32,
cake_eaten: u32,
camera_should_focus: Vec3,
camera_is_focus: Vec3,
}
#[derive(Resource, Deref, DerefMut)]
struct Random(ChaCha8Rng);
const BOARD_SIZE_I: usize = 14;
const BOARD_SIZE_J: usize = 21;
const RESET_FOCUS: [f32; 3] = [
BOARD_SIZE_I as f32 / 2.0,
0.0,
BOARD_SIZE_J as f32 / 2.0 - 0.5,
];
fn setup_cameras(mut commands: Commands, mut game: ResMut<Game>) {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
game.camera_is_focus = game.camera_should_focus;
commands.spawn((
Camera3d::default(),
Transform::from_xyz(
-(BOARD_SIZE_I as f32 / 2.0),
2.0 * BOARD_SIZE_J as f32 / 3.0,
BOARD_SIZE_J as f32 / 2.0 - 0.5,
)
.looking_at(game.camera_is_focus, Vec3::Y),
));
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMut<Game>) {
let mut rng = if std::env::var("GITHUB_ACTIONS") == Ok("true".to_string()) {
// We're seeding the PRNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
ChaCha8Rng::seed_from_u64(19878367467713)
} else {
ChaCha8Rng::from_entropy()
};
// reset the game state
game.cake_eaten = 0;
game.score = 0;
game.player.i = BOARD_SIZE_I / 2;
game.player.j = BOARD_SIZE_J / 2;
game.player.move_cooldown = Timer::from_seconds(0.3, TimerMode::Once);
commands.spawn((
StateScoped(GameState::Playing),
PointLight {
intensity: 2_000_000.0,
shadows_enabled: true,
range: 30.0,
..default()
},
Transform::from_xyz(4.0, 10.0, 4.0),
));
// spawn the game board
let cell_scene =
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/tile.glb"));
game.board = (0..BOARD_SIZE_J)
.map(|j| {
(0..BOARD_SIZE_I)
.map(|i| {
let height = rng.gen_range(-0.1..0.1);
commands.spawn((
StateScoped(GameState::Playing),
Transform::from_xyz(i as f32, height - 0.2, j as f32),
SceneRoot(cell_scene.clone()),
));
Cell { height }
})
.collect()
})
.collect();
// spawn the game character
game.player.entity = Some(
commands
.spawn((
StateScoped(GameState::Playing),
Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(-PI / 2.),
..default()
},
SceneRoot(
asset_server
.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/alien.glb")),
),
))
.id(),
);
// load the scene for the cake
game.bonus.handle =
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/AlienCake/cakeBirthday.glb"));
// scoreboard
commands.spawn((
StateScoped(GameState::Playing),
Text::new("Score:"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
Node {
position_type: PositionType::Absolute,
top: Val::Px(5.0),
left: Val::Px(5.0),
..default()
},
));
commands.insert_resource(Random(rng));
}
// control the game character
fn move_player(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut game: ResMut<Game>,
mut transforms: Query<&mut Transform>,
time: Res<Time>,
) {
if game.player.move_cooldown.tick(time.delta()).finished() {
let mut moved = false;
let mut rotation = 0.0;
if keyboard_input.pressed(KeyCode::ArrowUp) {
if game.player.i < BOARD_SIZE_I - 1 {
game.player.i += 1;
}
rotation = -PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowDown) {
if game.player.i > 0 {
game.player.i -= 1;
}
rotation = PI / 2.;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowRight) {
if game.player.j < BOARD_SIZE_J - 1 {
game.player.j += 1;
}
rotation = PI;
moved = true;
}
if keyboard_input.pressed(KeyCode::ArrowLeft) {
if game.player.j > 0 {
game.player.j -= 1;
}
rotation = 0.0;
moved = true;
}
// move on the board
if moved {
game.player.move_cooldown.reset();
*transforms.get_mut(game.player.entity.unwrap()).unwrap() = Transform {
translation: Vec3::new(
game.player.i as f32,
game.board[game.player.j][game.player.i].height,
game.player.j as f32,
),
rotation: Quat::from_rotation_y(rotation),
..default()
};
}
}
// eat the cake!
if let Some(entity) = game.bonus.entity {
if game.player.i == game.bonus.i && game.player.j == game.bonus.j {
game.score += 2;
game.cake_eaten += 1;
commands.entity(entity).despawn();
game.bonus.entity = None;
}
}
}
// change the focus of the camera
fn focus_camera(
time: Res<Time>,
mut game: ResMut<Game>,
mut transforms: ParamSet<(Query<&mut Transform, With<Camera3d>>, Query<&Transform>)>,
) {
const SPEED: f32 = 2.0;
// if there is both a player and a bonus, target the mid-point of them
if let (Some(player_entity), Some(bonus_entity)) = (game.player.entity, game.bonus.entity) {
let transform_query = transforms.p1();
if let (Ok(player_transform), Ok(bonus_transform)) = (
transform_query.get(player_entity),
transform_query.get(bonus_entity),
) {
game.camera_should_focus = player_transform
.translation
.lerp(bonus_transform.translation, 0.5);
}
// otherwise, if there is only a player, target the player
} else if let Some(player_entity) = game.player.entity {
if let Ok(player_transform) = transforms.p1().get(player_entity) {
game.camera_should_focus = player_transform.translation;
}
// otherwise, target the middle
} else {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
}
// calculate the camera motion based on the difference between where the camera is looking
// and where it should be looking; the greater the distance, the faster the motion;
// smooth out the camera movement using the frame time
let mut camera_motion = game.camera_should_focus - game.camera_is_focus;
if camera_motion.length() > 0.2 {
camera_motion *= SPEED * time.delta_secs();
// set the new camera's actual focus
game.camera_is_focus += camera_motion;
}
// look at that new camera's actual focus
for mut transform in transforms.p0().iter_mut() {
*transform = transform.looking_at(game.camera_is_focus, Vec3::Y);
}
}
// despawn the bonus if there is one, then spawn a new one at a random location
fn spawn_bonus(
time: Res<Time>,
mut timer: ResMut<BonusSpawnTimer>,
mut next_state: ResMut<NextState<GameState>>,
mut commands: Commands,
mut game: ResMut<Game>,
mut rng: ResMut<Random>,
) {
// make sure we wait enough time before spawning the next cake
if !timer.0.tick(time.delta()).finished() {
return;
}
if let Some(entity) = game.bonus.entity {
game.score -= 3;
commands.entity(entity).despawn();
game.bonus.entity = None;
if game.score <= -5 {
next_state.set(GameState::GameOver);
return;
}
}
// ensure bonus doesn't spawn on the player
loop {
game.bonus.i = rng.gen_range(0..BOARD_SIZE_I);
game.bonus.j = rng.gen_range(0..BOARD_SIZE_J);
if game.bonus.i != game.player.i || game.bonus.j != game.player.j {
break;
}
}
game.bonus.entity = Some(
commands
.spawn((
StateScoped(GameState::Playing),
Transform::from_xyz(
game.bonus.i as f32,
game.board[game.bonus.j][game.bonus.i].height + 0.2,
game.bonus.j as f32,
),
SceneRoot(game.bonus.handle.clone()),
children![(
PointLight {
color: Color::srgb(1.0, 1.0, 0.0),
intensity: 500_000.0,
range: 10.0,
..default()
},
Transform::from_xyz(0.0, 2.0, 0.0),
)],
))
.id(),
);
}
// let the cake turn on itself
fn rotate_bonus(game: Res<Game>, time: Res<Time>, mut transforms: Query<&mut Transform>) {
if let Some(entity) = game.bonus.entity {
if let Ok(mut cake_transform) = transforms.get_mut(entity) {
cake_transform.rotate_y(time.delta_secs());
cake_transform.scale =
Vec3::splat(1.0 + (game.score as f32 / 10.0 * ops::sin(time.elapsed_secs())).abs());
}
}
}
// update the score displayed during the game
fn scoreboard_system(game: Res<Game>, mut display: Single<&mut Text>) {
display.0 = format!("Sugar Rush: {}", game.score);
}
// restart the game when pressing spacebar
fn game_over_keyboard(
mut next_state: ResMut<NextState<GameState>>,
keyboard_input: Res<ButtonInput<KeyCode>>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
next_state.set(GameState::Playing);
}
}
// display the number of cake eaten before losing
fn display_score(mut commands: Commands, game: Res<Game>) {
commands.spawn((
StateScoped(GameState::GameOver),
Node {
width: Val::Percent(100.),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
children![(
Text::new(format!("Cake eaten: {}", game.cake_eaten)),
TextFont {
font_size: 67.0,
..default()
},
TextColor(Color::srgb(0.5, 0.5, 1.0)),
)],
));
}

437
vendor/bevy/examples/games/breakout.rs vendored Normal file
View File

@@ -0,0 +1,437 @@
//! A simplified implementation of the classic game "Breakout".
//!
//! Demonstrates Bevy's stepping capabilities if compiled with the `bevy_debug_stepping` feature.
use bevy::{
math::bounding::{Aabb2d, BoundingCircle, BoundingVolume, IntersectsVolume},
prelude::*,
};
mod stepping;
// These constants are defined in `Transform` units.
// Using the default 2D camera they correspond 1:1 with screen pixels.
const PADDLE_SIZE: Vec2 = Vec2::new(120.0, 20.0);
const GAP_BETWEEN_PADDLE_AND_FLOOR: f32 = 60.0;
const PADDLE_SPEED: f32 = 500.0;
// How close can the paddle get to the wall
const PADDLE_PADDING: f32 = 10.0;
// We set the z-value of the ball to 1 so it renders on top in the case of overlapping sprites.
const BALL_STARTING_POSITION: Vec3 = Vec3::new(0.0, -50.0, 1.0);
const BALL_DIAMETER: f32 = 30.;
const BALL_SPEED: f32 = 400.0;
const INITIAL_BALL_DIRECTION: Vec2 = Vec2::new(0.5, -0.5);
const WALL_THICKNESS: f32 = 10.0;
// x coordinates
const LEFT_WALL: f32 = -450.;
const RIGHT_WALL: f32 = 450.;
// y coordinates
const BOTTOM_WALL: f32 = -300.;
const TOP_WALL: f32 = 300.;
const BRICK_SIZE: Vec2 = Vec2::new(100., 30.);
// These values are exact
const GAP_BETWEEN_PADDLE_AND_BRICKS: f32 = 270.0;
const GAP_BETWEEN_BRICKS: f32 = 5.0;
// These values are lower bounds, as the number of bricks is computed
const GAP_BETWEEN_BRICKS_AND_CEILING: f32 = 20.0;
const GAP_BETWEEN_BRICKS_AND_SIDES: f32 = 20.0;
const SCOREBOARD_FONT_SIZE: f32 = 33.0;
const SCOREBOARD_TEXT_PADDING: Val = Val::Px(5.0);
const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7);
const BALL_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
const BRICK_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
const SCORE_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_plugins(
stepping::SteppingPlugin::default()
.add_schedule(Update)
.add_schedule(FixedUpdate)
.at(Val::Percent(35.0), Val::Percent(50.0)),
)
.insert_resource(Score(0))
.insert_resource(ClearColor(BACKGROUND_COLOR))
.add_event::<CollisionEvent>()
.add_systems(Startup, setup)
// Add our gameplay simulation systems to the fixed timestep schedule
// which runs at 64 Hz by default
.add_systems(
FixedUpdate,
(
apply_velocity,
move_paddle,
check_for_collisions,
play_collision_sound,
)
// `chain`ing systems together runs them in order
.chain(),
)
.add_systems(Update, update_scoreboard)
.run();
}
#[derive(Component)]
struct Paddle;
#[derive(Component)]
struct Ball;
#[derive(Component, Deref, DerefMut)]
struct Velocity(Vec2);
#[derive(Event, Default)]
struct CollisionEvent;
#[derive(Component)]
struct Brick;
#[derive(Resource, Deref)]
struct CollisionSound(Handle<AudioSource>);
// Default must be implemented to define this as a required component for the Wall component below
#[derive(Component, Default)]
struct Collider;
// This is a collection of the components that define a "Wall" in our game
#[derive(Component)]
#[require(Sprite, Transform, Collider)]
struct Wall;
/// Which side of the arena is this wall located on?
enum WallLocation {
Left,
Right,
Bottom,
Top,
}
impl WallLocation {
/// Location of the *center* of the wall, used in `transform.translation()`
fn position(&self) -> Vec2 {
match self {
WallLocation::Left => Vec2::new(LEFT_WALL, 0.),
WallLocation::Right => Vec2::new(RIGHT_WALL, 0.),
WallLocation::Bottom => Vec2::new(0., BOTTOM_WALL),
WallLocation::Top => Vec2::new(0., TOP_WALL),
}
}
/// (x, y) dimensions of the wall, used in `transform.scale()`
fn size(&self) -> Vec2 {
let arena_height = TOP_WALL - BOTTOM_WALL;
let arena_width = RIGHT_WALL - LEFT_WALL;
// Make sure we haven't messed up our constants
assert!(arena_height > 0.0);
assert!(arena_width > 0.0);
match self {
WallLocation::Left | WallLocation::Right => {
Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS)
}
WallLocation::Bottom | WallLocation::Top => {
Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS)
}
}
}
}
impl Wall {
// This "builder method" allows us to reuse logic across our wall entities,
// making our code easier to read and less prone to bugs when we change the logic
// Notice the use of Sprite and Transform alongside Wall, overwriting the default values defined for the required components
fn new(location: WallLocation) -> (Wall, Sprite, Transform) {
(
Wall,
Sprite::from_color(WALL_COLOR, Vec2::ONE),
Transform {
// We need to convert our Vec2 into a Vec3, by giving it a z-coordinate
// This is used to determine the order of our sprites
translation: location.position().extend(0.0),
// The z-scale of 2D objects must always be 1.0,
// or their ordering will be affected in surprising ways.
// See https://github.com/bevyengine/bevy/issues/4149
scale: location.size().extend(1.0),
..default()
},
)
}
}
// This resource tracks the game's score
#[derive(Resource, Deref, DerefMut)]
struct Score(usize);
#[derive(Component)]
struct ScoreboardUi;
// Add the game's entities to our world
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
asset_server: Res<AssetServer>,
) {
// Camera
commands.spawn(Camera2d);
// Sound
let ball_collision_sound = asset_server.load("sounds/breakout_collision.ogg");
commands.insert_resource(CollisionSound(ball_collision_sound));
// Paddle
let paddle_y = BOTTOM_WALL + GAP_BETWEEN_PADDLE_AND_FLOOR;
commands.spawn((
Sprite::from_color(PADDLE_COLOR, Vec2::ONE),
Transform {
translation: Vec3::new(0.0, paddle_y, 0.0),
scale: PADDLE_SIZE.extend(1.0),
..default()
},
Paddle,
Collider,
));
// Ball
commands.spawn((
Mesh2d(meshes.add(Circle::default())),
MeshMaterial2d(materials.add(BALL_COLOR)),
Transform::from_translation(BALL_STARTING_POSITION)
.with_scale(Vec2::splat(BALL_DIAMETER).extend(1.)),
Ball,
Velocity(INITIAL_BALL_DIRECTION.normalize() * BALL_SPEED),
));
// Scoreboard
commands.spawn((
Text::new("Score: "),
TextFont {
font_size: SCOREBOARD_FONT_SIZE,
..default()
},
TextColor(TEXT_COLOR),
ScoreboardUi,
Node {
position_type: PositionType::Absolute,
top: SCOREBOARD_TEXT_PADDING,
left: SCOREBOARD_TEXT_PADDING,
..default()
},
children![(
TextSpan::default(),
TextFont {
font_size: SCOREBOARD_FONT_SIZE,
..default()
},
TextColor(SCORE_COLOR),
)],
));
// Walls
commands.spawn(Wall::new(WallLocation::Left));
commands.spawn(Wall::new(WallLocation::Right));
commands.spawn(Wall::new(WallLocation::Bottom));
commands.spawn(Wall::new(WallLocation::Top));
// Bricks
let total_width_of_bricks = (RIGHT_WALL - LEFT_WALL) - 2. * GAP_BETWEEN_BRICKS_AND_SIDES;
let bottom_edge_of_bricks = paddle_y + GAP_BETWEEN_PADDLE_AND_BRICKS;
let total_height_of_bricks = TOP_WALL - bottom_edge_of_bricks - GAP_BETWEEN_BRICKS_AND_CEILING;
assert!(total_width_of_bricks > 0.0);
assert!(total_height_of_bricks > 0.0);
// Given the space available, compute how many rows and columns of bricks we can fit
let n_columns = (total_width_of_bricks / (BRICK_SIZE.x + GAP_BETWEEN_BRICKS)).floor() as usize;
let n_rows = (total_height_of_bricks / (BRICK_SIZE.y + GAP_BETWEEN_BRICKS)).floor() as usize;
let n_vertical_gaps = n_columns - 1;
// Because we need to round the number of columns,
// the space on the top and sides of the bricks only captures a lower bound, not an exact value
let center_of_bricks = (LEFT_WALL + RIGHT_WALL) / 2.0;
let left_edge_of_bricks = center_of_bricks
// Space taken up by the bricks
- (n_columns as f32 / 2.0 * BRICK_SIZE.x)
// Space taken up by the gaps
- n_vertical_gaps as f32 / 2.0 * GAP_BETWEEN_BRICKS;
// In Bevy, the `translation` of an entity describes the center point,
// not its bottom-left corner
let offset_x = left_edge_of_bricks + BRICK_SIZE.x / 2.;
let offset_y = bottom_edge_of_bricks + BRICK_SIZE.y / 2.;
for row in 0..n_rows {
for column in 0..n_columns {
let brick_position = Vec2::new(
offset_x + column as f32 * (BRICK_SIZE.x + GAP_BETWEEN_BRICKS),
offset_y + row as f32 * (BRICK_SIZE.y + GAP_BETWEEN_BRICKS),
);
// brick
commands.spawn((
Sprite {
color: BRICK_COLOR,
..default()
},
Transform {
translation: brick_position.extend(0.0),
scale: Vec3::new(BRICK_SIZE.x, BRICK_SIZE.y, 1.0),
..default()
},
Brick,
Collider,
));
}
}
}
fn move_paddle(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut paddle_transform: Single<&mut Transform, With<Paddle>>,
time: Res<Time>,
) {
let mut direction = 0.0;
if keyboard_input.pressed(KeyCode::ArrowLeft) {
direction -= 1.0;
}
if keyboard_input.pressed(KeyCode::ArrowRight) {
direction += 1.0;
}
// Calculate the new horizontal paddle position based on player input
let new_paddle_position =
paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs();
// Update the paddle position,
// making sure it doesn't cause the paddle to leave the arena
let left_bound = LEFT_WALL + WALL_THICKNESS / 2.0 + PADDLE_SIZE.x / 2.0 + PADDLE_PADDING;
let right_bound = RIGHT_WALL - WALL_THICKNESS / 2.0 - PADDLE_SIZE.x / 2.0 - PADDLE_PADDING;
paddle_transform.translation.x = new_paddle_position.clamp(left_bound, right_bound);
}
fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) {
for (mut transform, velocity) in &mut query {
transform.translation.x += velocity.x * time.delta_secs();
transform.translation.y += velocity.y * time.delta_secs();
}
}
fn update_scoreboard(
score: Res<Score>,
score_root: Single<Entity, (With<ScoreboardUi>, With<Text>)>,
mut writer: TextUiWriter,
) {
*writer.text(*score_root, 1) = score.to_string();
}
fn check_for_collisions(
mut commands: Commands,
mut score: ResMut<Score>,
ball_query: Single<(&mut Velocity, &Transform), With<Ball>>,
collider_query: Query<(Entity, &Transform, Option<&Brick>), With<Collider>>,
mut collision_events: EventWriter<CollisionEvent>,
) {
let (mut ball_velocity, ball_transform) = ball_query.into_inner();
for (collider_entity, collider_transform, maybe_brick) in &collider_query {
let collision = ball_collision(
BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.),
Aabb2d::new(
collider_transform.translation.truncate(),
collider_transform.scale.truncate() / 2.,
),
);
if let Some(collision) = collision {
// Writes a collision event so that other systems can react to the collision
collision_events.write_default();
// Bricks should be despawned and increment the scoreboard on collision
if maybe_brick.is_some() {
commands.entity(collider_entity).despawn();
**score += 1;
}
// Reflect the ball's velocity when it collides
let mut reflect_x = false;
let mut reflect_y = false;
// Reflect only if the velocity is in the opposite direction of the collision
// This prevents the ball from getting stuck inside the bar
match collision {
Collision::Left => reflect_x = ball_velocity.x > 0.0,
Collision::Right => reflect_x = ball_velocity.x < 0.0,
Collision::Top => reflect_y = ball_velocity.y < 0.0,
Collision::Bottom => reflect_y = ball_velocity.y > 0.0,
}
// Reflect velocity on the x-axis if we hit something on the x-axis
if reflect_x {
ball_velocity.x = -ball_velocity.x;
}
// Reflect velocity on the y-axis if we hit something on the y-axis
if reflect_y {
ball_velocity.y = -ball_velocity.y;
}
}
}
}
fn play_collision_sound(
mut commands: Commands,
mut collision_events: EventReader<CollisionEvent>,
sound: Res<CollisionSound>,
) {
// Play a sound once per frame if a collision occurred.
if !collision_events.is_empty() {
// This prevents events staying active on the next frame.
collision_events.clear();
commands.spawn((AudioPlayer(sound.clone()), PlaybackSettings::DESPAWN));
}
}
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
enum Collision {
Left,
Right,
Top,
Bottom,
}
// Returns `Some` if `ball` collides with `bounding_box`.
// The returned `Collision` is the side of `bounding_box` that `ball` hit.
fn ball_collision(ball: BoundingCircle, bounding_box: Aabb2d) -> Option<Collision> {
if !ball.intersects(&bounding_box) {
return None;
}
let closest = bounding_box.closest_point(ball.center());
let offset = ball.center() - closest;
let side = if offset.x.abs() > offset.y.abs() {
if offset.x < 0. {
Collision::Left
} else {
Collision::Right
}
} else if offset.y > 0. {
Collision::Top
} else {
Collision::Bottom
};
Some(side)
}

View File

@@ -0,0 +1,376 @@
//! This example displays each contributor to the bevy source code as a bouncing bevy-ball.
use bevy::{math::bounding::Aabb2d, prelude::*};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use std::{
collections::HashMap,
env::VarError,
hash::{DefaultHasher, Hash, Hasher},
io::{self, BufRead, BufReader},
process::Stdio,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.init_resource::<SelectionTimer>()
.init_resource::<SharedRng>()
.add_systems(Startup, (setup_contributor_selection, setup))
// Systems are chained for determinism only
.add_systems(Update, (gravity, movement, collisions, selection).chain())
.run();
}
type Contributors = Vec<(String, usize)>;
#[derive(Resource)]
struct ContributorSelection {
order: Vec<Entity>,
idx: usize,
}
#[derive(Resource)]
struct SelectionTimer(Timer);
impl Default for SelectionTimer {
fn default() -> Self {
Self(Timer::from_seconds(
SHOWCASE_TIMER_SECS,
TimerMode::Repeating,
))
}
}
#[derive(Component)]
struct ContributorDisplay;
#[derive(Component)]
struct Contributor {
name: String,
num_commits: usize,
hue: f32,
}
#[derive(Component)]
struct Velocity {
translation: Vec3,
rotation: f32,
}
// We're using a shared seeded RNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
#[derive(Resource, Deref, DerefMut)]
struct SharedRng(ChaCha8Rng);
impl Default for SharedRng {
fn default() -> Self {
Self(ChaCha8Rng::seed_from_u64(10223163112))
}
}
const GRAVITY: f32 = 9.821 * 100.0;
const SPRITE_SIZE: f32 = 75.0;
const SELECTED: Hsla = Hsla::hsl(0.0, 0.9, 0.7);
const DESELECTED: Hsla = Hsla::new(0.0, 0.3, 0.2, 0.92);
const SELECTED_Z_OFFSET: f32 = 100.0;
const SHOWCASE_TIMER_SECS: f32 = 3.0;
const CONTRIBUTORS_LIST: &[&str] = &["Carter Anderson", "And Many More"];
fn setup_contributor_selection(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut rng: ResMut<SharedRng>,
) {
let contribs = contributors_or_fallback();
let texture_handle = asset_server.load("branding/icon.png");
let mut contributor_selection = ContributorSelection {
order: Vec::with_capacity(contribs.len()),
idx: 0,
};
for (name, num_commits) in contribs {
let transform = Transform::from_xyz(
rng.gen_range(-400.0..400.0),
rng.gen_range(0.0..400.0),
rng.r#gen(),
);
let dir = rng.gen_range(-1.0..1.0);
let velocity = Vec3::new(dir * 500.0, 0.0, 0.0);
let hue = name_to_hue(&name);
// Some sprites should be flipped for variety
let flipped = rng.r#gen();
let entity = commands
.spawn((
Contributor {
name,
num_commits,
hue,
},
Velocity {
translation: velocity,
rotation: -dir * 5.0,
},
Sprite {
image: texture_handle.clone(),
custom_size: Some(Vec2::splat(SPRITE_SIZE)),
color: DESELECTED.with_hue(hue).into(),
flip_x: flipped,
..default()
},
transform,
))
.id();
contributor_selection.order.push(entity);
}
commands.insert_resource(contributor_selection);
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let text_style = TextFont {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 60.0,
..default()
};
commands
.spawn((
Text::new("Contributor showcase"),
text_style.clone(),
ContributorDisplay,
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.),
left: Val::Px(12.),
..default()
},
))
.with_child((
TextSpan::default(),
TextFont {
font_size: 30.,
..text_style
},
));
}
/// Finds the next contributor to display and selects the entity
fn selection(
mut timer: ResMut<SelectionTimer>,
mut contributor_selection: ResMut<ContributorSelection>,
contributor_root: Single<Entity, (With<ContributorDisplay>, With<Text>)>,
mut query: Query<(&Contributor, &mut Sprite, &mut Transform)>,
mut writer: TextUiWriter,
time: Res<Time>,
) {
if !timer.0.tick(time.delta()).just_finished() {
return;
}
// Deselect the previous contributor
let entity = contributor_selection.order[contributor_selection.idx];
if let Ok((contributor, mut sprite, mut transform)) = query.get_mut(entity) {
deselect(&mut sprite, contributor, &mut transform);
}
// Select the next contributor
if (contributor_selection.idx + 1) < contributor_selection.order.len() {
contributor_selection.idx += 1;
} else {
contributor_selection.idx = 0;
}
let entity = contributor_selection.order[contributor_selection.idx];
if let Ok((contributor, mut sprite, mut transform)) = query.get_mut(entity) {
let entity = *contributor_root;
select(
&mut sprite,
contributor,
&mut transform,
entity,
&mut writer,
);
}
}
/// Change the tint color to the "selected" color, bring the object to the front
/// and display the name.
fn select(
sprite: &mut Sprite,
contributor: &Contributor,
transform: &mut Transform,
entity: Entity,
writer: &mut TextUiWriter,
) {
sprite.color = SELECTED.with_hue(contributor.hue).into();
transform.translation.z += SELECTED_Z_OFFSET;
writer.text(entity, 0).clone_from(&contributor.name);
*writer.text(entity, 1) = format!(
"\n{} commit{}",
contributor.num_commits,
if contributor.num_commits > 1 { "s" } else { "" }
);
writer.color(entity, 0).0 = sprite.color;
}
/// Change the tint color to the "deselected" color and push
/// the object to the back.
fn deselect(sprite: &mut Sprite, contributor: &Contributor, transform: &mut Transform) {
sprite.color = DESELECTED.with_hue(contributor.hue).into();
transform.translation.z -= SELECTED_Z_OFFSET;
}
/// Applies gravity to all entities with a velocity.
fn gravity(time: Res<Time>, mut velocity_query: Query<&mut Velocity>) {
let delta = time.delta_secs();
for mut velocity in &mut velocity_query {
velocity.translation.y -= GRAVITY * delta;
}
}
/// Checks for collisions of contributor-birbs.
///
/// On collision with left-or-right wall it resets the horizontal
/// velocity. On collision with the ground it applies an upwards
/// force.
fn collisions(
window: Query<&Window>,
mut query: Query<(&mut Velocity, &mut Transform), With<Contributor>>,
mut rng: ResMut<SharedRng>,
) {
let Ok(window) = window.single() else {
return;
};
let window_size = window.size();
let collision_area = Aabb2d::new(Vec2::ZERO, (window_size - SPRITE_SIZE) / 2.);
// The maximum height the birbs should try to reach is one birb below the top of the window.
let max_bounce_height = (window_size.y - SPRITE_SIZE * 2.0).max(0.0);
let min_bounce_height = max_bounce_height * 0.4;
for (mut velocity, mut transform) in &mut query {
// Clamp the translation to not go out of the bounds
if transform.translation.y < collision_area.min.y {
transform.translation.y = collision_area.min.y;
// How high this birb will bounce.
let bounce_height = rng.gen_range(min_bounce_height..=max_bounce_height);
// Apply the velocity that would bounce the birb up to bounce_height.
velocity.translation.y = (bounce_height * GRAVITY * 2.).sqrt();
}
// Birbs might hit the ceiling if the window is resized.
// If they do, bounce them.
if transform.translation.y > collision_area.max.y {
transform.translation.y = collision_area.max.y;
velocity.translation.y *= -1.0;
}
// On side walls flip the horizontal velocity
if transform.translation.x < collision_area.min.x {
transform.translation.x = collision_area.min.x;
velocity.translation.x *= -1.0;
velocity.rotation *= -1.0;
}
if transform.translation.x > collision_area.max.x {
transform.translation.x = collision_area.max.x;
velocity.translation.x *= -1.0;
velocity.rotation *= -1.0;
}
}
}
/// Apply velocity to positions and rotations.
fn movement(time: Res<Time>, mut query: Query<(&Velocity, &mut Transform)>) {
let delta = time.delta_secs();
for (velocity, mut transform) in &mut query {
transform.translation += delta * velocity.translation;
transform.rotate_z(velocity.rotation * delta);
}
}
#[derive(Debug, thiserror::Error)]
enum LoadContributorsError {
#[error("An IO error occurred while reading the git log.")]
Io(#[from] io::Error),
#[error("The CARGO_MANIFEST_DIR environment variable was not set.")]
Var(#[from] VarError),
#[error("The git process did not return a stdout handle.")]
Stdout,
}
/// Get the names and commit counts of all contributors from the git log.
///
/// This function only works if `git` is installed and
/// the program is run through `cargo`.
fn contributors() -> Result<Contributors, LoadContributorsError> {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")?;
let mut cmd = std::process::Command::new("git")
.args(["--no-pager", "log", "--pretty=format:%an"])
.current_dir(manifest_dir)
.stdout(Stdio::piped())
.spawn()?;
let stdout = cmd.stdout.take().ok_or(LoadContributorsError::Stdout)?;
// Take the list of commit author names and collect them into a HashMap,
// keeping a count of how many commits they authored.
let contributors = BufReader::new(stdout).lines().map_while(Result::ok).fold(
HashMap::new(),
|mut acc, word| {
*acc.entry(word).or_insert(0) += 1;
acc
},
);
Ok(contributors.into_iter().collect())
}
/// Get the contributors list, or fall back to a default value if
/// it's unavailable or we're in CI
fn contributors_or_fallback() -> Contributors {
let get_default = || {
CONTRIBUTORS_LIST
.iter()
.cycle()
.take(1000)
.map(|name| (name.to_string(), 1))
.collect()
};
if cfg!(feature = "bevy_ci_testing") {
return get_default();
}
contributors().unwrap_or_else(|_| get_default())
}
/// Give each unique contributor name a particular hue that is stable between runs.
fn name_to_hue(s: &str) -> f32 {
let mut hasher = DefaultHasher::new();
s.hash(&mut hasher);
hasher.finish() as f32 / u64::MAX as f32 * 360.
}

381
vendor/bevy/examples/games/desk_toy.rs vendored Normal file
View File

@@ -0,0 +1,381 @@
//! Bevy logo as a desk toy using transparent windows! Now with Googly Eyes!
//!
//! This example demonstrates:
//! - Transparent windows that can be clicked through.
//! - Drag-and-drop operations in 2D.
//! - Using entity hierarchy, Transform, and Visibility to create simple animations.
//! - Creating simple 2D meshes based on shape primitives.
use bevy::{
app::AppExit,
input::common_conditions::{input_just_pressed, input_just_released},
prelude::*,
window::{PrimaryWindow, WindowLevel},
};
#[cfg(target_os = "macos")]
use bevy::window::CompositeAlphaMode;
fn main() {
App::new()
.add_plugins(DefaultPlugins.set(WindowPlugin {
primary_window: Some(Window {
title: "Bevy Desk Toy".into(),
transparent: true,
#[cfg(target_os = "macos")]
composite_alpha_mode: CompositeAlphaMode::PostMultiplied,
..default()
}),
..default()
}))
.insert_resource(ClearColor(WINDOW_CLEAR_COLOR))
.insert_resource(WindowTransparency(false))
.insert_resource(CursorWorldPos(None))
.add_systems(Startup, setup)
.add_systems(
Update,
(
get_cursor_world_pos,
update_cursor_hit_test,
(
start_drag.run_if(input_just_pressed(MouseButton::Left)),
end_drag.run_if(input_just_released(MouseButton::Left)),
drag.run_if(resource_exists::<DragOperation>),
quit.run_if(input_just_pressed(MouseButton::Right)),
toggle_transparency.run_if(input_just_pressed(KeyCode::Space)),
move_pupils.after(drag),
),
)
.chain(),
)
.run();
}
/// Whether the window is transparent
#[derive(Resource)]
struct WindowTransparency(bool);
/// The projected 2D world coordinates of the cursor (if it's within primary window bounds).
#[derive(Resource)]
struct CursorWorldPos(Option<Vec2>);
/// The current drag operation including the offset with which we grabbed the Bevy logo.
#[derive(Resource)]
struct DragOperation(Vec2);
/// Marker component for the instructions text entity.
#[derive(Component)]
struct InstructionsText;
/// Marker component for the Bevy logo entity.
#[derive(Component)]
struct BevyLogo;
/// Component for the moving pupil entity (the moving part of the googly eye).
#[derive(Component)]
struct Pupil {
/// Radius of the eye containing the pupil.
eye_radius: f32,
/// Radius of the pupil.
pupil_radius: f32,
/// Current velocity of the pupil.
velocity: Vec2,
}
// Dimensions are based on: assets/branding/icon.png
// Bevy logo radius
const BEVY_LOGO_RADIUS: f32 = 128.0;
// Birds' eyes x y (offset from the origin) and radius
// These values are manually determined from the logo image
const BIRDS_EYES: [(f32, f32, f32); 3] = [
(145.0 - 128.0, -(56.0 - 128.0), 12.0),
(198.0 - 128.0, -(87.0 - 128.0), 10.0),
(222.0 - 128.0, -(140.0 - 128.0), 8.0),
];
const WINDOW_CLEAR_COLOR: Color = Color::srgb(0.2, 0.2, 0.2);
/// Spawn the scene
fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<ColorMaterial>>,
) {
// Spawn a 2D camera
commands.spawn(Camera2d);
// Spawn the text instructions
let font = asset_server.load("fonts/FiraSans-Bold.ttf");
let text_style = TextFont {
font: font.clone(),
font_size: 25.0,
..default()
};
commands.spawn((
Text2d::new("Press Space to play on your desktop! Press it again to return.\nRight click Bevy logo to exit."),
text_style.clone(),
Transform::from_xyz(0.0, -300.0, 100.0),
InstructionsText,
));
// Create a circle mesh. We will reuse this mesh for all our circles.
let circle = meshes.add(Circle { radius: 1.0 });
// Create the different materials we will use for each part of the eyes. For this demo they are basic [`ColorMaterial`]s.
let outline_material = materials.add(Color::BLACK);
let sclera_material = materials.add(Color::WHITE);
let pupil_material = materials.add(Color::srgb(0.2, 0.2, 0.2));
let pupil_highlight_material = materials.add(Color::srgba(1.0, 1.0, 1.0, 0.2));
// Spawn the Bevy logo sprite
commands
.spawn((
Sprite::from_image(asset_server.load("branding/icon.png")),
BevyLogo,
))
.with_children(|commands| {
// For each bird eye
for (x, y, radius) in BIRDS_EYES {
let pupil_radius = radius * 0.6;
let pupil_highlight_radius = radius * 0.3;
let pupil_highlight_offset = radius * 0.3;
// eye outline
commands.spawn((
Mesh2d(circle.clone()),
MeshMaterial2d(outline_material.clone()),
Transform::from_xyz(x, y - 1.0, 1.0)
.with_scale(Vec2::splat(radius + 2.0).extend(1.0)),
));
// sclera
commands.spawn((
Transform::from_xyz(x, y, 2.0),
Visibility::default(),
children![
// sclera
(
Mesh2d(circle.clone()),
MeshMaterial2d(sclera_material.clone()),
Transform::from_scale(Vec3::new(radius, radius, 0.0)),
),
// pupil
(
Transform::from_xyz(0.0, 0.0, 1.0),
Visibility::default(),
Pupil {
eye_radius: radius,
pupil_radius,
velocity: Vec2::ZERO,
},
children![
// pupil main
(
Mesh2d(circle.clone()),
MeshMaterial2d(pupil_material.clone()),
Transform::from_xyz(0.0, 0.0, 0.0).with_scale(Vec3::new(
pupil_radius,
pupil_radius,
1.0,
)),
),
// pupil highlight
(
Mesh2d(circle.clone()),
MeshMaterial2d(pupil_highlight_material.clone()),
Transform::from_xyz(
-pupil_highlight_offset,
pupil_highlight_offset,
1.0,
)
.with_scale(Vec3::new(
pupil_highlight_radius,
pupil_highlight_radius,
1.0,
)),
)
],
)
],
));
}
});
}
/// Project the cursor into the world coordinates and store it in a resource for easy use
fn get_cursor_world_pos(
mut cursor_world_pos: ResMut<CursorWorldPos>,
primary_window: Single<&Window, With<PrimaryWindow>>,
q_camera: Single<(&Camera, &GlobalTransform)>,
) {
let (main_camera, main_camera_transform) = *q_camera;
// Get the cursor position in the world
cursor_world_pos.0 = primary_window.cursor_position().and_then(|cursor_pos| {
main_camera
.viewport_to_world_2d(main_camera_transform, cursor_pos)
.ok()
});
}
/// Update whether the window is clickable or not
fn update_cursor_hit_test(
cursor_world_pos: Res<CursorWorldPos>,
mut primary_window: Single<&mut Window, With<PrimaryWindow>>,
bevy_logo_transform: Single<&Transform, With<BevyLogo>>,
) {
// If the window has decorations (e.g. a border) then it should be clickable
if primary_window.decorations {
primary_window.cursor_options.hit_test = true;
return;
}
// If the cursor is not within the window we don't need to update whether the window is clickable or not
let Some(cursor_world_pos) = cursor_world_pos.0 else {
return;
};
// If the cursor is within the radius of the Bevy logo make the window clickable otherwise the window is not clickable
primary_window.cursor_options.hit_test = bevy_logo_transform
.translation
.truncate()
.distance(cursor_world_pos)
< BEVY_LOGO_RADIUS;
}
/// Start the drag operation and record the offset we started dragging from
fn start_drag(
mut commands: Commands,
cursor_world_pos: Res<CursorWorldPos>,
bevy_logo_transform: Single<&Transform, With<BevyLogo>>,
) {
// If the cursor is not within the primary window skip this system
let Some(cursor_world_pos) = cursor_world_pos.0 else {
return;
};
// Get the offset from the cursor to the Bevy logo sprite
let drag_offset = bevy_logo_transform.translation.truncate() - cursor_world_pos;
// If the cursor is within the Bevy logo radius start the drag operation and remember the offset of the cursor from the origin
if drag_offset.length() < BEVY_LOGO_RADIUS {
commands.insert_resource(DragOperation(drag_offset));
}
}
/// Stop the current drag operation
fn end_drag(mut commands: Commands) {
commands.remove_resource::<DragOperation>();
}
/// Drag the Bevy logo
fn drag(
drag_offset: Res<DragOperation>,
cursor_world_pos: Res<CursorWorldPos>,
time: Res<Time>,
mut bevy_transform: Single<&mut Transform, With<BevyLogo>>,
mut q_pupils: Query<&mut Pupil>,
) {
// If the cursor is not within the primary window skip this system
let Some(cursor_world_pos) = cursor_world_pos.0 else {
return;
};
// Calculate the new translation of the Bevy logo based on cursor and drag offset
let new_translation = cursor_world_pos + drag_offset.0;
// Calculate how fast we are dragging the Bevy logo (unit/second)
let drag_velocity =
(new_translation - bevy_transform.translation.truncate()) / time.delta_secs();
// Update the translation of Bevy logo transform to new translation
bevy_transform.translation = new_translation.extend(bevy_transform.translation.z);
// Add the cursor drag velocity in the opposite direction to each pupil.
// Remember pupils are using local coordinates to move. So when the Bevy logo moves right they need to move left to
// simulate inertia, otherwise they will move fixed to the parent.
for mut pupil in &mut q_pupils {
pupil.velocity -= drag_velocity;
}
}
/// Quit when the user right clicks the Bevy logo
fn quit(
cursor_world_pos: Res<CursorWorldPos>,
mut app_exit: EventWriter<AppExit>,
bevy_logo_transform: Single<&Transform, With<BevyLogo>>,
) {
// If the cursor is not within the primary window skip this system
let Some(cursor_world_pos) = cursor_world_pos.0 else {
return;
};
// If the cursor is within the Bevy logo radius send the [`AppExit`] event to quit the app
if bevy_logo_transform
.translation
.truncate()
.distance(cursor_world_pos)
< BEVY_LOGO_RADIUS
{
app_exit.write(AppExit::Success);
}
}
/// Enable transparency for the window and make it on top
fn toggle_transparency(
mut commands: Commands,
mut window_transparency: ResMut<WindowTransparency>,
mut q_instructions_text: Query<&mut Visibility, With<InstructionsText>>,
mut primary_window: Single<&mut Window, With<PrimaryWindow>>,
) {
// Toggle the window transparency resource
window_transparency.0 = !window_transparency.0;
// Show or hide the instructions text
for mut visibility in &mut q_instructions_text {
*visibility = if window_transparency.0 {
Visibility::Hidden
} else {
Visibility::Visible
};
}
// Remove the primary window's decorations (e.g. borders), make it always on top of other desktop windows, and set the clear color to transparent
// only if window transparency is enabled
let clear_color;
(
primary_window.decorations,
primary_window.window_level,
clear_color,
) = if window_transparency.0 {
(false, WindowLevel::AlwaysOnTop, Color::NONE)
} else {
(true, WindowLevel::Normal, WINDOW_CLEAR_COLOR)
};
// Set the clear color
commands.insert_resource(ClearColor(clear_color));
}
/// Move the pupils and bounce them around
fn move_pupils(time: Res<Time>, mut q_pupils: Query<(&mut Pupil, &mut Transform)>) {
for (mut pupil, mut transform) in &mut q_pupils {
// The wiggle radius is how much the pupil can move within the eye
let wiggle_radius = pupil.eye_radius - pupil.pupil_radius;
// Store the Z component
let z = transform.translation.z;
// Truncate the Z component to make the calculations be on [`Vec2`]
let mut translation = transform.translation.truncate();
// Decay the pupil velocity
pupil.velocity *= ops::powf(0.04f32, time.delta_secs());
// Move the pupil
translation += pupil.velocity * time.delta_secs();
// If the pupil hit the outside border of the eye, limit the translation to be within the wiggle radius and invert the velocity.
// This is not physically accurate but it's good enough for the googly eyes effect.
if translation.length() > wiggle_radius {
translation = translation.normalize() * wiggle_radius;
// Invert and decrease the velocity of the pupil when it bounces
pupil.velocity *= -0.75;
}
// Update the entity transform with the new translation after reading the Z component
transform.translation = translation.extend(z);
}
}

737
vendor/bevy/examples/games/game_menu.rs vendored Normal file
View File

@@ -0,0 +1,737 @@
//! This example will display a simple menu using Bevy UI where you can start a new game,
//! change some settings or quit. There is no actual game, it will just display the current
//! settings for 5 seconds before going back to the menu.
use bevy::prelude::*;
const TEXT_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
// Enum that will be used as a global state for the game
#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
enum GameState {
#[default]
Splash,
Menu,
Game,
}
// One of the two settings that can be set through the menu. It will be a resource in the app
#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
enum DisplayQuality {
Low,
Medium,
High,
}
// One of the two settings that can be set through the menu. It will be a resource in the app
#[derive(Resource, Debug, Component, PartialEq, Eq, Clone, Copy)]
struct Volume(u32);
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// Insert as resource the initial value for the settings resources
.insert_resource(DisplayQuality::Medium)
.insert_resource(Volume(7))
// Declare the game state, whose starting value is determined by the `Default` trait
.init_state::<GameState>()
.add_systems(Startup, setup)
// Adds the plugins for each state
.add_plugins((splash::splash_plugin, menu::menu_plugin, game::game_plugin))
.run();
}
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
}
mod splash {
use bevy::prelude::*;
use super::{despawn_screen, GameState};
// This plugin will display a splash screen with Bevy logo for 1 second before switching to the menu
pub fn splash_plugin(app: &mut App) {
// As this plugin is managing the splash screen, it will focus on the state `GameState::Splash`
app
// When entering the state, spawn everything needed for this screen
.add_systems(OnEnter(GameState::Splash), splash_setup)
// While in this state, run the `countdown` system
.add_systems(Update, countdown.run_if(in_state(GameState::Splash)))
// When exiting the state, despawn everything that was spawned for this screen
.add_systems(OnExit(GameState::Splash), despawn_screen::<OnSplashScreen>);
}
// Tag component used to tag entities added on the splash screen
#[derive(Component)]
struct OnSplashScreen;
// Newtype to use a `Timer` for this screen as a resource
#[derive(Resource, Deref, DerefMut)]
struct SplashTimer(Timer);
fn splash_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
let icon = asset_server.load("branding/icon.png");
// Display the logo
commands.spawn((
Node {
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
width: Val::Percent(100.0),
height: Val::Percent(100.0),
..default()
},
OnSplashScreen,
children![(
ImageNode::new(icon),
Node {
// This will set the logo to be 200px wide, and auto adjust its height
width: Val::Px(200.0),
..default()
},
)],
));
// Insert the timer as a resource
commands.insert_resource(SplashTimer(Timer::from_seconds(1.0, TimerMode::Once)));
}
// Tick the timer, and change state when finished
fn countdown(
mut game_state: ResMut<NextState<GameState>>,
time: Res<Time>,
mut timer: ResMut<SplashTimer>,
) {
if timer.tick(time.delta()).finished() {
game_state.set(GameState::Menu);
}
}
}
mod game {
use bevy::{
color::palettes::basic::{BLUE, LIME},
prelude::*,
};
use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
// This plugin will contain the game. In this case, it's just be a screen that will
// display the current settings for 5 seconds before returning to the menu
pub fn game_plugin(app: &mut App) {
app.add_systems(OnEnter(GameState::Game), game_setup)
.add_systems(Update, game.run_if(in_state(GameState::Game)))
.add_systems(OnExit(GameState::Game), despawn_screen::<OnGameScreen>);
}
// Tag component used to tag entities added on the game screen
#[derive(Component)]
struct OnGameScreen;
#[derive(Resource, Deref, DerefMut)]
struct GameTimer(Timer);
fn game_setup(
mut commands: Commands,
display_quality: Res<DisplayQuality>,
volume: Res<Volume>,
) {
commands.spawn((
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
// center children
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
OnGameScreen,
children![(
Node {
// This will display its children in a column, from top to bottom
flex_direction: FlexDirection::Column,
// `align_items` will align children on the cross axis. Here the main axis is
// vertical (column), so the cross axis is horizontal. This will center the
// children
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::BLACK),
children![
(
Text::new("Will be back to the menu shortly..."),
TextFont {
font_size: 67.0,
..default()
},
TextColor(TEXT_COLOR),
Node {
margin: UiRect::all(Val::Px(50.0)),
..default()
},
),
(
Text::default(),
Node {
margin: UiRect::all(Val::Px(50.0)),
..default()
},
children![
(
TextSpan(format!("quality: {:?}", *display_quality)),
TextFont {
font_size: 50.0,
..default()
},
TextColor(BLUE.into()),
),
(
TextSpan::new(" - "),
TextFont {
font_size: 50.0,
..default()
},
TextColor(TEXT_COLOR),
),
(
TextSpan(format!("volume: {:?}", *volume)),
TextFont {
font_size: 50.0,
..default()
},
TextColor(LIME.into()),
),
]
),
]
)],
));
// Spawn a 5 seconds timer to trigger going back to the menu
commands.insert_resource(GameTimer(Timer::from_seconds(5.0, TimerMode::Once)));
}
// Tick the timer, and change state when finished
fn game(
time: Res<Time>,
mut game_state: ResMut<NextState<GameState>>,
mut timer: ResMut<GameTimer>,
) {
if timer.tick(time.delta()).finished() {
game_state.set(GameState::Menu);
}
}
}
mod menu {
use bevy::{
app::AppExit,
color::palettes::css::CRIMSON,
ecs::spawn::{SpawnIter, SpawnWith},
prelude::*,
};
use super::{despawn_screen, DisplayQuality, GameState, Volume, TEXT_COLOR};
// This plugin manages the menu, with 5 different screens:
// - a main menu with "New Game", "Settings", "Quit"
// - a settings menu with two submenus and a back button
// - two settings screen with a setting that can be set and a back button
pub fn menu_plugin(app: &mut App) {
app
// At start, the menu is not enabled. This will be changed in `menu_setup` when
// entering the `GameState::Menu` state.
// Current screen in the menu is handled by an independent state from `GameState`
.init_state::<MenuState>()
.add_systems(OnEnter(GameState::Menu), menu_setup)
// Systems to handle the main menu screen
.add_systems(OnEnter(MenuState::Main), main_menu_setup)
.add_systems(OnExit(MenuState::Main), despawn_screen::<OnMainMenuScreen>)
// Systems to handle the settings menu screen
.add_systems(OnEnter(MenuState::Settings), settings_menu_setup)
.add_systems(
OnExit(MenuState::Settings),
despawn_screen::<OnSettingsMenuScreen>,
)
// Systems to handle the display settings screen
.add_systems(
OnEnter(MenuState::SettingsDisplay),
display_settings_menu_setup,
)
.add_systems(
Update,
(setting_button::<DisplayQuality>.run_if(in_state(MenuState::SettingsDisplay)),),
)
.add_systems(
OnExit(MenuState::SettingsDisplay),
despawn_screen::<OnDisplaySettingsMenuScreen>,
)
// Systems to handle the sound settings screen
.add_systems(OnEnter(MenuState::SettingsSound), sound_settings_menu_setup)
.add_systems(
Update,
setting_button::<Volume>.run_if(in_state(MenuState::SettingsSound)),
)
.add_systems(
OnExit(MenuState::SettingsSound),
despawn_screen::<OnSoundSettingsMenuScreen>,
)
// Common systems to all screens that handles buttons behavior
.add_systems(
Update,
(menu_action, button_system).run_if(in_state(GameState::Menu)),
);
}
// State used for the current menu screen
#[derive(Clone, Copy, Default, Eq, PartialEq, Debug, Hash, States)]
enum MenuState {
Main,
Settings,
SettingsDisplay,
SettingsSound,
#[default]
Disabled,
}
// Tag component used to tag entities added on the main menu screen
#[derive(Component)]
struct OnMainMenuScreen;
// Tag component used to tag entities added on the settings menu screen
#[derive(Component)]
struct OnSettingsMenuScreen;
// Tag component used to tag entities added on the display settings menu screen
#[derive(Component)]
struct OnDisplaySettingsMenuScreen;
// Tag component used to tag entities added on the sound settings menu screen
#[derive(Component)]
struct OnSoundSettingsMenuScreen;
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const HOVERED_BUTTON: Color = Color::srgb(0.25, 0.25, 0.25);
const HOVERED_PRESSED_BUTTON: Color = Color::srgb(0.25, 0.65, 0.25);
const PRESSED_BUTTON: Color = Color::srgb(0.35, 0.75, 0.35);
// Tag component used to mark which setting is currently selected
#[derive(Component)]
struct SelectedOption;
// All actions that can be triggered from a button click
#[derive(Component)]
enum MenuButtonAction {
Play,
Settings,
SettingsDisplay,
SettingsSound,
BackToMainMenu,
BackToSettings,
Quit,
}
// This system handles changing all buttons color based on mouse interaction
fn button_system(
mut interaction_query: Query<
(&Interaction, &mut BackgroundColor, Option<&SelectedOption>),
(Changed<Interaction>, With<Button>),
>,
) {
for (interaction, mut background_color, selected) in &mut interaction_query {
*background_color = match (*interaction, selected) {
(Interaction::Pressed, _) | (Interaction::None, Some(_)) => PRESSED_BUTTON.into(),
(Interaction::Hovered, Some(_)) => HOVERED_PRESSED_BUTTON.into(),
(Interaction::Hovered, None) => HOVERED_BUTTON.into(),
(Interaction::None, None) => NORMAL_BUTTON.into(),
}
}
}
// This system updates the settings when a new value for a setting is selected, and marks
// the button as the one currently selected
fn setting_button<T: Resource + Component + PartialEq + Copy>(
interaction_query: Query<(&Interaction, &T, Entity), (Changed<Interaction>, With<Button>)>,
selected_query: Single<(Entity, &mut BackgroundColor), With<SelectedOption>>,
mut commands: Commands,
mut setting: ResMut<T>,
) {
let (previous_button, mut previous_button_color) = selected_query.into_inner();
for (interaction, button_setting, entity) in &interaction_query {
if *interaction == Interaction::Pressed && *setting != *button_setting {
*previous_button_color = NORMAL_BUTTON.into();
commands.entity(previous_button).remove::<SelectedOption>();
commands.entity(entity).insert(SelectedOption);
*setting = *button_setting;
}
}
}
fn menu_setup(mut menu_state: ResMut<NextState<MenuState>>) {
menu_state.set(MenuState::Main);
}
fn main_menu_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// Common style for all buttons on the screen
let button_node = Node {
width: Val::Px(300.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
};
let button_icon_node = Node {
width: Val::Px(30.0),
// This takes the icons out of the flexbox flow, to be positioned exactly
position_type: PositionType::Absolute,
// The icon will be close to the left border of the button
left: Val::Px(10.0),
..default()
};
let button_text_font = TextFont {
font_size: 33.0,
..default()
};
let right_icon = asset_server.load("textures/Game Icons/right.png");
let wrench_icon = asset_server.load("textures/Game Icons/wrench.png");
let exit_icon = asset_server.load("textures/Game Icons/exitRight.png");
commands.spawn((
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
OnMainMenuScreen,
children![(
Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(CRIMSON.into()),
children![
// Display the game name
(
Text::new("Bevy Game Menu UI"),
TextFont {
font_size: 67.0,
..default()
},
TextColor(TEXT_COLOR),
Node {
margin: UiRect::all(Val::Px(50.0)),
..default()
},
),
// Display three buttons for each action available from the main menu:
// - new game
// - settings
// - quit
(
Button,
button_node.clone(),
BackgroundColor(NORMAL_BUTTON),
MenuButtonAction::Play,
children![
(ImageNode::new(right_icon), button_icon_node.clone()),
(
Text::new("New Game"),
button_text_font.clone(),
TextColor(TEXT_COLOR),
),
]
),
(
Button,
button_node.clone(),
BackgroundColor(NORMAL_BUTTON),
MenuButtonAction::Settings,
children![
(ImageNode::new(wrench_icon), button_icon_node.clone()),
(
Text::new("Settings"),
button_text_font.clone(),
TextColor(TEXT_COLOR),
),
]
),
(
Button,
button_node,
BackgroundColor(NORMAL_BUTTON),
MenuButtonAction::Quit,
children![
(ImageNode::new(exit_icon), button_icon_node),
(Text::new("Quit"), button_text_font, TextColor(TEXT_COLOR),),
]
),
]
)],
));
}
fn settings_menu_setup(mut commands: Commands) {
let button_node = Node {
width: Val::Px(200.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
};
let button_text_style = (
TextFont {
font_size: 33.0,
..default()
},
TextColor(TEXT_COLOR),
);
commands.spawn((
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
OnSettingsMenuScreen,
children![(
Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(CRIMSON.into()),
Children::spawn(SpawnIter(
[
(MenuButtonAction::SettingsDisplay, "Display"),
(MenuButtonAction::SettingsSound, "Sound"),
(MenuButtonAction::BackToMainMenu, "Back"),
]
.into_iter()
.map(move |(action, text)| {
(
Button,
button_node.clone(),
BackgroundColor(NORMAL_BUTTON),
action,
children![(Text::new(text), button_text_style.clone())],
)
})
))
)],
));
}
fn display_settings_menu_setup(mut commands: Commands, display_quality: Res<DisplayQuality>) {
fn button_node() -> Node {
Node {
width: Val::Px(200.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
}
}
fn button_text_style() -> impl Bundle {
(
TextFont {
font_size: 33.0,
..default()
},
TextColor(TEXT_COLOR),
)
}
let display_quality = *display_quality;
commands.spawn((
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
OnDisplaySettingsMenuScreen,
children![(
Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(CRIMSON.into()),
children![
// Create a new `Node`, this time not setting its `flex_direction`. It will
// use the default value, `FlexDirection::Row`, from left to right.
(
Node {
align_items: AlignItems::Center,
..default()
},
BackgroundColor(CRIMSON.into()),
Children::spawn((
// Display a label for the current setting
Spawn((Text::new("Display Quality"), button_text_style())),
SpawnWith(move |parent: &mut ChildSpawner| {
for quality_setting in [
DisplayQuality::Low,
DisplayQuality::Medium,
DisplayQuality::High,
] {
let mut entity = parent.spawn((
Button,
Node {
width: Val::Px(150.0),
height: Val::Px(65.0),
..button_node()
},
BackgroundColor(NORMAL_BUTTON),
quality_setting,
children![(
Text::new(format!("{quality_setting:?}")),
button_text_style(),
)],
));
if display_quality == quality_setting {
entity.insert(SelectedOption);
}
}
})
))
),
// Display the back button to return to the settings screen
(
Button,
button_node(),
BackgroundColor(NORMAL_BUTTON),
MenuButtonAction::BackToSettings,
children![(Text::new("Back"), button_text_style())]
)
]
)],
));
}
fn sound_settings_menu_setup(mut commands: Commands, volume: Res<Volume>) {
let button_node = Node {
width: Val::Px(200.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(20.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
};
let button_text_style = (
TextFont {
font_size: 33.0,
..default()
},
TextColor(TEXT_COLOR),
);
let volume = *volume;
let button_node_clone = button_node.clone();
commands.spawn((
Node {
width: Val::Percent(100.0),
height: Val::Percent(100.0),
align_items: AlignItems::Center,
justify_content: JustifyContent::Center,
..default()
},
OnSoundSettingsMenuScreen,
children![(
Node {
flex_direction: FlexDirection::Column,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(CRIMSON.into()),
children![
(
Node {
align_items: AlignItems::Center,
..default()
},
BackgroundColor(CRIMSON.into()),
Children::spawn((
Spawn((Text::new("Volume"), button_text_style.clone())),
SpawnWith(move |parent: &mut ChildSpawner| {
for volume_setting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {
let mut entity = parent.spawn((
Button,
Node {
width: Val::Px(30.0),
height: Val::Px(65.0),
..button_node_clone.clone()
},
BackgroundColor(NORMAL_BUTTON),
Volume(volume_setting),
));
if volume == Volume(volume_setting) {
entity.insert(SelectedOption);
}
}
})
))
),
(
Button,
button_node,
BackgroundColor(NORMAL_BUTTON),
MenuButtonAction::BackToSettings,
children![(Text::new("Back"), button_text_style)]
)
]
)],
));
}
fn menu_action(
interaction_query: Query<
(&Interaction, &MenuButtonAction),
(Changed<Interaction>, With<Button>),
>,
mut app_exit_events: EventWriter<AppExit>,
mut menu_state: ResMut<NextState<MenuState>>,
mut game_state: ResMut<NextState<GameState>>,
) {
for (interaction, menu_button_action) in &interaction_query {
if *interaction == Interaction::Pressed {
match menu_button_action {
MenuButtonAction::Quit => {
app_exit_events.write(AppExit::Success);
}
MenuButtonAction::Play => {
game_state.set(GameState::Game);
menu_state.set(MenuState::Disabled);
}
MenuButtonAction::Settings => menu_state.set(MenuState::Settings),
MenuButtonAction::SettingsDisplay => {
menu_state.set(MenuState::SettingsDisplay);
}
MenuButtonAction::SettingsSound => {
menu_state.set(MenuState::SettingsSound);
}
MenuButtonAction::BackToMainMenu => menu_state.set(MenuState::Main),
MenuButtonAction::BackToSettings => {
menu_state.set(MenuState::Settings);
}
}
}
}
}
}
// Generic system that takes a component as a parameter, and will despawn all entities with that component
fn despawn_screen<T: Component>(to_despawn: Query<Entity, With<T>>, mut commands: Commands) {
for entity in &to_despawn {
commands.entity(entity).despawn();
}
}

View File

@@ -0,0 +1,304 @@
//! Shows how to create a loading screen that waits for assets to load and render.
use bevy::{ecs::system::SystemId, prelude::*};
use pipelines_ready::*;
// The way we'll go about doing this in this example is to
// keep track of all assets that we want to have loaded before
// we transition to the desired scene.
//
// In order to ensure that visual assets are fully rendered
// before transitioning to the scene, we need to get the
// current status of cached pipelines.
//
// While loading and pipelines compilation is happening, we
// will show a loading screen. Once loading is complete, we
// will transition to the scene we just loaded.
fn main() {
App::new()
.add_plugins(DefaultPlugins)
// `PipelinesReadyPlugin` is declared in the `pipelines_ready` module below.
.add_plugins(PipelinesReadyPlugin)
.insert_resource(LoadingState::default())
.insert_resource(LoadingData::new(5))
.add_systems(Startup, (setup, load_loading_screen))
.add_systems(
Update,
(update_loading_data, level_selection, display_loading_screen),
)
.run();
}
// A `Resource` that holds the current loading state.
#[derive(Resource, Default)]
enum LoadingState {
#[default]
LevelReady,
LevelLoading,
}
// A resource that holds the current loading data.
#[derive(Resource, Debug, Default)]
struct LoadingData {
// This will hold the currently unloaded/loading assets.
loading_assets: Vec<UntypedHandle>,
// Number of frames that everything needs to be ready for.
// This is to prevent going into the fully loaded state in instances
// where there might be a some frames between certain loading/pipelines action.
confirmation_frames_target: usize,
// Current number of confirmation frames.
confirmation_frames_count: usize,
}
impl LoadingData {
fn new(confirmation_frames_target: usize) -> Self {
Self {
loading_assets: Vec::new(),
confirmation_frames_target,
confirmation_frames_count: 0,
}
}
}
// This resource will hold the level related systems ID for later use.
#[derive(Resource)]
struct LevelData {
unload_level_id: SystemId,
level_1_id: SystemId,
level_2_id: SystemId,
}
fn setup(mut commands: Commands) {
let level_data = LevelData {
unload_level_id: commands.register_system(unload_current_level),
level_1_id: commands.register_system(load_level_1),
level_2_id: commands.register_system(load_level_2),
};
commands.insert_resource(level_data);
// Spawns the UI that will show the user prompts.
let text_style = TextFont {
font_size: 42.0,
..default()
};
commands
.spawn((
Node {
justify_self: JustifySelf::Center,
align_self: AlignSelf::FlexEnd,
..default()
},
BackgroundColor(Color::NONE),
))
.with_child((Text::new("Press 1 or 2 to load a new scene."), text_style));
}
// Selects the level you want to load.
fn level_selection(
mut commands: Commands,
keyboard: Res<ButtonInput<KeyCode>>,
level_data: Res<LevelData>,
loading_state: Res<LoadingState>,
) {
// Only trigger a load if the current level is fully loaded.
if let LoadingState::LevelReady = loading_state.as_ref() {
if keyboard.just_pressed(KeyCode::Digit1) {
commands.run_system(level_data.unload_level_id);
commands.run_system(level_data.level_1_id);
} else if keyboard.just_pressed(KeyCode::Digit2) {
commands.run_system(level_data.unload_level_id);
commands.run_system(level_data.level_2_id);
}
}
}
// Marker component for easier deletion of entities.
#[derive(Component)]
struct LevelComponents;
// Removes all currently loaded level assets from the game World.
fn unload_current_level(
mut commands: Commands,
mut loading_state: ResMut<LoadingState>,
entities: Query<Entity, With<LevelComponents>>,
) {
*loading_state = LoadingState::LevelLoading;
for entity in entities.iter() {
commands.entity(entity).despawn();
}
}
fn load_level_1(
mut commands: Commands,
mut loading_data: ResMut<LoadingData>,
asset_server: Res<AssetServer>,
) {
// Spawn the camera.
commands.spawn((
Camera3d::default(),
Transform::from_xyz(155.0, 155.0, 155.0).looking_at(Vec3::new(0.0, 40.0, 0.0), Vec3::Y),
LevelComponents,
));
// Save the asset into the `loading_assets` vector.
let fox = asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb"));
loading_data.loading_assets.push(fox.clone().into());
// Spawn the fox.
commands.spawn((
SceneRoot(fox.clone()),
Transform::from_xyz(0.0, 0.0, 0.0),
LevelComponents,
));
// Spawn the light.
commands.spawn((
DirectionalLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(3.0, 3.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
LevelComponents,
));
}
fn load_level_2(
mut commands: Commands,
mut loading_data: ResMut<LoadingData>,
asset_server: Res<AssetServer>,
) {
// Spawn the camera.
commands.spawn((
Camera3d::default(),
Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::new(0.0, 0.2, 0.0), Vec3::Y),
LevelComponents,
));
// Spawn the helmet.
let helmet_scene = asset_server
.load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf"));
loading_data
.loading_assets
.push(helmet_scene.clone().into());
commands.spawn((SceneRoot(helmet_scene.clone()), LevelComponents));
// Spawn the light.
commands.spawn((
DirectionalLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(3.0, 3.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
LevelComponents,
));
}
// Monitors current loading status of assets.
fn update_loading_data(
mut loading_data: ResMut<LoadingData>,
mut loading_state: ResMut<LoadingState>,
asset_server: Res<AssetServer>,
pipelines_ready: Res<PipelinesReady>,
) {
if !loading_data.loading_assets.is_empty() || !pipelines_ready.0 {
// If we are still loading assets / pipelines are not fully compiled,
// we reset the confirmation frame count.
loading_data.confirmation_frames_count = 0;
loading_data.loading_assets.retain(|asset| {
asset_server
.get_recursive_dependency_load_state(asset)
.is_none_or(|state| !state.is_loaded())
});
// If there are no more assets being monitored, and pipelines
// are compiled, then start counting confirmation frames.
// Once enough confirmations have passed, everything will be
// considered to be fully loaded.
} else {
loading_data.confirmation_frames_count += 1;
if loading_data.confirmation_frames_count == loading_data.confirmation_frames_target {
*loading_state = LoadingState::LevelReady;
}
}
}
// Marker tag for loading screen components.
#[derive(Component)]
struct LoadingScreen;
// Spawns the necessary components for the loading screen.
fn load_loading_screen(mut commands: Commands) {
let text_style = TextFont {
font_size: 67.0,
..default()
};
// Spawn the UI and Loading screen camera.
commands.spawn((
Camera2d,
Camera {
order: 1,
..default()
},
LoadingScreen,
));
// Spawn the UI that will make up the loading screen.
commands
.spawn((
Node {
height: Val::Percent(100.0),
width: Val::Percent(100.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
BackgroundColor(Color::BLACK),
LoadingScreen,
))
.with_child((Text::new("Loading..."), text_style.clone()));
}
// Determines when to show the loading screen
fn display_loading_screen(
mut loading_screen: Single<&mut Visibility, (With<LoadingScreen>, With<Node>)>,
loading_state: Res<LoadingState>,
) {
let visibility = match loading_state.as_ref() {
LoadingState::LevelLoading => Visibility::Visible,
LoadingState::LevelReady => Visibility::Hidden,
};
**loading_screen = visibility;
}
mod pipelines_ready {
use bevy::{
prelude::*,
render::{render_resource::*, *},
};
pub struct PipelinesReadyPlugin;
impl Plugin for PipelinesReadyPlugin {
fn build(&self, app: &mut App) {
app.insert_resource(PipelinesReady::default());
// In order to gain access to the pipelines status, we have to
// go into the `RenderApp`, grab the resource from the main App
// and then update the pipelines status from there.
// Writing between these Apps can only be done through the
// `ExtractSchedule`.
app.sub_app_mut(RenderApp)
.add_systems(ExtractSchedule, update_pipelines_ready);
}
}
#[derive(Resource, Debug, Default)]
pub struct PipelinesReady(pub bool);
fn update_pipelines_ready(mut main_world: ResMut<MainWorld>, pipelines: Res<PipelineCache>) {
if let Some(mut pipelines_ready) = main_world.get_resource_mut::<PipelinesReady>() {
pipelines_ready.0 = pipelines.waiting_pipelines().count() == 0;
}
}
}

271
vendor/bevy/examples/games/stepping.rs vendored Normal file
View File

@@ -0,0 +1,271 @@
use bevy::{app::MainScheduleOrder, ecs::schedule::*, prelude::*};
/// Independent [`Schedule`] for stepping systems.
///
/// The stepping systems must run in their own schedule to be able to inspect
/// all the other schedules in the [`App`]. This is because the currently
/// executing schedule is removed from the [`Schedules`] resource while it is
/// being run.
#[derive(Debug, Hash, PartialEq, Eq, Clone, ScheduleLabel)]
struct DebugSchedule;
/// Plugin to add a stepping UI to an example
#[derive(Default)]
pub struct SteppingPlugin {
schedule_labels: Vec<InternedScheduleLabel>,
top: Val,
left: Val,
}
impl SteppingPlugin {
/// add a schedule to be stepped when stepping is enabled
pub fn add_schedule(mut self, label: impl ScheduleLabel) -> SteppingPlugin {
self.schedule_labels.push(label.intern());
self
}
/// Set the location of the stepping UI when activated
pub fn at(self, left: Val, top: Val) -> SteppingPlugin {
SteppingPlugin { top, left, ..self }
}
}
impl Plugin for SteppingPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, build_stepping_hint);
if cfg!(not(feature = "bevy_debug_stepping")) {
return;
}
// create and insert our debug schedule into the main schedule order.
// We need an independent schedule so we have access to all other
// schedules through the `Stepping` resource
app.init_schedule(DebugSchedule);
let mut order = app.world_mut().resource_mut::<MainScheduleOrder>();
order.insert_after(Update, DebugSchedule);
// create our stepping resource
let mut stepping = Stepping::new();
for label in &self.schedule_labels {
stepping.add_schedule(*label);
}
app.insert_resource(stepping);
// add our startup & stepping systems
app.insert_resource(State {
ui_top: self.top,
ui_left: self.left,
systems: Vec::new(),
})
.add_systems(
DebugSchedule,
(
build_ui.run_if(not(initialized)),
handle_input,
update_ui.run_if(initialized),
)
.chain(),
);
}
}
/// Struct for maintaining stepping state
#[derive(Resource, Debug)]
struct State {
// vector of schedule/node id -> text index offset
systems: Vec<(InternedScheduleLabel, NodeId, usize)>,
// ui positioning
ui_top: Val,
ui_left: Val,
}
/// condition to check if the stepping UI has been constructed
fn initialized(state: Res<State>) -> bool {
!state.systems.is_empty()
}
const FONT_COLOR: Color = Color::srgb(0.2, 0.2, 0.2);
const FONT_BOLD: &str = "fonts/FiraSans-Bold.ttf";
#[derive(Component)]
struct SteppingUi;
/// Construct the stepping UI elements from the [`Schedules`] resource.
///
/// This system may run multiple times before constructing the UI as all of the
/// data may not be available on the first run of the system. This happens if
/// one of the stepping schedules has not yet been run.
fn build_ui(
mut commands: Commands,
asset_server: Res<AssetServer>,
schedules: Res<Schedules>,
mut stepping: ResMut<Stepping>,
mut state: ResMut<State>,
) {
let mut text_spans = Vec::new();
let mut always_run = Vec::new();
let Ok(schedule_order) = stepping.schedules() else {
return;
};
// go through the stepping schedules and construct a list of systems for
// each label
for label in schedule_order {
let schedule = schedules.get(*label).unwrap();
text_spans.push((
TextSpan(format!("{label:?}\n")),
TextFont {
font: asset_server.load(FONT_BOLD),
..default()
},
TextColor(FONT_COLOR),
));
// grab the list of systems in the schedule, in the order the
// single-threaded executor would run them.
let Ok(systems) = schedule.systems() else {
return;
};
for (node_id, system) in systems {
// skip bevy default systems; we don't want to step those
if system.name().starts_with("bevy") {
always_run.push((*label, node_id));
continue;
}
// Add an entry to our systems list so we can find where to draw
// the cursor when the stepping cursor is at this system
// we add plus 1 to account for the empty root span
state.systems.push((*label, node_id, text_spans.len() + 1));
// Add a text section for displaying the cursor for this system
text_spans.push((
TextSpan::new(" "),
TextFont::default(),
TextColor(FONT_COLOR),
));
// add the name of the system to the ui
text_spans.push((
TextSpan(format!("{}\n", system.name())),
TextFont::default(),
TextColor(FONT_COLOR),
));
}
}
for (label, node) in always_run.drain(..) {
stepping.always_run_node(label, node);
}
commands.spawn((
Text::default(),
SteppingUi,
Node {
position_type: PositionType::Absolute,
top: state.ui_top,
left: state.ui_left,
padding: UiRect::all(Val::Px(10.0)),
..default()
},
BackgroundColor(Color::srgba(1.0, 1.0, 1.0, 0.33)),
Visibility::Hidden,
Children::spawn(text_spans),
));
}
fn build_stepping_hint(mut commands: Commands) {
let hint_text = if cfg!(feature = "bevy_debug_stepping") {
"Press ` to toggle stepping mode (S: step system, Space: step frame)"
} else {
"Bevy was compiled without stepping support. Run with `--features=bevy_debug_stepping` to enable stepping."
};
info!("{}", hint_text);
// stepping description box
commands.spawn((
Text::new(hint_text),
TextFont {
font_size: 15.0,
..default()
},
TextColor(FONT_COLOR),
Node {
position_type: PositionType::Absolute,
bottom: Val::Px(5.0),
left: Val::Px(5.0),
..default()
},
));
}
fn handle_input(keyboard_input: Res<ButtonInput<KeyCode>>, mut stepping: ResMut<Stepping>) {
if keyboard_input.just_pressed(KeyCode::Slash) {
info!("{:#?}", stepping);
}
// grave key to toggle stepping mode for the FixedUpdate schedule
if keyboard_input.just_pressed(KeyCode::Backquote) {
if stepping.is_enabled() {
stepping.disable();
debug!("disabled stepping");
} else {
stepping.enable();
debug!("enabled stepping");
}
}
if !stepping.is_enabled() {
return;
}
// space key will step the remainder of this frame
if keyboard_input.just_pressed(KeyCode::Space) {
debug!("continue");
stepping.continue_frame();
} else if keyboard_input.just_pressed(KeyCode::KeyS) {
debug!("stepping frame");
stepping.step_frame();
}
}
fn update_ui(
mut commands: Commands,
state: Res<State>,
stepping: Res<Stepping>,
ui: Single<(Entity, &Visibility), With<SteppingUi>>,
mut writer: TextUiWriter,
) {
// ensure the UI is only visible when stepping is enabled
let (ui, vis) = *ui;
match (vis, stepping.is_enabled()) {
(Visibility::Hidden, true) => {
commands.entity(ui).insert(Visibility::Inherited);
}
(Visibility::Hidden, false) | (_, true) => (),
(_, false) => {
commands.entity(ui).insert(Visibility::Hidden);
}
}
// if we're not stepping, there's nothing more to be done here.
if !stepping.is_enabled() {
return;
}
let (cursor_schedule, cursor_system) = match stepping.cursor() {
// no cursor means stepping isn't enabled, so we're done here
None => return,
Some(c) => c,
};
for (schedule, system, text_index) in &state.systems {
let mark = if &cursor_schedule == schedule && *system == cursor_system {
"-> "
} else {
" "
};
*writer.text(ui, *text_index) = mark.to_string();
}
}